diff --git a/DESIGN.md b/DESIGN.md index c0338a7..1853fb8 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -375,6 +375,21 @@ components: backgroundColor: "{colors.field}" rounded: "{rounded.kind}" height: 56px + option-row: + backgroundColor: "{colors.field}" + textColor: "{colors.text}" + rounded: "{rounded.field}" + padding: 12px 12px 12px 14px + switch: + backgroundColor: "{colors.knob}" + rounded: "{rounded.full}" + width: 44px + height: 26px + switch-on: + backgroundColor: "{colors.accent}" + rounded: "{rounded.full}" + width: 44px + height: 26px badge: backgroundColor: "{colors.field}" rounded: "{rounded.badge}" @@ -493,11 +508,11 @@ The measured luminance steps are tiny. In dark, raised vs bg is 1.07:1, field vs | Token | Dark | Light | Meaning | |---|---|---|---| -| `--accent` | `#4eafff` | `#2b9dff` | Primary action, "this device", today, links in hints, the selection ring | -| `--accent-ink` | `#ffffff` | `#ffffff` | Text on a filled accent button | +| `--accent` | `#4eafff` | `#2b9dff` | Primary action, "this device", today, links in hints, the selection ring, a field's caret and selection, a switch that is on | +| `--accent-ink` | `#ffffff` | `#ffffff` | Text on a filled accent button, the knob of a switch that is on | | `--accent-soft` | `blue @ 13%` | `blue @ 12%` | Tinted "Connect", the Demo chip, a primary badge's icon tile | | `--ok` / `--ok-soft` | `#57d64b` / 14% | `#33a328` / 12% | Connected, included, the way filling green, the arrival ring | -| `--warn` | `#ff8a3d` | `#ee6a12` | Not set up yet, settings changed, outside hours, Reconnect, ends soon | +| `--warn` | `#ff8a3d` | `#ee6a12` | Not set up yet, settings changed, outside hours, Reconnect, ends soon, a link that fails (the card's line; the way's can't finish and no data) | | `--bad` / `--bad-soft` | `#ff5c5c` / 13% | `#e5484d` / 10% | Out of data, access ended, Remove, errors | | `--sel-bg` / `--sel-fg` | `rgba(131,209,255,.25)` / `#64c6ff` | `rgba(78,175,255,.22)` / `#0a76cf` | `::selection` | | `--bar` | `text @ 13%` | `text @ 11%` | Chart bars, meter and ring tracks | @@ -508,13 +523,17 @@ All tints come from `color-mix`, never from new hex values: | Recipe | Where | |---|---| -| `color-mix(in srgb, var(--knob), var(--text) 6%)` | hover of knob, soft button, language pill, pinned keys | +| `color-mix(in srgb, var(--knob), var(--text) 6%)` | hover of knob, soft button, language pill, pinned keys; at rest, the file card's icon and a nested row's soft buttons inside an inset row | | `… var(--text) 10%` | pressed or open (`aria-expanded`) knob and language pill | +| `… var(--text) 12%` | hover of a nested row's soft buttons inside an inset row (the router's "Configuration" in "Set it up again") | | `color-mix(in srgb, var(--accent) 82%, transparent)` | hover of the filled accent button | | `accent 20%` / `24%` over transparent | hover / active of the tinted button | | `color-mix(in srgb, var(--warn|--bad) 10%, var(--raised))` + `inset 0 0 0 1px tone 22%` | warn / bad notice | | `warn 14%` → hover `22%` | the Update pill | -| `color-mix(in srgb, var(--raised), var(--knob) 40%)` | hover of an accordion row (inset rows: field + knob 50%) | +| `color-mix(in srgb, var(--raised), var(--knob) 40%)` | hover of an accordion row (inset rows and the option row: field + knob 50%) | +| `color-mix(in srgb, var(--knob) 65%, var(--field))` | the app picker's track, the badges, the file card and a nested inset row inside an inset row (a badge's and that row's hover: `knob`) | +| `color-mix(in srgb, var(--accent) 26%, transparent)` | a field's selection wash | +| `color-mix(in srgb, var(--warn) 14%, transparent)` | the way's router end when the device can't finish (accent 14% while waiting) | | `color-mix(in srgb, var(--accent) 32%, transparent)` inset 1px | ring of the card of "this device" | | `color-mix(in srgb, var(--text) 16%, transparent)` inset 1.5px | focused field | | `color-mix(in srgb, var(--accent) 65%, transparent)` 2px outline, offset 2px | `:focus-visible` everywhere | @@ -532,7 +551,7 @@ Glass icons (`ui/glass.ts`) draw a tinted back shape, the same shape blurred beh | Tone | Dark a → b | Light a → b | Used for | |---|---|---|---| | `t-grey` | `#cfcfcd` → `#5a5a59` | `#a9a9a7` → `#3d3d3c` | Device cards (default), access rows, Add | -| `t-blue` | `#a6d9ff` → `#1d84e6` | `#7cc4ff` → `#0a6fd6` | This device, first device, kinds, reach tiles that are on, lock | +| `t-blue` | `#a6d9ff` → `#1d84e6` | `#7cc4ff` → `#0a6fd6` | This device, first device, kinds, reach tiles that are on, the LAN Bypass row when on, "Set it up again", lock | | `t-green` | `#a8f29c` → `#3aa32c` | `#82e070` → `#2e8a22` | "Everything works" (demo) | | `t-orange` | `#ffc08f` → `#ec6a12` | *same as dark* | Warn notices, Reconnect question | | `t-red` | `#ffadad` → `#dc3a3a` | `#ff9090` → `#c92a2a` | Bad notices, Remove question | @@ -576,11 +595,12 @@ These ratios feed the findings in *Live audit*. | Input | 16 / 24 | 500 | −0.012em | Name fields (16 px stops iOS zoom) | | Step title | 16 / 24 | 500 | −0.02em | "1 Get AmneziaVPN" | | Row title | 15 / 22 | 500 | −0.02em | Accordion heads, notice title, month total | +| Option title | 15 / 22 | 500 | −0.015em | "LAN Bypass" in its option row | | Breadcrumb | 15 / 22 | 400 (current 500) | −0.15px | Server › person | | Question text | 15 / 21 | 400 | — | Remove / Reconnect body | | Desc / sub / value line | 14 / 20 | 400 | — | Row descriptions, sheet subs, head values | | Menu item, toast | 14 / 20 | 500 | — | ⋯ menu, toast | -| Meta | 13 / 18 | 400 | — | Card status, usage label, hints, "how to" paths, limit note | +| Meta | 13 / 18 | 400 | — | Card status, usage label, hints, "how to" paths, limit note, the option row's line, the way's second line | | Pill label | 13 | 600 | — | Update pill, Demo chip | | Small label | 12 / 16 | 500 | — | Kind labels, badge top line, reach tile sub, "Copy…" labels | | Divider | 12 | 500 | +0.06em | "OR" (the only positive tracking) | @@ -661,7 +681,16 @@ There is no strict 4/8 grid. The values in use are `2 3 4 5 6 8 10 12 14 16 18 2 | Toasts | 70 | | Inside the sheet: ×, pinned keys | 3; their tooltip 4 | -`html { scrollbar-gutter: stable }` and `body.locked { overflow: hidden }` keep the page from shifting sideways when a sheet locks the scroll. +### Scroll + +Only the person moves the page: on a phone nothing the page does pulls it up or down under them, and a reload finds it where they left it. + +- **No scroll anchoring** (`html { overflow-anchor: none }`). On a phone "Your access" shows above the devices but comes after them in the page, so the browser would hold "Your devices" still while an access row opens or folds, and pull a page scrolled less than the fold to the very top. A row grows and folds in place, and a repaint glides what moves. +- **A fold near the foot takes the page down with it** (`holdFoot()` in `page/frame.ts`). Without anchoring, a fold that leaves the page shorter than where it is scrolled would drop it to its new end on the frame the fold is measured. The page body holds the height the scroll needs until the rows' new shape is known, then lets go over 476 ms on EASE_OUT, which never overshoots: the scroll follows the fold down frame by frame and stops at the new foot, not short of it while the row's spring dips. +- **A repaint holds the page's height** (`render()` in `main.ts`). The content keeps its height on screen while it is refilled and lets go once everything in it has its styles. Safari lays the page out once with the new cards still empty (each is a size container) and would pull the scroll up to fit that shorter page; a language change empties it all. A page that really got shorter (a removed card) still shrinks after. +- **A reload keeps its place.** A phone drops a tab while the visitor is in another app (the VPN app, the App Store) and loads it again on return; a pull to refresh does too. The browser restores the scroll as the page loads, before the router has answered, onto one empty screen, so it would stay at the top. The tab keeps the page's place itself (`sessionStorage`, as the tab is hidden or left), and the first paint of a reload or of a step back onto the page goes there. A fresh visit to the link opens at the top. Each link keeps its own place (several people's links opened in one tab share the origin), and only the page drawn in its place writes one: a tab hidden before the router answered, or showing a card in place of the page, keeps the place it had. +- **The sheet's history entry never moves the page** (`scrollRestoration = 'manual'` on that entry only), and it is current only while its sheet is open. Left behind (a reload with a sheet open, a step forward onto it: Safari's swipe in from the right edge), it is stepped back off at once, on load or on that step, so Back from there leaves the page instead of putting it back where it stood when the sheet opened. The page's own entry stays `auto`, so Back and closing a sheet still restore it. +- `html { scrollbar-gutter: stable }` and `body.locked { overflow: hidden }` keep the page from shifting sideways when a sheet locks the scroll. --- @@ -678,7 +707,7 @@ There is no strict 4/8 grid. The values in use are `2 3 4 5 6 8 10 12 14 16 18 2 - this device: 1 px, accent at 32%; - notice tone: 1 px, tone at 22%; - the arrival flash: 1.5 px `--ok`, fading. -- **Inset context.** Inside the sheet, accordion rows use `--field` (`.acc.inset`), one step above the sheet's `--raised`. Segmented controls inside them step up again (`knob 65% + field`). +- **Inset context.** Inside the sheet, accordion rows use `--field` (`.acc.inset`), one step above the sheet's `--raised`. Segmented controls, badges, the file card and a row nested in one step up again (`knob 65% + field`; a badge's and a nested row's hover go to `knob`). - **Glass icons** are the only "material" effect: a frosted pane over a 1.5 px Gaussian-blurred copy of the tinted back shape, with a rim stroke. Keep it to icons. --- @@ -695,15 +724,16 @@ There is no strict 4/8 grid. The values in use are `2 3 4 5 6 8 10 12 14 16 18 2 | 22 | Dense QR | | 20 | Accordion row (open, and the shared ends of closed rows), usage block, ⋯ menu, the way | | 18 | Badge, QR in a row, file card | -| 16 | Field, segmented track, reach tile, "until" and "hours" blocks; the pinned keys' outer corners | +| 16 | Field, segmented track, reach tile, option row, "until" and "hours" blocks; the pinned keys' outer corners | | 14 | Kind tile, link row, menu item and highlight, `.conf` block | | 12 | Go button, segmented pill | | 11 | Ends of the way | | 10 | Name chip, badge icon tile, link row knobs | | 9 | File card icon | | 6 | Inner corners of the joined pinned keys | -| 2.5–4 | Chart bars (2.5 month, 3 spark, 3 calendar cells), meter and hours bar | -| 999 / 50% | Buttons, pills, chips, toasts, tooltips / knobs, step numbers, reach marks | +| 2.5–4 | Chart bars (2.5 month, 3 spark, 3 calendar cells), meter and hours bar, a field's selection wash (4) | +| 1 | A field's caret and selection handles | +| 999 / 50% | Buttons, pills, chips, toasts, tooltips, the switch / knobs, step numbers, reach marks, the switch's knob, the handles' knobs | ### Shape rules @@ -711,7 +741,7 @@ There is no strict 4/8 grid. The values in use are `2 3 4 5 6 8 10 12 14 16 18 2 - **Closed accordion rows touch and share rounded ends.** Only the first row's top and the last row's bottom are round. An open row lifts out with 10 px gaps and gets all four corners, and so do its neighbours' facing corners. - **Joined key pairs** (Download | Copy beside ×): `16 6 6 16` and `6 16 16 6`, with a 2 px gap. - **Line icons:** 24 viewBox, `stroke-width 1.8`, round caps and joins, `currentColor`. Shown at 14, 16, 18 or 20 px. -- **Glass icons:** 24 viewBox drawn at 22 (rows), 24, 26 (kinds), 28 (reach), 30 (demo rows), 32 (cards), 36 (notices, add), 44 (first), 56 (gone) and 64 (questions). +- **Glass icons:** 24 viewBox drawn at 22 (rows), 24, 26 (kinds), 28 (reach, option row), 30 (demo rows), 32 (cards), 36 (notices, add), 44 (first), 56 (gone) and 64 (questions). - **QR codes:** round dots (r 0.42, 0.48 when dense), eyes drawn whole as rounded squares (2.6 / 1.8 / 1.5), and the Dawnline mark in a rounded tile at the centre (dense codes have none). Light dots on `#0a0a0a` in dark, dark dots on white in light. - **The mark:** a sun dome over a horizon bar, one colour, `fill: var(--text)`: white on dark, black on light, never the accent. Clipped above the bar so the sun can rise from behind it. @@ -751,15 +781,20 @@ Measurements are CSS pixels, read live at 1138 px and 375 px. Source files are u ### Field and go button · `.field`, `.go` -- **Field:** 48 high, radius 16, `field` fill, padding `0 4 0 16`. The input is 16/24 500 and the placeholder `text-3`. Focus: inset 1.5 px ring at text 16%. -- **Go button:** 48 × 40, radius 12, at the field's end. Idle: `knob` / `text-3`, `cursor: not-allowed`. Ready: accent / white. Press `.9`. -- Arrow for create, check for save. The field and its go button are the whole form: no label row, no separate Save. +- **Field:** 48 high, radius 16, `field` fill, padding `0 4 0 16`. The input is 16/24 500 and the placeholder `text-3`. Focus: inset 1.5 px ring at text 16%, on SMOOTH. +- **Go button:** 48 × 40, radius 12, at the field's end. Idle: `knob` / `text-3`, `cursor: not-allowed`. Ready: accent / white, the colours changing on SMOOTH. Press `.9`. +- Arrow for create, check for save. The field and its go button are the whole form: no label row, no separate Save. Add a device's name field is not a login: no password manager offers itself there (`data-1p-ignore`). +- **Caret** (`ui/caret.ts`, on both name fields: Add a device and the name edited on its card): the input's own is hidden (`caret-color: transparent`) and the field draws one as macOS does: accent, 2 × 20, radius 1. It glides to where the next letter goes (see *Motion → Caret and selection*), and a click puts it where clicked at once. It blinks 0.6 s on / 0.6 s off with soft fades, stays solid while typing and blinks again 0.5 s after the last key. +- **Selection** (`pointer: fine` only): the native selection is see-through and the text keeps its colour. Under the text sits an accent 26% wash, 22 high, radius 4, with an iOS handle at each end: a 2 × 22 line with a 9 px knob, on top at the start and under it at the end. A selection grows out of the caret and, on collapse, fades in place before its ends rejoin the caret. It never runs past the input's edges, so a long, scrolled name's wash stops before the go button. On a touch screen the system's own selection and handles show, and the caret steps aside while one does. +- **What a name may hold** (`shared/name-guard.ts`, both name fields, the admin's too): up to 20 letters of any language (with their marks), digits, spaces and `- _ .` (ordinary words reach about as far as the card's status line), as the router takes it; punctuation, symbols and emoji don't. A character outside that, or a 21st, never gets in: it is turned away as it is typed, pasted or dropped, and the field **shakes** at once, with no request to the router, while the red line under it (`ui/bad-line.ts`, the one the router's refusals use) says why in a few words: "Only letters, digits, - _ ." or "Up to 20 characters." (short enough for a card's status line, where a name edited in place says it). It goes with the next change that gets in. Emptying the field doesn't shake; Return or the go button on an empty name does, as does a name the router or the page refuses (one already taken). Names the page makes up (the kind, the phone's model) are in the page's language, stripped of what doesn't fit and cut to the limit ("Galaxy S24+" → "Galaxy S24"). +- **Shake** (`shared/shake.ts`): iOS's wrong-passcode shake, a damped swing sideways about four times in 0.52 s (14 px at most, settling by half), linear over its frames. The field's outline goes red with it (a 1.5 px inset ring in `bad`, as the focus ring is drawn), holds 0.7 s and fades back to the ring the field has (focused or not) over 0.8 s on ease-out; another refusal starts it red again. Another one starts from where the field is, never jumping back; only its own animation is touched, so the focus ring's transition goes on. With less motion asked for it doesn't move (the red line or toast still says why). ### Notice · `page/notices.ts` - **Layout:** radius 24, padding `14 18 14 14`, gap 14, a 36 px glass icon, a 15/22 500 title and a 14/20 `text-2` line that adds to the title and never repeats it. - **Tones:** `warn` (orange) for paused, outside hours, server off, no server and ends soon. `bad` (red) for out of data and access ended. - **Placement:** one per page, above the columns, 22 px above them. Paused is not a notice: the whole page becomes the single card. +- **On a repaint** a notice that comes blurs in, one that goes fades where it stood and one that changes morphs in place, while its slot glides to the new height. The page under it moves instead of jumping. ### Section head @@ -774,8 +809,9 @@ Measurements are CSS pixels, read live at 1138 px and 375 px. Source files are u - Top row (padding `8 6 6 10`, gap 12): a 32 px glass icon (blue on "this device", else grey), the name (16/22 500, one line), the status (13/18, one line, full wording in `title`), and the ⋯ knob. - Bottom, one of three: - **Usage** (`field`, radius 20, padding `12 14 12 16`, min-height 66): "Last 7 days" 13/18 `text-2` over the total 17/24 500 tabular. Spark of 7 bars at the right: 6 px wide, gap 4, ≤ 34 px high, min 3, radius 3, `--bar`, today in accent. Hovering a bar puts that day's name and bytes in place of the label and total instantly, with no morph. - - **Update pill** (instead of the spark) when the settings changed: 32 high, warn 14%, 13 px 600, refresh icon 14. + - **Reconnect** (instead of the week) when the settings changed or no data gets through ("Connected, but no data"): a `tint` block button with the refresh icon. New keys, then the set-up again. Not on a device never set up, a disabled one or a locked page. - **Connect** when never set up: a `tint` block button with the QR icon. It disappears when the admin locked the person. +- A status is one line, and Reconnect or Connect takes the week's place. The button is lower than the week (48 against 66), so a card alone in its row is lower too; when its bottom changes, the card glides to its new height (see *Motion → Repaint choreography*). **Order:** "this device" first, then online, then seen, then never set up, then disabled (`byDeviceState`). The grid keeps cards in place across repaints and glides them (FLIP). @@ -785,9 +821,10 @@ Measurements are CSS pixels, read live at 1138 px and 375 px. Source files are u |---|---|---| | Page opened through this device's tunnel | This device | accent (and the card gets the accent ring, the icon turns blue) | | Disabled by the admin | Disabled | text-2, card at 50% opacity | -| Settings changed and it has connected before | Settings changed | warn (+ Update pill) | +| Settings changed and it has connected before | Settings changed | warn (+ Reconnect) | | Online while out of data | Connected, no data left | warn | | Online outside the hours | Connected, outside your hours | warn | +| Its link fails in a named way (the router's watcher held it 3 min) | Can't finish connecting · Connected, but no data · On two devices at once · Connection keeps dropping; why in `title` ("It reaches the router, but the connection never completes. The network may be blocking it.") and, for a screen reader, in hidden text right after the status | warn (+ Reconnect for "Connected, but no data") | | Online | Connected | ok | | Never connected | Not set up yet | warn (+ Connect) | | Otherwise | Last connected 3 h ago (exact time in `title`) | text-2 | @@ -802,6 +839,14 @@ Measurements are CSS pixels, read live at 1138 px and 375 px. Source files are u A disabled device has no Rename, Reconnect or Remove. A locked page has no ⋯ at all. +**Rename on the card** (`flows/rename.ts`): the name is where it is changed. A name the person may change (not a disabled device, not a locked page) is a button: under the pointer a faint wash (`raised` + text 6%, radius 8) hugs its words, a click, Return or Space edits it, as **Rename** in the ⋯ menu does. Editing, the name gives way to its own input in the same font and place, with no frame or fill: only the field's caret and selection (the name selected). The status line morphs to "Return to save, Esc to cancel" in `text-2` where there is a keyboard (a touch screen's Done key saves; there it stays as it was). + +- **Return** saves: the words shimmer while the router answers (see *Motion → Shimmer*), settle to solid, and the card is drawn again with the new name, the status morphing back from the hint, words and colour. +- **Esc or a click away** puts the name it had back, whatever was typed; the status turns back. +- **What it won't take** never gets in (see *Field → What a name may hold*): the words shake (no red ring here, the field has none) and the status line says why in `bad`, short enough for its one line ("Only letters, digits, - _ ."). An empty name ("Give the device a name.") and one another device of theirs has ("That name is taken.") are said here before asking the router; a refusal of the router's own says the same way, in full on hover. Typing again brings the hint back. +- The page isn't drawn again under a name being edited. +- **Focus.** The input takes focus in the same turn as the click, the key or the menu's item (iOS raises its keyboard only for a focus made inside the tap), with the whole name selected at once and again a frame later if iOS dropped it. Return (the screen's Done key too) and Esc give focus back to the name, the new one after a save, without its focus ring (that shows only when Tab brings focus there); a click or tap away leaves it where it went. Focus leaving for somewhere else in the page (Tab, iPad's hide-keyboard key) lets the edit go like a click away; leaving the window (another app or tab) keeps it. + **Add card:** a `button.dev.add`, min-height 144, centred, grey glass plus 36 and "Add device" in `text-2` 500. Hover raised + knob 45%, press `.98`. Gone when no slot is free or the page is locked. **First card** (no devices yet): @@ -816,8 +861,9 @@ A disabled device has no Rename, Reconnect or Remove. A locked page has no ⋯ a - **Row:** `raised`, padding `0 8`. Head 52 high, gap 10, with a 22 px glass icon, a 15/22 500 title (ellipsis), an optional chip, an optional value at the end (14 px `text-2`) and a 16 px chevron (pointing down, rotated 90°, and up when open). - **Body:** padding `0 8 16 40` (inset rows `0 8 16 8`), column, gap 12. - **One row open at a time.** A **still** row (nothing to open) has no chevron, no hover and no click. +- **A row inside a row** (the router's "Configuration" inside "Set it up again") keeps its own state: the open look (chevron, body, `valHide`) keys on the row's own head and body only. - **`valHide`:** a row whose body shows the same numbers drops its head value while open (blur, fade, slide 8 px right). -- **Inset variant** (inside the sheet): rows on `field`, hover field + knob 50%. +- **Inset variant** (inside the sheet): rows on `field`, hover field + knob 50%. Inside them the app picker and badges step up to knob 65% over field, and a badge's hover goes to `knob`. The router's file step inside one steps up the same way: the file card and an inset row inside the row on knob 65% over field (that row's hover `knob`, the `.conf` it opens on `knob`), the card's icon and that row's soft buttons on knob + text 6% (hover 12%). ### "Your access" rows · `page/access.ts` @@ -827,7 +873,7 @@ A disabled device has no Rename, Reconnect or Remove. A locked page has no ⋯ a | **Data this month** (chart glass; "Data used" for a total limit) | A 16 px **ring** (track `--bar`, arc accent, warn ≥ 90%, bad ≥ 100%) and "38.6 GB / 100 GB" or "· no limit"; hidden while open | The **month**: one bar per day (flex, gap 3, 64 high, radius 2.5, min 3; days to come at 45% bar; today accent), an axis 11 px `text-3` with "Today" in accent under its bar (the month's ends hide when it comes close), the total line ("38.6 GB used" / "61.4 GB left", `bad` when out), a 6 px **meter** (same tone thresholds), and a `.desc` about the reset. Hovering a bar puts "X on 13 Oct" in place of the total instantly. | | **Access until** (calendar glass) | "30 Nov" plus "42 days" in ok, warn when soon, or "ended" in bad | The **until block** (`field`, radius 16, padding `14 16`): the days left as a 36/40 600 number (warn when soon), "days left", "Ends Mon 30 Nov" in `text-3`, and a **calendar** of the weeks to the end. 7 columns of 10 px cells with gap 5 and radius 3: past at text 5%, left at text 16%, today in accent, the last day ringed 1.5 px accent; warn colours when soon. Under it the **hours bar** when set: 8 px track, the allowed window in ok 70%, a 2 × 16 "now" marker (`text`, warn when outside, with a 2 px field ring), and axis 00/06/12/18/24 at 10 px. Without an end date and hours, the row is still. | -The data row is open by default. A repaint keeps whichever row was open. +The data row is open by default. A repaint keeps the rows on the page and changes what they hold in place, the same row open (see *Motion → Repaint choreography*). Only rows of another shape (an end date set or taken away) are built afresh. ### Sheet · `ui/sheet.ts` @@ -846,18 +892,20 @@ The data row is open by default. A repaint keeps whichever row was open. - **Pinned keys:** a view's own buttons, pinned at top 22 / right 58. - **View:** padding `0 24 24`. - **View head** (`.vhead`): 76 high. Title 20/28 500, centred with a Back knob inside a flow. The head is the drag handle, with `touch-action: none` and a grab cursor. -- **Sub line:** 14/20 `text-2`, pulled up 16 px under the head. +- **Sub line:** 14/20 `text-2`, pulled up 16 px under the head. In the set-up sheet it shows only while waiting (see *Set-up sheet → Around the way*). **Behaviour:** - **Views stack.** `go()` pushes and `back()` pops. The sheet glides to each view's height. - **Closes by:** ×, the scrim, Escape (instant), the phone's back button (the sheet is a history entry), or a pull down on its head. Focus returns to the opener. +- **A double click** that opened it: clicks in the sheet are ignored for 320 ms, so its second half neither closes it nor answers its question. +- **A flow that comes while it closes** (an answer after Cancel) opens once it is gone. Escape while it closes ends it at once, and nothing opens after it. - **Labels:** `role="dialog"` named by the view title, or `alertdialog` for questions. **Pinned keys** (`.hpill`, a phone or tablet set up from elsewhere): Download and Copy for the picked app's config, each 38 × 32, joined. -- **Tooltip:** one 26 px pill in toast colours under the keys. It appears after 420 ms of hover, then follows the pointer from key to key at once, and says "Copied" after a copy. -- **On arrival:** when the device connects, × and the keys step away (`.arrived`). +- **Tooltip:** one 26 px pill in toast colours under the keys. It appears after 420 ms of hover, then follows the pointer (or Tab) from key to key at once, gliding from where it stands, and says "Copied" after a copy. Back on a key while it still fades out, it turns back from there. +- **On arrival:** when the device connects, × and the keys step away (`settle()`, `.arrived`). If it leaves that state (no data after all, or gone again) they come back (`settle(false)`). **Question view** (`.ask`: Reconnect, Remove): @@ -886,7 +934,7 @@ The data row is open by default. A repaint keeps whichever row was open. - Bottom centre, `24px + safe-area` from the bottom, one at a time; a new one replaces the shown one. - 42 high pill, padding `0 18 0 13`, 14 px 500, an 18 px icon (check in ok, alert in bad). -- 2.4 s on screen. Used for every result and every failure ("Renamed", "Device removed", "Address copied", an error message). +- 2.4 s on screen. Used for every result and every failure ("Device removed", "Address copied", an error message). ### App picker · `ui/seg.ts` @@ -902,6 +950,18 @@ The data row is open by default. A repaint keeps whichever row was open. - **Icons and labels:** a 26 px blue glass icon, greyscale at 55% opacity until picked. The label sits under the tile at 12/16 500. - **Picked:** the tile gets an inset 1.5 px accent ring **in place**, without travelling between tiles. Hover → `knob`, press `.94`. - **Defaults:** the kind and the name are guessed from the browser (iPhone, iPad, a Samsung model through Client Hints, Mac, Windows PC…), deduplicated with " 2", " 3". +- **Back from "Add it from the device"** brings the view back as they left it: the kind, LAN Bypass and a name they typed. +- **Under them:** the LAN Bypass option row, 16 px under the kinds and 12 px above the name field (see *Option row*). No note sits between them any more (the packet-size note is gone). + +### Option row and switch · `.swrow`, `.sw` (`flows/add.ts`) + +One choice with a switch: Add a device's **LAN Bypass** ("Your local network stays reachable while connected."). Off by default. With home and internet access, switching it on unfolds a third line, "Except 192.168.1.x: those addresses lead to the home network." (the server's home networks, `server.home`; a /24 reads as "x"): height, opacity and blur on SMOOTH from where the line is, so flicking the switch never snaps, and the row, what follows and the sheet ride along. The admin's drawer says the same ("On, except 192.168.1.x (home)"), and Health warns when a home network is one of the common out-of-the-box subnets. After the device is added it stays as chosen: the admin's drawer shows it ("set when it was added"), and neither the portal nor the admin UI changes it. + +- **Row:** the whole row is the switch (`button role="switch"`, `aria-checked`). `field` on the raised sheet, radius 16, padding `12 12 12 14`, gap 12. +- **Icon:** the `lan` glass at 28 px, blue. Grey while off (`grayscale(1)` at 55% opacity), on SMOOTH. +- **Words:** the title 15/22 500 −0.015em over a 13/18 `text-2` line, gap 1. +- **Hover:** field + knob 50% over 200 ms. **No press shrink.** +- **Switch:** a 44 × 26 pill on `knob`, accent when on. Its knob is 20 px, 3 px in, `text-2` (on: `accent-ink`), and moves 18 px. Held down, the knob stretches to 27 px toward where it goes (from the left when off, toward the left when on) and finishes the move when let go, as iOS switches do. Track colour, knob travel, width and colour all run on SMOOTH. ### Badge · `flows/setup-parts.ts` @@ -911,6 +971,7 @@ The data row is open by default. A repaint keeps whichever row was open. - A 16 px trailing mark: chevron for an action, "open" for a store page in a new tab. - `.primary` (the one thing to tap in step 2): the icon tile is accent-soft / accent. - `.badges2`: two side by side (Android's Google Play beside the APK), no trailing mark. +- Inside an inset row (the steps on the device itself folded into "Set it up again"): knob 65% over field, hover `knob`, one step above the row. ### Set-up sheet · `flows/setup-view.ts` @@ -918,9 +979,9 @@ The layout follows where the page is open: | Layout | When | Content | |---|---|---| -| `same` | The page is on the device being set up | "Not on the X right now?" inset accordion (opening it folds the steps away), then **1 Get ** (picker + store badge) and **2 Add the connection** (primary badge: a vpn:// link, the share sheet, a key to copy or a file to download, plus a "how to" path) | -| `away` | A phone or tablet set up from elsewhere | Inset accordion: "Open your link on the phone" (QR of the set-up link + link row) / "Already has the app" (picker + the connection as a QR + scan line), open by default; pinned Download / Copy keys | -| `pc-away` | A computer set up from elsewhere | "Open your link on the computer" / "Copy or save the connection" (picker + two small soft buttons) | +| `same` | The page is on the device being set up (another device, a TV or a box, when the page came from its own set-up link) | "Not on the X right now?" inset accordion (opening it folds the steps away), then **1 Get ** (picker + store badge) and **2 Add the connection** (primary badge: a vpn:// link, the share sheet, a key to copy or a file to download, plus a "how to" path) | +| `away` | A phone or tablet set up from elsewhere | Inset accordion: "Open your link on the phone" (QR of the set-up link + link row) / "Already has the app" (picker + the connection as a QR + scan line; where the key or the configuration is too long for a code, the set-up link's code and one line saying so instead, in the picked app's words), open by default; pinned Download / Copy keys | +| `pc-away` | A computer set up from elsewhere, or another device (TV, box, NAS) added from a phone | "Open your link on the computer" / "Copy or save the connection" (picker + two small soft buttons) | | `router` | A router | **1 Get AmneziaWG on the router** (OpenWrt packages badge), **2 Import the configuration** (file card with Download / Share, plus a "Configuration" inset row with Show key / Copy and the `.conf`, keys masked) | **Steps:** a 24 px round number (knob, 13 px 600), a 16/24 500 title and a body with gap 10. Steps sit 20 px apart. @@ -929,32 +990,54 @@ The layout follows where the page is open: **Scan line:** "In WireGuard: + › Create from QR code". Where iOS and Android name a step differently, that word alternates every 3 s, with the or Android mark beside it. -**The way** (waiting for the first connection), on top of every layout: +**The way** (waiting for the first connection), on top of every layout. Its state is read off the device in each poll's answer (`way.ts`, from the router's `setup`); it has no buttons. -- **Block:** `field`, radius 20, padding `12 14`. +- **Block:** `field`, radius 20, padding `12 14`, 18 px above what is under it in every state. - **Ends:** two 34 px rounded squares (radius 11): the device icon in `knob`, and the server in accent tint. - **Track:** a dotted line between the ends (1.4 px dots every 9 px, `text-3` at 80%). -- **Waiting:** a light runs along the track and rests a beat. -- **Line under it:** "Waiting for the connection" (14/20 500). -- **On connection:** the track fills green from the device, the line morphs to " connected" in green, and the server end turns green last with a pop. -- **After 10 minutes:** the line reads "No connection yet" with a 13 px hint. +- **Lines under it:** the line (14/20 500) and, in the states that need one, a second line (13/18 `text-2`). + +| State | When | The way | Lines | +|---|---|---|---| +| **Waiting** | Nothing heard yet, or gone quiet, offline or removed again | A light runs along the track and rests a beat | "Waiting for the connection" | +| **Can't finish** (`.trying`) | Its knocks reach the router and no handshake follows | The light turns warn, runs almost to the router and falls back (`way-knock`). A 2 × 18 warn break, tilted 18°, flashes at the router (`way-break`). The router's end turns warn 14%. | "Unable to complete the handshake" (warn) / "Your network may be blocking the connection." | +| **Connected** (`.done`) | A handshake newer than the sheet, and data flowing | The track fills green from the device and the server end turns green last with a pop | " connected" (green) | +| **No data** (`.nodata`) | A handshake newer than the sheet, but nothing in except handshakes and keep-alives (an outdated configuration) | The track is green and both ends too (the router's 600 ms after). Two 8 px warn packets, with a soft warn glow, take turns falling through midway (`way-drop`). | "Handshake complete, but no data" (warn) / "This device is using an outdated configuration." | +| **Given up** (`.stopped`) | 10 minutes without connecting | The light goes out | "No connection yet" / "Close this and open it again to keep checking." | + +Arrival is data flowing, not the first handshake, so no data shows instead of the sheet closing. Gone back to waiting, the way says nothing more: no second line. + +**Around the way** (`follow()` in `flows/wait.ts`): + +- **The sub line** ("Two steps, about a minute") says what setting up takes, so it shows only while waiting. In every other state it folds away with its margins and the way sits right under the head, as in a sheet with no sub line. It comes back with waiting. +- **Connected:** × and the pinned keys step away (`settle()`), the sheet scrolls back to the top, everything under the way folds shut with the way's 18 px gap, and the sheet closes onto the page after the reading time. +- **Any other state** undoes that: × and the keys come back (`settle(false)`), and what folded unfolds straight into the new shape. +- **On the device itself** (`same`) and **for a router**, the steps follow the way (`regroup()` in `flows/setup-view.ts`): + - **can't finish:** one closed inset row, "Set it up again" (refresh glass, blue). On the device itself it holds both steps. A router that knocks has AmneziaWG on it already, so its row holds only the file step (no number, no title of its own); + - **no data:** one open inset row, "Add the connection again" ("Import the configuration again" for a router), holding only the connection step (no number, no title of its own); + - "Not on the X right now?" (the device itself only) hides in both: the device is in hand; + - waiting: the steps as built; + - connected: what shows stays as it is while everything under the way folds shut. + + Inside the row what sat on field steps up one (*Accordion → Inset variant*). The layouts set up from elsewhere have rows, not steps, and keep them as built. When focus is inside what moves (a badge just used), it stays in the sheet: on that control where it still shows, else on the head of "Set it up again" or the first control of what now holds the steps. ### Code row, QR and link row · `ui/codes.ts` - **QR:** 148 px (radius 18) beside its words (gap 14). Big: 208 (radius 24). Dense: full width, square, radius 22, words under it. - **Link row:** 44 high, radius 14, the URL in mono 13 without its scheme (ellipsis, `user-select: all`), then copy and, where the browser has it, share. -- A code that changes **cross-fades in place**: the new one comes in first, so the place is never empty. +- A code that changes **cross-fades in place**: the new one comes in first, so the place is never empty; a code of the other size scales the box to its own. +- A code **too long to scan** (over about 1.6 KB, e.g. an AmneziaVPN key where the browser cannot compress it, or a LAN Bypass configuration with its long list of networks) gives its place to a stand-in: another code and words that say why (they change with the picked app). The row's own words come back with a code that fits. ### File card and configuration -- **File card:** `field`, radius 18, padding 12. A 38 × 46 "file" icon (radius 9, mono 10 600 ".conf"), the filename in mono 13, "For computers and routers" at 12 px, and an accent `sm` block button. +- **File card:** `field`, radius 18, padding 12. A 38 × 46 "file" icon (radius 9, mono 10 600 ".conf"), the filename in mono 13, "For computers and routers" at 12 px, and an accent `sm` block button. Inside an inset row it steps up one (*Accordion → Inset variant*). - **Configuration:** `pre` 12/18 mono, max-height 16 rem, scrolls. - colours: section headers in accent, keys in `text`, values in `text-2`; - - **PrivateKey and PresharedKey are masked** (`••••` in `text-3`, letter-spaced 1 px) until "Show key". + - **PrivateKey and PresharedKey are masked** (`••••` in `text-3`, letter-spaced 1 px) until "Show key". The mask and the key share one place and cross-fade; the one at rest is out of sight, so a selection of the `.conf` never takes a hidden key. ### Glass icon catalogue · `ui/glass.ts` -`phone, mobile, tablet, computer, router, other, plus, globe, home, shield, chart, calendar, clock, pause, server, link, key, lock, check, trash, refresh, app (AmneziaVPN mark), file`. An unknown name falls back to `other`. +`phone, mobile, tablet, computer, router, other, plus, globe, home, shield, chart, calendar, clock, pause, server, link, key, lock, check, trash, refresh, app (AmneziaVPN mark), file, lan (three devices joined: the LAN Bypass row)`. An unknown name falls back to `other`. ### Demo-only pieces · `demo/` (not in the router build) @@ -1000,14 +1083,14 @@ Motion in the portal does three jobs: - **Causality.** A response grows out of what caused it: a menu from its button, a dialog from its centre, a toast from below. - **Calm feedback.** The orb shows waiting, the check shows a copy, the green way shows a connection. -It never decorates, never loops without a reason (the only loops are the busy orb, the way's light and the OS alternation), and **never blinks**: nothing is torn down and redrawn in sight. +It never decorates, never loops without a reason (the only loops are the busy orb, the way's light, its knock and falling packets, a focused field's caret and the OS alternation, each tied to a real state), and **never blinks**: nothing is torn down and redrawn in sight. The caret's blink is the system's own beat for a field that has focus, not a redraw. Six rules hold everywhere: 1. **Springs, not durations.** Layout motion runs on physical springs (stiffness, damping, mass 1), sampled into CSS `linear()`, so CSS transitions and script animations share one curve. 2. **Exits are quick, entrances are soft.** Exits use an ease-in curve and run 120–220 ms. Entrances use ease-out or a spring and run 280–572 ms. In a cross-fade the incoming part waits 60–110 ms so the two overlap in the blur. 3. **Blur is the transition medium.** Things appear and disappear through `filter: blur(2–6px)` with opacity and a small scale (`.86–.96`) or a few px of travel. Large travel is reserved for the drawer (`translateY(100% + 40px)`) and the FLIP of cards. -4. **Interruptible from the present.** Every new animation starts from the computed current state (`getComputedStyle`, a morph's live width, the pill's current edges) and cancels the old one only after the new one is in place. +4. **Interruptible from the present.** Every new animation starts from the computed current state (`getComputedStyle`, a morph's live width, the pill's current edges, a live rect) and cancels the old one only after the new one is in place. Turned back half-way (a double click, a quick second pick), nothing starts over from fixed keyframes, and a fade runs only what is left of its way. 5. **The keyboard never animates.** Escape closes menus and sheets instantly. 6. **Reduced motion keeps fades, drops travel.** See *Reduced motion*. @@ -1020,10 +1103,11 @@ spring(k, c, m = 1) // closed-form damped harmonic oscillator; under-, critica publishSprings(root) // --spring-{bouncy,smooth,soft,quick} and --spring-*-dur on for CSS transitions play(el, frames, o) // el.animate() with the reduced-motion policy rubber(dist, dim) // (1 − 1 / (dist·0.55/dim + 1))·dim: resistance that grows with the pull +unrubber(d, dim) // rubber() undone: the pull that puts an edge d past it (a sheet taken while it settles back) dismisses(dy, v, h) // a pulled sheet goes on a flick down (v > 0.4 px/ms) or past h/3; never on a flick back up (v < −0.1) ``` -Animations from script go through `play()` (WAAPI). Hover and press states are CSS transitions. Loops and one-shots are CSS keyframes (`orb-converge`, `orb-breathe`, `way-run`, `way-pop`, `cal-in`). +Animations from script go through `play()` (WAAPI). Hover and press states are CSS transitions. Loops and one-shots are CSS keyframes (`orb-converge`, `orb-breathe`, `way-run`, `way-knock`, `way-break`, `way-drop`, `way-dip`, `way-pop`, `caret-blink`, `cal-in`). The field's caret and selection run a per-frame spring of their own, not `spring()` (`ui/caret.ts`, see *Caret and selection*). ### Springs @@ -1031,10 +1115,10 @@ Computed from `spring()` and confirmed live: the published CSS variables read 57 | Token | k / c | ζ | Settles | Overshoot | 50% at | 90% at | Peak at | Used for | |---|---|---|---|---|---|---|---|---| -| **BOUNCY** | 300 / 20 | 0.58 | 572 ms | **10.8%** | 78 ms | 133 ms | 222 ms | Toast in, a newly created device card popping in, the way's server icon pop (via CSS var) | +| **BOUNCY** | 300 / 20 | 0.58 | 572 ms | **10.8%** | 78 ms | 133 ms | 222 ms | Toast in, a newly created device card popping in and the way's server icon pop | | **POP** | 520 / 24 | 0.53 | 544 ms | **14.3%** | 58 ms | 96 ms | 162 ms | ⋯ menu open, check icon after copy, the OS mark turning in | | **SOFT** | 380 / 28 | 0.72 | 476 ms | 3.9% | 74 ms | 138 ms | 232 ms | Accordion rows and chevron, dialog open (computer) and its scrim | -| **SMOOTH** | 300 / 35 | 1.01 | 524 ms | 0 | 98 ms | 228 ms | — | Widths and heights (morph width, sheet height glide, sheet width), FLIP of cards and letters, picker pill trailing edge, flex-grow, folds, tooltip glide, snap-back after a pull | +| **SMOOTH** | 300 / 35 | 1.01 | 524 ms | 0 | 98 ms | 228 ms | — | Widths and heights (morph width, sheet height glide, sheet width, a card's and the notice's height on a repaint, the QR box's size), FLIP of cards and letters, picker pill trailing edge, flex-grow and the picked name's width, folds, tooltip glide, snap-back after a pull and its dim; the switch, the field's focus ring and the go button's colours (via CSS var) | | **LEAD** | 520 / 46 | 1.01 | 396 ms | 0 | 74 ms | 173 ms | — | Leading edge of the stretching picker pill | | **QUICK** | 900 / 60 | 1.00 | 296 ms | 0 | 56 ms | 130 ms | — | ⋯ menu highlight following the pointer | @@ -1052,23 +1136,25 @@ Computed from `spring()` and confirmed live: the published CSS variables read 57 | ad hoc | `cubic-bezier(0, 0, .58, 1)` | Accordion body fade-in, 300 ms | | `ease-out` / `ease` keywords | — | Drawer scrim (420 in / 320 out), tooltip hide, arrival ring, hover background colours | -The duration ladder in use is **120 · 140 · 150 · 160 · 180 · 200 · 220 · 240 · 260 · 280 · 300 · 320 · 340 · 360 · 380 · 400 · 420 · 500 · 520 · 700 · 900 · 1800 ms**, plus springs. Below 200 ms means feedback or exit, 200–400 ms means entrance or cross-fade, ≥ 500 ms means travel or a one-time moment. +The duration ladder in use is **100 · 120 · 140 · 150 · 160 · 180 · 200 · 220 · 240 · 260 · 280 · 300 · 320 · 340 · 360 · 380 · 400 · 420 · 500 · 520 · 700 · 900 · 1200 · 1800 · 2200 ms**, plus springs. Below 200 ms means feedback or exit, 200–400 ms means entrance or cross-fade, ≥ 500 ms means travel or a one-time moment. ### Hover and press (CSS transitions) | Element | Press | Hover | Timing | |---|---|---|---| | `.knob` | `scale(.8)` | bg +6% text | 150 ms ease-out (transform), 150 ms (bg) | -| `.btn` | `scale(.95)` | accent 82% / tint 20% (active 24%) / soft +6% | 200 ms ease-out (transform, bg, colour) | -| `.go.ready` | `scale(.9)` | — | 200 ms ease-out | +| `.btn` | `scale(.95)` | accent 82% / tint 20% (active 24%) / soft +6% (in a row nested in an inset row: +12%) | 200 ms ease-out (transform, bg, colour) | +| `.go.ready` | `scale(.9)` | — | 200 ms ease-out (transform); colours SMOOTH 524 | | `.kind` tile | `scale(.94)` | `knob` | 200 ms (bg, transform), ring 220, icon colour 260 | | `.badge`, `.dev.add` | `scale(.98)` | `knob` / raised+knob 45% | 200 ms | | `.namechip` | `scale(.96)` | `knob` | 150 ms | | `.upd-pill`, `.cr-lang`, `.hp-b`, demo chip / GitHub | `scale(.94)` | +6% / tone 22% | 150 ms | -| Accordion row | — | raised+knob 40% (inset: field+knob 50%) | 150 ms | +| Accordion row | — | raised+knob 40% (inset: field+knob 50%; nested in an inset row: `knob`) | 150 ms | +| `.swrow` (option row) | none | field+knob 50% | 200 ms | +| Switch knob (`.sw`) | held: stretches 20 → 27 px toward where it goes | — | SMOOTH 524 (travel, width, colour) | | Picker item | — | `text-3` → `text-2` | 200 ms colour | | Spark / month bar | — | `--bar` → `text-2` (today: accent+text 25%) | 150 / 120 ms | -| Field | — | focus ring inset 1.5 px | 200 ms | +| Field | — | focus ring inset 1.5 px | SMOOTH 524 | | Language chevron | — | rotates `90° → −90°` while open | 200 ms ease-out | ### Catalogue: every animation, measured live @@ -1085,24 +1171,29 @@ Notation: | What | From → to | Timing | |---|---|---| -| Each block (crumbs, notice, section heads, each card, the limit note, each access row, the gone card), in DOM order | `opacity 0 → its own opacity, y10 → 0, b4 → 0` | 520 / 60 + 40·i, EASE_OUT, fill backwards | +| Each block (crumbs, notice, section heads, each card, the limit note, each access row, the gone card), in the order they stand on screen (top to bottom, then left to right), from the first one on screen | `opacity 0 → its own opacity, y10 → 0, b4 → 0` | 520 / 60 + 40·i, EASE_OUT, fill backwards | | The sun of the logo | `translateY(7px) → 0`, clipped above the horizon bar: the sun rises | 900 / 150, EASE_OUT | -A disabled card rises to its own 50%, not to 1. Live at 375 px, the wave ran from `crumbs @60` through `devices head @100`, the cards @140–260, `access head @300` and the access rows @340–420. See *Live audit #2*. +A disabled card rises to its own 50%, not to 1. On a phone the wave runs from the crumbs through "Your access" and its rows down to "Your devices" and the cards. The first block on screen always rises at 60 ms: a reload that goes back deep into the page starts the wave there, and the blocks above it rise with it. #### 2. Repaint choreography (the page after a change) | What | Motion | Timing | |---|---|---| -| Cards that stay but moved (FLIP) | `translate(Δx, Δy) → 0` (live: ±315 px sideways, (−315, 154) diagonally) | SMOOTH 524 | +| Cards that stay but moved (FLIP) | `translate(Δx, Δy) → 0` (live: ±315 px sideways, (−315, 154) diagonally), measured before the notice and, on a phone, "Your access" above them change | SMOOTH 524 | +| A card whose height changes (Connect ↔ its week, a row that no longer stretches it) | `height` old → new, what it holds clipped on the way; a bottom of another kind crosses: the old one fades where it stood (`out, b4`, 180 EASE_IN) as the new one blurs in (280 / 60, EASE_OUT) | SMOOTH 524 | | A device just created (`pop`) | `in, s.9 → 1, b6 → 0` | BOUNCY 572 | | A card that newly shows (Add card after a removal, the first card) | `in (to own opacity), s.9, b6` | SMOOTH 524 / 60 | -| A device that just connected (`flash`) | `inset 1.5px var(--ok) → transparent` | 1800, ease-out | -| Changed texts on cards and access rows (`data-t` keys) | letter morph (see 3) | — | +| A card no longer there (Add card once the last slot is taken) | fades where it stood, `out, b4` | 180, EASE_IN | +| A device that just connected (`flash`) | `inset 1.5px var(--ok) →` the card's own ring (this device's accent ring, else none); a repaint while it fades carries it on | 1800, ease-out | +| Changed texts on cards and access rows (`data-t` keys) | letter morph (see 3); a status that takes another colour: the old letters keep the old one, the new turn from it | colour 280, EASE_OUT | | The count "3 of 4 → 4 of 4" | letter morph | — | | Limit note appears | `in, y6 → 0, b4 → 0` | 420, EASE_OUT | -| Limit note leaves (a slot freed) | `out, b4`, then `hidden` | 200, EASE_IN | +| Limit note leaves (a slot freed) | `out, b4` from where it stands while its space folds (`height, margin-top → 0`), then `hidden`; with less motion it fades, then goes with its space | 200, EASE_IN; the fold SMOOTH 524 | +| Limit note that stays | glides with the cards when one came in above it | SMOOTH 524 | | A removed card leaves (before the repaint) | `out, s.9, b6` | 220, EASE_IN, then the repaint glides the rest | +| The notice | comes: blurs in (280 / 60, EASE_OUT); goes: fades where it stood (`out, b4`, 180 EASE_IN); changes: morphs in place (see 3). Its slot glides to the new height and clips it on the way. | SMOOTH 524 | +| "Your access" rows | stay on the page: keyed values morph (one already turning into the same words goes on), a head swaps only what changed, and an open body refills in place (`morphInto`: a value that crosses fades with its old words, the new one blurs in) while its row glides to its new height (a row still opening or folding heads for it instead). The calendar's days don't come in again; a body whose days are still coming in changes once they are in. | SMOOTH 524 | #### 3. Text morph · `ui/morph.ts` @@ -1119,15 +1210,17 @@ Every text that changes in place while visible morphs. Hover readouts over chart **Whole mode** (`whole: true`, for words in a flowing sentence, app names, menu paths): old words `out, b4` 180 ms EASE_IN, new words `in, b4 → 0` 280 / 60 EASE_OUT. +**Colour** (`morphChanged` after a repaint): a text that takes another colour with its words (a status turning green) keeps the old colour on the words that leave, and the new words turn from it (280 ms EASE_OUT). + **`morphInto(box, kids)`** refills a whole box without a blink: - unchanged pieces stay still; - a piece with new words morphs where it stands (whole mode, up to 40 characters); -- a changed drawing blurs in (280 / 60); -- a piece that changed kind or height crosses: the old one is pinned where it stood and fades `b4` over 180 ms while the new one blurs in; +- a keyed text (`data-t`) with new words is left to `morphChanged`, which letter-morphs it; +- a piece that changed kind, height or drawing crosses: the old one is pinned where it stood and fades `b4` over 180 ms, from how it showed, while the new one blurs in (280 / 60); what came in whole is not morphed again (`morphChanged` skips it); - pieces that only moved glide on SMOOTH. -**Interrupting:** a morph under way ends where it was going (`finish`), and the width carries on from its on-screen width. No morph runs for reduced motion or for an element that is not on screen. +**Interrupting:** a morph under way is not cut short. The next one starts from what shows: the words that were coming in leave from as far as they came (a letter both texts keep slides on from where it is), the words still leaving go on leaving, and the width carries on from its on-screen width. Asked again for what it is already turning into, the morph just goes on. A `morphInto` refilled again half-way does the same: what was fading goes on fading where it is, and what was still coming in goes on from as far as it came. No morph runs for reduced motion or for an element that is not on screen. Live examples: @@ -1143,13 +1236,15 @@ Live examples: | What | Motion | Timing | |---|---|---| | Every row whose shape changes | `height, margin-top/bottom, four radii` from the measured "before" to the "after" | SOFT 476 | -| Body of the opening row | `opacity 0 → 1, b2 → 0` | 300, `cubic-bezier(0,0,.58,1)` | -| Body of the closing row | `opacity 1 → 0, b2`, kept displayed (`.closing`) until the row finishes | 160, EASE_IN | +| Body of the opening row | from where it stands (`opacity 0, b2` when shut) → `1, b0` | 300 × what is left of the way, `cubic-bezier(0,0,.58,1)` | +| Body of the closing row | from where it stands → `opacity 0, b2`, kept displayed (`.closing`) until the row finishes, also when another row is clicked meanwhile | 160 × what is left, EASE_IN | | Chevron | `rotate(90°) → rotate(−90°)` | SOFT 476 (CSS var) | | Head value (`valHide`) | `out, b4, translateX(8px)` | 200 (opacity, blur), 260 (transform), EASE_OUT | -| Calendar cells when "Access until" opens | `cal-in`: `opacity 0, scale .4 → 1` | 360 / 7·i ms (49 cells ≈ 700 ms total), EASE_OUT | +| Calendar cells when "Access until" opens | `cal-in`: `opacity 0, scale .4 → 1`; `.opened` stays until the row has shut, so a row opened again before then carries on its cascade | 360 / 7·i ms (49 cells ≈ 700 ms total), EASE_OUT | -On open the neighbours' facing corners round at the same time, so the open row lifts out of the stack rather than splitting it. Inside the sheet the accordion plans the sheet's width first, so a dense code that comes into view gets its width on the same frame. +On open the neighbours' facing corners round at the same time, so the open row lifts out of the stack rather than splitting it. Inside the sheet the accordion plans the sheet's width first, so a dense code that comes into view gets its width on the same frame. On the page a fold near the foot takes the page down with it (see *Layout → Scroll*). + +A click mid-way (a double click) turns every row and body back from where it stands. When content changes under a height glide that is still heading for an old end (a row inside a row, a pick while its row opens, a fold inside a row), that glide is re-aimed from where it stands to the new end on its own curve (`regrow()` in `ui/accordion.ts`). The sheet needs none of this: its height follows its view (see *5. Sheet → Content glide*). #### 5. Sheet @@ -1159,7 +1254,7 @@ On open the neighbours' facing corners round at the same time, so the open row l |---|---|---|---| | Computer (≥ 760) open | sheet | `in, s.9 → 1, b4 → 0` from its centre | SOFT 476 | | | scrim | `in` | SOFT 476 | -| Computer close | sheet | `out, s.96, b3` into its centre | 120, EASE_IN | +| Computer close | sheet | from its present fade, blur and scale: `out, s.96, b3` into its centre | 120, EASE_IN | | | scrim | `out` | 120, EASE_IN | | Phone open | sheet | `translateY(calc(100% + 40px)) → 0` | 500, DRAWER | | | scrim | `in` | 420, ease-out | @@ -1171,25 +1266,26 @@ On open the neighbours' facing corners round at the same time, so the open row l | Element | Motion | Timing | |---|---|---| -| Old view (pinned absolutely, inert) | `out, s.96, b2` | 200, `cubic-bezier(.2,0,0,1)` | +| Old view (pinned absolutely where it stands, inert; one already leaving keeps its fade) | from how it shows (one still coming in, from as far as it came) → `out, s.96, b2` | 200 × its opacity, `cubic-bezier(.2,0,0,1)` | | New view | `in, s.96 → 1, b4 → 0` | 280 / 110, same curve | -| Viewport height | old → new (live: 297 → 830, 430 → 638) | 360, `cubic-bezier(.25,1,.5,1)` | +| Viewport height | old → new, following the view (live: 297 → 830, 430 → 638) | 360, `cubic-bezier(.25,1,.5,1)` | | Sheet width | 400 → 448 for a dense key | SMOOTH 524 | | Pinned keys | old out `s.9, b3` 180; new in `s.9 → 1, b3 → 0` | 260 / 110 | | Clicks on the new view | ignored for 320 ms, so a tap meant for the old button doesn't press the new one | — | **Content glide** (`glide()`, a pick that changes a view): -- the viewport height glides on SMOOTH; -- every element that moved inside glides from its old place (outermost only) on SMOOTH; +- the viewport height glides on SMOOTH, as a gap (or overhang) under the view that closes, so whatever changes inside meanwhile (a row opening, a fold, a poll) carries the sheet's edge along; +- every element that moved inside glides from its old place (outermost only) on SMOOTH, added to a glide still under way, so a quick second pick takes it on from where it is; - blocks named as changed blur in (280, EASE_OUT). **Pull to close** (phone, by the head): - downward drag follows the finger 1:1, and the scrim fades by `1 − dy/420`; +- taken while it still rises or settles back, it is caught where it stands, the dim with it; - upward drag resists by `rubber()`; - release closes on a flick (> 0.4 px/ms) or past a third of the height. Live, a 250 px pull closed from scrim .40, and a fast 50 px flick closed from scrim .88. -- otherwise the sheet snaps back on SMOOTH. +- otherwise the sheet and its dim go back on SMOOTH (a touch that never moved only lets it settle). **Arrived** (`.arrived`) and question (`.asks`): × and the pinned keys go `out, b3, scale .9` over 240 ms EASE_OUT and stop taking clicks. @@ -1198,10 +1294,10 @@ On open the neighbours' facing corners round at the same time, so the open row l | What | Motion | Timing | |---|---|---| | Open | `in, s.9 → 1, b4 → 0`, origin at the button's corner (top right, or bottom right when above) | POP 544 | -| Close | `out, s.96, b3` | 120, EASE_IN | +| Close | from where it stands (one still popping in included) → `out, s.96, b3` | 120, EASE_IN | | Highlight appears | opacity at the hovered item | 150, EASE_OUT | | Highlight moves | `translateY` to the next item; colour to its tone | QUICK 296; bg 150 | -| Highlight leaves | opacity 0 when the pointer leaves the menu | 150 | +| Highlight leaves | opacity 0 when the pointer leaves the menu; back on an item while it still shows, it turns back and glides from where it stands | 150 | QUICK replaced SMOOTH for the highlight because SMOOTH felt late: it reaches 90% at 130 ms against SMOOTH's 228 ms. @@ -1212,7 +1308,7 @@ QUICK replaced SMOOTH for the highlight because SMOOTH felt late: it reaches 90% | In | `in, translateY(18px) scale(.9) → 0, b6 → 0` | BOUNCY 572 | | Dwell | — | 2400 ms | | Out | `out, translateY(6px) scale(.96), b4` | 180, EASE_IN | -| Replaced by a new toast | `out, s.96, b4`, while the new one comes in over it | 140, EASE_IN | +| Replaced by a new toast | from where it stands (one still rising included) → `out, s.96, b4`, while the new one comes in over it | 140, EASE_IN | #### 8. Busy orb · `ui/busy.ts`, `controls.css` @@ -1224,6 +1320,7 @@ The orb is aicss.dev's **Orbs B4 Converge** at its 28 px stage, twice its speed, | Orb in | `in, s.6 → 1, b5 → 0` | 340 / 70, EASE_OUT | | Minimum hold | a quick answer waits until the orb is fully in (`BUSY_IN` = 410 ms), so it never flickers | — | | Answer: orb out / content back | mirror of the above, starting from where each stands | 180 / 340 + 70 | +| Pressed again while the orb leaves | the orb turns back from where it stands, at once | 340, EASE_OUT | | Orb loop: front dot (7 px) | walks a triangle (top → bottom right → bottom left). It rests 10% at each corner, leaves ease-in (`.55,0,1,.45`), arrives ease-out (`.33,1,.68,1`), and is `scale .72, blur .8` between corners. | 1.8 s, linear keyframe timeline | | Orb loop: back dot | breathes in the centre: opacity .16 ↔ .32, blur 2.4 ↔ 1.6, scale 1.2 ↔ .98 | 1.8 s, ease-in-out | @@ -1233,7 +1330,7 @@ The orb starts on the click itself (a 250 ms "only if slow" delay was tried and The control that copied says so for 1.6 s: -- its icon swaps to a check (POP 544, from `s.6, b3`); +- its icon swaps to a check (POP 544, from `s.6, b3`), and back the same way; - its "Copy…" label morphs to "Copied" and back; - a toast says what was copied; - in the pinned keys, the tooltip glides and rewords to "Copied" (SMOOTH). @@ -1244,7 +1341,7 @@ On a pick: - **Edges:** the pill's two edges are driven per frame by `spring.at(t)`. The leading edge (toward the new item) runs on LEAD (396 ms) and the trailing edge on SMOOTH (524 ms), so the pill stretches toward the target and then contracts. - **Width shares:** items change `flex-grow` 0 ↔ 1 on SMOOTH. Shares of the track, not pixels, so they stay right while the sheet's width changes. -- **Labels:** the old label collapses (`max-width → 0, margin-left −8, out`, 220 ease-out) while the new one blurs in (280 / 70, EASE_OUT), always inside the pill. +- **Labels:** the old label collapses (`max-width → 0, margin-left −8, out`, 220 ease-out) while the new one opens to its width with its item's share (SMOOTH) and blurs in (280 / 70, EASE_OUT), always inside the pill. Picked again half-way, each name goes on from where it stands, one still folding included, over what is left of its way (`labelFade`). - **What follows:** everything the pick changes `morphInto`s in place (step title, store badge, step 2, the code) and the sheet glides. #### 11. Kinds picker @@ -1255,49 +1352,81 @@ The ring does not travel: the old tile's ring fades and the new tile's ring draw | What | Motion | Timing | |---|---|---| -| A new QR in the same box | new `in` first (200, EASE_OUT); old laid over it goes `out` (220 / 110, EASE_IN) | the box is never empty | +| A new QR in the same box | new `in` under them all first (200, EASE_OUT); old laid over it goes `out` (220 / 110, EASE_IN); each from where it stands. Nothing changes its place in the stack: a code turned back to fades up again where it lies (200 × what is left), what lies over it goes, and what lies under it goes once it shows whole | the box is never empty | +| A code of the other size (dense ↔ not, e.g. the stand-in link) | the box scales from its size on screen to its own (from its top left, corners kept), the codes with it; the words glide to their new place | SMOOTH 524 | | The same code for another app (WireGuard ↔ AmneziaWG take one file) | only the words change | — | -| Words beside a code | new `in, b3 → 0` 220 EASE_OUT; old `out, b3` 200 / 90 EASE_IN | — | -| Scan line, another app | app name and each path part morph whole; the OS mark grows or shrinks (`width 0 ↔ 1.05em`, `b3`) | SMOOTH; mark out 220 | +| Words beside a code | new `in, b3 → 0` 220 EASE_OUT; old `out, b3` from where they stand, 200 / 90 EASE_IN | — | +| Scan line, another app | app name and each path part morph whole; the OS mark grows or shrinks (`width 0 ↔ 1.05em`, `b3`) | SMOOTH; mark out 220 × the width it has left, from where it stands | | Scan line, OS alternation (every 3000 ms while on screen) | the differing word letter-morphs; the old mark `out, scale .5 rotate −40°, b3` (200, EASE_IN); the new one turns in from `scale .5 rotate 40°` | POP 544 / 80 | #### 13. Waiting for the first connection · `flows/wait.ts` -**While waiting:** the way's light (`way-run`) is a gradient band masked to the dots. It travels from −70% to +70% in the first 72% of a 2 s loop (`cubic-bezier(.45,0,.55,1)`) and rests for the last 28% (≈ 560 ms). Behind it, polls run every 5 s six times, then every 15 s six times, then every 30 s. They skip while the tab is hidden and stop at 10 minutes. +**While waiting:** the way's light (`way-run`) is a gradient band masked to the dots. It travels from −70% to +70% in the first 72% of a 2 s loop (`cubic-bezier(.45,0,.55,1)`) and rests for the last 28% (≈ 560 ms). Behind it, polls run every 5 s six times, then every 15 s six times, then every 30 s. They skip while the tab is hidden and go on until the sheet closes, through the arrival too, so a state that changes again is still seen. They give up at 10 minutes unless the device is connected (the sheet is closing by itself then). -**Arrival timeline**, measured live (t = 0 when the poll sees a fresh handshake): +**Can't finish:** the light turns warn and knocks (`way-knock`, 1.8 s, the same curve): −70% → +34% at 48%, back to +26% at 62% as if turned away, then home to −70%, fading out by 86% and resting to the end. The break at the router flashes on the same beat (`way-break`, 1.8 s): `opacity .25, scaleY .7`, up to `1, 1.15` at 50%, back by 70%. The router's end turns warn over 400 ms. Both loops (the run and the knock) and the break run from the way's first frame; each state fades its own in and the others out over 200 ms (ease-out) where they stand, so none starts over in sight. + +**No data:** the green fills the dots as on arrival (700 / 80, EASE_OUT) and the ends turn green (400; the router's 600 later, with no pop). Two packets take turns (`way-drop`, 2.2 s, the same curve, the second 1.1 s behind): each fades in by 8%, runs to 48% of the track at 46%, then drops 16 px past the middle (to 54%), shrinking to `.5` and fading out by 66%. Leaving no data, each packet fades out where it is as it falls on (200, EASE_IN), then goes; back to no data while they fade, a fresh pair sets off. + +**Arrival timeline**, measured live (t = 0 when the poll sees data flowing after a fresh handshake; the sub line's fold is read from the code): | t (ms) | What | |---|---| | 0 | The line morphs to " connected" (width glides on SMOOTH, letters lift and rise). Its colour turns green (300 ms). | | 0 | × and the pinned keys step away (`out, b3, s.9`, 240 ms). The sheet scrolls to the top. | +| 0 → 380 | The sub line folds away, if it still shows (see below). | | 0 → 200 | The light fades out (200 ms). | | 80 → 780 | The green fills the dots from the device's end (`clip-path inset(0 100% 0 0) → inset(0)`, 700 / 80 ms, EASE_OUT). The device's end turns green (400 ms). | -| 600 → 1000 | The server's end turns green (400 / 600). Its icon pops (`way-pop`, scale .6 → 1, 420 / 600, on BOUNCY's curve). | +| 480 → 1172 | The server's end turns green (400 / 600). Its icon dips to .6 (`way-dip`, 120 / 480, the way's curve) and springs back (`way-pop`, BOUNCY 572 / 600): it starts and ends at its own size. | | 410 → 930 | Everything under the way folds shut: height → 0, `out, b4` (520 ms, EASE_OUT), and the way's bottom margin goes 18 → 0. | | 410 → 2810 | **2.4 s of reading time.** Unchanged with reduced motion: it is not motion. | | 2810 | The sheet closes (120 ms on a computer, 420 on a phone). | | ≈ 2950 | The page repaints: the card glides to its new place (SMOOTH), its status morphs to "Connected", and its **green ring fades** over 1.8 s. | -#### 14. Other moments +**Changes of state** (`follow()`), each starting from where things stand on screen, so one turned round half-way never jumps: | What | Motion | Timing | |---|---|---| -| Add sheet, error under the field | `in, translateY(−4px) → 0`; a second error morphs its words | 220, EASE_OUT | -| "No connection yet" after 10 min | its line blurs in | 280, EASE_OUT | -| Show key | keys and masks come into focus: `b4, opacity .4 → none` | 320, EASE_OUT | -| Steps fold (same-device layout, the "Not on the X" row) | `height, opacity, blur(0 ↔ 4px)` | SMOOTH 524 | +| The line | letter morph to the new state's words (see 3); its colour 300 ms | — | +| Second line in | `in, b4 → 0`, while the block's height glides open and both lines FLIP to their new centre together | 300 / 60 EASE_OUT; height and FLIP 340 EASE_OUT (the FLIP measured on the glide's first frame) | +| Second line replaced | whole-word morph in place (old `out, b4` 180 EASE_IN, new `in, b4 → 0` 280 / 60 EASE_OUT) as the block glides to the new height | 340 EASE_OUT | +| Second line out | `out, b4` from its current opacity, then the block closes the same way | 180 EASE_OUT, the close from 170 ms, 340 EASE_OUT | +| Sub line folds (every state but waiting) and comes back | `height, margin-top/bottom → 0, out, b4` | 380, EASE_OUT | +| Steps regroup (`same` and `router`: into "Set it up again", "Add the connection again" or "Import the configuration again", and back) | `.setup` height from where it stands to the new one; `opacity .4, b2 → none` | 420, EASE_OUT; 320, EASE_OUT | +| Leaving connected | × and the keys come back (240); what folded unfolds straight into the new shape, the way's 18 px gap with it | 520, EASE_OUT | +| "No connection yet" after 10 min | the line morphs; "Close this and open it again to keep checking." comes in as the second line, or morphs from the one shown; the sub line folds away if it still shows | as above | + +#### 14. Caret and selection · `ui/caret.ts` + +| What | Motion | Timing | +|---|---|---| +| Caret, typing and the arrows | glides to its place on a per-frame spring of its own: per 16.67 ms frame `v += (target − x)·0.12`, `v ·= 0.62`, `x += v` (90% in ≈ 134 ms, ≈ 2% over, no stretch). At most 2.5 frames per step; after a gap of over 15 frames it is simply there. | one rAF loop | +| Caret, a click | where clicked at once, as macOS does | 0 | +| Caret blink | solid while it moves or they type; 0.5 s after the last key, 0.6 s on / 0.6 s off with soft fades (`caret-blink`); its on/off fade | 1200 ease-in-out loop; 100 linear | +| Selection | grows out of the caret: both edges start where the caret is and ride the caret's spring; the wash and handles fade in. A wash still fading from the last selection turns back instead and glides from its old ends to the new ones. | 140 linear | +| Selection collapses | the wash fades where it stands (no slide), then its ends rejoin the caret | 140 linear, the ends at 160 ms | + +#### 15. Other moments + +| What | Motion | Timing | +|---|---|---| +| Add sheet, error under the field | in: `in, y−4 → 0, b4 → 0` as the sheet glides open (see 5, *Content glide*); out (they type): `out, y−4, b4` where it stands, then the sheet glides shut; a second error morphs its words; each turns back from where it stands | 220, EASE_OUT; out 180, EASE_IN, the glide from 170 ms | +| Show key / Hide key | the mask and the key cross-fade in place, each from where it stands: in → `none, 1` (320, EASE_OUT); out → `0, b4` (200, EASE_IN), then out of sight. The icon (key ↔ ×) turns the same way, out through `s.6, b3`; the label morphs | 320 / 200 | +| Steps fold (same-device layout, the "Not on the X" row) | `height, opacity, blur(0 ↔ 4px)` from where it stands (a double click turns it back); a row still opening around it heads for the new height | SMOOTH 524 | | Top edge fade | opacity 0 ↔ 1 at `scrollY > 2` | 200 ms | | Demo scenario switch | page `out, b4` 160 EASE_OUT → repaint → `in, y6, b4 → 0` 420 EASE_OUT | demo only | +### Shimmer · `ui/shimmer.ts` + +Words on their way to the router (a name being saved on its card) shimmer as an assistant's "thinking" line does. A copy of the input's words is laid exactly over them (same font, clipped to the input and scrolled as it is) and the input's own go transparent. The copy is the words' colour (`text`) over a muted base (`text` 38% into `raised`), painted as a gradient clipped to the text: a band 2.2 em either side with a bell falloff (0, .5, .9, 1, .9, .5, 0) crosses it from left to right in 1.8 s, linear, then rests 0.58 s and goes again. It starts solid (the swap shows nothing), dims in 240 ms; stopping, the band holds where it is and the words fade back to their colour around it (480 ms, standard curve), and only then does the copy go. With less motion asked for there is no band: it only dims and comes back. + ### Choreographies, end to end (live, demo latency ~0.5–0.75 s) -**Rename:** +**Rename (on the card):** -- 0: busy (content out 180, orb in 70 + 340); -- +513: answer, sheet out 120, orb out; -- +645: repaint, the name letter-morphs; -- +650: "Renamed" toast (BOUNCY). +- 0: Return; the words' copy laid over them dims to the muted base (240, standard curve), the caret steps aside; +- +120: the first sweep sets off (1.8 s across, linear), then again after a 0.58 s rest, for as long as the router takes; +- answer: the band holds where it is and the words fade back to their colour (480, standard curve); +- then: the input gives way to the name (identical, nothing moves), the card is drawn again and its status morphs from the hint, words and colour. **Reconnect:** @@ -1327,19 +1456,23 @@ The ring does not travel: the old tile's ring fades and the new tile's ring draw | Text morph, `morphInto` | Plain text swap, no letters | | Picker pill | Jumps (uses SMOOTH and t = end) | | Busy | No 410 ms hold; orb shown as a still frame (front dot sharp, halo behind) | -| Accordion chevron, calendar cascade, way light, way fill, server pop | Off (CSS `@media` blocks) | +| Accordion chevron, calendar cascade, way light (its knock too), way fill, server pop, falling packets | Off (CSS `@media` blocks); the break at the router stands still | +| Caret and selection edges | Jump to their places; the caret stands still (no blink) | +| Second line, steps regroup | Fade only; the heights jump | +| Sub line fold, what folds on arrival, the limit note leaving | Fade out, then gone with their space (back at once, fading in): the way still moves up under the head | | OS mark alternation | Marks swap instantly (the word still changes) | | Sheets, menus, toasts | Fade only | | Arrival reading time (2.4 s) | Unchanged | -CSS hover and press transitions (`scale(.8–.98)`, colours) are not reduced. They are small, direct responses to input. +CSS hover and press transitions (`scale(.8–.98)`, colours, the switch) are not reduced. They are small, direct responses to input. ### Performance notes - Animated properties are `transform`, `opacity` and `filter: blur` almost everywhere. Layout properties animate only where the layout must truly change: `height`, `width`, `max-width`, margins and radii (sheet height, accordion rows, morph width, folds), `flex-grow` (picker) and `clip-path` (way fill). - Morphs skip elements that are not on screen. The OS alternation skips while folded. Polls pause in hidden tabs. +- The caret runs one `requestAnimationFrame` loop for itself and both selection edges, writes only `transform` (and the wash's width), and stops once all three rest. Its measuring copy of the text sits out of sight with the input's font, and several events in one frame make one measure. - Blur radii stay at ≤ 6 px; the edge fade's 12 px backdrop blur is the only large one. -- One animation per property per element at a time: new runs cancel old ones after starting from their computed state. +- One animation per property per element at a time: new runs cancel old ones after starting from their computed state. The exception is a FLIP inside the sheet, which adds to one still under way (`composite: 'add'`). ### Motion do's and don'ts @@ -1350,7 +1483,7 @@ CSS hover and press transitions (`scale(.8–.98)`, colours) are not reduced. Th - **Don't** animate Escape, a language change or a reload. - **Don't** morph a hover readout: it follows the pointer and must be instant. - **Don't** use `transition: all`, bounces on exits, or travel over ~20 px except the drawer and the FLIP. -- **Don't** re-run an entrance animation on a repaint the person didn't cause (see *Live audit #1*). +- **Don't** re-run an entrance animation on a repaint the person didn't cause: the calendar's days come in when its row is opened, not when a repaint keeps it open. --- @@ -1360,7 +1493,7 @@ CSS hover and press transitions (`scale(.8–.98)`, colours) are not reduced. Th - **Buttons are verbs, with no ellipsis:** Connect, Update, Add device, Reconnect, Remove, Cancel, Open securely, Show key, Copy. - **Statuses are short and fit one line.** The full wording goes in the tooltip: "Settings changed, update needed". - **Other apps are quoted word for word, in each language:** "+ › Insert › Continue" for AmneziaVPN, "Import Tunnel(s) from File…" for WireGuard. -- **Honest warnings sit where the choice is made:** plain HTTP, the router's own certificate, connected but no data left. +- **Honest warnings sit where the choice is made:** plain HTTP, the router's own certificate, connected but no data left, a device that can't finish connecting or connects with no data (the way says what it likely is, the card says it in one line with why in `title`). - **Numbers, sizes and dates** follow the page's language (`num`, `bytes`, `toLocaleDateString(locale())`). Times are the router's clock, hours shown in the visitor's time when the offset is known. - **The language pill switches in place.** The page opens in the kept choice, else the browser's language, else English. @@ -1373,12 +1506,14 @@ CSS hover and press transitions (`scale(.8–.98)`, colours) are not reduced. Th - the sheet is `dialog`, or `alertdialog` for questions, with `aria-modal` and `aria-label` = the view's title; - the menu is `menu` with `menuitem` or `menuitemradio` (`aria-checked`); - the picker is a `tablist` of `tab`s (`aria-selected`); the kinds are a `radiogroup` of `radio`s (`aria-checked`); + - the LAN Bypass row is one `button` with `role="switch"` and `aria-checked`, named by its title and line; - accordion heads are buttons with `aria-expanded`; - the way is `role="status"` with `aria-live="polite"`; - the menu path has its own `aria-label` naming both systems' words; - busy buttons get `aria-busy`. -- **Keyboard:** Escape closes the menu, then the sheet, without animation. The phone's back button closes the sheet. Focus returns to the opener. The rename field selects its text on open. -- **Hidden decoration:** icons and glass icons are `aria-hidden`. Morph overlays and ghosts are `aria-hidden` and click-through. An icon-only button has an `aria-label`. +- **Keyboard:** Escape closes the menu, then the sheet, without animation. The phone's back button closes the sheet. Focus returns to the opener. A name edited on its card selects its text as it opens; Esc there puts the name back without closing anything else, and focus returns to the name. When the set-up steps regroup under the way, focus inside them stays in the sheet (see *Set-up sheet → Around the way*). +- **Words only on hover:** a device card's status stays one line, so why a link fails sits in `title` for a pointer and in hidden text right after the status for a screen reader (`.offscreen`). A touch screen shows neither: the trade-off for cards of one height. +- **Hidden decoration:** icons and glass icons are `aria-hidden`. Morph overlays and ghosts are `aria-hidden` and click-through. A field's drawn caret, selection and handles are click-through, and its measuring copy is `aria-hidden`; the input underneath stays the browser's own (typing, IME, its real selection). An icon-only button has an `aria-label`. - **Contrast:** see the table in *Colors*. `--text-3` and white-on-accent are below AA. - **Targets:** buttons and fields are 48 px, menu items 40 px. Knobs and pills are 32 px, the pinned keys 38 × 32 and calendar cells 10 px (not interactive). The 32 px controls are below the 44 px touch guideline. @@ -1390,28 +1525,24 @@ These are observations from the code read and the live run, not changes. Each is ### Motion -1. **The calendar replays on every repaint.** While "Access until" is open, every repaint re-runs `cal-in` on all 49 cells (≈ 700 ms). That includes a Rename, a Reconnect (under the scrim), a device that connects, and a scenario switch. The cells are rebuilt and the CSS rule `.acc-row.open .cal-g i { animation: cal-in … }` fires again. This breaks "nothing blinks". Animate the cells only from the accordion's toggle, or skip when the row was already open. -2. **The phone intro runs out of visual order.** At < 960 px "Your access" is shown first (`order: -1`), but the intro staggers in DOM order. The wave goes crumbs → devices (below) → back up to access. Sort the intro list by on-screen position. -3. **"Show key" ↔ "Hide key" swaps instantly** (`replaceChildren`), against the rule that every in-place text morphs. Same for its icon. -4. **The sheet uses two height animations.** A view swap glides height over 360 ms `cubic-bezier(.25,1,.5,1)` with `cubic-bezier(.2,0,0,1)` cross-fades and pinned keys. In-view changes use SMOOTH (524 ms). Moving the swap onto the spring tokens would make the sheet move the same way however its content changes. -5. **`way-pop` uses BOUNCY's curve over 420 ms** instead of BOUNCY's own 572 ms. The spring is compressed and its 10.8% overshoot comes faster than the token's. -6. **The drawer scrim uses CSS keywords** (`ease-out` 420 / 320) where the dialog's scrim uses SOFT and EASE_IN. Harmless, but it sits outside the token set. -7. **Comments drift from the code.** +1. **The sheet uses two height animations.** A view swap glides height over 360 ms `cubic-bezier(.25,1,.5,1)` with `cubic-bezier(.2,0,0,1)` cross-fades and pinned keys. In-view changes use SMOOTH (524 ms). Moving the swap onto the spring tokens would make the sheet move the same way however its content changes. +2. **The drawer scrim uses CSS keywords** (`ease-out` 420 / 320) where the dialog's scrim uses SOFT and EASE_IN. Harmless, but it sits outside the token set. +3. **Comments drift from the code.** - `motion.ts` says BOUNCY is "the accordion", and `accordion.css` and `accordion.ts` call it "bouncy". The accordion runs on SOFT (476 ms, 3.9%), on purpose since 2026-10-19. - `docs/plan-portal-redesign.md` says "one bottom drawer at every width" and "four kinds with a sliding ring". Live, the sheet is a centred dialog from 760 px, and the ring does not travel. -8. **The language switch is a hard cut.** The whole page is rebuilt with no fade. It is consistent with "nothing animates that the person can't follow", but it is the only visible change without a transition. +4. **The language switch is a hard cut.** The whole page is rebuilt with no fade. It is consistent with "nothing animates that the person can't follow", but it is the only visible change without a transition. ### Visual and accessibility -9. **White on accent** (every primary button) is 2.4:1 in dark and 2.9:1 in light. It is below AA even for large text. It is the measured skiper21 look, so it is a decision for the user. Options: a deeper accent fill with the same hue (e.g. `#1d84e6`, the glass tone b) or dark ink on the light fill. -10. **`--text-3` carries meaningful text** at 2.2–2.4:1: the limit note ("You have reached your limit…"), "3 of 4", "Ends Mon 30 Nov", axis dates and the "OR" divider. The limit note and the end date carry information and could move to `--text-2`. -11. **Light theme tone text is thin.** Status lines at 13 px in ok, warn or accent are 3.1–3.3:1 on white. Accent text links in hints are 2.9:1. -12. **`--t-orange` has no light override.** The light block redefines the grey, blue, green and red glass tones, but not orange. Orange glass icons keep their dark-theme stops in light. -13. **Breadcrumb at 375 px:** with the demo chip, both crumbs truncate to "Dawnlin… › U…". The router build has no chip, but a long server name will do the same. Consider letting the person's crumb win (`flex-shrink` on the place first). -14. **Quota tone mismatch:** the "Out of data" notice is red (`bad`) while the cards say "Connected, no data left" in orange (`warn`). Intended (the tunnel is up), but the page shows two tones for one state. -15. **"How to" paths wrap with the separator first:** a wrapped line starts with "›" ("› Pick the file and connect"). -16. **The `.conf` block has no edge inside its inset row:** both are `--field`. In light especially, the code floats without a container. -17. **The trash glass icon reads as "pause"** at small sizes: two vertical strokes in a rounded body. The lid separates it at 64 px only. +5. **White on accent** (every primary button) is 2.4:1 in dark and 2.9:1 in light. It is below AA even for large text. It is the measured skiper21 look, so it is a decision for the user. Options: a deeper accent fill with the same hue (e.g. `#1d84e6`, the glass tone b) or dark ink on the light fill. +6. **`--text-3` carries meaningful text** at 2.2–2.4:1: the limit note ("You have reached your limit…"), "3 of 4", "Ends Mon 30 Nov", axis dates and the "OR" divider. The limit note and the end date carry information and could move to `--text-2`. +7. **Light theme tone text is thin.** Status lines at 13 px in ok, warn or accent are 3.1–3.3:1 on white. Accent text links in hints are 2.9:1. +8. **`--t-orange` has no light override.** The light block redefines the grey, blue, green and red glass tones, but not orange. Orange glass icons keep their dark-theme stops in light. +9. **Breadcrumb at 375 px:** with the demo chip, both crumbs truncate to "Dawnlin… › U…". The router build has no chip, but a long server name will do the same. Consider letting the person's crumb win (`flex-shrink` on the place first). +10. **Quota tone mismatch:** the "Out of data" notice is red (`bad`) while the cards say "Connected, no data left" in orange (`warn`). Intended (the tunnel is up), but the page shows two tones for one state. +11. **"How to" paths wrap with the separator first:** a wrapped line starts with "›" ("› Pick the file and connect"). +12. **The `.conf` block has no edge inside its inset row:** both are `--field`. In light especially, the code floats without a container. (Inside "Set it up again" both step up and the block shows: `knob` on knob 65%.) +13. **The trash glass icon reads as "pause"** at small sizes: two vertical strokes in a rounded body. The lid separates it at 64 px only. --- @@ -1421,13 +1552,15 @@ These are observations from the code read and the live run, not changes. Each is |---|---| | Tokens, fonts, light theme | `web/src/portal/styles/tokens.css` | | Reset, type, focus, selection, icons | `styles/base.css` | -| Knob, buttons, orb, field, picker, kinds, badges, hints, link row, QR | `styles/controls.css` | +| Knob, buttons, orb, field (its caret and selection), picker, kinds, option row and switch, badges, hints, link row, QR | `styles/controls.css` | +| Field caret and selection | `ui/caret.ts` | +| Add a device, the LAN Bypass row | `flows/add.ts` | | Page frame, edge fades, crumbs, columns, notices, single card | `styles/page.css`, `page/frame.ts`, `page/notices.ts` | | Device cards | `styles/devices.css`, `page/devices.ts` | | Access rows | `styles/access.css`, `page/access.ts`, `days.ts` | | Accordion | `styles/accordion.css`, `ui/accordion.ts` | | Sheet, views, questions | `styles/sheet.css`, `ui/sheet.ts`, `flows/device-actions.ts`, `flows/secure.ts` | -| Set-up | `styles/setup.css`, `flows/setup-view.ts`, `flows/setup-parts.ts`, `flows/wait.ts`, `setup.ts` | +| Set-up | `styles/setup.css`, `flows/setup-view.ts`, `flows/setup-parts.ts`, `flows/wait.ts`, `way.ts` (the way's state), `setup.ts` | | Menu, toast | `styles/menu-toast.css`, `ui/menu.ts`, `ui/feedback.ts` | | Motion engine | `motion.ts`; morph `ui/morph.ts` + `styles/morph.css`; busy `ui/busy.ts`; picker `ui/seg.ts` | | Glass icons, line icons, QR | `ui/glass.ts`, `web/src/shared/icons.ts`, `web/src/shared/qr.ts`, `ui/codes.ts` | diff --git a/README.md b/README.md index ac7e225..a34b91c 100644 --- a/README.md +++ b/README.md @@ -407,7 +407,8 @@ scripts/lint-ucode.py # static ucode checks scripts/check-ucode.sh root@router # compile every ucode file on a router scripts/deploy.sh root@router # install the working tree (backs up configs first) scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker -scripts/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people +scripts/capture-screenshots.mjs --demo # the admin's README screenshots from a router, a demo cast in place of its people +scripts/capture-portal.mjs # the portal's from its demo, in English and Russian scripts/frame-screenshots.py # frame them for this README ``` diff --git a/README_ru.md b/README_ru.md index d41259e..ab0e036 100644 --- a/README_ru.md +++ b/README_ru.md @@ -33,7 +33,7 @@ Dawnline запускает сервер [AmneziaWG] на вашем роуте **на какой срок, сколько трафика и в какие часы**.

- Личный портал: устройства и доступ, добавление телефона в три шага + Личный портал: устройства и доступ, добавление телефона в три шага
Личная страница человека: его устройства и доступ. Телефон добавляется в три шага, и страница видит, когда он подключился. Попробуйте в демо: ничего не устанавливается и никуда не подключается. @@ -161,7 +161,7 @@ flowchart LR ## 📸 Как это выглядит

- Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются + Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются
Обзор: кто в сети, скорость сейчас, последние 30 дней и карта, откуда подключаются.

@@ -169,11 +169,11 @@ flowchart LR @@ -411,7 +411,8 @@ scripts/lint-ucode.py # статические проверк scripts/check-ucode.sh root@router # скомпилировать все файлы ucode на роутере scripts/deploy.sh root@router # поставить рабочую копию (сначала сохраняет конфиги) scripts/build-packages.sh all # .ipk и .apk в OpenWrt SDK в Docker -scripts/capture-screenshots.mjs --demo # скриншоты для README с роутера, с демо-людьми вместо настоящих +scripts/capture-screenshots.mjs --demo # скриншоты админки для README с роутера, с демо-людьми вместо настоящих +scripts/capture-portal.mjs # скриншоты портала для README из его демо, на английском и русском scripts/frame-screenshots.py # оформить их для README ``` diff --git a/docs/screenshots/overview-ru.png b/docs/screenshots/overview-ru.png new file mode 100644 index 0000000..8c9313c Binary files /dev/null and b/docs/screenshots/overview-ru.png differ diff --git a/docs/screenshots/people-ru.png b/docs/screenshots/people-ru.png new file mode 100644 index 0000000..d353563 Binary files /dev/null and b/docs/screenshots/people-ru.png differ diff --git a/docs/screenshots/person-ru.png b/docs/screenshots/person-ru.png new file mode 100644 index 0000000..fb7f6ce Binary files /dev/null and b/docs/screenshots/person-ru.png differ diff --git a/docs/screenshots/portal-ru.png b/docs/screenshots/portal-ru.png new file mode 100644 index 0000000..c740274 Binary files /dev/null and b/docs/screenshots/portal-ru.png differ diff --git a/docs/screenshots/portal.png b/docs/screenshots/portal.png index a9faeed..b78cfe4 100644 Binary files a/docs/screenshots/portal.png and b/docs/screenshots/portal.png differ diff --git a/docs/screenshots/raw/overview-ru.png b/docs/screenshots/raw/overview-ru.png new file mode 100644 index 0000000..68c824d Binary files /dev/null and b/docs/screenshots/raw/overview-ru.png differ diff --git a/docs/screenshots/raw/people-ru.png b/docs/screenshots/raw/people-ru.png new file mode 100644 index 0000000..1ceda5a Binary files /dev/null and b/docs/screenshots/raw/people-ru.png differ diff --git a/docs/screenshots/raw/person-ru.png b/docs/screenshots/raw/person-ru.png new file mode 100644 index 0000000..d120127 Binary files /dev/null and b/docs/screenshots/raw/person-ru.png differ diff --git a/docs/screenshots/raw/portal-add-1-ru.png b/docs/screenshots/raw/portal-add-1-ru.png new file mode 100644 index 0000000..1504dae Binary files /dev/null and b/docs/screenshots/raw/portal-add-1-ru.png differ diff --git a/docs/screenshots/raw/portal-add-1.png b/docs/screenshots/raw/portal-add-1.png index ecad8f3..a8b07c9 100644 Binary files a/docs/screenshots/raw/portal-add-1.png and b/docs/screenshots/raw/portal-add-1.png differ diff --git a/docs/screenshots/raw/portal-add-2-ru.png b/docs/screenshots/raw/portal-add-2-ru.png new file mode 100644 index 0000000..4647e4d Binary files /dev/null and b/docs/screenshots/raw/portal-add-2-ru.png differ diff --git a/docs/screenshots/raw/portal-add-2.png b/docs/screenshots/raw/portal-add-2.png index 06cb0e8..1c58de8 100644 Binary files a/docs/screenshots/raw/portal-add-2.png and b/docs/screenshots/raw/portal-add-2.png differ diff --git a/docs/screenshots/raw/portal-add-3-ru.png b/docs/screenshots/raw/portal-add-3-ru.png new file mode 100644 index 0000000..eab7d88 Binary files /dev/null and b/docs/screenshots/raw/portal-add-3-ru.png differ diff --git a/docs/screenshots/raw/portal-add-3.png b/docs/screenshots/raw/portal-add-3.png index faf8e06..26bcb84 100644 Binary files a/docs/screenshots/raw/portal-add-3.png and b/docs/screenshots/raw/portal-add-3.png differ diff --git a/docs/screenshots/raw/portal-ru.png b/docs/screenshots/raw/portal-ru.png new file mode 100644 index 0000000..1e1c744 Binary files /dev/null and b/docs/screenshots/raw/portal-ru.png differ diff --git a/docs/screenshots/raw/portal.png b/docs/screenshots/raw/portal.png index 8983d93..07a7851 100644 Binary files a/docs/screenshots/raw/portal.png and b/docs/screenshots/raw/portal.png differ diff --git a/package/luci-app-dawnline/Makefile b/package/luci-app-dawnline/Makefile index 1751bdb..3113dc0 100644 --- a/package/luci-app-dawnline/Makefile +++ b/package/luci-app-dawnline/Makefile @@ -6,7 +6,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-dawnline -PKG_VERSION:=0.13.0 +PKG_VERSION:=0.14.0 PKG_RELEASE:=1 PKG_LICENSE:=MIT # po//dawnline.po becomes luci-i18n-dawnline- (luci.mk), released diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js b/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js index 7b88991..5c53d10 100644 --- a/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js @@ -5,27 +5,27 @@ 'require poll'; 'require rpc'; 'require ui'; -var Ba=Object.create;var Vo=Object.defineProperty;var Oa=Object.getOwnPropertyDescriptor;var ja=Object.getOwnPropertyNames;var Ua=Object.getPrototypeOf,Wa=Object.prototype.hasOwnProperty;var Ga=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var qa=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ja(e))!Wa.call(n,r)&&r!==o&&Vo(n,r,{get:()=>e[r],enumerable:!(s=Oa(e,r))||s.enumerable});return n};var Fa=(n,e,o)=>(o=n!=null?Ba(Ua(n)):{},qa(e||!n||!n.__esModule?Vo(o,"default",{value:n,enumerable:!0}):o,n));var is=Ga((rs,as)=>{"use strict";var ss=(function(){var n=function(E,$){var b=236,k=17,y=E,I=o[$],w=null,f=0,T=null,C=[],D={},F=function(R,O){f=y*4+17,w=(function(P){for(var U=new Array(P),A=0;A=7&&ne(R),T==null&&(T=J(y,I,C)),se(T,O)},Y=function(R,O){for(var P=-1;P<=7;P+=1)if(!(R+P<=-1||f<=R+P))for(var U=-1;U<=7;U+=1)O+U<=-1||f<=O+U||(0<=P&&P<=6&&(U==0||U==6)||0<=U&&U<=6&&(P==0||P==6)||2<=P&&P<=4&&2<=U&&U<=4?w[R+P][O+U]=!0:w[R+P][O+U]=!1)},ee=function(){for(var R=0,O=0,P=0;P<8;P+=1){F(!0,P);var U=r.getLostPoint(D);(P==0||R>U)&&(R=U,O=P)}return O},B=function(){for(var R=8;R>P&1)==1;w[Math.floor(P/3)][P%3+f-8-3]=U}for(var P=0;P<18;P+=1){var U=!R&&(O>>P&1)==1;w[P%3+f-8-3][Math.floor(P/3)]=U}},fe=function(R,O){for(var P=I<<3|O,U=r.getBCHTypeInfo(P),A=0;A<15;A+=1){var G=!R&&(U>>A&1)==1;A<6?w[A][8]=G:A<8?w[A+1][8]=G:w[f-15+A][8]=G}for(var A=0;A<15;A+=1){var G=!R&&(U>>A&1)==1;A<8?w[8][f-A-1]=G:A<9?w[8][15-A-1+1]=G:w[8][15-A-1]=G}w[f-8][8]=!R},se=function(R,O){for(var P=-1,U=f-1,A=7,G=0,te=r.getMaskFunction(O),X=f-1;X>0;X-=2)for(X==6&&(X-=1);;){for(var be=0;be<2;be+=1)if(w[U][X-be]==null){var Le=!1;G>>A&1)==1);var ae=te(U,X-be);ae&&(Le=!Le),w[U][X-be]=Le,A-=1,A==-1&&(G+=1,A=7)}if(U+=P,U<0||f<=U){U-=P,P=-P;break}}},j=function(R,O){for(var P=0,U=0,A=0,G=new Array(O.length),te=new Array(O.length),X=0;X=0?qo.getAt(Fo):0}}for(var Ko=0,ae=0;aeX*8)throw"code length overflow. ("+A.getLengthInBits()+">"+X*8+")";for(A.getLengthInBits()+4<=X*8&&A.put(0,4);A.getLengthInBits()%8!=0;)A.putBit(!1);for(;!(A.getLengthInBits()>=X*8||(A.put(b,8),A.getLengthInBits()>=X*8));)A.put(k,8);return j(A,U)};D.addData=function(R,O){O=O||"Byte";var P=null;switch(O){case"Numeric":P=c(R);break;case"Alphanumeric":P=p(R);break;case"Byte":P=u(R);break;case"Kanji":P=v(R);break;default:throw"mode:"+O}C.push(P),T=null},D.isDark=function(R,O){if(R<0||f<=R||O<0||f<=O)throw R+","+O;return w[R][O]},D.getModuleCount=function(){return f},D.make=function(){if(y<1){for(var R=1;R<40;R++){for(var O=l.getRSBlocks(R,I),P=d(),U=0;U"u"?R*4:O;var P="";P+='
- Люди: все на сервере, с устройствами, трафиком и состоянием + Люди: все на сервере, с устройствами, трафиком и состоянием

Люди: в сети, доступ скоро закончится, сверх лимита, вне часов доступа, на паузе.

- Человек: его устройства, трафик, места и лимиты + Человек: его устройства, трафик, места и лимиты

Человек: его устройства, трафик, места и лимиты.

";for(var A=0;A';P+=""}return P+="",P+="
",P},D.createSvgTag=function(R,O,P,U){var A={};typeof arguments[0]=="object"&&(A=arguments[0],R=A.cellSize,O=A.margin,P=A.alt,U=A.title),R=R||2,O=typeof O>"u"?R*4:O,P=typeof P=="string"?{text:P}:P||{},P.text=P.text||null,P.id=P.text?P.id||"qrcode-description":null,U=typeof U=="string"?{text:U}:U||{},U.text=U.text||null,U.id=U.text?U.id||"qrcode-title":null;var G=D.getModuleCount()*R+O*2,te,X,be,Le,ae="",Re;for(Re="l"+R+",0 0,"+R+" -"+R+",0 0,-"+R+"z ",ae+=''+ie(U.text)+"":"",ae+=P.text?''+ie(P.text)+"":"",ae+='',ae+='"u"?R*4:O;var P=D.getModuleCount()*R+O*2,U=O,A=P-O;return z(P,P,function(G,te){if(U<=G&&G"u"?R*4:O;var U=D.getModuleCount()*R+O*2,A="";return A+="",A};var ie=function(R){for(var O="",P=0;P":O+=">";break;case"&":O+="&";break;case'"':O+=""";break;default:O+=U;break}}return O},ve=function(R){var O=1;R=typeof R>"u"?O*2:R;var P=D.getModuleCount()*O+R*2,U=R,A=P-R,G,te,X,be,Le,ae={"██":"█","█ ":"▀"," █":"▄"," ":" "},Re={"██":"▀","█ ":"▀"," █":" "," ":" "},Ie="";for(G=0;G=A?Re[Le]:ae[Le];Ie+=` -`}return P%2&&R>0?Ie.substring(0,Ie.length-P-1)+Array(P+1).join("▀"):Ie.substring(0,Ie.length-1)};return D.createASCII=function(R,O){if(R=R||1,R<2)return ve(O);R-=1,O=typeof O>"u"?R*2:O;var P=D.getModuleCount()*R+O*2,U=O,A=P-O,G,te,X,be,Le=Array(R+1).join("██"),ae=Array(R+1).join(" "),Re="",Ie="";for(G=0;G>>8),I.push(T&255)):I.push(k)}}return I}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],$=1335,b=7973,k=21522,y={},I=function(w){for(var f=0;w!=0;)f+=1,w>>>=1;return f};return y.getBCHTypeInfo=function(w){for(var f=w<<10;I(f)-I($)>=0;)f^=$<=0;)f^=b<5&&(T+=3+F-5)}for(var C=0;C=256;)y-=255;return E[y]},k})();function i(E,$){if(typeof E.length>"u")throw E.length+"/"+$;var b=(function(){for(var y=0;y"u")throw"bad rs block @ typeNumber:"+y+"/errorCorrectionLevel:"+I;for(var f=w.length/3,T=[],C=0;C>>7-k%8&1)==1},b.put=function(k,y){for(var I=0;I>>y-I-1&1)==1)},b.getLengthInBits=function(){return $},b.putBit=function(k){var y=Math.floor($/8);E.length<=y&&E.push(0),k&&(E[y]|=128>>>$%8),$+=1},b},c=function(E){var $=e.MODE_NUMBER,b=E,k={};k.getMode=function(){return $},k.getLength=function(w){return b.length},k.write=function(w){for(var f=b,T=0;T+2>>8&255)*192+(C&255),w.put(C,13),T+=2}if(T>>8)},$.writeBytes=function(b,k,y){k=k||0,y=y||b.length;for(var I=0;I0&&(b+=","),b+=E[k];return b+="]",b},$},x=function(){var E=0,$=0,b=0,k="",y={},I=function(f){k+=String.fromCharCode(w(f&63))},w=function(f){if(!(f<0)){if(f<26)return 65+f;if(f<52)return 97+(f-26);if(f<62)return 48+(f-52);if(f==62)return 43;if(f==63)return 47}throw"n:"+f};return y.writeByte=function(f){for(E=E<<8|f&255,$+=8,b+=1;$>=6;)I(E>>>$-6),$-=6},y.flush=function(){if($>0&&(I(E<<6-$),E=0,$=0),b%3!=0)for(var f=3-b%3,T=0;T=$.length){if(y==0)return-1;throw"unexpected end of file./"+y}var f=$.charAt(b);if(b+=1,f=="=")return y=0,-1;if(f.match(/^\s$/))continue;k=k<<6|w(f.charCodeAt(0)),y+=6}var T=k>>>y-8&255;return y-=8,T};var w=function(f){if(65<=f&&f<=90)return f-65;if(97<=f&&f<=122)return f-97+26;if(48<=f&&f<=57)return f-48+52;if(f==43)return 62;if(f==47)return 63;throw"c:"+f};return I},S=function(E,$){var b=E,k=$,y=new Array(E*$),I={};I.setPixel=function(C,D,F){y[D*b+C]=F},I.write=function(C){C.writeString("GIF87a"),C.writeShort(b),C.writeShort(k),C.writeByte(128),C.writeByte(0),C.writeByte(0),C.writeByte(0),C.writeByte(0),C.writeByte(0),C.writeByte(255),C.writeByte(255),C.writeByte(255),C.writeString(","),C.writeShort(0),C.writeShort(0),C.writeShort(b),C.writeShort(k),C.writeByte(0);var D=2,F=f(D);C.writeByte(D);for(var Y=0;F.length-Y>255;)C.writeByte(255),C.writeBytes(F,Y,255),Y+=255;C.writeByte(F.length-Y),C.writeBytes(F,Y,F.length-Y),C.writeByte(0),C.writeString(";")};var w=function(C){var D=C,F=0,Y=0,ee={};return ee.write=function(B,Q){if(B>>>Q)throw"length over";for(;F+Q>=8;)D.writeByte(255&(B<>>=8-F,Y=0,F=0;Y=B<0&&D.writeByte(Y)},ee},f=function(C){for(var D=1<>6,128|a&63):a<55296||a>=57344?s.push(224|a>>12,128|a>>6&63,128|a&63):(r++,a=65536+((a&1023)<<10|o.charCodeAt(r)&1023),s.push(240|a>>18,128|a>>12&63,128|a>>6&63,128|a&63))}return s}return e(n)}})();(function(n){typeof define=="function"&&define.amd?define([],n):typeof rs=="object"&&(as.exports=n())})(function(){return ss})});function Qn(n,e){return n==null||n===!1||n===""||(Array.isArray(n)?n.forEach(o=>Qn(o,e)):e.push(n instanceof Node?n:String(n))),e}function t(n,e,o){let s=window.E,r=e!=null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Node);return!r&&o===void 0?s(n,{},Qn(e,[])):s(n,r?e:{},Qn(o,[]))}var Yo={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 _t(n,e="dl-icon"){let o=Yo[n]??Yo.phone;return``}function g(n,e="dl-icon"){let o=document.createElement("span");return o.className="dl-icon-wrap",o.innerHTML=_t(n,e),o}function q(n,e="info",o=0){let s=document.querySelector(".dl-toasts");s||(s=t("div",{class:"dl-toasts dl-root",role:"status","aria-live":"polite"}),document.body.appendChild(s));let r=e==="error"?"x":e==="warning"?"alert":e==="success"?"check":null,a=()=>{i.classList.remove("show"),setTimeout(()=>i.remove(),200)},i=t("div",{class:`dl-toast ${e}`},[r?g(r):"",t("span",{},n),e==="error"?t("button",{type:"button","aria-label":_("Close"),click:a},g("x")):""]);s.appendChild(i),requestAnimationFrame(()=>i.classList.add("show")),setTimeout(a,o||(e==="error"?8e3:e==="warning"?5e3:2600))}function Ce(n){return n instanceof Error?n.message:String(n)}async function K(n,e){try{let o=await n();return e&&q(e,"success",3500),o}catch(o){q(Ce(o),"error",1e4);return}}function Jo(n){try{let e=n();e&&typeof e.then=="function"&&e.catch(o=>q(Ce(o),"error"))}catch(e){q(Ce(e),"error")}}function Xn(){return(typeof document>"u"?"":document.documentElement.lang)||"en"}function le(){let n=Xn();return n==="en"?"en-GB":n}function m(n,...e){let o=0;return n.replace(/%([%sd])/g,(s,r)=>r==="%"?"%":String(e[o++]??""))}function V(n,e){return n.toLocaleString(le(),e===void 0?void 0:{minimumFractionDigits:e,maximumFractionDigits:e})}function W(n,e,o){return m(N_(n,e,o),V(n))}function oe(n,...e){let o=0;return n.split(/(%[%sd])/).filter(Boolean).map(s=>s==="%%"?"%":s==="%s"||s==="%d"?e[o++]:s)}var eo=n=>_(n);function Zo(n){if(n&&typeof n=="object"){if(typeof n.error=="string")throw new Error(n.error);typeof n.warning=="string"&&n.warning&&q(n.warning,"warning",12e3)}return n}function Z(n,e=[]){let o=rpc.declare({object:"luci.dawnline",method:n,params:[...e,"lang"]});return async(...s)=>Zo(await o(...e.map((r,a)=>s[a]),Xn()))}var Ka=Z("logs_clear",["person","device","category","older_days"]),Va=(n={})=>Ka(n.person??"",n.device??"",n.category??"",n.older_days??""),Ya=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 Ja(n,e){let s=[n,...["name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode"].map(r=>e[r]),e.paused,e.services,e.circle,e.home_nets,e.server];return Zo(await Ya(...s))}var Za=Z("status",["days"]),H={rev:Z("rev"),personUpdate:Ja,settingsGet:Z("settings_get"),portalInfo:Z("portal_info"),settingsUpdate:Z("settings_update",["values"]),serviceSet:Z("service_set",["id","name","address","ports"]),serviceDelete:Z("service_delete",["id"]),geoClear:Z("geo_clear"),events:Z("events",["limit","person","since"]),logsClear:Va,interfaces:Z("interfaces",["id"]),serverInterfaces:Z("server_interfaces",["id","auto_wan","wan_device","auto_lan","lan_devices","lan_like","device_mesh","mesh"]),circleSet:Z("circle_set",["id","server","name","color","members"]),circleDelete:Z("circle_delete",["id"]),accessCheck:Z("access_check",["from","to"]),homeHosts:Z("home_hosts",["id"]),usageClear:Z("usage_clear",["scope","id"]),uninstall:Z("uninstall",["confirm"]),status:Za,setupDefaults:Z("setup_defaults"),serverCreate:Z("server_create",["id","name","ifname","port","subnet","endpoint","mtu","preset","lan_zone","wan_zone","lan_like","portal_enabled","portal_port"]),serverObfuscation:Z("server_obfuscation",["id","preset"]),serverUpdate:Z("server_update",["id","values"]),serverPorts:Z("server_ports",["id"]),endpointProbe:Z("endpoint_probe",["host","id","port"]),serverDelete:Z("server_delete",["id"]),personLinks:Z("person_links",["id"]),personCreate:Z("person_create",["name","slug","server","access","device_limit","expires","quota_gb","quota_period"]),personPause:Z("person_pause",["id","paused"]),personRegen:Z("person_regen",["id","remove"]),personDelete:Z("person_delete",["id"]),personUsage:Z("person_usage",["id","days"]),deviceCreate:Z("device_create",["person","name","kind"]),deviceConfig:Z("device_config",["id"]),deviceUpdate:Z("device_update",["id","name","disabled"]),deviceDelete:Z("device_delete",["id"]),deviceRotate:Z("device_rotate",["id"]),apply:Z("apply"),health:Z("health"),healthFix:Z("health_fix",["id"]),serviceLog:Z("service_log"),serviceLogClear:Z("service_log_clear",["older_days"]),backupList:Z("backup_list"),backupCreate:Z("backup_create"),backupRestore:Z("backup_restore",["name"]),backupDelete:Z("backup_delete",["name"]),backupRead:Z("backup_read",["name"]),backupUpload:Z("backup_upload",["data"]),exportJson:Z("export"),importJson:Z("import",["data"]),updatesStatus:Z("updates_status"),updatesRun:Z("updates_run",["what"]),updatesReleases:Z("updates_releases",["page"]),updatesNotes:Z("updates_notes",["component","tag","build"]),updatesChanges:Z("updates_changes",["from","to"])};function N(n,e,o="neutral",s={}){let{disabled:r,...a}=s,i=t("button",{class:`cbi-button cbi-button-${o}`,type:"button",...a,click:async l=>{if(l.preventDefault(),l.stopPropagation(),!i.disabled){i.disabled=!0,i.classList.add("spinning");try{await e(l)}catch(d){q(Ce(d),"error")}finally{i.disabled=!1,i.classList.remove("spinning")}}}},n);return i.disabled=!!r,i}function Pe(n,e,o,s="neutral",r=""){return N([g(n),t("span",{class:"dl-btn-label"},e)],o,s,{title:e,class:`cbi-button cbi-button-${s} dl-icon-btn ${r}`.trim()})}function Ee(n){return document.addEventListener("luci-navigate",n),()=>document.removeEventListener("luci-navigate",n)}var Ct=null;function to(n=!1){let e=Ct;Ct=null,e?.(n)}function de(n,e,o,s=""){to();let r=t("div",{class:`dl-modal ${s}`},e),a=t("div",{class:"button-row"},o);r.addEventListener("keydown",i=>{if(i.key==="Escape"){i.preventDefault(),i.stopPropagation(),ce();return}if(i.key!=="Enter"||i.shiftKey||i.ctrlKey||i.metaKey||i.altKey)return;let l=i.target;if(!l||["TEXTAREA","BUTTON","SELECT","A"].includes(l.tagName))return;let d=a.querySelector(".cbi-button-positive");!d||d.disabled||(i.preventDefault(),d.click())}),ui.showModal(n,[r,a])}function ce(){to(),ui.hideModal()}function ue(n=_("Cancel"),e=!1){return t("button",{class:`cbi-button ${e?"cbi-button-negative":"cbi-button-neutral"}`,type:"button",click:ce},n)}function me(n,e,o=_("Confirm"),s=!1){return new Promise(r=>{de(n,e,[ue()," ",t("button",{class:`cbi-button ${s?"cbi-button-negative":"cbi-button-positive"}`,type:"button",click:()=>{let a=Ct;Ct=null,ui.hideModal(),a?.(!0)}},o)]),Ct=r})}Ee(()=>{Ct&&(to(),ui.hideModal())});async function xe(n,e=_("Copied to clipboard"),o=!1){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(n);else{let s=t("textarea",{style:"position:fixed;opacity:0"},n);document.body.appendChild(s),s.select();let r=document.execCommand("copy");if(s.remove(),!r)throw new Error(_("Copying is blocked here. Select the text and copy it by hand."))}return q(e,"success",2500),!0}catch(s){return o||q(Ce(s),"error"),!1}}function Ae(n,e,o="text/plain"){let s=globalThis,r=typeof e=="string"?new s.Blob([e],{type:o}):e,a=URL.createObjectURL(r),i=t("a",{href:a,download:n,style:"display:none"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(a),i.remove()},1e3)}function no(n,e){return new Promise(o=>{let s=t("input",{type:"file",accept:n,style:"display:none"});s.addEventListener("cancel",()=>{s.remove(),o(null)}),s.addEventListener("change",()=>{let r=s.files?.[0];if(s.remove(),!r)return o(null);let a=new FileReader;a.onload=()=>{let i=String(a.result??"");o({name:r.name,data:e==="base64"?i.replace(/^data:[^,]*,/,""):i})},a.onerror=()=>o(null),e==="base64"?a.readAsDataURL(r):a.readAsText(r)}),document.body.appendChild(s),s.click()})}function Te(n,e){let o=document.querySelector(".dl-dd");if(o&&(o.dlClose?o.dlClose():o.remove(),o.dlAnchor===n))return;let s=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(),Jo(u.run)}},[u.icon??"",t("span",{},u.label)]):t("hr")));document.body.appendChild(s);let r=n.getBoundingClientRect(),a=s.offsetWidth,i=s.offsetHeight;s.style.top=`${r.bottom+6+i>window.innerHeight-8&&r.top-6-i>8?r.top-6-i:r.bottom+6}px`,s.style.left=`${Math.max(8,Math.min(r.right-a,window.innerWidth-a-8))}px`;let l=u=>{!s.contains(u.target)&&!n.contains(u.target)&&p()},d=u=>{if(u.key==="Escape"||u.key==="Tab")return p();let v=[...s.querySelectorAll("button:not([disabled])")];if(!v.length||!["ArrowDown","ArrowUp","Home","End"].includes(u.key))return;u.preventDefault();let M=v.indexOf(document.activeElement),x=u.key==="Home"?0:u.key==="End"?v.length-1:u.key==="ArrowDown"?(M+1)%v.length:(M-1+v.length)%v.length;v[x].focus({preventScroll:!0})},c=Ee(p);s.dlAnchor=n,s.dlClose=p;function p(){s.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)}),s.querySelector("button")?.focus({preventScroll:!0})}var gt=null,nt=null,oo=0;function Lt(){gt&&(gt.style.display="none"),nt=null,clearInterval(oo),oo=0}function we(n,e){let o=s=>{gt??(gt=document.body.appendChild(t("div",{class:"dl-tip dl-tip-float dl-root"}))),gt.replaceChildren(...e().map(r=>typeof r=="string"?document.createTextNode(r):r)),gt.style.display="",gt.style.left=`${s.clientX}px`,gt.style.top=`${s.clientY-10}px`,nt=n,oo||(oo=window.setInterval(()=>{(!nt?.isConnected||!nt.getClientRects().length)&&Lt()},400))};n.addEventListener("mouseenter",o),n.addEventListener("mousemove",o),n.addEventListener("mouseleave",Lt),n.addEventListener("pointerup",s=>{s.pointerType!=="mouse"&&(nt===n?Lt():o(s))})}Ee(Lt);window.addEventListener("scroll",()=>nt&&Lt(),{capture:!0,passive:!0});document.addEventListener("pointerdown",n=>{nt&&!nt.contains(n.target)&&Lt()},!0);function Qa(n,e,o){let s=0;for(;n>=o&&s=100||s===0?V(Math.round(n)):V(n,1)} ${e[s]}`}function re(n){return Qa(!n||n<0?0:n,[_("B"),_("KB"),_("MB"),_("GB"),_("TB")],1024)}function qe(n){let e=n*8,o=[_("bit/s"),_("kbit/s"),_("Mbit/s"),_("Gbit/s")];if(e<1e3)return`${V(Math.round(e))} ${o[0]}`;let s=e<1e6?1:e<1e9?2:3,r=e/1e3**s;return`${V(r,s===3||r<10?1:0)} ${o[s]}`}function pe(n,e=Date.now()/1e3){if(!n)return _("never");let o=Math.max(0,Math.round(e-n));return o<60?_("just now"):o<3600?m(_("%s min ago"),Math.floor(o/60)):o<86400?m(_("%s h ago"),Math.floor(o/3600)):o<86400*30?m(_("%s d ago"),Math.floor(o/86400)):new Date(n*1e3).toLocaleDateString(le(),{day:"numeric",month:"short",year:"numeric"})}function ot(n){if(!n||n<0)return"—";let e=Math.floor(n/86400),o=Math.floor(n%86400/3600),s=Math.floor(n%3600/60);return e?m(_("%sd %sh"),e,o):o?m(_("%sh %sm"),o,s):m(_("%sm"),s)}function Wt(n){let e=new Date(n*1e3),o=new Date,s=e.toDateString()===o.toDateString(),r=e.toLocaleTimeString(le(),{hour:"2-digit",minute:"2-digit"});return s?r:`${e.toLocaleDateString(le(),{day:"numeric",month:"short"})} ${r}`}function Fe(n){return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`}function Et(n){let[e,o,s]=n.split("-").map(Number);return new Date(e,(o||1)-1,s||1,12)}function Be(n){return(typeof n=="string"?/^\d{4}-\d{2}-\d{2}$/.test(n)?Et(n):new Date(n):n).toLocaleDateString(le(),{day:"numeric",month:"short",year:"numeric"})}function $e(n){return n?Be(n):""}function so(n,e){let o=s=>{let[r,a,i]=s.split("-").map(Number);return Date.UTC(r,a-1,i)};return Math.round((o(n)-o(e))/864e5)}function Ut(n,e){let o=Et(n);return o.setDate(o.getDate()+e),Fe(o)}function Mt(n,e){let[o,s,r]=n.split("-").map(Number),a=new Date(o,s-1+e,1,12),i=new Date(a.getFullYear(),a.getMonth()+1,0).getDate();return a.setDate(Math.min(r,i)),Fe(a)}function We(n){return n?.length?n[n.length-1].day:Fe(new Date)}function Qo(n,e,o,s,r=30){let a=n||s;return e==="day"?Ut(a,o):e==="week"?Ut(a,7*o):e==="month"?Mt(a,o):e==="year"?Mt(a,12*o):Ut(a,r*o)}function st(n,e=Date.now()){if(!n)return null;let o=typeof e=="number"?Fe(new Date(e)):e,s=so(n,o);return s>=0?s+1:s}function rt(n,e){return e!=null&&e>0&&n.expire_warn>0&&e<=n.expire_warn}function dn(n){return n<=1?_("ends today"):n===2?_("ends tomorrow"):W(n,"ends in %s day","ends in %s days")}function Tt(n){return n<1024?`${V(n)} ${_("B")}`:n<1048576?`${V(n/1024,n<10240?1:0)} ${_("KB")}`:`${V(n/1048576,1)} ${_("MB")}`}function vt(n){return{lan:_("Home network"),internet:_("Internet"),both:_("Home network + Internet")}[n]}var Xo=["computer","phone","tablet","router","other"];function at(n){return{computer:_("PC"),phone:_("Phone"),tablet:_("Tablet"),router:_("Router"),other:_("Other")}[n]}function es(n){return{active:_("Active"),paused:_("Paused"),expired:_("Expired"),quota:_("Data limit reached"),hours:_("Outside allowed hours"),no_server:_("No server"),server_off:_("Server is turned off")}[n]}function Oe(n){let e=n.trim().split(/\s+/).filter(Boolean);if(!e.length)return"?";let o=e[0][0]??"",s=e.length>1?e[e.length-1][0]??"":e[0][1]??"";return(o+s).toUpperCase()}function cn(n){let e=o=>o.disabled?3:o.online?0:o.handshake?1:2;return n.map((o,s)=>[o,s]).sort((o,s)=>e(o[0])-e(s[0])||o[1]-s[1]).map(([o])=>o)}function Se(n,e,o){return t("span",{class:`dl-pill ${n}`,title:o??null},e)}function Xa(n){return n.state==="active"?"ok":n.state==="quota"||n.state==="expired"?"bad":"warn"}function ei(n){return n.state==="server_off"&&n.paused?"paused":n.state}function ts(n){let e=ei(n);return e==="active"||e==="server_off"?"":Se(Xa({...n,state:e}),es(e))}function ns(n){let e=n.access==="both"?["lan","inet"]:n.access==="lan"?["lan"]:["inet"],o=t("span",{class:"dl-access","aria-label":vt(n.access)},e.map(s=>t("span",{class:`dl-ibadge ${s}`},g(s==="lan"?"home":"globe"))));return we(o,()=>[t("div",{class:"dl-tip-title"},vt(n.access)),n.access==="lan"&&n.services?.length?t("div",{class:"dl-muted"},W(n.services.length,"%s home service only","%s home services only")):""]),o}function ti(n){return{active:null,paused:_("Paused"),expired:_("Access ended"),quota:_("Data limit"),hours:_("Outside hours"),server_off:_("Server off"),no_server:_("No server")}[n]}function pn(n,e,o=_("Not set up yet"),s){let r=new Date(n.handshake*1e3).toLocaleString(le()),a=n.handshake?`${m(_("Last seen %s"),pe(n.handshake,e))} · ${r}`:"";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=s&&ti(s.state);return i?t("span",{class:"dl-dstat warn",title:a||_("Not connected yet")},i):n.handshake?t("span",{class:"dl-dstat",title:r},m(_("Last seen %s"),pe(n.handshake,e))):t("span",{class:"dl-dstat warn",title:_("Waiting for the first connection")},o)}var un=null;function os(n,e,o,s){un?.close();let r=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()},g("x"))]),t("div",{class:"dl-drawer-body"},e),o?t("div",{class:"dl-drawer-foot"},o):""]),a=t("div",{class:"dl-drawer-overlay dl-root",click:u=>{u.target===a&&c()}},r),i=u=>{u.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&c()},l=!1,d=Ee(()=>c());function c(){l||(l=!0,d(),document.removeEventListener("keydown",i),a.classList.remove("open"),setTimeout(()=>a.remove(),220),un===p&&(un=null),s())}let p={close:c,panel:r};return document.addEventListener("keydown",i),document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("open")),un=p,p}function ge(n,e,o){return t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},n),o?t("span",{class:"dl-sub"},o):""]),t("div",{class:"dl-setrow-ctl"},e)])}function _e(n,e,o,s=e){let r=ge(n,s," "),a=r.querySelector(".dl-sub"),i=()=>{let l=o();a.textContent=l.text,a.classList.toggle("bad",l.bad),e.classList.toggle("cbi-input-invalid",l.bad)};return e.addEventListener("input",i),r.refresh=i,r.help=o,i(),r}function Me(n,e,o,s=e){let r=t("div",{class:"dl-sub"}),a=t("div",{class:"cbi-value dl-live"},[t("div",{class:"cbi-value-title"},[t("label",{},n),r]),t("div",{class:"cbi-value-field"},s)]),i=()=>{let l=o();r.textContent=l.text,r.classList.toggle("bad",l.bad),e.classList.toggle("cbi-input-invalid",l.bad)};return e.addEventListener("input",i),e.addEventListener("change",i),a.refresh=i,a.help=o,i(),a}function je(n,e=[]){for(let o of n){let s=o.help?.();if(s?.bad)return s.text}for(let o of e){let s=o();if(s.bad)return s.text}return null}function Gt(n,e,o,s=""){return t("section",{class:`dl-setsec ${s}`},[t("div",{class:"dl-setsec-body"},[n?t("h3",{},n):"",...e]),o.length?t("div",{class:"dl-setsec-foot"},o):""])}function ke(n,e,o,s){return t("div",{class:"dl-group"},[t("div",{class:"dl-group-head"},[t("span",{class:"dl-group-ic"},g(n)),t("span",{class:"dl-stack"},[t("b",{},e),o?t("span",{class:"dl-sub"},o):""])]),t("div",{class:"dl-group-body"},s.filter(r=>r!==""))])}function it(n,e,o,s,r){return t("div",{class:`dl-row dl-need-row ${e}`},[e?t("span",{class:"dl-need-ic"},g(n)):g(n),t("span",{class:"dl-row-main dl-stack"},[t("b",{},o),t("span",{class:"dl-sub"},s)]),r])}function bt(n){return t("div",{class:"dl-note warn"},[g("alert"),t("span",{},n)])}function xt(n,e){let o={ok:"success",warn:"warning",error:"error",info:"notice"}[n];return t("div",{class:`alert-message ${o}`},e)}function St(n,e=""){let o=t("div",{class:e});return o.innerHTML=n,o}var ds=Fa(is(),1),ni=n=>``,ls="#0a0a0a",oi="#f2f2f2",si={night:[ls,oi],day:["#ffffff",ls]},ri=n=>n.length>300,Pt=n=>+n.toFixed(2);function ro(n,e,o,s,r){return`M${Pt(n+r)} ${Pt(e)}h${Pt(o-2*r)}a${r} ${r} 0 0 1 ${r} ${r}v${Pt(s-2*r)}a${r} ${r} 0 0 1 -${r} ${r}h-${Pt(o-2*r)}a${r} ${r} 0 0 1 -${r} -${r}v-${Pt(s-2*r)}a${r} ${r} 0 0 1 ${r} -${r}z`}function mn(n,e=3,o=!0,s="plain"){let r=ri(n),a=s!=="plain",[i,l]=a?si[s]:["#fff","#000"],d=(0,ds.default)(0,r?"L":"H");d.addData(n,"Byte"),d.make();let c=d.getModuleCount(),p=c+e*2,u=o&&!r?Math.round(c*.22):0;u&&(c-u)%2&&u++;let v=(c-u)/2,M=v+u,x=(b,k)=>u>0&&b>=v&&b=v&&ka&&(k<7&&b<7||k<7&&b>=c-7||k>=c-7&&b<7),S="";if(a){let b=r?.48:.42;for(let k=0;k${ni(a?i:"#fff")}`}let $=``;return a?`${$}${E}`:`${$}${E}`}function wt(){let n=document.documentElement.getAttribute("data-darkmode");return n!=null?n==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function hn(n){let e=wt();return St(mn(n,3,!0,e?"night":"day"),`dl-qr${e?"":" light"}`)}function ao(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[o,s,r,a]=e.slice(1,5).map(Number),i=Number(e[5]);if([o,s,r,a].some(c=>c>255)||i<8||i>30)return null;let l=o*2**24+s*2**16+r*2**8+a,d=2**(32-i);return{net:l-l%d,size:d}}var ai=(n,e)=>n.netao(n));function Dt(n){return n.split("/")[0].split(".").slice(0,3).join(".")}function fn(n){return`${n.trim()}.0/24`}function lo(n,e,o){let s=n.trim(),r=/^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s)?ao(fn(s)):null;if(!r)return{text:_("Three numbers, like 10.77.0."),bad:!0};if(!ii.some(i=>r.net>=i.net&&r.net+r.size<=i.net+i.size))return{text:_("Use a private range: 10.x.x, 172.16–31.x or 192.168.x."),bad:!0};let a=e.find(i=>{let l=ao(i.cidr);return l!=null&&ai(r,l)});if(a){let i=a.cidr.endsWith("/24")?`${Dt(a.cidr)}.x`:a.cidr,l=m(_("%s already uses %s."),a.name,i);return{text:o&&o!==s?`${l} ${m(_("Try %s."),o)}`:l,bad:!0}}return{text:m(_("Devices get %s – %s, the router %s."),`${s}.2`,`${s}.254`,`${s}.1`),bad:!1}}var ps=(n,e)=>e.find(o=>o.from<=n&&n<=o.to)?.who??null,li=n=>Number.isInteger(n)&&n>=1&&n<=65535;function qt(n,e,o){if(!li(n))return{text:_("Use a port from 1 to 65535."),bad:!0};let s=ps(n,e);return s?{text:m(_("Used by %s. Choose another port."),s),bad:!0}:{text:o,bad:!1}}function gn(n,e,o){let s=o?m(_("HTTPS here, plain HTTP for links on IP addresses on %s."),n+1):_("HTTPS on this port, opened on WAN."),r=qt(n,e,s);if(r.bad||!o)return r;if(n===65535)return{text:_("Links on IP addresses also need the next port: choose a lower one."),bad:!0};let a=ps(n+1,e);return a?{text:m(_("Links on IP addresses also need %s, used by %s. Choose another port."),n+1,a),bad:!0}:r}var co=n=>Array.from(n).length,cs=48,di=/[<>"\\\u0000-\u001f\u007f]/,us=(n,e)=>m(N_(n,"Up to %s character (%s now).","Up to %s characters (%s now)."),V(n),V(co(e)));function Ne(n,e=[],o=""){let s=n.trim();return s?co(n)>cs?{text:us(cs,n),bad:!0}:di.test(n)?{text:_('Names can’t contain < > " or \\.'),bad:!0}:e.some(r=>r.toLowerCase()===s.toLowerCase())?{text:m(_("“%s” already exists - pick another name."),s),bad:!0}:{text:o,bad:!1}:{text:_("Enter a name."),bad:!0}}function ms(n,e=[]){return co(n)>32?{text:us(32,n),bad:!0}:Ne(n,e,_("Shown on the person cards."))}var ci=/^[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])?)*$/,pi=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;function At(n){let e=pi.exec(n);return!!e&&e.slice(1).every(o=>Number(o)<=255)}function io(n){return/^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/.test(n)&&!/:::/.test(n)}function $t(n,e,o=null){let s=n.trim();if(!s)return o!=null?{text:o,bad:!1}:{text:_("Enter a hostname or IP address."),bad:!0};if(/^[a-z]+:\/\//i.test(s))return{text:_("Leave out https:// - just the name."),bad:!0};if(/\/.*/.test(s))return{text:_("Just the name, without a path."),bad:!0};if(/^[^:\[]+:\d+$/.test(s))return{text:_("Just the name, without a port (the port is on AmneziaWG)."),bad:!0};if(/\s/.test(s))return{text:_("A hostname has no spaces."),bad:!0};if(s.length>253||!(ci.test(s)||At(s)||io(s)))return{text:_("Use a hostname or an IP address."),bad:!0};let r=io(s)?`[${s}]`:s;return{text:e?m(_("Devices connect to %s."),`${r}:${e}`):m(_("Links use %s."),r),bad:!1}}function hs(n,e){let o=n.split(/[ ,]+/).filter(Boolean);if(!o.length)return{text:m(_("This router (%s): queries go where your home network sends them, and home names work."),e),bad:!1};let s=o.find(a=>!At(a)&&!io(a));if(s)return{text:m(_("“%s” is not an IP address. Separate several with commas."),s),bad:!0};let r=new Intl.ListFormat(le(),{type:"conjunction"}).format(o);return{text:m(_("Devices use %s - home names and your LAN’s DNS filters no longer apply to them."),r),bad:!1}}function fs(n,e){let o=n.trim();if(!o)return{text:m(_("Automatic by device type and disguise: %s for computers and routers, %s for phones and tablets."),e.computer,e.phone),bad:!1};if(!/^\d{1,4}$/.test(o)||Number(o)<1280||Number(o)>1500)return{text:_("MTU must be 1280–1500, or empty for automatic."),bad:!0};let s=Number(o);return{text:m(_("Computers and routers get %s, phones and tablets %s."),s,Math.min(s,1280)),bad:!1}}function gs(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:m(_("Devices send a packet every %s s to keep NAT open (a little battery on phones)."),e),bad:!1}:{text:_("Default: a packet every 25 s keeps NAT open and “Connected” accurate."),bad:!1}}function vn(n,e=0){let o=n.trim();if(!/^\d{1,2}$/.test(o)||Number(o)<1||Number(o)>32)return{text:_("Use 1–32."),bad:!0};let s=Number(o);return e>s?{text:e-s===1?m(N_(e,"Already has %s device: remove one first, or allow more.","Already has %s devices: remove one first, or allow more."),V(e)):m(N_(e,"Already has %s device: remove %s first, or allow more.","Already has %s devices: remove %s first, or allow more."),V(e),V(e-s)),bad:!0}:{text:W(s,"They can add %s device themselves.","They can add %s devices themselves."),bad:!1}}function bn(n,e=!0){let o=n.trim();if(!o)return{text:_("Optional. No data limit."),bad:!1};let s=Number(o);return!/^\d+(\.\d+)?$/.test(o)||s<0||s>1e5?{text:_("A number of GB, up to 100000."),bad:!0}:s===0?{text:_("Optional. No data limit."),bad:!1}:{text:m(e?_("Paused after %s GB this month, resumed on the 1st."):_("Paused after %s GB in total."),V(s)),bad:!1}}function vs(n,e,o,s){let r=n.trim();if(!r)return{text:_("Optional. No end date."),bad:!1};let a=o(r,e);return a==null?{text:_("Use a date."),bad:!0}:a<0?{text:_("That date has passed: access would end at once."),bad:!0}:{text:a===1?m(_("Access ends today (%s)."),s(r)):m(N_(a,"Access ends in %s day (%s).","Access ends in %s days (%s)."),V(a),s(r)),bad:!1}}function bs(n,e=null){let o=n.trim();return o?At(o)?e&&!e(o)?{text:m(_("%s is not in any home network of this server: nobody would reach it."),o),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 xs(n){let e=n.split(/[ ,]+/).filter(Boolean);if(!e.length)return{text:_("All ports."),bad:!1};let o=e.find(s=>!/^\d{1,5}$/.test(s)||Number(s)<1||Number(s)>65535);return o?{text:m(_("“%s” is not a port (1–65535)."),o),bad:!0}:{text:m(N_(e.length,"Port %s.","Ports %s."),e.join(", ")),bad:!1}}function ws(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 ys(n,e="phone.myata"){let o=n.trim();return o?/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(o)?{text:m(_("Devices get names like %s."),`${e}.${o}`),bad:!1}:{text:/[A-Z]/.test(o)?_("Lowercase only."):_("Lowercase letters, digits, dashes and dots."),bad:!0}:{text:m(_("The default, lan: devices get names like %s."),`${e}.lan`),bad:!1}}function ks(n){let e=n.trim();return e?At(e)?{text:m(_("%s takes over when the tunnel is down."),e),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 _s(n){let e=n.trim();return/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(e)?{text:m(_("Runs within an hour after %s (router time)."),e),bad:!1}:{text:_("Use HH:MM, 00:00–23:59."),bad:!0}}function po(n,e,o,s={}){let r=0,a="",i=null;return{help:()=>{let{host:c,port:p}=n(),u=$t(c,p,s.empty??null);return u.bad||!c.trim()?u:i&&i.host===c.trim()?{text:i.text,bad:i.bad}:{text:`${s.idle?.()||u.text} ${_("Checking where it points…")}`,bad:!1}},schedule:()=>{let{host:c}=n(),p=$t(c,n().port,s.empty??null);p.bad||!c.trim()||c.trim()===i?.host||(clearTimeout(r),r=window.setTimeout(async()=>{let u=c.trim();a=u;try{let{id:v,port:M}=n(),x=await e(u,v,M);if(a!==u)return;i={host:u,text:x.text,bad:x.status==="error"}}catch{if(a!==u)return;i={host:u,text:p.text,bad:!1}}o()},700))}}}var uo=["%d system package","%d system packages","%s (after %d repair)","%s (after %d repairs)","%s - %d repairs didn't help","%s - %s","%s - not repaired again (%d repairs didn't help)","%s has no IPv4 address.","%s is not a bridge, so Dawnline cannot join the LAN as a device.","%s needs a manual switch in Components","%s still give devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.","%s still gives devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.","%s · restored","Access rules","Activity","AmneziaWG is missing from the router","AmneziaWG is running again","AmneziaWG is running again · accepting connections on port %d","AmneziaWG isn't accepting connections on port %d","AmneziaWG isn't running","Backup","Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.","Choose another interface name in the server settings.","Components","Connections","DNS for Home-only devices","Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.","Firewall","Install it in Dawnline → Components.","Internet like a home device","MTU is now automatic","Missing: %s.","No LAN detected.","No free address on %s.","No free link-local range for the internal link.","No free routing table.","People","Personal links","Personal portal","Router","Servers","Speed","System packages","The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.","Traffic","Watchdog","Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline.","a new build needs a manual switch in Components","answers again","are loaded again","are missing","automatic update failed","background check failed: %s","can't reach Dawnline (luci.dawnline is missing in rpcd)","can't use the network interface %s: it exists and isn't Dawnline's","certificate expires %s","certificate expires within 7 days","certificate renewed · valid until %s","couldn't be repaired: %s","couldn't be updated - the previous rules stay, and changes to access wait until they load","couldn't load - no device is loaded into the tunnels until they do","couldn't load devices into the tunnel","couldn't start","couldn't start · %d failed attempts in %d min","failed - internet goes out directly for now","failed: %s",'has an invalid interface name "%s"',"installed the %s build","installed the %s build · %s","is kept down","is kept down: its disguise needs AmneziaWG %s (installed: %s)","is kept down: its disguise needs AmneziaWG %s (installed: none)","is off","is on · traffic enters %s as %s","is ready again","isn't answering on port %d","isn't installed: no tunnel can run - install it in Dawnline → Components","isn't installed: tunnels were left as they are","isn't known to the network service - restart the network or reboot","isn't running","isn't running on this router (fw4): tunnels and the portal are closed","kernel module isn't installed: no tunnel can run - install it in Dawnline → Components","kernel module isn't loaded","loading it","loading them again","moved to word codes","netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.","network changed - Dawnline set itself up again","nightly backup failed: %s","public address changed · %s → %s","reaches Dawnline again","reloading rpcd","restarted · version %s","restarting for the AmneziaWG update","restarting it","restoring them","rules for Dawnline are in place again","rules for Dawnline aren't loaded","rules for Dawnline were changed or removed","runs again","runs without its fast path","setting it up again","started","started with the router · version %s","started · accepting connections on port %s","started · version %s","stopped unexpectedly","stopped unexpectedly - started again","update failed","update to %s failed its check - rolled back to %s","updated automatically · %s","updated automatically · %s → %s","updated · %s","updated · %s → %s","updates available · %s","was broken - set up again (%s as %s)"];var mi={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"},Ht=["connections","people","problems"];function Ke(n){return{connections:_("Connections"),people:_("People"),problems:_("Problems")}[n]}function Cs(n){return{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)")}[n]}var Ft=n=>mi[n]??"problems";function Kt(n){return{awg:"AmneziaWG",dawnline:"Dawnline",portal:_("Portal")}[n]??n}var hi=["person_added","person_removed","person_changed"];function Ve(n){return n.by?n.by:hi.includes(n.type)||n.detail==="by admin"||n.detail?.endsWith(" (admin)")?"admin":n.detail?.endsWith(" (portal)")?"portal":null}function Ls(n){return(n.detail??"").replace(/ \((admin|portal)\)$/,"").replace(/^by admin$/,"")}var xn=n=>n.sys?["error","repair","down"].includes(n.sys.level):Ft(n.ev.type)==="problems";function wn(n){let e=n.keep_days>0?W(n.keep_days,"%s day","%s days"):_("no age limit"),o=n.persist==="off"?_("kept in memory only (lost on reboot)"):n.persist==="10min"?_("saved to flash every 10 minutes"):_("saved to flash hourly");return m(_("Kept for %s, %s, %s."),e,W(n.max,"up to %s event","up to %s events"),o)}function mo(n){return{"paused by admin":_("paused by admin"),"end date reached":_("end date reached"),"data limit reached":_("data limit reached"),"outside allowed hours":_("outside allowed hours"),"no server":_("no server"),"server turned off":_("server turned off")}[n]??n}function Ms(n){let e=/^(\d+) days?$/.exec(n);return e?Number(e[1]):null}function Es(n){let e={name:_("name"),access:_("access"),device_limit:_("device limit"),expires:_("end date"),expire_action:_("what happens at the end"),expire_warn:_("warning before the end"),quota_gb:_("data limit"),quota_period:_("data limit period"),bonus_gb:_("extra data"),hours:_("allowed hours"),dns_mode:_("DNS"),paused:_("pause"),services:_("home services"),circle:_("circle","setting"),home_nets:_("home networks"),server:_("server")};return n.split(", ").map(o=>{let s=/^moved to (.+)$/.exec(o)?.[1];return s?m(_("moved to %s"),s):e[o]??o.replace(/_/g," ")}).join(", ")}function Ts(n,e,o){let r={"cleared|the service log":_("You cleared the service log"),"cleared|the activity log":_("You cleared the activity log"),"exported|all settings":_("You exported all settings"),"imported|settings from a file":_("You imported settings from a file"),"restored|from a file":_("You restored a backup from a file"),"turned on|the personal portal":_("You turned on the personal portal"),"turned off|the personal portal":_("You turned off the personal portal"),"changed|the personal portal":_("You changed the personal portal"),"turned on|the watchdog":_("You turned on the watchdog"),"turned off|the watchdog":_("You turned off the watchdog"),"reset traffic history|for everyone":_("You reset traffic history for everyone")}[`${n}|${o??""}`];if(r)return{text:r,named:!1};let i={"created|server":_("You created server %s"),"changed|server":_("You changed server %s"),"removed|server":_("You removed server %s"),"turned on|server":_("You turned on server %s"),"turned off|server":_("You turned off server %s"),"added|circle":_("You added circle %s"),"changed|circle":_("You changed circle %s"),"removed|circle":_("You removed circle %s"),"restored|backup":_("You restored backup %s")}[`${n}|${e??""}`];return i?{text:i,named:!0}:n==="reset traffic history"&&/^for (.+)$/.exec(o??"")?.[1]?{text:_("You reset traffic history for %s"),named:!0}:null}var Ss=(n,e)=>n==="reset traffic history"?e.replace(/^for /,""):e;function Ps(n){let e=o=>{let s={"other addresses":_("other addresses"),certificate:_("certificate"),redirect:_("redirect"),"devices kept apart":_("devices kept apart"),"devices reach each other":_("devices reach each other"),"devices reach each other in circles":_("devices reach each other in circles"),"home network and internet path":_("home network and internet path"),"the file holds private keys":_("the file holds private keys"),"problems are only logged, nothing is repaired":_("problems are only logged, nothing is repaired"),name:_("name"),"public address":_("public address"),"AmneziaWG port":_("AmneziaWG port"),"tunnel network":_("tunnel network"),connections:Ke("connections"),people:Ke("people"),problems:Ke("problems")};if(s[o])return s[o];let r;return(r=/^port (\d+)$/.exec(o))?m(_("port %s"),r[1]):(r=/^address (.+)$/.exec(o))?m(_("address %s"),r[1]):(r=/^disguise: (.+)$/.exec(o))?m(_("disguise: %s"),r[1]):(r=/^(\d+) events?$/.exec(o))?W(Number(r[1]),"%s event","%s events"):(r=/^older than (\d+) days$/.exec(o))?W(Number(r[1]),"older than %s day","older than %s days"):(r=/^with (\d+) (person|people)$/.exec(o))?W(Number(r[1]),"with %s person","with %s people"):(r=/^(\d+) entr(y|ies)( older than (\d+) days)?$/.exec(o))?r[4]?`${W(Number(r[1]),"%s entry","%s entries")}, ${W(Number(r[4]),"older than %s day","older than %s days")}`:W(Number(r[1]),"%s entry","%s entries"):o};return n.split(" · ").map(o=>o.split(", ").map(e).join(", ")).join(" · ")}var fi=null,gi=new Set(uo);function vi(){return fi??(fi=uo.filter(n=>/%[sd]/.test(n)&&n.replace(/%[sd]/g,"").trim()).map(n=>({t:n,fixed:n.replace(/%[sd]/g,"").length,re:new RegExp(`^${n.split(/(%[sd])/).map(e=>e==="%s"?"(.+?)":e==="%d"?"(\\d+)":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("")}$`)})).sort((n,e)=>e.fixed-n.fixed))}function Nt(n,e=0){let o=n.replace(/ — /g," - ");if(gi.has(o))return eo(o);if(e>2)return n;for(let s of vi()){let r=s.re.exec(o);if(r)return m(eo(s.t),...r.slice(1).map(a=>Nt(a,e+1)))}return o.includes(", ")?o.split(", ").map(s=>Nt(s,e+1)).join(", "):n}function $s(n,e=120,o=26,s=Fe(new Date)){let r=Math.max(1,...n),a=t("div",{class:"dl-spark"});return a.style.width=`${e}px`,a.style.height=`${o}px`,n.forEach((i,l)=>{let d=t("i");d.style.height=`${Math.max(6,i/r*100)}%`,i||d.classList.add("zero");let c=t("span",{},[d]),p=n.length-1-l;we(c,()=>[t("div",{class:"dl-tip-title"},p===0?_("Today"):p===1?_("Yesterday"):Et(Ut(s,-p)).toLocaleDateString(le(),{weekday:"short",day:"numeric",month:"short"})),t("div",{class:"dl-muted"},re(i))]),a.appendChild(c)}),a}function Ds(n){let e=n==null?"":String(n);return/^[=+\-@\t\r]/.test(e)&&(e=`'${e}`),/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function As(n,e,o){return[n.map(s=>Ds(o?.[s]??s)).join(","),...e.map(s=>n.map(r=>Ds(s[r])).join(","))].join(` -`)}function bi(n){let e=new Map(n.people.map(s=>[s.id,s.name])),o=new Map(n.people.flatMap(s=>s.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Ze(n,e,o,s="",r=[]){let a=bi(n),i=[...e.map(u=>({ts:u.ts,category:Ft(u.type),type:u.type,person:u.person?a.people.get(u.person)??u.pname??u.person:"",device:u.device?a.devices.get(u.device)??u.dname??u.device:"",detail:u.detail??"",where:u.where??"",by:Ve(u)??""})),...r.map(u=>({ts:u.ts,category:"system",type:`${u.src}.${u.level}`,person:"",device:"",detail:`${u.who?`${u.who} `:""}${u.msg}${u.detail?` -${u.detail}`:""}`,where:Kt(u.src),by:""}))].sort((u,v)=>u.ts-v.ts).map(({ts:u,...v})=>({time:new Date(u*1e3).toISOString(),...v})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${s?`-${s}`:""}-${l}.${o}`;if(o==="json"){Ae(d,JSON.stringify(i,null,2),"application/json");return}let c=["time","category","type","person","device","detail","where","by"],p={time:_("Time"),category:_("Category"),type:_("Type"),person:_("Person"),device:_("Device"),detail:_("Detail"),where:_("Where"),by:_("By")};Ae(d,As(c,i,p),"text/csv")}var xi=["","7","30","90"],wi=n=>n?W(Number(n),"Older than %s day","Older than %s days"):_("Everything"),Ns=n=>n?W(n,"%s event removed","%s events removed"):_("Nothing matched");function lt(n,e,o,s,r,a=!1){let i=t("select",{class:"cbi-input-select"},[t("option",{value:""},_("All categories")),...Ht.map(d=>t("option",{value:d,selected:d===r?"selected":null},Ke(d))),a?t("option",{value:"system",selected:r==="system"?"selected":null},_("System")):""]),l=t("select",{class:"cbi-input-select"},xi.map(d=>t("option",{value:d},wi(d))));de(n,[t("p",{class:"dl-muted"},`${e} ${_("This cannot be undone; export first if you want a copy.")}`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},_("Category")),i]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},_("Which events")),l])],[ue()," ",N(_("Clear"),async()=>{let d=0;if(i.value!=="system")try{d+=(await H.logsClear({...o,category:i.value,older_days:l.value})).removed}catch(c){q(Ce(c),"error",1e4);return}if(a&&(i.value==="system"||i.value===""))try{d+=(await H.serviceLogClear(l.value)).removed}catch(c){ce();let p=m(_("The service log was not cleared: %s"),Ce(c));q(i.value==="system"?p:`${m(_("Activity: %s."),Ns(d).toLowerCase())} ${p}`,"error",1e4),s();return}ce(),q(Ns(d),"success",3e3),s()},"negative")])}function zt(n,e,o,s){let r=n==="device"?m(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."),o):n==="person"?m(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."),o):_("Clears traffic history for everyone. Data limits start again from zero.");de(n==="all"?_("Reset all traffic history?"):m(_("Reset traffic history for %s?"),o),[t("p",{class:"dl-muted"},r)],[ue()," ",N(_("Reset"),async()=>{await K(()=>H.usageClear(n,e),_("Traffic history reset"))&&(ce(),s())},"negative")])}function ye(n,e,o){let s=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!s.classList.contains("on");ho(s,r),o?.(r)}},t("i"));return s}function ho(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var He=n=>n.classList.contains("on");function Qe(n,e,o={}){n.some(([a])=>a===e)||(n=[...n,[e,e]]);let s=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>s.querySelectorAll(":scope > button").forEach(a=>{let i=a.dataset.v===s.dataset.value;a.classList.toggle("on",i),a.setAttribute("aria-checked",i?"true":"false")});for(let[a,i]of n)s.appendChild(t("button",{type:"button",role:"radio","data-v":a,click:()=>{a!==s.dataset.value&&(o.optimistic!==!1&&(s.dataset.value=a,r()),o.onChange?.(a))}},i));return r(),s}function Vt(n,e,o,s={}){return t("button",{type:"button",...s,class:`dl-chipbtn${e?" on":""}${s.class?` ${s.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function Xe(n,e,o,s){return n.some(([r])=>r===e)||(n=[...n,[e,e]]),t("select",{class:"cbi-input-select","aria-label":o,change:r=>s?.(r.target.value)},n.map(([r,a])=>t("option",{value:r,selected:r===e?"selected":null},a)))}function yn(n,e,o){let s=new ui.Dropdown(e,Object.fromEntries(n),{multiple:!0,sort:n.map(([a])=>a),select_placeholder:_("None")}),r=s.render();return r.setAttribute("aria-label",o),{node:r,value:()=>s.getValue()}}function he(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var yi={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:""},ki={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 _i(n){let e={};for(let[o,s]of Object.entries(ki))n[o]!=null&&n[o]!==""&&(e[s]=String(n[o]));return e}function Ci(n,e){let o=n.amnezia,s=o.obfuscation??{},r=d=>s[d]!=null&&s[d]!==""?String(s[d]):yi[d],a=o.host.replace(/^\[(.*)\]$/,"$1"),i={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),..._i(s),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r -`),hostName:a,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(i),port:String(o.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:a};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Li(n){let e="";for(let o=0;o"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),s=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+s.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(s,4),r}catch{return null}}async function fo(n,e,o=!0){let s=new TextEncoder().encode(JSON.stringify(Ci(n,e))),r=o?await Mi(s):null;return`vpn://${Li(r??s)}`}function zs(){return[{id:"off",title:_("Off"),ic:"zap",stealth:0,speed:4,text:_("Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block."),apps:_("Any WireGuard app"),short:_("Any WireGuard app")},{id:"balanced",title:_("Balanced"),ic:"shield",stealth:3,speed:4,needs:"v2",text:_("AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk."),apps:_("AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps"),short:_("AmneziaWG 2.0+ apps")},{id:"max",title:_("Maximum"),ic:"lock",stealth:4,speed:3,needs:"v3",text:_("AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS."),apps:_("Apps with AmneziaWG 3.1 (current AmneziaVPN)"),short:_("AmneziaWG 3.1 apps")}]}var Yt=n=>zs().find(e=>e.id===n),kn=n=>n.v3?"max":n.v2?"balanced":"off",Jt=n=>n==="standard"?_("Standard (old)"):n==="strong"?_("Strong (old)"):null;function Ei(n,e){return e?n==="v2"?_("Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on)."):_("Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."):n==="v2"?_("Needs AmneziaWG on the router."):_("Needs AmneziaWG 3.1 on the router: install it first.")}function Hs(n,e){return t("span",{class:"dl-dots",title:m(_("%s: %s of 4"),e,n)},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:odom.content(a,zs().map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,i(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},g(l.ic)),t("b",{},l.title),l.id===s?t("span",{class:"dl-pill ok"},_("Current")):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[Hs(l.stealth,_("Stealth")),Hs(l.speed,_("Speed"))]),t("div",{class:"dl-method-foot"},d?[g(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[g("alert"),t("span",{},Ei(l.needs,r))])])}));return i(),a}function Rs(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var Is=[["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 Ti(n){let e=c=>n[c]!=null&&n[c]!=="",o=Is.filter(([c])=>e(c));if(!o.length)return null;let s=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),r=(c,p,u,v)=>{let M=Is.filter(([x])=>v.includes(x)&&e(x));return M.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[g(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},M.map(([x,h])=>s(x,h)))]):""},a=Number(n.jc||0),i=(n.i1??"").includes("0x8580")?_("A first packet shaped like a DNS answer."):_("Extra packets sent before the handshake."),l=o.map(([c,p])=>`${p} = ${n[c]}`).join(` -`),d=t("div",{class:"dl-pgrid"},[r(_("Junk packets"),"zap",a?m(N_(a,"%s random packet of %s–%s bytes before each handshake.","%s random packets of %s–%s bytes before each handshake."),V(a),n.jmin,n.jmax):_("No junk packets."),["jc","jmin","jmax"]),r(_("Padding"),"archive",_("Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard."),["s1","s2","s3","s4"]),r(_("Packet types"),"key",_("The values that replace WireGuard’s recognisable message types."),["h1","h2","h3","h4"]),r(_("Signatures"),"globe",i,["i1","i2","i3","i4","i5"]),r(_("Protection"),"lock",_("AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets."),["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r(_("Timing"),"clock",_("Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."),["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[g("chevron"),t("span",{},_("Current parameters")),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),xe(l,_("Parameters copied"))}},_("Copy as config"))]),d])}function Bs(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",s&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Si(n){let e=!1,o=t("pre",{class:"dl-conf"}),s=()=>dom.content(o,n.conf.split(` -`).flatMap((i,l)=>l?[` -`,Bs(i,e)]:[Bs(i,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),e=!e,dom.content(r,[g(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[g("key"),_("Show key")]);s();let a=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${W(a,"%s byte","%s bytes")}`)]),N([g("download")," ",_("Download")],()=>Ae(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[g("chevron"),t("span",{},_("Configuration")),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),xe(n.conf,_("Configuration copied"))}},[g("copy"),_("Copy")])]),o])])}function go(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([s,r])=>r==null||r===""||r===(o[s]??"0"))}async function Pi(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},_("This device generated its own keys in the browser, so its full configuration only exists on that device."));let o=await fo(n,n.server),s={qr:()=>t("div",{class:"dl-qr-pane"},[hn(n.conf),t("span",{class:"dl-sub"},go(n)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),N(_("Copy"),()=>xe(o,_("Key copied")))]),t("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>Si(n)},r=t("div",{class:"dl-connect-body"}),a=t("div",{class:"dl-seg"}),i=l=>{a.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,s[l]())};for(let[l,d]of[["file",_("File")],["key",_("Key")],["qr",_("QR code")]])a.appendChild(t("button",{type:"button","data-id":l,click:()=>i(l)},d));return i(e),t("div",{class:"dl-stack gap12"},[a,r])}async function $i(n,e,o,s){let r=Yt(o),i=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await me(s?_("Generate new disguise values?"):m(_("Switch to %s?"),r.title),[W(i,"%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).","%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."),o==="max"?_("They need an app with AmneziaWG 3.1."):o==="balanced"?_("They need an app with AmneziaWG 2.0 or newer."):"",n.st.servers.length===1&&i?_("To keep the old disguise for some people, add a second server and move them there."):""].filter(Boolean).join(" "),s?_("Generate and apply"):_("Switch and apply"),!0)&&await K(()=>H.serverObfuscation(e.id,o),s?_("New values applied"):m(_("%s applied"),r.title))&&(q(_("Devices are marked “Update config” until they import again."),"info",6e3),await n.refresh())}function Di(n,e){let o=n.st,s=he(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=he(e.mtu?String(e.mtu):"",{placeholder:_("Auto"),inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=he(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=Yt(e.preset)?e.preset:void 0,l=i??kn(o.awg),d=N("",()=>$i(n,e,l,l===i),"neutral"),c=()=>dom.content(d,l===i?[g("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Yt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],v=_e(_("UDP port"),s,()=>qt(Number(s.value),u,[_("Opened on the WAN firewall automatically."),Number(s.value)===4500?_("4500 is IPsec’s port: most networks let it through."):""].filter(Boolean).join(" ")));H.serverPorts(e.id).then(h=>{u=h.udp_taken??[],v.refresh()}).catch(()=>{});let M=_e("MTU",r,()=>fs(r.value,e.mtus)),x=_e(_("Keep-alive"),a,()=>gs(a.value));return Gt("",[Rs("AmneziaWG",e.ifname),ke("globe",_("Listening"),_("Where devices reach this core from the internet"),[v]),ke("file",_("In every device configuration"),_("Changing these marks devices “Update config” until they import again"),[M,x]),ke("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[Jt(e.preset)?xt("warn",oe(_("%s is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to %s or %s: devices import their configuration again."),t("b",{},Jt(e.preset)),t("b",{},_("Balanced")),t("b",{},_("Maximum")))):"",_n(o.awg,l,h=>{l=h,c()},i,p),p&&!o.awg.v3?xt("info",oe(_("This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1."),t("b",{},_("Maximum")))):"",Ti(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",{},[g("chevron"),t("span",{},_("Tunnel")),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ge(_("Interface"),t("span",{class:"dl-mono"},`${e.ifname} · ${m(_("router %s"),e.address)}`)),ge(_("Tunnel subnet"),t("span",{class:"dl-mono"},e.subnet),_("Device addresses come from it.")),ge(_("Server public key"),t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),N([g("copy")],()=>xe(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.")),N(_("Save"),()=>{let h=je([v,M,x]);if(h){q(h,"warning");return}return n.save({port:s.value,mtu:r.value,keepalive:a.value},_("AmneziaWG saved"))},"positive")])}function Ai(n){let e=Yt(n.preset),o=n.obf??{},s=(i,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>t("i",{class:d+o[i]).map(i=>`${i.toUpperCase()} ${o[i]}`);return a.length&&r.push(a.slice(0,2).join(" · ")+(a.length>2?` +${a.length-2}`:"")),["h1","h2","h3","h4"].some(i=>o[i]&&o[i]!==String(["h1","h2","h3","h4"].indexOf(i)+1))&&r.push(_("H1–H4 random")),o.i1&&r.push(/0x(8580|0100)0001/.test(o.i1)?_("DNS-like first packets"):_("Signature packets")),o.header_protection_key&&r.push(_("Encrypted headers")),r.length||r.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":""}`},g(e?.ic??"shield")),t("span",{class:"dl-stack"},[t("b",{},e?e.title:Jt(n.preset)??_("Custom","disguise")),t("span",{class:"dl-sub"},e?e.short:Jt(n.preset)?_("Switch to Balanced or Maximum"):_("Set by hand"))])]),e?t("div",{class:"dl-disg-meters"},[t("span",{},_("Stealth")),s(e.stealth,"acc"),t("span",{},_("Speed")),s(e.speed,"ok")]):"",t("div",{class:"dl-disg-chips"},r.map(i=>t("span",{},i)))])}var vo={id:"awg",label:"AmneziaWG",settingsCard:Di,overviewTile:Ai,connectBlock:Pi,qrText:n=>n.conf,appKey:{get label(){return _("Copy AmneziaVPN config")},make:n=>fo(n,n.server)},file:{get label(){return _("Download AmneziaWG config")},make:n=>({name:n.filename,text:n.conf})}};var Ni={awg:vo};function Ge(n){return Ni[n?.core||"awg"]??vo}function Rt(n,e){return Ge(n.find(o=>o.id===e))}var Hi=2,Zt=new Set,bo=null,Cn=null;async function Os(){if(document.visibilityState!=="visible"||!Zt.size)return;let n=await H.rev().catch(()=>null);if(!n)return;let e=bo!=null&&n.rev!==bo;bo=n.rev,n.version&&(Cn&&n.version!==Cn?(q(m(_("Dawnline was updated to %s: reload the page."),n.version),"warning",15e3),Cn=null):Cn??(Cn=n.version)),e&&Zt.forEach(o=>o())}function Ln(n){return Zt.add(n),poll.add(Os,Hi),()=>{Zt.delete(n),Zt.size||poll.remove(Os)}}function Ws(n,e,o,s,r=0){let a=[],i=null,l=p=>{i&&p>i.from&&a.push({...i,to:p}),i=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&&(i={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&&(i={ip:u,from:p.ts,to:p.ts,live:!1})}else p.type==="disconnect"&&l(p.ts);let c=i;return c&&s?a.push({...c,to:Math.max(o,c.from),live:!0}):l(Math.min(o,r)),a}function et(n){return`${n.city||`${n.lat.toFixed(1)},${n.lon.toFixed(1)}`}|${n.cc}`}function Gs(n,e,o,s){let r=new Map;for(let i of e)(i.device===o||!r.has(i.ip))&&r.set(i.ip,i);let a=[];for(let i of n){let l=r.get(i.ip);!l||i.to<=s||a.push({key:et(l),point:l,from:Math.max(i.from,s),to:i.to,live:i.live})}return a}function qs(n){let e=new Map,o=0;for(let s of n)e.set(s.key,(e.get(s.key)??0)+(s.to-s.from)),o+=s.to-s.from;return new Map([...e].map(([s,r])=>[s,o?r/o:0]))}function js(n,e=2700){let o=[];for(let s of n){let r=o[o.length-1];if(r&&s.key!==r.key&&!s.live&&s.to-s.from{a&&(o.push({kind:"move",k:a,start:s,ms:e}),s+=e);let i=Math.min(1100,Math.max(350,(r.to-r.from)/3600*45));o.push({kind:"stay",k:a,start:s,ms:i}),s+=i}),{steps:o,total:s}}function Ys(n,e,o){let s=e.findIndex(l=>o>=l.start&&oo>=i.from&&oi.kind==="stay"&&i.k===s),a=n[s];return r.start+r.ms*Math.min(.999,Math.max(0,(o-a.from)/Math.max(1,a.to-a.from)))}var zi=n=>n<=0?0:n>=1?1:n<.5?2*n*n:1-(-2*n+2)**2/2;function Zs(n){return-xo/2+(1+xo)*zi((n-Us)/(1-Us))}var Qs=n=>n+Ks>=1;function Xs(n){return["interpolate",["linear"],["abs",["-",["get","pos"],n]],0,1,Ks,1,xo/2,0]}function er(n,e){let o=n==="24h"?86400:n==="7d"?604800:2592e3,s=e-o,r=[],a=(l,d)=>{let c=(l-s)/o;c>.02&&c<.98&&r.push([c,d])},i=new Date(s*1e3);if(n==="24h")for(i.setMinutes(0,0,0);i.getTime()/1e3<=e;)i.getHours()%6===0&&a(i.getTime()/1e3,`${String(i.getHours()).padStart(2,"0")}:00`),i.setHours(i.getHours()+1);else if(n==="7d")for(i.setHours(12,0,0,0);i.getTime()/1e3<=e;i.setDate(i.getDate()+1))a(i.getTime()/1e3,i.toLocaleDateString(le(),{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),a(c.getTime()/1e3,c.toLocaleDateString(le(),{day:"numeric",month:"short"}))}r.reverse()}return r}var Mn=n=>new Date(n*1e3).toLocaleTimeString(le(),{hour:"2-digit",minute:"2-digit"});function tr(n,e){let o=s=>new Date(s*1e3).toDateString();return o(n)===o(e)?_("Today"):o(n)===o(e-86400)?_("Yesterday"):new Date(n*1e3).toLocaleDateString(le(),{weekday:"short",day:"numeric",month:"short"})}var yo="https://unpkg.com/maplibre-gl@6.14.0/dist",nr={module:"sha384-q26X6R1yFeg0QR9SHHn6U3Nb0ddRRTtwxsahubv5R89/v5nijKpk9KviUp9ZLySk",css:"sha384-1TZtfVz7qtwR5vD7cMwjGT+9uiK4lqE3pbUOPwYO6OCpb+TYP0S9vLIhG02JCU04"},or="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",sr="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",Ri={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Qt=null;function Ii(n){if(n.appendChild(t("link",{rel:"stylesheet",href:`${yo}/maplibre-gl.css`,integrity:nr.css,crossorigin:"anonymous"})),Qt)return Qt;let e=`${yo}/maplibre-gl.mjs`;return Qt=new Promise((s,r)=>{let a=t("link",{rel:"modulepreload",href:e,integrity:nr.module,crossorigin:"anonymous"});a.addEventListener("load",()=>s()),a.addEventListener("error",()=>r(new Error("integrity"))),document.head.appendChild(a)}).then(()=>import(e)).then(s=>(s.getWorkerUrl()||s.setWorkerUrl(`${yo}/maplibre-gl-worker.mjs`),s),s=>{throw Qt=null,new Error(s?.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?)"))}),Qt}var Bi=10,rr=30,Oi=62,ji=4,ar=4.5,Ui=7,En="#3b82f6",ko="#8a8a8a";function ir(n,e,o=.2,s=64){let[r,a]=n,[i,l]=e,d=i-r,c=d>180?i-360:d<-180?i+360:i,p=c-r,u=l-a,v=Math.hypot(p,u);if(v===0||o===0)return[n,[c,l]];let M=-u/v,x=p/v,h=v*o,S=(r+c)/2+M*h,z=(a+l)/2+x*h,E=[],$=Math.max(2,Math.floor(s));for(let b=0;b<=$;b+=1){let k=b/$,y=1-k;E.push([y*y*r+2*y*k*S+k*k*c,y*y*a+2*y*k*z+k*k*l])}return E}function _o(n,e){let o=new Map;for(let s of n.geo.points){if(n.person&&s.person!==n.person||n.device&&s.device!==n.device||(e==="online"?!s.online:n.now-s.ts>Ri[e]))continue;let r=n.device?et(s):n.person?`${s.device}|${s.city}|${s.cc}`:s.device,a=o.get(r);(!a||s.online&&!a.online||s.online===a.online&&s.ts>a.ts)&&o.set(r,s)}return[...o.values()]}function Co(n,e){let o=0;return _o(n,e).sort((s,r)=>Number(r.online)-Number(s.online)||r.ts-s.ts).map(s=>({...s,n:s.online?0:++o}))}var dt=class{constructor(e,o="online",s=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=o,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:${s}px`},[this.status,this.card])}async mount(e){this.data=e;try{this.gl=await Ii(this.el)}catch(s){this.status.textContent=s.message;return}if(this.dead)return;this.map=new this.gl.Map({container:this.el,style:wt()?or:sr,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 s=this.el.querySelector(".maplibregl-ctrl-attrib");s?.classList.remove("maplibregl-compact-show"),s?.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 o=wt();this.theme=new MutationObserver(()=>{!this.map||wt()===o||(o=wt(),this.map.setStyle(o?or:sr))}),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"],En,ko],"circle-opacity":["case",["get","online"],.12,.06],"circle-stroke-width":1,"circle-stroke-color":["case",["get","online"],En,ko],"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":En,"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?En:ko,"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 o=new Map;for(let s of e){let r=`${s.person}|${et(s)}`,a=o.get(r);a||(a={key:r,person:s.person,lat:s.lat,lon:s.lon,city:s.city,country:s.country,cc:s.cc,asn:s.asn,org:s.org,online:!1,ts:0,points:[]},o.set(r,a)),a.points.push(s),a.online||(a.online=s.online),a.ts=Math.max(a.ts,s.ts)}return[...o.values()]}draw(){if(!this.map||!this.data||!this.map.getSource("dl-arcs"))return;let e=this.data,o=this.groups(_o(e,this.range)),s=e.person||e.device?null:e.geo.home;for(let d of this.markers)d.remove();this.markers=[];let r=e.person||e.device?null:Gi(o,s),a=o.map(d=>({g:d,at:r?.get(d.key)??[d.lon,d.lat]}));if(this.slots=[],this.map.getSource("dl-areas").setData({type:"FeatureCollection",features:a.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:s?a.map(({g:d,at:c})=>({type:"Feature",properties:{online:d.online,person:d.person,key:d.key},geometry:{type:"LineString",coordinates:ir([s.lon,s.lat],c)}})):[]}),s){let d=t("span",{class:"dl-mk-host"});d.innerHTML=`${_t("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")}${s.city?` · ${s.city}`:""}${s.org?` · ${s.org}`:""}`},[d,t("span",{class:"dl-mk-label chip"},s.city||_("Home"))]);c.addEventListener("mouseenter",()=>this.showMerged(s.city)),c.addEventListener("mouseleave",()=>this.focus(this.focused)),c.addEventListener("click",()=>this.zoomToMerged()),this.add(c,[s.lon,s.lat],!0)}let i=new Map(e.device?Co(e,this.range).map(d=>[et(d),d.n]):[]);this.people=[],this.places.clear();for(let{g:d,at:c}of a){let p=d.points.length,u=e.people.find(h=>h.id===d.person);if(e.person){let h=e.device?this.deviceMarker(d,c,u,i.get(et(d))??0):this.placeMarker(d,c,u);this.add(h,c);continue}let v=d.points.map(h=>u?.devices.find(S=>S.id===h.device)?.kind??"other"),M=t("span",{class:"dl-mk-badge"});M.innerHTML=p<=2?v.map(h=>_t(h,"dl-mk-badge-ic")).join(""):String(p);let x=t("button",{type:"button",class:`dl-mk${d.online?" online":""}`,"aria-label":d.city?m(N_(p,"%s: %s device in %s","%s: %s devices in %s"),u?.name??_("Someone"),V(p),d.city):m(N_(p,"%s: %s device in an unknown city","%s: %s devices in an unknown city"),u?.name??_("Someone"),V(p))},[t("span",{class:"dl-mk-av"},[Oe(u?.name??"?"),M]),t("span",{class:"dl-mk-label below"},d.city||d.cc||"?")]);x.addEventListener("mouseenter",()=>this.focus(d.person)),x.addEventListener("mouseleave",()=>this.focus(null)),this.people.push({el:x,person:d.person}),x.addEventListener("click",h=>{h.stopPropagation(),this.openPopup(d,c,x)}),this.add(x,c,!1,u?.name??_("Someone"),`${d.city||d.cc||"?"} · ${d.online?_("now"):pe(d.ts,e.now)}`,d.key,d)}this.declutter();let l=a.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,s&&!a.length){let c={center:[s.lon,s.lat],zoom:12};d?this.glide(12,()=>this.map.flyTo({...c,duration:1200})):this.map.jumpTo(c)}else{let c=a.map(p=>p.at);s&&(c.length===0||this.range!=="online"||a.some(p=>p.g.online))&&c.push([s.lon,s.lat]),this.fit(c,d)}}this.status.textContent=a.length||s?"":_("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,o,s=!1,r,a,i,l){i&&this.foldedKeys.has(i)&&e.classList.add("merged"),i&&this.piledKeys.has(i)&&e.classList.add("piled"),e.dataset.key=i??"",e.classList.add("dl-mk-new"),requestAnimationFrame(()=>requestAnimationFrame(()=>e.classList.remove("dl-mk-new")));let d=new this.gl.Marker({element:e}).setLngLat(o).addTo(this.map);this.markers.push(d),this.slots.push({marker:d,el:e,at:o,fixed:s,who:r,where:a,g:l})}declutter(){if(!this.map)return;let e=this.map.getZoom();this.el.classList.toggle("dl-lod-far",e=ar&&e{let l=this.map.project(i.at),d=i.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:i.fixed}}),s=o.filter(i=>i.fixed);this.merged=[],this.foldedKeys.clear();let r=this.targetZoom==null?1:Math.min(1,2**(this.targetZoom-this.map.getZoom()));o.forEach((i,l)=>{if(i.fixed)return;let d=this.slots[l],c=d.el.classList.contains("merged")?12:6,p=s.find(u=>Math.hypot(u.x-i.x,u.y-i.y)*r{let c=this.slots[d];!c||c.fixed||(o[d].fixed&&([i,l]=[0,0]),c.marker.setOffset([i,l]),Fi(c.el,i,l))})}closePopup(e=!1){let o=this.popup;if(!o||o.card.classList.contains("leaving"))return;o.card.classList.add("leaving"),setTimeout(()=>{this.popup===o&&this.dropCard()},140);let s=this.before;if(this.before=null,!s)return;let r=()=>this.map?.flyTo({...s,duration:800});if(!e)return r();let a=!1,i=()=>{a||(a=!0,window.removeEventListener("pointerup",i,!0),window.removeEventListener("pointercancel",i,!0),setTimeout(r,0))};window.addEventListener("pointerup",i,!0),window.addEventListener("pointercancel",i,!0),setTimeout(i,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",{},e?m(_("Near %s"),e):_("Near the server")),` · ${_("click to zoom in")}`]),...this.merged.map(o=>t("div",{class:"dl-map-card-row"},[t("span",{},o.who),t("span",{class:"dl-faint"},o.where)]))]),this.card.classList.add("on"))}paintDock(){let e=this.dock;if(!e)return;let o=this.merged.map(r=>`${r.key}:${r.online?1:0}`).join("|");if(o===this.dockKey)return;this.dockKey=o,e.parentElement?.classList.toggle("docked",this.merged.length>0);let s=this.slots.find(r=>r.fixed).at;this.merged.length&&dr(e,this.merged,this.faceActions(()=>[s]),this.dockQuiet),this.dockQuiet=!1}faceActions(e){return{click:(o,s)=>this.openFace(o,s,e()),hover:o=>this.focus(o?.g?.person??null)}}pileUp(e){let o=new Set;if(!this.data?.person&&!this.data?.device){let s=e.flatMap((l,d)=>!l.fixed&&this.slots[d].el.querySelector(":scope > .dl-mk-av")?[d]:[]),r=new Map(s.map(l=>[l,l])),a=l=>r.get(l)===l?l:a(r.get(l));for(let l of s)for(let d of s){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[h]),c=d.map(lr),p=c.map(h=>h.key).sort().join(",");o.add(p);let u=[d.reduce((h,S)=>h+S.at[0],0)/d.length,d.reduce((h,S)=>h+S.at[1],0)/d.length],v=this.piles.get(p);if(!v){let h=t("span",{class:"dl-mk-pile-box"}),S=[...new Set(d.map($=>$.g?.city||$.g?.cc||"?"))],z=t("div",{class:"dl-mk-pile"},[h,t("span",{class:"dl-mk-label below"},S.length===1?S[0]:W(d.length,"%s person","%s people"))]);v={marker:new this.gl.Marker({element:z}).setLngLat(u).addTo(this.map),el:z,box:h,faces:c},z.addEventListener("mouseleave",()=>this.focus(this.focused));let E=v;z.addEventListener("click",$=>{$.stopPropagation(),this.zoomInTo(E.faces.map(b=>b.at),!1)}),this.piles.set(p,v)}v.faces=c;let M=v;dr(v.box,c,this.faceActions(()=>M.faces.map(h=>h.at)));for(let h of l)this.slots[h].el.classList.add("piled"),Object.assign(e[h],{r:0,fixed:!0});let x=this.map.project(u);e.push({x:x.x,y:x.y,r:(v.el.offsetWidth||60)/2+3,fixed:!0})}}this.piledKeys=new Set(this.slots.filter(s=>s.el.classList.contains("piled")).map(s=>s.el.dataset.key??"")),this.slots.forEach((s,r)=>{(!e[r].fixed||s.fixed||s.el.classList.contains("merged"))&&s.el.classList.remove("piled")});for(let[s,r]of this.piles)o.has(s)||(this.piles.delete(s),r.el.classList.add("out"),setTimeout(()=>r.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,o,s){if(!e.g)return;if(s.every(a=>Tn(a,e.at)<1))return this.openPopup(e.g,e.at,o);let r=()=>{let a=this.slots.find(i=>i.el.dataset.key===e.key);a?.g&&!a.el.classList.contains("merged")&&!a.el.classList.contains("piled")&&this.openPopup(a.g,a.at,a.el)};this.zoomInTo(this.nearby(e.at),!0)?this.map.once("moveend",r):r()}nearby(e){return[e,...this.slots.filter(o=>!o.fixed&&o.at!==e&&Tn(o.at,e)<=rr).map(o=>o.at)]}zoomInTo(e,o){let s=new this.gl.LngLatBounds;for(let p of e)s.extend(p);let r=e.some(p=>e.some(u=>Tn(p,u)>rr)),a=this.map.cameraForBounds(s,{padding:50,maxZoom:r?12:Bi}),i=this.map.getZoom(),l=e.map(p=>this.map.project(p)),d=0;l.forEach((p,u)=>l.slice(u+1).forEach(v=>{let M=Math.hypot(p.x-v.x,p.y-v.y),x=i+Math.log2(Oi/Math.max(M,1e-6));x<=12&&(d=Math.max(d,x))}));let c=Math.min(12,Math.max(a?.zoom??0,d));return c<=i+.05?!1:(o&&!this.before&&(this.before={center:this.map.getCenter().toArray(),zoom:i}),this.map.flyTo({center:a?.center??s.getCenter(),zoom:c,duration:800}),!0)}placeMarker(e,o,s){let r=this.data.now,a=[...e.points].sort((u,v)=>Number(v.online)-Number(u.online)||v.ts-u.ts)[0],i=s?.devices.find(u=>u.id===a.device)?.kind??"other",l=e.points.length,d=t("span",{class:"dl-mk-tile"});d.innerHTML=_t(i,"dl-mk-tile-ic")+(l>1?`${l}`:"");let c=e.online?_("now"):pe(e.ts,r),p=t("button",{type:"button",class:`dl-mk place${e.online?" online":""}`,style:e.online?null:`--dl-mk-fade:${Math.max(.4,1-.6*(r-e.ts)/(30*86400)).toFixed(2)}`,"aria-label":e.city?m(N_(l,"%s device in %s, %s","%s devices in %s, %s"),V(l),e.city,c):m(N_(l,"%s device in an unknown city, %s","%s devices in an unknown city, %s"),V(l),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,o,p)}),p}deviceMarker(e,o,s,r){let a=s?.devices.find(p=>p.id===e.points[0].device)?.kind??"other",i=t("span",{class:"dl-mk-tile"}),l=t("span",{class:"dl-mk-label below"}),d=t("button",{type:"button",class:"dl-mk place step"},[i,l]);d.addEventListener("click",p=>{p.stopPropagation(),this.openPopup(e,o,d)});let c=et(e);return this.places.set(c,{el:d,tile:i,label:l,when:null,g:e,n:r,kind:a}),this.paintPlace(c,!1),d}paintPlace(e,o){let s=this.places.get(e);if(!s)return;let r=this.replaying,a=r?r.active===e:s.g.online,i=s.el.classList.contains("online"),l=s.g.city||s.g.cc||"?";s.el.classList.toggle("online",a),s.el.classList.toggle("faded",!!r&&!a),s.tile.classList.toggle("sm",!a),a||!s.n?s.tile.innerHTML=_t(s.kind,"dl-mk-tile-ic"):s.tile.textContent=String(s.n),s.when=null,a?(s.when=t("span",{class:`dl-mk-when${r?" inline":""}`},r?r.when:_("now")),s.label.replaceChildren(l,r?" · ":"",s.when)):s.label.replaceChildren(`${l} · ${s.g.online?_("now"):pe(s.g.ts,this.data.now)}`);let d=a?r?r.when:_("now"):s.g.online?_("now"):pe(s.g.ts,this.data.now);s.el.setAttribute("aria-label",`${s.n?`${s.n}: `:""}${s.g.city||_("an unknown city")}, ${d}`),o&&a&&!i&&(s.el.classList.remove("arrive"),s.el.offsetWidth,s.el.classList.add("arrive"),setTimeout(()=>s.el.classList.remove("arrive"),500))}replay(e,o=!0){let s=this.replaying;if(this.replaying=e,s&&e&&s.active===e.active){let r=e.active?this.places.get(e.active):null;r?.when&&(r.when.textContent=e.when);return}for(let r of this.places.keys())r!==e?.active&&this.paintPlace(r,o);e?.active&&this.paintPlace(e.active,o),this.declutter(),setTimeout(()=>this.declutter(),320)}hoverPlace(e){for(let[o,s]of this.places)s.el.classList.toggle("hl",o===e)}band(e,o){if(this.bandDots=[],this.map&&e&&o){let s=ir(e,o),r=s.map(c=>this.map.project(c)),a=[0];for(let c=1;ca[d]?(p-a[d])/(a[d+1]-a[d]):0,v=[s[d][0]+(s[d+1][0]-s[d][0])*u,s[d][1]+(s[d+1][1]-s[d][1])*u];this.bandDots.push({type:"Feature",properties:{pos:c/l},geometry:{type:"Point",coordinates:v}})}}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",Xs(e))}focus(e){this.focused=e;for(let i of this.people)i.el.classList.toggle("dim",!!e&&i.person!==e),i.el.classList.toggle("hl",i.person===e);let o=e?["case",["==",["get","person"],e],.85,.15]:.85;for(let i of["dl-arc-live","dl-arc-recent"])this.map?.getLayer(i)&&this.map.setPaintProperty(i,"line-opacity",o);if(this.card.classList.toggle("on",!!e),!e||!this.data)return;let s=this.data,r=s.people.find(i=>i.id===e),a=_o(s,this.range).filter(i=>i.person===e).sort((i,l)=>Number(l.online)-Number(i.online)||l.ts-i.ts);dom.content(this.card,[t("div",{class:"dl-map-card-head"},[t("b",{},r?.name??e),` · ${W(a.length,"%s device","%s devices")}`]),...a.map(i=>t("div",{class:"dl-map-card-row"},[t("span",{},r?.devices.find(l=>l.id===i.device)?.name??_("Device")),t("span",{class:"dl-faint"},`${i.city||i.cc||"?"} · ${i.online?_("now"):pe(i.ts,s.now)}`)]))])}fit(e,o=!1){if(!e.length)return;let s=(p,u)=>{let v=Math.PI/180,M=(u[1]-p[1])*v,x=(u[0]-p[0])*v,h=Math.sin(M/2)**2+Math.cos(p[1]*v)*Math.cos(u[1]*v)*Math.sin(x/2)**2;return 12742*Math.asin(Math.sqrt(h))},r=[e.reduce((p,u)=>p+u[0],0)/e.length,e.reduce((p,u)=>p+u[1],0)/e.length],a=e;if(e.length>=5){let p=[...e].sort((u,v)=>s(r,u)-s(r,v));a=p.slice(0,Math.ceil(p.length*.9))}let i=new this.gl.LngLatBounds(a[0],a[0]);a.forEach(p=>i.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};o?this.glide(this.map.cameraForBounds(i,c)?.zoom??null,()=>this.map.fitBounds(i,{...c,duration:1200})):this.map.fitBounds(i,{...c,duration:0})}glide(e,o){this.targetZoom=e,this.declutter(),this.map.once("moveend",()=>{this.targetZoom=null,this.declutter()}),o()}openPopup(e,o,s){let r=this.data,a=[e.city,e.cc||e.country].filter(Boolean).join(", "),i=[...new Set(e.points.map(b=>b.person))],l=i.length===1?r.people.find(b=>b.id===i[0])?.name:void 0,d=e.points.sort((b,k)=>Number(k.online)-Number(b.online)||k.ts-b.ts).map(b=>{let k=r.people.find(I=>I.id===b.person),y=k?.devices.find(I=>I.id===b.device);return t("button",{type:"button",class:"dl-pop-row",click:()=>this.cb.openDevice(b.person,b.device)},[t("span",{class:`dl-pop-dot${b.online?" on":""}`}),t("span",{class:"dl-pop-name"},[t("b",{},k?.name??b.person),` · ${y?.name??_("device")}`]),t("span",{class:"dl-faint dl-nowrap"},b.online?_("now"):pe(b.ts,r.now))])}),c=t("div",{class:"dl-pop"},[t("div",{class:"dl-pop-head"},[t("span",{class:"dl-pop-net"},g("globe")),t("div",{class:"dl-stack"},[t("strong",{},e.org||_("Unknown network")),t("span",{class:"dl-faint"},[e.asn?`AS${e.asn} · `:"",a?`${a} · ${_("approximate")}`:_("approximate location")])])]),t("div",{class:"dl-pop-list"},d),i.length===1?t("div",{class:"dl-pop-actions"},[t("button",{type:"button",class:"cbi-button cbi-button-positive important",click:()=>this.cb.openPerson(i[0])},l?m(_("Open %s"),l):_("Open person"))]):""]);this.zoomInTo(this.nearby(o),!0),this.dropCard();let p=t("div",{class:"dl-root dl-popcard",role:"dialog"},[t("span",{class:"dl-popcard-tip"}),c]);document.body.appendChild(p);let u=this.el,v=s?.querySelector(".dl-mk-av, .dl-mk-tile")??s??null,M=()=>{if(!v)return;let b=v.getBoundingClientRect(),k=u.getBoundingClientRect(),y=b.left+b.width/2,I=b.top+b.height/2;p.classList.toggle("away",yk.right||Ik.bottom);let w=p.offsetWidth,f=p.offsetHeight,T=b.top-f-12>=8||b.top>window.innerHeight-b.bottom,C=Math.min(Math.max(8,y-w/2),window.innerWidth-w-8);p.classList.toggle("above",T),p.classList.toggle("below",!T),p.style.left=`${C}px`,p.style.top=`${T?b.top-f-12:b.bottom+12}px`,p.style.setProperty("--tip-x",`${y-C}px`)},x=b=>{b.target?.closest(".dl-popcard, .maplibregl-marker")||this.closePopup(!0)},h=b=>{b.key==="Escape"&&this.closePopup()},S=b=>{b.target instanceof Element&&b.target.closest(".dl-popcard")||this.closePopup()},z=()=>this.closePopup();this.map.on("move",M),window.addEventListener("scroll",S,{capture:!0,passive:!0}),window.addEventListener("resize",M),document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",h);let E=Ee(z);window.addEventListener("pagehide",z),this.popup={card:p,off:()=>{this.map?.off("move",M),window.removeEventListener("scroll",S,!0),window.removeEventListener("resize",M),document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",h),E(),window.removeEventListener("pagehide",z)}};let $=window.setInterval(()=>{if(this.popup?.card!==p)return clearInterval($);(!u.isConnected||!u.getClientRects().length)&&this.dropCard()},400);M()}};function Wi(n,e=6){let o=n.map(s=>({x:s.x,y:s.y}));for(let s=0;s<16;s++){let r=!1;for(let a=0;a[s.x-n[r].x,s.y-n[r].y])}function Gi(n,e){let o=new Map,s=e?[[e.lon,e.lat]]:[],r=a=>s.some(i=>Tn(a,i)<1.3);for(let a of[...n].sort((i,l)=>i.key>>12)/1048575),d=(i&4095)/4096*2*Math.PI,c=[a.lon,a.lat];for(let p=0;p<24;p++){let u=d+p*2.39996,v=Math.min(8,l+p*.25);if(c=[a.lon+v*Math.sin(u)/(111.32*Math.cos(a.lat*Math.PI/180)),a.lat+v*Math.cos(u)/111.32],!r(c))break}s.push(c),o.set(a.key,c)}return o}function qi(n){let e=2166136261;for(let o=0;o>>0}function lr(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 dr(n,e,o,s=!1){let r=e.length>3,a=()=>[...n.children].filter(x=>!x.classList.contains("out")),i=new Map(a().map(x=>[x,x.getBoundingClientRect().left])),l=n.getBoundingClientRect().width,d=new Map;n.querySelectorAll(".dl-mk-face:not(.out)").forEach(x=>d.set(x.dataset.key??"",x));let c=n.querySelector(".dl-mk-more:not(.out)"),p=x=>{Object.assign(x.style,{position:"absolute",left:`${x.offsetLeft}px`,top:`${x.offsetTop}px`,transform:""}),x.classList.add("out"),setTimeout(()=>x.remove(),200)},u=[];for(let x of e.slice(0,r?2:3)){let h=d.get(x.key);if(d.delete(x.key),!h){let E=t("button",{type:"button",class:`dl-mk-face${s?"":" in"}`,"data-key":x.key},[t("span",{class:"dl-mk-av"},Oe(x.who)),t("span",{class:"dl-mk-badge"})]);E.addEventListener("animationend",()=>E.classList.remove("in"),{once:!0}),h=E}let S=h,z=S.querySelector(".dl-mk-badge");z.innerHTML!==x.badge&&(z.innerHTML=x.badge),S.title=`${x.who} · ${x.where}`,S.setAttribute("aria-label",`${x.who}, ${x.where}`),S.classList.toggle("on",x.online),S.onclick=E=>{E.stopPropagation(),o.click(x,S)},S.onmouseenter=()=>o.hover(x),S.onmouseleave=()=>o.hover(null),u.push(S)}for(let x of d.values())p(x);if(r){if(!c){c=t("span",{class:`dl-mk-more${s?"":" in"}`});let x=c;x.addEventListener("animationend",()=>x.classList.remove("in"),{once:!0})}c.textContent=`+${e.length-2}`,u.push(c)}else c&&p(c);let v=null;for(let x of u)(v?v.nextElementSibling:n.firstElementChild)!==x&&(v?v.after(x):n.prepend(x)),v=x;for(let x of u){let h=i.get(x);if(h==null)continue;let S=h-x.getBoundingClientRect().left;Math.abs(S)<.5||(x.style.transition="none",x.style.transform=`translateX(${S}px)`,x.offsetWidth,x.style.transition="",x.style.transform="")}n.style.width="";let M=n.getBoundingClientRect().width;if(l&&Math.abs(M-l)>.5){n.style.width=`${l}px`,n.offsetWidth,n.style.width=`${M}px`;let x=()=>{n.style.width="",n.removeEventListener("transitionend",x)};n.addEventListener("transitionend",x),setTimeout(x,400)}}function Tn(n,e){let o=Math.PI/180,s=Math.sin((e[1]-n[1])*o/2)**2+Math.cos(n[1]*o)*Math.cos(e[1]*o)*Math.sin((e[0]-n[0])*o/2)**2;return 12742*Math.asin(Math.min(1,Math.sqrt(s)))}function Fi(n,e,o){let s=n.querySelector(":scope > .dl-mk-ptr"),r=Math.hypot(e,o);if(r<1){s?.remove();return}s||(s=t("span",{class:"dl-mk-ptr"},[t("i",{class:"line"}),t("i",{class:"spot"})]),n.prepend(s));let a=s.firstElementChild,i=s.lastElementChild;a.style.width=`${r}px`,a.style.transform=`rotate(${Math.atan2(-o,-e)}rad)`,i.style.transform=`translate(${-e}px, ${-o}px)`}function It(n,e,o=!0){let s=[["online",_("Online now")],["24h",_("24h")],["7d",_("7 days")],["30d",_("30 days")]],r=t("div",{class:"dl-seg",role:"tablist"});for(let[a,i]of s)a==="online"&&!o||r.appendChild(t("button",{type:"button",role:"tab",class:a===n?"on":"","data-v":a,click:()=>{r.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.v===a)),e(a)}},i));return r}var cr={"24h":86400,"7d":7*86400,"30d":30*86400},Lo=(n,e)=>`${(n/e*100).toFixed(3)}%`,Sn=class{constructor(e,o,s){this.map=e;this.range=o;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")},g("x"));this.reduced=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;this.data=s,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 o={...this.pending??this.data,...e};if(this.on){this.pending=o;return}this.data=o,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,o=cr[this.range],s=e.now-o,r=Gs(Ws(e.events??[],e.device.id,e.now,e.device.online,e.device.handshake),e.geo.points,e.device.id,s),a=qs(r);this.st=Fs(r);let i=Co(this.mapData(),this.range),l=r.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,i.length?[...i.map(d=>{let c=et(d),p=a.get(c),u=l?t("div",{class:`dl-dplace-strip${d.online?" live":""}`},r.filter(M=>M.key===c).map(M=>t("i",{style:`left:${Lo(M.from-s,o)};width:${Lo(M.to-M.from,o)}`}))):"",v=t("div",{class:"dl-dplace-row"},[t("span",{class:`dl-dplace-n${d.online?" live":""}`},d.online?g(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?` · ${m(_("%s%% of the time"),p>0&&p<.005?"<1":Math.round(p*100))}`:""])]),t("span",{class:d.online?"dl-dplace-now":"dl-faint dl-nowrap"},d.online?_("now"):pe(d.ts,e.now)),u]);if(v.addEventListener("mouseenter",()=>this.map.hoverPlace(c)),v.addEventListener("mouseleave",()=>this.map.hoverPlace(null)),u){let M=x=>{let h=u.getBoundingClientRect();this.seek(s+o*Math.min(1,Math.max(0,(x.clientX-h.left)/h.width)))};u.addEventListener("pointerdown",x=>{u.setPointerCapture(x.pointerId),M(x)}),u.addEventListener("pointermove",x=>x.buttons&&M(x))}return this.rows.set(c,v),v}),l?t("div",{class:"dl-dplace-axis"},er(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,g(this.playing?"pause":"play")),this.play.title=this.playing?_("Pause","replay"):_("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}=Vs(this.st,this.reduced?400:wo),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(o));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=Js(this.st,this.steps,e),this.stepI=-1,this.show(!1),this.paintControls())}show(e){let o=Ys(this.st,this.steps,this.ms),s=this.st[o.step.k];if(o.step.kind==="move"){let i=this.st[o.step.k-1];o.i!==this.stepI&&(this.map.replay({active:null,when:""},e),this.map.band([i.point.lon,i.point.lat],[s.point.lon,s.point.lat]));let l=Zs(o.q);this.reduced||this.map.bandAt(l),(this.reduced?o.q>=.5:Qs(l))&&this.map.replay({active:s.key,when:Mn(o.t)},e)}else o.i!==this.stepI&&this.map.band(),this.map.replay({active:s.key,when:Mn(o.t)},e);this.stepI=o.i;let r=this.data,a=r.now-cr[this.range];this.el.classList.add("replay"),this.el.style.setProperty("--at",Lo(o.t-a,r.now-a));for(let[i,l]of this.rows)l.classList.toggle("cur",i===s.key);this.chip.textContent=`${tr(o.t,r.now)}, ${Mn(o.t)} · ${s.point.city||s.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 Bt(n){return`${L.url("admin/network/dawnline/server")}?${n?`server=${encodeURIComponent(n)}&`:""}section=people`}function ze(n,e){return`${L.url("admin/network/dawnline/person")}?id=${encodeURIComponent(n)}${e?`&device=${encodeURIComponent(e)}`:""}`}function Ki(n){return n?new Date(n*1e3).toLocaleString(le(),{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function Mo(n,e,o=!1){return t("div",{class:"dl-kvrow"},[t("span",{class:"dl-kvrow-k"},n),t("button",{type:"button",class:`dl-kvrow-v copy${o?" dl-mono":""}`,title:_("Copy"),click:()=>xe(e,m(_("%s copied"),n))},[t("span",{},e),g("copy")])])}function Pn(n,e){return t("div",{class:"dl-kvrow"},[t("span",{class:"dl-kvrow-k"},n),t("span",{class:"dl-kvrow-v"},e)])}var pr={connect:["ok","plug"],disconnect:["","plug"],roam:["","network"],device_added:["ok","plus"],device_removed:["","trash"],device_keys:["","reset"]};function Vi(n){let e=s=>t("span",{class:"dl-muted"},s),o=Ve(n)==="portal"?_("on the portal"):Ve(n)==="admin"?_("by you"):"";switch(n.type){case"connect":return[...n.detail?oe(_("Connected from %s"),e(n.detail)):[_("Connected")],n.where?e(` · ${n.where}`):""];case"disconnect":return[_("Went offline")];case"roam":return[_("Changed network"),e(` · ${n.detail??""}`)];case"device_added":return o?oe(_("Added %s"),e(o)):[_("Added")];case"device_removed":return o?oe(_("Removed %s"),e(o)):[_("Removed")];default:return o?oe(_("New keys %s"),e(o)):[_("New keys")]}}function Yi(n,e,o){let s=n.filter(r=>r.device===e&&pr[r.type]).reverse().slice(0,12);return s.length?t("div",{class:"dl-dev-log"},s.map(r=>{let[a,i]=pr[r.type],l=new Date(r.ts*1e3);return t("div",{class:`dl-dev-log-row${Ve(r)==="admin"?" dl-ev-by-admin":""}`},[Ve(r)==="admin"?t("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},g("admin")):t("span",{class:`dl-ev-tile ev ${a}`},g(i)),t("span",{class:"dl-row-main"},Vi(r)),t("span",{class:"dl-faint dl-nowrap",title:l.toLocaleString(le())},pe(r.ts,o))])})):t("div",{class:"dl-sub"},_("No activity yet."))}async function ur(n,e,o){let s=await H.status(1).catch(()=>null),r=s?.people.find(i=>i.id===n),a=r?.devices.find(i=>i.id===e);s&&r&&a&&Ye(r,a,{...o,geo:s.geo,now:s.now,today:We(s.series),core:Rt(s.servers,r.server)})}async function Ye(n,e,o){let s=await K(()=>H.deviceConfig(e.id));if(!s)return;let r=o.core??Ge(null),a=e,i=n,l=o.geo,d=o.now,c=o.today??Fe(new Date),p=await r.connectBlock(s,e.kind==="phone"||e.kind==="tablet"?"qr":"file"),u=t("div",{class:"dl-drawer-title"}),v=t("div",{}),M=t("div",{}),x=t("div",{},t("div",{class:"dl-sub"},_("Loading…"))),h=[],S=se=>{h=se.filter(j=>j.device===a.id),dom.content(x,Yi(se,a.id,d)),b?.update({events:se})},z=async(se=!1)=>{let j=o.events?.();if(j&&!se)return S(j);let J=await H.events(2e3,n.id).catch(()=>null);J&&S(J.events)},E="30d",$=null,b=null,k=()=>{dom.content(u,[t("span",{class:`dl-dcard-ic${a.online?" on":""}`},g(a.kind)),t("div",{class:"dl-stack"},[t("div",{class:"dl-title-row"},[t("h3",{},a.name),N([g("edit")],()=>w(),"neutral",{title:_("Rename"),class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),t("span",{class:"dl-sub"},`${i.name} · ${at(a.kind)}`)])]);let se=a.spark.map(([J,ie])=>J+ie),j=se.reduce((J,ie)=>J+ie,0);dom.content(v,t("div",{class:"dl-dstats"},[t("div",{class:"dl-dstats-cell wide"},[t("span",{class:"dl-metric-label"},_("Status")),pn(a,d,_("Waiting for the first connection"),i)]),t("div",{class:"dl-dstats-cell"},[t("span",{class:"dl-metric-label"},_("This month")),t("b",{},re(a.month[0]+a.month[1])),t("span",{class:"dl-sub dl-mono"},`↓ ${re(a.month[1])} ↑ ${re(a.month[0])}`)]),t("div",{class:"dl-dstats-cell"},[t("span",{class:"dl-metric-label"},_("Last 7 days")),t("b",{},re(j)),$s(se,120,22,c)])])),dom.content(M,t("div",{class:"dl-kv2"},[Mo(_("Tunnel address"),a.address),a.hostname&&i.access!=="internet"?Mo(_("Local address"),a.hostname):"",a.endpoint&&!l?.points.some(J=>J.device===a.id&&J.ip===a.endpoint)?Pn(_("Client IP"),a.endpoint):"",Pn(_("Total"),t("span",{class:"dl-kv-act"},[`↓ ${re(a.total[1])} · ↑ ${re(a.total[0])}`,t("button",{type:"button",class:"dl-linkbtn danger",click:()=>zt("device",a.id,a.name,()=>setTimeout(I,300))},_("Reset"))])),Pn(_("Added"),`${Ki(a.created)} · ${a.created_by==="portal"?_("from the portal"):_("by you")}`),s.amnezia.client_pub_key?Mo(_("Public key"),s.amnezia.client_pub_key):Pn(_("Public key"),"—")])),dom.content(f,[N([g(a.disabled?"play":"pause")," ",a.disabled?_("Enable"):_("Disable")],async()=>{await K(()=>H.deviceUpdate(a.id,void 0,!a.disabled),a.disabled?_("Device enabled"):_("Device disabled"))&&await I()},"neutral",a.disabled?{}:{class:"cbi-button cbi-button-neutral dl-btn-warn"}),N([g("key")," ",_("New keys")],async()=>{if(!await me(_("Generate new keys?"),_("The current configuration on this device stops working until it is imported again."),_("Generate"),!0))return;await K(()=>H.deviceRotate(a.id),_("New keys generated"))&&(o.refresh(),fe.close(),await ur(i.id,a.id,o))}),t("span",{class:"dl-spacer"}),N([g("trash")," ",_("Remove")],async()=>{await me(m(_("Remove %s?"),a.name),_("The device is disconnected immediately and its configuration stops working."),_("Remove"),!0)&&await K(()=>H.deviceDelete(a.id),_("Device removed"))&&(fe.close(),o.refresh())},"negative")])},y=async()=>{let se=await H.status(1).catch(()=>null),j=se?.people.find(ie=>ie.id===i.id),J=j?.devices.find(ie=>ie.id===a.id);!se||!j||!J||(i=j,a=J,l=se.geo,d=se.now,c=We(se.series),k(),b?.update({geo:se.geo,now:se.now,person:i,device:a}))},I=async()=>{await y(),o.refresh()},w=()=>{let se=t("input",{type:"text",class:"cbi-input-text",value:a.name,maxlength:48}),j=i.devices.filter(ie=>ie.id!==a.id).map(ie=>ie.name),J=Me(_("Name"),se,()=>Ne(se.value,j,_("Shown in the portal and in the app.")));de(m(_("Rename %s"),a.name),[J],[ue()," ",N(_("Save"),async()=>{let ie=J.help();if(ie.bad){q(ie.text,"warning");return}await K(()=>H.deviceUpdate(a.id,se.value,void 0),_("Renamed"))&&(ce(),await I())},"positive")]),setTimeout(()=>se.select(),50)},f=t("div",{class:"dl-drawer-actions"}),T=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},_("Connect","section"))]),a.config_stale?bt(_("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]),C=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:()=>Ze({people:[i]},h,"csv",a.id)},_("Export")),t("button",{type:"button",class:"dl-linkbtn danger",click:()=>lt(m(_("Clear %s's activity"),a.name),m(_("Removes events about %s."),a.name),{device:a.id},()=>{z(!0),o.refresh()})},_("Clear")),t("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},_("All activity"))])]),x]),D=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},t("h4",{},_("Details","section"))),M]),F="";if(l?.enabled){$=new dt({openPerson:j=>location.href=ze(j),openDevice:(j,J)=>location.href=ze(j,J)},E,220);let se=b=new Sn($,E,{geo:l,now:d??Date.now()/1e3,person:i,device:a,events:o.events?.()??null});F=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},_("Locations")),It(E,j=>{E=j,se.setRange(j)},!1)]),t("div",{class:"dl-dmap"},[$.el,se.controls]),se.el])}let Y=!a.handshake||a.config_stale,ee=t("div",{class:"dl-stack gap16"},Y?[v,T,D,F,C]:[v,D,F,C,T]);z();let B=()=>{y(),z()},Q=Ln(B),ne=window.setInterval(B,3e4),fe=os(u,ee,f,()=>{clearInterval(ne),Q(),b?.destroy(),$?.destroy()});k(),$&&b&&requestAnimationFrame(()=>b&&$?.mount(b.mapData()))}function mr(n,e,o,s){let r=s.core??Ge(null),a=()=>K(()=>H.deviceConfig(o.id)),i=[{label:_("Show QR code"),icon:g("qr"),run:async()=>{let l=await a();l&&de(`${o.name} · ${_("QR code")}`,t("div",{class:"dl-qr-pane"},[hn(r.qrText(l)),t("span",{class:"dl-sub"},go(l)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),ue(_("Close")))}},{label:r.file.label,icon:g("download"),run:async()=>{let l=await a();if(!l)return;let d=r.file.make(l);Ae(d.name,d.text,"application/octet-stream")}},r.appKey?{label:r.appKey.label,icon:g("copy"),run:async()=>{let l=await a();l&&xe(await r.appKey.make(l),_("Key copied"))}}:null,null,{label:_("Rename"),icon:g("edit"),run:()=>Ye(e,o,s)},{label:_("New keys"),icon:g("key"),run:async()=>{await me(_("Generate new keys?"),_("The current configuration on this device stops working until it is imported again."),_("Generate"),!0)&&await K(()=>H.deviceRotate(o.id),_("New keys generated"))&&s.refresh()}},{label:o.disabled?_("Enable"):_("Disable"),icon:g(o.disabled?"play":"pause"),warn:!o.disabled,run:async()=>{await K(()=>H.deviceUpdate(o.id,void 0,!o.disabled),o.disabled?_("Device enabled"):_("Device disabled"))&&s.refresh()}},{label:_("Delete"),icon:g("trash"),danger:!0,run:async()=>{await me(m(_("Remove %s?"),o.name),_("The device is disconnected immediately and its configuration stops working."),_("Remove"),!0)&&await K(()=>H.deviceDelete(o.id),_("Device removed"))&&s.refresh()}}];Te(n,i)}function ct(n,e){let o=n.devices.map(c=>c.name),s=c=>{let p=at(c),u=1,v=p;for(;o.some(M=>M.toLowerCase()===v.toLowerCase());)v=`${p} ${++u}`;return v},r="phone",a=t("input",{type:"text",class:"cbi-input-text",placeholder:s(r),maxlength:48}),i=Me(_("Name"),a,()=>a.value.trim()?Ne(a.value,o,_("Shown in the portal and in the app.")):{text:m(_("Named after its type: %s."),s(r)),bad:!1}),l=t("div",{class:"dl-kinds",role:"radiogroup","aria-label":_("Type")},Xo.map(c=>t("button",{type:"button",role:"radio",class:c===r?"on":"","aria-checked":c===r?"true":"false","data-kind":c,click:()=>{r=c,l.querySelectorAll("button").forEach(p=>{let u=p.dataset.kind===c;p.classList.toggle("on",u),p.setAttribute("aria-checked",u?"true":"false")}),a.placeholder=s(c),i.refresh()}},[g(c),t("span",{},at(c))]))),d=n.devices.length>=n.device_limit;de(m(_("Add a device for %s"),n.name),[d?t("p",{class:"dl-hint"},m(N_(n.device_limit,"%s already has %s of %s device. As admin you can still add one.","%s already has %s of %s devices. As admin you can still add one."),n.name,V(n.devices.length),V(n.device_limit))):"",t("div",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},_("Type")),l]),i],[ue()," ",N(_("Add device"),async()=>{let c=i.help();if(c.bad){q(c.text,"warning");return}let p=a.value.trim()||s(r),u=await K(()=>H.deviceCreate(n.id,p,r));u&&(ce(),q(m(_("%s added"),p),"success",3e3),e.refresh(),await ur(n.id,u.id,e))},"positive")]),setTimeout(()=>a.focus(),50)}var tt=1080,en=1512,Je=96,Ji="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",Zi="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",Xt=n=>n.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]);function Qi(n,e,o){let s=new URL(o),r=s.pathname.slice(1),a=m(_("Hi, %s"),n.name),i=Math.min(92,Math.floor((tt-2*Je)/(.58*a.length))),l=tt-2*Je,d=392,c=40,p=mn(o,2).replace("`${S}`;return``+u(Je+82,Je+42,36,"#a3a3a3",Xt(e))+u(Je,276,i,"#ffffff",Xt(a),'font-weight="600"')+u(Je,340,40,"#8a8a8a",Xt(m(_("Scan to connect to %s"),e)))+``+p+`${Xt(r)}`+u(tt/2,d+l+156,34,"#737373",Xt(s.host),'text-anchor="middle"')+""}async function Xi(n){let e=new Image;e.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`,await e.decode();let o=document.createElement("canvas");return o.width=tt,o.height=en,o.getContext("2d").drawImage(e,0,0,tt,en),new Promise((s,r)=>o.toBlob(a=>a?s(a):r(new Error(_("Could not draw the card"))),"image/png"))}async function hr(n){let e=await K(()=>H.personLinks(n));return e?e.link?{link:e.link,links:e.links??[]}:(q(_("The personal portal is off. Turn it on in Settings."),"warning"),null):null}async function $n(n){let e=await hr(n);e&&await xe(e.link,_("Personal link copied"))}async function tn(n,e,o={}){let s=n.link,r=n.links;if(s===void 0){let h=await hr(n.id);if(!h)return;s=h.link,r=h.links}if(!s){q(_("The personal portal is off. Turn it on in Settings."),"warning");return}let a=s,i=await K(()=>Xi(Qi(n,e,a)));if(!i)return;let l=new File([i],`${n.id}-invite.png`,{type:"image/png"}),d=URL.createObjectURL(i),c=navigator,p=!!c.canShare?.({files:[l]}),u=!p&&typeof c.share=="function"&&(c.canShare?.({url:a})??!0),v=()=>{URL.revokeObjectURL(d),ce()},M=async h=>{try{await c.share(h)}catch{}},x=p?N([g("link")," ",_("Share card")],()=>M({files:[l],title:m(_("Invite %s"),n.name)}),"positive"):u?N([g("link")," ",_("Share link")],()=>M({url:a,title:m(_("Invite %s"),n.name),text:_("Your personal VPN link")}),"positive"):N([g("download")," ",_("Download card")],()=>Ae(l.name,i),"positive");de(o.title??m(_("Invite %s"),n.name),t("div",{class:"dl-invite"},[t("img",{src:d,alt:m(_("Invite card for %s"),n.name)}),t("div",{class:"dl-invite-side"},[t("p",{class:"dl-muted"},o.lead??m(_("Send %s the card or the link. They open it, add their devices and connect - no account needed."),n.name)),t("button",{type:"button",class:"dl-invite-link",title:_("Copy link"),click:()=>xe(a,_("Personal link copied"))},[t("span",{},a.replace(/^https:\/\//,"")),g("copy")]),...(r??[]).filter(h=>h!==a).map(h=>t("button",{type:"button",class:"dl-invite-link alt",title:_("Copy this link"),click:()=>xe(h,_("Link copied"))},[t("span",{},h.replace(/^https?:\/\//,"")),t("span",{class:`dl-pill ${h.startsWith("http:")?"warn":""}`},h.startsWith("http:")?"HTTP":_("Also")),g("copy")])),t("ol",{class:"dl-invite-steps"},[t("li",{},oe(_("Install %s on the device"),t("b",{},"AmneziaVPN"))),t("li",{},_("Open the link or scan the code")),t("li",{},_("Add the device and connect"))]),t("div",{class:"dl-invite-actions"},[x,N([g("copy")," ",_("Copy link")],()=>xe(a,_("Personal link copied")))])])]),[t("button",{class:"cbi-button cbi-button-neutral",click:v},_("Done"))],"wide")}function nn(n,e){let o=n.servers.find(d=>d.id===e)??n.servers[0],s=n.people.filter(d=>d.server===o.id),r=new Set(s.map(d=>d.id)),a=s.flatMap(d=>d.devices),i=d=>s.reduce((c,p)=>{let u=d(p);return[c[0]+u[0],c[1]+u[1]]},[0,0]),l=o.series?.[o.series.length-1];return{...n,servers:[o],people:s,series:o.series??n.series,events:n.events.filter(d=>d.person?r.has(d.person):!0),geo:{...n.geo,points:n.geo.points.filter(d=>r.has(d.person))},totals:{people:s.length,devices:a.length,online:a.filter(d=>d.online).length,active:s.filter(d=>d.state==="active").length,today:l?[l.rx,l.tx]:[0,0],month:i(d=>d.month)}}}var fr=3,Eo=class{constructor(){this.n=0;this.shown=0}next(){return++this.n}take(e){return e{let v=e.next(),M=null;try{M=await n.fetch(u),o>=fr&&q(_("The router answers again."),"success",3e3),o=0}catch{return++o===fr&&q(_("The router is not answering: what you see may be out of date."),"warning",8e3),null}return M==null||!e.take(v)?null:(n.apply(M,p),M)},r=(p=!1)=>s(p,!1),a=()=>document.visibilityState==="visible",i=()=>a()&&(n.active?.()??!0)?s(!0,!1):Promise.resolve(null);poll.add(i,n.every);let l=n.live?Ln(()=>void(a()&&(n.active?.()??!0)&&s(!0,!0))):null,d=()=>{poll.remove(i),l?.(),c()},c=Ee(d);return{refresh:r,claim:()=>e.claim(),stop:d}}function Ot(n){let e=document.activeElement;return!!n&&!!e&&e!==document.body&&n.contains(e)}function De(n,e,o=!1){return o&&Ot(n)?!1:(dom.content(n,e),!0)}function gr(n,e){let o=n,s=[{v:"internet",ic:"globe",text:_("Browse the internet through your router. No access to devices at home.")},{v:"lan",ic:"home",text:_("Reach devices at home (NAS, printer, cameras). Internet stays on their own connection.")},{v:"both",ic:"shield",text:_("Home devices and the internet, all through your router.")}],r=t("div",{class:"dl-choices"},s.map(a=>t("button",{type:"button",class:`dl-choice${a.v===o?" selected":""}`,"data-v":a.v,click:()=>{o=a.v,r.querySelectorAll(".dl-choice").forEach(i=>i.classList.toggle("selected",i.dataset.v===a.v)),e?.(a.v)}},[t("span",{class:"dl-choice-title"},[g(a.ic),vt(a.v)]),t("span",{class:"dl-choice-text"},a.text)])));return{el:r,get:()=>o}}function To(n){try{return localStorage.getItem(n)}catch{return null}}function So(n,e){try{localStorage.setItem(n,e)}catch{}}function el(n){let e=n.devices.length,o=Math.max(1,n.device_limit,e),s=Math.min(160,o*22+(o-1)*3);return t("div",{class:"dl-slotbar",title:m(N_(n.device_limit,"%s of %s device","%s of %s devices"),e,n.device_limit)},[t("span",{class:"dl-slotbar-segs",style:`width: ${s}px`},Array.from({length:o},(r,a)=>t("i",{class:a>=n.device_limit?"over":an.state==="server_off"?n.paused:!["active","quota","expired"].includes(n.state),Po=n=>n.state==="server_off"?n.paused:n.state!=="active",br=n=>Po(n)?n.state==="server_off"?"paused":n.state:null;function tl(n,e){let o=st(n.expires,e);return n.state==="quota"||n.state==="expired"||rt(n,o)||!!n.quota_limit&&n.quota_used>=n.quota_limit*.9}function xr(n,e){return Mt(n&&so(n,e)>=0?n:e,1)}var wr=n=>n.people.map(e=>e.id).sort().join(" "),yr=!1,yt=class{constructor(){this.list=t("div",{class:"dl-plist",role:"list"});this.filter=["all","online","attention","paused"].find(e=>e===(new URLSearchParams(location.search).get("filter")??To("dl.people.filter")))??"all";this.sort=["seen","name","usage"].find(e=>e===To("dl.people.sort"))??"seen";this.query="";this.noFooter=!0;this.serverId=null;this.el=null}async load(){return H.status(30)}scope(e){return this.serverId?nn(e,this.serverId):e}embed(e,o){return this.serverId=o,this.render(e)}person(e){return this.st.people.find(o=>o.id===e)}get today(){return We(this.st.series)}deviceOpts(e){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:Rt(this.st.servers,e.server)}}take(e,o){let s=this.scope(e),r=wr(s)!==wr(this.st);this.st=s,r?this.rebuild():(this.paintCards(o),this.decorate(o))}async update(){await this.poller?.refresh()}async refresh(){this.poller?.claim();let e=await H.status(30).catch(()=>null);e&&(this.st=this.scope(e),this.rebuild())}rebuild(){let e=new Map;for(let s of Array.from(this.list.children))s.dataset.sid&&e.set(s.dataset.sid,s);let o=this.st.people.map(s=>{let r=e.get(s.id)??t("div",{class:"dl-card",role:"listitem","data-sid":s.id});return this.renderCard(r,s.id)});dom.content(this.list,o.length?o:t("div",{class:"dl-plist-none"},this.st.servers.length?_("No people yet. Add someone and send them their personal link."):_("Set up the server first, then add people."))),this.decorate()}paintCards(e=!1){for(let o of this.st.people){let s=this.card(o.id);s&&!(e&&Ot(s))&&this.renderCard(s,o.id)}}card(e){return this.list.querySelector(`[data-sid="${CSS.escape(e)}"]`)}render(e){let o=this.scope(e);this.st=o;let s=this,r=t("select",{class:"dl-select","aria-label":_("Sort"),change:d=>{s.sort=d.target.value,So("dl.people.sort",s.sort),s.decorate()}},[t("option",{value:"seen",selected:s.sort==="seen"?"selected":null},_("Last seen","sort")),t("option",{value:"name",selected:s.sort==="name"?"selected":null},_("Name","sort")),t("option",{value:"usage",selected:s.sort==="usage"?"selected":null},_("Usage","sort"))]),a=t("input",{type:"search",class:"cbi-input-text dl-people-find",placeholder:_("Find…"),"aria-label":_("Find a person or device"),hidden:o.people.length>8?null:"hidden",input:d=>{s.query=d.target.value.trim().toLowerCase(),s.decorate()}}),i=d=>{let c=d.target;d.key==="/"&&!a.hidden&&!["INPUT","TEXTAREA","SELECT"].includes(c?.tagName)&&!c?.isContentEditable&&(d.preventDefault(),a.focus())};document.addEventListener("keydown",i),Ee(()=>document.removeEventListener("keydown",i));let l=t("div",{class:"dl-root"},[s.serverId?"":t("div",{class:"dl-pagehead"},[t("div",{class:"dl-stack"},[t("h2",{class:"dl-h1"},_("People")),t("span",{class:"dl-muted dl-people-count"},this.countText())]),o.servers.length?N([g("plus"),` ${_("Add person")}`],()=>s.openCreate(),"add"):""]),o.servers.length?"":t("div",{class:"alert-message warning"},oe(_("No server yet. %s before adding people."),t("a",{href:L.url("admin/network/dawnline/server")},_("Run the setup wizard")))),t("div",{class:"dl-toolbar"},[t("div",{class:"dl-seg dl-people-tabs",role:"tablist"}),t("div",{class:"dl-toolbar-end"},[a,r,s.serverId?N([g("plus"),` ${_("Add person")}`],()=>s.openCreate(),"add"):""])]),this.list]);return this.el=l,this.rebuild(),this.poller??(this.poller=pt({fetch:()=>H.status(30),every:30,live:!0,active:()=>!!s.el?.isConnected,apply:(d,c)=>s.take(d,c)})),!yr&&new URLSearchParams(location.search).get("add")&&(yr=!0,setTimeout(()=>s.openCreate(),100)),Promise.resolve(l)}countText(){let e=this.st.totals;return[W(e.people,"%s person","%s people"),W(e.devices,"%s device","%s devices"),m(_("%s online"),V(e.online))].join(" · ")}decorate(e=!1){let o=this.el?.querySelector(".dl-people-count");o&&(o.textContent=this.countText());let s=this.st.people,r=this.today,a=h=>tl(h,r),i={all:s.length,online:s.filter(h=>h.online>0).length,attention:s.filter(a).length,paused:s.filter(h=>vr(h)).length},l=this.el?.querySelector(".dl-people-tabs");if(l&&!(e&&Ot(l))){let h={all:_("All"),online:_("Online"),attention:_("Needs attention"),paused:_("Paused")};dom.content(l,Object.keys(h).map(S=>t("button",{type:"button",role:"tab",class:S===this.filter?"on":"",click:()=>{this.filter=S,So("dl.people.filter",S),this.decorate()}},[h[S],t("b",{class:S==="attention"&&i[S]?"warn":""},String(i[S]))])))}let d=this.query,c=h=>[h.name,h.note??"",...h.devices.flatMap(S=>[S.name,S.address,S.hostname,S.endpoint])].join(" ").toLowerCase(),p=h=>!(this.filter==="online"&&!h.online||this.filter==="attention"&&!a(h)||this.filter==="paused"&&!vr(h)||d&&!c(h).includes(d)),u=h=>br(h)==="paused"?2:Po(h)?1:0,v=[...s].sort((h,S)=>u(h)-u(S)||(this.sort==="name"?h.name.localeCompare(S.name):this.sort==="usage"?S.month[0]+S.month[1]-(h.month[0]+h.month[1]):S.online-h.online||S.last_seen-h.last_seen)),M=0;for(let h of v){let S=this.card(h.id);if(!S)continue;this.list.appendChild(S),S.classList.toggle("dl-off",Po(h));let z=p(h);S.classList.toggle("dl-filtered",!z),z&&M++}let x=this.el?.querySelector(".dl-people-none")??null;s.length&&!M?(x??(x=t("div",{class:"dl-empty dl-people-none"},t("p",{},_("No one here right now.")))),x.previousElementSibling!==this.list&&this.list.after(x)):x?.remove()}async quick(e,o,s){await K(()=>H.personUpdate(e.id,o),s)&&await this.update()}renderCard(e,o){let s=this.person(o);if(!s)return dom.content(e,t("em",{},_("This person was just removed."))),e;let r=this.today,a=st(s.expires,r),i=Math.max(0,s.device_limit-s.devices.length),l=s.has_link??this.st.settings.portal_enabled,d=[],c=br(s);if(s.expires&&c!=="expired"){let x=rt(s,a),h=a!=null&&a<0;d.push(t("span",{class:`dl-pill-ic${h?" bad":x?" warn":""}`,title:m(_("Access ends %s"),$e(s.expires))},[g("calendar"),h?m(_("ended %s"),$e(s.expires)):x?dn(a):m(_("until %s"),$e(s.expires))]))}s.hours&&c!=="hours"&&d.push(t("span",{class:"dl-pill-ic",title:_("Allowed hours")},[g("clock"),s.hours.replace("-","–")]));let p=cn(s.devices).map(x=>t("button",{type:"button",class:`dl-chip${x.disabled?" disabled":""}${x.online?" live":""}`,title:[at(x.kind),x.address,x.online?m(_("online from %s"),x.endpoint):x.handshake?m(_("seen %s"),pe(x.handshake,this.st.now)):""].filter(Boolean).join(" · "),click:h=>{h.preventDefault(),Ye(s,x,this.deviceOpts(s))}},[g(x.kind),t("span",{class:"dl-chip-name"},x.name),!x.handshake&&!x.disabled?t("span",{class:"dl-chip-tag"},_("not set up")):""]));p.push(t("button",{type:"button",class:"dl-chip add",title:i>0?_("Add device"):_("Over the limit: admins can still add"),click:x=>{x.preventDefault(),ct(s,this.deviceOpts(s))}},[g("plus"),_("Add device")]));let u=[];s.expires&&rt(s,a)&&c!=="expired"&&u.push(t("button",{type:"button",class:"dl-fix",click:()=>this.quick(s,{expires:xr(s.expires,r)},_("Extended by 1 month"))},_("Extend 1 month")));let v=Pe("more",_("More"),x=>Te(x.currentTarget,[{label:_("Open"),icon:g("open"),run:()=>{location.href=ze(s.id)}},l?{label:_("Invite card"),icon:g("qr"),run:()=>tn(s,this.st.servers.find(h=>h.id===s.server)?.name??_("Home"))}:null,i>0?{label:_("Add device"),icon:g("plus"),run:()=>ct(s,this.deviceOpts(s))}:null,null,{label:s.paused?_("Resume"):_("Pause"),icon:g(s.paused?"play":"pause"),warn:!s.paused,run:()=>this.togglePause(s)},{label:_("Delete"),icon:g("trash"),danger:!0,run:()=>this.remove(s.id)}].filter((h,S,z)=>h||S>0&&z[S-1])),"neutral","dl-icon-only"),M=t("div",{class:"dl-pcard-actions"},[l?Pe("link",_("Copy link"),()=>$n(s.id),"neutral","dl-icon-only"):"",v]);return dom.content(e,t("div",{class:"dl-pcard"},[t("div",{class:"dl-pcard-main"},[t("div",{class:"dl-pcard-top"},[t("span",{class:`dl-avatar${s.online?" online":""}`},Oe(s.name)),t("div",{class:"dl-pcard-who"},[t("div",{class:"dl-card-head"},[t("a",{class:"dl-card-name",href:ze(s.id)},s.name),ns(s),...d]),el(s)])]),t("div",{class:"dl-chips"},p),u.length?t("div",{class:"dl-fixes"},u):""]),this.usageSide(s,M),c?this.stopStrip(s,c):""])),e}stopStrip(e,o){let s=this.today,r=Mt(`${s.slice(0,8)}01`,1),a=()=>this.quick(e,{bonus_gb:String((e.bonus_gb||0)+10)},_("+10 GB this month")),i={paused:["pause","warn",_("Paused"),_("Devices can’t connect until you resume"),["play",_("Resume"),()=>this.togglePause(e)]],quota:e.quota_period==="month"?["chart","bad",_("Data limit reached"),m(_("Paused until it resets on %s"),$e(r)),["plus",_("+10 GB this month"),a]]:["chart","bad",_("Data limit reached"),_("Paused until the limit is raised"),["edit",_("Change limit"),()=>location.href=ze(e.id)]],expired:["calendar","bad",m(_("Access ended %s"),$e(e.expires)),_("Devices can’t connect"),["calendar",_("Extend 1 month"),()=>this.quick(e,{expires:xr(e.expires,s)},_("Extended by 1 month"))]],hours:["clock","warn",_("Outside allowed hours"),m(_("Access %s (router time)"),e.hours.replace("-","–")),null],no_server:["alert","warn",_("No server"),_("Choose a server on their page"),null]},[l,d,c,p,u]=i[o];return t("div",{class:`dl-pstrip ${d}`},[t("span",{class:`dl-need-ic ${d}`},g(l)),t("span",{class:"dl-pstrip-text"},[t("b",{},c),t("span",{class:"dl-faint"},p)]),u?N([g(u[0]),` ${u[1]}`],u[2]):""])}usageSide(e,o){let s=e.quota_used||e.month[0]+e.month[1],r=e.quota_limit?Math.min(100,e.quota_used/e.quota_limit*100):0,a=e.devices.reduce((p,u)=>p+(u.spark[u.spark.length-1]??[0,0]).reduce((v,M)=>v+M),0),i=e.rate?.[e.rate.length-1],l=e.online&&i&&this.st.now-i[0]<180,d=t("div",{class:`dl-usebar${r>=100?" bad":r>=90?" warn":""}`});if(e.quota_limit){let p=t("i",{class:"fill"});p.style.width=`${r}%`,d.appendChild(p),we(d,()=>[t("div",{class:"dl-tip-title"},m(_("%s%% used"),V(r,1))),t("div",{class:"dl-muted"},`${m(_("%s of %s"),re(e.quota_used),re(e.quota_limit))} · ${m(_("%s left"),re(Math.max(0,e.quota_limit-e.quota_used)))}`),t("div",{class:"dl-faint"},e.quota_period==="total"?_("In total"):[_("This month"),e.bonus_gb?m(_("includes +%s GB extra"),V(e.bonus_gb)):""].filter(Boolean).join(" · "))])}else{let p=e.devices.map(u=>({d:u,v:u.month[0]+u.month[1]})).filter(u=>u.v>0).sort((u,v)=>v.v-u.v);p.forEach((u,v)=>{let M=t("i",{class:`c${Math.min(v,4)}`});M.style.flexGrow=String(u.v),d.appendChild(M)}),p.length&&we(d,()=>[t("div",{class:"dl-tip-title"},_("This month by device")),...p.map((u,v)=>t("div",{class:"dl-tip-row"},[t("span",{class:`dl-swatch c${Math.min(v,4)}`}),t("span",{},u.d.name),t("b",{},re(u.v))]))])}let c=e.quota_limit?m(_("%s left"),re(Math.max(0,e.quota_limit-e.quota_used))):_("no limit");return t("div",{class:"dl-pside"},[t("div",{class:"dl-pside-top"},[l?t("span",{class:"dl-pside-state live"},_("Online")):t("span",{class:"dl-pside-state"},e.online?_("Online"):e.last_seen?_("Offline"):_("Never connected")),o]),t("div",{class:"dl-use-num"},[t("b",{class:s?"":"dl-faint"},re(s)),t("span",{class:"dl-faint"},e.quota_limit?m(_("of %s"),re(e.quota_limit)):e.quota_period==="total"&&e.quota_gb?_("in total"):_("this month"))]),d,l?t("div",{class:"dl-use-live",title:_("Right now")},[`↓ ${qe(i[2])}`,t("span",{class:"dl-faint"},`↑ ${qe(i[1])}`)]):t("div",{class:"dl-faint dl-pside-foot"},a?`${m(_("today %s"),re(a))} · ${c}`:c)])}async togglePause(e){await K(()=>H.personPause(e.id,!e.paused),m(e.paused?_("%s resumed"):_("%s paused"),e.name))&&await this.refresh()}async remove(e){let o=this.person(e);await me(m(_("Remove %s?"),o?.name??e),W(o?.devices.length??0,"%s device is disconnected immediately and the personal link stops working. Usage history is kept in backups.","All %s devices are disconnected immediately and the personal link stops working. Usage history is kept in backups."),_("Remove"),!0)&&await K(()=>H.personDelete(e),_("Person removed"))&&await this.refresh()}openCreate(){let e=this.st;if(!e.servers.length){q(_("Set up the server first."),"warning");return}let o=t("input",{type:"text",class:"cbi-input-text",placeholder:_("e.g. Myata"),maxlength:48}),s=(()=>{try{return JSON.parse(To("dl.person.last")??"{}")}catch{return{}}})(),r=gr(s.access??"internet"),a=t("input",{type:"number",class:"cbi-input-text",min:1,max:32,value:e.settings.default_device_limit}),i=t("input",{type:"date",class:"cbi-input-text"}),l=t("input",{type:"number",class:"cbi-input-text",min:0,step:"any",placeholder:_("Unlimited"),value:s.quota??""}),d=(E,$)=>t("button",{type:"button",class:"cbi-button cbi-button-neutral",click:()=>{i.value=$?Mt(We(e.series),$):"",i.dispatchEvent(new Event("change"))}},E),c=e.servers[0],p=!this.serverId&&e.servers.length>1?t("select",{class:"cbi-input-select"},e.servers.map(E=>t("option",{value:E.id},E.name))):null,u=(E,$,b)=>t("div",{class:"cbi-value"},[t("label",{class:"cbi-value-title"},E),t("div",{class:"cbi-value-field"},[$,b?t("div",{class:"cbi-value-description"},b):""])]),v=We(e.series),M=Me(_("Name","person"),o,()=>Ne(o.value,[],_("Shown in their portal and apps."))),x=Me(_("Devices"),a,()=>vn(a.value)),h=Me(_("End date"),i,()=>vs(i.value,v,st,$e),t("div",{class:"dl-actions"},[i,d(_("1 month"),1),d(_("3 months"),3),d(_("1 year"),12),d(_("None","end date"),0)])),S=Me(_("Monthly data (GB)"),l,()=>bn(l.value));i.addEventListener("change",()=>h.refresh());let z=e.settings.portal_enabled;de(_("Add person"),[M,p?u(_("Server"),p):"",t("div",{class:"cbi-value dl-block"},[t("label",{class:"cbi-value-title"},_("Access")),t("div",{class:"cbi-value-field"},r.el)]),x,h,S],[ue()," ",N(z?_("Create and copy link"):_("Create"),async()=>{let E=je([M,x,h,S]);if(E){q(E,"warning");return}let $=await K(()=>H.personCreate(o.value.trim(),"",p?.value??c.id,r.get(),a.value.trim(),i.value,l.value.trim(),"month"));$&&(So("dl.person.last",JSON.stringify({access:r.get(),quota:l.value.trim()})),$.link&&await xe($.link,_("Personal link copied"),!0),this.showCreated($.id,o.value.trim(),$.link,e.servers.find(b=>b.id===(p?.value??c.id))?.name??c.name),await this.refresh())},"positive")]),setTimeout(()=>o.focus(),50)}showCreated(e,o,s,r){if(s){tn({id:e,name:o,link:s},r,{title:m(_("%s is ready"),o),lead:m(_("Send %s the card or the link. They open it, add their devices and connect - no account needed."),o)});return}let a=this.person(e);de(m(_("%s is ready"),o),[t("p",{},_("Created. Turn on the personal portal in Settings to get a link, or add devices for them here."))],[t("button",{class:"cbi-button cbi-button-neutral",click:ce},_("Done"))," ",t("a",{class:"cbi-button cbi-button-neutral",href:`${L.url("admin/network/dawnline/settings")}?section=portal`},_("Open Settings"))," ",a?N(_("Add device"),()=>{ce(),ct(a,this.deviceOpts(a))},"positive"):""])}};var Dn=["#3a83f7","#a78bfa","#f472b6","#f59e0b","#10b981","#22d3ee","#ef4444","#84cc16"],$o=n=>t("i",{class:"dl-circle-dot",style:`background:${Dn[n?.color??0]??Dn[0]}`}),ut=n=>n.access==="both"||n.access==="lan"&&!n.services?.length;function kr(n,e,o){let s=he(n?.name??e.name??"",{placeholder:_("NAS")}),r=he(n?.address??e.address??"",{placeholder:"192.168.1.10",class:"cbi-input-text dl-mono"}),a=he((n?.ports??e.ports??[]).join(", "),{placeholder:_("All ports, or e.g. 445, 5000"),class:"cbi-input-text dl-mono"}),i=Me(_("Name","circle or service"),s,()=>Ne(s.value,[],_("Shown to people who may reach it."))),l=Me(_("Address"),r,()=>bs(r.value)),d=Me(_("Ports"),a,()=>xs(a.value));de(n?m(_("Edit %s"),n.name):_("Add service"),[i,l,d],[ue()," ",N(_("Save"),async()=>{let c=je([i,l,d]);if(c){q(c,"warning");return}let p=a.value.split(/[ ,]+/).filter(Boolean);await K(()=>H.serviceSet(n?.id??"",s.value,r.value,p),_("Saved"))&&(ce(),o())},"positive")])}function nl(){let n=_("Web"),e=_("Printer");return{_smb:"SMB",_afpovertcp:"AFP",_http:n,_https:n,_ssh:"SSH",_sftp:"SFTP","_sftp-ssh":"SFTP",_ipp:e,_ipps:e,_printer:e,"_pdl-datastream":e,_airplay:"AirPlay",_raop:"AirPlay",_rfb:_("Screen sharing"),_googlecast:"Cast",_hap:"HomeKit",_rdp:_("Remote desktop"),_ftp:"FTP"}}function ol(n){let e=nl(),o=new Map;for(let s of n.services){let r=e[s.type.split(".")[0]];!r||!s.port||(o.get(r)??o.set(r,new Set).get(r)).add(String(s.port))}return o.size?[...o].map(([s,r])=>[s,[...r].sort((a,i)=>+a-+i)]):[[_("Web"),["80","443"]],["SMB",["445"]],["SSH",["22"]]]}function _r(n,e,o){let s=n,r=null,a=!1,i=null,l=new Set,d=t("div",{class:"dl-list"}),c=t("div",{class:"dl-stack gap8"},t("span",{class:"dl-sub"},_("Looking for devices at home…"))),p=()=>{let h=s.services;dom.content(d,h.length?h.map(S=>t("div",{class:"dl-row"},[g("home"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},S.name),t("span",{class:"dl-mono dl-faint"},`${S.address} · ${S.ports.length?m(_("ports %s"),S.ports.join(", ")):_("all ports")}`)]),N(_("Edit"),()=>kr(S,{},o)),N([g("trash")],async()=>{await me(m(_("Remove %s?"),S.name),_("People limited to this service lose access to it."),_("Remove"),!0)&&await K(()=>H.serviceDelete(S.id),_("Removed"))&&await o()},"neutral",{title:_("Remove"),"aria-label":m(_("Remove %s"),S.name)})])):[t("div",{class:"dl-row dl-muted"},_("No services yet: pick ports of a device below."))])};async function u(h,S){if(!l.has(h.address)){l.add(h.address),M();try{let z=s.services.find($=>$.address===h.address);(S===null?z&&await K(()=>H.serviceDelete(z.id),m(_("%s removed"),z.name)):await K(()=>H.serviceSet(z?.id??"",z?.name??(h.name||h.address),h.address,S),z?m(_("%s updated"),z.name):m(_("%s added"),h.name||h.address)))&&await o()}finally{l.delete(h.address),M()}}}function v(h){let S=s.services.find(k=>k.address===h.address),z=!!S&&!S.ports.length,E=new Set(S?.ports??[]),$=l.has(h.address),b=(k,y,I)=>Vt(k,y,I,{disabled:$?"disabled":null,"aria-busy":$?"true":null});return t("div",{class:"dl-row dl-host"},[g(h.services.some(k=>k.type.startsWith("_ipp")||k.type.startsWith("_printer"))?"file":"computer"),t("div",{class:"dl-host-body"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},h.name||h.address),t("span",{class:"dl-mono dl-faint"},h.address)]),t("div",{class:"dl-chips-row"},[b(_("All ports"),z,()=>u(h,z?null:[])),...ol(h).map(([k,y])=>{let I=!z&&y.every(w=>E.has(w));return b(`${k} ${y.join(", ")}`,I,()=>{let w=new Set(z?[]:E);for(let f of y)I?w.delete(f):w.add(f);u(h,w.size?[...w]:null)})})])])])}function M(){if(a)return dom.content(c,t("span",{class:"dl-sub"},_("Couldn't read the devices at home.")));if(!r)return;let h=r;if(!h.hosts.length)return dom.content(c,t("span",{class:"dl-sub"},_("No devices found in the home network right now.")));let S=t("details",{class:"dl-params",open:i??!s.services.length?"":null},[t("summary",{},[g("chevron"),t("span",{},_("Add from devices at home")),t("span",{class:"dl-pcount"},String(h.hosts.length))]),t("div",{class:"dl-params-body"},[t("span",{class:"dl-sub"},h.mdns?_("Ports they announce over Bonjour. Pick what to open, or all ports."):_("Devices that got an address from this router. Pick the ports to open, or all ports.")),t("div",{class:"dl-list"},h.hosts.map(v))])]);S.addEventListener("toggle",()=>i=S.open),dom.content(c,S)}return H.homeHosts(e).then(h=>{r=h,M()}).catch(()=>{a=!0,M()}),p(),{el:t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-iflead"},[t("div",{class:"dl-iflead-row"},[t("b",{},_("Home services")),N([g("plus")," ",_("Add service")],()=>kr(null,{},o))]),t("span",{class:"dl-sub"},_("Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers."))]),d,c]),update(h){s=h,p(),M()}}}function An(n,e,o,s){let r=new Set(n.circles.filter(h=>h.server===e).map(h=>h.color)),a=o?.color??Dn.findIndex((h,S)=>!r.has(S));a<0&&(a=0);let i=he(o?.name??"",{placeholder:_("Family")}),l=n.people.filter(h=>h.server===e).sort((h,S)=>h.name.localeCompare(S.name)),d=new Set(l.filter(h=>o&&h.circle===o.id).map(h=>h.id)),c=t("div",{class:"dl-swatches",role:"radiogroup","aria-label":_("Colour")}),p=()=>dom.content(c,Dn.map((h,S)=>t("button",{type:"button",role:"radio",class:`dl-swatch${S===a?" on":""}`,style:`--sw:${h}`,"aria-checked":S===a?"true":"false","aria-label":m(_("Colour %s"),S+1),click:()=>{a=S,p()}})));p();let u=t("div",{class:"dl-chips-row"},l.map(h=>{let S=h.circle&&h.circle!==o?.id?n.circles.find(z=>z.id===h.circle):void 0;return t("button",{type:"button",class:`dl-chipbtn${d.has(h.id)?" on":""}`,title:ut(h)?S?m(_("Now in %s"),S.name):"":m(_("%s has no home access: their devices aren't reachable anyway"),h.name),click:z=>{d.delete(h.id)||d.add(h.id),z.currentTarget.classList.toggle("on",d.has(h.id))}},[h.name,ut(h)?S?t("b",{},S.name):"":t("b",{},_("internet"))])})),v=(h,S)=>t("div",{class:"cbi-value"},[t("label",{class:"cbi-value-title"},h),t("div",{class:"cbi-value-field"},S)]),M=n.circles.filter(h=>h.server===e&&h.id!==o?.id).map(h=>h.name),x=Me(_("Name","circle or service"),i,()=>ms(i.value,M));de(o?m(_("Edit %s"),o.name):_("New circle"),[x,v(_("Colour"),c),v(_("People"),u),t("p",{class:"dl-sub"},_("Devices of people in one circle reach each other. A person is in one circle at a time."))],[o?N(_("Delete"),async()=>{await K(()=>H.circleDelete(o.id),m(_("%s deleted"),o.name))&&(ce(),s())},"negative"):"",t("span",{class:"dl-spacer"}),ue()," ",N(_("Save"),async()=>{let h=x.help();if(h.bad){q(h.text,"warning");return}await K(()=>H.circleSet(o?.id??"",e,i.value,a,[...d]),_("Saved"))&&(ce(),s())},"positive")],"dl-circle-modal")}function Cr(n,e,o){let s=n.circles.filter(r=>r.server===e);return t("div",{class:"dl-chips-row dl-circles"},[...s.map(r=>{let a=n.people.filter(i=>i.circle===r.id).map(i=>i.name);return t("button",{type:"button",class:"dl-chip",title:m(_("Edit %s"),r.name),click:()=>An(n,e,r,o)},[$o(r),t("b",{},r.name),t("span",{class:"dl-faint"},a.length?a.join(", "):_("nobody yet"))])}),t("button",{type:"button",class:"dl-chip add",title:_("New circle"),"aria-label":_("New circle"),click:()=>An(n,e,null,o)},g("plus"))])}function Do(n,e){let o=n.people.filter(p=>p.server===e.id),s=(p="")=>t("span",{class:"dl-yes"},[g("check"),p]),r=()=>t("span",{class:"dl-faint"},"—"),a=p=>{let u=new Set(p.map(M=>M.access==="lan"&&M.services?.length?"services":M.home_nets?.length?"some":"all"));u.size||u.add("all");let v={all:_("all networks"),some:_("their networks"),services:_("services")};return s([...u].map(M=>v[M]).join(" / "))},i=()=>e.mesh==="off"?r():e.mesh==="circles"?s(_("circle")):s(),l=e.lan_like?_("like home"):_("direct"),d=(p,u,v)=>t("tr",{},[t("td",{},[t("b",{},p),t("div",{class:"dl-sub"},W(u.length,"%s person","%s people"))]),...v.map(M=>t("td",{},M))]),c=p=>o.filter(u=>u.access===p);return t("section",{class:"dl-setsec"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},_("Who reaches what")),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},_("From the rules on this server"))]),t("div",{class:"dl-reach-wrap"},t("table",{class:"dl-table dl-reach"},[t("tr",{},["",_("Internet"),_("Home"),_("This router"),_("Each other")].map(p=>t("th",{},p))),d(_("Internet"),c("internet"),[s(l),r(),t("span",{class:"dl-faint"},"DNS"),r()]),d(_("Home"),c("lan"),[t("span",{class:"dl-faint"},_("their own")),a(c("lan")),s(),i()]),d(_("Both"),c("both"),[s(l),a(c("both")),s(),i()])])),t("p",{class:"dl-sub"},_("Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing."))])])}function Lr(n,e){let o=n.people.filter(c=>c.server===e.id).flatMap(c=>c.devices.map(p=>({id:p.id,label:`${c.name} · ${p.name}`}))).sort((c,p)=>c.label.localeCompare(p.label)),s="@addr",r=(c,p)=>{let u=t("select",{class:"cbi-input-select","aria-label":c},[...o.map(h=>t("option",{value:h.id,selected:h.id===p?"selected":null},h.label)),t("option",{value:s,selected:p===s?"selected":null},_("Address"))]),v=he("",{placeholder:c,class:"cbi-input-text dl-mono"}),M=t("div",{class:"dl-check-end"},[u,v]),x=()=>v.hidden=u.value!==s;return u.addEventListener("change",x),x(),{el:M,value:()=>u.value===s?v.value.trim():u.value}},a=r("10.0.1.11",o[0]?.id??s),i=r("10.0.1.20:445",s),l=t("div",{class:"dl-stack gap8"}),d=async()=>{let c=await K(()=>H.accessCheck(a.value(),i.value()));if(!c)return;let p=c.steps.findIndex(u=>!u.ok);dom.content(l,[t("div",{class:`dl-verdict ${c.ok?"ok":"bad"}`},[t("b",{},c.ok?_("Allowed"):_("Blocked")),t("span",{class:"dl-sub"},c.ok?_("Every step lets it through"):m(_("Stops at step %s of %s"),p+1,c.steps.length))]),t("ul",{class:"dl-checks"},c.steps.map(u=>t("li",{},[t("span",{class:`dl-check-icon ${u.ok?"ok":"error"}`},g(u.ok?"check":"x")),t("div",{class:"dl-check-body"},[t("div",{class:"dl-check-title"},u.title),u.detail?t("div",{class:"dl-check-detail"},u.detail):""])])))])};return t("section",{class:"dl-setsec"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},_("Check access")),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},_("Why something does or does not connect"))]),t("div",{class:"dl-check-form"},[a.el,t("span",{class:"dl-faint"},"→"),i.el,N(_("Check"),d)]),l])])}function Nn(n){return n==="app"?"Dawnline":n==="amneziawg"?"AmneziaWG":n==="packages"||n==="pkgs"?_("System packages"):void 0}function mt(n){return(n.startsWith("check")?n.slice(6)||"all":n).split(/[:@ ]/)[0]}function Hn(n){return mt(n.action==="check"?`check:${n.component??""}`:n.component??"")}function Mr(n){return n=Math.max(0,Math.floor(n)),`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function Er(n,e){return!n?.from&&!n?.to?e:n.from&&n.to&&n.from!==n.to?`${n.from} → ${n.to}`:n.to??n.from??e}function Tr(n,e){let o=n.check?.components??{},s=e==="all"?["app","amneziawg","packages"]:[e],r=[],a;for(let l of s){let d=o[l];if(d){if(d.error)return{tone:"warn",text:d.error};l==="packages"&&d.updates?r.push(W(d.updates,"%s system package","%s system packages")):l!=="packages"&&d.update&&d.installed&&d.latest&&(r.push(`${Nn(l)} ${d.latest}`),e!=="all"&&(a=d.latest))}}if(r.length)return{tone:"acc",text:m(_("Update available: %s"),r.join(", ")),update:a};let i=s.length===1?o[s[0]]:null;return i?.status==="dev"?{tone:"acc",text:m(_("Installed version is newer than the release (%s)"),i.latest)}:i?.note?{tone:"warn",text:i.note}:{tone:"ok",text:s.length>1?_("Everything is up to date"):_("Latest version is installed")}}function Sr(n,e,o,s){return e?n.id===e:o&&n.id===o?!1:n.state==="running"||s>0&&n.started>=s}var Ao=n=>new Promise(e=>setTimeout(e,n));async function on(n,e,o){let s=o?Hn(o):mt(n),r=o?o.action==="check":n.startsWith("check"),a=Date.now(),i=t("b",{},Nn(s)??(s==="all"?_("All components"):"Dawnline")),l=t("span",{class:"dl-pill dl-mono"},e.version??""),d=t("span",{class:"dl-pill info",hidden:!0}),c=t("span",{},"0:00"),p=t("pre",{class:"dl-log"},_("Operation started. Waiting for log output…")),u=t("div",{}),v=t("div",{class:"dl-op-actions"}),M=[],x=T=>dom.content(v,T),h=(T=!1)=>ue(_("Close"),T);de(e.title,t("div",{class:"dl-op"},[t("div",{class:"dl-op-head"},[i,e.version?l:"",d,t("span",{class:"dl-spacer"}),t("span",{class:"dl-faint dl-op-timer"},[g("clock"),c])]),t("div",{class:"dl-op-loghead"},[t("b",{},_("Operation log")),Pe("copy",_("Copy log"),()=>xe(M.join(` -`),_("Log copied")))]),p,u]),[v],"wide"),x([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?_("Checking…"):_("Working…"))]);let S=o??null,z=o?.id,E,$=0,b=T=>{z!==T.id&&(z=T.id,e.onJob?.(T))};if(o)e.onJob?.(o);else try{let T=await H.updatesStatus().catch(()=>null);E=T?.job?.id,$=T?.now??0;let C=await H.updatesRun(n);C.job&&C.job.state==="running"&&C.job.id!==E&&(S=C.job,b(C.job))}catch(T){return M=[Ce(T)],p.textContent=M[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[g("alert"),t("span",{},Ce(T))])),x([h(!0)]),q(Ce(T),"error"),null}let k=null,y=0;for(;;){if(await Ao(1e3),k=await H.updatesStatus().catch(()=>null),!k){if(++y>60)break;continue}y=0;let T=k.job;if(!T||!Sr(T,z,E,$)){if(Date.now()-a>15e3)break;continue}if(b(T),S=T,T.log.length){M=T.log;let C=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=M.join(` -`),C&&(p.scrollTop=p.scrollHeight)}if(l.textContent=Er(T,e.version??""),!l.isConnected&&l.textContent&&i.after(l),c.textContent=Mr((T.finished??k.now)-T.started),T.state==="running"){d.hidden=!T.phase,d.textContent=T.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!S||S.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,t("div",{class:"dl-comp-status warn"},[g("alert"),t("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),x([h()]),e.onDone?.(k),S;if(S.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,t("div",{class:"dl-comp-status bad"},[g("x"),t("span",{},[t("b",{},(S.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),x([N(_("Copy log"),()=>xe(M.join(` -`),_("Log copied"))),h(!0)]),q(`${Nn(s)??_("Update","noun")}: ${S.error??_("failed")}`,"error"),e.onDone?.(k),S;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&k){let T=Tr(k,s);if(dom.content(u,t("div",{class:`dl-comp-status ${T.tone}`},[g(T.tone==="ok"?"check":T.tone==="warn"?"alert":"download"),t("span",{},T.text)])),q(T.text,T.tone==="warn"?"warning":"success"),e.onDone?.(k),T.update&&e.onUpdate){let C=k;x([h(),N(m(_("Update to %s"),T.update),()=>e.onUpdate(C),"positive")])}else x([h()]),T.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return S}let I=/^app:(lang:|nolang$)/.exec(S.component??"");if(I){let T=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,t("div",{class:"dl-comp-status ok"},[g("check"),t("span",{},[t("b",{},I[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),x([h(),N(_("Reload now"),T,"positive")]),await Ao(4e3),u.isConnected&&T(),S}if(s==="app"&&S.to){let T=S.to,C=t("span",{},_("Waiting for the router to restart its services…"));dom.content(u,t("div",{class:"dl-comp-status ok"},[g("check"),t("span",{},[t("b",{},m(_("Dawnline %s is installed."),T))," ",C])]));let D=()=>{ui.menu?.flushCache(),location.reload()};x([h(),N(_("Reload now"),D,"positive")]),q(m(_("Dawnline updated to %s"),T),"success",6e3);for(let F=1;F<=30;F++)if(C.textContent=m(_("Waiting for the router to restart its services (%s of 30)…"),F),await Ao(1500),(await H.updatesStatus().catch(()=>null))?.version===T)return C.textContent=_("Services are back. Reloading…"),setTimeout(D,800),S;return C.textContent=_("Services restarted. Reload the page to use the new version."),S}let w=[...S.result?.pkgs?.updated??[],...S.result?.pkgs?.installed??[]],f=s==="pkgs"?w.length?m(_("Updated %s"),w.join(", ")):_("Updated system packages"):s==="amneziawg"?S.to?m(_("AmneziaWG %s is installed"),S.to):_("AmneziaWG is installed"):_("Operation completed");return dom.content(u,t("div",{class:"dl-comp-status ok"},[g("check"),t("span",{},f)])),x([h()]),q(f,"success"),e.onDone?.(k),S}function sl(n){return{https:[_("Install HTTPS for the portal?"),_("Installing HTTPS for the portal")],acme:[_("Install ACME certificates?"),_("Installing ACME certificates")],home:[_("Install the home-like link?"),_("Installing the home-like link")],awg:[_("Install AmneziaWG?"),_("Installing AmneziaWG")]}[n]}async function Pr(n,e,o,s){let[r,a]=sl(e);return!await me(r,o,_("Install"))||(await on(n,{title:a}))?.state!=="done"?!1:(setTimeout(()=>s?.(),4e3),!0)}function zn(n){return Pr("amneziawg:auto","awg",_("Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds."),n)}async function sn(n,e,o){return n==="awg"?zn(o):e.length?Pr(`pkgs:${e.join(",")}`,n,m(_("%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive."),e.join(", ")),o):!0}async function $r(n,e){if(n==="awg")return zn(e);let o=await K(()=>H.updatesStatus());return o?sn(n,o.needs?.[n]??[],e):!1}var rl=()=>[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn",_("VPN & tunnels")],["other",_("Other")]],al={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function No(n){let e=t("b",{},oe(_("add its interface %s to their source interfaces yourself"),t("span",{class:"dl-mono"},n)));return[...oe(_("Off: internet traffic goes straight to the WAN, the fastest way. DNS still goes through this router. Proxies and filters here handle the tunnel only if you %s."),e)," ",t("span",{class:"dl-warn"},_("If the router’s DNS hands out proxy addresses, those sites won’t open without it."))]}function Ho(){return bt(_("Slower: every packet crosses the router twice. On a dual-core router expect up to a third less speed, and lost packets at full load."))}function Dr(n,e,o){let s=n.id,r=e,a=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},_("Loading interfaces…"))))),i,l=!0,d="",c=!0,p=!0,u="all",v=!1,M=_r(r,s,o),x=new Set,h="",S=()=>JSON.stringify([p,l,l?"":d,c,[...x].sort()]),z=()=>i.detected.lan||i.saved.lan||"",E=()=>(l?i.detected.wan||i.saved.wan:d)||"",$=()=>new Map(i.devices.map(B=>[B.name,B])),b=()=>{let B=$();return[...c&&z()?[z()]:[],...[...x].filter(ne=>ne!==z())].filter(ne=>ne!==E()).map(ne=>B.get(ne)??{name:ne,nets:[],missing:!0})},k=(B,Q)=>{i=B,Q&&(l=B.config.auto_wan,d=B.config.wan_device||B.detected.wan||B.saved.wan||"",c=B.config.auto_lan,p=B.config.lan_like,u=B.config.mesh??(B.config.device_mesh?"all":"off"),x=new Set(B.config.lan_devices),h=S()),Y()},y=async B=>{let Q=await H.interfaces(s).catch(ne=>(q(ne.message,"error"),null));Q&&k(Q,B)};function I(B){let Q=c&&B.name===z(),ne=!!B.own||!!B.master||B.name===E()||Q;return Q||x.has(B.name)||!ne&&(B.nets.length>0||!!B.missing)}function w(B){let Q=c&&B.name===z(),ne=B.name===E(),fe=!Q&&x.has(B.name),j=!(!!B.own||!!B.master||ne||Q)&&(B.nets.length>0||fe||!!B.missing),J=(fe||Q)&&!B.zone&&!B.missing,ie=B.missing?_("Not present right now"):B.own?_("This server"):B.master?m(_("Port of %s"),B.master):ne?`${_("Internet")}${B.zone?` · ${m(_("zone %s"),B.zone)}`:""}`:B.nets.length?B.nets.join(", "):_("No IPv4 network"),ve=t("button",{type:"button",class:`dl-if${fe?" sel":""}${Q?" auto":""}${!j&&!fe&&!Q?" off":""}${J?" warn":""}`,"aria-pressed":fe||Q?"true":"false","aria-disabled":j?null:"true",click:()=>{j&&(x.has(B.name)?x.delete(B.name):x.add(B.name),Y())}},[t("span",{class:"dl-if-ic"},g(al[B.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},B.name),t("span",{class:"dl-if-sub"},ie)]),Q?t("span",{class:"dl-if-badge ok"},_("Auto")):fe?t("span",{class:"dl-if-check"},g("check")):""]);return we(ve,()=>[t("div",{class:"dl-tip-title"},B.name),t("div",{class:"dl-muted"},[B.logical?m(_("Interface %s"),B.logical):_("No netifd interface")," · ",B.zone?m(_("zone %s"),B.zone):_("no firewall zone")]),B.members.length?t("div",{class:"dl-muted"},m(_("Ports: %s"),B.members.join(", "))):"",B.nets.length?t("div",{class:"dl-mono"},B.nets.join(", ")):"",J?t("div",{class:"dl-warn"},_("Not in a firewall zone: the firewall rejects this traffic.")):"",B.master?t("div",{class:"dl-muted"},m(_("Choose %s to include it."),B.master)):""]),ve}function f(){let B=i.like_home;return!p||!i.config.lan_like||!n.enabled?"":!i.needs?.length&&B.active&&B.bridged?"ok":"warn"}function T(){let B=i.like_home;return p?i.needs?.length?[t("span",{class:"dl-warn"},m(_("Needs %s."),new Intl.ListFormat(le(),{type:"conjunction"}).format(i.needs)))," ",_("Until they are installed, internet traffic goes straight to the WAN.")]:i.config.lan_like?n.enabled?B.active&&B.bridged?oe(_("Internet traffic enters %s as %s, so whatever handles home traffic (proxies, filters, DNS) handles it too."),t("span",{class:"dl-mono"},B.dev??""),t("span",{class:"dl-mono"},B.address??"")):[t("span",{class:"dl-warn"},m(_("Not working: %s"),B.error??_("the link is down")))," ",_("Internet traffic goes straight to the WAN for now.")]:[_("Internet traffic enters the router from your LAN, so whatever handles home traffic (proxies, filters, DNS) handles it too.")]:[_("Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.")]:No(n.ifname)}let C=B=>({off:_("Devices of different people never reach each other; a person's own devices don't either."),all:_("Devices of people with home access reach each other, like home devices do. Internet-only people never."),circles:_("Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never.")})[B];function D(B,Q,ne,fe,se="",j){return t("div",{class:j?"dl-setrow head":"dl-setrow"},[t("div",{class:"dl-lh-main"},[t("span",{class:`dl-need-ic ${se}`},g(B)),t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},Q),t("span",{class:"dl-sub"},ne),j??""])]),t("div",{class:"dl-setrow-ctl"},fe)])}let F=(B,Q)=>{let ne=fe=>t("span",{class:"dl-mono"},fe);return B?t("span",{},[" ",...Q&&Q!==B?oe(_("Now: %s, was %s."),ne(B),ne(Q)):oe(_("Now: %s."),ne(B))]):t("span",{},[" ",...Q?oe(_("Not found now: using %s."),ne(Q)):[_("Not found.")]])};function Y(){let B=t("select",{class:"cbi-input-select","aria-label":_("Internet interface"),change:A=>{d=A.target.value,Y()}},i.devices.filter(A=>!A.own&&!A.master&&A.zone&&!A.missing).map(A=>t("option",{value:A.name,selected:A.name===d?"selected":null},`${A.name} · ${m(_("zone %s"),A.zone)}`))),ne=b().flatMap(A=>A.nets.map(G=>[G,A.name])),fe=JSON.parse(S()),se=JSON.parse(h),j=(...A)=>A.some(G=>JSON.stringify(fe[G])!==JSON.stringify(se[G])),J=j(0,1,2),ie=j(3,4),ve=A=>N(_("Save"),async()=>{let G=await K(()=>H.serverInterfaces(s,l,l?"":d,c,[...x],p,u!=="off",u),_("Access saved"));G&&(k(G,!0),G.nets_changed&&G.lan_only&&q(W(G.lan_only,"%s person has Home-only access: their devices need the configuration again to reach the new networks.","%s people have Home-only access: their devices need the configuration again to reach the new networks."),"warning",1e4))},"positive",{disabled:!A}),R=t("section",{class:"dl-setsec dl-ifcard"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},_("Internet")),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},_("People with Internet or Both"))]),D("home",_("Internet like a home device"),T(),[p&&i.needs?.length?N(_("Install"),()=>sn("home",i.needs,()=>y(!1)),"positive"):"",ye(p,_("Internet like a home device"),A=>{p=A,Y()})],f(),p?Ho():void 0),D("globe",_("Auto-detect WAN"),[_("The interface with the default route: the server port opens there and Internet access leaves through it."),F(i.detected.wan,i.saved.wan)],[l?"":B,ye(l,_("Auto-detect WAN"),A=>{l=A,Y()})])]),t("div",{class:"dl-setsec-foot"},[t("span",{class:"dl-sub"},p?[_("Internet like a home device"),E()?[" · ",...oe(_("leaves through %s"),t("span",{class:"dl-mono"},E()))]:""]:E()?oe(_("Internet straight to %s"),t("span",{class:"dl-mono"},E())):_("No WAN found")),ve(J)])]),O=Qe([["off",_("Off")],["all",_("Everyone")],["circles",_("Circles")]],u,{label:_("Devices reach each other"),cls:"sm",optimistic:!1,onChange:async A=>{let G={off:_("Off"),all:_("Everyone"),circles:_("Circles")}[A];await K(()=>H.serverUpdate(s,{mesh:A}),m(_("Devices reach each other: %s"),G))&&(u=A,i.config.mesh=A,Y(),await o())}}),P=t("section",{class:"dl-setsec dl-ifcard"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},_("Home network")),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},_("People with Home or Both")),N([g("reset")," ",_("Rescan")],()=>y(!1),"neutral",{title:_("Read the interfaces again")})]),D("network",_("Networks"),_("Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it."),"","",ee()),D("link",_("Devices reach each other"),C(u),O,"",u==="circles"?Cr(r,s,o):void 0),M.el]),t("div",{class:"dl-setsec-foot"},[t("span",{class:"dl-sub dl-if-summary"},ne.length?oe(_("Home access reaches %s"),t("span",{},ne.flatMap(([A,G],te)=>[te?", ":"",t("span",{class:"dl-mono"},A),` (${G})`]))):_("No home network: Home access reaches nothing but this router.")),ve(ie)])]),U=window.scrollY;a.style.minHeight=`${a.offsetHeight}px`,dom.content(a,[R,P]),a.style.minHeight="",window.scrollTo({top:U})}function ee(){let B=i.devices.filter(I),Q=i.devices.filter(ne=>!I(ne));return t("div",{class:"dl-stack gap8 dl-netpick"},[B.length?t("div",{class:"dl-ifgrid"},B.map(w)):t("span",{class:"dl-warn"},_("No home network: Home access reaches nothing but this router.")),t("label",{class:"dl-boxrow"},[t("span",{class:"dl-stack"},[t("span",{},_("Auto-detect LAN")),t("span",{class:"dl-sub"},[_("Adds the LAN this router uses."),F(i.detected.lan,i.saved.lan)])]),ye(c,_("Auto-detect LAN"),ne=>{c=ne,Y()})]),Q.length?t("details",{class:"dl-params",open:v?"":null,toggle:ne=>v=ne.currentTarget.open},[t("summary",{},[g("chevron"),t("span",{},_("Other interfaces")),t("span",{class:"dl-pcount"},String(Q.length))]),t("div",{class:"dl-params-body"},[t("span",{class:"dl-sub"},_("The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network.")),...rl().map(([ne,fe])=>{let se=Q.filter(j=>j.category===ne);return se.length?t("div",{class:"dl-ifgroup"},[t("h4",{},fe),t("div",{class:"dl-ifgrid"},se.map(w))]):""})])]):""])}return y(!0),{el:a,update(B){r=B,M.update(B),i&&Y()}}}var il={connect:"ok",disconnect:"",roam:"",device_added:"ok",device_removed:"",person_added:"",person_removed:"",paused:"warn",resumed:"ok",expiring:"warn",expired_kept:"",portal_blocked:"bad",person_changed:"",devices_removed:"warn"},ll={devices_removed:"trash",link_changed:"link",person_added:"plus",person_removed:"trash",person_changed:"edit",paused:"pause",resumed:"play",expiring:"calendar",expired_kept:"calendar"};function dl(n,e){return e.device?n.people.flatMap(s=>s.devices).find(s=>s.id===e.device)?.kind??e.dkind??"other":ll[e.type]??"activity"}var cl=n=>/^\d{4}-\d{2}-\d{2}$/.test(n)?Be(n):n;function zo(n,e){let o=n.people.find(h=>h.id===e.person),s=o?.name??e.pname??e.person??"",r=o?.devices.find(h=>h.id===e.device)?.name??e.dname??"",a=h=>t("b",{},h),i=h=>t("span",{class:"dl-muted"},h),l=h=>t("span",{class:"dl-mono"},h),d=h=>e.hosts?.[h]?[t("span",{class:"dl-ev-host"},[t("b",{},e.hosts[h]),t("span",{class:"dl-faint"},` (${h})`)])]:[l(h)],c=(h,...S)=>oe(h,...S).map(z=>typeof z=="string"?i(z):z),p=(h,...S)=>{let z=_("You");return h.startsWith(`${z} `)?[t("span",{class:"dl-you"},z),...c(h.slice(z.length),...S)]:c(h,...S)},u=a(r?`${s} · ${r}`:s),v=Ls(e),M=a(v||r||_("a device")),x=Ve(e);if(x==="admin")switch(e.type){case"device_added":return p(_("You added device %s for %s"),M,a(s));case"device_removed":return p(_("You removed device %s from %s"),M,a(s));case"paused":return p(_("You paused person %s"),a(s));case"resumed":return p(_("You resumed person %s"),a(s));case"device_changed":{let h=a(r||_("a device"));return v.startsWith("renamed from ")?[...p(_("You renamed device %s of %s"),h,a(s)),i(` · ${m(_("was %s"),v.slice(13))}`)]:v==="turned off"?p(_("You turned off device %s of %s"),h,a(s)):v==="turned on"?p(_("You turned on device %s of %s"),h,a(s)):[...p(_("You changed device %s of %s"),h,a(s)),...v?[i(` · ${v}`)]:[]]}case"device_keys":return[...p(_("You issued new keys for device %s of %s"),M,a(s)),i(` · ${_("it needs its new configuration")}`)];case"link_changed":return[...p(_("You issued a new link for person %s"),a(s)),i(` · ${_("the old link stopped working")}`)]}switch(e.type){case"connect":return[...e.detail?c(_("Device %s connected from %s"),u,t("span",{},d(e.detail))):c(_("Device %s connected"),u),...e.where?[i(` · ${e.where}`)]:[]];case"disconnect":return c(_("Device %s went offline"),u);case"roam":return c(_("Device %s changed network %s"),u,t("span",{},(e.detail??"").split(" → ").flatMap((h,S)=>S?[i(" → "),...d(h)]:d(h))));case"device_added":return c(x==="portal"?_("Person %s added device %s on their portal"):_("Person %s added device %s"),a(s),M);case"device_removed":return c(x==="portal"?_("Person %s removed device %s on their portal"):_("Person %s removed device %s"),a(s),M);case"device_keys":return c(_("Person %s issued new keys for device %s on their portal"),a(s),M);case"person_added":return p(_("You added person %s"),a(e.detail??s));case"person_removed":return p(_("You removed person %s"),a(e.detail??s));case"person_changed":return[...p(_("You changed person %s"),a(s)),...v?[i(` · ${Es(v)}`)]:[]];case"expiring":{let h=Ms(e.detail??"");return h!=null?c(N_(h,"Person %s’s access ends in %s day","Person %s’s access ends in %s days"),a(s),i(V(h))):c(_("Person %s’s access ends in a few days"),a(s))}case"expired_kept":return c(_("Person %s’s end date passed (%s) · access kept"),a(s),i(cl(e.detail??"")));case"paused":return e.detail?c(_("Person %s paused - %s"),a(s),i(mo(e.detail))):c(_("Person %s paused"),a(s));case"resumed":return e.detail&&e.detail!=="active"?c(_("Person %s resumed - %s"),a(s),i(mo(e.detail))):c(_("Person %s resumed"),a(s));case"portal_blocked":return c(_("%s blocked %s for 15 min after too many wrong codes"),t("b",{class:"dl-sys-src"},_("Personal portal")),e.detail==="all Cloudflare visitors"?i(_("all Cloudflare visitors")):l(e.detail??""));case"devices_removed":return c(_("Person %s - all devices removed, end date reached"),a(s));default:return[i(`${e.type}${e.detail?`: ${e.detail}`:""}`)]}}var pl={portal_blocked:["globe","bad"]};function ul(n,e){if(n.servers.length<2||!e.person)return"";let o=n.people.find(r=>r.id===e.person),s=o&&n.servers.find(r=>r.id===o.server);return s?t("span",{class:"dl-ev-srv",title:_("Server")},s.name):""}function ht(n,e,o={}){let s=pl[e.type],r=Ve(e);return t("div",{class:`dl-row${r==="admin"?" dl-ev-by-admin":s?` dl-ev-by-system ${s[1]}`:""}`},[r==="admin"?t("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},g("admin")):s?t("span",{class:"dl-ev-tile sys"},g(s[0])):t("span",{class:`dl-ev-tile ev ${il[e.type]??""}`},g(dl(n,e))),t("span",{class:"dl-row-main"},zo(n,e)),o.server===!1?"":ul(n,e),t("span",{class:"dl-faint dl-nowrap",title:new Date(e.ts*1e3).toLocaleString(le())},o.time??pe(e.ts,n.now))])}var ml={info:"",up:"ok",down:"warn",repair:"warn",error:"bad"},hl={awg:"tunnel",dawnline:"sunrise",portal:"globe"};function fl(n){return{info:_("info"),up:_("up"),down:_("down"),repair:_("repair"),error:_("error")}[n]??n}function gl(n){let e=Ts(n.msg,n.kind,n.who),o=_("You");if(!e)return[t("span",{class:"dl-you"},o),t("span",{class:"dl-muted"},` ${n.msg} `),n.kind?t("span",{class:"dl-ev-kind"},`${n.kind} `):"",n.who?t("b",{},n.who):""];let s=(e.named?oe(e.text,t("b",{},Ss(n.msg,n.who??""))):[e.text]).map(a=>typeof a=="string"?t("span",{class:"dl-muted"},a):a),r=s[0]?.textContent??"";return r.startsWith(`${o} `)?[t("span",{class:"dl-you"},o),t("span",{class:"dl-muted"},r.slice(o.length)),...s.slice(1)]:s}var Ar=n=>n.split(` -`).map(e=>Nt(e)).join(` -`);function Rn(n,e,o,s){let r=n.by==="admin",a=Nt(n.msg),i=t("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${ml[n.level]??""}`}${n.detail?" has-detail":""}`},[r?t("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},g("admin")):t("span",{class:"dl-ev-tile sys",title:fl(n.level)},g(hl[n.src]??"zap")),t("span",{class:"dl-row-main"},r?[...gl(n),n.note?t("span",{class:"dl-muted"},` · ${Ps(n.note)}`):"",n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},g("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Ar(n.detail)):""]:[n.src==="awg"&&n.who&&n.who!=="AmneziaWG"?t("span",{class:"dl-ev-kind"},`${_("Server")} `):"",t("b",{class:"dl-sys-src",title:Kt(n.src)},n.who?n.src==="awg"?n.who:Nt(n.who):Kt(n.src)),/^[:,]/.test(a)?"":" ",t("span",{class:"dl-muted"},a),n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},g("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Ar(n.detail)):""]),t("span",{class:"dl-faint dl-nowrap",title:new Date(n.ts*1e3).toLocaleString(le())},s)]);return n.detail&&i.addEventListener("click",l=>{l.target.closest("pre")||o()}),i}function Nr(n){let e=new Date(n*1e3),o=new Date,s=new Date;if(s.setDate(o.getDate()-1),e.toDateString()===o.toDateString())return _("Today");if(e.toDateString()===s.toDateString())return _("Yesterday");let r=e.toLocaleDateString(le(),{weekday:"long",day:"numeric",month:"long"});return r.charAt(0).toLocaleUpperCase(le())+r.slice(1)}var jt=n=>Et(n).toLocaleDateString(le(),{day:"numeric",month:"short"});function In(n,e,o,s=!1){let r=n.slice(-15),a=r[r.length-1],i=a&&e-a[0]<180,l=i?a[2]:0,d=i?a[1]:0,[c,p]=o,u=200,v=40,M=Math.max(1,...r.map($=>Math.max($[1],$[2]))),x=$=>r.map((b,k)=>`${r.length>1?k/(r.length-1)*u:u},${v-2-b[$]/M*(v-6)}`),h=x(2),S=x(1),z=r.length>1&&!s?St(``):t("div",{class:"dl-speed-wait"},[t("i"),s?"":t("span",{},_("Collecting… 1 point a minute"))]),E=($,b,k,y)=>t("div",{class:"dl-speed-col"},[t("span",{class:"dl-sub"},[t("span",{class:k},b),` ${$}`]),s?t("span",{class:"dl-speed-val off"},"—"):t("span",{class:"dl-speed-val"},qe(y))]);return r.length>1&&!s&&we(z,()=>{let $=r[r.length-1];return[t("div",{class:"dl-tip-title"},new Date($[0]*1e3).toLocaleTimeString(le(),{hour:"2-digit",minute:"2-digit"})),t("div",{},`↓ ${qe($[2])} · ↑ ${qe($[1])}`)]}),t("div",{class:"dl-bento-tile"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},_("Speed now")),s?"":t("span",{class:"dl-sub"},_("last 15 min"))]),t("div",{class:"dl-speed-cols"},[E(_("Download","speed"),"↓","dl-dn",l),E(_("Upload","speed"),"↑","dl-up",d)]),z,t("div",{class:"dl-speed-today"},[t("span",{},oe(_("Today %s"),t("b",{},re(c+p)))),t("span",{},[t("span",{class:"dl-dn"},"↓"),` ${re(p)} `,t("span",{class:"dl-up"},"↑"),` ${re(c)}`])])])}function Bn(n,e){let o=n.slice(-30),s=o.map(d=>d.rx+d.tx),r=Math.max(1,...s),a=s.reduce((d,c)=>d+c,0),i=s.reduce((d,c,p)=>c>s[d]?p:d,0),l=t("div",{class:"dl-bento-bars"},o.map((d,c)=>{let p=s[c],u=t("i",{class:c===o.length-1?"hi":"",style:`height:${Math.max(4,p/r*100)}%`}),v=t("span",{},[u]);return we(v,()=>[t("div",{class:"dl-tip-title"},c===o.length-1?`${_("Today")} · ${jt(d.day)}`:jt(d.day)),t("div",{},re(p)),t("div",{class:"dl-muted dl-mono"},`↓ ${re(d.tx)} ↑ ${re(d.rx)}`)]),v}));return t("div",{class:"dl-bento-tile month"},[t("div",{class:"dl-bento-head"},[t("span",{},[t("span",{class:"dl-metric-label"},_("Last 30 days")),t("b",{class:"dl-bento-total"},re(a))]),s[i]>0?t("span",{class:"dl-sub"},`${m(_("peak %s"),re(s[i]))} · ${jt(o[i].day)}`):""]),o.length?l:t("p",{class:"dl-muted"},_("No traffic yet.")),t("div",{class:"dl-bento-head"},[t("span",{class:"dl-sub"},o.length?jt(o[0].day):""),t("span",{class:"dl-sub"},e),t("span",{class:"dl-sub"},_("today"))])])}function Hr(n){let e=n.slice(-30),o=e.map(r=>r.rx+r.tx),s=Math.max(1,...o);return t("div",{class:"dl-dbars"},e.map((r,a)=>{let i=t("i",{class:`${o[a]?"":"zero"}${a===e.length-1?" hi":""}`});i.style.height=`${Math.max(8,o[a]/s*100)}%`;let l=t("span",{},[i]);return we(l,()=>[t("div",{class:"dl-tip-title"},a===e.length-1?`${_("Today")} · ${jt(r.day)}`:jt(r.day)),t("div",{},re(o[a]))]),l}))}function zr(n){return{apply:_("Repair"),sync:_("Reload devices"),restart:_("Restart service"),netrestart:_("Restart network"),updates:_("Open Components")}[n]??_("Fix")}async function On(n){return n==="netrestart"&&!await me(_("Restart the network?"),_("Every interface restarts. Connections drop for a few seconds."),_("Restart network"))?null:await K(()=>H.healthFix(n),_("Done"))??null}function Ro(n,e,o,s="action"){let r=n.fix;return r?r.startsWith("install:")?N(_("Install"),()=>$r(r.slice(8),o),s):r==="updates"?t("a",{class:`cbi-button cbi-button-${s}`,href:L.url("admin/network/dawnline/updates")},zr(r)):N(zr(r),()=>e(r),s):""}function vl(n){return/^(awg|up_|peers_|fw_|reply_|port_|subnet_)/.test(n)?"shield":/^(portal|cert)/.test(n)?"link":/^(ep_|home_|resolver)/.test(n)?"globe":n==="clock"?"clock":n==="agent"?"activity":n==="flash"?"download":n==="nft"?"lock":n==="data"?"users":"alert"}function Rr(n,e,o,s=3){let r=n.filter(i=>i.status==="error"||i.status==="warn").sort((i,l)=>i.status===l.status?0:i.status==="error"?-1:1);if(!r.length)return"";let a=r.length-s;return t("div",{class:"dl-list dl-notices"},[...r.slice(0,s).map(i=>it(vl(i.id),i.status==="error"?"bad":"warn",i.problem??i.title,i.detail,Ro(i,e,o,i.status==="error"?"positive":"neutral"))),a>0?t("a",{class:"dl-row dl-notices-more",href:L.url("admin/network/dawnline/diagnostics")},[m(_("%s more in Diagnostics"),V(a)),t("span",{class:"dl-spacer"}),"→"]):""])}function bl(n){let e=[],o=(l,d)=>t("a",{href:l},d),s=()=>o(L.url("admin/network/dawnline/diagnostics"),_("Open Diagnostics")),r=We(n.series),a=!!n.awg_state&&!n.awg_state.ok;for(let l of n.servers)l.enabled&&l.blocked?e.push({tone:"bad",text:[l.blocked," ",s()]}):l.enabled&&!l.up&&!a&&e.push({tone:"bad",text:[m(_("Tunnel %s is down."),l.ifname)," ",s()]});for(let l of n.people){let d=()=>o(ze(l.id),l.name);if(l.state==="quota")e.push({tone:"warn",text:oe(_("%s reached the data limit."),d())});else if(l.state==="expired")e.push({tone:"warn",text:oe(_("%s’s access has ended."),d())});else{let c=st(l.expires,r);rt(l,c)?e.push({tone:"",text:oe(_("%s’s access %s."),d(),dn(c))}):c!=null&&c<0&&l.expire_action==="notify"&&e.push({tone:"",text:oe(_("%s’s end date passed (%s) · access kept."),d(),$e(l.expires))}),l.quota_limit&&l.quota_used>=l.quota_limit*.9&&e.push({tone:"",text:oe(_("%s has used 90% of the data limit."),d())})}}let i=n.people.flatMap(l=>l.devices.filter(d=>d.config_stale).map(d=>[l,d]));i.length&&e.push({tone:"warn",text:i.length===1?oe(_("%s needs its configuration again."),o(ze(i[0][0].id,i[0][1].id),`${i[0][0].name} · ${i[0][1].name}`)):[W(i.length,"%s device needs its configuration again (networks or DNS changed).","%s devices need their configuration again (networks or DNS changed).")]});for(let l of n.servers)n.wan&&At(l.endpoint)&&l.endpoint!==n.wan&&e.push({tone:"warn",text:[m(_("Public address changed: %s still gives devices %s, the router is %s now."),l.name,l.endpoint,n.wan)," ",t("button",{type:"button",class:"dl-fix",click:async d=>{let c=d.currentTarget;c.disabled=!0,await K(()=>H.serverUpdate(l.id,{endpoint:n.wan}),m(_("%s uses %s now - devices need their configuration again"),l.name,n.wan)),c.disabled=!1}},_("Use the new address"))," ",_("A DDNS name would follow it by itself.")]});return n.servers.some(l=>l.lan_like)&&n.like_home.error&&e.push({tone:"warn",text:[m(_("Internet through the LAN is off: %s"),n.like_home.error)," ",o(L.url("admin/network/dawnline/diagnostics"),_("Details"))]}),!n.settings.portal_enabled&&!n.people.length&&e.push({tone:"",text:[_("The personal portal is off.")," ",o(L.url("admin/network/dawnline/settings"),_("Turn on"))]}),e}var jn=class{constructor(e,o){this.srvId=e;this.go=o;this.el=t("div",{class:"dl-srvov"});this.map=null;this.mapOn=null;this.range="online";this.parts={};this.healthAt=0}mount(e){this.st=nn(e,this.srvId);for(let o of["health","bento","map","side","activity"])this.parts[o]=t("div",{});return dom.content(this.el,[this.parts.health,this.parts.bento,this.parts.map,t("div",{class:"dl-grid2"},[this.parts.activity,this.parts.side])]),this.paint(),this.loadHealth(),this.el}update(e,o=!1){this.st=nn(e,this.srvId),this.paint(o),Date.now()-this.healthAt>6e4&&this.loadHealth()}async loadHealth(){this.healthAt=Date.now();let e=await H.health().catch(()=>null);if(!e)return;let o=()=>void this.loadHealth(),s=async r=>{await On(r)&&(o(),r==="netrestart"&&setTimeout(o,5e3))};De(this.parts.health,Rr(e.checks,r=>void s(r),o),!0)}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now}}paintMap(){let e=this.st.geo.enabled;if(e===this.mapOn&&(!e||this.map)){this.map?.update(this.mapData());return}this.mapOn=e,dom.content(this.parts.map,this.mapCard())}mapCard(){let e=this.st,o=t("div",{class:"dl-panel-head pad"},[t("div",{class:"dl-stack"},[t("h3",{},_("Where people connect from")),t("span",{class:"dl-sub"},_("City-level, from the client IP · locations cached on the router"))]),t("span",{class:"dl-spacer"}),It(this.range,l=>{this.range=l,this.map?.setRange(l)})]);if(this.map?.destroy(),this.map=null,!e.geo.enabled)return t("div",{class:"dl-panel flush"},[o,t("div",{class:"dl-map-off"},oe(_("Locations are off. %s."),t("a",{href:L.url("admin/network/dawnline/settings")},_("Turn them on in Settings"))))]);let s=this.map=new dt({openPerson:l=>location.href=ze(l),openDevice:(l,d)=>location.href=ze(l,d)},this.range),r=Ee(()=>{r(),s.destroy(),this.map===s&&(this.map=null)}),a=t("div",{class:"dl-map-legend"},[t("span",{},[t("i",{class:"line live"}),_("Live tunnel")]),t("span",{},[t("i",{class:"line"}),_("Seen recently")])]),i=t("div",{class:"dl-map-wrap"},[s.el,a]);return requestAnimationFrame(()=>s.mount(this.mapData())),t("div",{class:"dl-panel flush"},[o,i])}paint(e=!1){let o=this.st,s=o.servers[0];this.paintMap(),De(this.parts.bento,t("div",{class:"dl-bento"},[this.onlineTile(),this.speedTile(),Ge(s).overviewTile(s),this.monthTile()]),e);let r=bl(o);De(this.parts.side,t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Needs attention")),t("span",{class:"dl-spacer"}),t("a",{href:L.url("admin/network/dawnline/diagnostics")},_("Health"))]),r.length?r.slice(0,8).map(i=>t("div",{class:"dl-attn-item dl-row"},[t("span",{class:`dl-ev-dot ${i.tone}`}),t("span",{},i.text),i.action??""])):t("div",{class:"dl-row dl-muted"},[g("check"),_("All good. Nothing needs you right now.")])]),e);let a=[...o.events].reverse().slice(0,8);De(this.parts.activity,t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Activity")),t("span",{class:"dl-spacer"}),t("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},_("View all"))]),a.length?a.map(i=>ht(o,i)):t("div",{class:"dl-row dl-muted"},_("Nothing yet. Connections, new devices and pauses appear here."))]),e)}onlineTile(){let e=this.st,o=e.servers[0]?!e.servers[0].enabled:!1,s=12,r=z=>{let[E,$]=z.spark[z.spark.length-1]??[0,0];return E+$},a=z=>e.geo.points.find(E=>E.device===z.id&&E.city)?.city,i=z=>/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(z.endpoint??""),l=(z,E=!1)=>i(z)?E&&z.endpoint?`LAN · ${z.endpoint}`:"LAN":a(z)??"",d=z=>[...e.events].reverse().find(E=>E.type==="connect"&&E.device===z.id)?.ts??0,c=e.people.map(z=>({p:z,devs:z.devices.filter(E=>E.online).sort((E,$)=>r($)-r(E))})).filter(z=>z.devs.length).sort((z,E)=>E.devs.reduce(($,b)=>$+r(b),0)-z.devs.reduce(($,b)=>$+r(b),0)),p=c.length<=2,u=({p:z,devs:E})=>{let $=E.map(d).filter(Boolean),b=$.length?Math.min(...$):0,k=(z.rate??[]).slice(-15),y=k[k.length-1],I=y&&e.now-y[0]<180?y:null,w=200,f=30,T=Math.max(1,...k.map(ee=>Math.max(ee[1],ee[2]))),C=ee=>k.map((B,Q)=>`${k.length>1?Q/(k.length-1)*w:w},${f-2-B[ee]/T*(f-6)}`),D=k.length>1?St(``):"",F=!I||I[1]<64&&I[2]<64,Y=z.access==="both"?["home","globe"]:z.access==="lan"?["home"]:["globe"];return[t("div",{class:"dl-hc"},[t("div",{class:"dl-hc-head"},[t("span",{class:"dl-onl-av sm"},Oe(z.name)),t("span",{class:"dl-stack"},[t("b",{},z.name),t("span",{class:"dl-hc-since"},b?m(_("online for %s"),ot(Math.max(60,e.now-b))):_("online"))]),t("span",{class:"dl-hc-reach"},Y.map(ee=>t("span",{class:`dl-ibadge ${ee==="home"?"lan":"inet"}`},g(ee))))]),t("div",{class:"dl-hc-speed"},[t("div",{class:"dl-hc-speed-row"},F?[t("span",{class:"dl-faint"},_("Idle right now"))]:[t("span",{},[t("span",{class:"dl-dn"},"↓"),` ${qe(I[2])}`]),t("span",{},[t("span",{class:"dl-up"},"↑"),` ${qe(I[1])}`]),t("span",{class:"dl-spacer"}),t("span",{class:"dl-faint"},_("15 min"))]),D]),t("div",{class:"dl-hc-devs"},E.map(ee=>t("span",{class:"dl-hc-dev"},[g(ee.kind),ee.name,l(ee)?[" · ",l(ee,!0)]:""]))),t("div",{class:"dl-hc-foot"},[t("span",{class:"dl-faint"},`${m(_("%s today"),re(E.reduce((ee,B)=>ee+r(B),0)))} · ${m(_("%s this month"),re(z.month[0]+z.month[1]))}`)])])]},v=z=>{let{p:E,devs:$}=z,b=t("span",{class:"dl-onl-dev"},$.length>1?String($.length):g($[0].kind)),k=t("a",{class:`dl-onl-p${p?"":" sm"}`,href:ze(E.id),"aria-label":m(_("%s, online"),E.name)},[t("span",{class:"dl-onl-av"},[Oe(E.name),b]),p?t("span",{class:"dl-onl-name"},E.name):"",p?t("span",{class:"dl-onl-meta"},[...$.slice(0,3).map(y=>g(y.kind)),$.length>3?`+${$.length-3}`:"",l($[0])?t("span",{},[" · ",l($[0])]):""]):""]);return we(k,()=>u(z)),k},M=t("b",{class:`dl-onl-count${c.length?"":" none"}`},String(c.length)),x=c.reduce((z,E)=>z+E.devs.length,0);c.length&&we(M,()=>[`${W(c.length,"%s person","%s people")} · ${W(x,"%s device","%s devices")}`]);let h=c.length>s?c.slice(0,s-1):c,S=e.people.flatMap(z=>z.devices.map(E=>({p:z,d:E}))).filter(z=>z.d.handshake).sort((z,E)=>E.d.handshake-z.d.handshake)[0];return t("div",{class:"dl-bento-tile online"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},_("Online")),M]),c.length?t("div",{class:`dl-onl-row${p?"":" grid"}`},[...h.map(v),c.length>s?t("a",{class:"dl-onl-p sm more",href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(this.srvId)}§ion=people&filter=online`,title:_("Everyone online"),click:z=>{this.go&&(z.preventDefault(),this.go("people","online"))}},[t("span",{class:"dl-onl-av"},`+${c.length-h.length}`)]):""]):t("div",{class:"dl-onl-empty"},[t("span",{},o?_("The server is turned off"):_("Nobody is connected")),S?t("span",{class:"dl-sub"},m(_("Last: %s, %s"),S.p.name,pe(S.d.handshake,e.now))):t("span",{class:"dl-sub"},o?_("Devices connect once it is on"):_("No device has connected yet"))])])}speedTile(){let e=this.st.servers[0];return In(e?.rate??[],this.st.now,this.st.totals.today,e?!e.enabled:!1)}monthTile(){let e=[...this.st.people].map(o=>[o,o.month[0]+o.month[1]]).filter(([,o])=>o>0).sort((o,s)=>s[1]-o[1]).slice(0,2);return Bn(this.st.series,e.length?m(_("Most: %s"),e.map(([o,s])=>`${o.name} ${re(s)}`).join(" · ")):"")}};var Ir=["overview","people","connection","access","awg"],xl=n=>({overview:_("Overview"),people:_("People"),connection:_("Connection"),access:_("Access")})[n],wl={general:"connection",network:"connection",interfaces:"access",advanced:"awg",disguise:"awg",tunnel:"awg",core:"awg"},Io=(n,e)=>{let o=new URLSearchParams;n&&o.set("server",n),e&&e!=="overview"&&o.set("section",e);let s=o.toString();return`${L.url("admin/network/dawnline/server")}${s?`?${s}`:""}`},rn=class{constructor(){this.noFooter=!0;this.root=t("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=t("div",{});this.headEl=t("div",{});this.secEl=t("div",{});this.bodyEl=t("div",{class:"dl-srvbody"})}async load(){let e=await H.status(31),o=e.servers.length?null:await H.setupDefaults();return[e,o]}render([e,o]){if(this.st=e,!e.servers.length&&o)return this.wizard(o);let s=new URLSearchParams(location.search),r=s.get("section")??"",a=wl[r]??r;return Ir.includes(a)&&(this.section=a),this.srvId=(e.servers.find(i=>i.id===s.get("server"))??e.servers[0]).id,dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),this.poller?.stop(),this.poller=pt({fetch:()=>H.status(31),every:30,live:!0,active:()=>this.section==="overview"&&this.root.isConnected,apply:(i,l)=>{i.servers.length&&(this.st=i,this.paintHead(l),this.ov[this.current().id]?.update(i,l))}}),this.root}paintHead(e=!1){De(this.headEl,this.head(this.current()),e),(!e||!Ot(this.tabsEl))&&this.paintTabs()}async refreshStatus(){let e=await H.status(31).catch(()=>null);return e?.servers.length?(this.st=e,this.paintHead(),e):null}current(){return this.st.servers.find(e=>e.id===this.srvId)??this.st.servers[0]}async refresh(){let e=await H.status(31).catch(()=>null);e&&(this.st=e,e.servers.length?this.paint():location.href=Io())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let e=this.current();dom.content(this.tabsEl,t("div",{class:"dl-srvtabs",role:"tablist","aria-label":_("Servers")},[...this.st.servers.map(o=>t("button",{type:"button",role:"tab",class:`dl-srvtab${o.id===e.id?" on":""}`,"aria-selected":o.id===e.id?"true":"false",click:()=>{o.id!==this.srvId&&(this.srvId=o.id,this.paint())}},[t("i",{class:`dot ${o.enabled?o.up?"ok":"bad":"warn"}`}),t("b",{},o.name)])),t("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[g("plus"),_("Add server")])]))}paintSections(){let e=Ge(this.current());dom.content(this.secEl,t("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":_("Server")},Ir.map(o=>t("button",{type:"button",role:"tab","data-section":o,class:o===this.section?"on":"","aria-selected":o===this.section?"true":"false",click:()=>this.showSection(o)},o==="awg"?e.label:xl(o)))))}go(e,o){let s=this.pp[this.current().id];if(o&&s)s.filter=o,s.el&&s.decorate();else if(o){let r=this.pp[this.current().id]=new yt;r.filter=o}this.showSection(e),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let e=[...Object.values(this.ov).map(o=>o.el),...Object.values(this.pp).map(o=>o.el)];for(let o of e)o&&this.bodyEl.contains(o)&&o.remove()}showSection(e){this.section=e,this.secEl.querySelectorAll("[data-section]").forEach(i=>{let l=i.dataset.section===e;i.classList.toggle("on",l),i.setAttribute("aria-selected",l?"true":"false")});let o=this.st,s=this.current(),a={overview:()=>{let i=this.ov[s.id];return i?(i.update(o),i.el):(this.ov[s.id]=new jn(s.id,(l,d)=>this.go(l,d))).mount(o)},people:()=>{var c,p;let i=this.pp[s.id];if(i?.el)return i.update(),i.el;let l=t("div",{},t("p",{class:"dl-muted"},_("Loading people…")));return((c=this.pp)[p=s.id]??(c[p]=new yt)).embed(o,s.id).then(u=>{l.isConnected?dom.content(l,u):l.replaceChildren(u)}).catch(u=>{delete this.pp[s.id],dom.content(l,t("p",{class:"dl-muted"},m(_("Couldn't show people: %s"),Ce(u))))}),l},connection:()=>this.connection(s),access:()=>this.access(s),awg:()=>this.awg(s)}[e]();this.detachKept(),dom.content(this.bodyEl,a)}head(e){let o=(a,i)=>t("span",{class:"dl-addrbar-seg"},[g(a),...i]),s=e.endpoint||"—",r=t("div",{class:"dl-actions"},[e.enabled?"":N([g("play"),` ${_("Turn on")}`],()=>this.save(e,{enabled:"1"},_("Server turned on")),"add")]);return t("div",{class:"dl-srvpagehead"},[t("div",{class:"dl-title-row"},[t("h2",{class:"dl-h1"},e.name),t("span",{class:`dl-pill ${e.enabled?e.up?"ok":"bad":"warn"}`},e.enabled?e.up?_("Running"):e.blocked?_("Can’t start"):_("Not running"):_("Turned off")),t("span",{class:"dl-spacer"}),r]),t("div",{class:"dl-addrbar"},[t("button",{type:"button",class:"dl-addrbar-seg main",title:_("Copy address"),click:()=>xe(s,_("Address copied"))},[g("globe"),t("span",{class:"dl-mono"},s),g("copy")]),o(Ge(e).id==="awg"?"amneziawg":"tunnel",[t("span",{class:"dl-mono"},`${Ge(e).label} :${e.port}`)]),e.up?o("clock",[m(_("up %s"),ot(e.uptime))]):""]),e.blocked?bt(e.blocked):""])}async save(e,o,s=_("Saved")){await K(()=>H.serverUpdate(e.id,o),s)&&await this.refresh()}connection(e){let o=he(e.name,{placeholder:_("Home")}),s=he(e.endpoint,{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),r=he(e.dns.join(", "),{placeholder:_("This router (recommended)"),class:"cbi-input-text dl-mono"}),a=this.st.people.filter(M=>M.server===e.id).length,i=N([g(e.enabled?"pause":"play"),` ${e.enabled?_("Turn off"):_("Turn on")}`],async()=>{e.enabled&&!await me(m(_("Turn off %s?"),e.name),W(a,"The tunnel stops and %s person is disconnected until you turn it back on. Nothing is deleted.","The tunnel stops and %s people are disconnected until you turn it back on. Nothing is deleted."),_("Turn off"),!0)||await this.save(e,{enabled:e.enabled?"0":"1"},e.enabled?_("Server turned off"):_("Server turned on"))},e.enabled?"negative":"positive"),l=this.st.settings.portal_host,d=_e(_("Name"),o,()=>Ne(o.value,[],_("Shown to people in their portal and apps."))),c=po(()=>({host:s.value,port:e.port,id:e.id}),(M,x,h)=>H.endpointProbe(M,x,h),()=>p.refresh(),{empty:l?m(_("Empty = the portal’s address (%s)."),l):_("Empty = the portal’s address.")}),p=_e(_("Public address"),s,c.help);s.addEventListener("input",c.schedule),c.schedule();let u=e.reached?m(_("Reached from the internet %s."),pe(e.reached,this.st.now)):_("Never reached from the internet yet - test with a phone on mobile data."),v=_e(_("DNS for devices"),r,()=>hs(r.value,e.address));return t("div",{class:"dl-stack gap16"},[Gt(_("Connection"),[t("p",{class:"dl-muted"},_("The name people see, where devices find the router, and DNS. The port is on AmneziaWG.")),ke("router",_("Server"),_("What people see"),[d]),ke("globe",_("Devices connect to"),_("A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)"),[p,t("div",{class:`dl-sub ${e.reached?"ok":"warn"}`},u)]),ke("file",_("For every device"),_("Changing it marks devices “Update config” until they import again"),[v])],[t("span"),N(_("Save"),()=>{let M=je([d,p,v]);if(M){q(M,"warning");return}return this.save(e,{name:o.value,endpoint:s.value,dns:r.value})},"positive")]),Gt(_("Danger zone"),[t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},e.enabled?_("Turn off this server"):_("This server is off")),t("span",{class:"dl-sub"},e.enabled?_("Stops the tunnel and disconnects everyone on it. Settings and people are kept."):_("Nobody can connect. Turn it on to bring the tunnel back."))]),t("div",{class:"dl-setrow-ctl"},i)]),t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},_("Change the tunnel network")),t("span",{class:"dl-sub"},m(_("Devices have %s addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again."),`${Dt(e.subnet)}.x`))]),t("div",{class:"dl-setrow-ctl"},N([g("edit"),` ${_("Change")}`],()=>this.changeSubnet(e),"negative"))]),t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},_("Remove server")),t("span",{class:"dl-sub"},W(a,"Removes the tunnel, its firewall rules and %s person with all their devices. A backup is made first.","Removes the tunnel, its firewall rules and %s people with all their devices. A backup is made first."))]),t("div",{class:"dl-setrow-ctl"},N([g("trash"),` ${_("Remove")}`],()=>this.remove(e),"negative"))])],[],"danger")])}access(e){let o=Do(this.st,e),s=Dr(e,this.st,async()=>{let r=await this.refreshStatus();if(!r)return;let a=r.servers.find(l=>l.id===e.id)??e;s.update(r);let i=Do(r,a);o.replaceWith(i),o=i});return t("div",{class:"dl-stack gap16"},[s.el,t("div",{class:"dl-health-cols"},[o,Lr(this.st,e)])])}awg(e){let o={st:this.st,save:(s,r)=>this.save(e,s,r),refresh:()=>this.refresh()};return t("div",{class:"dl-stack gap16"},[Ge(e).settingsCard(o,e)])}async addServer(){let e=await K(()=>H.setupDefaults());e&&dom.content(this.root,this.wizard(e,!0,()=>{dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint()}))}async changeSubnet(e){let o=await K(()=>H.serverPorts(e.id));if(!o)return;let s=o.networks??[],r=this.st.people.filter(l=>l.server===e.id).reduce((l,d)=>l+d.devices.length,0),a=he(Dt(e.subnet),{class:"cbi-input-text dl-mono dl-w-range"}),i=_e(_("Address range"),a,()=>lo(a.value,s,""));de(_("Change the tunnel network"),[i,t("p",{class:"dl-muted"},r?W(r,"%s device gets a new address and stops connecting until it imports its configuration again (from their personal link or from you).","%s devices get new addresses and stop connecting until they import their configuration again (from their personal link or from you)."):_("No devices on this server yet: nothing else changes."))],[ue()," ",N(_("Change"),async()=>{let l=i.help();if(l.bad){q(l.text,"warning");return}let d=fn(a.value);if(d===e.subnet){ce();return}await K(()=>H.serverUpdate(e.id,{subnet:d}),_("Tunnel network changed"))&&(ce(),r&&q(_("Devices are marked “Update config” until they import again."),"info",6e3),await this.refresh())},"negative")]),setTimeout(()=>a.select(),50)}async remove(e){let o=this.st.people.filter(s=>s.server===e.id);de(m(_("Remove %s?"),e.name),[t("p",{},W(o.length,"This removes the tunnel, its firewall rules and %s person with all their devices. A backup is made first.","This removes the tunnel, its firewall rules and %s people with all their devices. A backup is made first."))],[ue()," ",N(_("Remove"),async()=>{ce(),await K(()=>H.serverDelete(e.id),_("Server removed"))&&setTimeout(()=>{location.href=Io()},800)},"negative")])}wizard(e,o=!1,s){let r={id:e.id,name:e.name,endpoint:e.endpoint,port:e.port,range:Dt(e.subnet),preset:kn(e.awg),portal:!1,portal_port:e.portal_port||8443,lan_like:!1,lan_zone:e.lan_zone,wan_zone:e.wan_zone},a=0,i=!o&&r.portal_port===r.port,l=()=>/^\d{1,3}(\.\d{1,3}){3}$/.test(r.endpoint),d=()=>qt(r.port,e.udp_taken??[],r.port===4500?`${_("Opened on the WAN firewall automatically.")} ${_("4500 is IPsec’s port: most networks let it through.")}`:_("Opened on the WAN firewall automatically.")),c={ddns:_("From your DDNS name."),cert:_("From your Let’s Encrypt certificate."),wan:_("Your WAN address now - it may change; a DDNS name is better."),portal:_("The portal’s address.")},p=po(()=>({host:r.endpoint,port:r.port}),(C,D,F)=>H.endpointProbe(C,"",F),()=>u?.refresh(),{idle:()=>r.endpoint===e.endpoint&&e.endpoint_from?c[e.endpoint_from]??"":""}),u=null,v=e.wan_kind==="cgnat"||e.wan_kind==="private"?it("alert","warn",e.wan_kind==="cgnat"?_("Your router has no public address (CGNAT)"):m(_("Your router is behind another router (WAN %s)"),e.wan_ip),e.wan_kind==="cgnat"?_("The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address."):_("Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here."),""):"",M=e.awg_state?.tools&&e.awg_state.handler===!1?bt(_("Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.")):"",x=()=>lo(r.range,e.networks??[],Dt(e.subnet)),h=()=>gn(r.portal_port,e.tcp_taken??[],l()),S=t("div",{class:"dl-wizard"}),z=(C,D={})=>{let F=he(String(r[C]),D);return F.addEventListener("input",()=>{C==="port"||C==="portal_port"?r[C]=F.value.trim()===""?0:Number(F.value):r[C]=F.value.trim(),C==="port"&&i&&(r.portal_port=r.port),C==="portal_port"&&(i=r.portal_port===r.port)}),F},E=()=>{let C=Ho(),D=ge(_("Through the home network"),ye(r.lan_like,_("Internet like a home device"),ee=>{r.lan_like=ee,F()})," "),F=()=>{dom.content(D.querySelector(".dl-sub"),r.lan_like?_("Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access."):No(e.ifname)),r.lan_like?D.after(C):C.remove()},Y=ke("home",_("Internet like a home device"),_("How devices reach the internet"),[D]);return F(),Y},$={id:"server",title:_("Server"),render:()=>t("div",{class:"dl-wizard-groups"},[t("p",{class:"dl-muted"},o?_("One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page."):_("Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.")),ke("router",_("Server"),_("What people see"),[_e(_("Name"),z("name"),()=>Ne(r.name,[],_("Shown to people in their portal and apps.")))]),ke("globe",_("Devices connect to"),_("A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT"),[(()=>{let C=z("endpoint",{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"});return u=_e(_("Public address"),C,p.help),C.addEventListener("input",p.schedule),p.schedule(),u})()]),v,M]),check:()=>{let C=Ne(r.name);if(C.bad)return m(_("Name: %s"),C.text);let D=$t(r.endpoint,r.port);return D.bad?m(_("Public address: %s"),D.text):null}},b={id:"awg",title:"AmneziaWG",render:()=>t("div",{class:"dl-wizard-groups"},[ke("globe",_("Listening"),_("Where devices reach AmneziaWG from the internet"),[_e(_("UDP port"),z("port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),d)]),ke("network",_("Tunnel network"),_("Addresses devices get inside the tunnel"),[(()=>{let C=z("range",{class:"cbi-input-text dl-w-range dl-mono","aria-label":_("First three numbers of the device addresses")});return _e(_("Device addresses"),C,x,t("span",{class:"dl-suffixed"},[C,t("span",{class:"dl-mono"},".x")]))})()]),ke("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[_n(e.awg,r.preset,C=>r.preset=C,void 0,e.awg_state?.tools!==!1)]),o?E():""]),check:()=>{let C=d();if(C.bad)return m(_("UDP port: %s"),C.text);let D=x();return D.bad?m(_("Device addresses: %s"),D.text):null}},k={id:"portal",title:_("Portal"),render:()=>{let C=z("portal_port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),D=_e(_("Listening port"),C,h);D.hidden=!r.portal;let F=Qe([["off",_("Off")],["on",_("On")]],r.portal?"on":"off",{label:_("Personal portal"),onChange:Y=>{r.portal=Y==="on",D.hidden=!r.portal}});return t("div",{class:"dl-wizard-groups"},[E(),ke("link",_("Personal portal"),_("A page where each person adds their own devices with their personal link"),[ge(_("Portal"),F,_("Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.")),D])])},check:()=>{if(!r.portal)return null;let C=h();return C.bad?m(_("Portal port: %s"),C.text):null}},y=()=>[$,b,o?null:k].filter(C=>C!=null),I=e.awg_state,w=I?.missing??[],f=w.length?t("div",{class:"dl-list dl-notices"},[it("shield","bad",_("AmneziaWG isn’t installed"),m(_("The tunnel needs %s. Install the build made for this firmware, then create the server."),new Intl.ListFormat(le(),{type:"conjunction"}).format(w)),N(_("Install"),()=>zn(()=>location.reload()),"positive"))]):I&&!I.loaded?t("div",{class:"dl-list dl-notices"},[it("shield","warn",_("AmneziaWG’s kernel module doesn’t load on this firmware"),_("Try another build in Components, or update OpenWrt. The server can’t start until it loads."),t("a",{class:"cbi-button cbi-button-neutral",href:L.url("admin/network/dawnline/updates")},_("Open Components")))]):"",T=()=>{let C=y();a>=C.length&&(a=C.length-1),dom.content(S,[t("h2",{},o?_("Add a server"):_("Set up Dawnline")),f,t("div",{class:"dl-steps"},C.map((D,F)=>t("span",{class:`dl-step${F===a?" current":F0?N(_("Back"),()=>{a--,T()}):s?N(_("Cancel"),s):"",t("span",{class:"dl-spacer"}),a{let D=C[a].check?.();if(D){q(D,"warning");return}a++,T()},"positive"):N(_("Create server"),async()=>{for(let F of C){let Y=F.check?.();if(Y){q(Y,"warning");return}}let D=await K(()=>H.serverCreate(r.id,r.name,e.ifname,r.port,fn(r.range),r.endpoint,e.mtu,r.preset,r.lan_zone,r.wan_zone,r.lan_like,o?void 0:r.portal,o?void 0:r.portal_port),_("Server created"));D&&(D.network_restart&&q(_("Restarting the network so it knows AmneziaWG: back in a few seconds")),setTimeout(()=>{location.href=Io(D.id)},D.network_restart?1e4:1500))},"positive",{disabled:w.length>0,title:w.length?_("Install AmneziaWG first"):null})])])};return T(),S}};function ft(n){let e={el:n(),refresh(){let o=n();e.el.replaceWith(o),e.el=o}};return e}function Ue(n,e,o,s,r="",a=[]){return t("section",{class:`dl-setsec ${r}`,id:`dl-set-${n}`},[t("div",{class:"dl-setsec-body"},[a.length?t("div",{class:"dl-setsec-head"},[t("h3",{},e),t("span",{class:"dl-spacer"}),...a]):t("h3",{},e),...o]),s.length?t("div",{class:"dl-setsec-foot"},s):""])}function Br(n){let e=n.filter(r=>r.status!=="skip"),o=e.filter(r=>r.status==="error"||r.status==="warn"),s=e.some(r=>r.status==="error")?"error":o.length?"warn":"ok";return{bad:o,worst:s}}function Or(n){let e=n.d.settings,o=n.d.effective,s=n.d.cert,r=ye(o.portal_enabled,_("Enable portal")),a=he(e.portal_port,{placeholder:"8443",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),i=he(e.portal_redirect,{placeholder:_("Show “Not found”"),class:"cbi-input-text dl-mono"}),l=he("",{placeholder:_("vpn.example.com or an IP"),"aria-label":_("Other address")}),d=j=>/^\d{1,3}(\.\d{1,3}){3}$/.test(j),c=[o.portal_host,...o.portal_alt??[]].filter((j,J,ie)=>j&&ie.indexOf(j)===J),p=!!n.portal,u=[],v=j=>{j&&!u.some(J=>J.host===j)&&u.push({host:j,kind:d(j)?"ip":"name",ips:[],here:!1,cloudflare:!1,cert:!1})},M=j=>{u=[...j,...u.filter(J=>!j.some(ie=>ie.host===J.host))],!c.length&&j[0]&&(c=[j[0].host])};n.portal&&M(n.portal.candidates),c.forEach(v);let x=j=>j.kind==="ip"?t("span",{class:"dl-addr-warn"},[g("alert"),_("Plain HTTP: the link and VPN keys travel unencrypted")]):t("span",{class:"dl-sub"},j.cloudflare?_("Behind Cloudflare · often stalls in Russia"):j.ips.length?j.here?j.cert?_("Points at this router · Let’s Encrypt certificate"):_("Points at this router · no certificate yet"):m(_("Points at %s, not this router"),j.ips.join(", ")):p?_("Your address"):_("Checking where it points…")),h=t("div",{class:"dl-addr-opts",role:"group","aria-label":_("Portal addresses")}),S=j=>{c.includes(j)?c.length>1&&(c=c.filter(J=>J!==j)):c=[...c,j],z(),b()},z=()=>dom.content(h,[...u.map(j=>{let J=c.includes(j.host),ie=c[0]===j.host;return t("div",{class:`dl-addr-opt${J?" on":""}`,role:"checkbox","aria-checked":J?"true":"false",tabindex:"0",click:()=>S(j.host),keydown:ve=>{(ve.key===" "||ve.key==="Enter")&&(ve.preventDefault(),S(j.host))}},[t("i",{class:"dl-addr-check"},J?g("check"):""),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono"},j.host),x(j)]),ie?t("span",{class:"dl-pill info"},_("Main")):J?t("button",{type:"button",class:"dl-linkbtn",click:ve=>{ve.stopPropagation(),c=[j.host,...c.filter(R=>R!==j.host)],z(),b()}},_("Make main")):j.cloudflare?t("span",{class:"dl-pill warn"},"Cloudflare"):j.kind==="ip"?t("span",{class:"dl-pill"},"IP"):j.here&&j.cert?t("span",{class:"dl-pill ok"},_("Recommended")):""])}),t("div",{class:"dl-addr-opt other"},[t("i",{class:"dl-addr-check"},g("plus")),l,N(_("Add"),()=>{let j=l.value.trim().toLowerCase();if(!j)return;let J=$t(j);if(J.bad){q(J.text,"warning");return}v(j),c.includes(j)||(c=[...c,j]),l.value="",z(),b()})])]);l.addEventListener("keydown",j=>{j.key==="Enter"&&(j.preventDefault(),l.nextElementSibling?.click())});let E=t("div",{class:"dl-links"}),$=()=>{},b=()=>{$();let j=Number(a.value)||o.portal_port;dom.content(E,c.map((J,ie)=>{let ve=d(J),R=ve?j+1:j,O=`${ve?"http":"https"}://${J}${R===(ve?80:443)?"":`:${R}`}/`;return t("div",{class:"dl-link-row"},[t("span",{class:`dl-link-ic ${ve?"warn":"ok"}`},g(ve?"alert":"lock")),t("span",{class:"dl-mono dl-link-url"},[O,t("b",{},"kamiro-telosu-bavine")]),ie===0?t("span",{class:"dl-pill info"},_("Main")):ve?t("span",{class:"dl-pill warn"},"HTTP"):""])}))};z(),b(),a.addEventListener("input",()=>b());let k={portal:_("Portal running"),portal_dns:_("Points here"),portal_reply:_("Answers reach visitors"),portal_http:_("Plain HTTP"),cert:_("Certificate")},y=n.d.needs??{https:[],acme:[],home:[]},I=j=>{if(!o.portal_enabled)return t("div",{hidden:!0});if(!j)return ke("check",_("Ready to share"),_("The portal’s checks from Health"),[t("p",{class:"dl-muted dl-loading"},_("Running checks…"))]);let J=j.filter(P=>P.status!=="skip");if(!J.length)return t("div",{hidden:!0});let{bad:ie,worst:ve}=Br(j),R=t("div",{class:"dl-ready-details",hidden:!0},J.map(P=>t("div",{class:`dl-ready-item ${P.status}`},[g(P.status==="ok"?"check":"alert"),t("span",{class:"dl-stack"},[t("span",{},P.title),t("span",{class:"dl-sub"},P.detail)])]))),O=t("div",{class:"dl-stack gap8"},[t("div",{class:`dl-ready-sum ${ve}`},[g(ve==="ok"?"check":"alert"),t("span",{class:"dl-stack"},[t("b",{},ve==="ok"?W(J.length,"All %s check passed","All %s checks passed"):m(N_(J.length,"%s of %s check passed","%s of %s checks passed"),V(J.length-ie.length),V(J.length))),ie.length?t("span",{class:"dl-sub"},ie.map(P=>P.detail).join(" ")):t("span",{class:"dl-sub"},_("Links will open for the people you send them to."))]),t("button",{type:"button",class:"dl-linkbtn",click:P=>{R.hidden=!R.hidden,P.currentTarget.textContent=R.hidden?_("Details"):_("Hide")}},_("Details"))]),t("div",{class:"dl-chips-row"},J.map(P=>t("span",{class:`dl-check-chip ${P.status}`,title:P.detail},[g(P.status==="ok"?"check":"alert"),k[P.id]??P.title]))),R]);return ke("check",_("Ready to share"),_("The portal’s checks from Health"),[O])},w=j=>{if(!o.portal_enabled||!j&&!y.https.length)return t("span",{hidden:!0});if(y.https.length)return t("span",{class:"dl-pill bad"},_("Can’t start"));let{worst:J}=Br(j);return t("span",{class:`dl-pill ${J==="ok"?"ok":J==="error"?"bad":"warn"}`},J==="error"?_("Needs attention"):_("Ready"))},f=I(n.portal?.checks??null),T=w(n.portal?.checks??null);n.portalFill=j=>{p=!0,M(j.candidates),z(),b();let J=I(j.checks);f.replaceWith(J),f=J;let ie=w(j.checks);T.replaceWith(ie),T=ie};let C=s&&!s.self_signed&&s.expires?Be(s.expires):"",D=_e(_("Listening port"),a,()=>gn(a.value.trim()===""?o.portal_port:Number(a.value),n.d.tcp_taken??[],c.some(d)));$=D.refresh;let F=_e(_("Unknown links"),i,()=>ws(i.value)),Y=!!(e.portal_cert&&e.portal_key),ee=s?Y?_("Your files"):s.self_signed?_("Self-signed"):"Let’s Encrypt":_("Portal is off"),B=()=>{let j=he(e.portal_cert,{placeholder:"/etc/ssl/…/fullchain.crt"}),J=he(e.portal_key,{placeholder:"/etc/ssl/…/key"});de(_("Use your own certificate"),[t("p",{class:"dl-muted"},_("Paths on the router. Leave both empty to pick a certificate automatically.")),ge(_("Certificate file"),j),ge(_("Key file"),J)],[ue()," ",N(_("Save"),()=>{ce(),n.save({portal_cert:j.value.trim(),portal_key:J.value.trim()},_("Certificate saved"),"portal")},"positive")])},Q=(j,J,ie,ve,R,O)=>it(j,J,ie,ve,N(O,()=>sn(R,y[R],()=>n.reload("portal")),"positive")),ne=y.https.length?Q("lock","bad",_("HTTPS isn’t available on this router"),m(_("The portal needs %s. It can’t start without them."),new Intl.ListFormat(le(),{type:"conjunction"}).format(y.https)),"https",_("Install")):"",fe=y.acme.length&&(!s||s.self_signed)?Q("lock","",_("Free certificate from Let’s Encrypt"),e.portal_host?m(_("ACME isn’t installed. With it the router gets a certificate for %s and browsers stop warning."),e.portal_host):_("ACME isn’t installed. With it the router gets a certificate and browsers stop warning."),"acme",_("Install ACME")):"",se=[t("div",{class:"dl-row"},[g("lock"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},[ee,C?t("span",{class:"dl-faint"},` · ${m(_("until %s"),C)}`):""]),t("span",{class:"dl-sub dl-ellipsis",title:s?.path??""},s?s.self_signed?_("Made by the router: browsers warn until a certificate covers the address."):`${Y?_("Your files"):_("Found automatically")} · ${s.path}`:_("Turn the portal on to see its certificate."))])]),t("div",{class:"dl-row"},[g("file"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},_("Your own files")),t("span",{class:"dl-sub"},Y?`${e.portal_cert} · ${e.portal_key}`:_("Not set: the certificate is picked automatically."))]),Y?N(_("Reset"),()=>n.save({portal_cert:"",portal_key:""},_("Automatic certificate"),"portal"),"negative"):"",N(Y?_("Change"):_("Use files"),B)]),fe];return Ue("portal",_("Personal portal"),[t("span",{class:"dl-muted"},_("A page where each person adds and manages their devices with their personal link.")),ne?t("div",{class:"dl-list"},[ne]):"",ke("network",_("Port"),_("How the portal listens (80 and 443 stay free)"),[D]),ke("edit",_("Appearance"),_("What people see"),[F]),ke("link",_("Addresses"),_("Pick one or more; the first is the main link"),[h,t("div",{class:"dl-stack gap8"},[E,t("span",{class:"dl-sub"},_("Example code; each person gets their own three words."))])]),ke("lock",_("Certificate"),_("Used for HTTPS links"),se),f],[t("span"),N(_("Save"),()=>{let j=je([D,F]);if(j){q(j,"warning");return}return n.save({portal_enabled:He(r)?"1":"0",portal_host:c[0]??"",portal_alt:c.slice(1),portal_port:a.value,portal_redirect:i.value.trim()},_("Saved"),"portal")},"positive")],"",[T,r])}function jr(n){let e=n.d.settings,o=n.d.effective,s=he(e.default_device_limit,{placeholder:"3",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),r=ye(o.hostnames,_("Device hostnames")),a=he(e.domain,{placeholder:"lan",class:"cbi-input-text dl-w-port"}),i=he(e.home_dns_fallback==="none"?"":e.home_dns_fallback||o.home_dns_fallback||"",{placeholder:_("None"),inputmode:"decimal",class:"cbi-input-text dl-w-ip dl-mono"}),l=_e(_("Devices per person"),s,()=>{if(!s.value.trim())return{text:_("The default, 3. Pre-filled when you add someone."),bad:!1};let p=vn(s.value);return p.bad?p:{text:_("Pre-filled when you add someone."),bad:!1}}),d=_e(_("Device hostnames"),a,()=>ys(a.value),t("div",{class:"dl-hostport"},[r,t("span",{class:"dl-faint dl-mono"},"phone.myata."),a])),c=_e(_("Fallback DNS"),i,()=>{let p=ks(i.value);return p.bad?p:{text:m(_("For Home-only devices using home names: %s"),p.text),bad:!1}});return Ue("defaults",_("New people"),[l,d,c],[t("span"),N(_("Save"),()=>{let p=je([l,d,c]);if(p){q(p,"warning");return}return n.save({default_device_limit:s.value,hostnames:He(r)?"1":"0",domain:a.value,home_dns_fallback:i.value},_("Saved"),"defaults")},"positive")])}function Ur(n){let e=n.d.effective,o=ye(e.geo_enabled,_("Locations")),s=t("select",{class:"cbi-input-select"},[t("option",{value:"ipwho.is",selected:e.geo_provider!=="ipapi.co"?"selected":null},m(_("%s (fallback: %s)"),"ipwho.is","ipapi.co")),t("option",{value:"ipapi.co",selected:e.geo_provider==="ipapi.co"?"selected":null},m(_("%s (fallback: %s)"),"ipapi.co","ipwho.is"))]);return Ue("map",_("Map & locations"),[t("div",{class:"dl-setrow head"},[t("span",{class:"dl-muted"},_("Show where people connect from on the Overview and person pages, at city level.")),o]),ge(_("Provider"),s)],[t("span",{class:"dl-sub"},_("The router sends each new client IP to the provider once and caches the city. Map tiles load in your browser from CARTO; people never see the map.")),N(_("Save"),()=>n.save({geo_enabled:He(o)?"1":"0",geo_provider:s.value},_("Saved"),"map"),"positive")])}var yl=()=>[["app","Dawnline"],["amneziawg","AmneziaWG"],["packages",_("System packages")]];function Wr(n){let e=n.d.effective.updates,o=ye(e.check,_("Check automatically"),M=>v(M,He(r))),s=Xe([["6h",_("Every 6 h")],["12h",_("Every 12 h")],["1d",_("Daily")],["7d",_("Weekly")]],e.interval,_("How often")),r=ye(e.auto,_("Install automatically"),M=>v(He(o),M)),a=he(e.time,{placeholder:"04:00",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono","aria-label":_("Time")}),i=Xe([["scheduled",_("At a set time")],["immediate",_("As soon as found")]],e.mode,_("When"),M=>a.hidden=M!=="scheduled");a.hidden=e.mode!=="scheduled";let l=yn(yl(),e.targets,_("Components")),d=ye(e.keep,_("Keep the previous version")),c=ye(e.mirrors,_("GitHub mirrors")),p=ge(_("How often"),s),u=[ge(_("When"),t("div",{class:"dl-hostport"},[i,a]),_("A set time keeps tunnel restarts out of the evening; the run happens within an hour of it.")),ge(_("Components"),l.node,_("AmneziaWG is off by default: a new kernel module restarts every tunnel."))],v=(M,x)=>{p.hidden=!M;for(let h of u)h.hidden=!x};return v(e.check,e.auto),Ue("updates",_("Updates"),[t("span",{class:"dl-muted"},_("How Dawnline keeps its components current. Every Dawnline update makes a backup of the settings first.")),ge(_("Check automatically"),o,_("Looks for new versions in the background; Components shows what it found and the service log names it.")),p,ge(_("Install automatically"),r,_("Downloads and installs new versions of the components below.")),...u,ge(_("Keep the previous version"),d,_("Saves the replaced Dawnline or AmneziaWG package on flash, so Roll back works without internet. Under 1 MB.")),ge(_("GitHub mirrors"),c,_("When GitHub is unreachable, download through mirrors. Checksums are still verified."))],[t("span",{class:"dl-sub"},_("Run a check or an update by hand in Components.")),N(_("Save"),()=>{if(i.value==="scheduled"){let M=_s(a.value);if(M.bad){q(m(_("Time: %s"),M.text),"warning");return}}return n.save({update_check:He(o)?"1":"0",update_interval:s.value,update_auto:He(r)?"1":"0",update_mode:i.value,update_time:a.value.trim(),update_targets:l.value(),update_keep:He(d)?"1":"0",update_mirrors:He(c)?"1":"0"},_("Saved"),"updates")},"positive")])}function Gr(n){let e=n.d.logs,o=e.policy,s=Xe([["7",W(7,"%s day","%s days")],["30",W(30,"%s day","%s days")],["90",W(90,"%s day","%s days")],["365",W(1,"%s year","%s years")],["0",_("No limit","retention")]],String(o.keep_days),_("Keep activity")),r=Xe([["500",V(500)],["2000",V(2e3)],["5000",V(5e3)],["20000",V(2e4)]],String(o.max),_("Maximum events")),a=Xe([["10min",_("Every 10 min")],["hourly",_("Hourly")],["off",_("Memory only")]],o.persist,_("Save to flash")),i=Xe([["31",W(1,"%s month","%s months")],["62",W(2,"%s month","%s months")],["180",W(6,"%s month","%s months")],["365",W(1,"%s year","%s years")],["730",W(2,"%s year","%s years")]],String(o.usage_days),_("Daily traffic")),l=Xe([["12",W(1,"%s year","%s years")],["24",W(2,"%s year","%s years")],["60",W(5,"%s year","%s years")],["120",W(10,"%s year","%s years")]],String(o.usage_months),_("Monthly traffic")),d=yn(Ht.map(v=>[v,t("span",{title:Cs(v)},[Ke(v)," ",t("span",{class:"dl-faint dl-opt-note"},V(e.by_category[v]??0))])]),o.categories,_("Record")),c=e.oldest?Be(new Date(e.oldest*1e3)):"",p=(v,M,x,h)=>t("div",{class:"dl-row"},[g(v),t("span",{class:"dl-row-main dl-stack"},[t("b",{},M),t("span",{class:"dl-sub"},x)]),...h]),u=v=>N(v.toUpperCase(),async()=>{let[M,x]=await Promise.all([H.status(1),H.events(2e4)]);Ze(M,x.events,v)},"neutral",{title:m(_("Download the log as %s"),v.toUpperCase())});return Ue("logs",_("Logs & history"),[t("p",{class:"dl-muted"},wn(o)),ge(_("Keep activity"),s,_("Older events are removed automatically.")),ge(_("Maximum size"),r,_("Newest events are kept when the log is full.")),ge(_("Record"),d.node,_("Switched-off categories are not logged from now on.")),ge(_("Save to flash"),a,_("The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot.")),ge(_("Daily traffic"),i,_("Per-day history behind the charts.")),ge(_("Monthly traffic"),l,_("Per-month totals; data limits use the current month.")),t("h4",{class:"dl-setsub"},_("Stored data")),t("div",{class:"dl-list"},[p("activity",_("Activity log"),e.events?`${m(_("%s since %s"),W(e.events,"%s event","%s events"),c)} · ${o.persist==="off"?m(_("%s in memory"),Tt(e.log_ram)):m(_("%s in memory, %s on flash"),Tt(e.log_ram),Tt(e.log_flash))}`:_("Empty"),[u("csv"),u("json"),N(_("Clear"),()=>lt(_("Clear activity"),_("Removes events from the log on the router."),{},()=>n.reload("logs")),"negative")]),p("chart",_("Traffic history"),e.usage_days?`${m(_("%s since %s"),W(e.usage_days,"%s day","%s days"),Be(e.usage_since))} · ${m(_("%s on flash"),Tt(e.usage_flash))}`:_("Empty"),[N(_("Reset"),()=>zt("all","","",()=>setTimeout(()=>n.reload("logs"),300)),"negative")]),p("pin",_("Location cache"),`${W(n.d.geo_cached,"%s address","%s addresses")} · ${m(_("%s on flash"),Tt(e.geo_flash))}`,[N(_("Clear"),async()=>{await K(()=>H.geoClear(),_("Location cache cleared"))&&await n.reload("logs")},"negative")])])],[t("span",{class:"dl-sub"},_("Clear one person or device from their own page.")),N(_("Save"),()=>n.save({log_keep_days:s.value,log_max:r.value,log_persist:a.value,usage_keep_days:i.value,usage_keep_months:l.value,log_category:d.value()},_("Saved"),"logs"),"positive")])}function kl(n){return{manual:_("Manual"),auto:_("Nightly"),"pre-restore":_("Before restore"),"pre-import":_("Before import"),"pre-delete":_("Before removing a server"),"pre-update":_("Before update")}[n]??n}var qr=3;function Bo(n){let e=new Date(n*1e3),o=e.toLocaleTimeString(le(),{hour:"2-digit",minute:"2-digit"}),s=Math.round((new Date(new Date().toDateString()).getTime()-new Date(e.toDateString()).getTime())/864e5);return s===0?m(_("Today, %s"),o):s===1?m(_("Yesterday, %s"),o):`${e.toLocaleDateString(le(),{day:"numeric",month:"short"})}, ${o}`}async function _l(n){let e=await K(()=>H.backupRead(n.name));if(!e)return;let o=atob(e.data),s=new Uint8Array(o.length);for(let a=0;a_l(n),"neutral","dl-icon-only"),Pe("more",_("More"),o=>Te(o.currentTarget,[{label:_("Restore"),icon:g("reset"),run:async()=>{await me(_("Restore this backup?"),m(_("Everything returns to %s. The current state is backed up first."),Bo(n.created)),_("Restore"),!0)&&await K(()=>H.backupRestore(n.name),_("Restored"))&&e(!0)}},{label:_("Delete"),icon:g("trash"),danger:!0,run:async()=>{await me(_("Delete this backup?"),m(_("The backup from %s is removed from the router."),Bo(n.created)),_("Delete"),!0)&&await K(()=>H.backupDelete(n.name),_("Backup deleted"))&&e()}}]),"neutral","dl-icon-only")])])}function Kr(n,e){let o=n.slice(0,qr).map(d=>Fr(d,e)),s=n.slice(qr),r=n.length?t("div",{class:"dl-list"},[...o,s.length?t("details",{class:"dl-bk-older"},[t("summary",{},[g("chevron"),W(s.length,"%s older backup","%s older backups")]),...s.map(d=>Fr(d,e))]):""]):t("div",{class:"dl-list"},[t("div",{class:"dl-row dl-muted"},_("No backups yet."))]),a=N(_("Restore from file"),async()=>{let d=await no(".tar.gz,.tgz,application/gzip","base64");if(!d)return;await me(_("Restore from file?"),m(_("Replace the current Dawnline configuration with %s? The current state is backed up first."),d.name),_("Restore"),!0)&&await K(()=>H.backupUpload(d.data),_("Restored"))&&e(!0)}),i=N(_("Export JSON"),async()=>{let d=await K(()=>H.exportJson());d&&Ae(`dawnline-export-${new Date().toISOString().slice(0,10)}.json`,JSON.stringify(d,null,2),"application/json")}),l=N(_("Import JSON"),async()=>{let d=await no(".json,application/json","text");if(!d)return;let c;try{c=JSON.parse(d.data)}catch{q(_("Not a JSON file."),"error");return}await me(_("Import?"),_("This replaces the whole Dawnline configuration on this router. The current state is backed up first."),_("Import"),!0)&&await K(()=>H.importJson(c),_("Imported"))&&e(!0)});return t("section",{class:"dl-setsec",id:"dl-set-backups"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-setsec-head"},[t("div",{class:"dl-stack"},[t("h3",{},_("Backups")),t("span",{class:"dl-sub"},_("Nightly when something changed, and before every restore, import or update. The last 10 are kept."))]),t("span",{class:"dl-spacer"}),N([g("plus")," ",_("Back up now")],async()=>{await K(()=>H.backupCreate(),_("Backup created"))&&e()},"positive")]),r]),t("div",{class:"dl-setsec-foot"},[t("span",{class:"dl-sub"},_("Backups contain private keys: keep downloads safe. JSON moves everything except usage history to another router.")),t("span",{class:"dl-row-actions dl-bk-actions"},[a,i,l])])])}var Oo="remove";function Cl(){let n=he("",{placeholder:Oo}),e=N(_("Remove Dawnline"),async()=>{await K(()=>H.uninstall(n.value.trim()),_("Dawnline removed"))&&(ce(),setTimeout(()=>location.reload(),800))},"negative",{disabled:!0});n.addEventListener("input",()=>{e.disabled=n.value.trim()!==Oo}),de(_("Remove Dawnline?"),[t("p",{},m(_("Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “%s” to confirm."),Oo)),n],[ue()," ",e])}function Vr(){return Ue("danger",_("Remove Dawnline from this router"),[t("p",{class:"dl-muted"},_("Deletes the tunnel, firewall rules, access table and hostnames Dawnline created, and stops the service. People and keys are kept in a backup."))],[t("span"),N(_("Remove"),()=>Cl(),"negative")],"danger")}var Un=class{constructor(){this.root=t("div",{class:"dl-settings-main"});this.backups=[];this.portal=null;this.portalSeq=0;this.cards={}}load(){return H.settingsGet()}render(e){this.d=e,this.cards={portal:ft(()=>Or(this)),defaults:ft(()=>jr(this)),map:ft(()=>Ur(this)),updates:ft(()=>Wr(this)),logs:ft(()=>Gr(this)),backups:ft(()=>Kr(this.backups,r=>this.loadBackups(r))),danger:ft(()=>Vr())};let o=["portal","defaults","map","updates","logs","backups","danger"];dom.content(this.root,o.map(r=>this.cards[r].el)),this.loadBackups().then(()=>{new URLSearchParams(location.search).get("section")==="backups"&&document.getElementById("dl-set-backups")?.scrollIntoView({block:"start"})}),this.loadPortal();let s=new URLSearchParams(location.search).get("section");return s&&s!=="backups"&&requestAnimationFrame(()=>document.getElementById(`dl-set-${s}`)?.scrollIntoView({block:"start"})),t("div",{},[t("div",{class:"dl-pagehead"},[t("h2",{class:"dl-h1"},_("Settings"))]),this.root])}async save(e,o,s){let r=await K(()=>H.settingsUpdate(e),o);r&&(this.d=r,this.cards[s].refresh(),s==="portal"&&this.loadPortal())}async loadPortal(){let e=++this.portalSeq,o=await H.portalInfo().catch(()=>null);e===this.portalSeq&&(this.portal=o??this.portal??{candidates:[],checks:[]},this.portalFill?.(this.portal))}async loadBackups(e=!1){e&&await this.reload();let o=await H.backupList().catch(()=>null);o&&(this.backups=o.backups,this.cards.backups?.refresh())}async reload(e){let o=await H.settingsGet().catch(()=>null);if(o){if(this.d=o,e)this.cards[e].refresh();else for(let s of Object.values(this.cards))s.refresh();(!e||e==="portal")&&this.loadPortal()}}};function Yr(n,e=!1){return n&&(e?/^https?:\/\//i:/^https:\/\//i).test(n)?n:null}function Jr(n){let e=[],o=l=>{let d=[],c=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\((https?:\/\/[^)\s]+)\))|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?])/g,p=0;for(let u;u=c.exec(l);)u.index>p&&d.push(l.slice(p,u.index)),u[1]?d.push(t("code",{},u[1].slice(1,-1))):u[2]?d.push(t("b",{},u[2].slice(2,-2))):u[3]?d.push(t("a",{href:u[4],target:"_blank",rel:"noopener"},u[3].replace(/^\[|\]\(.*$/g,""))):u[5]&&d.push(t("a",{href:u[5],target:"_blank",rel:"noopener"},u[5].replace(/^https?:\/\/(github\.com\/)?/,""))),p=u.index+u[0].length;return p{r.length&&e.push(t("p",{},o(r.join(" ")))),r=[],s=null};for(let l of n.replace(/\r/g,"").split(` -`)){let d=l.trimEnd();if(a){/^```/.test(d.trim())?(e.push(t("pre",{},a.join(` -`))),a=null):a.push(l);continue}if(/^```/.test(d.trim())){i(),a=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(i(),e.push(t("h5",{},o(c[2])))):p?(r.length&&i(),s||(s=t("ul",{}),e.push(s)),s.appendChild(t("li",{},o(p[1])))):d.trim()?(s&&(s=null),r.push(d.trim())):i()}return a&&e.push(t("pre",{},a.join(` -`))),i(),e}function Zr(n){let e=[],o=!1;for(let s of n.replace(/\r/g,"").split(` +var va=Object.create;var ds=Object.defineProperty;var ba=Object.getOwnPropertyDescriptor;var xa=Object.getOwnPropertyNames;var wa=Object.getPrototypeOf,ya=Object.prototype.hasOwnProperty;var ka=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var _a=(t,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xa(e))!ya.call(t,r)&&r!==o&&ds(t,r,{get:()=>e[r],enumerable:!(s=ba(e,r))||s.enumerable});return t};var Ca=(t,e,o)=>(o=t!=null?va(wa(t)):{},_a(e||!t||!t.__esModule?ds(o,"default",{value:t,enumerable:!0}):o,t));var _s=ka((ys,ks)=>{"use strict";var ws=(function(){var t=function(P,R){var w=236,k=17,y=P,O=o[R],b=null,f=0,T=null,C=[],A={},K=function(z,$){f=y*4+17,b=(function(E){for(var I=new Array(E),D=0;D=7&&te(z),T==null&&(T=ne(y,O,C)),ke(T,$)},Y=function(z,$){for(var E=-1;E<=7;E+=1)if(!(z+E<=-1||f<=z+E))for(var I=-1;I<=7;I+=1)$+I<=-1||f<=$+I||(0<=E&&E<=6&&(I==0||I==6)||0<=I&&I<=6&&(E==0||E==6)||2<=E&&E<=4&&2<=I&&I<=4?b[z+E][$+I]=!0:b[z+E][$+I]=!1)},Q=function(){for(var z=0,$=0,E=0;E<8;E+=1){K(!0,E);var I=r.getLostPoint(A);(E==0||z>I)&&(z=I,$=E)}return $},j=function(){for(var z=8;z>E&1)==1;b[Math.floor(E/3)][E%3+f-8-3]=I}for(var E=0;E<18;E+=1){var I=!z&&($>>E&1)==1;b[E%3+f-8-3][Math.floor(E/3)]=I}},me=function(z,$){for(var E=O<<3|$,I=r.getBCHTypeInfo(E),D=0;D<15;D+=1){var W=!z&&(I>>D&1)==1;D<6?b[D][8]=W:D<8?b[D+1][8]=W:b[f-15+D][8]=W}for(var D=0;D<15;D+=1){var W=!z&&(I>>D&1)==1;D<8?b[8][f-D-1]=W:D<9?b[8][15-D-1+1]=W:b[8][15-D-1]=W}b[f-8][8]=!z},ke=function(z,$){for(var E=-1,I=f-1,D=7,W=0,ee=r.getMaskFunction($),X=f-1;X>0;X-=2)for(X==6&&(X-=1);;){for(var ve=0;ve<2;ve+=1)if(b[I][X-ve]==null){var Le=!1;W>>D&1)==1);var re=ee(I,X-ve);re&&(Le=!Le),b[I][X-ve]=Le,D-=1,D==-1&&(W+=1,D=7)}if(I+=E,I<0||f<=I){I-=E,E=-E;break}}},U=function(z,$){for(var E=0,I=0,D=0,W=new Array($.length),ee=new Array($.length),X=0;X<$.length;X+=1){var ve=$[X].dataCount,Le=$[X].totalCount-ve;I=Math.max(I,ve),D=Math.max(D,Le),W[X]=new Array(ve);for(var re=0;re=0?is.getAt(as):0}}for(var ls=0,re=0;re<$.length;re+=1)ls+=$[re].totalCount;for(var ao=new Array(ls),hn=0,re=0;reX*8)throw"code length overflow. ("+D.getLengthInBits()+">"+X*8+")";for(D.getLengthInBits()+4<=X*8&&D.put(0,4);D.getLengthInBits()%8!=0;)D.putBit(!1);for(;!(D.getLengthInBits()>=X*8||(D.put(w,8),D.getLengthInBits()>=X*8));)D.put(k,8);return U(D,I)};A.addData=function(z,$){$=$||"Byte";var E=null;switch($){case"Numeric":E=c(z);break;case"Alphanumeric":E=p(z);break;case"Byte":E=u(z);break;case"Kanji":E=g(z);break;default:throw"mode:"+$}C.push(E),T=null},A.isDark=function(z,$){if(z<0||f<=z||$<0||f<=$)throw z+","+$;return b[z][$]},A.getModuleCount=function(){return f},A.make=function(){if(y<1){for(var z=1;z<40;z++){for(var $=l.getRSBlocks(z,O),E=d(),I=0;I"u"?z*4:$;var E="";E+='";for(var D=0;D';E+=""}return E+="",E+="
",E},A.createSvgTag=function(z,$,E,I){var D={};typeof arguments[0]=="object"&&(D=arguments[0],z=D.cellSize,$=D.margin,E=D.alt,I=D.title),z=z||2,$=typeof $>"u"?z*4:$,E=typeof E=="string"?{text:E}:E||{},E.text=E.text||null,E.id=E.text?E.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 W=A.getModuleCount()*z+$*2,ee,X,ve,Le,re="",ze;for(ze="l"+z+",0 0,"+z+" -"+z+",0 0,-"+z+"z ",re+=''+he(I.text)+"":"",re+=E.text?''+he(E.text)+"":"",re+='',re+='"u"?z*4:$;var E=A.getModuleCount()*z+$*2,I=$,D=E-$;return B(E,E,function(W,ee){if(I<=W&&W"u"?z*4:$;var I=A.getModuleCount()*z+$*2,D="";return D+="",D};var he=function(z){for(var $="",E=0;E":$+=">";break;case"&":$+="&";break;case'"':$+=""";break;default:$+=I;break}}return $},fe=function(z){var $=1;z=typeof z>"u"?$*2:z;var E=A.getModuleCount()*$+z*2,I=z,D=E-z,W,ee,X,ve,Le,re={"██":"█","█ ":"▀"," █":"▄"," ":" "},ze={"██":"▀","█ ":"▀"," █":" "," ":" "},Re="";for(W=0;W=D?ze[Le]:re[Le];Re+=` +`}return E%2&&z>0?Re.substring(0,Re.length-E-1)+Array(E+1).join("▀"):Re.substring(0,Re.length-1)};return A.createASCII=function(z,$){if(z=z||1,z<2)return fe($);z-=1,$=typeof $>"u"?z*2:$;var E=A.getModuleCount()*z+$*2,I=$,D=E-$,W,ee,X,ve,Le=Array(z+1).join("██"),re=Array(z+1).join(" "),ze="",Re="";for(W=0;W>>8),O.push(T&255)):O.push(k)}}return O}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var P=[[],[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]],R=1335,w=7973,k=21522,y={},O=function(b){for(var f=0;b!=0;)f+=1,b>>>=1;return f};return y.getBCHTypeInfo=function(b){for(var f=b<<10;O(f)-O(R)>=0;)f^=R<=0;)f^=w<5&&(T+=3+K-5)}for(var C=0;C=256;)y-=255;return P[y]},k})();function a(P,R){if(typeof P.length>"u")throw P.length+"/"+R;var w=(function(){for(var y=0;y"u")throw"bad rs block @ typeNumber:"+y+"/errorCorrectionLevel:"+O;for(var f=b.length/3,T=[],C=0;C>>7-k%8&1)==1},w.put=function(k,y){for(var O=0;O>>y-O-1&1)==1)},w.getLengthInBits=function(){return R},w.putBit=function(k){var y=Math.floor(R/8);P.length<=y&&P.push(0),k&&(P[y]|=128>>>R%8),R+=1},w},c=function(P){var R=e.MODE_NUMBER,w=P,k={};k.getMode=function(){return R},k.getLength=function(b){return w.length},k.write=function(b){for(var f=w,T=0;T+2>>8&255)*192+(C&255),b.put(C,13),T+=2}if(T>>8)},R.writeBytes=function(w,k,y){k=k||0,y=y||w.length;for(var O=0;O0&&(w+=","),w+=P[k];return w+="]",w},R},x=function(){var P=0,R=0,w=0,k="",y={},O=function(f){k+=String.fromCharCode(b(f&63))},b=function(f){if(!(f<0)){if(f<26)return 65+f;if(f<52)return 97+(f-26);if(f<62)return 48+(f-52);if(f==62)return 43;if(f==63)return 47}throw"n:"+f};return y.writeByte=function(f){for(P=P<<8|f&255,R+=8,w+=1;R>=6;)O(P>>>R-6),R-=6},y.flush=function(){if(R>0&&(O(P<<6-R),P=0,R=0),w%3!=0)for(var f=3-w%3,T=0;T=R.length){if(y==0)return-1;throw"unexpected end of file./"+y}var f=R.charAt(w);if(w+=1,f=="=")return y=0,-1;if(f.match(/^\s$/))continue;k=k<<6|b(f.charCodeAt(0)),y+=6}var T=k>>>y-8&255;return y-=8,T};var b=function(f){if(65<=f&&f<=90)return f-65;if(97<=f&&f<=122)return f-97+26;if(48<=f&&f<=57)return f-48+52;if(f==43)return 62;if(f==47)return 63;throw"c:"+f};return O},S=function(P,R){var w=P,k=R,y=new Array(P*R),O={};O.setPixel=function(C,A,K){y[A*w+C]=K},O.write=function(C){C.writeString("GIF87a"),C.writeShort(w),C.writeShort(k),C.writeByte(128),C.writeByte(0),C.writeByte(0),C.writeByte(0),C.writeByte(0),C.writeByte(0),C.writeByte(255),C.writeByte(255),C.writeByte(255),C.writeString(","),C.writeShort(0),C.writeShort(0),C.writeShort(w),C.writeShort(k),C.writeByte(0);var A=2,K=f(A);C.writeByte(A);for(var Y=0;K.length-Y>255;)C.writeByte(255),C.writeBytes(K,Y,255),Y+=255;C.writeByte(K.length-Y),C.writeBytes(K,Y,K.length-Y),C.writeByte(0),C.writeString(";")};var b=function(C){var A=C,K=0,Y=0,Q={};return Q.write=function(j,Z){if(j>>>Z)throw"length over";for(;K+Z>=8;)A.writeByte(255&(j<>>=8-K,Y=0,K=0;Y=j<0&&A.writeByte(Y)},Q},f=function(C){for(var A=1<>6,128|i&63):i<55296||i>=57344?s.push(224|i>>12,128|i>>6&63,128|i&63):(r++,i=65536+((i&1023)<<10|o.charCodeAt(r)&1023),s.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}return s}return e(t)}})();(function(t){typeof define=="function"&&define.amd?define([],t):typeof ys=="object"&&(ks.exports=t())})(function(){return ws})});function lo(t,e){return t==null||t===!1||t===""||(Array.isArray(t)?t.forEach(o=>lo(o,e)):e.push(t instanceof Node?t:String(t))),e}function n(t,e,o){let s=window.E,r=e!=null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Node);return!r&&o===void 0?s(t,{},lo(e,[])):s(t,r?e:{},lo(o,[]))}var cs={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 Mt(t,e="dl-icon"){let o=cs[t]??cs.phone;return``}function v(t,e="dl-icon"){let o=document.createElement("span");return o.className="dl-icon-wrap",o.innerHTML=Mt(t,e),o}function F(t,e="info",o=0){let s=document.querySelector(".dl-toasts");s||(s=n("div",{class:"dl-toasts dl-root",role:"status","aria-live":"polite"}),document.body.appendChild(s));let r=e==="error"?"x":e==="warning"?"alert":e==="success"?"check":null,i=()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),200)},a=n("div",{class:`dl-toast ${e}`},[r?v(r):"",n("span",{},t),e==="error"?n("button",{type:"button","aria-label":_("Close"),click:i},v("x")):""]);s.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(i,o||(e==="error"?8e3:e==="warning"?5e3:2600))}function _e(t){return t instanceof Error?t.message:String(t)}async function q(t,e){try{let o=await t();return e&&F(e,"success",3500),o}catch(o){F(_e(o),"error",1e4);return}}function ps(t){try{let e=t();e&&typeof e.then=="function"&&e.catch(o=>F(_e(o),"error"))}catch(e){F(_e(e),"error")}}function co(){return(typeof document>"u"?"":document.documentElement.lang)||"en"}function ie(){let t=co();return t==="en"?"en-GB":t}function m(t,...e){let o=0;return t.replace(/%([%sd])/g,(s,r)=>r==="%"?"%":String(e[o++]??""))}function V(t,e){return t.toLocaleString(ie(),e===void 0?void 0:{minimumFractionDigits:e,maximumFractionDigits:e})}function G(t,e,o){return m(N_(t,e,o),V(t))}function oe(t,...e){let o=0;return t.split(/(%[%sd])/).filter(Boolean).map(s=>s==="%%"?"%":s==="%s"||s==="%d"?e[o++]:s)}var po=t=>_(t);function us(t){if(t&&typeof t=="object"){if(typeof t.error=="string")throw new Error(t.error);typeof t.warning=="string"&&t.warning&&F(t.warning,"warning",12e3)}return t}function J(t,e=[]){let o=rpc.declare({object:"luci.dawnline",method:t,params:[...e,"lang"]});return async(...s)=>us(await o(...e.map((r,i)=>s[i]),co()))}var La=J("logs_clear",["person","device","category","older_days"]),Ma=(t={})=>La(t.person??"",t.device??"",t.category??"",t.older_days??""),Ea=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 Ta(t,e){let s=[t,...["name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode"].map(r=>e[r]),e.paused,e.services,e.circle,e.home_nets,e.server];return us(await Ea(...s))}var Sa=J("status",["days"]),Pa=J("device_update",["id","name","disabled","mtu","keepalive"]),$a=(t,e,o,s={})=>Pa(t,e,o,s.mtu,s.keepalive),N={rev:J("rev"),meter:J("meter",["since"]),personUpdate:Ta,settingsGet:J("settings_get"),portalInfo:J("portal_info"),settingsUpdate:J("settings_update",["values"]),serviceSet:J("service_set",["id","name","address","ports"]),serviceDelete:J("service_delete",["id"]),geoClear:J("geo_clear"),events:J("events",["limit","person","since"]),logsClear:Ma,interfaces:J("interfaces",["id"]),serverInterfaces:J("server_interfaces",["id","auto_wan","wan_device","auto_lan","lan_devices","lan_like","device_mesh","mesh"]),circleSet:J("circle_set",["id","server","name","color","members"]),circleDelete:J("circle_delete",["id"]),accessCheck:J("access_check",["from","to"]),homeHosts:J("home_hosts",["id"]),usageClear:J("usage_clear",["scope","id"]),uninstall:J("uninstall",["confirm"]),status:Sa,setupDefaults:J("setup_defaults"),serverCreate:J("server_create",["id","name","ifname","port","subnet","endpoint","mtu","preset","lan_zone","wan_zone","lan_like","portal_enabled","portal_port"]),serverObfuscation:J("server_obfuscation",["id","preset"]),serverUpdate:J("server_update",["id","values"]),serverPorts:J("server_ports",["id"]),endpointProbe:J("endpoint_probe",["host","id","port"]),serverDelete:J("server_delete",["id"]),personLinks:J("person_links",["id"]),personCreate:J("person_create",["name","slug","server","access","device_limit","expires","quota_gb","quota_period"]),personPause:J("person_pause",["id","paused"]),personRegen:J("person_regen",["id","remove"]),personDelete:J("person_delete",["id"]),personUsage:J("person_usage",["id","days"]),deviceCreate:J("device_create",["person","name","kind","lan_bypass"]),deviceConfig:J("device_config",["id","issue"]),deviceUpdate:$a,deviceDelete:J("device_delete",["id"]),deviceRotate:J("device_rotate",["id"]),apply:J("apply"),health:J("health"),healthFix:J("health_fix",["id"]),serviceLog:J("service_log"),serviceLogClear:J("service_log_clear",["older_days"]),backupList:J("backup_list"),backupCreate:J("backup_create"),backupRestore:J("backup_restore",["name"]),backupDelete:J("backup_delete",["name"]),backupRead:J("backup_read",["name"]),backupUpload:J("backup_upload",["data"]),exportJson:J("export"),importJson:J("import",["data"]),updatesStatus:J("updates_status"),updatesRun:J("updates_run",["what"]),updatesReleases:J("updates_releases",["page"]),updatesNotes:J("updates_notes",["component","tag","build"]),updatesChanges:J("updates_changes",["from","to"])};function H(t,e,o="neutral",s={}){let{disabled:r,...i}=s,a=n("button",{class:`cbi-button cbi-button-${o}`,type:"button",...i,click:async l=>{if(l.preventDefault(),l.stopPropagation(),!a.disabled){a.disabled=!0,a.classList.add("spinning");try{await e(l)}catch(d){F(_e(d),"error")}finally{a.disabled=!1,a.classList.remove("spinning")}}}},t);return a.disabled=!!r,a}function Pe(t,e,o,s="neutral",r=""){return H([v(t),n("span",{class:"dl-btn-label"},e)],o,s,{title:e,class:`cbi-button cbi-button-${s} dl-icon-btn ${r}`.trim()})}function Ee(t){return document.addEventListener("luci-navigate",t),()=>document.removeEventListener("luci-navigate",t)}var Et=null;function uo(t=!1){let e=Et;Et=null,e?.(t)}function ae(t,e,o,s=""){uo();let r=n("div",{class:`dl-modal ${s}`},e),i=n("div",{class:"button-row"},o);r.addEventListener("keydown",a=>{if(a.key==="Escape"){a.preventDefault(),a.stopPropagation(),le();return}if(a.key!=="Enter"||a.shiftKey||a.ctrlKey||a.metaKey||a.altKey)return;let l=a.target;if(!l||["TEXTAREA","BUTTON","SELECT","A"].includes(l.tagName))return;let d=i.querySelector(".cbi-button-positive");!d||d.disabled||(a.preventDefault(),d.click())}),ui.showModal(t,[r,i])}function le(){uo(),ui.hideModal()}function de(t=_("Cancel"),e=!1){return n("button",{class:`cbi-button ${e?"cbi-button-negative":"cbi-button-neutral"}`,type:"button",click:le},t)}function pe(t,e,o=_("Confirm"),s=!1){return new Promise(r=>{ae(t,e,[de()," ",n("button",{class:`cbi-button ${s?"cbi-button-negative":"cbi-button-positive"}`,type:"button",click:()=>{let i=Et;Et=null,ui.hideModal(),i?.(!0)}},o)]),Et=r})}Ee(()=>{Et&&(uo(),ui.hideModal())});async function xe(t,e=_("Copied to clipboard"),o=!1){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{let s=n("textarea",{style:"position:fixed;opacity:0"},t);document.body.appendChild(s),s.select();let r=document.execCommand("copy");if(s.remove(),!r)throw new Error(_("Copying is blocked here. Select the text and copy it by hand."))}return F(e,"success",2500),!0}catch(s){return o||F(_e(s),"error"),!1}}function Ae(t,e,o="text/plain"){let s=globalThis,r=typeof e=="string"?new s.Blob([e],{type:o}):e,i=URL.createObjectURL(r),a=n("a",{href:i,download:t,style:"display:none"});document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(i),a.remove()},1e3)}function mo(t,e){return new Promise(o=>{let s=n("input",{type:"file",accept:t,style:"display:none"});s.addEventListener("cancel",()=>{s.remove(),o(null)}),s.addEventListener("change",()=>{let r=s.files?.[0];if(s.remove(),!r)return o(null);let i=new FileReader;i.onload=()=>{let a=String(i.result??"");o({name:r.name,data:e==="base64"?a.replace(/^data:[^,]*,/,""):a})},i.onerror=()=>o(null),e==="base64"?i.readAsDataURL(r):i.readAsText(r)}),document.body.appendChild(s),s.click()})}function Te(t,e){let o=document.querySelector(".dl-dd");if(o&&(o.dlClose?o.dlClose():o.remove(),o.dlAnchor===t))return;let s=n("div",{class:"dl-dd dl-root",role:"menu"},e.map(u=>u?n("button",{type:"button",role:"menuitem",class:u.danger?"danger":u.warn?"warn":"",click:()=>{p(),ps(u.run)}},[u.icon??"",n("span",{},u.label)]):n("hr")));document.body.appendChild(s);let r=t.getBoundingClientRect(),i=s.offsetWidth,a=s.offsetHeight;s.style.top=`${r.bottom+6+a>window.innerHeight-8&&r.top-6-a>8?r.top-6-a:r.bottom+6}px`,s.style.left=`${Math.max(8,Math.min(r.right-i,window.innerWidth-i-8))}px`;let l=u=>{!s.contains(u.target)&&!t.contains(u.target)&&p()},d=u=>{if(u.key==="Escape"||u.key==="Tab")return p();let g=[...s.querySelectorAll("button:not([disabled])")];if(!g.length||!["ArrowDown","ArrowUp","Home","End"].includes(u.key))return;u.preventDefault();let M=g.indexOf(document.activeElement),x=u.key==="Home"?0:u.key==="End"?g.length-1:u.key==="ArrowDown"?(M+1)%g.length:(M-1+g.length)%g.length;g[x].focus({preventScroll:!0})},c=Ee(p);s.dlAnchor=t,s.dlClose=p;function p(){s.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)}),s.querySelector("button")?.focus({preventScroll:!0})}var vt=null,ot=null,ho=0;function Tt(){vt&&(vt.style.display="none"),ot=null,clearInterval(ho),ho=0}function we(t,e){let o=s=>{vt??(vt=document.body.appendChild(n("div",{class:"dl-tip dl-tip-float dl-root"}))),vt.replaceChildren(...e().map(r=>typeof r=="string"?document.createTextNode(r):r)),vt.style.display="",vt.style.left=`${s.clientX}px`,vt.style.top=`${s.clientY-10}px`,ot=t,ho||(ho=window.setInterval(()=>{(!ot?.isConnected||!ot.getClientRects().length)&&Tt()},400))};t.addEventListener("mouseenter",o),t.addEventListener("mousemove",o),t.addEventListener("mouseleave",Tt),t.addEventListener("pointerup",s=>{s.pointerType!=="mouse"&&(ot===t?Tt():o(s))})}Ee(Tt);window.addEventListener("scroll",()=>ot&&Tt(),{capture:!0,passive:!0});document.addEventListener("pointerdown",t=>{ot&&!ot.contains(t.target)&&Tt()},!0);function Da(t,e,o){let s=0;for(;t>=o&&s=100||s===0?V(Math.round(t)):V(t,1)} ${e[s]}`}function se(t){return Da(!t||t<0?0:t,[_("B"),_("KB"),_("MB"),_("GB"),_("TB")],1024)}function We(t){let e=t*8,o=[_("bit/s"),_("kbit/s"),_("Mbit/s"),_("Gbit/s")];if(e<1e3)return`${V(Math.round(e))} ${o[0]}`;let s=e<1e6?1:e<1e9?2:3,r=e/1e3**s;return`${V(r,s===3||r<10?1:0)} ${o[s]}`}function ce(t,e=Date.now()/1e3){if(!t)return _("never");let o=Math.max(0,Math.round(e-t));return o<60?_("just now"):o<3600?m(_("%s min ago"),Math.floor(o/60)):o<86400?m(_("%s h ago"),Math.floor(o/3600)):o<86400*30?m(_("%s d ago"),Math.floor(o/86400)):new Date(t*1e3).toLocaleDateString(ie(),{day:"numeric",month:"short",year:"numeric"})}function st(t){if(!t||t<0)return"—";let e=Math.floor(t/86400),o=Math.floor(t%86400/3600),s=Math.floor(t%3600/60);return e?m(_("%sd %sh"),e,o):o?m(_("%sh %sm"),o,s):m(_("%sm"),s)}function Ft(t){let e=new Date(t*1e3),o=new Date,s=e.toDateString()===o.toDateString(),r=e.toLocaleTimeString(ie(),{hour:"2-digit",minute:"2-digit"});return s?r:`${e.toLocaleDateString(ie(),{day:"numeric",month:"short"})} ${r}`}function qe(t){return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function Pt(t){let[e,o,s]=t.split("-").map(Number);return new Date(e,(o||1)-1,s||1,12)}function Ie(t){return(typeof t=="string"?/^\d{4}-\d{2}-\d{2}$/.test(t)?Pt(t):new Date(t):t).toLocaleDateString(ie(),{day:"numeric",month:"short",year:"numeric"})}function $e(t){return t?Ie(t):""}function fo(t,e){let o=s=>{let[r,i,a]=s.split("-").map(Number);return Date.UTC(r,i-1,a)};return Math.round((o(t)-o(e))/864e5)}function Gt(t,e){let o=Pt(t);return o.setDate(o.getDate()+e),qe(o)}function St(t,e){let[o,s,r]=t.split("-").map(Number),i=new Date(o,s-1+e,1,12),a=new Date(i.getFullYear(),i.getMonth()+1,0).getDate();return i.setDate(Math.min(r,a)),qe(i)}function Ge(t){return t?.length?t[t.length-1].day:qe(new Date)}function ms(t,e,o,s,r=30){let i=t||s;return e==="day"?Gt(i,o):e==="week"?Gt(i,7*o):e==="month"?St(i,o):e==="year"?St(i,12*o):Gt(i,r*o)}function rt(t,e=Date.now()){if(!t)return null;let o=typeof e=="number"?qe(new Date(e)):e,s=fo(t,o);return s>=0?s+1:s}function it(t,e){return e!=null&&e>0&&t.expire_warn>0&&e<=t.expire_warn}function fn(t){return t<=1?_("ends today"):t===2?_("ends tomorrow"):G(t,"ends in %s day","ends in %s days")}function $t(t){return t<1024?`${V(t)} ${_("B")}`:t<1048576?`${V(t/1024,t<10240?1:0)} ${_("KB")}`:`${V(t/1048576,1)} ${_("MB")}`}function bt(t){return{lan:_("Home network"),internet:_("Internet"),both:_("Home network + Internet")}[t]}var xt=20,Aa=[[128,191],[215,215],[247,247],[8192,11263],[12288,12351],[55296,63743],[65024,65039],[65072,65103],[65279,65279],[65520,65535],[126976,130047],[917504,917631]],Na=/^[A-Za-z0-9 ._-]$/,Ha=/^[\p{L}\p{M}\p{N}]$/u;function gn(t){let e=t.codePointAt(0)??0;return e<128?Na.test(t):!Aa.some(([o,s])=>e>=o&&e<=s)&&Ha.test(t)}function qt(t){let e=[...t];return e.length<=xt&&e.every(gn)}function go(t,e=""){return[...[...t].map(r=>gn(r)?r:" ").join("").replace(/\s+/g," ").trim()||_("Device")].slice(0,Math.max(1,xt-[...e].length)).join("").trimEnd()+e}function hs(t){return t==="other"?_("Device"):at(t)}var fs=["computer","phone","tablet","router","other"];function at(t){return{computer:_("PC"),phone:_("Phone"),tablet:_("Tablet"),router:_("Router"),other:_("Other")}[t]}function gs(t){return{active:_("Active"),paused:_("Paused"),expired:_("Expired"),quota:_("Data limit reached"),hours:_("Outside allowed hours"),no_server:_("No server"),server_off:_("Server is turned off")}[t]}function Oe(t){let e=t.trim().split(/\s+/).filter(Boolean);if(!e.length)return"?";let o=e[0][0]??"",s=e.length>1?e[e.length-1][0]??"":e[0][1]??"";return(o+s).toUpperCase()}function vn(t){let e=o=>o.disabled?3:o.online?0:o.handshake?1:2;return t.map((o,s)=>[o,s]).sort((o,s)=>e(o[0])-e(s[0])||o[1]-s[1]).map(([o])=>o)}function bn(t){return t.map(e=>e.endsWith(".0/24")?`${e.slice(0,-5)}.x`:e).join(", ")}function Kt(t,e){if(t.access!=="both"||!e)return[];let o=t.home_nets??[];return e.home.filter(s=>!o.length||o.includes(s.dev)).flatMap(s=>s.nets)}function Se(t,e,o){return n("span",{class:`dl-pill ${t}`,title:o??null},e)}function za(t){return t.state==="active"?"ok":t.state==="quota"||t.state==="expired"?"bad":"warn"}function Ra(t){return t.state==="server_off"&&t.paused?"paused":t.state}function vs(t){let e=Ra(t);return e==="active"||e==="server_off"?"":Se(za({...t,state:e}),gs(e))}function bs(t){let e=t.access==="both"?["lan","inet"]:t.access==="lan"?["lan"]:["inet"],o=n("span",{class:"dl-access","aria-label":bt(t.access)},e.map(s=>n("span",{class:`dl-ibadge ${s}`},v(s==="lan"?"home":"globe"))));return we(o,()=>[n("div",{class:"dl-tip-title"},bt(t.access)),t.access==="lan"&&t.services?.length?n("div",{class:"dl-muted"},G(t.services.length,"%s home service only","%s home services only")):""]),o}function Ia(t){return{active:null,paused:_("Paused"),expired:_("Access ended"),quota:_("Data limit"),hours:_("Outside hours"),server_off:_("Server off"),no_server:_("No server")}[t]}function xn(t,e,o=_("Not set up yet"),s){let r=new Date(t.handshake*1e3).toLocaleString(ie()),i=t.handshake?`${m(_("Last seen %s"),ce(t.handshake,e))} · ${r}`:"";if(t.disabled)return n("span",{class:"dl-dstat",title:i},_("Disabled"));if(t.online)return n("span",{class:"dl-dstat ok"},_("Connected"));let a=s&&Ia(s.state);return a?n("span",{class:"dl-dstat warn",title:i||_("Not connected yet")},a):t.handshake?n("span",{class:"dl-dstat",title:r},m(_("Last seen %s"),ce(t.handshake,e))):n("span",{class:"dl-dstat warn",title:_("Waiting for the first connection")},o)}var wn=null;function xs(t,e,o,s){wn?.close();let r=n("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[n("div",{class:"dl-drawer-head"},[t,n("button",{type:"button",class:"dl-drawer-x","aria-label":_("Close"),click:()=>c()},v("x"))]),n("div",{class:"dl-drawer-body"},e),o?n("div",{class:"dl-drawer-foot"},o):""]),i=n("div",{class:"dl-drawer-overlay dl-root",click:u=>{u.target===i&&c()}},r),a=u=>{u.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&c()},l=!1,d=Ee(()=>c());function c(){l||(l=!0,d(),document.removeEventListener("keydown",a),i.classList.remove("open"),setTimeout(()=>i.remove(),220),wn===p&&(wn=null),s())}let p={close:c,panel:r};return document.addEventListener("keydown",a),document.body.appendChild(i),requestAnimationFrame(()=>i.classList.add("open")),wn=p,p}function ge(t,e,o){return n("div",{class:"dl-setrow"},[n("div",{class:"dl-stack"},[n("span",{class:"dl-setrow-label"},t),o?n("span",{class:"dl-sub"},o):""]),n("div",{class:"dl-setrow-ctl"},e)])}function Ce(t,e,o,s=e){let r=ge(t,s," "),i=r.querySelector(".dl-sub"),a=()=>{let l=o();i.textContent=l.text,i.classList.toggle("bad",l.bad),e.classList.toggle("cbi-input-invalid",l.bad)};return e.addEventListener("input",a),r.refresh=a,r.help=o,a(),r}function Me(t,e,o,s=e){let r=n("div",{class:"dl-sub"}),i=n("div",{class:"cbi-value dl-live"},[n("div",{class:"cbi-value-title"},[n("label",{},t),r]),n("div",{class:"cbi-value-field"},s)]),a=()=>{let l=o();r.textContent=l.text,r.classList.toggle("bad",l.bad),e.classList.toggle("cbi-input-invalid",l.bad)};return e.addEventListener("input",a),e.addEventListener("change",a),i.refresh=a,i.help=o,a(),i}function Be(t,e=[]){for(let o of t){let s=o.help?.();if(s?.bad)return s.text}for(let o of e){let s=o();if(s.bad)return s.text}return null}function Vt(t,e,o,s=""){return n("section",{class:`dl-setsec ${s}`},[n("div",{class:"dl-setsec-body"},[t?n("h3",{},t):"",...e]),o.length?n("div",{class:"dl-setsec-foot"},o):""])}function ye(t,e,o,s){return n("div",{class:"dl-group"},[n("div",{class:"dl-group-head"},[n("span",{class:"dl-group-ic"},v(t)),n("span",{class:"dl-stack"},[n("b",{},e),o?n("span",{class:"dl-sub"},o):""])]),n("div",{class:"dl-group-body"},s.filter(r=>r!==""))])}function lt(t,e,o,s,r){return n("div",{class:`dl-row dl-need-row ${e}`},[e?n("span",{class:"dl-need-ic"},v(t)):v(t),n("span",{class:"dl-row-main dl-stack"},[n("b",{},o),n("span",{class:"dl-sub"},s)]),r])}function wt(t){return n("div",{class:"dl-note warn"},[v("alert"),n("span",{},t)])}function yt(t,e){let o={ok:"success",warn:"warning",error:"error",info:"notice"}[t];return n("div",{class:`alert-message ${o}`},e)}function kt(t,e=""){let o=n("div",{class:e});return o.innerHTML=t,o}function be(t,e,o){let s=n("button",{type:"button",role:"switch",class:`dl-switch${t?" on":""}`,"aria-checked":t?"true":"false","aria-label":e,click:()=>{let r=!s.classList.contains("on");vo(s,r),o?.(r)}},n("i"));return s}function vo(t,e){t.classList.toggle("on",e),t.setAttribute("aria-checked",e?"true":"false")}var De=t=>t.classList.contains("on");function Ze(t,e,o={}){t.some(([i])=>i===e)||(t=[...t,[e,e]]);let s=n("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>s.querySelectorAll(":scope > button").forEach(i=>{let a=i.dataset.v===s.dataset.value;i.classList.toggle("on",a),i.setAttribute("aria-checked",a?"true":"false")});for(let[i,a]of t)s.appendChild(n("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==s.dataset.value&&(o.optimistic!==!1&&(s.dataset.value=i,r()),o.onChange?.(i))}},a));return r(),s}function Yt(t,e,o,s={}){return n("button",{type:"button",...s,class:`dl-chipbtn${e?" on":""}${s.class?` ${s.class}`:""}`,"aria-pressed":e?"true":"false",click:o},t)}function Qe(t,e,o,s){return t.some(([r])=>r===e)||(t=[...t,[e,e]]),n("select",{class:"cbi-input-select","aria-label":o,change:r=>s?.(r.target.value)},t.map(([r,i])=>n("option",{value:r,selected:r===e?"selected":null},i)))}function yn(t,e,o){let s=new ui.Dropdown(e,Object.fromEntries(t),{multiple:!0,sort:t.map(([i])=>i),select_placeholder:_("None")}),r=s.render();return r.setAttribute("aria-label",o),{node:r,value:()=>s.getValue()}}function ue(t,e={}){return n("input",{type:"text",class:"cbi-input-text",value:t,...e})}var Ls=Ca(_s(),1),Oa=t=>``,Cs="#0a0a0a",Ba="#f2f2f2",ja={night:[Cs,Ba],day:["#ffffff",Cs]},Ms=t=>t.length>300,bo=null;function Ua(t){if(bo?.text===t)return bo.qr;let e=(0,Ls.default)(0,Ms(t)?"L":"H");return e.addData(t,"Byte"),e.make(),bo={text:t,qr:e},e}var Dt=t=>+t.toFixed(2);function xo(t,e,o,s,r){return`M${Dt(t+r)} ${Dt(e)}h${Dt(o-2*r)}a${r} ${r} 0 0 1 ${r} ${r}v${Dt(s-2*r)}a${r} ${r} 0 0 1 -${r} ${r}h-${Dt(o-2*r)}a${r} ${r} 0 0 1 -${r} -${r}v-${Dt(s-2*r)}a${r} ${r} 0 0 1 ${r} -${r}z`}function kn(t,e=3,o=!0,s="plain"){let r=Ms(t),i=s!=="plain",[a,l]=i?ja[s]:["#fff","#000"],d=Ua(t),c=d.getModuleCount(),p=c+e*2,u=o&&!r?Math.round(c*.22):0;u&&(c-u)%2&&u++;let g=(c-u)/2,M=g+u,x=(w,k)=>u>0&&w>=g&&w=g&&ki&&(k<7&&w<7||k<7&&w>=c-7||k>=c-7&&w<7),S="";if(i){let w=r?.48:.42;for(let k=0;k${Oa(i?a:"#fff")}`}let R=``;return i?`${R}${P}`:`${R}${P}`}function _t(){let t=document.documentElement.getAttribute("data-darkmode");return t!=null?t==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function _n(t){let e=_t();return kt(kn(t,3,!0,e?"night":"day"),`dl-qr${e?"":" light"}`)}function wo(t){let e=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/.exec(t.trim());if(!e)return null;let[o,s,r,i]=e.slice(1,5).map(Number),a=Number(e[5]);if([o,s,r,i].some(c=>c>255)||a<8||a>30)return null;let l=o*2**24+s*2**16+r*2**8+i,d=2**(32-a);return{net:l-l%d,size:d}}var Wa=(t,e)=>t.netwo(t));function Nt(t){return t.split("/")[0].split(".").slice(0,3).join(".")}function Cn(t){return`${t.trim()}.0/24`}function ko(t,e,o){let s=t.trim(),r=/^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s)?wo(Cn(s)):null;if(!r)return{text:_("Three numbers, like 10.77.0."),bad:!0};if(!Ga.some(a=>r.net>=a.net&&r.net+r.size<=a.net+a.size))return{text:_("Use a private range: 10.x.x, 172.16–31.x or 192.168.x."),bad:!0};let i=e.find(a=>{let l=wo(a.cidr);return l!=null&&Wa(r,l)});if(i){let a=i.cidr.endsWith("/24")?`${Nt(i.cidr)}.x`:i.cidr,l=m(_("%s already uses %s."),i.name,a);return{text:o&&o!==s?`${l} ${m(_("Try %s."),o)}`:l,bad:!0}}return{text:m(_("Devices get %s – %s, the router %s."),`${s}.2`,`${s}.254`,`${s}.1`),bad:!1}}var Ts=(t,e)=>e.find(o=>o.from<=t&&t<=o.to)?.who??null,Fa=t=>Number.isInteger(t)&&t>=1&&t<=65535;function Jt(t,e,o){if(!Fa(t))return{text:_("Use a port from 1 to 65535."),bad:!0};let s=Ts(t,e);return s?{text:m(_("Used by %s. Choose another port."),s),bad:!0}:{text:o,bad:!1}}function Ln(t,e,o){let s=o?m(_("HTTPS here, plain HTTP for links on IP addresses on %s."),t+1):_("HTTPS on this port, opened on WAN."),r=Jt(t,e,s);if(r.bad||!o)return r;if(t===65535)return{text:_("Links on IP addresses also need the next port: choose a lower one."),bad:!0};let i=Ts(t+1,e);return i?{text:m(_("Links on IP addresses also need %s, used by %s. Choose another port."),t+1,i),bad:!0}:r}var Mn=t=>Array.from(t).length,Es=48,qa=/[<>"\\\u0000-\u001f\u007f]/,_o=(t,e)=>m(N_(t,"Up to %s character (%s now).","Up to %s characters (%s now)."),V(t),V(Mn(e)));function je(t,e=[],o=""){let s=t.trim();return s?Mn(t)>Es?{text:_o(Es,t),bad:!0}:qa.test(t)?{text:_('Names can’t contain < > " or \\.'),bad:!0}:e.some(r=>r.toLowerCase()===s.toLowerCase())?{text:m(_("“%s” already exists - pick another name."),s),bad:!0}:{text:o,bad:!1}:{text:_("Enter a name."),bad:!0}}function Co(t,e=[],o=""){return Mn(t.trim())>xt?{text:_o(xt,t.trim()),bad:!0}:qt(t.trim())?je(t,e,o):{text:_("Letters, digits, spaces and - _ . only."),bad:!0}}function Ss(t,e=[]){return Mn(t)>32?{text:_o(32,t),bad:!0}:je(t,e,_("Shown on the person cards."))}var Ka=/^[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])?)*$/,Va=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;function Ht(t){let e=Va.exec(t);return!!e&&e.slice(1).every(o=>Number(o)<=255)}function yo(t){return/^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/.test(t)&&!/:::/.test(t)}function At(t,e,o=null){let s=t.trim();if(!s)return o!=null?{text:o,bad:!1}:{text:_("Enter a hostname or IP address."),bad:!0};if(/^[a-z]+:\/\//i.test(s))return{text:_("Leave out https:// - just the name."),bad:!0};if(/\/.*/.test(s))return{text:_("Just the name, without a path."),bad:!0};if(/^[^:\[]+:\d+$/.test(s))return{text:_("Just the name, without a port (the port is on AmneziaWG)."),bad:!0};if(/\s/.test(s))return{text:_("A hostname has no spaces."),bad:!0};if(s.length>253||!(Ka.test(s)||Ht(s)||yo(s)))return{text:_("Use a hostname or an IP address."),bad:!0};let r=yo(s)?`[${s}]`:s;return{text:e?m(_("Devices connect to %s."),`${r}:${e}`):m(_("Links use %s."),r),bad:!1}}function Ps(t,e){let o=t.split(/[ ,]+/).filter(Boolean);if(!o.length)return{text:m(_("This router (%s): queries go where your home network sends them, and home names work."),e),bad:!1};let s=o.find(i=>!Ht(i)&&!yo(i));if(s)return{text:m(_("“%s” is not an IP address. Separate several with commas."),s),bad:!0};let r=new Intl.ListFormat(ie(),{type:"conjunction"}).format(o);return{text:m(_("Devices use %s - home names and your LAN’s DNS filters no longer apply to them."),r),bad:!1}}function $s(t,e){let o=t.trim();if(!o)return{text:m(_("Automatic by device type and disguise: %s for computers and routers, %s for phones and tablets."),e.computer,e.phone),bad:!1};if(!/^\d{1,4}$/.test(o)||Number(o)<1280||Number(o)>1500)return{text:_("MTU must be 1280–1500, or empty for automatic."),bad:!0};let s=Number(o);return{text:m(_("Computers and routers get %s, phones and tablets %s."),s,Math.min(s,1280)),bad:!1}}function Ds(t){let e=t.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:m(_("Devices send a packet every %s s to keep NAT open (a little battery on phones)."),e),bad:!1}:{text:_("Default: a packet every 25 s keeps NAT open and “Connected” accurate."),bad:!1}}function As(t){let e=t.trim();return e&&(!/^\d{1,4}$/.test(e)||Number(e)<1280||Number(e)>1500)?{text:_("From 1280 to 1500."),bad:!0}:{text:_("Empty: automatic. Lower it when big pages hang on this device."),bad:!1}}function Ns(t){let e=t.trim();return e&&(!/^\d{1,4}$/.test(e)||Number(e)>600)?{text:_("From 0 to 600 seconds."),bad:!0}:{text:_("Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops."),bad:!1}}function En(t,e=0){let o=t.trim();if(!/^\d{1,2}$/.test(o)||Number(o)<1||Number(o)>32)return{text:_("Use 1–32."),bad:!0};let s=Number(o);return e>s?{text:e-s===1?m(N_(e,"Already has %s device: remove one first, or allow more.","Already has %s devices: remove one first, or allow more."),V(e)):m(N_(e,"Already has %s device: remove %s first, or allow more.","Already has %s devices: remove %s first, or allow more."),V(e),V(e-s)),bad:!0}:{text:G(s,"They can add %s device themselves.","They can add %s devices themselves."),bad:!1}}function Tn(t,e=!0){let o=t.trim();if(!o)return{text:_("Optional. No data limit."),bad:!1};let s=Number(o);return!/^\d+(\.\d+)?$/.test(o)||s<0||s>1e5?{text:_("A number of GB, up to 100000."),bad:!0}:s===0?{text:_("Optional. No data limit."),bad:!1}:{text:m(e?_("Paused after %s GB this month, resumed on the 1st."):_("Paused after %s GB in total."),V(s)),bad:!1}}function Hs(t,e,o,s){let r=t.trim();if(!r)return{text:_("Optional. No end date."),bad:!1};let i=o(r,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?m(_("Access ends today (%s)."),s(r)):m(N_(i,"Access ends in %s day (%s).","Access ends in %s days (%s)."),V(i),s(r)),bad:!1}}function zs(t,e=null){let o=t.trim();return o?Ht(o)?e&&!e(o)?{text:m(_("%s is not in any home network of this server: nobody would reach it."),o),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 Rs(t){let e=t.split(/[ ,]+/).filter(Boolean);if(!e.length)return{text:_("All ports."),bad:!1};let o=e.find(s=>!/^\d{1,5}$/.test(s)||Number(s)<1||Number(s)>65535);return o?{text:m(_("“%s” is not a port (1–65535)."),o),bad:!0}:{text:m(N_(e.length,"Port %s.","Ports %s."),e.join(", ")),bad:!1}}function Is(t){let e=t.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 Os(t,e="phone.myata"){let o=t.trim();return o?/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(o)?{text:m(_("Devices get names like %s."),`${e}.${o}`),bad:!1}:{text:/[A-Z]/.test(o)?_("Lowercase only."):_("Lowercase letters, digits, dashes and dots."),bad:!0}:{text:m(_("The default, lan: devices get names like %s."),`${e}.lan`),bad:!1}}function Bs(t){let e=t.trim();return e?Ht(e)?{text:m(_("%s takes over when the tunnel is down."),e),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 js(t){let e=t.trim();return/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(e)?{text:m(_("Runs within an hour after %s (router time)."),e),bad:!1}:{text:_("Use HH:MM, 00:00–23:59."),bad:!0}}function Lo(t,e,o,s={}){let r=0,i="",a=null;return{help:()=>{let{host:c,port:p}=t(),u=At(c,p,s.empty??null);return u.bad||!c.trim()?u:a&&a.host===c.trim()?{text:a.text,bad:a.bad}:{text:`${s.idle?.()||u.text} ${_("Checking where it points…")}`,bad:!1}},schedule:()=>{let{host:c}=t(),p=At(c,t().port,s.empty??null);p.bad||!c.trim()||c.trim()===a?.host||(clearTimeout(r),r=window.setTimeout(async()=>{let u=c.trim();i=u;try{let{id:g,port:M}=t(),x=await e(u,g,M);if(i!==u)return;a={host:u,text:x.text,bad:x.status==="error"}}catch{if(i!==u)return;a={host:u,text:p.text,bad:!1}}o()},700))}}}var Ya=Array.from({length:31},(t,e)=>{let o=e/30;return 14*Math.exp(-4.2*o)*Math.sin(o*Math.PI*2*3.6)}),Us=700,Ja=800;function Za(t){t.getAnimations().filter(i=>i.id==="redden").forEach(i=>i.cancel());let e=getComputedStyle(t),s=`${t.classList.contains("field")?"inset ":""}0 0 0 1.5px ${e.getPropertyValue("--bad").trim()||"#e5484d"}`,r=Us+Ja;t.animate([{boxShadow:s,offset:0},{boxShadow:s,offset:Us/r,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}],{duration:r,id:"redden"})}function Mo(t,e={}){if(e.ring!==!1&&Za(t),typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches)return;let o=getComputedStyle(t).transform,s=o&&o!=="none"?new DOMMatrix(o).m41:0;t.getAnimations().filter(r=>r.id==="shake").forEach(r=>r.cancel()),t.animate(Ya.map((r,i)=>({transform:`translateX(${(i===0?s:r).toFixed(2)}px)`})),{duration:520,easing:"linear",id:"shake"})}function Ws(t){return[...t].every(gn)?m(_("Up to %s characters."),V(xt)):_("Only letters, digits, - _ .")}function Gs(t,e=t,o=()=>{},s={}){let r=()=>typeof e=="function"?e():e,i=t.value;t.addEventListener("beforeinput",a=>{if(i=t.value,a.inputType.startsWith("delete")||a.isComposing||a.inputType==="insertCompositionText")return;let l=a.data??a.dataTransfer?.getData("text/plain")??"",d=t.selectionStart??t.value.length,c=t.selectionEnd??d,p=t.value.slice(0,d)+l+t.value.slice(c);qt(p)||(a.preventDefault(),Mo(r(),s),o(Ws(p)))}),t.addEventListener("input",a=>{if(a instanceof InputEvent&&a.inputType.startsWith("delete")||qt(t.value)){i=t.value,o(null);return}let d=t.value,c=Math.min(t.selectionStart??i.length,i.length);t.value=i,t.setSelectionRange(c,c),a.stopImmediatePropagation(),Mo(r(),s),o(Ws(d))})}var Eo=["%d system package","%d system packages","%s (after %d repair)","%s (after %d repairs)","%s - %d repairs didn't help","%s - %s","%s - not repaired again (%d repairs didn't help)","%s has no IPv4 address.","%s is not a bridge, so Dawnline cannot join the LAN as a device.","%s needs a manual switch in Components","%s still give devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.","%s still gives devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.","%s · restored","Access rules","Activity","AmneziaWG is missing from the router","AmneziaWG is running again","AmneziaWG is running again · accepting connections on port %d","AmneziaWG isn't accepting connections on port %d","AmneziaWG isn't running","Backup","Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.","Changed: %s.","Choose a disguise on the Server page: it replaces the values set by hand.","Choose another interface name in the server settings.","Components","Connections","DNS for Home-only devices","Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.","Firewall","Install it in Dawnline → Components.","Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.","Internet like a home device","MTU is now automatic","Missing: %s.","No LAN detected.","No free address on %s.","No free link-local range for the internal link.","No free routing table.","People","Personal links","Personal portal","Router","Servers","Speed","System packages","The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.","Traffic","Watchdog","Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline.","a new build needs a manual switch in Components","answers again","are loaded again","are missing","automatic update failed","background check failed: %s","can't reach Dawnline (luci.dawnline is missing in rpcd)","can't use the network interface %s: it exists and isn't Dawnline's","certificate expires %s","certificate expires within 7 days","certificate renewed · valid until %s","couldn't be repaired: %s","couldn't be updated - the previous rules stay, and changes to access wait until they load","couldn't load - no device is loaded into the tunnels until they do","couldn't load devices into the tunnel","couldn't start","couldn't start · %d failed attempts in %d min","failed - internet goes out directly for now","failed: %s",'has an invalid interface name "%s"',"installed the %s build","installed the %s build · %s","interface %s has Dawnline's settings again","interface %s was changed outside Dawnline","is kept down","is kept down: its disguise has values AmneziaWG cannot take","is kept down: its disguise needs AmneziaWG %s (installed: %s)","is kept down: its disguise needs AmneziaWG %s (installed: none)","is off","is on · traffic enters %s as %s","is ready again","isn't answering on port %d","isn't installed: no tunnel can run - install it in Dawnline → Components","isn't installed: tunnels were left as they are","isn't known to the network service - restart the network or reboot","isn't running","isn't running on this router (fw4): tunnels and the portal are closed","kernel module isn't installed: no tunnel can run - install it in Dawnline → Components","kernel module isn't loaded","loading it","loading them again","moved to word codes","netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.","network changed - Dawnline set itself up again","nightly backup failed: %s","public address changed · %s → %s","reaches Dawnline again","reloading rpcd","restarted · version %s","restarting for the AmneziaWG update","restarting it","restoring them","rules for Dawnline are in place again","rules for Dawnline aren't loaded","rules for Dawnline were changed or removed","runs again","runs without its fast path","setting it up again","started","started with the router · version %s","started · accepting connections on port %s","started · version %s","stopped unexpectedly","stopped unexpectedly - started again","update failed","update to %s failed its check - rolled back to %s","updated automatically · %s","updated automatically · %s → %s","updated · %s","updated · %s → %s","updates available · %s","was broken - set up again (%s as %s)"];var Qa={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",device_failing:"problems",device_recovered:"problems"},Rt=["connections","people","problems"];function Ke(t){return{connections:_("Connections"),people:_("People"),problems:_("Problems")}[t]}function Fs(t){return{connections:_("Connects, disconnects and IP changes"),people:_("People and their devices added, changed, paused, removed"),problems:_("Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)")}[t]}var Zt=t=>Qa[t]??"problems";function Qt(t){return{awg:"AmneziaWG",dawnline:"Dawnline",portal:_("Portal")}[t]??t}var Xa=["person_added","person_removed","person_changed"];function Ve(t){return t.by?t.by:Xa.includes(t.type)||t.detail==="by admin"||t.detail?.endsWith(" (admin)")?"admin":t.detail?.endsWith(" (portal)")?"portal":null}function qs(t){return(t.detail??"").replace(/ \((admin|portal)\)$/,"").replace(/^by admin$/,"")}var Sn=t=>t.sys?["error","repair","down"].includes(t.sys.level):Zt(t.ev.type)==="problems";function Pn(t){let e=t.keep_days>0?G(t.keep_days,"%s day","%s days"):_("no age limit"),o=t.persist==="off"?_("kept in memory only (lost on reboot)"):t.persist==="10min"?_("saved to flash every 10 minutes"):_("saved to flash hourly");return m(_("Kept for %s, %s, %s."),e,G(t.max,"up to %s event","up to %s events"),o)}function To(t){return{"paused by admin":_("paused by admin"),"end date reached":_("end date reached"),"data limit reached":_("data limit reached"),"outside allowed hours":_("outside allowed hours"),"no server":_("no server"),"server turned off":_("server turned off")}[t]??t}function Ks(t){let e=/^(\d+) days?$/.exec(t);return e?Number(e[1]):null}function Vs(t){let e={name:_("name"),access:_("access"),device_limit:_("device limit"),expires:_("end date"),expire_action:_("what happens at the end"),expire_warn:_("warning before the end"),quota_gb:_("data limit"),quota_period:_("data limit period"),bonus_gb:_("extra data"),hours:_("allowed hours"),dns_mode:_("DNS"),paused:_("pause"),services:_("home services"),circle:_("circle","setting"),home_nets:_("home networks"),server:_("server")};return t.split(", ").map(o=>{let s=/^moved to (.+)$/.exec(o)?.[1];return s?m(_("moved to %s"),s):e[o]??o.replace(/_/g," ")}).join(", ")}function Ys(t){let e={mtu:"MTU",keepalive:_("keep-alive"),lan_bypass:_("LAN Bypass")};return t.split(", ").map(o=>e[o]??o).join(", ")}function So(t){let o={trying:[_("Unable to complete the handshake"),_("The device’s network may be blocking the connection.")],dropped:[_("Handshake complete, but no data"),_("This device is using an outdated configuration.")],shared:[_("On two devices at once"),_("The same configuration connects from two places in turn. Give the other device its own.")],unstable:[_("Connection keeps dropping"),_("It connects, but the connection breaks every few minutes: the network may be cutting it.")]}[t];return o?{title:o[0],line:o[1]}:null}function Js(t){return t.split(", ").map(e=>So(e)?.title??e).join(", ")}function Zs(t,e,o){let r={"cleared|the service log":_("You cleared the service log"),"cleared|the activity log":_("You cleared the activity log"),"exported|all settings":_("You exported all settings"),"imported|settings from a file":_("You imported settings from a file"),"restored|from a file":_("You restored a backup from a file"),"turned on|the personal portal":_("You turned on the personal portal"),"turned off|the personal portal":_("You turned off the personal portal"),"changed|the personal portal":_("You changed the personal portal"),"turned on|the watchdog":_("You turned on the watchdog"),"turned off|the watchdog":_("You turned off the watchdog"),"reset traffic history|for everyone":_("You reset traffic history for everyone")}[`${t}|${o??""}`];if(r)return{text:r,named:!1};let a={"created|server":_("You created server %s"),"changed|server":_("You changed server %s"),"removed|server":_("You removed server %s"),"turned on|server":_("You turned on server %s"),"turned off|server":_("You turned off server %s"),"added|circle":_("You added circle %s"),"changed|circle":_("You changed circle %s"),"removed|circle":_("You removed circle %s"),"restored|backup":_("You restored backup %s")}[`${t}|${e??""}`];return a?{text:a,named:!0}:t==="reset traffic history"&&/^for (.+)$/.exec(o??"")?.[1]?{text:_("You reset traffic history for %s"),named:!0}:null}var Qs=(t,e)=>t==="reset traffic history"?e.replace(/^for /,""):e;function Xs(t){let e=o=>{let s={"other addresses":_("other addresses"),certificate:_("certificate"),redirect:_("redirect"),"devices kept apart":_("devices kept apart"),"devices reach each other":_("devices reach each other"),"devices reach each other in circles":_("devices reach each other in circles"),"home network and internet path":_("home network and internet path"),"the file holds private keys":_("the file holds private keys"),"problems are only logged, nothing is repaired":_("problems are only logged, nothing is repaired"),name:_("name"),"public address":_("public address"),"AmneziaWG port":_("AmneziaWG port"),"tunnel network":_("tunnel network"),connections:Ke("connections"),people:Ke("people"),problems:Ke("problems")};if(s[o])return s[o];let r;return(r=/^port (\d+)$/.exec(o))?m(_("port %s"),r[1]):(r=/^address (.+)$/.exec(o))?m(_("address %s"),r[1]):(r=/^disguise: (.+)$/.exec(o))?m(_("disguise: %s"),r[1]):(r=/^(\d+) events?$/.exec(o))?G(Number(r[1]),"%s event","%s events"):(r=/^older than (\d+) days$/.exec(o))?G(Number(r[1]),"older than %s day","older than %s days"):(r=/^with (\d+) (person|people)$/.exec(o))?G(Number(r[1]),"with %s person","with %s people"):(r=/^(\d+) entr(y|ies)( older than (\d+) days)?$/.exec(o))?r[4]?`${G(Number(r[1]),"%s entry","%s entries")}, ${G(Number(r[4]),"older than %s day","older than %s days")}`:G(Number(r[1]),"%s entry","%s entries"):o};return t.split(" · ").map(o=>o.split(", ").map(e).join(", ")).join(" · ")}var el=null,tl=new Set(Eo);function nl(){return el??(el=Eo.filter(t=>/%[sd]/.test(t)&&t.replace(/%[sd]/g,"").trim()).map(t=>({t,fixed:t.replace(/%[sd]/g,"").length,re:new RegExp(`^${t.split(/(%[sd])/).map(e=>e==="%s"?"(.+?)":e==="%d"?"(\\d+)":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("")}$`)})).sort((t,e)=>e.fixed-t.fixed))}function zt(t,e=0){let o=t.replace(/ — /g," - ");if(tl.has(o))return po(o);if(e>2)return t;for(let s of nl()){let r=s.re.exec(o);if(r)return m(po(s.t),...r.slice(1).map(i=>zt(i,e+1)))}return o.includes(", ")?o.split(", ").map(s=>zt(s,e+1)).join(", "):t}function er(t,e=120,o=26,s=qe(new Date)){let r=Math.max(1,...t),i=n("div",{class:"dl-spark"});return i.style.width=`${e}px`,i.style.height=`${o}px`,t.forEach((a,l)=>{let d=n("i");d.style.height=`${Math.max(6,a/r*100)}%`,a||d.classList.add("zero");let c=n("span",{},[d]),p=t.length-1-l;we(c,()=>[n("div",{class:"dl-tip-title"},p===0?_("Today"):p===1?_("Yesterday"):Pt(Gt(s,-p)).toLocaleDateString(ie(),{weekday:"short",day:"numeric",month:"short"})),n("div",{class:"dl-muted"},se(a))]),i.appendChild(c)}),i}function tr(t){let e=t==null?"":String(t);return/^[=+\-@\t\r]/.test(e)&&(e=`'${e}`),/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function nr(t,e,o){return[t.map(s=>tr(o?.[s]??s)).join(","),...e.map(s=>t.map(r=>tr(s[r])).join(","))].join(` +`)}function ol(t){let e=new Map(t.people.map(s=>[s.id,s.name])),o=new Map(t.people.flatMap(s=>s.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Xe(t,e,o,s="",r=[]){let i=ol(t),a=[...e.map(u=>({ts:u.ts,category:Zt(u.type),type:u.type,person:u.person?i.people.get(u.person)??u.pname??u.person:"",device:u.device?i.devices.get(u.device)??u.dname??u.device:"",detail:u.detail??"",where:u.where??"",by:Ve(u)??""})),...r.map(u=>({ts:u.ts,category:"system",type:`${u.src}.${u.level}`,person:"",device:"",detail:`${u.who?`${u.who} `:""}${u.msg}${u.detail?` +${u.detail}`:""}`,where:Qt(u.src),by:""}))].sort((u,g)=>u.ts-g.ts).map(({ts:u,...g})=>({time:new Date(u*1e3).toISOString(),...g})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${s?`-${s}`:""}-${l}.${o}`;if(o==="json"){Ae(d,JSON.stringify(a,null,2),"application/json");return}let c=["time","category","type","person","device","detail","where","by"],p={time:_("Time"),category:_("Category"),type:_("Type"),person:_("Person"),device:_("Device"),detail:_("Detail"),where:_("Where"),by:_("By")};Ae(d,nr(c,a,p),"text/csv")}var sl=["","7","30","90"],rl=t=>t?G(Number(t),"Older than %s day","Older than %s days"):_("Everything"),or=t=>t?G(t,"%s event removed","%s events removed"):_("Nothing matched");function dt(t,e,o,s,r,i=!1){let a=n("select",{class:"cbi-input-select"},[n("option",{value:""},_("All categories")),...Rt.map(d=>n("option",{value:d,selected:d===r?"selected":null},Ke(d))),i?n("option",{value:"system",selected:r==="system"?"selected":null},_("System")):""]),l=n("select",{class:"cbi-input-select"},sl.map(d=>n("option",{value:d},rl(d))));ae(t,[n("p",{class:"dl-muted"},`${e} ${_("This cannot be undone; export first if you want a copy.")}`),n("label",{class:"dl-fld"},[n("span",{class:"dl-fld-label"},_("Category")),a]),n("label",{class:"dl-fld"},[n("span",{class:"dl-fld-label"},_("Which events")),l])],[de()," ",H(_("Clear"),async()=>{let d=0;if(a.value!=="system")try{d+=(await N.logsClear({...o,category:a.value,older_days:l.value})).removed}catch(c){F(_e(c),"error",1e4);return}if(i&&(a.value==="system"||a.value===""))try{d+=(await N.serviceLogClear(l.value)).removed}catch(c){le();let p=m(_("The service log was not cleared: %s"),_e(c));F(a.value==="system"?p:`${m(_("Activity: %s."),or(d).toLowerCase())} ${p}`,"error",1e4),s();return}le(),F(or(d),"success",3e3),s()},"negative")])}function It(t,e,o,s){let r=t==="device"?m(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."),o):t==="person"?m(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."),o):_("Clears traffic history for everyone. Data limits start again from zero.");ae(t==="all"?_("Reset all traffic history?"):m(_("Reset traffic history for %s?"),o),[n("p",{class:"dl-muted"},r)],[de()," ",H(_("Reset"),async()=>{await q(()=>N.usageClear(t,e),_("Traffic history reset"))&&(le(),s())},"negative")])}var il={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"",s4:"",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},al={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 ll(t){let e={};for(let[o,s]of Object.entries(al))t[o]!=null&&t[o]!==""&&(e[s]=String(t[o]));return e}function dl(t,e){let o=t.amnezia,s=o.obfuscation??{},r=d=>s[d]!=null&&s[d]!==""?String(s[d]):il[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),a={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...ll(s),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:t.conf.replace(/\r?\n/g,`\r +`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(a),port:String(o.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0],l.dns2=o.dns[1]||o.dns[0]),l}function cl(t){let e="";for(let o=0;o"u")return null;try{let o=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),s=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+s.length);return new DataView(r.buffer).setUint32(0,t.length,!1),r.set(s,4),r}catch{return null}}async function Po(t,e,o=!0){let s=new TextEncoder().encode(JSON.stringify(dl(t,e))),r=o?await pl(s):null;return`vpn://${cl(r??s)}`}function rr(){return[{id:"off",title:_("Off"),ic:"zap",stealth:0,speed:4,text:_("Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block."),apps:_("Any WireGuard app"),short:_("Any WireGuard app")},{id:"balanced",title:_("Balanced"),ic:"shield",stealth:3,speed:4,needs:"v2",text:_("AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk."),apps:_("AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps"),short:_("AmneziaWG 2.0+ apps")},{id:"max",title:_("Maximum"),ic:"lock",stealth:4,speed:3,needs:"v3",text:_("AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS."),apps:_("Apps with AmneziaWG 3.1 (current AmneziaVPN)"),short:_("AmneziaWG 3.1 apps")}]}var Xt=t=>rr().find(e=>e.id===t),$n=t=>t.v3?"max":t.v2?"balanced":"off",en=t=>t==="standard"?_("Standard (old)"):t==="strong"?_("Strong (old)"):null;function ul(t,e){return e?t==="v2"?_("Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on)."):_("Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."):t==="v2"?_("Needs AmneziaWG on the router."):_("Needs AmneziaWG 3.1 on the router: install it first.")}function sr(t,e){return n("span",{class:"dl-dots",title:m(_("%s: %s of 4"),e,t)},[n("span",{class:"dl-dots-label"},e),n("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>n("i",{class:odom.content(i,rr().map(l=>{let d=!l.needs||t[l.needs],c=l.id===e;return n("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,a(),o(l.id))}},[n("div",{class:"dl-method-head"},[n("span",{class:"dl-method-ic"},v(l.ic)),n("b",{},l.title),l.id===s?n("span",{class:"dl-pill ok"},_("Current")):""]),n("p",{},l.text),n("div",{class:"dl-method-meters"},[sr(l.stealth,_("Stealth")),sr(l.speed,_("Speed"))]),n("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),n("span",{},l.apps)]:[v("alert"),n("span",{},ul(l.needs,r))])])}));return a(),i}function ir(t,e){return n("div",{class:"dl-corehead"},[n("h3",{},t),e?n("span",{class:"dl-sub"},e):""])}var ar=[["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 ml(t,e){let o=p=>p==="header_protection_key"?e:t[p]!=null&&t[p]!=="",s=ar.filter(([p])=>o(p));if(!s.length)return null;let r=(p,u)=>n("span",{class:"dl-pv"},[n("i",{},u),n("b",{},p==="header_protection_key"?_("set","key"):t[p])]),i=(p,u,g,M)=>{let x=ar.filter(([h])=>M.includes(h)&&o(h));return x.length?n("div",{class:"dl-pgroup"},[n("div",{class:"dl-pgroup-head"},[v(u),n("b",{},p)]),n("p",{},g),n("div",{class:"dl-pvals"},x.map(([h,S])=>r(h,S)))]):""},a=Number(t.jc||0),l=(t.i1??"").includes("0x8580")?_("A first packet shaped like a DNS answer."):_("Extra packets sent before the handshake."),d=s.filter(([p])=>p!=="header_protection_key").map(([p,u])=>`${u} = ${t[p]}`).join(` +`),c=n("div",{class:"dl-pgrid"},[i(_("Junk packets"),"zap",a?m(N_(a,"%s random packet of %s–%s bytes before each handshake.","%s random packets of %s–%s bytes before each handshake."),V(a),t.jmin,t.jmax):_("No junk packets."),["jc","jmin","jmax"]),i(_("Padding"),"archive",_("Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard."),["s1","s2","s3","s4"]),i(_("Packet types"),"key",_("The values that replace WireGuard’s recognisable message types."),["h1","h2","h3","h4"]),i(_("Signatures"),"globe",l,["i1","i2","i3","i4","i5"]),i(_("Protection"),"lock",_("AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets."),["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),i(_("Timing"),"clock",_("Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."),["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return n("details",{class:"dl-params"},[n("summary",{},[v("chevron"),n("span",{},_("Current parameters")),n("span",{class:"dl-pcount"},String(s.length)),n("span",{class:"dl-spacer"}),n("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),xe(d,e?_("Parameters copied. The header protection key is in each device’s file."):_("Parameters copied"))}},_("Copy as config"))]),c])}function lr(t,e){if(/^\s*\[.+\]\s*$/.test(t))return n("span",{class:"dl-conf-sec"},t);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(t);if(!o)return document.createTextNode(t);let s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(t);return n("span",{},[n("span",{class:"dl-conf-k"},o[1])," ",s&&!e?n("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function hl(t){let e=!1,o=n("pre",{class:"dl-conf"}),s=()=>dom.content(o,t.conf.split(` +`).flatMap((a,l)=>l?[` +`,lr(a,e)]:[lr(a,e)])),r=n("button",{type:"button",class:"dl-chipbtn",click:a=>{a.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[v("key"),_("Show key")]);s();let i=new Blob([t.conf]).size;return n("div",{class:"dl-stack gap8"},[n("div",{class:"dl-filecard"},[n("span",{class:"dl-filecard-ic"},".conf"),n("span",{class:"dl-stack"},[n("span",{class:"dl-mono dl-ellipsis"},t.filename),n("span",{class:"dl-sub"},`AmneziaWG · ${G(i,"%s byte","%s bytes")}`)]),H([v("download")," ",_("Download")],()=>Ae(t.filename,t.conf,"application/octet-stream"),"positive")]),n("details",{class:"dl-params"},[n("summary",{},[v("chevron"),n("span",{},_("Configuration")),n("span",{class:"dl-spacer"}),r,n("button",{type:"button",class:"dl-chipbtn",click:a=>{a.preventDefault(),xe(t.conf,_("Configuration copied"))}},[v("copy"),_("Copy")])]),o])])}function $o(t){let e=t.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([s,r])=>r==null||r===""||r===(o[s]??"0"))}async function fl(t,e="file"){if(!t.has_private_key)return n("div",{class:"dl-hint"},_("This device generated its own keys in the browser, so its full configuration only exists on that device."));let o=await Po(t,t.server),s={qr:()=>n("div",{class:"dl-qr-pane"},[_n(t.conf),n("span",{class:"dl-sub"},$o(t)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),key:()=>n("div",{class:"dl-stack gap8"},[n("div",{class:"dl-linkbox"},[n("span",{class:"dl-mono"},o),H(_("Copy"),()=>xe(o,_("Key copied")))]),n("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>hl(t)},r=n("div",{class:"dl-connect-body"}),i=n("div",{class:"dl-seg"}),a=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,s[l]())};for(let[l,d]of[["file",_("File")],["key",_("Key")],["qr",_("QR code")]])i.appendChild(n("button",{type:"button","data-id":l,click:()=>a(l)},d));return a(e),n("div",{class:"dl-stack gap12"},[i,r])}async function gl(t,e,o,s){let r=Xt(o),a=t.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await pe(s?_("Generate new disguise values?"):m(_("Switch to %s?"),r.title),[G(a,"%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).","%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."),o==="max"?_("They need an app with AmneziaWG 3.1."):o==="balanced"?_("They need an app with AmneziaWG 2.0 or newer."):"",t.st.servers.length===1&&a?_("To keep the old disguise for some people, add a second server and move them there."):""].filter(Boolean).join(" "),s?_("Generate and apply"):_("Switch and apply"),!0)&&await q(()=>N.serverObfuscation(e.id,o),s?_("New values applied"):m(_("%s applied"),r.title))&&(F(_("Devices are marked “Update config” until they import again."),"info",6e3),await t.refresh())}function vl(t,e){let o=t.st,s=ue(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=ue(e.mtu?String(e.mtu):"",{placeholder:_("Auto"),inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ue(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=Xt(e.preset)?e.preset:void 0,l=a??$n(o.awg),d=H("",()=>gl(t,e,l,l===a),"neutral"),c=()=>dom.content(d,l===a?[v("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Xt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],g=Ce(_("UDP port"),s,()=>Jt(Number(s.value),u,[_("Opened on the WAN firewall automatically."),Number(s.value)===4500?_("4500 is IPsec’s port: most networks let it through."):""].filter(Boolean).join(" ")));N.serverPorts(e.id).then(h=>{u=h.udp_taken??[],g.refresh()}).catch(()=>{});let M=Ce("MTU",r,()=>$s(r.value,e.mtus)),x=Ce(_("Keep-alive"),i,()=>Ds(i.value));return Vt("",[ir("AmneziaWG",e.ifname),ye("globe",_("Listening"),_("Where devices reach this core from the internet"),[g]),ye("file",_("In every device configuration"),_("Changing these marks devices “Update config” until they import again"),[M,x]),ye("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[en(e.preset)?yt("warn",oe(_("%s is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to %s or %s: devices import their configuration again."),n("b",{},en(e.preset)),n("b",{},_("Balanced")),n("b",{},_("Maximum")))):"",Dn(o.awg,l,h=>{l=h,c()},a,p),p&&!o.awg.v3?yt("info",oe(_("This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1."),n("b",{},_("Maximum")))):"",ml(e.obf??{},e.hpk)??"",n("div",{class:"dl-row-end"},[n("span",{class:"dl-sub"},_("Applies at once: every AmneziaWG device imports its configuration again.")),d])]),n("details",{class:"dl-params"},[n("summary",{},[v("chevron"),n("span",{},_("Tunnel")),n("span",{class:"dl-pcount"},"3")]),n("div",{class:"dl-params-body"},[ge(_("Interface"),n("span",{class:"dl-mono"},`${e.ifname} · ${m(_("router %s"),e.address)}`)),ge(_("Tunnel subnet"),n("span",{class:"dl-mono"},e.subnet),_("Device addresses come from it.")),ge(_("Server public key"),n("span",{class:"dl-keyrow"},[n("code",{class:"dl-mono"},e.public_key),H([v("copy")],()=>xe(e.public_key,_("Public key copied")),"neutral",{title:_("Copy"),class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[n("span",{class:"dl-sub"},_("Port, MTU and keep-alive apply at once.")),H(_("Save"),()=>{let h=Be([g,M,x]);if(h){F(h,"warning");return}return t.save({port:s.value,mtu:r.value,keepalive:i.value},_("AmneziaWG saved"))},"positive")])}function bl(t){let e=Xt(t.preset),o=t.obf??{},s=(a,l)=>n("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>n("i",{class:d+o[a]).map(a=>`${a.toUpperCase()} ${o[a]}`);return i.length&&r.push(i.slice(0,2).join(" · ")+(i.length>2?` +${i.length-2}`:"")),["h1","h2","h3","h4"].some(a=>o[a]&&o[a]!==String(["h1","h2","h3","h4"].indexOf(a)+1))&&r.push(_("H1–H4 random")),o.i1&&r.push(/0x(8580|0100)0001/.test(o.i1)?_("DNS-like first packets"):_("Signature packets")),t.hpk&&r.push(_("Encrypted headers")),r.length||r.push(e?.id==="off"?_("Plain WireGuard"):_("No values yet")),n("div",{class:"dl-bento-tile dl-disg"},[n("div",{class:"dl-bento-head"},[n("span",{class:"dl-metric-label"},_("Disguise")),n("a",{href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(t.id)}§ion=awg`},_("Change"))]),n("div",{class:"dl-disg-id"},[n("span",{class:`dl-disg-ic${e?.id==="off"?" off":""}`},v(e?.ic??"shield")),n("span",{class:"dl-stack"},[n("b",{},e?e.title:en(t.preset)??_("Custom","disguise")),n("span",{class:"dl-sub"},e?e.short:en(t.preset)?_("Switch to Balanced or Maximum"):_("Set by hand"))])]),e?n("div",{class:"dl-disg-meters"},[n("span",{},_("Stealth")),s(e.stealth,"acc"),n("span",{},_("Speed")),s(e.speed,"ok")]):"",n("div",{class:"dl-disg-chips"},r.map(a=>n("span",{},a)))])}var Do={id:"awg",label:"AmneziaWG",settingsCard:vl,overviewTile:bl,connectBlock:fl,qrText:t=>t.conf,appKey:{get label(){return _("Copy AmneziaVPN config")},make:t=>Po(t,t.server)},file:{get label(){return _("Download AmneziaWG config")},make:t=>({name:t.filename,text:t.conf})}};var xl={awg:Do};function Fe(t){return xl[t?.core||"awg"]??Do}function Ot(t,e){return Fe(t.find(o=>o.id===e))}var wl=2,tn=new Set,Ao=null,An=null;async function dr(){if(document.visibilityState!=="visible"||!tn.size)return;let t=await N.rev().catch(()=>null);if(!t)return;let e=Ao!=null&&t.rev!==Ao;Ao=t.rev,t.version&&(An&&t.version!==An?(F(m(_("Dawnline was updated to %s: reload the page."),t.version),"warning",15e3),An=null):An??(An=t.version)),e&&tn.forEach(o=>o())}function Nn(t){return tn.add(t),poll.add(dr,wl),()=>{tn.delete(t),tn.size||poll.remove(dr)}}function ur(t,e,o,s,r=0){let i=[],a=null,l=p=>{a&&p>a.from&&i.push({...a,to:p}),a=null},d=t.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&&(a={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&&(a={ip:u,from:p.ts,to:p.ts,live:!1})}else p.type==="disconnect"&&l(p.ts);let c=a;return c&&s?i.push({...c,to:Math.max(o,c.from),live:!0}):l(Math.min(o,r)),i}function et(t){return`${t.city||`${t.lat.toFixed(1)},${t.lon.toFixed(1)}`}|${t.cc}`}function mr(t,e,o,s){let r=new Map;for(let a of e)(a.device===o||!r.has(a.ip))&&r.set(a.ip,a);let i=[];for(let a of t){let l=r.get(a.ip);!l||a.to<=s||i.push({key:et(l),point:l,from:Math.max(a.from,s),to:a.to,live:a.live})}return i}function hr(t){let e=new Map,o=0;for(let s of t)e.set(s.key,(e.get(s.key)??0)+(s.to-s.from)),o+=s.to-s.from;return new Map([...e].map(([s,r])=>[s,o?r/o:0]))}function cr(t,e=2700){let o=[];for(let s of t){let r=o[o.length-1];if(r&&s.key!==r.key&&!s.live&&s.to-s.from{i&&(o.push({kind:"move",k:i,start:s,ms:e}),s+=e);let a=Math.min(1100,Math.max(350,(r.to-r.from)/3600*45));o.push({kind:"stay",k:i,start:s,ms:a}),s+=a}),{steps:o,total:s}}function br(t,e,o){let s=e.findIndex(l=>o>=l.start&&oo>=a.from&&oa.kind==="stay"&&a.k===s),i=t[s];return r.start+r.ms*Math.min(.999,Math.max(0,(o-i.from)/Math.max(1,i.to-i.from)))}var yl=t=>t<=0?0:t>=1?1:t<.5?2*t*t:1-(-2*t+2)**2/2;function wr(t){return-No/2+(1+No)*yl((t-pr)/(1-pr))}var yr=t=>t+gr>=1;function kr(t){return["interpolate",["linear"],["abs",["-",["get","pos"],t]],0,1,gr,1,No/2,0]}function _r(t,e){let o=t==="24h"?86400:t==="7d"?604800:2592e3,s=e-o,r=[],i=(l,d)=>{let c=(l-s)/o;c>.02&&c<.98&&r.push([c,d])},a=new Date(s*1e3);if(t==="24h")for(a.setMinutes(0,0,0);a.getTime()/1e3<=e;)a.getHours()%6===0&&i(a.getTime()/1e3,`${String(a.getHours()).padStart(2,"0")}:00`),a.setHours(a.getHours()+1);else if(t==="7d")for(a.setHours(12,0,0,0);a.getTime()/1e3<=e;a.setDate(a.getDate()+1))i(a.getTime()/1e3,a.toLocaleDateString(ie(),{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(ie(),{day:"numeric",month:"short"}))}r.reverse()}return r}var Hn=t=>new Date(t*1e3).toLocaleTimeString(ie(),{hour:"2-digit",minute:"2-digit"});function Cr(t,e){let o=s=>new Date(s*1e3).toDateString();return o(t)===o(e)?_("Today"):o(t)===o(e-86400)?_("Yesterday"):new Date(t*1e3).toLocaleDateString(ie(),{weekday:"short",day:"numeric",month:"short"})}var zo="https://unpkg.com/maplibre-gl@6.14.0/dist",Lr={module:"sha384-q26X6R1yFeg0QR9SHHn6U3Nb0ddRRTtwxsahubv5R89/v5nijKpk9KviUp9ZLySk",css:"sha384-1TZtfVz7qtwR5vD7cMwjGT+9uiK4lqE3pbUOPwYO6OCpb+TYP0S9vLIhG02JCU04"},Mr="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",Er="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",kl={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},nn=null;function _l(t){if(t.appendChild(n("link",{rel:"stylesheet",href:`${zo}/maplibre-gl.css`,integrity:Lr.css,crossorigin:"anonymous"})),nn)return nn;let e=`${zo}/maplibre-gl.mjs`;return nn=new Promise((s,r)=>{let i=n("link",{rel:"modulepreload",href:e,integrity:Lr.module,crossorigin:"anonymous"});i.addEventListener("load",()=>s()),i.addEventListener("error",()=>r(new Error("integrity"))),document.head.appendChild(i)}).then(()=>import(e)).then(s=>(s.getWorkerUrl()||s.setWorkerUrl(`${zo}/maplibre-gl-worker.mjs`),s),s=>{throw nn=null,new Error(s?.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?)"))}),nn}var Cl=10,Tr=30,Ll=62,Ml=4,Sr=4.5,El=7,zn="#3b82f6",Ro="#8a8a8a";function Pr(t,e,o=.2,s=64){let[r,i]=t,[a,l]=e,d=a-r,c=d>180?a-360:d<-180?a+360:a,p=c-r,u=l-i,g=Math.hypot(p,u);if(g===0||o===0)return[t,[c,l]];let M=-u/g,x=p/g,h=g*o,S=(r+c)/2+M*h,B=(i+l)/2+x*h,P=[],R=Math.max(2,Math.floor(s));for(let w=0;w<=R;w+=1){let k=w/R,y=1-k;P.push([y*y*r+2*y*k*S+k*k*c,y*y*i+2*y*k*B+k*k*l])}return P}function Io(t,e){let o=new Map;for(let s of t.geo.points){if(t.person&&s.person!==t.person||t.device&&s.device!==t.device||(e==="online"?!s.online:t.now-s.ts>kl[e]))continue;let r=t.device?et(s):t.person?`${s.device}|${s.city}|${s.cc}`:s.device,i=o.get(r);(!i||s.online&&!i.online||s.online===i.online&&s.ts>i.ts)&&o.set(r,s)}return[...o.values()]}function Oo(t,e){let o=0;return Io(t,e).sort((s,r)=>Number(r.online)-Number(s.online)||r.ts-s.ts).map(s=>({...s,n:s.online?0:++o}))}var ct=class{constructor(e,o="online",s=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=o,this.status=n("div",{class:"dl-map-status"}),this.card=n("div",{class:"dl-map-card","aria-live":"polite"}),this.el=n("div",{class:"dl-geomap",style:`height:${s}px`},[this.status,this.card])}async mount(e){this.data=e;try{this.gl=await _l(this.el)}catch(s){this.status.textContent=s.message;return}if(this.dead)return;this.map=new this.gl.Map({container:this.el,style:_t()?Mr:Er,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 s=this.el.querySelector(".maplibregl-ctrl-attrib");s?.classList.remove("maplibregl-compact-show"),s?.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 o=_t();this.theme=new MutationObserver(()=>{!this.map||_t()===o||(o=_t(),this.map.setStyle(o?Mr:Er))}),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"],zn,Ro],"circle-opacity":["case",["get","online"],.12,.06],"circle-stroke-width":1,"circle-stroke-color":["case",["get","online"],zn,Ro],"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":zn,"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?zn:Ro,"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 o=new Map;for(let s of e){let r=`${s.person}|${et(s)}`,i=o.get(r);i||(i={key:r,person:s.person,lat:s.lat,lon:s.lon,city:s.city,country:s.country,cc:s.cc,asn:s.asn,org:s.org,online:!1,ts:0,points:[]},o.set(r,i)),i.points.push(s),i.online||(i.online=s.online),i.ts=Math.max(i.ts,s.ts)}return[...o.values()]}draw(){if(!this.map||!this.data||!this.map.getSource("dl-arcs"))return;let e=this.data,o=this.groups(Io(e,this.range)),s=e.person||e.device?null:e.geo.home;for(let d of this.markers)d.remove();this.markers=[];let r=e.person||e.device?null:Sl(o,s),i=o.map(d=>({g:d,at:r?.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:s?i.map(({g:d,at:c})=>({type:"Feature",properties:{online:d.online,person:d.person,key:d.key},geometry:{type:"LineString",coordinates:Pr([s.lon,s.lat],c)}})):[]}),s){let d=n("span",{class:"dl-mk-host"});d.innerHTML=`${Mt("server","dl-mk-host-ic")}`,this.dock=d.appendChild(n("span",{class:"dl-mk-dock"})),this.dockQuiet=this.dockKey!=="",this.dockKey="";let c=n("div",{class:"dl-mk-hub",title:`${_("Home router")}${s.city?` · ${s.city}`:""}${s.org?` · ${s.org}`:""}`},[d,n("span",{class:"dl-mk-label chip"},s.city||_("Home"))]);c.addEventListener("mouseenter",()=>this.showMerged(s.city)),c.addEventListener("mouseleave",()=>this.focus(this.focused)),c.addEventListener("click",()=>this.zoomToMerged()),this.add(c,[s.lon,s.lat],!0)}let a=new Map(e.device?Oo(e,this.range).map(d=>[et(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(h=>h.id===d.person);if(e.person){let h=e.device?this.deviceMarker(d,c,u,a.get(et(d))??0):this.placeMarker(d,c,u);this.add(h,c);continue}let g=d.points.map(h=>u?.devices.find(S=>S.id===h.device)?.kind??"other"),M=n("span",{class:"dl-mk-badge"});M.innerHTML=p<=2?g.map(h=>Mt(h,"dl-mk-badge-ic")).join(""):String(p);let x=n("button",{type:"button",class:`dl-mk${d.online?" online":""}`,"aria-label":d.city?m(N_(p,"%s: %s device in %s","%s: %s devices in %s"),u?.name??_("Someone"),V(p),d.city):m(N_(p,"%s: %s device in an unknown city","%s: %s devices in an unknown city"),u?.name??_("Someone"),V(p))},[n("span",{class:"dl-mk-av"},[Oe(u?.name??"?"),M]),n("span",{class:"dl-mk-label below"},d.city||d.cc||"?")]);x.addEventListener("mouseenter",()=>this.focus(d.person)),x.addEventListener("mouseleave",()=>this.focus(null)),this.people.push({el:x,person:d.person}),x.addEventListener("click",h=>{h.stopPropagation(),this.openPopup(d,c,x)}),this.add(x,c,!1,u?.name??_("Someone"),`${d.city||d.cc||"?"} · ${d.online?_("now"):ce(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,s&&!i.length){let c={center:[s.lon,s.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);s&&(c.length===0||this.range!=="online"||i.some(p=>p.g.online))&&c.push([s.lon,s.lat]),this.fit(c,d)}}this.status.textContent=i.length||s?"":_("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,o,s=!1,r,i,a,l){a&&this.foldedKeys.has(a)&&e.classList.add("merged"),a&&this.piledKeys.has(a)&&e.classList.add("piled"),e.dataset.key=a??"",e.classList.add("dl-mk-new"),requestAnimationFrame(()=>requestAnimationFrame(()=>e.classList.remove("dl-mk-new")));let d=new this.gl.Marker({element:e}).setLngLat(o).addTo(this.map);this.markers.push(d),this.slots.push({marker:d,el:e,at:o,fixed:s,who:r,where:i,g:l})}declutter(){if(!this.map)return;let e=this.map.getZoom();this.el.classList.toggle("dl-lod-far",e=Sr&&e{let l=this.map.project(a.at),d=a.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:a.fixed}}),s=o.filter(a=>a.fixed);this.merged=[],this.foldedKeys.clear();let r=this.targetZoom==null?1:Math.min(1,2**(this.targetZoom-this.map.getZoom()));o.forEach((a,l)=>{if(a.fixed)return;let d=this.slots[l],c=d.el.classList.contains("merged")?12:6,p=s.find(u=>Math.hypot(u.x-a.x,u.y-a.y)*r{let c=this.slots[d];!c||c.fixed||(o[d].fixed&&([a,l]=[0,0]),c.marker.setOffset([a,l]),$l(c.el,a,l))})}closePopup(e=!1){let o=this.popup;if(!o||o.card.classList.contains("leaving"))return;o.card.classList.add("leaving"),setTimeout(()=>{this.popup===o&&this.dropCard()},140);let s=this.before;if(this.before=null,!s)return;let r=()=>this.map?.flyTo({...s,duration:800});if(!e)return r();let i=!1,a=()=>{i||(i=!0,window.removeEventListener("pointerup",a,!0),window.removeEventListener("pointercancel",a,!0),setTimeout(r,0))};window.addEventListener("pointerup",a,!0),window.addEventListener("pointercancel",a,!0),setTimeout(a,1500)}dropCard(){this.popup?.off(),this.popup?.card.remove(),this.popup=null}showMerged(e){this.merged.length&&(dom.content(this.card,[n("div",{class:"dl-map-card-head"},[n("b",{},e?m(_("Near %s"),e):_("Near the server")),` · ${_("click to zoom in")}`]),...this.merged.map(o=>n("div",{class:"dl-map-card-row"},[n("span",{},o.who),n("span",{class:"dl-faint"},o.where)]))]),this.card.classList.add("on"))}paintDock(){let e=this.dock;if(!e)return;let o=this.merged.map(r=>`${r.key}:${r.online?1:0}`).join("|");if(o===this.dockKey)return;this.dockKey=o,e.parentElement?.classList.toggle("docked",this.merged.length>0);let s=this.slots.find(r=>r.fixed).at;this.merged.length&&Dr(e,this.merged,this.faceActions(()=>[s]),this.dockQuiet),this.dockQuiet=!1}faceActions(e){return{click:(o,s)=>this.openFace(o,s,e()),hover:o=>this.focus(o?.g?.person??null)}}pileUp(e){let o=new Set;if(!this.data?.person&&!this.data?.device){let s=e.flatMap((l,d)=>!l.fixed&&this.slots[d].el.querySelector(":scope > .dl-mk-av")?[d]:[]),r=new Map(s.map(l=>[l,l])),i=l=>r.get(l)===l?l:i(r.get(l));for(let l of s)for(let d of s){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[h]),c=d.map($r),p=c.map(h=>h.key).sort().join(",");o.add(p);let u=[d.reduce((h,S)=>h+S.at[0],0)/d.length,d.reduce((h,S)=>h+S.at[1],0)/d.length],g=this.piles.get(p);if(!g){let h=n("span",{class:"dl-mk-pile-box"}),S=[...new Set(d.map(R=>R.g?.city||R.g?.cc||"?"))],B=n("div",{class:"dl-mk-pile"},[h,n("span",{class:"dl-mk-label below"},S.length===1?S[0]:G(d.length,"%s person","%s people"))]);g={marker:new this.gl.Marker({element:B}).setLngLat(u).addTo(this.map),el:B,box:h,faces:c},B.addEventListener("mouseleave",()=>this.focus(this.focused));let P=g;B.addEventListener("click",R=>{R.stopPropagation(),this.zoomInTo(P.faces.map(w=>w.at),!1)}),this.piles.set(p,g)}g.faces=c;let M=g;Dr(g.box,c,this.faceActions(()=>M.faces.map(h=>h.at)));for(let h of l)this.slots[h].el.classList.add("piled"),Object.assign(e[h],{r:0,fixed:!0});let x=this.map.project(u);e.push({x:x.x,y:x.y,r:(g.el.offsetWidth||60)/2+3,fixed:!0})}}this.piledKeys=new Set(this.slots.filter(s=>s.el.classList.contains("piled")).map(s=>s.el.dataset.key??"")),this.slots.forEach((s,r)=>{(!e[r].fixed||s.fixed||s.el.classList.contains("merged"))&&s.el.classList.remove("piled")});for(let[s,r]of this.piles)o.has(s)||(this.piles.delete(s),r.el.classList.add("out"),setTimeout(()=>r.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,o,s){if(!e.g)return;if(s.every(i=>Rn(i,e.at)<1))return this.openPopup(e.g,e.at,o);let r=()=>{let i=this.slots.find(a=>a.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",r):r()}nearby(e){return[e,...this.slots.filter(o=>!o.fixed&&o.at!==e&&Rn(o.at,e)<=Tr).map(o=>o.at)]}zoomInTo(e,o){let s=new this.gl.LngLatBounds;for(let p of e)s.extend(p);let r=e.some(p=>e.some(u=>Rn(p,u)>Tr)),i=this.map.cameraForBounds(s,{padding:50,maxZoom:r?12:Cl}),a=this.map.getZoom(),l=e.map(p=>this.map.project(p)),d=0;l.forEach((p,u)=>l.slice(u+1).forEach(g=>{let M=Math.hypot(p.x-g.x,p.y-g.y),x=a+Math.log2(Ll/Math.max(M,1e-6));x<=12&&(d=Math.max(d,x))}));let c=Math.min(12,Math.max(i?.zoom??0,d));return c<=a+.05?!1:(o&&!this.before&&(this.before={center:this.map.getCenter().toArray(),zoom:a}),this.map.flyTo({center:i?.center??s.getCenter(),zoom:c,duration:800}),!0)}placeMarker(e,o,s){let r=this.data.now,i=[...e.points].sort((u,g)=>Number(g.online)-Number(u.online)||g.ts-u.ts)[0],a=s?.devices.find(u=>u.id===i.device)?.kind??"other",l=e.points.length,d=n("span",{class:"dl-mk-tile"});d.innerHTML=Mt(a,"dl-mk-tile-ic")+(l>1?`${l}`:"");let c=e.online?_("now"):ce(e.ts,r),p=n("button",{type:"button",class:`dl-mk place${e.online?" online":""}`,style:e.online?null:`--dl-mk-fade:${Math.max(.4,1-.6*(r-e.ts)/(30*86400)).toFixed(2)}`,"aria-label":e.city?m(N_(l,"%s device in %s, %s","%s devices in %s, %s"),V(l),e.city,c):m(N_(l,"%s device in an unknown city, %s","%s devices in an unknown city, %s"),V(l),c)},[d,n("span",{class:"dl-mk-label below"},[e.city||e.cc||"?",n("span",{class:"dl-mk-when"},c)])]);return p.addEventListener("click",u=>{u.stopPropagation(),this.openPopup(e,o,p)}),p}deviceMarker(e,o,s,r){let i=s?.devices.find(p=>p.id===e.points[0].device)?.kind??"other",a=n("span",{class:"dl-mk-tile"}),l=n("span",{class:"dl-mk-label below"}),d=n("button",{type:"button",class:"dl-mk place step"},[a,l]);d.addEventListener("click",p=>{p.stopPropagation(),this.openPopup(e,o,d)});let c=et(e);return this.places.set(c,{el:d,tile:a,label:l,when:null,g:e,n:r,kind:i}),this.paintPlace(c,!1),d}paintPlace(e,o){let s=this.places.get(e);if(!s)return;let r=this.replaying,i=r?r.active===e:s.g.online,a=s.el.classList.contains("online"),l=s.g.city||s.g.cc||"?";s.el.classList.toggle("online",i),s.el.classList.toggle("faded",!!r&&!i),s.tile.classList.toggle("sm",!i),i||!s.n?s.tile.innerHTML=Mt(s.kind,"dl-mk-tile-ic"):s.tile.textContent=String(s.n),s.when=null,i?(s.when=n("span",{class:`dl-mk-when${r?" inline":""}`},r?r.when:_("now")),s.label.replaceChildren(l,r?" · ":"",s.when)):s.label.replaceChildren(`${l} · ${s.g.online?_("now"):ce(s.g.ts,this.data.now)}`);let d=i?r?r.when:_("now"):s.g.online?_("now"):ce(s.g.ts,this.data.now);s.el.setAttribute("aria-label",`${s.n?`${s.n}: `:""}${s.g.city||_("an unknown city")}, ${d}`),o&&i&&!a&&(s.el.classList.remove("arrive"),s.el.offsetWidth,s.el.classList.add("arrive"),setTimeout(()=>s.el.classList.remove("arrive"),500))}replay(e,o=!0){let s=this.replaying;if(this.replaying=e,s&&e&&s.active===e.active){let r=e.active?this.places.get(e.active):null;r?.when&&(r.when.textContent=e.when);return}for(let r of this.places.keys())r!==e?.active&&this.paintPlace(r,o);e?.active&&this.paintPlace(e.active,o),this.declutter(),setTimeout(()=>this.declutter(),320)}hoverPlace(e){for(let[o,s]of this.places)s.el.classList.toggle("hl",o===e)}band(e,o){if(this.bandDots=[],this.map&&e&&o){let s=Pr(e,o),r=s.map(c=>this.map.project(c)),i=[0];for(let c=1;ci[d]?(p-i[d])/(i[d+1]-i[d]):0,g=[s[d][0]+(s[d+1][0]-s[d][0])*u,s[d][1]+(s[d+1][1]-s[d][1])*u];this.bandDots.push({type:"Feature",properties:{pos:c/l},geometry:{type:"Point",coordinates:g}})}}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",kr(e))}focus(e){this.focused=e;for(let a of this.people)a.el.classList.toggle("dim",!!e&&a.person!==e),a.el.classList.toggle("hl",a.person===e);let o=e?["case",["==",["get","person"],e],.85,.15]:.85;for(let a of["dl-arc-live","dl-arc-recent"])this.map?.getLayer(a)&&this.map.setPaintProperty(a,"line-opacity",o);if(this.card.classList.toggle("on",!!e),!e||!this.data)return;let s=this.data,r=s.people.find(a=>a.id===e),i=Io(s,this.range).filter(a=>a.person===e).sort((a,l)=>Number(l.online)-Number(a.online)||l.ts-a.ts);dom.content(this.card,[n("div",{class:"dl-map-card-head"},[n("b",{},r?.name??e),` · ${G(i.length,"%s device","%s devices")}`]),...i.map(a=>n("div",{class:"dl-map-card-row"},[n("span",{},r?.devices.find(l=>l.id===a.device)?.name??_("Device")),n("span",{class:"dl-faint"},`${a.city||a.cc||"?"} · ${a.online?_("now"):ce(a.ts,s.now)}`)]))])}fit(e,o=!1){if(!e.length)return;let s=(p,u)=>{let g=Math.PI/180,M=(u[1]-p[1])*g,x=(u[0]-p[0])*g,h=Math.sin(M/2)**2+Math.cos(p[1]*g)*Math.cos(u[1]*g)*Math.sin(x/2)**2;return 12742*Math.asin(Math.sqrt(h))},r=[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,g)=>s(r,u)-s(r,g));i=p.slice(0,Math.ceil(p.length*.9))}let a=new this.gl.LngLatBounds(i[0],i[0]);i.forEach(p=>a.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};o?this.glide(this.map.cameraForBounds(a,c)?.zoom??null,()=>this.map.fitBounds(a,{...c,duration:1200})):this.map.fitBounds(a,{...c,duration:0})}glide(e,o){this.targetZoom=e,this.declutter(),this.map.once("moveend",()=>{this.targetZoom=null,this.declutter()}),o()}openPopup(e,o,s){let r=this.data,i=[e.city,e.cc||e.country].filter(Boolean).join(", "),a=[...new Set(e.points.map(w=>w.person))],l=a.length===1?r.people.find(w=>w.id===a[0])?.name:void 0,d=e.points.sort((w,k)=>Number(k.online)-Number(w.online)||k.ts-w.ts).map(w=>{let k=r.people.find(O=>O.id===w.person),y=k?.devices.find(O=>O.id===w.device);return n("button",{type:"button",class:"dl-pop-row",click:()=>this.cb.openDevice(w.person,w.device)},[n("span",{class:`dl-pop-dot${w.online?" on":""}`}),n("span",{class:"dl-pop-name"},[n("b",{},k?.name??w.person),` · ${y?.name??_("device")}`]),n("span",{class:"dl-faint dl-nowrap"},w.online?_("now"):ce(w.ts,r.now))])}),c=n("div",{class:"dl-pop"},[n("div",{class:"dl-pop-head"},[n("span",{class:"dl-pop-net"},v("globe")),n("div",{class:"dl-stack"},[n("strong",{},e.org||_("Unknown network")),n("span",{class:"dl-faint"},[e.asn?`AS${e.asn} · `:"",i?`${i} · ${_("approximate")}`:_("approximate location")])])]),n("div",{class:"dl-pop-list"},d),a.length===1?n("div",{class:"dl-pop-actions"},[n("button",{type:"button",class:"cbi-button cbi-button-positive important",click:()=>this.cb.openPerson(a[0])},l?m(_("Open %s"),l):_("Open person"))]):""]);this.zoomInTo(this.nearby(o),!0),this.dropCard();let p=n("div",{class:"dl-root dl-popcard",role:"dialog"},[n("span",{class:"dl-popcard-tip"}),c]);document.body.appendChild(p);let u=this.el,g=s?.querySelector(".dl-mk-av, .dl-mk-tile")??s??null,M=()=>{if(!g)return;let w=g.getBoundingClientRect(),k=u.getBoundingClientRect(),y=w.left+w.width/2,O=w.top+w.height/2;p.classList.toggle("away",yk.right||Ok.bottom);let b=p.offsetWidth,f=p.offsetHeight,T=w.top-f-12>=8||w.top>window.innerHeight-w.bottom,C=Math.min(Math.max(8,y-b/2),window.innerWidth-b-8);p.classList.toggle("above",T),p.classList.toggle("below",!T),p.style.left=`${C}px`,p.style.top=`${T?w.top-f-12:w.bottom+12}px`,p.style.setProperty("--tip-x",`${y-C}px`)},x=w=>{w.target?.closest(".dl-popcard, .maplibregl-marker")||this.closePopup(!0)},h=w=>{w.key==="Escape"&&this.closePopup()},S=w=>{w.target instanceof Element&&w.target.closest(".dl-popcard")||this.closePopup()},B=()=>this.closePopup();this.map.on("move",M),window.addEventListener("scroll",S,{capture:!0,passive:!0}),window.addEventListener("resize",M),document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",h);let P=Ee(B);window.addEventListener("pagehide",B),this.popup={card:p,off:()=>{this.map?.off("move",M),window.removeEventListener("scroll",S,!0),window.removeEventListener("resize",M),document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",h),P(),window.removeEventListener("pagehide",B)}};let R=window.setInterval(()=>{if(this.popup?.card!==p)return clearInterval(R);(!u.isConnected||!u.getClientRects().length)&&this.dropCard()},400);M()}};function Tl(t,e=6){let o=t.map(s=>({x:s.x,y:s.y}));for(let s=0;s<16;s++){let r=!1;for(let i=0;i[s.x-t[r].x,s.y-t[r].y])}function Sl(t,e){let o=new Map,s=e?[[e.lon,e.lat]]:[],r=i=>s.some(a=>Rn(i,a)<1.3);for(let i of[...t].sort((a,l)=>a.key>>12)/1048575),d=(a&4095)/4096*2*Math.PI,c=[i.lon,i.lat];for(let p=0;p<24;p++){let u=d+p*2.39996,g=Math.min(8,l+p*.25);if(c=[i.lon+g*Math.sin(u)/(111.32*Math.cos(i.lat*Math.PI/180)),i.lat+g*Math.cos(u)/111.32],!r(c))break}s.push(c),o.set(i.key,c)}return o}function Pl(t){let e=2166136261;for(let o=0;o>>0}function $r(t){return{key:t.el.dataset.key??"",who:t.who??_("Someone"),where:t.where??"",online:!!t.g?.online,at:t.at,badge:t.el.querySelector(".dl-mk-badge")?.innerHTML??"",g:t.g}}function Dr(t,e,o,s=!1){let r=e.length>3,i=()=>[...t.children].filter(x=>!x.classList.contains("out")),a=new Map(i().map(x=>[x,x.getBoundingClientRect().left])),l=t.getBoundingClientRect().width,d=new Map;t.querySelectorAll(".dl-mk-face:not(.out)").forEach(x=>d.set(x.dataset.key??"",x));let c=t.querySelector(".dl-mk-more:not(.out)"),p=x=>{Object.assign(x.style,{position:"absolute",left:`${x.offsetLeft}px`,top:`${x.offsetTop}px`,transform:""}),x.classList.add("out"),setTimeout(()=>x.remove(),200)},u=[];for(let x of e.slice(0,r?2:3)){let h=d.get(x.key);if(d.delete(x.key),!h){let P=n("button",{type:"button",class:`dl-mk-face${s?"":" in"}`,"data-key":x.key},[n("span",{class:"dl-mk-av"},Oe(x.who)),n("span",{class:"dl-mk-badge"})]);P.addEventListener("animationend",()=>P.classList.remove("in"),{once:!0}),h=P}let S=h,B=S.querySelector(".dl-mk-badge");B.innerHTML!==x.badge&&(B.innerHTML=x.badge),S.title=`${x.who} · ${x.where}`,S.setAttribute("aria-label",`${x.who}, ${x.where}`),S.classList.toggle("on",x.online),S.onclick=P=>{P.stopPropagation(),o.click(x,S)},S.onmouseenter=()=>o.hover(x),S.onmouseleave=()=>o.hover(null),u.push(S)}for(let x of d.values())p(x);if(r){if(!c){c=n("span",{class:`dl-mk-more${s?"":" in"}`});let x=c;x.addEventListener("animationend",()=>x.classList.remove("in"),{once:!0})}c.textContent=`+${e.length-2}`,u.push(c)}else c&&p(c);let g=null;for(let x of u)(g?g.nextElementSibling:t.firstElementChild)!==x&&(g?g.after(x):t.prepend(x)),g=x;for(let x of u){let h=a.get(x);if(h==null)continue;let S=h-x.getBoundingClientRect().left;Math.abs(S)<.5||(x.style.transition="none",x.style.transform=`translateX(${S}px)`,x.offsetWidth,x.style.transition="",x.style.transform="")}t.style.width="";let M=t.getBoundingClientRect().width;if(l&&Math.abs(M-l)>.5){t.style.width=`${l}px`,t.offsetWidth,t.style.width=`${M}px`;let x=()=>{t.style.width="",t.removeEventListener("transitionend",x)};t.addEventListener("transitionend",x),setTimeout(x,400)}}function Rn(t,e){let o=Math.PI/180,s=Math.sin((e[1]-t[1])*o/2)**2+Math.cos(t[1]*o)*Math.cos(e[1]*o)*Math.sin((e[0]-t[0])*o/2)**2;return 12742*Math.asin(Math.min(1,Math.sqrt(s)))}function $l(t,e,o){let s=t.querySelector(":scope > .dl-mk-ptr"),r=Math.hypot(e,o);if(r<1){s?.remove();return}s||(s=n("span",{class:"dl-mk-ptr"},[n("i",{class:"line"}),n("i",{class:"spot"})]),t.prepend(s));let i=s.firstElementChild,a=s.lastElementChild;i.style.width=`${r}px`,i.style.transform=`rotate(${Math.atan2(-o,-e)}rad)`,a.style.transform=`translate(${-e}px, ${-o}px)`}function Bt(t,e,o=!0){let s=[["online",_("Online now")],["24h",_("24h")],["7d",_("7 days")],["30d",_("30 days")]],r=n("div",{class:"dl-seg",role:"tablist"});for(let[i,a]of s)i==="online"&&!o||r.appendChild(n("button",{type:"button",role:"tab",class:i===t?"on":"","data-v":i,click:()=>{r.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.v===i)),e(i)}},a));return r}var Ar={"24h":86400,"7d":7*86400,"30d":30*86400},Bo=(t,e)=>`${(t/e*100).toFixed(3)}%`,In=class{constructor(e,o,s){this.map=e;this.range=o;this.el=n("div",{class:"dl-dplaces"});this.controls=n("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=n("button",{type:"button",class:"dl-map-btn"});this.chip=n("span",{class:"dl-map-chip"});this.stop=n("button",{type:"button",class:"dl-map-btn",title:_("Back to now"),"aria-label":_("Back to now")},v("x"));this.reduced=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;this.data=s,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 o={...this.pending??this.data,...e};if(this.on){this.pending=o;return}this.data=o,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,o=Ar[this.range],s=e.now-o,r=mr(ur(e.events??[],e.device.id,e.now,e.device.online,e.device.handshake),e.geo.points,e.device.id,s),i=hr(r);this.st=fr(r);let a=Oo(this.mapData(),this.range),l=r.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,a.length?[...a.map(d=>{let c=et(d),p=i.get(c),u=l?n("div",{class:`dl-dplace-strip${d.online?" live":""}`},r.filter(M=>M.key===c).map(M=>n("i",{style:`left:${Bo(M.from-s,o)};width:${Bo(M.to-M.from,o)}`}))):"",g=n("div",{class:"dl-dplace-row"},[n("span",{class:`dl-dplace-n${d.online?" live":""}`},d.online?v(e.device.kind):String(d.n)),n("span",{class:"dl-row-main dl-stack"},[n("span",{},[d.city||d.cc||_("Unknown city"),d.org?n("span",{class:"dl-muted"},` · ${d.org}`):""]),n("span",{class:"dl-faint"},[n("span",{class:"dl-mono"},d.ip),p!=null?` · ${m(_("%s%% of the time"),p>0&&p<.005?"<1":Math.round(p*100))}`:""])]),n("span",{class:d.online?"dl-dplace-now":"dl-faint dl-nowrap"},d.online?_("now"):ce(d.ts,e.now)),u]);if(g.addEventListener("mouseenter",()=>this.map.hoverPlace(c)),g.addEventListener("mouseleave",()=>this.map.hoverPlace(null)),u){let M=x=>{let h=u.getBoundingClientRect();this.seek(s+o*Math.min(1,Math.max(0,(x.clientX-h.left)/h.width)))};u.addEventListener("pointerdown",x=>{u.setPointerCapture(x.pointerId),M(x)}),u.addEventListener("pointermove",x=>x.buttons&&M(x))}return this.rows.set(c,g),g}),l?n("div",{class:"dl-dplace-axis"},_r(this.range,e.now).map(([d,c])=>n("span",{style:`left:${(d*100).toFixed(2)}%`},c))):""]:n("div",{class:"dl-sub"},_("No locations in this period."))),this.paintControls()}paintControls(){dom.content(this.play,v(this.playing?"pause":"play")),this.play.title=this.playing?_("Pause","replay"):_("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}=vr(this.st,this.reduced?400:Ho),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(o));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=xr(this.st,this.steps,e),this.stepI=-1,this.show(!1),this.paintControls())}show(e){let o=br(this.st,this.steps,this.ms),s=this.st[o.step.k];if(o.step.kind==="move"){let a=this.st[o.step.k-1];o.i!==this.stepI&&(this.map.replay({active:null,when:""},e),this.map.band([a.point.lon,a.point.lat],[s.point.lon,s.point.lat]));let l=wr(o.q);this.reduced||this.map.bandAt(l),(this.reduced?o.q>=.5:yr(l))&&this.map.replay({active:s.key,when:Hn(o.t)},e)}else o.i!==this.stepI&&this.map.band(),this.map.replay({active:s.key,when:Hn(o.t)},e);this.stepI=o.i;let r=this.data,i=r.now-Ar[this.range];this.el.classList.add("replay"),this.el.style.setProperty("--at",Bo(o.t-i,r.now-i));for(let[a,l]of this.rows)l.classList.toggle("cur",a===s.key);this.chip.textContent=`${Cr(o.t,r.now)}, ${Hn(o.t)} · ${s.point.city||s.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 jt(t){return`${L.url("admin/network/dawnline/server")}?${t?`server=${encodeURIComponent(t)}&`:""}section=people`}function He(t,e){return`${L.url("admin/network/dawnline/person")}?id=${encodeURIComponent(t)}${e?`&device=${encodeURIComponent(e)}`:""}`}function Nr(t){let e=So(t.state);return e?[n("span",{class:"dl-dstat warn"},e.title),n("span",{class:"dl-sub"},e.line)]:null}function Dl(t,e){return e?t.kind==="phone"||t.kind==="tablet"?e.mtus.phone:e.mtus.computer:t.mtu?null:t.mtu_used??null}function Hr(t,e,o,s,r,i,a){let l=Me(e,o,s);ae(t,[l],[de()," ",H(_("Save"),async()=>{let d=l.help();if(d.bad){F(d.text,"warning");return}await q(()=>N.deviceUpdate(i,void 0,void 0,r()),_("Saved"))&&(le(),await a())},"positive")]),setTimeout(()=>o.select(),50)}function zr(t,e){return n("input",{type:"text",class:"cbi-input-text",inputmode:"numeric",maxlength:4,value:t==null?"":String(t),placeholder:e})}function Al(t,e,o){let s=Dl(t,e),r=zr(t.mtu||null,s?m(_("Automatic: %s"),s):null);Hr(m(_("MTU of %s"),t.name),"MTU",r,()=>As(r.value),()=>({mtu:r.value.trim()}),t.id,o)}function Nl(t,e,o){let s=zr(t.keepalive,e?m(_("As the server: %s"),e.keepalive):null);Hr(m(_("Keep-alive of %s"),t.name),_("Keep-alive"),s,()=>Ns(s.value),()=>({keepalive:s.value.trim()}),t.id,o)}function Rr(t,e,o,s){let r=Kt(e,o),i=(l,d,c,p)=>n("span",{class:"dl-kv-act"},[n("span",{},[l,d?[" ",n("span",{class:"dl-faint"},d)]:""]),n("button",{type:"button",class:"dl-linkbtn","aria-label":c,click:p},_("Change"))]),a=t.keepalive_used;return[["MTU",i(t.mtu_used==null?"—":String(t.mtu_used),t.mtu?"":_("automatic"),_("Change the MTU"),()=>Al(t,o,s))],[_("Keep-alive"),i(a==null?"—":a?m(_("%s s"),a):_("Off"),t.keepalive!=null?"":_("as the server"),_("Change the keep-alive"),()=>Nl(t,o,s))],[_("LAN Bypass"),n("span",{},[t.lan_bypass?r.length?m(_("On, except %s (home)"),bn(r)):_("On"):_("Off")," ",n("span",{class:"dl-faint"},_("set when it was added"))])]]}function Hl(t){return t?new Date(t*1e3).toLocaleString(ie(),{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function jo(t,e,o=!1){return n("div",{class:"dl-kvrow"},[n("span",{class:"dl-kvrow-k"},t),n("button",{type:"button",class:`dl-kvrow-v copy${o?" dl-mono":""}`,title:_("Copy"),click:()=>xe(e,m(_("%s copied"),t))},[n("span",{},e),v("copy")])])}function on(t,e){return n("div",{class:"dl-kvrow"},[n("span",{class:"dl-kvrow-k"},t),n("span",{class:"dl-kvrow-v"},e)])}var Ir={connect:["ok","plug"],disconnect:["","plug"],roam:["","network"],device_added:["ok","plus"],device_removed:["","trash"],device_keys:["","reset"]};function zl(t){let e=s=>n("span",{class:"dl-muted"},s),o=Ve(t)==="portal"?_("on the portal"):Ve(t)==="admin"?_("by you"):"";switch(t.type){case"connect":return[...t.detail?oe(_("Connected from %s"),e(t.detail)):[_("Connected")],t.where?e(` · ${t.where}`):""];case"disconnect":return[_("Went offline")];case"roam":return[_("Changed network"),e(` · ${t.detail??""}`)];case"device_added":return o?oe(_("Added %s"),e(o)):[_("Added")];case"device_removed":return o?oe(_("Removed %s"),e(o)):[_("Removed")];default:return o?oe(_("New keys %s"),e(o)):[_("New keys")]}}function Rl(t,e,o){let s=t.filter(r=>r.device===e&&Ir[r.type]).reverse().slice(0,12);return s.length?n("div",{class:"dl-dev-log"},s.map(r=>{let[i,a]=Ir[r.type],l=new Date(r.ts*1e3);return n("div",{class:`dl-dev-log-row${Ve(r)==="admin"?" dl-ev-by-admin":""}`},[Ve(r)==="admin"?n("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):n("span",{class:`dl-ev-tile ev ${i}`},v(a)),n("span",{class:"dl-row-main"},zl(r)),n("span",{class:"dl-faint dl-nowrap",title:l.toLocaleString(ie())},ce(r.ts,o))])})):n("div",{class:"dl-sub"},_("No activity yet."))}async function Or(t,e,o){let s=await N.status(1).catch(()=>null),r=s?.people.find(a=>a.id===t),i=r?.devices.find(a=>a.id===e);s&&r&&i&&Ye(r,i,{...o,geo:s.geo,now:s.now,today:Ge(s.series),core:Ot(s.servers,r.server),server:s.servers.find(a=>a.id===r.server)})}function Il(t,e,o){let s=n("div",{class:"dl-row-actions"});return dom.content(s,H([v("qr")," ",_("Show the new configuration")],async()=>{let r=await q(()=>N.deviceConfig(t,!0));r&&(s.className="",dom.content(s,await e(r)),o())})),s}async function Ye(t,e,o){let s=await q(()=>N.deviceConfig(e.id));if(!s)return;let r=o.core??Fe(null),i=e,a=t,l=o.geo,d=o.now,c=o.today??qe(new Date),p=o.server,u=$=>r.connectBlock($,e.kind==="phone"||e.kind==="tablet"?"qr":"file"),g=e.config_stale,M=!1,x=()=>Il(e.id,u,()=>(g=!1,A())),h=g?x():await u(s),S=n("div",{class:"dl-drawer-title"}),B=n("div",{}),P=n("div",{}),R=n("div",{},n("div",{class:"dl-sub"},_("Loading…"))),w=[],k=$=>{w=$.filter(E=>E.device===i.id),dom.content(R,Rl($,i.id,d)),f?.update({events:$})},y=async($=!1)=>{let E=o.events?.();if(E&&!$)return k(E);let I=await N.events(2e3,t.id).catch(()=>null);I&&k(I.events)},O="30d",b=null,f=null,T=()=>{dom.content(S,[n("span",{class:`dl-dcard-ic${i.online?" on":""}`},v(i.kind)),n("div",{class:"dl-stack"},[n("div",{class:"dl-title-row"},[n("h3",{},i.name),H([v("edit")],()=>K(),"neutral",{title:_("Rename"),class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),n("span",{class:"dl-sub"},`${a.name} · ${at(i.kind)}`)])]);let $=i.spark.map(([I,D])=>I+D),E=$.reduce((I,D)=>I+D,0);dom.content(B,n("div",{class:"dl-dstats"},[n("div",{class:"dl-dstats-cell wide"},[n("span",{class:"dl-metric-label"},_("Status")),i.link&&!i.disabled&&Nr(i.link)||xn(i,d,_("Waiting for the first connection"),a)]),n("div",{class:"dl-dstats-cell"},[n("span",{class:"dl-metric-label"},_("This month")),n("b",{},se(i.month[0]+i.month[1])),n("span",{class:"dl-sub dl-mono"},`↓ ${se(i.month[1])} ↑ ${se(i.month[0])}`)]),n("div",{class:"dl-dstats-cell"},[n("span",{class:"dl-metric-label"},_("Last 7 days")),n("b",{},se(E)),er($,120,22,c)])])),dom.content(P,n("div",{class:"dl-kv2"},[jo(_("Tunnel address"),i.address),...Rr(i,a,p,()=>(M=!0,A())).map(([I,D])=>on(I,D)),i.hostname&&a.access!=="internet"?jo(_("Local address"),i.hostname):"",i.endpoint&&!l?.points.some(I=>I.device===i.id&&I.ip===i.endpoint)?on(_("Client IP"),i.endpoint):"",on(_("Total"),n("span",{class:"dl-kv-act"},[`↓ ${se(i.total[1])} · ↑ ${se(i.total[0])}`,n("button",{type:"button",class:"dl-linkbtn danger",click:()=>It("device",i.id,i.name,()=>setTimeout(A,300))},_("Reset"))])),on(_("Added"),`${Hl(i.created)} · ${i.created_by==="portal"?_("from the portal"):_("by you")}`),s.amnezia.client_pub_key?jo(_("Public key"),s.amnezia.client_pub_key):on(_("Public key"),"—")])),dom.content(Y,[H([v(i.disabled?"play":"pause")," ",i.disabled?_("Enable"):_("Disable")],async()=>{await q(()=>N.deviceUpdate(i.id,void 0,!i.disabled),i.disabled?_("Device enabled"):_("Device disabled"))&&await A()},"neutral",i.disabled?{}:{class:"cbi-button cbi-button-neutral dl-btn-warn"}),H([v("key")," ",_("New keys")],async()=>{if(!await pe(_("Generate new keys?"),_("The current configuration on this device stops working until it is imported again."),_("Generate"),!0))return;await q(()=>N.deviceRotate(i.id),_("New keys generated"))&&(o.refresh(),z.close(),await Or(a.id,i.id,o))}),n("span",{class:"dl-spacer"}),H([v("trash")," ",_("Remove")],async()=>{await pe(m(_("Remove %s?"),i.name),_("The device is disconnected immediately and its configuration stops working."),_("Remove"),!0)&&await q(()=>N.deviceDelete(i.id),_("Device removed"))&&(z.close(),o.refresh())},"negative")])},C=async()=>{let $=await N.status(1).catch(()=>null),E=$?.people.find(D=>D.id===a.id),I=E?.devices.find(D=>D.id===i.id);!$||!E||!I||(a=E,i=I,l=$.geo,d=$.now,c=Ge($.series),p=$.servers.find(D=>D.id===E.server),T(),(i.config_stale||M)&&!g&&(g=!0,dom.content(j,Q(x()))),M=!1,f?.update({geo:$.geo,now:$.now,person:a,device:i}))},A=async()=>{await C(),o.refresh()},K=()=>{let $=n("input",{type:"text",class:"cbi-input-text",value:i.name}),E=jr($,()=>D.refresh()),I=a.devices.filter(W=>W.id!==i.id).map(W=>W.name),D=Me(_("Name"),$,()=>E(Co($.value,I,_("Shown in the portal and in the app."))));ae(m(_("Rename %s"),i.name),[D],[de()," ",H(_("Save"),async()=>{let W=D.help();if(W.bad){F(W.text,"warning");return}await q(()=>N.deviceUpdate(i.id,$.value,void 0),_("Renamed"))&&(le(),await A())},"positive")]),setTimeout(()=>$.select(),50)},Y=n("div",{class:"dl-drawer-actions"}),Q=$=>[n("div",{class:"dl-dsec-head"},[n("h4",{},_("Connect","section"))]),i.config_stale?wt(_("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.")):"",$],j=n("section",{class:"dl-dsec"},Q(h)),Z=n("section",{class:"dl-dsec"},[n("div",{class:"dl-dsec-head"},[n("h4",{},_("Activity")),n("div",{class:"dl-dsec-actions"},[n("button",{type:"button",class:"dl-linkbtn",click:()=>Xe({people:[a]},w,"csv",i.id)},_("Export")),n("button",{type:"button",class:"dl-linkbtn danger",click:()=>dt(m(_("Clear %s's activity"),i.name),m(_("Removes events about %s."),i.name),{device:i.id},()=>{y(!0),o.refresh()})},_("Clear")),n("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},_("All activity"))])]),R]),te=n("section",{class:"dl-dsec"},[n("div",{class:"dl-dsec-head"},n("h4",{},_("Details","section"))),P]),me="";if(l?.enabled){b=new ct({openPerson:E=>location.href=He(E),openDevice:(E,I)=>location.href=He(E,I)},O,220);let $=f=new In(b,O,{geo:l,now:d??Date.now()/1e3,person:a,device:i,events:o.events?.()??null});me=n("section",{class:"dl-dsec"},[n("div",{class:"dl-dsec-head"},[n("h4",{},_("Locations")),Bt(O,E=>{O=E,$.setRange(E)},!1)]),n("div",{class:"dl-dmap"},[b.el,$.controls]),$.el])}let ke=!i.handshake||i.config_stale,U=n("div",{class:"dl-stack gap16"},ke?[B,j,te,me,Z]:[B,te,me,Z,j]);y();let ne=()=>{C(),y()},he=Nn(ne),fe=window.setInterval(ne,3e4),z=xs(S,U,Y,()=>{clearInterval(fe),he(),f?.destroy(),b?.destroy()});T(),b&&f&&requestAnimationFrame(()=>f&&b?.mount(f.mapData()))}function Br(t,e,o,s){let r=s.core??Fe(null),i=()=>q(()=>N.deviceConfig(o.id,!0)),a=[{label:_("Show QR code"),icon:v("qr"),run:async()=>{let l=await i();l&&ae(`${o.name} · ${_("QR code")}`,n("div",{class:"dl-qr-pane"},[_n(r.qrText(l)),n("span",{class:"dl-sub"},$o(l)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),de(_("Close")))}},{label:r.file.label,icon:v("download"),run:async()=>{let l=await i();if(!l)return;let d=r.file.make(l);Ae(d.name,d.text,"application/octet-stream")}},r.appKey?{label:r.appKey.label,icon:v("copy"),run:async()=>{let l=await i();l&&xe(await r.appKey.make(l),_("Key copied"))}}:null,null,{label:_("Rename"),icon:v("edit"),run:()=>Ye(e,o,s)},{label:_("New keys"),icon:v("key"),run:async()=>{await pe(_("Generate new keys?"),_("The current configuration on this device stops working until it is imported again."),_("Generate"),!0)&&await q(()=>N.deviceRotate(o.id),_("New keys generated"))&&s.refresh()}},{label:o.disabled?_("Enable"):_("Disable"),icon:v(o.disabled?"play":"pause"),warn:!o.disabled,run:async()=>{await q(()=>N.deviceUpdate(o.id,void 0,!o.disabled),o.disabled?_("Device enabled"):_("Device disabled"))&&s.refresh()}},{label:_("Delete"),icon:v("trash"),danger:!0,run:async()=>{await pe(m(_("Remove %s?"),o.name),_("The device is disconnected immediately and its configuration stops working."),_("Remove"),!0)&&await q(()=>N.deviceDelete(o.id),_("Device removed"))&&s.refresh()}}];Te(t,a)}function jr(t,e){let o=null;return Gs(t,t,s=>{o=s,e()}),t.addEventListener("blur",()=>{o&&(o=null,e())}),s=>o?{text:o,bad:!0}:s}function pt(t,e){let o=t.devices.map(u=>u.name),s=u=>{let g=hs(u),M=1,x=go(g);for(;o.some(h=>h.toLowerCase()===x.toLowerCase());)x=go(g,` ${++M}`);return x},r="phone",i=n("input",{type:"text",class:"cbi-input-text",placeholder:s(r)}),a=jr(i,()=>l.refresh()),l=Me(_("Name"),i,()=>a(i.value.trim()?Co(i.value,o,_("Shown in the portal and in the app.")):{text:m(_("Named after its type: %s."),s(r)),bad:!1})),d=n("div",{class:"dl-kinds",role:"radiogroup","aria-label":_("Type")},fs.map(u=>n("button",{type:"button",role:"radio",class:u===r?"on":"","aria-checked":u===r?"true":"false","data-kind":u,click:()=>{r=u,d.querySelectorAll("button").forEach(g=>{let M=g.dataset.kind===u;g.classList.toggle("on",M),g.setAttribute("aria-checked",M?"true":"false")}),i.placeholder=s(u),l.refresh()}},[v(u),n("span",{},at(u))]))),c=be(!1,_("LAN Bypass")),p=t.devices.length>=t.device_limit;ae(m(_("Add a device for %s"),t.name),[p?n("p",{class:"dl-hint"},m(N_(t.device_limit,"%s already has %s of %s device. As admin you can still add one.","%s already has %s of %s devices. As admin you can still add one."),t.name,V(t.devices.length),V(t.device_limit))):"",n("div",{class:"dl-fld"},[n("span",{class:"dl-fld-label"},_("Type")),d]),n("div",{class:"cbi-value dl-live"},[n("div",{class:"cbi-value-title"},[n("label",{},_("LAN Bypass")),n("div",{class:"dl-sub"},Kt(t,e.server).length?m(_("The device’s local network stays reachable while connected, except %s: your home network."),bn(Kt(t,e.server))):_("The device’s local network stays reachable while connected."))]),n("div",{class:"cbi-value-field"},c)]),l],[de()," ",H(_("Add device"),async()=>{let u=l.help();if(u.bad){F(u.text,"warning");return}let g=i.value.trim()||s(r),M=await q(()=>N.deviceCreate(t.id,g,r,De(c)));M&&(le(),F(m(_("%s added"),g),"success",3e3),e.refresh(),await Or(t.id,M.id,e))},"positive")]),setTimeout(()=>i.focus(),50)}var tt=1080,rn=1512,Je=96,Ol="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",Bl="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",sn=t=>t.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]);function jl(t,e,o){let s=new URL(o),r=s.pathname.slice(1),i=m(_("Hi, %s"),t.name),a=Math.min(92,Math.floor((tt-2*Je)/(.58*i.length))),l=tt-2*Je,d=392,c=40,p=kn(o,2).replace("`${S}`;return``+u(Je+82,Je+42,36,"#a3a3a3",sn(e))+u(Je,276,a,"#ffffff",sn(i),'font-weight="600"')+u(Je,340,40,"#8a8a8a",sn(m(_("Scan to connect to %s"),e)))+``+p+`${sn(r)}`+u(tt/2,d+l+156,34,"#737373",sn(s.host),'text-anchor="middle"')+""}async function Ul(t){let e=new Image;e.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`,await e.decode();let o=document.createElement("canvas");return o.width=tt,o.height=rn,o.getContext("2d").drawImage(e,0,0,tt,rn),new Promise((s,r)=>o.toBlob(i=>i?s(i):r(new Error(_("Could not draw the card"))),"image/png"))}async function Ur(t){let e=await q(()=>N.personLinks(t));return e?e.link?{link:e.link,links:e.links??[]}:(F(_("The personal portal is off. Turn it on in Settings."),"warning"),null):null}async function On(t){let e=await Ur(t);e&&await xe(e.link,_("Personal link copied"))}async function an(t,e,o={}){let s=t.link,r=t.links;if(s===void 0){let h=await Ur(t.id);if(!h)return;s=h.link,r=h.links}if(!s){F(_("The personal portal is off. Turn it on in Settings."),"warning");return}let i=s,a=await q(()=>Ul(jl(t,e,i)));if(!a)return;let l=new File([a],`${t.id}-invite.png`,{type:"image/png"}),d=URL.createObjectURL(a),c=navigator,p=!!c.canShare?.({files:[l]}),u=!p&&typeof c.share=="function"&&(c.canShare?.({url:i})??!0),g=()=>{URL.revokeObjectURL(d),le()},M=async h=>{try{await c.share(h)}catch{}},x=p?H([v("link")," ",_("Share card")],()=>M({files:[l],title:m(_("Invite %s"),t.name)}),"positive"):u?H([v("link")," ",_("Share link")],()=>M({url:i,title:m(_("Invite %s"),t.name),text:_("Your personal VPN link")}),"positive"):H([v("download")," ",_("Download card")],()=>Ae(l.name,a),"positive");ae(o.title??m(_("Invite %s"),t.name),n("div",{class:"dl-invite"},[n("img",{src:d,alt:m(_("Invite card for %s"),t.name)}),n("div",{class:"dl-invite-side"},[n("p",{class:"dl-muted"},o.lead??m(_("Send %s the card or the link. They open it, add their devices and connect - no account needed."),t.name)),n("button",{type:"button",class:"dl-invite-link",title:_("Copy link"),click:()=>xe(i,_("Personal link copied"))},[n("span",{},i.replace(/^https:\/\//,"")),v("copy")]),...(r??[]).filter(h=>h!==i).map(h=>n("button",{type:"button",class:"dl-invite-link alt",title:_("Copy this link"),click:()=>xe(h,_("Link copied"))},[n("span",{},h.replace(/^https?:\/\//,"")),n("span",{class:`dl-pill ${h.startsWith("http:")?"warn":""}`},h.startsWith("http:")?"HTTP":_("Also")),v("copy")])),n("ol",{class:"dl-invite-steps"},[n("li",{},oe(_("Install %s on the device"),n("b",{},"AmneziaVPN"))),n("li",{},_("Open the link or scan the code")),n("li",{},_("Add the device and connect"))]),n("div",{class:"dl-invite-actions"},[x,H([v("copy")," ",_("Copy link")],()=>xe(i,_("Personal link copied")))])])]),[n("button",{class:"cbi-button cbi-button-neutral",click:g},_("Done"))],"wide")}function ln(t,e){let o=t.servers.find(d=>d.id===e)??t.servers[0],s=t.people.filter(d=>d.server===o.id),r=new Set(s.map(d=>d.id)),i=s.flatMap(d=>d.devices),a=d=>s.reduce((c,p)=>{let u=d(p);return[c[0]+u[0],c[1]+u[1]]},[0,0]),l=o.series?.[o.series.length-1];return{...t,servers:[o],people:s,series:o.series??t.series,events:t.events.filter(d=>d.person?r.has(d.person):!0),geo:{...t.geo,points:t.geo.points.filter(d=>r.has(d.person))},totals:{people:s.length,devices:i.length,online:i.filter(d=>d.online).length,active:s.filter(d=>d.state==="active").length,today:l?[l.rx,l.tx]:[0,0],month:a(d=>d.month)}}}var Wr=3,Uo=class{constructor(){this.n=0;this.shown=0}next(){return++this.n}take(e){return e{let g=e.next(),M=null;try{M=await t.fetch(u),o>=Wr&&F(_("The router answers again."),"success",3e3),o=0}catch{return++o===Wr&&F(_("The router is not answering: what you see may be out of date."),"warning",8e3),null}return M==null||!e.take(g)?null:(t.apply(M,p),M)},r=(p=!1)=>s(p,!1),i=()=>document.visibilityState==="visible",a=()=>i()&&(t.active?.()??!0)?s(!0,!1):Promise.resolve(null);poll.add(a,t.every);let l=t.live?Nn(()=>void(i()&&(t.active?.()??!0)&&s(!0,!0))):null,d=()=>{poll.remove(a),l?.(),c()},c=Ee(d);return{refresh:r,claim:()=>e.claim(),stop:d}}function ut(t){let e=document.activeElement;return!!t&&!!e&&e!==document.body&&t.contains(e)}function Ne(t,e,o=!1){return o&&ut(t)?!1:(dom.content(t,e),!0)}function Gr(t,e){let o=t,s=[{v:"internet",ic:"globe",text:_("Browse the internet through your router. No access to devices at home.")},{v:"lan",ic:"home",text:_("Reach devices at home (NAS, printer, cameras). Internet stays on their own connection.")},{v:"both",ic:"shield",text:_("Home devices and the internet, all through your router.")}],r=n("div",{class:"dl-choices"},s.map(i=>n("button",{type:"button",class:`dl-choice${i.v===o?" selected":""}`,"data-v":i.v,click:()=>{o=i.v,r.querySelectorAll(".dl-choice").forEach(a=>a.classList.toggle("selected",a.dataset.v===i.v)),e?.(i.v)}},[n("span",{class:"dl-choice-title"},[v(i.ic),bt(i.v)]),n("span",{class:"dl-choice-text"},i.text)])));return{el:r,get:()=>o}}function Wo(t){try{return localStorage.getItem(t)}catch{return null}}function Go(t,e){try{localStorage.setItem(t,e)}catch{}}function Wl(t){let e=t.devices.length,o=Math.max(1,t.device_limit,e),s=Math.min(160,o*22+(o-1)*3);return n("div",{class:"dl-slotbar",title:m(N_(t.device_limit,"%s of %s device","%s of %s devices"),e,t.device_limit)},[n("span",{class:"dl-slotbar-segs",style:`width: ${s}px`},Array.from({length:o},(r,i)=>n("i",{class:i>=t.device_limit?"over":it.state==="server_off"?t.paused:!["active","quota","expired"].includes(t.state),Fo=t=>t.state==="server_off"?t.paused:t.state!=="active",qr=t=>Fo(t)?t.state==="server_off"?"paused":t.state:null;function Gl(t,e){let o=rt(t.expires,e);return t.state==="quota"||t.state==="expired"||it(t,o)||!!t.quota_limit&&t.quota_used>=t.quota_limit*.9}function Kr(t,e){return St(t&&fo(t,e)>=0?t:e,1)}var Vr=t=>t.people.map(e=>e.id).sort().join(" "),Yr=!1,Ct=class{constructor(){this.list=n("div",{class:"dl-plist",role:"list"});this.filter=["all","online","attention","paused"].find(e=>e===(new URLSearchParams(location.search).get("filter")??Wo("dl.people.filter")))??"all";this.sort=["seen","name","usage"].find(e=>e===Wo("dl.people.sort"))??"seen";this.query="";this.noFooter=!0;this.serverId=null;this.el=null}async load(){return N.status(30)}scope(e){return this.serverId?ln(e,this.serverId):e}embed(e,o){return this.serverId=o,this.render(e)}person(e){return this.st.people.find(o=>o.id===e)}get today(){return Ge(this.st.series)}deviceOpts(e){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:Ot(this.st.servers,e.server),server:this.st.servers.find(o=>o.id===e.server)}}take(e,o){let s=this.scope(e),r=Vr(s)!==Vr(this.st);this.st=s,r?this.rebuild():(this.paintCards(o),this.decorate(o))}async update(){await this.poller?.refresh()}async refresh(){this.poller?.claim();let e=await N.status(30).catch(()=>null);e&&(this.st=this.scope(e),this.rebuild())}rebuild(){let e=new Map;for(let s of Array.from(this.list.children))s.dataset.sid&&e.set(s.dataset.sid,s);let o=this.st.people.map(s=>{let r=e.get(s.id)??n("div",{class:"dl-card",role:"listitem","data-sid":s.id});return this.renderCard(r,s.id)});dom.content(this.list,o.length?o:n("div",{class:"dl-plist-none"},this.st.servers.length?_("No people yet. Add someone and send them their personal link."):_("Set up the server first, then add people."))),this.decorate()}paintCards(e=!1){for(let o of this.st.people){let s=this.card(o.id);s&&!(e&&ut(s))&&this.renderCard(s,o.id)}}card(e){return this.list.querySelector(`[data-sid="${CSS.escape(e)}"]`)}render(e){let o=this.scope(e);this.st=o;let s=this,r=n("select",{class:"dl-select","aria-label":_("Sort"),change:d=>{s.sort=d.target.value,Go("dl.people.sort",s.sort),s.decorate()}},[n("option",{value:"seen",selected:s.sort==="seen"?"selected":null},_("Last seen","sort")),n("option",{value:"name",selected:s.sort==="name"?"selected":null},_("Name","sort")),n("option",{value:"usage",selected:s.sort==="usage"?"selected":null},_("Usage","sort"))]),i=n("input",{type:"search",class:"cbi-input-text dl-people-find",placeholder:_("Find…"),"aria-label":_("Find a person or device"),hidden:o.people.length>8?null:"hidden",input:d=>{s.query=d.target.value.trim().toLowerCase(),s.decorate()}}),a=d=>{let c=d.target;d.key==="/"&&!i.hidden&&!["INPUT","TEXTAREA","SELECT"].includes(c?.tagName)&&!c?.isContentEditable&&(d.preventDefault(),i.focus())};document.addEventListener("keydown",a),Ee(()=>document.removeEventListener("keydown",a));let l=n("div",{class:"dl-root"},[s.serverId?"":n("div",{class:"dl-pagehead"},[n("div",{class:"dl-stack"},[n("h2",{class:"dl-h1"},_("People")),n("span",{class:"dl-muted dl-people-count"},this.countText())]),o.servers.length?H([v("plus"),` ${_("Add person")}`],()=>s.openCreate(),"add"):""]),o.servers.length?"":n("div",{class:"alert-message warning"},oe(_("No server yet. %s before adding people."),n("a",{href:L.url("admin/network/dawnline/server")},_("Run the setup wizard")))),n("div",{class:"dl-toolbar"},[n("div",{class:"dl-seg dl-people-tabs",role:"tablist"}),n("div",{class:"dl-toolbar-end"},[i,r,s.serverId?H([v("plus"),` ${_("Add person")}`],()=>s.openCreate(),"add"):""])]),this.list]);return this.el=l,this.rebuild(),this.poller??(this.poller=nt({fetch:()=>N.status(30),every:30,live:!0,active:()=>!!s.el?.isConnected,apply:(d,c)=>s.take(d,c)})),!Yr&&new URLSearchParams(location.search).get("add")&&(Yr=!0,setTimeout(()=>s.openCreate(),100)),Promise.resolve(l)}countText(){let e=this.st.totals;return[G(e.people,"%s person","%s people"),G(e.devices,"%s device","%s devices"),m(_("%s online"),V(e.online))].join(" · ")}decorate(e=!1){let o=this.el?.querySelector(".dl-people-count");o&&(o.textContent=this.countText());let s=this.st.people,r=this.today,i=h=>Gl(h,r),a={all:s.length,online:s.filter(h=>h.online>0).length,attention:s.filter(i).length,paused:s.filter(h=>Fr(h)).length},l=this.el?.querySelector(".dl-people-tabs");if(l&&!(e&&ut(l))){let h={all:_("All"),online:_("Online"),attention:_("Needs attention"),paused:_("Paused")};dom.content(l,Object.keys(h).map(S=>n("button",{type:"button",role:"tab",class:S===this.filter?"on":"",click:()=>{this.filter=S,Go("dl.people.filter",S),this.decorate()}},[h[S],n("b",{class:S==="attention"&&a[S]?"warn":""},String(a[S]))])))}let d=this.query,c=h=>[h.name,h.note??"",...h.devices.flatMap(S=>[S.name,S.address,S.hostname,S.endpoint])].join(" ").toLowerCase(),p=h=>!(this.filter==="online"&&!h.online||this.filter==="attention"&&!i(h)||this.filter==="paused"&&!Fr(h)||d&&!c(h).includes(d)),u=h=>qr(h)==="paused"?2:Fo(h)?1:0,g=[...s].sort((h,S)=>u(h)-u(S)||(this.sort==="name"?h.name.localeCompare(S.name):this.sort==="usage"?S.month[0]+S.month[1]-(h.month[0]+h.month[1]):S.online-h.online||S.last_seen-h.last_seen)),M=0;for(let h of g){let S=this.card(h.id);if(!S)continue;this.list.appendChild(S),S.classList.toggle("dl-off",Fo(h));let B=p(h);S.classList.toggle("dl-filtered",!B),B&&M++}let x=this.el?.querySelector(".dl-people-none")??null;s.length&&!M?(x??(x=n("div",{class:"dl-empty dl-people-none"},n("p",{},_("No one here right now.")))),x.previousElementSibling!==this.list&&this.list.after(x)):x?.remove()}async quick(e,o,s){await q(()=>N.personUpdate(e.id,o),s)&&await this.update()}renderCard(e,o){let s=this.person(o);if(!s)return dom.content(e,n("em",{},_("This person was just removed."))),e;let r=this.today,i=rt(s.expires,r),a=Math.max(0,s.device_limit-s.devices.length),l=s.has_link??this.st.settings.portal_enabled,d=[],c=qr(s);if(s.expires&&c!=="expired"){let x=it(s,i),h=i!=null&&i<0;d.push(n("span",{class:`dl-pill-ic${h?" bad":x?" warn":""}`,title:m(_("Access ends %s"),$e(s.expires))},[v("calendar"),h?m(_("ended %s"),$e(s.expires)):x?fn(i):m(_("until %s"),$e(s.expires))]))}s.hours&&c!=="hours"&&d.push(n("span",{class:"dl-pill-ic",title:_("Allowed hours")},[v("clock"),s.hours.replace("-","–")]));let p=vn(s.devices).map(x=>n("button",{type:"button",class:`dl-chip${x.disabled?" disabled":""}${x.online?" live":""}`,title:[at(x.kind),x.address,x.online?m(_("online from %s"),x.endpoint):x.handshake?m(_("seen %s"),ce(x.handshake,this.st.now)):""].filter(Boolean).join(" · "),click:h=>{h.preventDefault(),Ye(s,x,this.deviceOpts(s))}},[v(x.kind),n("span",{class:"dl-chip-name"},x.name),!x.handshake&&!x.disabled?n("span",{class:"dl-chip-tag"},_("not set up")):""]));p.push(n("button",{type:"button",class:"dl-chip add",title:a>0?_("Add device"):_("Over the limit: admins can still add"),click:x=>{x.preventDefault(),pt(s,this.deviceOpts(s))}},[v("plus"),_("Add device")]));let u=[];s.expires&&it(s,i)&&c!=="expired"&&u.push(n("button",{type:"button",class:"dl-fix",click:()=>this.quick(s,{expires:Kr(s.expires,r)},_("Extended by 1 month"))},_("Extend 1 month")));let g=Pe("more",_("More"),x=>Te(x.currentTarget,[{label:_("Open"),icon:v("open"),run:()=>{location.href=He(s.id)}},l?{label:_("Invite card"),icon:v("qr"),run:()=>an(s,this.st.servers.find(h=>h.id===s.server)?.name??_("Home"))}:null,a>0?{label:_("Add device"),icon:v("plus"),run:()=>pt(s,this.deviceOpts(s))}:null,null,{label:s.paused?_("Resume"):_("Pause"),icon:v(s.paused?"play":"pause"),warn:!s.paused,run:()=>this.togglePause(s)},{label:_("Delete"),icon:v("trash"),danger:!0,run:()=>this.remove(s.id)}].filter((h,S,B)=>h||S>0&&B[S-1])),"neutral","dl-icon-only"),M=n("div",{class:"dl-pcard-actions"},[l?Pe("link",_("Copy link"),()=>On(s.id),"neutral","dl-icon-only"):"",g]);return dom.content(e,n("div",{class:"dl-pcard"},[n("div",{class:"dl-pcard-main"},[n("div",{class:"dl-pcard-top"},[n("span",{class:`dl-avatar${s.online?" online":""}`},Oe(s.name)),n("div",{class:"dl-pcard-who"},[n("div",{class:"dl-card-head"},[n("a",{class:"dl-card-name",href:He(s.id)},s.name),bs(s),...d]),Wl(s)])]),n("div",{class:"dl-chips"},p),u.length?n("div",{class:"dl-fixes"},u):""]),this.usageSide(s,M),c?this.stopStrip(s,c):""])),e}stopStrip(e,o){let s=this.today,r=St(`${s.slice(0,8)}01`,1),i=()=>this.quick(e,{bonus_gb:String((e.bonus_gb||0)+10)},_("+10 GB this month")),a={paused:["pause","warn",_("Paused"),_("Devices can’t connect until you resume"),["play",_("Resume"),()=>this.togglePause(e)]],quota:e.quota_period==="month"?["chart","bad",_("Data limit reached"),m(_("Paused until it resets on %s"),$e(r)),["plus",_("+10 GB this month"),i]]:["chart","bad",_("Data limit reached"),_("Paused until the limit is raised"),["edit",_("Change limit"),()=>location.href=He(e.id)]],expired:["calendar","bad",m(_("Access ended %s"),$e(e.expires)),_("Devices can’t connect"),["calendar",_("Extend 1 month"),()=>this.quick(e,{expires:Kr(e.expires,s)},_("Extended by 1 month"))]],hours:["clock","warn",_("Outside allowed hours"),m(_("Access %s (router time)"),e.hours.replace("-","–")),null],no_server:["alert","warn",_("No server"),_("Choose a server on their page"),null]},[l,d,c,p,u]=a[o];return n("div",{class:`dl-pstrip ${d}`},[n("span",{class:`dl-need-ic ${d}`},v(l)),n("span",{class:"dl-pstrip-text"},[n("b",{},c),n("span",{class:"dl-faint"},p)]),u?H([v(u[0]),` ${u[1]}`],u[2]):""])}usageSide(e,o){let s=e.quota_used||e.month[0]+e.month[1],r=e.quota_limit?Math.min(100,e.quota_used/e.quota_limit*100):0,i=e.devices.reduce((p,u)=>p+(u.spark[u.spark.length-1]??[0,0]).reduce((g,M)=>g+M),0),a=e.rate?.[e.rate.length-1],l=e.online&&a&&this.st.now-a[0]<180,d=n("div",{class:`dl-usebar${r>=100?" bad":r>=90?" warn":""}`});if(e.quota_limit){let p=n("i",{class:"fill"});p.style.width=`${r}%`,d.appendChild(p),we(d,()=>[n("div",{class:"dl-tip-title"},m(_("%s%% used"),V(r,1))),n("div",{class:"dl-muted"},`${m(_("%s of %s"),se(e.quota_used),se(e.quota_limit))} · ${m(_("%s left"),se(Math.max(0,e.quota_limit-e.quota_used)))}`),n("div",{class:"dl-faint"},e.quota_period==="total"?_("In total"):[_("This month"),e.bonus_gb?m(_("includes +%s GB extra"),V(e.bonus_gb)):""].filter(Boolean).join(" · "))])}else{let p=e.devices.map(u=>({d:u,v:u.month[0]+u.month[1]})).filter(u=>u.v>0).sort((u,g)=>g.v-u.v);p.forEach((u,g)=>{let M=n("i",{class:`c${Math.min(g,4)}`});M.style.flexGrow=String(u.v),d.appendChild(M)}),p.length&&we(d,()=>[n("div",{class:"dl-tip-title"},_("This month by device")),...p.map((u,g)=>n("div",{class:"dl-tip-row"},[n("span",{class:`dl-swatch c${Math.min(g,4)}`}),n("span",{},u.d.name),n("b",{},se(u.v))]))])}let c=e.quota_limit?m(_("%s left"),se(Math.max(0,e.quota_limit-e.quota_used))):_("no limit");return n("div",{class:"dl-pside"},[n("div",{class:"dl-pside-top"},[l?n("span",{class:"dl-pside-state live"},_("Online")):n("span",{class:"dl-pside-state"},e.online?_("Online"):e.last_seen?_("Offline"):_("Never connected")),o]),n("div",{class:"dl-use-num"},[n("b",{class:s?"":"dl-faint"},se(s)),n("span",{class:"dl-faint"},e.quota_limit?m(_("of %s"),se(e.quota_limit)):e.quota_period==="total"&&e.quota_gb?_("in total"):_("this month"))]),d,l?n("div",{class:"dl-use-live",title:_("Right now")},[`↓ ${We(a[2])}`,n("span",{class:"dl-faint"},`↑ ${We(a[1])}`)]):n("div",{class:"dl-faint dl-pside-foot"},i?`${m(_("today %s"),se(i))} · ${c}`:c)])}async togglePause(e){await q(()=>N.personPause(e.id,!e.paused),m(e.paused?_("%s resumed"):_("%s paused"),e.name))&&await this.refresh()}async remove(e){let o=this.person(e);await pe(m(_("Remove %s?"),o?.name??e),G(o?.devices.length??0,"%s device is disconnected immediately and the personal link stops working. Usage history is kept in backups.","All %s devices are disconnected immediately and the personal link stops working. Usage history is kept in backups."),_("Remove"),!0)&&await q(()=>N.personDelete(e),_("Person removed"))&&await this.refresh()}openCreate(){let e=this.st;if(!e.servers.length){F(_("Set up the server first."),"warning");return}let o=n("input",{type:"text",class:"cbi-input-text",placeholder:_("e.g. Myata"),maxlength:48}),s=(()=>{try{return JSON.parse(Wo("dl.person.last")??"{}")}catch{return{}}})(),r=Gr(s.access??"internet"),i=n("input",{type:"number",class:"cbi-input-text",min:1,max:32,value:e.settings.default_device_limit}),a=n("input",{type:"date",class:"cbi-input-text"}),l=n("input",{type:"number",class:"cbi-input-text",min:0,step:"any",placeholder:_("Unlimited"),value:s.quota??""}),d=(P,R)=>n("button",{type:"button",class:"cbi-button cbi-button-neutral",click:()=>{a.value=R?St(Ge(e.series),R):"",a.dispatchEvent(new Event("change"))}},P),c=e.servers[0],p=!this.serverId&&e.servers.length>1?n("select",{class:"cbi-input-select"},e.servers.map(P=>n("option",{value:P.id},P.name))):null,u=(P,R,w)=>n("div",{class:"cbi-value"},[n("label",{class:"cbi-value-title"},P),n("div",{class:"cbi-value-field"},[R,w?n("div",{class:"cbi-value-description"},w):""])]),g=Ge(e.series),M=Me(_("Name","person"),o,()=>je(o.value,[],_("Shown in their portal and apps."))),x=Me(_("Devices"),i,()=>En(i.value)),h=Me(_("End date"),a,()=>Hs(a.value,g,rt,$e),n("div",{class:"dl-actions"},[a,d(_("1 month"),1),d(_("3 months"),3),d(_("1 year"),12),d(_("None","end date"),0)])),S=Me(_("Monthly data (GB)"),l,()=>Tn(l.value));a.addEventListener("change",()=>h.refresh());let B=e.settings.portal_enabled;ae(_("Add person"),[M,p?u(_("Server"),p):"",n("div",{class:"cbi-value dl-block"},[n("label",{class:"cbi-value-title"},_("Access")),n("div",{class:"cbi-value-field"},r.el)]),x,h,S],[de()," ",H(B?_("Create and copy link"):_("Create"),async()=>{let P=Be([M,x,h,S]);if(P){F(P,"warning");return}let R=await q(()=>N.personCreate(o.value.trim(),"",p?.value??c.id,r.get(),i.value.trim(),a.value,l.value.trim(),"month"));R&&(Go("dl.person.last",JSON.stringify({access:r.get(),quota:l.value.trim()})),R.link&&await xe(R.link,_("Personal link copied"),!0),this.showCreated(R.id,o.value.trim(),R.link,e.servers.find(w=>w.id===(p?.value??c.id))?.name??c.name),await this.refresh())},"positive")]),setTimeout(()=>o.focus(),50)}showCreated(e,o,s,r){if(s){an({id:e,name:o,link:s},r,{title:m(_("%s is ready"),o),lead:m(_("Send %s the card or the link. They open it, add their devices and connect - no account needed."),o)});return}let i=this.person(e);ae(m(_("%s is ready"),o),[n("p",{},_("Created. Turn on the personal portal in Settings to get a link, or add devices for them here."))],[n("button",{class:"cbi-button cbi-button-neutral",click:le},_("Done"))," ",n("a",{class:"cbi-button cbi-button-neutral",href:`${L.url("admin/network/dawnline/settings")}?section=portal`},_("Open Settings"))," ",i?H(_("Add device"),()=>{le(),pt(i,this.deviceOpts(i))},"positive"):""])}};var Bn=["#3a83f7","#a78bfa","#f472b6","#f59e0b","#10b981","#22d3ee","#ef4444","#84cc16"],qo=t=>n("i",{class:"dl-circle-dot",style:`background:${Bn[t?.color??0]??Bn[0]}`}),mt=t=>t.access==="both"||t.access==="lan"&&!t.services?.length;function Jr(t,e,o){let s=ue(t?.name??e.name??"",{placeholder:_("NAS")}),r=ue(t?.address??e.address??"",{placeholder:"192.168.1.10",class:"cbi-input-text dl-mono"}),i=ue((t?.ports??e.ports??[]).join(", "),{placeholder:_("All ports, or e.g. 445, 5000"),class:"cbi-input-text dl-mono"}),a=Me(_("Name","circle or service"),s,()=>je(s.value,[],_("Shown to people who may reach it."))),l=Me(_("Address"),r,()=>zs(r.value)),d=Me(_("Ports"),i,()=>Rs(i.value));ae(t?m(_("Edit %s"),t.name):_("Add service"),[a,l,d],[de()," ",H(_("Save"),async()=>{let c=Be([a,l,d]);if(c){F(c,"warning");return}let p=i.value.split(/[ ,]+/).filter(Boolean);await q(()=>N.serviceSet(t?.id??"",s.value,r.value,p),_("Saved"))&&(le(),o())},"positive")])}function Fl(){let t=_("Web"),e=_("Printer");return{_smb:"SMB",_afpovertcp:"AFP",_http:t,_https:t,_ssh:"SSH",_sftp:"SFTP","_sftp-ssh":"SFTP",_ipp:e,_ipps:e,_printer:e,"_pdl-datastream":e,_airplay:"AirPlay",_raop:"AirPlay",_rfb:_("Screen sharing"),_googlecast:"Cast",_hap:"HomeKit",_rdp:_("Remote desktop"),_ftp:"FTP"}}function ql(t){let e=Fl(),o=new Map;for(let s of t.services){let r=e[s.type.split(".")[0]];!r||!s.port||(o.get(r)??o.set(r,new Set).get(r)).add(String(s.port))}return o.size?[...o].map(([s,r])=>[s,[...r].sort((i,a)=>+i-+a)]):[[_("Web"),["80","443"]],["SMB",["445"]],["SSH",["22"]]]}function Zr(t,e,o){let s=t,r=null,i=!1,a=null,l=new Set,d=n("div",{class:"dl-list"}),c=n("div",{class:"dl-stack gap8"},n("span",{class:"dl-sub"},_("Looking for devices at home…"))),p=()=>{let h=s.services;dom.content(d,h.length?h.map(S=>n("div",{class:"dl-row"},[v("home"),n("span",{class:"dl-row-main dl-stack"},[n("b",{},S.name),n("span",{class:"dl-mono dl-faint"},`${S.address} · ${S.ports.length?m(_("ports %s"),S.ports.join(", ")):_("all ports")}`)]),H(_("Edit"),()=>Jr(S,{},o)),H([v("trash")],async()=>{await pe(m(_("Remove %s?"),S.name),_("People limited to this service lose access to it."),_("Remove"),!0)&&await q(()=>N.serviceDelete(S.id),_("Removed"))&&await o()},"neutral",{title:_("Remove"),"aria-label":m(_("Remove %s"),S.name)})])):[n("div",{class:"dl-row dl-muted"},_("No services yet: pick ports of a device below."))])};async function u(h,S){if(!l.has(h.address)){l.add(h.address),M();try{let B=s.services.find(R=>R.address===h.address);(S===null?B&&await q(()=>N.serviceDelete(B.id),m(_("%s removed"),B.name)):await q(()=>N.serviceSet(B?.id??"",B?.name??(h.name||h.address),h.address,S),B?m(_("%s updated"),B.name):m(_("%s added"),h.name||h.address)))&&await o()}finally{l.delete(h.address),M()}}}function g(h){let S=s.services.find(k=>k.address===h.address),B=!!S&&!S.ports.length,P=new Set(S?.ports??[]),R=l.has(h.address),w=(k,y,O)=>Yt(k,y,O,{disabled:R?"disabled":null,"aria-busy":R?"true":null});return n("div",{class:"dl-row dl-host"},[v(h.services.some(k=>k.type.startsWith("_ipp")||k.type.startsWith("_printer"))?"file":"computer"),n("div",{class:"dl-host-body"},[n("span",{class:"dl-row-main dl-stack"},[n("b",{},h.name||h.address),n("span",{class:"dl-mono dl-faint"},h.address)]),n("div",{class:"dl-chips-row"},[w(_("All ports"),B,()=>u(h,B?null:[])),...ql(h).map(([k,y])=>{let O=!B&&y.every(b=>P.has(b));return w(`${k} ${y.join(", ")}`,O,()=>{let b=new Set(B?[]:P);for(let f of y)O?b.delete(f):b.add(f);u(h,b.size?[...b]:null)})})])])])}function M(){if(i)return dom.content(c,n("span",{class:"dl-sub"},_("Couldn't read the devices at home.")));if(!r)return;let h=r;if(!h.hosts.length)return dom.content(c,n("span",{class:"dl-sub"},_("No devices found in the home network right now.")));let S=n("details",{class:"dl-params",open:a??!s.services.length?"":null},[n("summary",{},[v("chevron"),n("span",{},_("Add from devices at home")),n("span",{class:"dl-pcount"},String(h.hosts.length))]),n("div",{class:"dl-params-body"},[n("span",{class:"dl-sub"},h.mdns?_("Ports they announce over Bonjour. Pick what to open, or all ports."):_("Devices that got an address from this router. Pick the ports to open, or all ports.")),n("div",{class:"dl-list"},h.hosts.map(g))])]);S.addEventListener("toggle",()=>a=S.open),dom.content(c,S)}return N.homeHosts(e).then(h=>{r=h,M()}).catch(()=>{i=!0,M()}),p(),{el:n("div",{class:"dl-stack gap8"},[n("div",{class:"dl-iflead"},[n("div",{class:"dl-iflead-row"},[n("b",{},_("Home services")),H([v("plus")," ",_("Add service")],()=>Jr(null,{},o))]),n("span",{class:"dl-sub"},_("Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers."))]),d,c]),update(h){s=h,p(),M()}}}function jn(t,e,o,s){let r=new Set(t.circles.filter(h=>h.server===e).map(h=>h.color)),i=o?.color??Bn.findIndex((h,S)=>!r.has(S));i<0&&(i=0);let a=ue(o?.name??"",{placeholder:_("Family")}),l=t.people.filter(h=>h.server===e).sort((h,S)=>h.name.localeCompare(S.name)),d=new Set(l.filter(h=>o&&h.circle===o.id).map(h=>h.id)),c=n("div",{class:"dl-swatches",role:"radiogroup","aria-label":_("Colour")}),p=()=>dom.content(c,Bn.map((h,S)=>n("button",{type:"button",role:"radio",class:`dl-swatch${S===i?" on":""}`,style:`--sw:${h}`,"aria-checked":S===i?"true":"false","aria-label":m(_("Colour %s"),S+1),click:()=>{i=S,p()}})));p();let u=n("div",{class:"dl-chips-row"},l.map(h=>{let S=h.circle&&h.circle!==o?.id?t.circles.find(B=>B.id===h.circle):void 0;return n("button",{type:"button",class:`dl-chipbtn${d.has(h.id)?" on":""}`,title:mt(h)?S?m(_("Now in %s"),S.name):"":m(_("%s has no home access: their devices aren't reachable anyway"),h.name),click:B=>{d.delete(h.id)||d.add(h.id),B.currentTarget.classList.toggle("on",d.has(h.id))}},[h.name,mt(h)?S?n("b",{},S.name):"":n("b",{},_("internet"))])})),g=(h,S)=>n("div",{class:"cbi-value"},[n("label",{class:"cbi-value-title"},h),n("div",{class:"cbi-value-field"},S)]),M=t.circles.filter(h=>h.server===e&&h.id!==o?.id).map(h=>h.name),x=Me(_("Name","circle or service"),a,()=>Ss(a.value,M));ae(o?m(_("Edit %s"),o.name):_("New circle"),[x,g(_("Colour"),c),g(_("People"),u),n("p",{class:"dl-sub"},_("Devices of people in one circle reach each other. A person is in one circle at a time."))],[o?H(_("Delete"),async()=>{await q(()=>N.circleDelete(o.id),m(_("%s deleted"),o.name))&&(le(),s())},"negative"):"",n("span",{class:"dl-spacer"}),de()," ",H(_("Save"),async()=>{let h=x.help();if(h.bad){F(h.text,"warning");return}await q(()=>N.circleSet(o?.id??"",e,a.value,i,[...d]),_("Saved"))&&(le(),s())},"positive")],"dl-circle-modal")}function Qr(t,e,o){let s=t.circles.filter(r=>r.server===e);return n("div",{class:"dl-chips-row dl-circles"},[...s.map(r=>{let i=t.people.filter(a=>a.circle===r.id).map(a=>a.name);return n("button",{type:"button",class:"dl-chip",title:m(_("Edit %s"),r.name),click:()=>jn(t,e,r,o)},[qo(r),n("b",{},r.name),n("span",{class:"dl-faint"},i.length?i.join(", "):_("nobody yet"))])}),n("button",{type:"button",class:"dl-chip add",title:_("New circle"),"aria-label":_("New circle"),click:()=>jn(t,e,null,o)},v("plus"))])}function Ko(t,e){let o=t.people.filter(p=>p.server===e.id),s=(p="")=>n("span",{class:"dl-yes"},[v("check"),p]),r=()=>n("span",{class:"dl-faint"},"—"),i=p=>{let u=new Set(p.map(M=>M.access==="lan"&&M.services?.length?"services":M.home_nets?.length?"some":"all"));u.size||u.add("all");let g={all:_("all networks"),some:_("their networks"),services:_("services")};return s([...u].map(M=>g[M]).join(" / "))},a=()=>e.mesh==="off"?r():e.mesh==="circles"?s(_("circle")):s(),l=e.lan_like?_("like home"):_("direct"),d=(p,u,g)=>n("tr",{},[n("td",{},[n("b",{},p),n("div",{class:"dl-sub"},G(u.length,"%s person","%s people"))]),...g.map(M=>n("td",{},M))]),c=p=>o.filter(u=>u.access===p);return n("section",{class:"dl-setsec"},[n("div",{class:"dl-setsec-body"},[n("div",{class:"dl-panel-head"},[n("h3",{},_("Who reaches what")),n("span",{class:"dl-spacer"}),n("span",{class:"dl-sub"},_("From the rules on this server"))]),n("div",{class:"dl-reach-wrap"},n("table",{class:"dl-table dl-reach"},[n("tr",{},["",_("Internet"),_("Home"),_("This router"),_("Each other")].map(p=>n("th",{},p))),d(_("Internet"),c("internet"),[s(l),r(),n("span",{class:"dl-faint"},"DNS"),r()]),d(_("Home"),c("lan"),[n("span",{class:"dl-faint"},_("their own")),i(c("lan")),s(),a()]),d(_("Both"),c("both"),[s(l),i(c("both")),s(),a()])])),n("p",{class:"dl-sub"},_("Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing."))])])}function Xr(t,e){let o=t.people.filter(c=>c.server===e.id).flatMap(c=>c.devices.map(p=>({id:p.id,label:`${c.name} · ${p.name}`}))).sort((c,p)=>c.label.localeCompare(p.label)),s="@addr",r=(c,p)=>{let u=n("select",{class:"cbi-input-select","aria-label":c},[...o.map(h=>n("option",{value:h.id,selected:h.id===p?"selected":null},h.label)),n("option",{value:s,selected:p===s?"selected":null},_("Address"))]),g=ue("",{placeholder:c,class:"cbi-input-text dl-mono"}),M=n("div",{class:"dl-check-end"},[u,g]),x=()=>g.hidden=u.value!==s;return u.addEventListener("change",x),x(),{el:M,value:()=>u.value===s?g.value.trim():u.value}},i=r("10.0.1.11",o[0]?.id??s),a=r("10.0.1.20:445",s),l=n("div",{class:"dl-stack gap8"}),d=async()=>{let c=await q(()=>N.accessCheck(i.value(),a.value()));if(!c)return;let p=c.steps.findIndex(u=>!u.ok);dom.content(l,[n("div",{class:`dl-verdict ${c.ok?"ok":"bad"}`},[n("b",{},c.ok?_("Allowed"):_("Blocked")),n("span",{class:"dl-sub"},c.ok?_("Every step lets it through"):m(_("Stops at step %s of %s"),p+1,c.steps.length))]),n("ul",{class:"dl-checks"},c.steps.map(u=>n("li",{},[n("span",{class:`dl-check-icon ${u.ok?"ok":"error"}`},v(u.ok?"check":"x")),n("div",{class:"dl-check-body"},[n("div",{class:"dl-check-title"},u.title),u.detail?n("div",{class:"dl-check-detail"},u.detail):""])])))])};return n("section",{class:"dl-setsec"},[n("div",{class:"dl-setsec-body"},[n("div",{class:"dl-panel-head"},[n("h3",{},_("Check access")),n("span",{class:"dl-spacer"}),n("span",{class:"dl-sub"},_("Why something does or does not connect"))]),n("div",{class:"dl-check-form"},[i.el,n("span",{class:"dl-faint"},"→"),a.el,H(_("Check"),d)]),l])])}function Un(t){return t==="app"?"Dawnline":t==="amneziawg"?"AmneziaWG":t==="packages"||t==="pkgs"?_("System packages"):void 0}function ht(t){return(t.startsWith("check")?t.slice(6)||"all":t).split(/[:@ ]/)[0]}function Wn(t){return ht(t.action==="check"?`check:${t.component??""}`:t.component??"")}function ei(t){return t=Math.max(0,Math.floor(t)),`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function ti(t,e){return!t?.from&&!t?.to?e:t.from&&t.to&&t.from!==t.to?`${t.from} → ${t.to}`:t.to??t.from??e}function ni(t,e){let o=t.check?.components??{},s=e==="all"?["app","amneziawg","packages"]:[e],r=[],i;for(let l of s){let d=o[l];if(d){if(d.error)return{tone:"warn",text:d.error};l==="packages"&&d.updates?r.push(G(d.updates,"%s system package","%s system packages")):l!=="packages"&&d.update&&d.installed&&d.latest&&(r.push(`${Un(l)} ${d.latest}`),e!=="all"&&(i=d.latest))}}if(r.length)return{tone:"acc",text:m(_("Update available: %s"),r.join(", ")),update:i};let a=s.length===1?o[s[0]]:null;return a?.status==="dev"?{tone:"acc",text:m(_("Installed version is newer than the release (%s)"),a.latest)}:a?.note?{tone:"warn",text:a.note}:{tone:"ok",text:s.length>1?_("Everything is up to date"):_("Latest version is installed")}}function oi(t,e,o,s){return e?t.id===e:o&&t.id===o?!1:t.state==="running"||s>0&&t.started>=s}var Vo=t=>new Promise(e=>setTimeout(e,t));async function dn(t,e,o){let s=o?Wn(o):ht(t),r=o?o.action==="check":t.startsWith("check"),i=Date.now(),a=n("b",{},Un(s)??(s==="all"?_("All components"):"Dawnline")),l=n("span",{class:"dl-pill dl-mono"},e.version??""),d=n("span",{class:"dl-pill info",hidden:!0}),c=n("span",{},"0:00"),p=n("pre",{class:"dl-log"},_("Operation started. Waiting for log output…")),u=n("div",{}),g=n("div",{class:"dl-op-actions"}),M=[],x=T=>dom.content(g,T),h=(T=!1)=>de(_("Close"),T);ae(e.title,n("div",{class:"dl-op"},[n("div",{class:"dl-op-head"},[a,e.version?l:"",d,n("span",{class:"dl-spacer"}),n("span",{class:"dl-faint dl-op-timer"},[v("clock"),c])]),n("div",{class:"dl-op-loghead"},[n("b",{},_("Operation log")),Pe("copy",_("Copy log"),()=>xe(M.join(` +`),_("Log copied")))]),p,u]),[g],"wide"),x([n("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?_("Checking…"):_("Working…"))]);let S=o??null,B=o?.id,P,R=0,w=T=>{B!==T.id&&(B=T.id,e.onJob?.(T))};if(o)e.onJob?.(o);else try{let T=await N.updatesStatus().catch(()=>null);P=T?.job?.id,R=T?.now??0;let C=await N.updatesRun(t);C.job&&C.job.state==="running"&&C.job.id!==P&&(S=C.job,w(C.job))}catch(T){return M=[_e(T)],p.textContent=M[0],dom.content(u,n("div",{class:"dl-comp-status warn"},[v("alert"),n("span",{},_e(T))])),x([h(!0)]),F(_e(T),"error"),null}let k=null,y=0;for(;;){if(await Vo(1e3),k=await N.updatesStatus().catch(()=>null),!k){if(++y>60)break;continue}y=0;let T=k.job;if(!T||!oi(T,B,P,R)){if(Date.now()-i>15e3)break;continue}if(w(T),S=T,T.log.length){M=T.log;let C=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=M.join(` +`),C&&(p.scrollTop=p.scrollHeight)}if(l.textContent=ti(T,e.version??""),!l.isConnected&&l.textContent&&a.after(l),c.textContent=ei((T.finished??k.now)-T.started),T.state==="running"){d.hidden=!T.phase,d.textContent=T.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!S||S.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,n("div",{class:"dl-comp-status warn"},[v("alert"),n("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),x([h()]),e.onDone?.(k),S;if(S.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,n("div",{class:"dl-comp-status bad"},[v("x"),n("span",{},[n("b",{},(S.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),x([H(_("Copy log"),()=>xe(M.join(` +`),_("Log copied"))),h(!0)]),F(`${Un(s)??_("Update","noun")}: ${S.error??_("failed")}`,"error"),e.onDone?.(k),S;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&k){let T=ni(k,s);if(dom.content(u,n("div",{class:`dl-comp-status ${T.tone}`},[v(T.tone==="ok"?"check":T.tone==="warn"?"alert":"download"),n("span",{},T.text)])),F(T.text,T.tone==="warn"?"warning":"success"),e.onDone?.(k),T.update&&e.onUpdate){let C=k;x([h(),H(m(_("Update to %s"),T.update),()=>e.onUpdate(C),"positive")])}else x([h()]),T.tone==="ok"&&setTimeout(()=>u.isConnected&&le(),1200);return S}let O=/^app:(lang:|nolang$)/.exec(S.component??"");if(O){let T=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},[n("b",{},O[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),x([h(),H(_("Reload now"),T,"positive")]),await Vo(4e3),u.isConnected&&T(),S}if(s==="app"&&S.to){let T=S.to,C=n("span",{},_("Waiting for the router to restart its services…"));dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},[n("b",{},m(_("Dawnline %s is installed."),T))," ",C])]));let A=()=>{ui.menu?.flushCache(),location.reload()};x([h(),H(_("Reload now"),A,"positive")]),F(m(_("Dawnline updated to %s"),T),"success",6e3);for(let K=1;K<=30;K++)if(C.textContent=m(_("Waiting for the router to restart its services (%s of 30)…"),K),await Vo(1500),(await N.updatesStatus().catch(()=>null))?.version===T)return C.textContent=_("Services are back. Reloading…"),setTimeout(A,800),S;return C.textContent=_("Services restarted. Reload the page to use the new version."),S}let b=[...S.result?.pkgs?.updated??[],...S.result?.pkgs?.installed??[]],f=s==="pkgs"?b.length?m(_("Updated %s"),b.join(", ")):_("Updated system packages"):s==="amneziawg"?S.to?m(_("AmneziaWG %s is installed"),S.to):_("AmneziaWG is installed"):_("Operation completed");return dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},f)])),x([h()]),F(f,"success"),e.onDone?.(k),S}function Kl(t){return{https:[_("Install HTTPS for the portal?"),_("Installing HTTPS for the portal")],acme:[_("Install ACME certificates?"),_("Installing ACME certificates")],home:[_("Install the home-like link?"),_("Installing the home-like link")],awg:[_("Install AmneziaWG?"),_("Installing AmneziaWG")]}[t]}async function si(t,e,o,s){let[r,i]=Kl(e);return!await pe(r,o,_("Install"))||(await dn(t,{title:i}))?.state!=="done"?!1:(setTimeout(()=>s?.(),4e3),!0)}function Gn(t){return si("amneziawg:auto","awg",_("Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds."),t)}async function cn(t,e,o){return t==="awg"?Gn(o):e.length?si(`pkgs:${e.join(",")}`,t,m(_("%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive."),e.join(", ")),o):!0}async function ri(t,e){if(t==="awg")return Gn(e);let o=await q(()=>N.updatesStatus());return o?cn(t,o.needs?.[t]??[],e):!1}var Vl=()=>[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn",_("VPN & tunnels")],["other",_("Other")]],Yl={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Yo(t){let e=n("b",{},oe(_("add its interface %s to their source interfaces yourself"),n("span",{class:"dl-mono"},t)));return[...oe(_("Off: internet traffic goes straight to the WAN, the fastest way. DNS still goes through this router. Proxies and filters here handle the tunnel only if you %s."),e)," ",n("span",{class:"dl-warn"},_("If the router’s DNS hands out proxy addresses, those sites won’t open without it."))]}function Jo(){return wt(_("Slower: every packet crosses the router twice. On a dual-core router expect up to a third less speed, and lost packets at full load."))}function ii(t,e,o){let s=t.id,r=e,i=n("div",{class:"dl-stack gap16"},n("section",{class:"dl-setsec"},n("div",{class:"dl-setsec-body"},n("p",{class:"dl-muted"},_("Loading interfaces…"))))),a,l=!0,d="",c=!0,p=!0,u="all",g=!1,M=Zr(r,s,o),x=new Set,h="",S=()=>JSON.stringify([p,l,l?"":d,c,[...x].sort()]),B=()=>a.detected.lan||a.saved.lan||"",P=()=>(l?a.detected.wan||a.saved.wan:d)||"",R=()=>new Map(a.devices.map(j=>[j.name,j])),w=()=>{let j=R();return[...c&&B()?[B()]:[],...[...x].filter(te=>te!==B())].filter(te=>te!==P()).map(te=>j.get(te)??{name:te,nets:[],missing:!0})},k=(j,Z)=>{a=j,Z&&(l=j.config.auto_wan,d=j.config.wan_device||j.detected.wan||j.saved.wan||"",c=j.config.auto_lan,p=j.config.lan_like,u=j.config.mesh??(j.config.device_mesh?"all":"off"),x=new Set(j.config.lan_devices),h=S()),Y()},y=async j=>{let Z=await N.interfaces(s).catch(te=>(F(te.message,"error"),null));Z&&k(Z,j)};function O(j){let Z=c&&j.name===B(),te=!!j.own||!!j.master||j.name===P()||Z;return Z||x.has(j.name)||!te&&(j.nets.length>0||!!j.missing)}function b(j){let Z=c&&j.name===B(),te=j.name===P(),me=!Z&&x.has(j.name),U=!(!!j.own||!!j.master||te||Z)&&(j.nets.length>0||me||!!j.missing),ne=(me||Z)&&!j.zone&&!j.missing,he=j.missing?_("Not present right now"):j.own?_("This server"):j.master?m(_("Port of %s"),j.master):te?`${_("Internet")}${j.zone?` · ${m(_("zone %s"),j.zone)}`:""}`:j.nets.length?j.nets.join(", "):_("No IPv4 network"),fe=n("button",{type:"button",class:`dl-if${me?" sel":""}${Z?" auto":""}${!U&&!me&&!Z?" off":""}${ne?" warn":""}`,"aria-pressed":me||Z?"true":"false","aria-disabled":U?null:"true",click:()=>{U&&(x.has(j.name)?x.delete(j.name):x.add(j.name),Y())}},[n("span",{class:"dl-if-ic"},v(Yl[j.kind]??"link")),n("span",{class:"dl-if-main"},[n("span",{class:"dl-if-name"},j.name),n("span",{class:"dl-if-sub"},he)]),Z?n("span",{class:"dl-if-badge ok"},_("Auto")):me?n("span",{class:"dl-if-check"},v("check")):""]);return we(fe,()=>[n("div",{class:"dl-tip-title"},j.name),n("div",{class:"dl-muted"},[j.logical?m(_("Interface %s"),j.logical):_("No netifd interface")," · ",j.zone?m(_("zone %s"),j.zone):_("no firewall zone")]),j.members.length?n("div",{class:"dl-muted"},m(_("Ports: %s"),j.members.join(", "))):"",j.nets.length?n("div",{class:"dl-mono"},j.nets.join(", ")):"",ne?n("div",{class:"dl-warn"},_("Not in a firewall zone: the firewall rejects this traffic.")):"",j.master?n("div",{class:"dl-muted"},m(_("Choose %s to include it."),j.master)):""]),fe}function f(){let j=a.like_home;return!p||!a.config.lan_like||!t.enabled?"":!a.needs?.length&&j.active&&j.bridged?"ok":"warn"}function T(){let j=a.like_home;return p?a.needs?.length?[n("span",{class:"dl-warn"},m(_("Needs %s."),new Intl.ListFormat(ie(),{type:"conjunction"}).format(a.needs)))," ",_("Until they are installed, internet traffic goes straight to the WAN.")]:a.config.lan_like?t.enabled?j.active&&j.bridged?oe(_("Internet traffic enters %s as %s, so whatever handles home traffic (proxies, filters, DNS) handles it too."),n("span",{class:"dl-mono"},j.dev??""),n("span",{class:"dl-mono"},j.address??"")):[n("span",{class:"dl-warn"},m(_("Not working: %s"),j.error??_("the link is down")))," ",_("Internet traffic goes straight to the WAN for now.")]:[_("Internet traffic enters the router from your LAN, so whatever handles home traffic (proxies, filters, DNS) handles it too.")]:[_("Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.")]:Yo(t.ifname)}let C=j=>({off:_("Devices of different people never reach each other; a person's own devices don't either."),all:_("Devices of people with home access reach each other, like home devices do. Internet-only people never."),circles:_("Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never.")})[j];function A(j,Z,te,me,ke="",U){return n("div",{class:U?"dl-setrow head":"dl-setrow"},[n("div",{class:"dl-lh-main"},[n("span",{class:`dl-need-ic ${ke}`},v(j)),n("div",{class:"dl-stack"},[n("span",{class:"dl-setrow-label"},Z),n("span",{class:"dl-sub"},te),U??""])]),n("div",{class:"dl-setrow-ctl"},me)])}let K=(j,Z)=>{let te=me=>n("span",{class:"dl-mono"},me);return j?n("span",{},[" ",...Z&&Z!==j?oe(_("Now: %s, was %s."),te(j),te(Z)):oe(_("Now: %s."),te(j))]):n("span",{},[" ",...Z?oe(_("Not found now: using %s."),te(Z)):[_("Not found.")]])};function Y(){let j=n("select",{class:"cbi-input-select","aria-label":_("Internet interface"),change:D=>{d=D.target.value,Y()}},a.devices.filter(D=>!D.own&&!D.master&&D.zone&&!D.missing).map(D=>n("option",{value:D.name,selected:D.name===d?"selected":null},`${D.name} · ${m(_("zone %s"),D.zone)}`))),te=w().flatMap(D=>D.nets.map(W=>[W,D.name])),me=JSON.parse(S()),ke=JSON.parse(h),U=(...D)=>D.some(W=>JSON.stringify(me[W])!==JSON.stringify(ke[W])),ne=U(0,1,2),he=U(3,4),fe=D=>H(_("Save"),async()=>{let W=await q(()=>N.serverInterfaces(s,l,l?"":d,c,[...x],p,u!=="off",u),_("Access saved"));W&&(k(W,!0),W.nets_changed&&W.lan_only&&F(G(W.lan_only,"%s person has Home-only access: their devices need the configuration again to reach the new networks.","%s people have Home-only access: their devices need the configuration again to reach the new networks."),"warning",1e4))},"positive",{disabled:!D}),z=n("section",{class:"dl-setsec dl-ifcard"},[n("div",{class:"dl-setsec-body"},[n("div",{class:"dl-panel-head"},[n("h3",{},_("Internet")),n("span",{class:"dl-spacer"}),n("span",{class:"dl-sub"},_("People with Internet or Both"))]),A("home",_("Internet like a home device"),T(),[p&&a.needs?.length?H(_("Install"),()=>cn("home",a.needs,()=>y(!1)),"positive"):"",be(p,_("Internet like a home device"),D=>{p=D,Y()})],f(),p?Jo():void 0),A("globe",_("Auto-detect WAN"),[_("The interface with the default route: the server port opens there and Internet access leaves through it."),K(a.detected.wan,a.saved.wan)],[l?"":j,be(l,_("Auto-detect WAN"),D=>{l=D,Y()})])]),n("div",{class:"dl-setsec-foot"},[n("span",{class:"dl-sub"},p?[_("Internet like a home device"),P()?[" · ",...oe(_("leaves through %s"),n("span",{class:"dl-mono"},P()))]:""]:P()?oe(_("Internet straight to %s"),n("span",{class:"dl-mono"},P())):_("No WAN found")),fe(ne)])]),$=Ze([["off",_("Off")],["all",_("Everyone")],["circles",_("Circles")]],u,{label:_("Devices reach each other"),cls:"sm",optimistic:!1,onChange:async D=>{let W={off:_("Off"),all:_("Everyone"),circles:_("Circles")}[D];await q(()=>N.serverUpdate(s,{mesh:D}),m(_("Devices reach each other: %s"),W))&&(u=D,a.config.mesh=D,Y(),await o())}}),E=n("section",{class:"dl-setsec dl-ifcard"},[n("div",{class:"dl-setsec-body"},[n("div",{class:"dl-panel-head"},[n("h3",{},_("Home network")),n("span",{class:"dl-spacer"}),n("span",{class:"dl-sub"},_("People with Home or Both")),H([v("reset")," ",_("Rescan")],()=>y(!1),"neutral",{title:_("Read the interfaces again")})]),A("network",_("Networks"),_("Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it."),"","",Q()),A("link",_("Devices reach each other"),C(u),$,"",u==="circles"?Qr(r,s,o):void 0),M.el]),n("div",{class:"dl-setsec-foot"},[n("span",{class:"dl-sub dl-if-summary"},te.length?oe(_("Home access reaches %s"),n("span",{},te.flatMap(([D,W],ee)=>[ee?", ":"",n("span",{class:"dl-mono"},D),` (${W})`]))):_("No home network: Home access reaches nothing but this router.")),fe(he)])]),I=window.scrollY;i.style.minHeight=`${i.offsetHeight}px`,dom.content(i,[z,E]),i.style.minHeight="",window.scrollTo({top:I})}function Q(){let j=a.devices.filter(O),Z=a.devices.filter(te=>!O(te));return n("div",{class:"dl-stack gap8 dl-netpick"},[j.length?n("div",{class:"dl-ifgrid"},j.map(b)):n("span",{class:"dl-warn"},_("No home network: Home access reaches nothing but this router.")),n("label",{class:"dl-boxrow"},[n("span",{class:"dl-stack"},[n("span",{},_("Auto-detect LAN")),n("span",{class:"dl-sub"},[_("Adds the LAN this router uses."),K(a.detected.lan,a.saved.lan)])]),be(c,_("Auto-detect LAN"),te=>{c=te,Y()})]),Z.length?n("details",{class:"dl-params",open:g?"":null,toggle:te=>g=te.currentTarget.open},[n("summary",{},[v("chevron"),n("span",{},_("Other interfaces")),n("span",{class:"dl-pcount"},String(Z.length))]),n("div",{class:"dl-params-body"},[n("span",{class:"dl-sub"},_("The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network.")),...Vl().map(([te,me])=>{let ke=Z.filter(U=>U.category===te);return ke.length?n("div",{class:"dl-ifgroup"},[n("h4",{},me),n("div",{class:"dl-ifgrid"},ke.map(b))]):""})])]):""])}return y(!0),{el:i,update(j){r=j,M.update(j),a&&Y()}}}var Fn=class{constructor(){this.points=[];this.at=0;this.now=0;this.keep=120;this.failed=0;this.error="";this.empty=0}live(e){return this.points.length>0&&e-this.at<5e3}since(e){return this.live(e)?this.points[this.points.length-1].ts:0}take(e,o){if("error"in e){this.failed++,this.error=e.error;return}let s=e.meter,r=this.live(o)?this.points:[];r.length&&s.ts>0&&s.tsd.ts>i)];this.keep=s.keep>1?s.keep:120;let l=a.length?a[a.length-1].ts:0;this.points=a.filter(d=>d.ts>l-this.keep),this.empty=this.points.length?0:this.empty+1,this.at=o,this.now=s.now,this.failed=0,this.error=""}speed(e,o){let s=this.failed>=3?this.error:null,r=this.live(o)?this.points:[],i=r.flatMap(u=>u.servers[e]?[[u.ts,u.servers[e][0],u.servers[e][1]]]:[]),a=r.length?r[r.length-1].ts:0,l=this.keep-1,d=i[i.length-1],c=d?this.now-d[0]:-1,p=c>=0&&c<5;return{pts:i,xs:i.map(u=>1-(a-u[0])/l),rx:p?d[1]:0,tx:p?d[2]:0,error:s,early:!r.length&&this.empty<3}}};var Jl={connect:"ok",disconnect:"",roam:"",device_added:"ok",device_removed:"",person_added:"",person_removed:"",paused:"warn",resumed:"ok",expiring:"warn",expired_kept:"",portal_blocked:"bad",person_changed:"",devices_removed:"warn",device_failing:"warn",device_recovered:"ok"},Zl={devices_removed:"trash",link_changed:"link",person_added:"plus",person_removed:"trash",person_changed:"edit",paused:"pause",resumed:"play",expiring:"calendar",expired_kept:"calendar"};function Ql(t,e){return e.device?t.people.flatMap(s=>s.devices).find(s=>s.id===e.device)?.kind??e.dkind??"other":Zl[e.type]??"activity"}var Xl=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?Ie(t):t;function Zo(t,e){let o=t.people.find(h=>h.id===e.person),s=o?.name??e.pname??e.person??"",r=o?.devices.find(h=>h.id===e.device)?.name??e.dname??"",i=h=>n("b",{},h),a=h=>n("span",{class:"dl-muted"},h),l=h=>n("span",{class:"dl-mono"},h),d=h=>e.hosts?.[h]?[n("span",{class:"dl-ev-host"},[n("b",{},e.hosts[h]),n("span",{class:"dl-faint"},` (${h})`)])]:[l(h)],c=(h,...S)=>oe(h,...S).map(B=>typeof B=="string"?a(B):B),p=(h,...S)=>{let B=_("You");return h.startsWith(`${B} `)?[n("span",{class:"dl-you"},B),...c(h.slice(B.length),...S)]:c(h,...S)},u=i(r?`${s} · ${r}`:s),g=qs(e),M=i(g||r||_("a device")),x=Ve(e);if(x==="admin")switch(e.type){case"device_added":return p(_("You added device %s for %s"),M,i(s));case"device_removed":return p(_("You removed device %s from %s"),M,i(s));case"paused":return p(_("You paused person %s"),i(s));case"resumed":return p(_("You resumed person %s"),i(s));case"device_changed":{let h=i(r||_("a device"));return g.startsWith("renamed from ")?[...p(_("You renamed device %s of %s"),h,i(s)),a(` · ${m(_("was %s"),g.slice(13))}`)]:g==="turned off"?p(_("You turned off device %s of %s"),h,i(s)):g==="turned on"?p(_("You turned on device %s of %s"),h,i(s)):[...p(_("You changed device %s of %s"),h,i(s)),...g?[a(` · ${Ys(g)}`)]:[]]}case"device_keys":return[...p(_("You issued new keys for device %s of %s"),M,i(s)),a(` · ${_("it needs its new configuration")}`)];case"link_changed":return[...p(_("You issued a new link for person %s"),i(s)),a(` · ${_("the old link stopped working")}`)]}switch(e.type){case"connect":return[...e.detail?c(_("Device %s connected from %s"),u,n("span",{},d(e.detail))):c(_("Device %s connected"),u),...e.where?[a(` · ${e.where}`)]:[]];case"disconnect":return c(_("Device %s went offline"),u);case"roam":return c(_("Device %s changed network %s"),u,n("span",{},(e.detail??"").split(" → ").flatMap((h,S)=>S?[a(" → "),...d(h)]:d(h))));case"device_added":return c(x==="portal"?_("Person %s added device %s on their portal"):_("Person %s added device %s"),i(s),M);case"device_removed":return c(x==="portal"?_("Person %s removed device %s on their portal"):_("Person %s removed device %s"),i(s),M);case"device_keys":return c(_("Person %s issued new keys for device %s on their portal"),i(s),M);case"person_added":return p(_("You added person %s"),i(e.detail??s));case"person_removed":return p(_("You removed person %s"),i(e.detail??s));case"person_changed":return[...p(_("You changed person %s"),i(s)),...g?[a(` · ${Vs(g)}`)]:[]];case"expiring":{let h=Ks(e.detail??"");return h!=null?c(N_(h,"Person %s’s access ends in %s day","Person %s’s access ends in %s days"),i(s),a(V(h))):c(_("Person %s’s access ends in a few days"),i(s))}case"expired_kept":return c(_("Person %s’s end date passed (%s) · access kept"),i(s),a(Xl(e.detail??"")));case"paused":return e.detail?c(_("Person %s paused - %s"),i(s),a(To(e.detail))):c(_("Person %s paused"),i(s));case"resumed":return e.detail&&e.detail!=="active"?c(_("Person %s resumed - %s"),i(s),a(To(e.detail))):c(_("Person %s resumed"),i(s));case"portal_blocked":return c(_("%s blocked %s for 15 min after too many wrong codes"),n("b",{class:"dl-sys-src"},_("Personal portal")),e.detail==="all Cloudflare visitors"?a(_("all Cloudflare visitors")):l(e.detail??""));case"devices_removed":return c(_("Person %s - all devices removed, end date reached"),i(s));case"device_failing":return[...c(_("Device %s has a connection problem"),u),...e.detail?[a(` · ${Js(e.detail)}`)]:[]];case"device_recovered":return c(_("Device %s connects normally again"),u);default:return[a(`${e.type}${e.detail?`: ${e.detail}`:""}`)]}}var ed={portal_blocked:["globe","bad"]};function td(t,e){if(t.servers.length<2||!e.person)return"";let o=t.people.find(r=>r.id===e.person),s=o&&t.servers.find(r=>r.id===o.server);return s?n("span",{class:"dl-ev-srv",title:_("Server")},s.name):""}function ft(t,e,o={}){let s=ed[e.type],r=Ve(e);return n("div",{class:`dl-row${r==="admin"?" dl-ev-by-admin":s?` dl-ev-by-system ${s[1]}`:""}`},[r==="admin"?n("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):s?n("span",{class:"dl-ev-tile sys"},v(s[0])):n("span",{class:`dl-ev-tile ev ${Jl[e.type]??""}`},v(Ql(t,e))),n("span",{class:"dl-row-main"},Zo(t,e)),o.server===!1?"":td(t,e),n("span",{class:"dl-faint dl-nowrap",title:new Date(e.ts*1e3).toLocaleString(ie())},o.time??ce(e.ts,t.now))])}var nd={info:"",up:"ok",down:"warn",repair:"warn",error:"bad"},od={awg:"tunnel",dawnline:"sunrise",portal:"globe"};function sd(t){return{info:_("info"),up:_("up"),down:_("down"),repair:_("repair"),error:_("error")}[t]??t}function rd(t){let e=Zs(t.msg,t.kind,t.who),o=_("You");if(!e)return[n("span",{class:"dl-you"},o),n("span",{class:"dl-muted"},` ${t.msg} `),t.kind?n("span",{class:"dl-ev-kind"},`${t.kind} `):"",t.who?n("b",{},t.who):""];let s=(e.named?oe(e.text,n("b",{},Qs(t.msg,t.who??""))):[e.text]).map(i=>typeof i=="string"?n("span",{class:"dl-muted"},i):i),r=s[0]?.textContent??"";return r.startsWith(`${o} `)?[n("span",{class:"dl-you"},o),n("span",{class:"dl-muted"},r.slice(o.length)),...s.slice(1)]:s}var ai=t=>t.split(` +`).map(e=>zt(e)).join(` +`);function qn(t,e,o,s){let r=t.by==="admin",i=zt(t.msg),a=n("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${nd[t.level]??""}`}${t.detail?" has-detail":""}`},[r?n("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):n("span",{class:"dl-ev-tile sys",title:sd(t.level)},v(od[t.src]??"zap")),n("span",{class:"dl-row-main"},r?[...rd(t),t.note?n("span",{class:"dl-muted"},` · ${Xs(t.note)}`):"",t.detail?n("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",t.detail&&e?n("pre",{class:"dl-slog-detail"},ai(t.detail)):""]:[t.src==="awg"&&t.who&&t.who!=="AmneziaWG"?n("span",{class:"dl-ev-kind"},`${_("Server")} `):"",n("b",{class:"dl-sys-src",title:Qt(t.src)},t.who?t.src==="awg"?t.who:zt(t.who):Qt(t.src)),/^[:,]/.test(i)?"":" ",n("span",{class:"dl-muted"},i),t.detail?n("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",t.detail&&e?n("pre",{class:"dl-slog-detail"},ai(t.detail)):""]),n("span",{class:"dl-faint dl-nowrap",title:new Date(t.ts*1e3).toLocaleString(ie())},s)]);return t.detail&&a.addEventListener("click",l=>{l.target.closest("pre")||o()}),a}function li(t){let e=new Date(t*1e3),o=new Date,s=new Date;if(s.setDate(o.getDate()-1),e.toDateString()===o.toDateString())return _("Today");if(e.toDateString()===s.toDateString())return _("Yesterday");let r=e.toLocaleDateString(ie(),{weekday:"long",day:"numeric",month:"long"});return r.charAt(0).toLocaleUpperCase(ie())+r.slice(1)}var Ut=t=>Pt(t).toLocaleDateString(ie(),{day:"numeric",month:"short"}),pn=200,Wt=40;function di(t,e){let o=Math.max(1,...t.map(a=>Math.max(a[1],a[2]))),s=a=>t.map((l,d)=>`${e[d]*pn},${Wt-2-l[a]/o*(Wt-6)}`),r=s(2),i=s(1);return{area:`M${r.join(" L")} L${e[e.length-1]*pn},${Wt} L${e[0]*pn},${Wt}Z`,down:`M${r.join(" L")}`,up:`M${i.join(" L")}`}}var Kn=(t,e,o,s)=>n("div",{class:"dl-speed-col"},[n("span",{class:"dl-sub"},[n("span",{class:o},e),` ${t}`]),s]),ci=([t,e])=>[n("span",{},oe(_("Today %s"),n("b",{},se(t+e)))),n("span",{},[n("span",{class:"dl-dn"},"↓"),` ${se(e)} `,n("span",{class:"dl-up"},"↑"),` ${se(t)}`])];function pi(t,e,o,s=!1){let r=t.slice(-15),i=r[r.length-1],a=i&&e-i[0]<180,l=a?i[2]:0,d=a?i[1]:0,c;if(r.length>1&&!s){let u=di(r,r.map((g,M)=>M/(r.length-1)));c=kt(``),we(c,()=>{let g=r[r.length-1];return[n("div",{class:"dl-tip-title"},new Date(g[0]*1e3).toLocaleTimeString(ie(),{hour:"2-digit",minute:"2-digit"})),n("div",{},`↓ ${We(g[2])} · ↑ ${We(g[1])}`)]})}else c=n("div",{class:"dl-speed-wait"},[n("i"),s?"":n("span",{},_("Collecting… 1 point a minute"))]);let p=u=>s?n("span",{class:"dl-speed-val off"},"—"):n("span",{class:"dl-speed-val"},We(u));return n("div",{class:"dl-bento-tile"},[n("div",{class:"dl-bento-head"},[n("span",{class:"dl-metric-label"},_("Speed now")),s?"":n("span",{class:"dl-sub"},_("last 15 min"))]),n("div",{class:"dl-speed-cols"},[Kn(_("Download","speed"),"↓","dl-dn",p(l)),Kn(_("Upload","speed"),"↑","dl-up",p(d))]),c,n("div",{class:"dl-speed-today"},ci(o))])}var Vn=class{constructor(){this.span=n("span",{class:"dl-sub"},_("last 2 min"));this.down=n("span",{class:"dl-speed-val"});this.up=n("span",{class:"dl-speed-val"});this.chart=kt(``);this.wait=n("div",{class:"dl-speed-wait"});this.shown=this.wait;this.today=n("div",{class:"dl-speed-today"});this.el=n("div",{class:"dl-bento-tile"},[n("div",{class:"dl-bento-head"},[n("span",{class:"dl-metric-label"},_("Speed now")),this.span]),n("div",{class:"dl-speed-cols"},[Kn(_("Download","speed"),"↓","dl-dn",this.down),Kn(_("Upload","speed"),"↑","dl-up",this.up)]),this.wait,this.today])}update(e,o,s){let r=s||!!e.error;this.span.style.display=s?"none":"";for(let[l,d]of[[this.down,e.tx],[this.up,e.rx]])l.className=`dl-speed-val${r?" off":""}`,l.textContent=r?"—":We(d);let i=!r&&e.pts.length>1;if(i){let l=di(e.pts,e.xs),[d,c,p]=this.chart.querySelectorAll("path");d.setAttribute("d",l.area),c.setAttribute("d",l.down),p.setAttribute("d",l.up)}else dom.content(this.wait,[n("i"),s||e.early&&!e.error?"":n("span",{},e.error?m(_("Couldn't read the live speed: %s"),e.error):_("Collecting… 1 point a second"))]);let a=i?this.chart:this.wait;a!==this.shown&&(this.shown.replaceWith(a),this.shown=a),dom.content(this.today,ci(o))}};function Yn(t,e){let o=t.slice(-30),s=o.map(d=>d.rx+d.tx),r=Math.max(1,...s),i=s.reduce((d,c)=>d+c,0),a=s.reduce((d,c,p)=>c>s[d]?p:d,0),l=n("div",{class:"dl-bento-bars"},o.map((d,c)=>{let p=s[c],u=n("i",{class:c===o.length-1?"hi":"",style:`height:${Math.max(4,p/r*100)}%`}),g=n("span",{},[u]);return we(g,()=>[n("div",{class:"dl-tip-title"},c===o.length-1?`${_("Today")} · ${Ut(d.day)}`:Ut(d.day)),n("div",{},se(p)),n("div",{class:"dl-muted dl-mono"},`↓ ${se(d.tx)} ↑ ${se(d.rx)}`)]),g}));return n("div",{class:"dl-bento-tile month"},[n("div",{class:"dl-bento-head"},[n("span",{},[n("span",{class:"dl-metric-label"},_("Last 30 days")),n("b",{class:"dl-bento-total"},se(i))]),s[a]>0?n("span",{class:"dl-sub"},`${m(_("peak %s"),se(s[a]))} · ${Ut(o[a].day)}`):""]),o.length?l:n("p",{class:"dl-muted"},_("No traffic yet.")),n("div",{class:"dl-bento-head"},[n("span",{class:"dl-sub"},o.length?Ut(o[0].day):""),n("span",{class:"dl-sub"},e),n("span",{class:"dl-sub"},_("today"))])])}function mi(t){let e=t.slice(-30),o=e.map(r=>r.rx+r.tx),s=Math.max(1,...o);return n("div",{class:"dl-dbars"},e.map((r,i)=>{let a=n("i",{class:`${o[i]?"":"zero"}${i===e.length-1?" hi":""}`});a.style.height=`${Math.max(8,o[i]/s*100)}%`;let l=n("span",{},[a]);return we(l,()=>[n("div",{class:"dl-tip-title"},i===e.length-1?`${_("Today")} · ${Ut(r.day)}`:Ut(r.day)),n("div",{},se(o[i]))]),l}))}function hi(t){return{apply:_("Repair"),sync:_("Reload devices"),restart:_("Restart service"),netrestart:_("Restart network"),updates:_("Open Components")}[t]??_("Fix")}async function Jn(t){return t==="netrestart"&&!await pe(_("Restart the network?"),_("Every interface restarts. Connections drop for a few seconds."),_("Restart network"))?null:await q(()=>N.healthFix(t),_("Done"))??null}function Qo(t,e,o,s="action"){let r=t.fix;return r?r.startsWith("install:")?H(_("Install"),()=>ri(r.slice(8),o),s):r==="updates"?n("a",{class:`cbi-button cbi-button-${s}`,href:L.url("admin/network/dawnline/updates")},hi(r)):H(hi(r),()=>e(r),s):""}function id(t){return/^(awg|up_|peers_|fw_|reply_|port_|subnet_)/.test(t)?"shield":/^(portal|cert)/.test(t)?"link":/^(ep_|home_|resolver)/.test(t)?"globe":t==="clock"?"clock":t==="agent"?"activity":t==="flash"?"download":t==="nft"?"lock":t==="data"?"users":"alert"}function fi(t,e,o,s=3){let r=t.filter(a=>a.status==="error"||a.status==="warn").sort((a,l)=>a.status===l.status?0:a.status==="error"?-1:1);if(!r.length)return"";let i=r.length-s;return n("div",{class:"dl-list dl-notices"},[...r.slice(0,s).map(a=>lt(id(a.id),a.status==="error"?"bad":"warn",a.problem??a.title,a.detail,Qo(a,e,o,a.status==="error"?"positive":"neutral"))),i>0?n("a",{class:"dl-row dl-notices-more",href:L.url("admin/network/dawnline/diagnostics")},[m(_("%s more in Diagnostics"),V(i)),n("span",{class:"dl-spacer"}),"→"]):""])}function ad(t){let e=[],o=(l,d)=>n("a",{href:l},d),s=()=>o(L.url("admin/network/dawnline/diagnostics"),_("Open Diagnostics")),r=Ge(t.series),i=!!t.awg_state&&!t.awg_state.ok;for(let l of t.servers)l.enabled&&l.blocked?e.push({tone:"bad",text:[l.blocked," ",s()]}):l.enabled&&!l.up&&!i&&e.push({tone:"bad",text:[m(_("Tunnel %s is down."),l.ifname)," ",s()]});for(let l of t.people){let d=()=>o(He(l.id),l.name);if(l.state==="quota")e.push({tone:"warn",text:oe(_("%s reached the data limit."),d())});else if(l.state==="expired")e.push({tone:"warn",text:oe(_("%s’s access has ended."),d())});else{let c=rt(l.expires,r);it(l,c)?e.push({tone:"",text:oe(_("%s’s access %s."),d(),fn(c))}):c!=null&&c<0&&l.expire_action==="notify"&&e.push({tone:"",text:oe(_("%s’s end date passed (%s) · access kept."),d(),$e(l.expires))}),l.quota_limit&&l.quota_used>=l.quota_limit*.9&&e.push({tone:"",text:oe(_("%s has used 90% of the data limit."),d())})}}let a=t.people.flatMap(l=>l.devices.filter(d=>d.config_stale).map(d=>[l,d]));a.length&&e.push({tone:"warn",text:a.length===1?oe(_("%s needs its configuration again."),o(He(a[0][0].id,a[0][1].id),`${a[0][0].name} · ${a[0][1].name}`)):[G(a.length,"%s device needs its configuration again (networks or DNS changed).","%s devices need their configuration again (networks or DNS changed).")]});for(let l of t.servers)t.wan&&Ht(l.endpoint)&&l.endpoint!==t.wan&&e.push({tone:"warn",text:[m(_("Public address changed: %s still gives devices %s, the router is %s now."),l.name,l.endpoint,t.wan)," ",n("button",{type:"button",class:"dl-fix",click:async d=>{let c=d.currentTarget;c.disabled=!0,await q(()=>N.serverUpdate(l.id,{endpoint:t.wan}),m(_("%s uses %s now - devices need their configuration again"),l.name,t.wan)),c.disabled=!1}},_("Use the new address"))," ",_("A DDNS name would follow it by itself.")]});return t.servers.some(l=>l.lan_like)&&t.like_home.error&&e.push({tone:"warn",text:[m(_("Internet through the LAN is off: %s"),t.like_home.error)," ",o(L.url("admin/network/dawnline/diagnostics"),_("Details"))]}),!t.settings.portal_enabled&&!t.people.length&&e.push({tone:"",text:[_("The personal portal is off.")," ",o(L.url("admin/network/dawnline/settings"),_("Turn on"))]}),e}var Zn=class{constructor(e,o,s){this.srvId=e;this.meter=o;this.go=s;this.el=n("div",{class:"dl-srvov"});this.map=null;this.mapOn=null;this.range="online";this.parts={};this.healthAt=0;this.speed=new Vn}mount(e){this.st=ln(e,this.srvId);for(let o of["health","bento","map","side","activity"])this.parts[o]=n("div",{});return dom.content(this.el,[this.parts.health,this.parts.bento,this.parts.map,n("div",{class:"dl-grid2"},[this.parts.activity,this.parts.side])]),this.paint(),this.loadHealth(),this.el}update(e,o=!1){this.st=ln(e,this.srvId),this.paint(o),Date.now()-this.healthAt>6e4&&this.loadHealth()}async loadHealth(){this.healthAt=Date.now();let e=await N.health().catch(()=>null);if(!e)return;let o=()=>void this.loadHealth(),s=async r=>{await Jn(r)&&(o(),r==="netrestart"&&setTimeout(o,5e3))};Ne(this.parts.health,fi(e.checks,r=>void s(r),o),!0)}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now}}paintMap(){let e=this.st.geo.enabled;if(e===this.mapOn&&(!e||this.map)){this.map?.update(this.mapData());return}this.mapOn=e,dom.content(this.parts.map,this.mapCard())}mapCard(){let e=this.st,o=n("div",{class:"dl-panel-head pad"},[n("div",{class:"dl-stack"},[n("h3",{},_("Where people connect from")),n("span",{class:"dl-sub"},_("City-level, from the client IP · locations cached on the router"))]),n("span",{class:"dl-spacer"}),Bt(this.range,l=>{this.range=l,this.map?.setRange(l)})]);if(this.map?.destroy(),this.map=null,!e.geo.enabled)return n("div",{class:"dl-panel flush"},[o,n("div",{class:"dl-map-off"},oe(_("Locations are off. %s."),n("a",{href:L.url("admin/network/dawnline/settings")},_("Turn them on in Settings"))))]);let s=this.map=new ct({openPerson:l=>location.href=He(l),openDevice:(l,d)=>location.href=He(l,d)},this.range),r=Ee(()=>{r(),s.destroy(),this.map===s&&(this.map=null)}),i=n("div",{class:"dl-map-legend"},[n("span",{},[n("i",{class:"line live"}),_("Live tunnel")]),n("span",{},[n("i",{class:"line"}),_("Seen recently")])]),a=n("div",{class:"dl-map-wrap"},[s.el,i]);return requestAnimationFrame(()=>s.mount(this.mapData())),n("div",{class:"dl-panel flush"},[o,a])}paint(e=!1){let o=this.st,s=o.servers[0];this.paintMap(),e&&ut(this.parts.bento)?this.paintSpeed():dom.content(this.parts.bento,n("div",{class:"dl-bento"},[this.onlineTile(),this.speedTile(),Fe(s).overviewTile(s),this.monthTile()]));let r=ad(o);Ne(this.parts.side,n("div",{class:"dl-panel flush"},[n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Needs attention")),n("span",{class:"dl-spacer"}),n("a",{href:L.url("admin/network/dawnline/diagnostics")},_("Health"))]),r.length?r.slice(0,8).map(a=>n("div",{class:"dl-attn-item dl-row"},[n("span",{class:`dl-ev-dot ${a.tone}`}),n("span",{},a.text),a.action??""])):n("div",{class:"dl-row dl-muted"},[v("check"),_("All good. Nothing needs you right now.")])]),e);let i=[...o.events].reverse().slice(0,8);Ne(this.parts.activity,n("div",{class:"dl-panel flush"},[n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Activity")),n("span",{class:"dl-spacer"}),n("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},_("View all"))]),i.length?i.map(a=>ft(o,a)):n("div",{class:"dl-row dl-muted"},_("Nothing yet. Connections, new devices and pauses appear here."))]),e)}onlineTile(){let e=this.st,o=e.servers[0]?!e.servers[0].enabled:!1,s=12,r=B=>{let[P,R]=B.spark[B.spark.length-1]??[0,0];return P+R},i=B=>e.geo.points.find(P=>P.device===B.id&&P.city)?.city,a=B=>/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(B.endpoint??""),l=(B,P=!1)=>a(B)?P&&B.endpoint?`LAN · ${B.endpoint}`:"LAN":i(B)??"",d=B=>[...e.events].reverse().find(P=>P.type==="connect"&&P.device===B.id)?.ts??0,c=e.people.map(B=>({p:B,devs:B.devices.filter(P=>P.online).sort((P,R)=>r(R)-r(P))})).filter(B=>B.devs.length).sort((B,P)=>P.devs.reduce((R,w)=>R+r(w),0)-B.devs.reduce((R,w)=>R+r(w),0)),p=c.length<=2,u=({p:B,devs:P})=>{let R=P.map(d).filter(Boolean),w=R.length?Math.min(...R):0,k=(B.rate??[]).slice(-15),y=k[k.length-1],O=y&&e.now-y[0]<180?y:null,b=200,f=30,T=Math.max(1,...k.map(Q=>Math.max(Q[1],Q[2]))),C=Q=>k.map((j,Z)=>`${k.length>1?Z/(k.length-1)*b:b},${f-2-j[Q]/T*(f-6)}`),A=k.length>1?kt(``):"",K=!O||O[1]<64&&O[2]<64,Y=B.access==="both"?["home","globe"]:B.access==="lan"?["home"]:["globe"];return[n("div",{class:"dl-hc"},[n("div",{class:"dl-hc-head"},[n("span",{class:"dl-onl-av sm"},Oe(B.name)),n("span",{class:"dl-stack"},[n("b",{},B.name),n("span",{class:"dl-hc-since"},w?m(_("online for %s"),st(Math.max(60,e.now-w))):_("online"))]),n("span",{class:"dl-hc-reach"},Y.map(Q=>n("span",{class:`dl-ibadge ${Q==="home"?"lan":"inet"}`},v(Q))))]),n("div",{class:"dl-hc-speed"},[n("div",{class:"dl-hc-speed-row"},K?[n("span",{class:"dl-faint"},_("Idle right now"))]:[n("span",{},[n("span",{class:"dl-dn"},"↓"),` ${We(O[2])}`]),n("span",{},[n("span",{class:"dl-up"},"↑"),` ${We(O[1])}`]),n("span",{class:"dl-spacer"}),n("span",{class:"dl-faint"},_("15 min"))]),A]),n("div",{class:"dl-hc-devs"},P.map(Q=>n("span",{class:"dl-hc-dev"},[v(Q.kind),Q.name,l(Q)?[" · ",l(Q,!0)]:""]))),n("div",{class:"dl-hc-foot"},[n("span",{class:"dl-faint"},`${m(_("%s today"),se(P.reduce((Q,j)=>Q+r(j),0)))} · ${m(_("%s this month"),se(B.month[0]+B.month[1]))}`)])])]},g=B=>{let{p:P,devs:R}=B,w=n("span",{class:"dl-onl-dev"},R.length>1?String(R.length):v(R[0].kind)),k=n("a",{class:`dl-onl-p${p?"":" sm"}`,href:He(P.id),"aria-label":m(_("%s, online"),P.name)},[n("span",{class:"dl-onl-av"},[Oe(P.name),w]),p?n("span",{class:"dl-onl-name"},P.name):"",p?n("span",{class:"dl-onl-meta"},[...R.slice(0,3).map(y=>v(y.kind)),R.length>3?`+${R.length-3}`:"",l(R[0])?n("span",{},[" · ",l(R[0])]):""]):""]);return we(k,()=>u(B)),k},M=n("b",{class:`dl-onl-count${c.length?"":" none"}`},String(c.length)),x=c.reduce((B,P)=>B+P.devs.length,0);c.length&&we(M,()=>[`${G(c.length,"%s person","%s people")} · ${G(x,"%s device","%s devices")}`]);let h=c.length>s?c.slice(0,s-1):c,S=e.people.flatMap(B=>B.devices.map(P=>({p:B,d:P}))).filter(B=>B.d.handshake).sort((B,P)=>P.d.handshake-B.d.handshake)[0];return n("div",{class:"dl-bento-tile online"},[n("div",{class:"dl-bento-head"},[n("span",{class:"dl-metric-label"},_("Online")),M]),c.length?n("div",{class:`dl-onl-row${p?"":" grid"}`},[...h.map(g),c.length>s?n("a",{class:"dl-onl-p sm more",href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(this.srvId)}§ion=people&filter=online`,title:_("Everyone online"),click:B=>{this.go&&(B.preventDefault(),this.go("people","online"))}},[n("span",{class:"dl-onl-av"},`+${c.length-h.length}`)]):""]):n("div",{class:"dl-onl-empty"},[n("span",{},o?_("The server is turned off"):_("Nobody is connected")),S?n("span",{class:"dl-sub"},m(_("Last: %s, %s"),S.p.name,ce(S.d.handshake,e.now))):n("span",{class:"dl-sub"},o?_("Devices connect once it is on"):_("No device has connected yet"))])])}speedTile(){return this.paintSpeed(),this.speed.el}paintSpeed(){if(!this.st)return;let e=this.st.servers[0];this.speed.update(this.meter.speed(this.srvId,Date.now()),this.st.totals.today,e?!e.enabled:!1)}monthTile(){let e=[...this.st.people].map(o=>[o,o.month[0]+o.month[1]]).filter(([,o])=>o>0).sort((o,s)=>s[1]-o[1]).slice(0,2);return Yn(this.st.series,e.length?m(_("Most: %s"),e.map(([o,s])=>`${o.name} ${se(s)}`).join(" · ")):"")}};var gi=["overview","people","connection","access","awg"],ld=t=>({overview:_("Overview"),people:_("People"),connection:_("Connection"),access:_("Access")})[t],dd={general:"connection",network:"connection",interfaces:"access",advanced:"awg",disguise:"awg",tunnel:"awg",core:"awg"},Xo=(t,e)=>{let o=new URLSearchParams;t&&o.set("server",t),e&&e!=="overview"&&o.set("section",e);let s=o.toString();return`${L.url("admin/network/dawnline/server")}${s?`?${s}`:""}`},un=class{constructor(){this.noFooter=!0;this.root=n("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=n("div",{});this.headEl=n("div",{});this.secEl=n("div",{});this.bodyEl=n("div",{class:"dl-srvbody"});this.meter=new Fn}async load(){let e=await N.status(31),o=e.servers.length?null:await N.setupDefaults();return[e,o]}render([e,o]){if(this.st=e,!e.servers.length&&o)return this.wizard(o);let s=new URLSearchParams(location.search),r=s.get("section")??"",i=dd[r]??r;return gi.includes(i)&&(this.section=i),this.srvId=(e.servers.find(a=>a.id===s.get("server"))??e.servers[0]).id,dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),this.poller?.stop(),this.poller=nt({fetch:()=>N.status(31),every:30,live:!0,active:()=>this.section==="overview"&&this.root.isConnected,apply:(a,l)=>{a.servers.length&&(this.st=a,this.paintHead(l),this.ov[this.current().id]?.update(a,l))}}),this.meterPoller?.stop(),this.meterPoller=nt({fetch:()=>N.meter(this.meter.since(Date.now())).then(a=>({meter:a}),a=>({error:_e(a)})),every:1,active:()=>this.section==="overview"&&this.root.isConnected&&this.current().enabled,apply:a=>{this.meter.take(a,Date.now()),this.ov[this.current().id]?.paintSpeed()}}),this.root}paintHead(e=!1){Ne(this.headEl,this.head(this.current()),e),(!e||!ut(this.tabsEl))&&this.paintTabs()}async refreshStatus(){let e=await N.status(31).catch(()=>null);return e?.servers.length?(this.st=e,this.paintHead(),e):null}current(){return this.st.servers.find(e=>e.id===this.srvId)??this.st.servers[0]}async refresh(){let e=await N.status(31).catch(()=>null);e&&(this.st=e,e.servers.length?this.paint():location.href=Xo())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let e=this.current();dom.content(this.tabsEl,n("div",{class:"dl-srvtabs",role:"tablist","aria-label":_("Servers")},[...this.st.servers.map(o=>n("button",{type:"button",role:"tab",class:`dl-srvtab${o.id===e.id?" on":""}`,"aria-selected":o.id===e.id?"true":"false",click:()=>{o.id!==this.srvId&&(this.srvId=o.id,this.paint())}},[n("i",{class:`dot ${o.enabled?o.up?"ok":"bad":"warn"}`}),n("b",{},o.name)])),n("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[v("plus"),_("Add server")])]))}paintSections(){let e=Fe(this.current());dom.content(this.secEl,n("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":_("Server")},gi.map(o=>n("button",{type:"button",role:"tab","data-section":o,class:o===this.section?"on":"","aria-selected":o===this.section?"true":"false",click:()=>this.showSection(o)},o==="awg"?e.label:ld(o)))))}go(e,o){let s=this.pp[this.current().id];if(o&&s)s.filter=o,s.el&&s.decorate();else if(o){let r=this.pp[this.current().id]=new Ct;r.filter=o}this.showSection(e),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let e=[...Object.values(this.ov).map(o=>o.el),...Object.values(this.pp).map(o=>o.el)];for(let o of e)o&&this.bodyEl.contains(o)&&o.remove()}showSection(e){this.section=e,this.secEl.querySelectorAll("[data-section]").forEach(a=>{let l=a.dataset.section===e;a.classList.toggle("on",l),a.setAttribute("aria-selected",l?"true":"false")});let o=this.st,s=this.current(),i={overview:()=>{let a=this.ov[s.id];return a?(a.update(o),a.el):(this.ov[s.id]=new Zn(s.id,this.meter,(l,d)=>this.go(l,d))).mount(o)},people:()=>{var c,p;let a=this.pp[s.id];if(a?.el)return a.update(),a.el;let l=n("div",{},n("p",{class:"dl-muted"},_("Loading people…")));return((c=this.pp)[p=s.id]??(c[p]=new Ct)).embed(o,s.id).then(u=>{l.isConnected?dom.content(l,u):l.replaceChildren(u)}).catch(u=>{delete this.pp[s.id],dom.content(l,n("p",{class:"dl-muted"},m(_("Couldn't show people: %s"),_e(u))))}),l},connection:()=>this.connection(s),access:()=>this.access(s),awg:()=>this.awg(s)}[e]();this.detachKept(),dom.content(this.bodyEl,i)}head(e){let o=(i,a)=>n("span",{class:"dl-addrbar-seg"},[v(i),...a]),s=e.endpoint||"—",r=n("div",{class:"dl-actions"},[e.enabled?"":H([v("play"),` ${_("Turn on")}`],()=>this.save(e,{enabled:"1"},_("Server turned on")),"add")]);return n("div",{class:"dl-srvpagehead"},[n("div",{class:"dl-title-row"},[n("h2",{class:"dl-h1"},e.name),n("span",{class:`dl-pill ${e.enabled?e.up?"ok":"bad":"warn"}`},e.enabled?e.up?_("Running"):e.blocked?_("Can’t start"):_("Not running"):_("Turned off")),n("span",{class:"dl-spacer"}),r]),n("div",{class:"dl-addrbar"},[n("button",{type:"button",class:"dl-addrbar-seg main",title:_("Copy address"),click:()=>xe(s,_("Address copied"))},[v("globe"),n("span",{class:"dl-mono"},s),v("copy")]),o(Fe(e).id==="awg"?"amneziawg":"tunnel",[n("span",{class:"dl-mono"},`${Fe(e).label} :${e.port}`)]),e.up?o("clock",[m(_("up %s"),st(e.uptime))]):""]),e.blocked?wt(e.blocked):""])}async save(e,o,s=_("Saved")){await q(()=>N.serverUpdate(e.id,o),s)&&await this.refresh()}connection(e){let o=ue(e.name,{placeholder:_("Home")}),s=ue(e.endpoint,{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),r=ue(e.dns.join(", "),{placeholder:_("This router (recommended)"),class:"cbi-input-text dl-mono"}),i=this.st.people.filter(M=>M.server===e.id).length,a=H([v(e.enabled?"pause":"play"),` ${e.enabled?_("Turn off"):_("Turn on")}`],async()=>{e.enabled&&!await pe(m(_("Turn off %s?"),e.name),G(i,"The tunnel stops and %s person is disconnected until you turn it back on. Nothing is deleted.","The tunnel stops and %s people are disconnected until you turn it back on. Nothing is deleted."),_("Turn off"),!0)||await this.save(e,{enabled:e.enabled?"0":"1"},e.enabled?_("Server turned off"):_("Server turned on"))},e.enabled?"negative":"positive"),l=this.st.settings.portal_host,d=Ce(_("Name"),o,()=>je(o.value,[],_("Shown to people in their portal and apps."))),c=Lo(()=>({host:s.value,port:e.port,id:e.id}),(M,x,h)=>N.endpointProbe(M,x,h),()=>p.refresh(),{empty:l?m(_("Empty = the portal’s address (%s)."),l):_("Empty = the portal’s address.")}),p=Ce(_("Public address"),s,c.help);s.addEventListener("input",c.schedule),c.schedule();let u=e.reached?m(_("Reached from the internet %s."),ce(e.reached,this.st.now)):_("Never reached from the internet yet - test with a phone on mobile data."),g=Ce(_("DNS for devices"),r,()=>Ps(r.value,e.address));return n("div",{class:"dl-stack gap16"},[Vt(_("Connection"),[n("p",{class:"dl-muted"},_("The name people see, where devices find the router, and DNS. The port is on AmneziaWG.")),ye("router",_("Server"),_("What people see"),[d]),ye("globe",_("Devices connect to"),_("A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)"),[p,n("div",{class:`dl-sub ${e.reached?"ok":"warn"}`},u)]),ye("file",_("For every device"),_("Changing it marks devices “Update config” until they import again"),[g])],[n("span"),H(_("Save"),()=>{let M=Be([d,p,g]);if(M){F(M,"warning");return}return this.save(e,{name:o.value,endpoint:s.value,dns:r.value})},"positive")]),Vt(_("Danger zone"),[n("div",{class:"dl-setrow"},[n("div",{class:"dl-stack"},[n("span",{class:"dl-setrow-label"},e.enabled?_("Turn off this server"):_("This server is off")),n("span",{class:"dl-sub"},e.enabled?_("Stops the tunnel and disconnects everyone on it. Settings and people are kept."):_("Nobody can connect. Turn it on to bring the tunnel back."))]),n("div",{class:"dl-setrow-ctl"},a)]),n("div",{class:"dl-setrow"},[n("div",{class:"dl-stack"},[n("span",{class:"dl-setrow-label"},_("Change the tunnel network")),n("span",{class:"dl-sub"},m(_("Devices have %s addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again."),`${Nt(e.subnet)}.x`))]),n("div",{class:"dl-setrow-ctl"},H([v("edit"),` ${_("Change")}`],()=>this.changeSubnet(e),"negative"))]),n("div",{class:"dl-setrow"},[n("div",{class:"dl-stack"},[n("span",{class:"dl-setrow-label"},_("Remove server")),n("span",{class:"dl-sub"},G(i,"Removes the tunnel, its firewall rules and %s person with all their devices. A backup is made first.","Removes the tunnel, its firewall rules and %s people with all their devices. A backup is made first."))]),n("div",{class:"dl-setrow-ctl"},H([v("trash"),` ${_("Remove")}`],()=>this.remove(e),"negative"))])],[],"danger")])}access(e){let o=Ko(this.st,e),s=ii(e,this.st,async()=>{let r=await this.refreshStatus();if(!r)return;let i=r.servers.find(l=>l.id===e.id)??e;s.update(r);let a=Ko(r,i);o.replaceWith(a),o=a});return n("div",{class:"dl-stack gap16"},[s.el,n("div",{class:"dl-health-cols"},[o,Xr(this.st,e)])])}awg(e){let o={st:this.st,save:(s,r)=>this.save(e,s,r),refresh:()=>this.refresh()};return n("div",{class:"dl-stack gap16"},[Fe(e).settingsCard(o,e)])}async addServer(){let e=await q(()=>N.setupDefaults());e&&dom.content(this.root,this.wizard(e,!0,()=>{dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint()}))}async changeSubnet(e){let o=await q(()=>N.serverPorts(e.id));if(!o)return;let s=o.networks??[],r=this.st.people.filter(l=>l.server===e.id).reduce((l,d)=>l+d.devices.length,0),i=ue(Nt(e.subnet),{class:"cbi-input-text dl-mono dl-w-range"}),a=Ce(_("Address range"),i,()=>ko(i.value,s,""));ae(_("Change the tunnel network"),[a,n("p",{class:"dl-muted"},r?G(r,"%s device gets a new address and stops connecting until it imports its configuration again (from their personal link or from you).","%s devices get new addresses and stop connecting until they import their configuration again (from their personal link or from you)."):_("No devices on this server yet: nothing else changes."))],[de()," ",H(_("Change"),async()=>{let l=a.help();if(l.bad){F(l.text,"warning");return}let d=Cn(i.value);if(d===e.subnet){le();return}await q(()=>N.serverUpdate(e.id,{subnet:d}),_("Tunnel network changed"))&&(le(),r&&F(_("Devices are marked “Update config” until they import again."),"info",6e3),await this.refresh())},"negative")]),setTimeout(()=>i.select(),50)}async remove(e){let o=this.st.people.filter(s=>s.server===e.id);ae(m(_("Remove %s?"),e.name),[n("p",{},G(o.length,"This removes the tunnel, its firewall rules and %s person with all their devices. A backup is made first.","This removes the tunnel, its firewall rules and %s people with all their devices. A backup is made first."))],[de()," ",H(_("Remove"),async()=>{le(),await q(()=>N.serverDelete(e.id),_("Server removed"))&&setTimeout(()=>{location.href=Xo()},800)},"negative")])}wizard(e,o=!1,s){let r={id:e.id,name:e.name,endpoint:e.endpoint,port:e.port,range:Nt(e.subnet),preset:$n(e.awg),portal:!1,portal_port:e.portal_port||8443,lan_like:!1,lan_zone:e.lan_zone,wan_zone:e.wan_zone},i=0,a=!o&&r.portal_port===r.port,l=()=>/^\d{1,3}(\.\d{1,3}){3}$/.test(r.endpoint),d=()=>Jt(r.port,e.udp_taken??[],r.port===4500?`${_("Opened on the WAN firewall automatically.")} ${_("4500 is IPsec’s port: most networks let it through.")}`:_("Opened on the WAN firewall automatically.")),c={ddns:_("From your DDNS name."),cert:_("From your Let’s Encrypt certificate."),wan:_("Your WAN address now - it may change; a DDNS name is better."),portal:_("The portal’s address.")},p=Lo(()=>({host:r.endpoint,port:r.port}),(C,A,K)=>N.endpointProbe(C,"",K),()=>u?.refresh(),{idle:()=>r.endpoint===e.endpoint&&e.endpoint_from?c[e.endpoint_from]??"":""}),u=null,g=e.wan_kind==="cgnat"||e.wan_kind==="private"?lt("alert","warn",e.wan_kind==="cgnat"?_("Your router has no public address (CGNAT)"):m(_("Your router is behind another router (WAN %s)"),e.wan_ip),e.wan_kind==="cgnat"?_("The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address."):_("Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here."),""):"",M=e.awg_state?.tools&&e.awg_state.handler===!1?wt(_("Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.")):"",x=()=>ko(r.range,e.networks??[],Nt(e.subnet)),h=()=>Ln(r.portal_port,e.tcp_taken??[],l()),S=n("div",{class:"dl-wizard"}),B=(C,A={})=>{let K=ue(String(r[C]),A);return K.addEventListener("input",()=>{C==="port"||C==="portal_port"?r[C]=K.value.trim()===""?0:Number(K.value):r[C]=K.value.trim(),C==="port"&&a&&(r.portal_port=r.port),C==="portal_port"&&(a=r.portal_port===r.port)}),K},P=()=>{let C=Jo(),A=ge(_("Through the home network"),be(r.lan_like,_("Internet like a home device"),Q=>{r.lan_like=Q,K()})," "),K=()=>{dom.content(A.querySelector(".dl-sub"),r.lan_like?_("Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access."):Yo(e.ifname)),r.lan_like?A.after(C):C.remove()},Y=ye("home",_("Internet like a home device"),_("How devices reach the internet"),[A]);return K(),Y},R={id:"server",title:_("Server"),render:()=>n("div",{class:"dl-wizard-groups"},[n("p",{class:"dl-muted"},o?_("One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page."):_("Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.")),ye("router",_("Server"),_("What people see"),[Ce(_("Name"),B("name"),()=>je(r.name,[],_("Shown to people in their portal and apps.")))]),ye("globe",_("Devices connect to"),_("A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT"),[(()=>{let C=B("endpoint",{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"});return u=Ce(_("Public address"),C,p.help),C.addEventListener("input",p.schedule),p.schedule(),u})()]),g,M]),check:()=>{let C=je(r.name);if(C.bad)return m(_("Name: %s"),C.text);let A=At(r.endpoint,r.port);return A.bad?m(_("Public address: %s"),A.text):null}},w={id:"awg",title:"AmneziaWG",render:()=>n("div",{class:"dl-wizard-groups"},[ye("globe",_("Listening"),_("Where devices reach AmneziaWG from the internet"),[Ce(_("UDP port"),B("port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),d)]),ye("network",_("Tunnel network"),_("Addresses devices get inside the tunnel"),[(()=>{let C=B("range",{class:"cbi-input-text dl-w-range dl-mono","aria-label":_("First three numbers of the device addresses")});return Ce(_("Device addresses"),C,x,n("span",{class:"dl-suffixed"},[C,n("span",{class:"dl-mono"},".x")]))})()]),ye("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[Dn(e.awg,r.preset,C=>r.preset=C,void 0,e.awg_state?.tools!==!1)]),o?P():""]),check:()=>{let C=d();if(C.bad)return m(_("UDP port: %s"),C.text);let A=x();return A.bad?m(_("Device addresses: %s"),A.text):null}},k={id:"portal",title:_("Portal"),render:()=>{let C=B("portal_port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),A=Ce(_("Listening port"),C,h);A.hidden=!r.portal;let K=Ze([["off",_("Off")],["on",_("On")]],r.portal?"on":"off",{label:_("Personal portal"),onChange:Y=>{r.portal=Y==="on",A.hidden=!r.portal}});return n("div",{class:"dl-wizard-groups"},[P(),ye("link",_("Personal portal"),_("A page where each person adds their own devices with their personal link"),[ge(_("Portal"),K,_("Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.")),A])])},check:()=>{if(!r.portal)return null;let C=h();return C.bad?m(_("Portal port: %s"),C.text):null}},y=()=>[R,w,o?null:k].filter(C=>C!=null),O=e.awg_state,b=O?.missing??[],f=b.length?n("div",{class:"dl-list dl-notices"},[lt("shield","bad",_("AmneziaWG isn’t installed"),m(_("The tunnel needs %s. Install the build made for this firmware, then create the server."),new Intl.ListFormat(ie(),{type:"conjunction"}).format(b)),H(_("Install"),()=>Gn(()=>location.reload()),"positive"))]):O&&!O.loaded?n("div",{class:"dl-list dl-notices"},[lt("shield","warn",_("AmneziaWG’s kernel module doesn’t load on this firmware"),_("Try another build in Components, or update OpenWrt. The server can’t start until it loads."),n("a",{class:"cbi-button cbi-button-neutral",href:L.url("admin/network/dawnline/updates")},_("Open Components")))]):"",T=()=>{let C=y();i>=C.length&&(i=C.length-1),dom.content(S,[n("h2",{},o?_("Add a server"):_("Set up Dawnline")),f,n("div",{class:"dl-steps"},C.map((A,K)=>n("span",{class:`dl-step${K===i?" current":K0?H(_("Back"),()=>{i--,T()}):s?H(_("Cancel"),s):"",n("span",{class:"dl-spacer"}),i{let A=C[i].check?.();if(A){F(A,"warning");return}i++,T()},"positive"):H(_("Create server"),async()=>{for(let K of C){let Y=K.check?.();if(Y){F(Y,"warning");return}}let A=await q(()=>N.serverCreate(r.id,r.name,e.ifname,r.port,Cn(r.range),r.endpoint,e.mtu,r.preset,r.lan_zone,r.wan_zone,r.lan_like,o?void 0:r.portal,o?void 0:r.portal_port),_("Server created"));A&&(A.network_restart&&F(_("Restarting the network so it knows AmneziaWG: back in a few seconds")),setTimeout(()=>{location.href=Xo(A.id)},A.network_restart?1e4:1500))},"positive",{disabled:b.length>0,title:b.length?_("Install AmneziaWG first"):null})])])};return T(),S}};function gt(t){let e={el:t(),refresh(){let o=t();e.el.replaceWith(o),e.el=o}};return e}function Ue(t,e,o,s,r="",i=[]){return n("section",{class:`dl-setsec ${r}`,id:`dl-set-${t}`},[n("div",{class:"dl-setsec-body"},[i.length?n("div",{class:"dl-setsec-head"},[n("h3",{},e),n("span",{class:"dl-spacer"}),...i]):n("h3",{},e),...o]),s.length?n("div",{class:"dl-setsec-foot"},s):""])}function vi(t){let e=t.filter(r=>r.status!=="skip"),o=e.filter(r=>r.status==="error"||r.status==="warn"),s=e.some(r=>r.status==="error")?"error":o.length?"warn":"ok";return{bad:o,worst:s}}function bi(t){let e=t.d.settings,o=t.d.effective,s=t.d.cert,r=be(o.portal_enabled,_("Enable portal")),i=ue(e.portal_port,{placeholder:"8443",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),a=ue(e.portal_redirect,{placeholder:_("Show “Not found”"),class:"cbi-input-text dl-mono"}),l=ue("",{placeholder:_("vpn.example.com or an IP"),"aria-label":_("Other address")}),d=U=>/^\d{1,3}(\.\d{1,3}){3}$/.test(U),c=[o.portal_host,...o.portal_alt??[]].filter((U,ne,he)=>U&&he.indexOf(U)===ne),p=!!t.portal,u=[],g=U=>{U&&!u.some(ne=>ne.host===U)&&u.push({host:U,kind:d(U)?"ip":"name",ips:[],here:!1,cloudflare:!1,cert:!1})},M=U=>{u=[...U,...u.filter(ne=>!U.some(he=>he.host===ne.host))],!c.length&&U[0]&&(c=[U[0].host])};t.portal&&M(t.portal.candidates),c.forEach(g);let x=U=>U.kind==="ip"?n("span",{class:"dl-addr-warn"},[v("alert"),_("Plain HTTP: the link and VPN keys travel unencrypted")]):n("span",{class:"dl-sub"},U.cloudflare?_("Behind Cloudflare · often stalls in Russia"):U.ips.length?U.here?U.cert?_("Points at this router · Let’s Encrypt certificate"):_("Points at this router · no certificate yet"):m(_("Points at %s, not this router"),U.ips.join(", ")):p?_("Your address"):_("Checking where it points…")),h=n("div",{class:"dl-addr-opts",role:"group","aria-label":_("Portal addresses")}),S=U=>{c.includes(U)?c.length>1&&(c=c.filter(ne=>ne!==U)):c=[...c,U],B(),w()},B=()=>dom.content(h,[...u.map(U=>{let ne=c.includes(U.host),he=c[0]===U.host;return n("div",{class:`dl-addr-opt${ne?" on":""}`,role:"checkbox","aria-checked":ne?"true":"false",tabindex:"0",click:()=>S(U.host),keydown:fe=>{(fe.key===" "||fe.key==="Enter")&&(fe.preventDefault(),S(U.host))}},[n("i",{class:"dl-addr-check"},ne?v("check"):""),n("span",{class:"dl-stack"},[n("span",{class:"dl-mono"},U.host),x(U)]),he?n("span",{class:"dl-pill info"},_("Main")):ne?n("button",{type:"button",class:"dl-linkbtn",click:fe=>{fe.stopPropagation(),c=[U.host,...c.filter(z=>z!==U.host)],B(),w()}},_("Make main")):U.cloudflare?n("span",{class:"dl-pill warn"},"Cloudflare"):U.kind==="ip"?n("span",{class:"dl-pill"},"IP"):U.here&&U.cert?n("span",{class:"dl-pill ok"},_("Recommended")):""])}),n("div",{class:"dl-addr-opt other"},[n("i",{class:"dl-addr-check"},v("plus")),l,H(_("Add"),()=>{let U=l.value.trim().toLowerCase();if(!U)return;let ne=At(U);if(ne.bad){F(ne.text,"warning");return}g(U),c.includes(U)||(c=[...c,U]),l.value="",B(),w()})])]);l.addEventListener("keydown",U=>{U.key==="Enter"&&(U.preventDefault(),l.nextElementSibling?.click())});let P=n("div",{class:"dl-links"}),R=()=>{},w=()=>{R();let U=Number(i.value)||o.portal_port;dom.content(P,c.map((ne,he)=>{let fe=d(ne),z=fe?U+1:U,$=`${fe?"http":"https"}://${ne}${z===(fe?80:443)?"":`:${z}`}/`;return n("div",{class:"dl-link-row"},[n("span",{class:`dl-link-ic ${fe?"warn":"ok"}`},v(fe?"alert":"lock")),n("span",{class:"dl-mono dl-link-url"},[$,n("b",{},"kamiro-telosu-bavine")]),he===0?n("span",{class:"dl-pill info"},_("Main")):fe?n("span",{class:"dl-pill warn"},"HTTP"):""])}))};B(),w(),i.addEventListener("input",()=>w());let k={portal:_("Portal running"),portal_dns:_("Points here"),portal_reply:_("Answers reach visitors"),portal_http:_("Plain HTTP"),cert:_("Certificate")},y=t.d.needs??{https:[],acme:[],home:[]},O=U=>{if(!o.portal_enabled)return n("div",{hidden:!0});if(!U)return ye("check",_("Ready to share"),_("The portal’s checks from Health"),[n("p",{class:"dl-muted dl-loading"},_("Running checks…"))]);let ne=U.filter(E=>E.status!=="skip");if(!ne.length)return n("div",{hidden:!0});let{bad:he,worst:fe}=vi(U),z=n("div",{class:"dl-ready-details",hidden:!0},ne.map(E=>n("div",{class:`dl-ready-item ${E.status}`},[v(E.status==="ok"?"check":"alert"),n("span",{class:"dl-stack"},[n("span",{},E.title),n("span",{class:"dl-sub"},E.detail)])]))),$=n("div",{class:"dl-stack gap8"},[n("div",{class:`dl-ready-sum ${fe}`},[v(fe==="ok"?"check":"alert"),n("span",{class:"dl-stack"},[n("b",{},fe==="ok"?G(ne.length,"All %s check passed","All %s checks passed"):m(N_(ne.length,"%s of %s check passed","%s of %s checks passed"),V(ne.length-he.length),V(ne.length))),he.length?n("span",{class:"dl-sub"},he.map(E=>E.detail).join(" ")):n("span",{class:"dl-sub"},_("Links will open for the people you send them to."))]),n("button",{type:"button",class:"dl-linkbtn",click:E=>{z.hidden=!z.hidden,E.currentTarget.textContent=z.hidden?_("Details"):_("Hide")}},_("Details"))]),n("div",{class:"dl-chips-row"},ne.map(E=>n("span",{class:`dl-check-chip ${E.status}`,title:E.detail},[v(E.status==="ok"?"check":"alert"),k[E.id]??E.title]))),z]);return ye("check",_("Ready to share"),_("The portal’s checks from Health"),[$])},b=U=>{if(!o.portal_enabled||!U&&!y.https.length)return n("span",{hidden:!0});if(y.https.length)return n("span",{class:"dl-pill bad"},_("Can’t start"));let{worst:ne}=vi(U);return n("span",{class:`dl-pill ${ne==="ok"?"ok":ne==="error"?"bad":"warn"}`},ne==="error"?_("Needs attention"):_("Ready"))},f=O(t.portal?.checks??null),T=b(t.portal?.checks??null);t.portalFill=U=>{p=!0,M(U.candidates),B(),w();let ne=O(U.checks);f.replaceWith(ne),f=ne;let he=b(U.checks);T.replaceWith(he),T=he};let C=s&&!s.self_signed&&s.expires?Ie(s.expires):"",A=Ce(_("Listening port"),i,()=>Ln(i.value.trim()===""?o.portal_port:Number(i.value),t.d.tcp_taken??[],c.some(d)));R=A.refresh;let K=Ce(_("Unknown links"),a,()=>Is(a.value)),Y=!!(e.portal_cert&&e.portal_key),Q=s?Y?_("Your files"):s.self_signed?_("Self-signed"):"Let’s Encrypt":_("Portal is off"),j=()=>{let U=ue(e.portal_cert,{placeholder:"/etc/ssl/…/fullchain.crt"}),ne=ue(e.portal_key,{placeholder:"/etc/ssl/…/key"});ae(_("Use your own certificate"),[n("p",{class:"dl-muted"},_("Paths on the router. Leave both empty to pick a certificate automatically.")),ge(_("Certificate file"),U),ge(_("Key file"),ne)],[de()," ",H(_("Save"),()=>{le(),t.save({portal_cert:U.value.trim(),portal_key:ne.value.trim()},_("Certificate saved"),"portal")},"positive")])},Z=(U,ne,he,fe,z,$)=>lt(U,ne,he,fe,H($,()=>cn(z,y[z],()=>t.reload("portal")),"positive")),te=y.https.length?Z("lock","bad",_("HTTPS isn’t available on this router"),m(_("The portal needs %s. It can’t start without them."),new Intl.ListFormat(ie(),{type:"conjunction"}).format(y.https)),"https",_("Install")):"",me=y.acme.length&&(!s||s.self_signed)?Z("lock","",_("Free certificate from Let’s Encrypt"),e.portal_host?m(_("ACME isn’t installed. With it the router gets a certificate for %s and browsers stop warning."),e.portal_host):_("ACME isn’t installed. With it the router gets a certificate and browsers stop warning."),"acme",_("Install ACME")):"",ke=[n("div",{class:"dl-row"},[v("lock"),n("span",{class:"dl-row-main dl-stack"},[n("b",{},[Q,C?n("span",{class:"dl-faint"},` · ${m(_("until %s"),C)}`):""]),n("span",{class:"dl-sub dl-ellipsis",title:s?.path??""},s?s.self_signed?_("Made by the router: browsers warn until a certificate covers the address."):`${Y?_("Your files"):_("Found automatically")} · ${s.path}`:_("Turn the portal on to see its certificate."))])]),n("div",{class:"dl-row"},[v("file"),n("span",{class:"dl-row-main dl-stack"},[n("b",{},_("Your own files")),n("span",{class:"dl-sub"},Y?`${e.portal_cert} · ${e.portal_key}`:_("Not set: the certificate is picked automatically."))]),Y?H(_("Reset"),()=>t.save({portal_cert:"",portal_key:""},_("Automatic certificate"),"portal"),"negative"):"",H(Y?_("Change"):_("Use files"),j)]),me];return Ue("portal",_("Personal portal"),[n("span",{class:"dl-muted"},_("A page where each person adds and manages their devices with their personal link.")),te?n("div",{class:"dl-list"},[te]):"",ye("network",_("Port"),_("How the portal listens (80 and 443 stay free)"),[A]),ye("edit",_("Appearance"),_("What people see"),[K]),ye("link",_("Addresses"),_("Pick one or more; the first is the main link"),[h,n("div",{class:"dl-stack gap8"},[P,n("span",{class:"dl-sub"},_("Example code; each person gets their own three words."))])]),ye("lock",_("Certificate"),_("Used for HTTPS links"),ke),f],[n("span"),H(_("Save"),()=>{let U=Be([A,K]);if(U){F(U,"warning");return}return t.save({portal_enabled:De(r)?"1":"0",portal_host:c[0]??"",portal_alt:c.slice(1),portal_port:i.value,portal_redirect:a.value.trim()},_("Saved"),"portal")},"positive")],"",[T,r])}function xi(t){let e=t.d.settings,o=t.d.effective,s=ue(e.default_device_limit,{placeholder:"3",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),r=be(o.hostnames,_("Device hostnames")),i=ue(e.domain,{placeholder:"lan",class:"cbi-input-text dl-w-port"}),a=ue(e.home_dns_fallback==="none"?"":e.home_dns_fallback||o.home_dns_fallback||"",{placeholder:_("None"),inputmode:"decimal",class:"cbi-input-text dl-w-ip dl-mono"}),l=Ce(_("Devices per person"),s,()=>{if(!s.value.trim())return{text:_("The default, 3. Pre-filled when you add someone."),bad:!1};let p=En(s.value);return p.bad?p:{text:_("Pre-filled when you add someone."),bad:!1}}),d=Ce(_("Device hostnames"),i,()=>Os(i.value),n("div",{class:"dl-hostport"},[r,n("span",{class:"dl-faint dl-mono"},"phone.myata."),i])),c=Ce(_("Fallback DNS"),a,()=>{let p=Bs(a.value);return p.bad?p:{text:m(_("For Home-only devices using home names: %s"),p.text),bad:!1}});return Ue("defaults",_("New people"),[l,d,c],[n("span"),H(_("Save"),()=>{let p=Be([l,d,c]);if(p){F(p,"warning");return}return t.save({default_device_limit:s.value,hostnames:De(r)?"1":"0",domain:i.value,home_dns_fallback:a.value},_("Saved"),"defaults")},"positive")])}function wi(t){let e=t.d.effective,o=be(e.geo_enabled,_("Locations")),s=n("select",{class:"cbi-input-select"},[n("option",{value:"ipwho.is",selected:e.geo_provider!=="ipapi.co"?"selected":null},m(_("%s (fallback: %s)"),"ipwho.is","ipapi.co")),n("option",{value:"ipapi.co",selected:e.geo_provider==="ipapi.co"?"selected":null},m(_("%s (fallback: %s)"),"ipapi.co","ipwho.is"))]);return Ue("map",_("Map & locations"),[n("div",{class:"dl-setrow head"},[n("span",{class:"dl-muted"},_("Show where people connect from on the Overview and person pages, at city level.")),o]),ge(_("Provider"),s)],[n("span",{class:"dl-sub"},_("The router sends each new client IP to the provider once and caches the city. Map tiles load in your browser from CARTO; people never see the map.")),H(_("Save"),()=>t.save({geo_enabled:De(o)?"1":"0",geo_provider:s.value},_("Saved"),"map"),"positive")])}var cd=()=>[["app","Dawnline"],["amneziawg","AmneziaWG"],["packages",_("System packages")]];function yi(t){let e=t.d.effective.updates,o=be(e.check,_("Check automatically"),M=>g(M,De(r))),s=Qe([["6h",_("Every 6 h")],["12h",_("Every 12 h")],["1d",_("Daily")],["7d",_("Weekly")]],e.interval,_("How often")),r=be(e.auto,_("Install automatically"),M=>g(De(o),M)),i=ue(e.time,{placeholder:"04:00",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono","aria-label":_("Time")}),a=Qe([["scheduled",_("At a set time")],["immediate",_("As soon as found")]],e.mode,_("When"),M=>i.hidden=M!=="scheduled");i.hidden=e.mode!=="scheduled";let l=yn(cd(),e.targets,_("Components")),d=be(e.keep,_("Keep the previous version")),c=be(e.mirrors,_("GitHub mirrors")),p=ge(_("How often"),s),u=[ge(_("When"),n("div",{class:"dl-hostport"},[a,i]),_("A set time keeps tunnel restarts out of the evening; the run happens within an hour of it.")),ge(_("Components"),l.node,_("AmneziaWG is off by default: a new kernel module restarts every tunnel."))],g=(M,x)=>{p.hidden=!M;for(let h of u)h.hidden=!x};return g(e.check,e.auto),Ue("updates",_("Updates"),[n("span",{class:"dl-muted"},_("How Dawnline keeps its components current. Every Dawnline update makes a backup of the settings first.")),ge(_("Check automatically"),o,_("Looks for new versions in the background; Components shows what it found and the service log names it.")),p,ge(_("Install automatically"),r,_("Downloads and installs new versions of the components below.")),...u,ge(_("Keep the previous version"),d,_("Saves the replaced Dawnline or AmneziaWG package on flash, so Roll back works without internet. Under 1 MB.")),ge(_("GitHub mirrors"),c,_("When GitHub is unreachable, download through mirrors. Checksums are still verified."))],[n("span",{class:"dl-sub"},_("Run a check or an update by hand in Components.")),H(_("Save"),()=>{if(a.value==="scheduled"){let M=js(i.value);if(M.bad){F(m(_("Time: %s"),M.text),"warning");return}}return t.save({update_check:De(o)?"1":"0",update_interval:s.value,update_auto:De(r)?"1":"0",update_mode:a.value,update_time:i.value.trim(),update_targets:l.value(),update_keep:De(d)?"1":"0",update_mirrors:De(c)?"1":"0"},_("Saved"),"updates")},"positive")])}function ki(t){let e=t.d.logs,o=e.policy,s=Qe([["7",G(7,"%s day","%s days")],["30",G(30,"%s day","%s days")],["90",G(90,"%s day","%s days")],["365",G(1,"%s year","%s years")],["0",_("No limit","retention")]],String(o.keep_days),_("Keep activity")),r=Qe([["500",V(500)],["2000",V(2e3)],["5000",V(5e3)],["20000",V(2e4)]],String(o.max),_("Maximum events")),i=Qe([["10min",_("Every 10 min")],["hourly",_("Hourly")],["off",_("Memory only")]],o.persist,_("Save to flash")),a=Qe([["31",G(1,"%s month","%s months")],["62",G(2,"%s month","%s months")],["180",G(6,"%s month","%s months")],["365",G(1,"%s year","%s years")],["730",G(2,"%s year","%s years")]],String(o.usage_days),_("Daily traffic")),l=Qe([["12",G(1,"%s year","%s years")],["24",G(2,"%s year","%s years")],["60",G(5,"%s year","%s years")],["120",G(10,"%s year","%s years")]],String(o.usage_months),_("Monthly traffic")),d=yn(Rt.map(g=>[g,n("span",{title:Fs(g)},[Ke(g)," ",n("span",{class:"dl-faint dl-opt-note"},V(e.by_category[g]??0))])]),o.categories,_("Record")),c=e.oldest?Ie(new Date(e.oldest*1e3)):"",p=(g,M,x,h)=>n("div",{class:"dl-row"},[v(g),n("span",{class:"dl-row-main dl-stack"},[n("b",{},M),n("span",{class:"dl-sub"},x)]),...h]),u=g=>H(g.toUpperCase(),async()=>{let[M,x]=await Promise.all([N.status(1),N.events(2e4)]);Xe(M,x.events,g)},"neutral",{title:m(_("Download the log as %s"),g.toUpperCase())});return Ue("logs",_("Logs & history"),[n("p",{class:"dl-muted"},Pn(o)),ge(_("Keep activity"),s,_("Older events are removed automatically.")),ge(_("Maximum size"),r,_("Newest events are kept when the log is full.")),ge(_("Record"),d.node,_("Switched-off categories are not logged from now on.")),ge(_("Save to flash"),i,_("The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot.")),ge(_("Daily traffic"),a,_("Per-day history behind the charts.")),ge(_("Monthly traffic"),l,_("Per-month totals; data limits use the current month.")),n("h4",{class:"dl-setsub"},_("Stored data")),n("div",{class:"dl-list"},[p("activity",_("Activity log"),e.events?`${m(_("%s since %s"),G(e.events,"%s event","%s events"),c)} · ${o.persist==="off"?m(_("%s in memory"),$t(e.log_ram)):m(_("%s in memory, %s on flash"),$t(e.log_ram),$t(e.log_flash))}`:_("Empty"),[u("csv"),u("json"),H(_("Clear"),()=>dt(_("Clear activity"),_("Removes events from the log on the router."),{},()=>t.reload("logs")),"negative")]),p("chart",_("Traffic history"),e.usage_days?`${m(_("%s since %s"),G(e.usage_days,"%s day","%s days"),Ie(e.usage_since))} · ${m(_("%s on flash"),$t(e.usage_flash))}`:_("Empty"),[H(_("Reset"),()=>It("all","","",()=>setTimeout(()=>t.reload("logs"),300)),"negative")]),p("pin",_("Location cache"),`${G(t.d.geo_cached,"%s address","%s addresses")} · ${m(_("%s on flash"),$t(e.geo_flash))}`,[H(_("Clear"),async()=>{await q(()=>N.geoClear(),_("Location cache cleared"))&&await t.reload("logs")},"negative")])])],[n("span",{class:"dl-sub"},_("Clear one person or device from their own page.")),H(_("Save"),()=>t.save({log_keep_days:s.value,log_max:r.value,log_persist:i.value,usage_keep_days:a.value,usage_keep_months:l.value,log_category:d.value()},_("Saved"),"logs"),"positive")])}function pd(t){return{manual:_("Manual"),auto:_("Nightly"),"pre-restore":_("Before restore"),"pre-import":_("Before import"),"pre-delete":_("Before removing a server"),"pre-update":_("Before update")}[t]??t}var _i=3;function es(t){let e=new Date(t*1e3),o=e.toLocaleTimeString(ie(),{hour:"2-digit",minute:"2-digit"}),s=Math.round((new Date(new Date().toDateString()).getTime()-new Date(e.toDateString()).getTime())/864e5);return s===0?m(_("Today, %s"),o):s===1?m(_("Yesterday, %s"),o):`${e.toLocaleDateString(ie(),{day:"numeric",month:"short"})}, ${o}`}async function ud(t){let e=await q(()=>N.backupRead(t.name));if(!e)return;let o=atob(e.data),s=new Uint8Array(o.length);for(let i=0;iud(t),"neutral","dl-icon-only"),Pe("more",_("More"),o=>Te(o.currentTarget,[{label:_("Restore"),icon:v("reset"),run:async()=>{await pe(_("Restore this backup?"),m(_("Everything returns to %s. The current state is backed up first."),es(t.created)),_("Restore"),!0)&&await q(()=>N.backupRestore(t.name),_("Restored"))&&e(!0)}},{label:_("Delete"),icon:v("trash"),danger:!0,run:async()=>{await pe(_("Delete this backup?"),m(_("The backup from %s is removed from the router."),es(t.created)),_("Delete"),!0)&&await q(()=>N.backupDelete(t.name),_("Backup deleted"))&&e()}}]),"neutral","dl-icon-only")])])}function Li(t,e){let o=t.slice(0,_i).map(d=>Ci(d,e)),s=t.slice(_i),r=t.length?n("div",{class:"dl-list"},[...o,s.length?n("details",{class:"dl-bk-older"},[n("summary",{},[v("chevron"),G(s.length,"%s older backup","%s older backups")]),...s.map(d=>Ci(d,e))]):""]):n("div",{class:"dl-list"},[n("div",{class:"dl-row dl-muted"},_("No backups yet."))]),i=H(_("Restore from file"),async()=>{let d=await mo(".tar.gz,.tgz,application/gzip","base64");if(!d)return;await pe(_("Restore from file?"),m(_("Replace the current Dawnline configuration with %s? The current state is backed up first."),d.name),_("Restore"),!0)&&await q(()=>N.backupUpload(d.data),_("Restored"))&&e(!0)}),a=H(_("Export JSON"),async()=>{let d=await q(()=>N.exportJson());d&&Ae(`dawnline-export-${new Date().toISOString().slice(0,10)}.json`,JSON.stringify(d,null,2),"application/json")}),l=H(_("Import JSON"),async()=>{let d=await mo(".json,application/json","text");if(!d)return;let c;try{c=JSON.parse(d.data)}catch{F(_("Not a JSON file."),"error");return}await pe(_("Import?"),_("This replaces the whole Dawnline configuration on this router. The current state is backed up first."),_("Import"),!0)&&await q(()=>N.importJson(c),_("Imported"))&&e(!0)});return n("section",{class:"dl-setsec",id:"dl-set-backups"},[n("div",{class:"dl-setsec-body"},[n("div",{class:"dl-setsec-head"},[n("div",{class:"dl-stack"},[n("h3",{},_("Backups")),n("span",{class:"dl-sub"},_("Nightly when something changed, and before every restore, import or update. The last 10 are kept."))]),n("span",{class:"dl-spacer"}),H([v("plus")," ",_("Back up now")],async()=>{await q(()=>N.backupCreate(),_("Backup created"))&&e()},"positive")]),r]),n("div",{class:"dl-setsec-foot"},[n("span",{class:"dl-sub"},_("Backups contain private keys: keep downloads safe. JSON moves everything except usage history to another router.")),n("span",{class:"dl-row-actions dl-bk-actions"},[i,a,l])])])}var ts="remove";function md(){let t=ue("",{placeholder:ts}),e=H(_("Remove Dawnline"),async()=>{await q(()=>N.uninstall(t.value.trim()),_("Dawnline removed"))&&(le(),setTimeout(()=>location.reload(),800))},"negative",{disabled:!0});t.addEventListener("input",()=>{e.disabled=t.value.trim()!==ts}),ae(_("Remove Dawnline?"),[n("p",{},m(_("Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “%s” to confirm."),ts)),t],[de()," ",e])}function Mi(){return Ue("danger",_("Remove Dawnline from this router"),[n("p",{class:"dl-muted"},_("Deletes the tunnel, firewall rules, access table and hostnames Dawnline created, and stops the service. People and keys are kept in a backup."))],[n("span"),H(_("Remove"),()=>md(),"negative")],"danger")}var Qn=class{constructor(){this.root=n("div",{class:"dl-settings-main"});this.backups=[];this.portal=null;this.portalSeq=0;this.cards={}}load(){return N.settingsGet()}render(e){this.d=e,this.cards={portal:gt(()=>bi(this)),defaults:gt(()=>xi(this)),map:gt(()=>wi(this)),updates:gt(()=>yi(this)),logs:gt(()=>ki(this)),backups:gt(()=>Li(this.backups,r=>this.loadBackups(r))),danger:gt(()=>Mi())};let o=["portal","defaults","map","updates","logs","backups","danger"];dom.content(this.root,o.map(r=>this.cards[r].el)),this.loadBackups().then(()=>{new URLSearchParams(location.search).get("section")==="backups"&&document.getElementById("dl-set-backups")?.scrollIntoView({block:"start"})}),this.loadPortal();let s=new URLSearchParams(location.search).get("section");return s&&s!=="backups"&&requestAnimationFrame(()=>document.getElementById(`dl-set-${s}`)?.scrollIntoView({block:"start"})),n("div",{},[n("div",{class:"dl-pagehead"},[n("h2",{class:"dl-h1"},_("Settings"))]),this.root])}async save(e,o,s){let r=await q(()=>N.settingsUpdate(e),o);r&&(this.d=r,this.cards[s].refresh(),s==="portal"&&this.loadPortal())}async loadPortal(){let e=++this.portalSeq,o=await N.portalInfo().catch(()=>null);e===this.portalSeq&&(this.portal=o??this.portal??{candidates:[],checks:[]},this.portalFill?.(this.portal))}async loadBackups(e=!1){e&&await this.reload();let o=await N.backupList().catch(()=>null);o&&(this.backups=o.backups,this.cards.backups?.refresh())}async reload(e){let o=await N.settingsGet().catch(()=>null);if(o){if(this.d=o,e)this.cards[e].refresh();else for(let s of Object.values(this.cards))s.refresh();(!e||e==="portal")&&this.loadPortal()}}};function Ei(t,e=!1){return t&&(e?/^https?:\/\//i:/^https:\/\//i).test(t)?t:null}function Ti(t){let e=[],o=l=>{let d=[],c=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\((https?:\/\/[^)\s]+)\))|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?])/g,p=0;for(let u;u=c.exec(l);)u.index>p&&d.push(l.slice(p,u.index)),u[1]?d.push(n("code",{},u[1].slice(1,-1))):u[2]?d.push(n("b",{},u[2].slice(2,-2))):u[3]?d.push(n("a",{href:u[4],target:"_blank",rel:"noopener"},u[3].replace(/^\[|\]\(.*$/g,""))):u[5]&&d.push(n("a",{href:u[5],target:"_blank",rel:"noopener"},u[5].replace(/^https?:\/\/(github\.com\/)?/,""))),p=u.index+u[0].length;return p{r.length&&e.push(n("p",{},o(r.join(" ")))),r=[],s=null};for(let l of t.replace(/\r/g,"").split(` +`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(e.push(n("pre",{},i.join(` +`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){a(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(a(),e.push(n("h5",{},o(c[2])))):p?(r.length&&a(),s||(s=n("ul",{}),e.push(s)),s.appendChild(n("li",{},o(p[1])))):d.trim()?(s&&(s=null),r.push(d.trim())):a()}return i&&e.push(n("pre",{},i.join(` +`))),a(),e}function Si(t){let e=[],o=!1;for(let s of t.replace(/\r/g,"").split(` `)){let r=/^#{1,6}\s+(.*)$/.exec(s);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(s)&&(o=!1);o||e.push(s)}return e.join(` `).replace(/\n{3,}/g,` -`).trim()}async function an(n,e,o,s){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},_("Loading release notes…"))),a=t("div",{class:"dl-op-head"}),i="";de(o,[a,r],[N([g("copy")," ",_("Copy")],()=>xe(i,_("Release notes copied")))," ",ue(_("Close"))],"wide");try{let l=await H.updatesNotes(n,e,s??"");i=Zr(l.body||"");let d=Yr(l.url);dom.content(a,[l.published?t("span",{class:"dl-pill"},Be(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},_("Pre-release")):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},[_("On GitHub")," ",g("open")]):""]),dom.content(r,i.trim()?Jr(i):t("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,t("p",{class:"dl-muted"},Ce(l)))}}function Ll(n){let e={"6h":_("checks every 6 h"),"12h":_("checks every 12 h"),"1d":_("checks daily"),"7d":_("checks weekly")};return e[n]??e["1d"]}var jo=n=>n?Be(n):"";function Ml(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Xr(n,e){let o=n.st,s=o.policy,r=o.kept?.app,a=e?.update&&e.tag?e.tag:o.version,i=v=>()=>an("app",v,m(_("What’s new in Dawnline %s"),v.replace(/^v/,""))),l=e?.tag&&(e.update||e.status==="latest")?El(n,e.tag,e.update?o.version:""):null,d=e?.tag??a,c=s.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[s.interval]??24)*3600:0,p=(v,M)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},v),t("span",{class:"dl-comp-side-v"},M)]),u=[{label:_("What’s new"),ic:"file",run:i(a)},{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:m(_("Reinstall %s"),o.version),ic:"reset",warn:!0,run:()=>n.op("app:reinstall",_("Reinstalling Dawnline"),o.version)},r?{label:m(_("Roll back to %s"),r.version),ic:"archive",warn:!0,run:async()=>{await me(m(_("Roll back to Dawnline %s?"),r.version),m(_("The copy kept on the router replaces %s. A backup of the settings is made first."),o.version),_("Roll back"))&&n.op("app:rollback",_("Rolling back Dawnline"),o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},g("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app",_("Checking Dawnline"),o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},m(_("release %s"),e.latest)):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?m(_("released %s"),jo(e.published)):"":e?.status==="dev"?_("ahead of the latest release"):e?[_("latest release"),e.published?m(_("released %s"),jo(e.published)):""].filter(Boolean).join(" · "):_("not checked yet"))])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(v=>t("li",{},v))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:i(d)},W(l.total-l.items.length,"+%s more in What’s new","+%s more in What’s new")):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[N(_("Update now"),()=>n.op("app",_("Updating Dawnline"),o.version),"positive",{disabled:n.busy}),N(_("What’s new"),i(a))]):"",Sl(n),Tl(n)]),t("div",{class:"dl-comp-hero-side"},[p(_("Source"),[g("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p(_("Auto-update"),[s.auto?Se("ok",_("On")):Se("",_("Off")),t("span",{class:"dl-muted"},s.auto?s.mode==="immediate"?_("as soon as found"):m(s.interval==="7d"?_("weekly at %s"):_("daily at %s"),s.time):s.check?Ll(s.interval):_("checks off"))]),p(_("Last check"),o.check?[pe(o.check.time,o.now),c>o.now?t("span",{class:"dl-faint"},`· ${m(_("next in %s"),ot(c-o.now))}`):""]:[_("Never")]),p(_("Rollback"),r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},_("kept on flash"))]:[t("span",{class:"dl-muted"},s.keep?_("Kept after the next update"):_("Off"))])])])}function El(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let s=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(a,i)=>i??"").trim();return(async()=>{let a=((await H.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(` -`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);a.length||(a=(await H.updatesChanges(o,e).catch(()=>null))?.items??[]);let i={items:a.slice(0,3).map(l=>Ml(s(l))),total:a.length};n.notes.set(e,i),i.items.length&&n.root.isConnected&&n.paint()})(),null}function Wn(n){return n==="ru"?_("Russian translation"):n}function Tl(n){let e=(n.st.translations??[]).includes("ru"),o=ye(e,Wn("ru"),r=>{n.op(r?"app:lang:ru":"app:nolang",r?_("Adding the Russian translation"):_("Removing the Russian translation"),n.st.version)});o.disabled=n.busy;let s=t("details",{class:"dl-params dl-comp-fold",open:n.langOpen?"open":null},[t("summary",{},[g("chevron"),t("span",{},_("Translation")),t("span",{class:"dl-sub"},e?_("Russian"):_("English only"))]),t("div",{class:"dl-params-body"},[t("div",{class:"dl-list"},[t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},Wn("ru")),t("span",{class:"dl-sub"},_("LuCI pages for Dawnline"))]),t("span",{class:"dl-comp-bact"},o)])])])]);return s.addEventListener("toggle",()=>n.langOpen=s.open),s}function Sl(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[g("chevron"),t("span",{},_("Versions")),t("span",{class:"dl-sub"},_("install any release"))]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&Gn(n,e)}),n.versOpen&&Gn(n,e),o}async function Gn(n,e){let o=he("",{placeholder:_("Tag, e.g. 0.3.1"),class:"cbi-input-text dl-mono","aria-label":_("Release tag")}),s=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return q(_("Enter a release tag like 0.3.1"),"warning");Qr(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),s(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,N(_("Install"),()=>s(o.value),"neutral",{disabled:n.busy})]),a=n.versPage,i=p=>{n.versPage=Math.max(1,n.versPage+p),Gn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:a<=1?"disabled":null,click:()=>i(-1)},_("← Newer")),t("span",{class:"dl-faint"},m(_("Page %s"),a)),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>i(1)},_("Older →"))]),d=n.versCache.get(a);if(!d){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},_("Loading versions…"))]);try{d=(await H.updatesReleases(a)).releases}catch(p){if(a!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},m(_("Failed to load versions: %s"),Ce(p))),N(_("Try again"),()=>Gn(n,e))]),l(!1)]);return}if(n.versCache.set(a,d),a!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[r,t("p",{class:"dl-muted"},a>1?_("No more versions."):_("No versions found.")),l(!1)]);let c=n.st.version;dom.content(e,[r,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},jo(p.published)),p.prerelease?Se("warn",_("Pre-release")):"",t("span",{class:"dl-comp-ic"},Pe("file",_("What’s new"),()=>an("app",p.tag,m(_("What’s new in Dawnline %s"),u)))),u===c?Se("ok",_("Installed")):N(_("Install"),()=>Qr(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Qr(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await me(m(_("Install Dawnline %s?"),o),m(_("It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong."),n.st.version),_("Install"))||n.op(`app@${e}`,m(_("Installing Dawnline %s"),o),n.st.version)}function ea(n,e){let o=n.st,s=o.kept?.amneziawg,r=e?.sources??{},a=Object.keys(r),i=e?.current??null,l=i?r[i]:void 0,d=!!e?.ru,c=o.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];i&&p&&u.push({label:_("Reinstall this build"),warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${i}${d?":ru":""}`,_("Reinstalling AmneziaWG"),p)}),s&&u.push({label:m(_("Roll back to %s"),s.version),ic:"archive",warn:!0,run:async()=>{await me(m(_("Roll back AmneziaWG to %s?"),s.version),_("The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds."),_("Roll back"))&&n.op("amneziawg:rollback",_("Rolling back AmneziaWG"),p??void 0)}});let v=[e?.release?{label:_("What’s new"),ic:"file",run:()=>an("amneziawg",e.release,m(_("What’s new in the %s build"),l?.label??"AmneziaWG"),i??"slava")}:null,{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((w,f,T)=>w!==null||f>0&&T[f-1]!==null),M=o.tunnels??[],x=M.length?M.length===1?m(_("Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations."),M[0]):m(N_(M.length,"Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.","Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations."),V(M.length),M.join(", ")):_("Switching takes a few seconds. Devices keep their configurations."),h=M.length>1?m(_("%s and %s"),M.slice(0,-1).join(", "),M[M.length-1]):M[0],S=M.length?m(_("Switching restarts %s for a few seconds."),h):_("Switching takes a few seconds."),z=async w=>{let f=r[w];await me(p?m(_("Switch to AmneziaWG %s?"),f.gen):m(_("Install AmneziaWG %s?"),f.gen),[m(_("The %s build, %s."),f.label,f.version),x,f.gen==="3.1"?_("Devices need AmneziaVPN 3.1 or newer."):""].filter(Boolean).join(" "),p?_("Switch"):_("Install"))&&n.op(`amneziawg:${w}${d?":ru":""}`,p?m(_("Switching to AmneziaWG %s"),f.gen):_("Installing AmneziaWG"),p??void 0)},E=w=>{let f=r[w],T=i===w&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":_("every app")}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??_("none yet")),t("span",{class:"dl-comp-bact"},T?Se("ok",_("Active","build")):f.version?N(p?_("Switch"):_("Install"),()=>z(w),p?"neutral":"positive",{disabled:n.busy}):Se("",_("No build")))])},$=a.map(w=>r[w]?.newer?m(_("%s moves to %s with OpenWrt %s."),r[w].label,r[w].newer.gen,r[w].newer.tag.replace(/^v/,"")):"").filter(Boolean),b=ye(d,_("Russian translation"),w=>{i&&n.op(`amneziawg:${i}${w?":ru":""}`,w?_("Adding the Russian translation"):_("Removing the Russian translation"),p??void 0)});b.disabled=!i||!p||n.busy;let k=n.awgOpen??!p,y=t("details",{class:"dl-params dl-comp-fold",open:k?"open":null},[t("summary",{},[g("chevron"),t("span",{},_("Build and translation"))]),t("div",{class:"dl-params-body"},[t("div",{class:"dl-list"},[...a.length?a.map(E):[t("div",{class:"dl-row"},t("span",{class:"dl-sub"},_("Check for updates to see the builds for this router.")))],t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},_("Russian translation")),t("span",{class:"dl-sub"},_("LuCI pages for AmneziaWG"))]),t("span",{class:"dl-comp-bact"},b)])]),p&&a.length||$.length?t("div",{class:`dl-comp-status ${p&&a.length?"warn":"acc"}`},[g(p&&a.length?"alert":"download"),t("span",{},[p&&a.length?t("b",{},S):"",...$.map(w=>` ${w}`)])]):""])]);y.addEventListener("toggle",()=>n.awgOpen=y.open);let I=[];return e?.update&&p&&i?I.push(N(m(_("Update to %s"),e.latest),()=>n.op(`amneziawg:${i}${d?":ru":""}`,_("Updating AmneziaWG"),p),"neutral",{disabled:n.busy})):I.push((e||c.length)&&!p?Se("warn",_("Not installed")):n.state("amneziawg",e,e?.latest??"")),I.push(n.round(()=>n.op("check:amneziawg",_("Checking AmneziaWG"),p??void 0),v)),[n.row("shield","AmneziaWG",[p?`${p}${e?.release?` · ${m(_("%s build"),e.release)}`:""}`:c.length?m(_("missing %s"),c.join(", ")):e?_("not installed"):_("version not checked")],I),t("div",{class:"dl-comp-foldwrap"},y)]}function Pl(){return[{title:_("Home-like link"),sub:_("Policy routing and the veth pair"),pkgs:["ip-full","kmod-veth"],feature:"home"},{title:_("HTTPS for the portal"),sub:_("OpenSSL for uhttpd"),pkgs:["libustream-openssl","openssl-util"],feature:"https"},{title:_("Certificates (ACME)"),sub:_("Let’s Encrypt certificate for the portal"),pkgs:["acme","acme-acmesh-dnsapi"],feature:"acme",optional:!0}]}var Uo={home:"network",https:"lock",acme:"file"};function ta(n,e){let o=n.st,s=e?.pkgs??{},r=Pl().filter(c=>c.feature==="home"?o.home:o.portal),a=async(c,p,u=c)=>{await me(m(_("Update %s?"),p),m(_("%s from the OpenWrt feeds. Services that use them restart for a moment."),u.join(", ")),_("Update"))&&n.op(`pkgs:${c.join(",")}`,m(_("Updating %s"),p))},i=[{label:_("Check system packages"),ic:"refresh",run:()=>n.op("check:packages",_("Checking system packages"))},{label:_("Open the OpenWrt package list"),ic:"globe",run:()=>window.open("https://openwrt.org/packages/start","_blank","noopener")}],l=0;return{rows:r.map(c=>{let p=c.pkgs.filter(h=>s[h]?.installed),u=[...new Set(p.flatMap(h=>[...s[h]?.latest?[h]:[],...s[h]?.with??[]]))],v=o.needs?.[c.feature]??c.pkgs.filter(h=>!s[h]?.installed),M=p.find(h=>s[h]?.latest),x=p.map(h=>`${h} ${s[h]?.installed??""}`).join(", ");return v.length?n.row(Uo[c.feature],c.title,[c.optional?_("not installed"):m(_("missing %s"),v.join(", "))],[N(_("Install"),()=>n.op(`pkgs:${v.join(",")}`,m(_("Installing %s"),c.title)),c.optional?"neutral":"positive",{disabled:n.busy}),t("span",{class:"dl-comp-ic"},n.more(i))]):e&&u.length?(l++,n.row(Uo[c.feature],c.title,M?[`${s[M].installed} → ${s[M].latest}`,u.length>1?` · +${u.length-1}`:""]:[u.join(", ")],[N(_("Update"),()=>a(p.filter(h=>s[h]?.latest||s[h]?.with?.length),c.title,u),"neutral",{disabled:n.busy}),t("span",{class:"dl-comp-ic"},n.more(i))])):n.row(Uo[c.feature],c.title,[x||c.sub],[n.state("pkgs",e,""),t("span",{class:"dl-comp-ic"},n.more(i))])}),updates:l,total:r.length}}function $l(n){return n==="app"?"Dawnline":n==="amneziawg"?"AmneziaWG":n==="pkgs"?_("System packages"):_("Components")}function Dl(n){let e=/^(\d+) system packages?$/.exec(n)?.[1];return e?W(Number(e),"%s system package","%s system packages"):n}function na(n){let e=n.st,o=r=>{let a=mt(r.component??"app"),i=t("b",{},$l(a)),l="ok",d="check",c;if(r.kind==="found")l="accent",d="download",c=oe(r.auto?_("%s found by the automatic check"):_("%s found by a check"),t("b",{},(r.items??[]).map(Dl).join(", ")));else if(r.state==="failed")l="bad",d="x",c=[...oe(r.kind==="install"?_("%s update failed"):_("%s check failed"),i),r.error?` · ${r.error}`:""];else if(/^app:(lang:|nolang$)/.test(r.component??"")){let p=/^app:lang:(.+)$/.exec(r.component??"")?.[1];c=p?oe(_("%s added by you"),t("b",{},Wn(p))):[_("Translation removed by you")]}else{let p=r.from&&r.to&&r.from!==r.to?`${r.from} → ${r.to}`:r.to??"";c=[...p?oe(r.auto?_("%s %s automatically"):_("%s %s by you"),i,p):oe(r.auto?_("%s updated automatically"):_("%s updated by you"),i),r.took?` · ${ot(r.took)}`:""]}return t("div",{class:"dl-row"},[t("span",{class:`dl-ev-tile ev ${l}`},g(d)),t("span",{class:"dl-row-main"},c),t("span",{class:"dl-faint dl-nowrap",title:new Date(r.ts*1e3).toLocaleString(le())},pe(r.ts,e.now))])},s=e.history??[];return t("section",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Activity")),t("span",{class:"dl-spacer"}),t("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},_("All in Log →"))]),s.length?t("div",{},s.slice(0,8).map(o)):t("p",{class:"dl-sub dl-comp-empty"},_("Updates, and checks that found something, show up here."))])}var qn=class{constructor(){this.root=t("div",{class:"dl-upd"});this.following=null;this.versOpen=!1;this.versPage=1;this.versCache=new Map;this.notes=new Map;this.awgOpen=null;this.langOpen=!1}load(){return H.updatesStatus()}render(e){return this.st=e,this.paint(),e.job?.state==="running"&&this.follow(e.job),poll.add(async()=>{if(!this.root.isConnected)return;let o=await H.updatesStatus().catch(()=>null);if(!o)return;let s=this.st;this.st=o,o.job?.state==="running"&&this.following!=="starting"&&o.job.id!==this.following&&this.follow(o.job),(o.job?.id!==s.job?.id||o.job?.state!==s.job?.state||o.job?.phase!==s.job?.phase||o.check?.time!==s.check?.time)&&this.paint()},5),this.root}get busy(){return this.st.job?.state==="running"}async refresh(e){this.st=e??await H.updatesStatus().catch(()=>null)??this.st,this.paint()}async op(e,o,s){if(this.busy||this.following==="starting"){q(_("Another component action is already running"),"warning");return}this.following="starting",this.paint();let r=mt(e),a=await on(e,{title:o,version:s,onJob:i=>this.following=i.id,onDone:i=>this.refresh(i),onUpdate:i=>{let l=i.check?.components??{};r==="amneziawg"&&l.amneziawg?.current?this.op(`amneziawg:${l.amneziawg.current}${l.amneziawg.ru?":ru":""}`,_("Updating AmneziaWG"),l.amneziawg.installed??void 0):this.op("app",_("Updating Dawnline"),this.st.version)}});this.following==="starting"&&(this.following=a?.id??null),this.refresh()}async follow(e){this.following=e.id;let o={app:[_("Checking Dawnline"),_("Automatic update: Dawnline"),_("Updating Dawnline")],amneziawg:[_("Checking AmneziaWG"),_("Automatic update: AmneziaWG"),_("Updating AmneziaWG")],pkgs:[_("Checking system packages"),_("Automatic update: system packages"),_("Updating system packages")],all:[_("Checking components"),_("Automatic update: components"),_("Updating components")]};await on(null,{title:(o[Hn(e)]??o.all)[e.action==="check"?0:e.auto?1:2],onDone:s=>this.refresh(s)},e)}paint(){let e=this.st,o=e.check?.components??{},s=e.firmware,r=ta(this,o.packages),a=(e.needs?.awg??[]).length>0,l=(!a&&o.amneziawg?.update&&o.amneziawg.installed?1:0)+r.updates;dom.content(this.root,[t("div",{class:"dl-pagehead"},[t("div",{class:"dl-stack"},[t("h2",{class:"dl-h1"},_("Components")),t("span",{class:"dl-faint"},[s?.version?`OpenWrt ${s.version} · ${s.target}`:"",e.check?m(_("checked %s"),pe(e.check.time,e.now)):_("not checked yet")].filter(Boolean).join(" · "))]),t("div",{class:"dl-row-actions"},[t("a",{class:"cbi-button cbi-button-neutral dl-icon-btn",href:`${L.url("admin/network/dawnline/settings")}?section=updates`},[g("edit")," ",_("Settings")]),N([g("refresh")," ",_("Check all")],()=>this.op("check",_("Checking all components")),"neutral",{disabled:this.busy})])]),Xr(this,o.app),t("div",{class:"dl-comp-cols"},[t("section",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Components")),t("span",{class:"dl-spacer"}),t("span",{class:"dl-faint dl-comp-count"},a?l?`${_("AmneziaWG not installed")} · ${W(l,"%s update","%s updates")}`:_("AmneziaWG not installed"):!o.amneziawg&&!o.packages?"":l?m(N_(l,"%s of %s needs an update","%s of %s need an update"),V(l),V(1+r.total)):_("Everything is up to date"))]),t("div",{},[...ea(this,o.amneziawg),...r.rows])]),na(this)])])}state(e,o,s){let r=this.st.job;if(r?.state==="running"){let a=l=>l==="packages"?"pkgs":l,i=r.action==="check"?[a(r.component||"all")]:(r.component??"").split(" ").map(l=>a(mt(l)));if(i.includes(e)||i.includes("all"))return t("button",{type:"button",class:"dl-pill info dl-comp-run",title:_("Show progress"),click:()=>this.follow(r)},[r.action==="check"?_("Checking…"):_("Updating…")])}return o?o.error?Se("warn",_("Check failed"),o.error):o.update?Se("info",_("Update available")):o.status==="dev"?Se("info",_("Newer than release"),m(_("The latest release is %s"),s)):Se("ok",_("Up to date")):Se("",_("Not checked"))}more(e){let o=N([g("more")],()=>Te(o,e.filter((s,r,a)=>s!==null||r>0&&rs?{label:s.label,icon:g(s.ic),warn:s.warn,run:s.run}:null)),"neutral",{title:_("More"),"aria-label":_("More")});return o}round(e,o,s=!1){let r=this.busy?" is-busy":"",a;return s?a=N([g("refresh")," ",_("Check")],e,"neutral",{class:`cbi-button cbi-button-neutral dl-comp-check${r}`,"aria-label":_("Check for updates")}):(a=Pe("refresh",_("Check for updates"),e,"neutral",r.trim()),a.removeAttribute("title"),a.setAttribute("aria-label",_("Check for updates")),we(a,()=>[_("Check for updates")])),t("span",{class:"dl-comp-ic"},[a,this.more(o)])}row(e,o,s,r){return t("div",{class:"dl-row"},[t("span",{class:"dl-group-ic"},g(e)),t("span",{class:"dl-row-main dl-stack"},[t("b",{},o),t("span",{class:"dl-mono dl-faint dl-comp-sub"},s)]),...r])}};var oa=(n,e)=>t("div",{class:"cbi-value"},[t("label",{class:"cbi-value-title"},n),t("div",{class:"cbi-value-field"},e)]);function sa(n){let e=n.st.servers.find(o=>o.id===n.p.server)?.name??_("Home");tn(n.p,e)}async function ra(n){let e=n.p,o=e.code_set??0,s=e.devices.filter(l=>l.created_by==="portal"&&l.created>=o),r=s.map(l=>t("input",{type:"checkbox",id:`dl-rm-${l.id}`,checked:"checked","data-id":l.id})),a=[t("p",{},_("The old link stops working right away."))];s.length&&a.push(t("p",{},_("Devices added through the old link keep working until they are removed. Remove them too:")),t("div",{class:"dl-checklist"},s.map((l,d)=>t("label",{for:`dl-rm-${l.id}`},[r[d],` ${l.name}`]))));let i=async()=>{let l=r.filter(c=>c.checked).map(c=>c.dataset.id),d=await K(()=>H.personRegen(e.id,l),l.length?W(l.length,"New link created, %s device removed","New link created, %s devices removed"):_("New link created"));d&&(ce(),l.length&&await n.refresh(),d.link&&await xe(d.link,_("New link copied")))};de(_("Create a new link?"),a,[ue()," ",N(_("Create new link"),i,"negative")])}function Wo(n){let e=t("textarea",{class:"cbi-input-textarea dl-note-input",rows:3,maxlength:500,placeholder:_("Only you see this")},n.p.note??"");de(_("Note"),[e],[ue()," ",N(_("Save"),async()=>{ce(),await n.patch({note:e.value.trim()},e.value.trim()?_("Note saved"):_("Note removed"))},"positive")]),setTimeout(()=>e.focus(),50)}function aa(n){let e=n.p,o=t("select",{class:"cbi-input-select"},[t("option",{value:"pause",selected:e.expire_action==="pause"?"selected":null},_("Pause access")),t("option",{value:"notify",selected:e.expire_action==="notify"?"selected":null},_("Keep access")),t("option",{value:"remove",selected:e.expire_action==="remove"?"selected":null},_("Remove their devices"))]),s=t("select",{class:"cbi-input-select"},[0,1,3,7,14].map(r=>t("option",{value:r,selected:e.expire_warn===r?"selected":null},r?W(r,"%s day before","%s days before"):_("Don’t warn"))));de(_("When access ends"),[oa(_("Then"),o),t("div",{class:"cbi-value"},[t("label",{class:"cbi-value-title"},_("Warn")),t("div",{class:"cbi-value-field"},[s,t("div",{class:"cbi-value-description"},_("Shown in their portal and on the Overview."))])])],[ue()," ",N(_("Save"),async()=>{ce(),await n.patch({expire_action:o.value,expire_warn:s.value},_("Saved"))},"positive")])}function ia(n){let e=t("input",{type:"text",class:"cbi-input-text",value:n.p.name,maxlength:48}),o=Me(_("Name","person"),e,()=>Ne(e.value,[],_("Shown in their portal and apps.")));de(_("Rename"),[o],[ue()," ",N(_("Save"),async()=>{let s=o.help();if(s.bad){q(s.text,"warning");return}await n.patch({name:e.value.trim()},_("Renamed"))&&ce()},"positive")]),setTimeout(()=>e.select(),50)}function la(n){let e=n.p,o=n.st.servers.filter(a=>a.id!==e.server),s=t("select",{class:"cbi-input-select"},o.map(a=>t("option",{value:a.id},`${a.name} · ${a.endpoint||_("no address")}:${a.port}`))),r=e.devices.length;de(m(_("Move %s to another server"),e.name),[oa(_("Server"),s),t("p",{class:"dl-muted"},r?W(r,"%s device gets a new address and stops connecting until it imports its configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.","%s devices get new addresses and stop connecting until they import their configuration again (from the personal link or from you). Circles and home networks of the old server are left behind."):_("They have no devices yet: nothing else changes."))],[ue()," ",N(_("Move"),async()=>{await n.patch({server:s.value},m(_("Moved to %s"),o.find(a=>a.id===s.value)?.name??_("the server")))&&(ce(),r&&q(_("Devices are marked “Update config” until they import again."),"info",6e3))},"positive")])}async function da(n){let e=n.p;await me(m(_("Delete %s?"),e.name),W(e.devices.length,"%s device is disconnected immediately and the personal link stops working.","All %s devices are disconnected immediately and the personal link stops working."),_("Delete"),!0)&&await K(()=>H.personDelete(e.id),_("Deleted"))&&(location.href=Bt(e.server))}function ca(n){let e=n.p,o=n.st,s=e.online?_("online now"):e.last_seen?m(_("last seen %s"),pe(e.last_seen,o.now)):_("never connected"),r=e.created?m(_("Added %s","date"),$e(Fe(new Date(e.created*1e3)))):"",a=e.has_link??o.settings.portal_enabled,i=[{label:_("Rename"),icon:g("edit"),run:()=>ia(n)},{label:e.note?_("Edit note"):_("Add note"),icon:g("file"),run:()=>Wo(n)},...o.servers.length>1?[{label:_("Move to server…"),icon:g("server"),run:()=>la(n)}]:[],...a?[null,{label:_("Invite card"),icon:g("qr"),run:()=>sa(n)},{label:_("New link"),icon:g("key"),run:()=>ra(n)}]:[],null,...e.paused?[]:[{label:_("Pause"),icon:g("pause"),warn:!0,run:()=>n.patch({paused:!0},_("Paused"))}],{label:_("Delete"),icon:g("trash"),danger:!0,run:()=>da(n)}];return t("div",{class:"dl-person-head"},[t("div",{class:"dl-pagehead"},[t("div",{class:"dl-person-id"},[t("span",{class:`dl-avatar lg${e.online?" online":""}`},Oe(e.name)),t("div",{class:"dl-stack"},[t("div",{class:"dl-title-row"},[t("h2",{class:"dl-h1"},e.name),ts(e)]),t("span",{class:"dl-faint",title:r},`${m(N_(e.device_limit,"%s of %s device","%s of %s devices"),e.devices.length,e.device_limit)} · ${s}`)])]),t("div",{class:"dl-pcard-actions"},[e.paused?N([g("play"),` ${_("Resume")}`],()=>n.patch({paused:!1},_("Resumed")),"add"):"",a?Pe("link",_("Copy link"),()=>$n(e.id),"neutral","dl-icon-only"):"",Pe("more",_("More"),l=>Te(l.currentTarget,i),"neutral","dl-icon-only")])]),e.note?t("button",{type:"button",class:"dl-pnote",title:_("Edit note"),click:()=>Wo(n)},[g("file"),t("span",{},e.note)]):""])}function pa(n){let e=n.p,o=n.series[n.series.length-1];return t("div",{class:`dl-person-live${e.online?"":" solo"}`},[e.online?In(e.rate??[],n.st.now,o?[o.rx,o.tx]:[0,0]):"",Bn(n.series,m(_("%s this month"),re(e.month[0]+e.month[1])))])}async function Al(n,e){let o=await K(()=>H.deviceConfig(e.id));o&&de(m(_("Set up %s"),e.name),[await n.core.connectBlock(o,"qr")],[ue(_("Close"))])}async function Nl(n,e){let o=await K(()=>H.deviceConfig(e.id));if(!o)return;if(!o.has_private_key){q(_("This device made its own keys in the browser; its configuration only exists there."),"warning");return}let s=n.core.file.make(o);Ae(s.name,s.text,"application/octet-stream")}function ua(n){let e=n.p,o=n.st.now,s=d=>Ye(e,d,n.deviceOpts()),r=d=>c=>{c.target.closest("button:not(.dl-dcard-title), a")||s(d)},a=d=>N([g("more")],c=>mr(c.currentTarget,e,d,n.deviceOpts()),"neutral",{title:_("QR, file, key, rename, new keys, remove"),class:"cbi-button cbi-button-neutral dl-icon-only"}),i=cn(e.devices).map(d=>{let c=t("div",{class:"dl-dcard-head"},[t("span",{class:"dl-dcard-ic"},g(d.kind)),t("button",{type:"button",class:"dl-dcard-title",click:()=>s(d)},[t("b",{},d.name),pn(d,o,void 0,e),d.config_stale?t("span",{class:"dl-pill warn dl-stale"},_("Update config")):""]),a(d)]),p=t("div",{class:"dl-dcard-trend"},[t("div",{class:"dl-stack"},[t("b",{},re(d.month[0]+d.month[1])),t("span",{class:"dl-sub"},_("this month"))]),Hr(n.devSeries[d.id]??[])]);return t("article",{class:`dl-dcard clickable${d.online?" online":""}${d.disabled?" off":""}`,click:r(d)},[c,d.handshake?p:d.disabled?t("div",{class:"dl-sub"},`${at(d.kind)} · ${m(d.created_by==="portal"?_("created %s in the portal."):_("created %s by you."),pe(d.created,o))}`):t("div",{class:"dl-chips-row"},[t("button",{type:"button",class:"dl-chipbtn",click:()=>Al(n,d)},[g("qr"),_("Show QR")]),t("button",{type:"button",class:"dl-chipbtn",click:()=>Nl(n,d)},[g("download"),_("Config")])])])}),l=e.devices.length>=e.device_limit;return i.push(t("button",{type:"button",class:"dl-dslot add",click:()=>ct(e,n.deviceOpts())},[t("span",{class:"dl-dslot-ic"},g("plus")),t("span",{class:"dl-stack"},[t("b",{},_("Add device")),t("span",{class:"dl-sub"},l?`${_("Over the limit")} · ${m(_("%s of %s"),e.devices.length,e.device_limit)}`:m(_("%s of %s"),e.devices.length,e.device_limit))])])),t("section",{class:"dl-devsec"},[t("div",{class:"dl-panel-head"},[t("h3",{},_("Devices")),t("span",{class:"dl-sub"},m(_("%s online"),V(e.online)))]),t("div",{class:"dl-dgrid"},i)])}function ma(n){let e=n.p,o=Qe([["device",_("Device’s own DNS")],["home",_("Home names")]],e.dns_mode,{label:"DNS",cls:"sm",optimistic:!1,onChange:r=>n.patch({dns_mode:r},r==="home"?_("Home names on - devices need their configuration again"):_("Device DNS - devices need their configuration again"))}),s=n.st.settings.home_dns_fallback;return t("div",{class:"dl-stack gap4 dl-dnspick"},[t("div",{class:"dl-row-actions"},[t("span",{class:"dl-sub"},"DNS"),o]),t("span",{class:"dl-sub"},e.dns_mode==="home"?s?oe(_("Names like %s work. Internet names are resolved at home, so they depend on the tunnel (%s takes over when it is down)."),t("span",{class:"dl-mono"},`nas.${n.st.settings.domain}`),t("span",{class:"dl-mono"},s)):oe(_("Names like %s work. Internet names are resolved at home, so they depend on the tunnel - with no fallback set, they stop when it is down."),t("span",{class:"dl-mono"},`nas.${n.st.settings.domain}`)):_("Internet keeps working exactly as without the VPN. Reach home devices by IP address."))])}function ha(n){let e=n.p,s=n.st.servers.find(a=>a.id===e.server)?.home??[];if(s.length<2)return"";let r=new Set(e.home_nets?.length?e.home_nets:s.map(a=>a.dev));return t("div",{class:"dl-stack gap4"},[t("div",{class:"dl-chips-row"},s.map(a=>Vt(a.dev,r.has(a.dev),()=>{let i=new Set(r);if(i.delete(a.dev)||i.add(a.dev),!i.size)return q(_("Keep at least one network, or choose Internet only."),"warning",5e3);let l=i.size===s.length?[]:[...i];n.patch({home_nets:l},l.length?m(_("%s reaches %s"),e.name,l.join(", ")):m(_("%s reaches every home network"),e.name))},{title:a.nets.join(", ")}))),t("span",{class:"dl-sub"},e.home_nets?.length?m(_("Home networks %s reaches. Networks added to the server later stay out."),e.name):m(_("Home networks %s reaches: all of them. Untick one to keep %s out of it."),e.name,e.name))])}function fa(n){let e=new Set(n.p.services??[]);return t("div",{class:"dl-stack gap4"},[t("div",{class:"dl-chips-row"},n.st.services.map(o=>Vt(o.name,e.has(o.id),()=>{let s=new Set(e);s.delete(o.id)||s.add(o.id),n.patch({services:[...s]},s.size?_("Home services updated"):_("Whole home network"))},{title:`${o.address}${o.ports.length?` · ${o.ports.join(", ")}`:""}`}))),t("span",{class:"dl-sub"},e.size?_("Only the selected services at home."):_("Whole home network. Pick services to narrow it down."))])}function ga(n){let e=n.p,o=n.st;if(o.servers.find(c=>c.id===e.server)?.mesh!=="circles"||!ut(e))return"";let r=o.circles.filter(c=>c.server===e.server),a=r.find(c=>c.id===e.circle),i=a?o.people.filter(c=>c.id!==e.id&&c.circle===a.id&&ut(c)).map(c=>c.name):[],l=t("button",{type:"button",class:"dl-chipbtn",click:()=>Te(l,[...r.map(c=>({label:c.name,icon:$o(c),run:()=>c.id!==e.circle&&n.patch({circle:c.id},m(_("%s is in %s"),e.name,c.name))})),e.circle?{label:_("No circle"),icon:g("x"),run:()=>n.patch({circle:""},m(_("%s is in no circle"),e.name))}:null,{label:_("New circle"),icon:g("plus"),run:()=>An(o,e.server,null,()=>n.refresh())}])},_("Change")),d=a?o.people.filter(c=>c.circle===a.id&&ut(c)):[e];return t("div",{class:"dl-tile2"},[t("div",{class:"dl-tile2-label"},[t("span",{},_("Devices see each other")),l]),t("div",{class:"dl-tile2-row"},[t("span",{class:"dl-tile2-value"},a?a.name:_("No circle")),t("span",{class:"dl-avstack",title:d.map(c=>c.name).join(", ")},d.slice(0,5).map(c=>t("span",{class:"dl-avatar sm"},Oe(c.name))))]),t("span",{class:"dl-sub"},a?i.length?[e.name,...i].join(", "):m(_("Nobody else in %s yet"),a.name):m(_("Only %s's own devices"),e.name))])}function va(n){let e=n.p,o=n.st.now,s=t("div",{class:"dl-slots"});for(let i=0;i=e.device_limit,c=t("i",{class:d?"over":l?"used":""});we(c,()=>[t("div",{class:"dl-tip-title"},l?`${l.name}${d?` · ${_("over the limit")}`:""}`:_("Free slot")),t("div",{class:"dl-muted"},l?l.online?_("Connected"):l.handshake?m(_("Last seen %s"),pe(l.handshake,o)):_("Not set up yet"):_("They can add a device here"))]),s.appendChild(c)}let r=Math.max(1,e.devices.length),a=t("button",{type:"button","aria-label":_("Allow fewer devices"),disabled:e.device_limit<=r?"disabled":null,click:()=>n.patch({device_limit:String(e.device_limit-1)})},"−");return e.device_limit<=r&&e.devices.length>1&&we(a,()=>[t("div",{class:"dl-tip-title"},W(e.devices.length,"%s device in use","%s devices in use")),t("div",{class:"dl-muted"},_("Remove a device first to lower the limit"))]),t("div",{class:"dl-tile2"},[t("div",{class:"dl-tile2-label"},_("Devices")),t("div",{class:"dl-tile2-row"},[t("span",{class:"dl-tile2-value"},[String(e.devices.length),t("span",{class:"dl-faint"},` / ${e.device_limit}`)]),t("div",{class:"dl-stepper"},[a,t("button",{type:"button","aria-label":_("Allow more devices"),disabled:e.device_limit>=32?"disabled":null,click:()=>n.patch({device_limit:String(e.device_limit+1)})},"+")])]),s])}function Hl(n){return{internet:_("Browse the internet through your router. No access to devices at home, and home cannot reach theirs."),lan:_("Reach devices at home, and home reaches theirs. Internet stays on their own connection."),both:_("Home devices and the internet, all through your router. Home reaches their devices too.")}[n]}var ba=/^([01]\d|2[0-3]):[0-5]\d$/;function zl(n){let e=n.p,o=n.today,s=st(e.expires,o),r=t("input",{type:"date",class:"dl-date-hidden",value:e.expires,tabindex:"-1","aria-hidden":"true"});r.addEventListener("change",()=>r.value&&n.patch({expires:r.value},m(_("Access until %s"),$e(r.value))));let a=(c,p)=>{let u=Qo(e.expires&&(s??-1)>=0?e.expires:"",c,p,o);n.patch({expires:u},m(_("Access until %s"),$e(u)))},i=[["week",1,_("+1 week")],["month",1,_("+1 month")],["month",3,_("+3 months")],["year",1,_("+1 year")]].map(([c,p,u])=>t("button",{type:"button",class:"dl-chipbtn",click:()=>a(c,p)},u)),l=t("span",{class:"dl-datechip"},[t("button",{type:"button",class:"dl-chipbtn",click:()=>{r.focus({preventScroll:!0});try{r.showPicker()}catch{}}},[g("calendar"),e.expires?$e(e.expires):_("Date")]),r]),d={pause:_("pause access"),notify:_("keep access"),remove:_("remove their devices")}[e.expire_action];return t("div",{class:"dl-tile2"},[t("div",{class:"dl-tile2-label"},[t("span",{},_("Access ends")),e.expires?t("span",{class:s!=null&&s<0?"dl-bad":rt(e,s)?"dl-warn":"dl-ok"},s!=null&&s<0?_("ended"):W(s??0,"%s day left","%s days left")):t("span",{class:"dl-faint"},_("no end date"))]),t("div",{class:"dl-chips-row"},[...i,l,e.expires?t("button",{type:"button",class:"dl-chipbtn",click:()=>n.patch({expires:""},_("No end date"))},_("No end")):""]),t("div",{class:"dl-tile2-foot"},[t("span",{class:"dl-muted"},e.expire_warn?m(N_(e.expire_warn,"When it ends: %s, warn %s day before","When it ends: %s, warn %s days before"),d,V(e.expire_warn)):m(_("When it ends: %s"),d)),t("a",{href:"#",click:c=>{c.preventDefault(),aa(n)}},_("Change"))])])}function Rl(n){let e=n.p,o=e.quota_used||e.month[0]+e.month[1],s=e.quota_limit?Math.min(100,e.quota_used/e.quota_limit*100):0,r=t("div",{class:`dl-meter${s>=100?" bad":s>=90?" warn":""}`},[t("i"),e.quota_limit?t("span",{class:"mark",title:_("Alert at 90%")}):""]);r.firstChild.style.width=`${s}%`,e.quota_limit&&we(r,()=>[t("div",{class:"dl-tip-title"},m(_("%s%% used"),V(s,1))),t("div",{class:"dl-muted"},`${m(_("%s of %s"),re(e.quota_used),re(e.quota_limit))} · ${m(_("%s left"),re(Math.max(0,e.quota_limit-e.quota_used)))}`),t("div",{class:"dl-faint"},_("Alert at 90%"))]);let a=Qe([["month",_("Monthly")],["total",_("Total")]],e.quota_period,{label:_("Data limit period"),cls:"sm",optimistic:!1,onChange:l=>n.patch({quota_period:l})}),i=[10,50,100].map(l=>t("button",{type:"button",class:`dl-chipbtn${e.quota_gb===l?" on":""}`,click:()=>n.patch({quota_gb:String(l)},m(_("Data limit %s GB"),V(l)))},`${V(l)} ${_("GB")}`));return i.push(t("button",{type:"button",class:`dl-chipbtn${e.quota_gb?"":" on"}`,click:()=>n.patch({quota_gb:""},_("No data limit"))},_("Unlimited"))),i.push(t("button",{type:"button",class:"dl-chipbtn",click:()=>{let l=t("input",{type:"number",class:"cbi-input-text dl-w-port",min:0,step:"any",value:e.quota_gb?String(e.quota_gb):""}),d=Me(_("Data limit (GB)"),l,()=>bn(l.value,e.quota_period==="month"));de(_("Data limit"),[d],[ue()," ",N(_("Save"),async()=>{let c=d.help();if(c.bad){q(c.text,"warning");return}let p=l.value.trim();await n.patch({quota_gb:p},p&&Number(p)>0?m(_("Data limit %s GB"),V(Number(p))):_("No data limit"))&&ce()},"positive")]),setTimeout(()=>l.select(),50)}},_("Custom"))),t("div",{class:"dl-tile2"},[t("div",{class:"dl-tile2-label"},[t("span",{},_("Data")),a]),t("div",{class:"dl-tile2-row"},[t("span",{class:"dl-tile2-value"},[re(o),e.quota_limit?t("span",{class:"dl-faint"},` ${m(_("of %s"),re(e.quota_limit))}`):t("span",{class:"dl-faint"},` · ${_("no limit")}`)]),e.quota_period==="month"?t("span",{class:"dl-sub"},_("resets on the 1st")):""]),e.quota_limit?r:"",t("div",{class:"dl-chips-row"},i),e.quota_gb&&e.quota_period==="month"?t("div",{class:"dl-tile2-foot"},[t("span",{class:"dl-muted"},e.bonus_gb?m(_("Includes +%s GB extra this month"),V(e.bonus_gb)):_("Need a little more this month?")),t("a",{href:"#",click:l=>{l.preventDefault(),n.patch({bonus_gb:String((e.bonus_gb||0)+10)},_("+10 GB this month"))}},_("+10 GB this month"))]):"",t("div",{class:"dl-tile2-foot"},[t("span",{class:"dl-muted"},m(_("%s in total"),re(e.total[0]+e.total[1]))),t("button",{type:"button",class:"dl-linkbtn danger",click:()=>zt("person",e.id,e.name,()=>setTimeout(()=>n.refresh(),300))},_("Reset usage"))])])}function Il(n){let e=n.p,o=!!e.hours,[s,r]=(e.hours||"07:00-23:00").split("-"),a=t("input",{type:"time",class:"cbi-input-text",value:s,"aria-label":_("From")}),i=t("input",{type:"time",class:"cbi-input-text",value:r,"aria-label":_("To")}),l=t("div",{class:"dl-tile2-row"},[a,t("span",{class:"dl-faint"},_("to","time range")),i]),d=()=>{let v=`${a.value}-${i.value}`;if(v!==e.hours){if(!ba.test(a.value)||!ba.test(i.value))return q(_("Enter both times, like 07:00 and 23:00."),"warning");if(a.value===i.value)return q(_("The start and the end must differ."),"warning");n.patch({hours:v},m(_("Allowed %s–%s"),a.value,i.value))}};l.addEventListener("focusout",v=>{l.contains(v.relatedTarget)||d()});for(let v of[a,i])v.addEventListener("keydown",M=>{M.key==="Enter"&&(M.preventDefault(),d())});let c=t("button",{type:"button",role:"switch","aria-checked":o?"true":"false",class:`dl-switch${o?" on":""}`,"aria-label":_("Limit hours"),click:()=>{if(o)return n.patch({hours:""},_("Any time"));c.classList.add("on"),c.setAttribute("aria-checked","true"),p.textContent=_("Set the hours, then press Enter"),u.appendChild(l),a.focus()}},t("i")),p=t("span",{},o?m(_("%s – %s (router time)"),s,r):_("Any time")),u=t("div",{class:"dl-tile2"},[t("div",{class:"dl-tile2-row"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-tile2-label"},_("Allowed hours")),p]),c]),o?l:""]);return u}function xa(n){let e=n.p,o=Qe(["internet","lan","both"].map(s=>[s,[g(s==="internet"?"globe":s==="lan"?"home":"shield"),s==="internet"?_("Internet"):s==="lan"?_("Home"):_("Both")]]),e.access,{label:_("Access"),cls:"wide",optimistic:!1,onChange:s=>n.patch({access:s},m(_("Access: %s"),vt(s)))});return t("section",{class:"dl-devsec","aria-label":_("Access and limits")},[t("div",{class:"dl-panel-head"},[t("h3",{},_("Access & limits"))]),t("div",{class:"dl-panel"},[t("div",{class:"dl-stack gap8"},[t("span",{class:"dl-tile2-label"},_("Can reach")),o,t("span",{class:"dl-sub"},Hl(e.access)),e.access==="lan"&&n.st.services.length?fa(n):"",ut(e)?ha(n):"",e.access==="lan"?ma(n):""]),t("div",{class:"dl-tiles2"},[va(n),ga(n),zl(n),Rl(n),Il(n)])])])}function Bl(n){let e=n.st,o=t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Locations")),t("span",{class:"dl-spacer"}),e.geo.enabled?It("30d",r=>n.map?.setRange(r),!1):"",N(_("Hide"),()=>{n.mapOpen=!1,n.map?.destroy(),n.map=null,n.paintPlaces()},"neutral")]);if(!e.geo.enabled)return t("div",{class:"dl-panel flush"},[o,t("div",{class:"dl-map-off"},oe(_("Locations are off. %s."),t("a",{href:L.url("admin/network/dawnline/settings")},_("Turn them on in Settings"))))]);let s=new dt({openPerson:()=>{},openDevice:(r,a)=>{let i=n.p.devices.find(l=>l.id===a);i&&Ye(n.p,i,n.deviceOpts())}},"30d",280);return n.map=s,requestAnimationFrame(()=>s.mount(n.mapData())),t("div",{class:"dl-panel flush"},[o,s.el])}function wa(n){let e=n.st;if(!e.geo.enabled)return t("div",{class:"dl-places"},[g("pin"),t("div",{class:"dl-stack"},[t("span",{},_("Locations are off")),t("span",{class:"dl-sub"},_("City-level, from the client IP"))]),t("span",{class:"dl-spacer"}),t("a",{class:"cbi-button cbi-button-neutral",href:L.url("admin/network/dawnline/settings")},_("Turn on"))]);if(n.mapOpen)return n.map&&n.parts.places.contains(n.map.el)?null:Bl(n);let o=e.now-30*86400,s=e.geo.points.filter(i=>i.person===n.p.id&&i.ts>=o).sort((i,l)=>l.ts-i.ts),r=[...new Set(s.map(i=>i.city||i.country).filter(Boolean))],a=s[0];return t("div",{class:"dl-places"},[g("pin"),t("div",{class:"dl-stack"},[t("span",{},a?a.city||a.country:_("No locations yet")),t("span",{class:"dl-sub"},a?[W(r.length,"%s place in 30 days","%s places in 30 days"),a.org].filter(Boolean).join(" · "):_("Shown after a device connects"))]),t("span",{class:"dl-spacer"}),s.length?N(_("Show map"),()=>{n.mapOpen=!0,n.paintPlaces()},"neutral"):""])}function ya(n){let e=n.p,o=n.st,s=n.events.filter(l=>l.person===e.id),r=[],a=[...s].reverse();for(let l=0;l1){let u=p.querySelector(".dl-row-main");dom.content(u,[...zo(o,d).slice(0,3),t("span",{class:"dl-muted"},W(c,"%s time","%s times"))]),u.title=a.slice(l,l+c).map(v=>v.detail??"").join(` -`)}r.push(p),l+=c-1}let i=N([g("more")],()=>Te(i,[{label:_("Export CSV"),icon:g("download"),run:()=>Ze(o,s,"csv",e.id)},{label:_("Export JSON"),icon:g("download"),run:()=>Ze(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:g("trash"),danger:!0,run:()=>lt(m(_("Clear %s's activity"),e.name),m(_("Removes events about %s and their devices."),e.name),{person:e.id},()=>n.refresh())}]),"neutral",{title:_("Export or clear"),class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Activity")),t("span",{class:"dl-sub"},s.length>10?m(_("latest 10 of %s"),V(s.length)):""),t("span",{class:"dl-spacer"}),i]),r.length?r:t("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var Fn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,s,r]=await Promise.all([H.status(30),e?H.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?H.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:s?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(i=>i.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},_("Person not found")),t("p",{},_("They may have been removed.")),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},_("Back to Servers"))]);this.p=o;for(let i of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[i]=t("div",{});this.parts.devices.className="dl-person-devices";let s=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),a=r.get("device")&&o.devices.find(i=>i.id===r.get("device"));return a?setTimeout(()=>Ye(this.p,a,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ct(this.p,this.deviceOpts()),50),this.poller=pt({fetch:i=>{let l=i||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>s.isConnected,apply:(i,l)=>this.apply(i,l)}),s}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let s=this.st.people.find(r=>r.id===this.id);if(!s){o||(location.href=Bt(this.p?.server));return}this.p=s,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var a;this.poller?.claim();let s=await K(()=>H.personUpdate(this.p.id,e),o);if(!s)return!1;this.poller?.claim();let r=this.st.people.findIndex(i=>i.id===this.p.id);return(a=s.person).rate??(a.rate=this.p.rate),r>=0&&(this.st.people[r]=s.person),this.p=s.person,this.paint(),!0}get today(){return We(this.series.length?this.series:this.st.series)}get core(){return Rt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":_("Breadcrumb")},[t("a",{href:Bt(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),t("span",{},"/"),t("a",{href:Bt(e.server)},_("People")),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){De(this.parts.crumbs,this.crumbs(),e),De(this.parts.head,ca(this),e),De(this.parts.traffic,pa(this),e),De(this.parts.devices,ua(this),e),De(this.parts.limits,xa(this),e),this.paintPlaces(e),De(this.parts.activity,ya(this),e)}paintPlaces(e=!1){let o=wa(this);o&&De(this.parts.places,o,e&&!this.mapOpen)}};var Ol={ok:"check",warn:"alert",error:"x",skip:"pause"},Kn=class{constructor(e,o,s,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=s,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,s)}async run(e){let o=e?await On(e):await H.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},_("Checks"))]),t("p",{class:"dl-muted dl-loading"},_("Running checks…"))]);return}let o=e.filter(i=>i.status==="error").length,s=e.filter(i=>i.status==="warn").length;dom.content(this.summary,o?xt("error",W(o,"%s problem needs attention.","%s problems need attention.")):s?xt("warn",W(s,"%s warning.","%s warnings.")):xt("ok",_("All checks passed.")));let r=new Map;for(let i of this.sl.watchdog.repairs)r.set(i.id,Math.max(r.get(i.id)??0,i.ts));let a=()=>this.run();dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},_("Checks")),t("span",{class:"dl-spacer"}),N(_("Run again"),a)]),t("ul",{class:"dl-checks"},e.map(i=>t("li",{},[t("span",{class:`dl-check-icon ${i.status}`},g(Ol[i.status])),t("div",{class:"dl-check-body"},[t("div",{class:"dl-check-title"},i.title),t("div",{class:"dl-check-detail"},i.detail),r.has(i.id)?t("div",{class:"dl-check-repaired"},m(_("Repaired by the watchdog at %s"),Wt(r.get(i.id)))):""]),Ro(i,l=>void this.run(l),a)])))])}paintLive(e,o){this.sl=e,this.events=o;let s=e.watchdog,r=s.beat!=null&&s.now-s.beat>180,a=s.repairs.filter(d=>s.now-d.ts<86400),i=a[a.length-1],l=ye(s.enabled,_("Watchdog repairs"),async d=>{await K(()=>H.settingsUpdate({watchdog:d?"1":"0"}),d?_("Watchdog on"):_("Watchdog off"))||ho(l,!d);let p=await H.serviceLog().catch(()=>null);p&&this.paintLive(p,this.events)});dom.content(this.wdEl,t("div",{class:"dl-panel dl-wd"},[t("div",{class:"dl-wd-head"},[t("span",{class:`dl-wd-tile${s.enabled?"":" off"}`},g("shield")),t("div",{class:"dl-stack"},[t("span",{class:"dl-wd-title"},_("Watchdog")),t("span",{class:"dl-sub"},s.enabled?_("Every minute it checks the tunnels and services and repairs what it can on its own."):_("Off: problems are only written to the log. Nothing is repaired on its own."))]),t("span",{class:"dl-spacer"}),l]),t("div",{class:"dl-wd-foot"},[t("div",{class:"dl-wd-chips"},s.targets.map(d=>t("span",{class:`dl-check-chip${d.ok?"":" error"}`,title:d.ok?_("OK"):d.tries?`${_("Not working")} · ${W(d.tries,"%s repair","%s repairs")}`:_("Not working")},[g(d.ok?"check":"x"),d.name]))),t("span",{class:`dl-sub${r?" dl-warn-text":""}`},r?m(_("The agent has not checked in for %s min; cron restarts it after 5."),V(Math.round((s.now-s.beat)/60))):[s.last?m(_("Looked %s"),pe(s.last,s.now)):_("Starts within a minute")," · ",a.length?m(N_(a.length,"%s repair today, last %s at %s","%s repairs today, last %s at %s"),V(a.length),i.name,Wt(i.ts)):_("no repairs today")])])])),this.paintRecent()}paintRecent(){let e=(this.sl.watchdog.now||Date.now()/1e3)-604800,o=[...this.events.map(r=>({ts:r.ts,ev:r})),...this.sl.log.map(r=>({ts:r.ts,sys:r}))].filter(r=>r.ts>=e&&xn(r)).sort((r,a)=>a.ts-r.ts),s=t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Recent problems")),t("span",{class:"dl-spacer"}),o.length?t("a",{href:"#",click:r=>(r.preventDefault(),this.toLog())},`${_("All in Log")} →`):""]);if(!o.length){dom.content(this.recentEl,[s,t("div",{class:"dl-recent-empty"},[t("span",{class:"dl-check-icon ok"},g("check")),_("No problems in the last 7 days.")])]);return}dom.content(this.recentEl,[s,...o.slice(0,8).map(r=>{if(r.sys){let a=r.sys,i=`${a.ts}|${a.msg}`;return Rn(a,this.open.has(i),()=>{this.open.delete(i)||this.open.add(i),this.paintRecent()},Wt(a.ts))}return ht(this.st,r.ev,{time:Wt(r.ts)})})])}};var Vn=300,jl=["all","connections","people","system","problems"],Yn=class{constructor(e,o,s){this.events=[];this.system=[];this.kind="all";this.shown=Vn;this.open=new Set;this.list=t("div",{});this.sub="";this.tabs=t("div",{class:"dl-seg",role:"tablist"});this.st=e,this.take(o),this.system=s,this.el=t("div",{},[t("div",{class:"dl-toolbar"},[this.tabs]),this.list]),this.paint()}actions(){let e=()=>this.kind==="all"?"":this.kind,o=a=>()=>{let i=this.filtered().reverse();Ze(this.st,i.filter(l=>l.ev).map(l=>l.ev),a,e(),i.filter(l=>l.sys).map(l=>l.sys))},s=N([g("download"),` ${_("Export")}`],()=>Te(s,[{label:_("CSV (spreadsheet)"),icon:g("download"),run:o("csv")},{label:"JSON",icon:g("download"),run:o("json")}])),r=N([g("trash"),` ${_("Clear")}`],()=>lt(_("Clear the log"),_("Removes events from the log on the router."),{},()=>this.reload(),this.kind==="all"?void 0:this.kind,!0));return[s,r]}take(e){this.events=e.events,this.policy=e.policy;let o=Ht.filter(r=>!e.policy.categories.includes(r)),s=wn(e.policy);this.sub=o.length?`${s} ${m(_("Not recorded: %s."),o.map(r=>Ke(r).toLowerCase()).join(", "))}`:s}async reload(){let[e,o]=await Promise.all([H.events(2e4).catch(()=>null),H.serviceLog().catch(()=>null)]);e&&this.take(e),o&&(this.system=o.log),this.paint()}items(){return[...this.events.map(e=>({ts:e.ts,ev:e})),...this.system.map(e=>({ts:e.ts,sys:e}))].sort((e,o)=>o.ts-e.ts)}matches(e,o){return o==="all"?!0:o==="problems"?xn(e):o==="system"?!!e.sys:!!e.ev&&Ft(e.ev.type)===o}filtered(){return this.items().filter(e=>this.matches(e,this.kind))}paintTabs(e){dom.content(this.tabs,jl.map(o=>t("button",{type:"button",role:"tab",class:o===this.kind?"on":"","aria-selected":o===this.kind?"true":"false",click:()=>this.show(o)},[o==="all"?_("All"):o==="system"?_("System"):Ke(o),t("b",{},String(e.filter(s=>this.matches(s,o)).length))])))}show(e){this.kind=e,this.shown=Vn,this.paint()}paint(){this.paintTabs(this.items());let e=this.filtered();if(!e.length){dom.content(this.list,t("div",{class:"dl-empty"},[t("p",{},this.events.length||this.system.length?_("No events match."):_("The log is empty."))]));return}let o=[],s="",r=null;for(let a of e.slice(0,this.shown)){let i=Nr(a.ts);i!==s&&(s=i,r=t("div",{class:"dl-panel flush"},t("div",{class:"dl-panel-head pad"},t("h3",{},i))),o.push(r));let l=new Date(a.ts*1e3).toLocaleTimeString(le(),{hour:"2-digit",minute:"2-digit"});if(a.sys){let d=`${a.sys.ts}|${a.sys.msg}`;r.appendChild(Rn(a.sys,this.open.has(d),()=>{this.open.delete(d)||this.open.add(d),this.paint()},l))}else r.appendChild(ht(this.st,a.ev,{time:l}))}e.length>this.shown&&o.push(t("div",{class:"dl-more-row"},N(m(_("Show %s more of %s"),V(Math.min(Vn,e.length-this.shown)),V(e.length-this.shown)),()=>{this.shown+=Vn,this.paint()}))),dom.content(this.list,o)}};var Ul=["health","log"],Wl=n=>n==="log"?_("Log"):_("Health"),Go=2e4,Jn=class{constructor(){this.tab=new URLSearchParams(location.search).get("tab")==="log"?"log":"health";this.segEl=t("div",{class:"dl-seg dl-srvsections dl-diag-tabs",role:"tablist","aria-label":_("Diagnostics")});this.subEl=t("span",{class:"dl-muted"});this.actionsEl=t("div",{class:"dl-row-actions"});this.bodyEl=t("div",{});this.eventsAt=0}load(){return this.eventsAt=Date.now(),Promise.all([H.status(1),H.events(Go),H.serviceLog()])}render([e,o,s]){return this.log=new Yn(e,o,s.log),this.health=new Kn(e,s,o.events,()=>{this.show("log"),this.log.show("problems")}),this.show(this.tab),pt({fetch:async()=>{let r=this.tab==="log",[a,i]=await Promise.all([H.serviceLog().catch(()=>null),r?H.events(Go).catch(()=>null):Promise.resolve(null)]);return a||i?{n:a,e:i}:null},every:10,active:()=>this.bodyEl.isConnected,apply:({n:r,e:a})=>this.take(r,a)}),t("div",{},[t("div",{class:"dl-pagehead"},[t("div",{class:"dl-stack"},[t("h2",{class:"dl-h1"},_("Diagnostics")),this.subEl]),this.actionsEl]),this.segEl,this.bodyEl])}take(e,o){o&&(this.log.take(o),this.eventsAt=Date.now()),e&&(this.log.system=e.log),e&&this.health.paintLive(e,o?.events??this.health.events),this.tab==="log"&&this.log.paint()}show(e){this.tab=e,dom.content(this.segEl,Ul.map(o=>t("button",{type:"button",role:"tab",class:o===e?"on":"","aria-selected":o===e?"true":"false",click:()=>o!==this.tab&&this.show(o)},Wl(o)))),this.bodyEl.replaceChildren(e==="log"?this.log.el:this.health.el),this.subEl.textContent=e==="log"?this.log.sub:_("Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own."),dom.content(this.actionsEl,e==="log"?this.log.actions():""),e==="log"?(this.log.paint(),Date.now()-this.eventsAt>1e4&&H.events(Go).then(o=>this.take(null,o)).catch(()=>null)):this.health.checks||this.health.run()}};var ka=":root{--dl-card: var(--panel-bg, var(--background-color-high, transparent));--dl-elevated: var(--elevated, var(--background-color-high, Canvas));--dl-line: var(--border, var(--border-color-medium, color-mix(in srgb, currentColor 14%, transparent)));--dl-fg: var(--foreground, var(--text-color-highest, currentColor));--dl-soft: var(--muted, color-mix(in srgb, var(--dl-fg) 5%, transparent));--dl-soft-hover: var(--soft-hover, color-mix(in srgb, var(--dl-fg) 10%, transparent));--dl-fg-muted: var(--muted-foreground, color-mix(in srgb, currentColor 65%, transparent));--dl-fg-faint: var(--text-tertiary, color-mix(in srgb, currentColor 50%, transparent));--dl-accent: var(--accent, #3a83f7);--dl-ok: var(--success, #00a240);--dl-warn: var(--warning, #e25507);--dl-bad: var(--danger, #e02e2a);--dl-info: var(--info, #2c67c5);--dl-ok-wash: var(--success-a15, color-mix(in srgb, var(--dl-ok) 15%, transparent));--dl-warn-wash: var(--warning-a15, color-mix(in srgb, var(--dl-warn) 15%, transparent));--dl-bad-wash: var(--destructive-a15, color-mix(in srgb, var(--dl-bad) 15%, transparent));--dl-info-wash: var(--info-a15, color-mix(in srgb, var(--dl-info) 15%, transparent));--dl-track: var(--foreground-a10, color-mix(in srgb, var(--dl-fg) 10%, transparent));--dl-chart-1: var(--chart-blue, #3a83f7);--dl-chart-2: var(--chart-green, var(--dl-ok));--dl-ring: var(--ring, #3a83f7);--dl-primary: var(--primary, var(--dl-fg));--dl-primary-fg: var(--primary-foreground, var(--dl-elevated));--dl-mono: var(--font-mono, ui-monospace, Menlo, Consolas, monospace);--dl-shadow: var(--shadow-sm, none);--dl-radius: 16px}:root[data-darkmode=true]{--dl-card: var(--panel-bg, var(--background-color-low, transparent));--dl-elevated: var(--elevated, var(--background-color-low, Canvas));--dl-accent: var(--accent, #006efe);--dl-ok: var(--success, #40c977);--dl-warn: var(--warning, #ff8549);--dl-bad: var(--danger, #ff6764);--dl-info: var(--info, #5ba2fe);--dl-ring: var(--ring, #5ba2febc)}.dl-root,.dl-modal{cursor:default}:is(.dl-root,.dl-modal) :is(input:not([type=checkbox],[type=radio],[type=range],[type=button],[type=submit]),textarea,[contenteditable=true]){cursor:text}.dl-icon-wrap{display:inline-flex;align-items:center;justify-content:center;line-height:0}.dl-icon{width:16px;height:16px}.dl-icon-btn{display:inline-flex!important;align-items:center;gap:6px}.dl-muted{color:var(--dl-fg-muted)}.dl-faint,.dl-sep{color:var(--dl-fg-faint)}.dl-nowrap{white-space:nowrap}.dl-mono{font-family:var(--dl-mono);font-size:13px}.dl-spacer{flex:1}.dl-pill{display:inline-flex;align-items:center;gap:4px;height:20px;padding:0 8px;border-radius:999px;font-size:12px;line-height:20px;font-weight:500;white-space:nowrap;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pill.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-pill.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-pill.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-pill.accent{background:var(--dl-info-wash);color:var(--dl-info)}.dl-pill.off{opacity:.75}.dl-panel{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:16px;margin:0 0 16px;min-width:0;box-shadow:var(--dl-shadow)}.dl-panel-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin:0 0 12px}.dl-panel-head h3{margin:0!important;padding:0;font-size:16px;line-height:24px;font-weight:500;border:0;background:none}.dl-tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:0 0 16px}.dl-tile{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:14px 16px;min-width:0;box-shadow:var(--dl-shadow)}.dl-tile-label{font-size:12px;line-height:16px;font-weight:500;color:var(--dl-fg-faint)}.dl-tile-value{font-size:24px;line-height:32px;font-weight:500;margin-top:4px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;letter-spacing:-.01em}.dl-tile-sub{font-size:12px;line-height:16px;color:var(--dl-fg-muted);margin-top:2px;font-variant-numeric:tabular-nums}.dl-grid2{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:0 16px}@media(max-width:960px){.dl-grid2{grid-template-columns:minmax(0,1fr)}}.dl-chart{display:block;width:100%;height:120px}.dl-bar-down{fill:var(--dl-chart-1)}.dl-bar-up{fill:var(--dl-chart-2);opacity:.8}.dl-legend{display:flex;gap:16px;font-size:12px;color:var(--dl-fg-muted);margin-top:8px}.dl-legend i{display:inline-block;width:8px;height:8px;border-radius:999px;margin-right:6px;vertical-align:0}.dl-legend .down{background:var(--dl-chart-1)}.dl-legend .up{background:var(--dl-chart-2)}.dl-events{list-style:none;margin:0;padding:0}.dl-events li{display:flex;gap:12px;align-items:baseline;padding:8px 0;border-top:1px solid var(--dl-line);font-size:14px;line-height:20px;min-width:0}.dl-events li:first-child{border-top:0;padding-top:0}.dl-ev-time{flex:0 0 88px;color:var(--dl-fg-faint);font-variant-numeric:tabular-nums;white-space:nowrap;font-size:13px}.dl-ev-dot{flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);transform:translateY(-2px)}.dl-ev-dot.ok{background:var(--dl-ok)}.dl-ev-dot.warn{background:var(--dl-warn)}.dl-ev-dot.bad{background:var(--dl-bad)}.dl-ev-dot.accent{background:var(--dl-accent)}.dl-row>.dl-ev-dot,.dl-dev-log-row>.dl-ev-dot{margin:0 4px}.dl-ev-tile{flex:none;display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;margin:-2px -4px;border-radius:7px;background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent);align-self:center}.dl-ev-tile .dl-icon-wrap{display:inline-flex}.dl-ev-tile .dl-icon{width:14px;height:14px}.dl-row.dl-ev-by-admin{background:color-mix(in srgb,var(--dl-accent) 6%,transparent)}.dl-you{color:var(--dl-accent);font-weight:500}.dl-ev-kind{color:var(--dl-fg-faint)}.dl-slotbar{display:flex;align-items:center;gap:8px;margin:8px 0 0 44px}.dl-slotbar-segs{display:flex;gap:3px;flex:none;max-width:100%}.dl-slotbar-segs i{flex:1;min-width:2px;display:block;height:4px;border-radius:2px;background:var(--dl-soft-hover)}.dl-slotbar-segs i.used{background:var(--dl-fg-muted)}.dl-slotbar-text{font-size:12px;color:var(--dl-fg-faint);font-variant-numeric:tabular-nums}.dl-slotbar-segs i.over{background:color-mix(in srgb,var(--dl-warn) 80%,transparent)}.dl-ev-srv{flex:none;font-size:11px;line-height:18px;padding:0 8px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);white-space:nowrap}.dl-ev-by-system{--sys: var(--dl-fg-muted)}.dl-ev-by-system.ok{--sys: var(--dl-ok)}.dl-ev-by-system.warn{--sys: var(--dl-warn)}.dl-ev-by-system.bad{--sys: var(--dl-bad)}.dl-ev-tile.ev{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-ev-tile.ev.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-ev-tile.ev.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-ev-tile.ev.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-ev-tile.ev.accent{background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent)}.dl-ev-tile.sys{background:color-mix(in srgb,var(--sys) 16%,transparent);color:var(--sys)}.dl-row.dl-ev-by-system{background:color-mix(in srgb,var(--sys) 6%,transparent)}.dl-sys-src{color:var(--sys)}.dl-ev-by-system:not(.ok):not(.warn):not(.bad) .dl-sys-src{color:var(--dl-fg)}.dl-ev-text{min-width:0;overflow-wrap:anywhere}.dl-server{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}.dl-server-name{font-size:16px;line-height:24px;font-weight:500}.dl-kv{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:6px 24px;margin:12px 0 0;font-size:14px;line-height:20px}.dl-kv dt{color:var(--dl-fg-muted);font-weight:400;margin:0}.dl-kv dd{margin:0;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}";var _a='.dl-plist{display:block}.dl-plist>.dl-card{display:block;margin:0 0 12px;padding:16px;min-width:0;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);box-shadow:var(--dl-shadow)}.dl-plist>.dl-card.dl-filtered{display:none}.dl-plist>.dl-card.dl-off :is(.dl-card-name,.dl-avatar,.dl-access,.dl-slotbar,.dl-chips,.dl-pill-ic,.dl-use-num,.dl-pside-foot,.dl-pside-state){opacity:.45}.dl-plist>.dl-card.dl-off .dl-usebar i{background:var(--dl-fg-faint)}.dl-plist>.dl-card.dl-off .dl-chip-tag{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pcard:has(>.dl-pstrip){row-gap:14px}.dl-pstrip{grid-column:1 / -1;display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin:0 -16px -16px;padding:10px 16px;border-top:1px solid var(--dl-line);border-radius:0 0 var(--dl-radius) var(--dl-radius);font-size:14px;line-height:20px}.dl-pstrip.warn{background:color-mix(in srgb,var(--dl-warn) 7%,transparent)}.dl-pstrip.bad{background:color-mix(in srgb,var(--dl-bad) 7%,transparent)}.dl-pstrip-text{flex:1;min-width:0;display:flex;flex-wrap:wrap;align-items:baseline;gap:0 8px}.dl-pstrip-text b{font-weight:500}.dl-pstrip>.cbi-button{flex:none;height:32px!important}.dl-plist-none{color:var(--dl-fg-muted);text-align:center;padding:28px 16px;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius)}.dl-card-head{display:flex;align-items:center;flex-wrap:wrap;gap:6px 8px}.dl-avatar{flex:0 0 auto;width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;color:var(--dl-fg);background:var(--dl-soft);position:relative;margin-right:4px;letter-spacing:.02em}.dl-avatar.online:after{content:"";position:absolute;right:-1px;bottom:-1px;width:9px;height:9px;border-radius:50%;background:var(--dl-ok);box-shadow:0 0 0 2px var(--dl-card)}.dl-card-name{font-size:16px;line-height:24px;font-weight:500}.dl-card-slug{font-size:13px;color:var(--dl-fg-faint);font-family:var(--dl-mono)}.dl-quota{margin:8px 0 0 44px;max-width:320px;height:6px;border-radius:999px;background:var(--dl-track);overflow:hidden}.dl-quota>i{display:block;height:100%;background:var(--dl-accent);border-radius:999px}.dl-quota.warn>i{background:var(--dl-warn)}.dl-quota.bad>i{background:var(--dl-bad)}.dl-chips{display:flex;flex-wrap:wrap;gap:6px;margin:12px 0 0 44px}.dl-chip{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;max-width:240px;height:28px;padding:0 12px 0 10px;border-radius:999px;font-size:13px;background:var(--dl-soft);color:var(--dl-fg);transition:background .15s}.dl-chip:hover{background:var(--dl-soft-hover)}.dl-chip:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-chip .dl-icon{width:14px;height:14px;color:var(--dl-fg-muted)}.dl-chip.add{background:transparent;border:1px dashed color-mix(in srgb,var(--dl-fg) 28%,transparent);color:var(--dl-fg-muted)}.dl-chip.add:hover{background:var(--dl-soft);color:var(--dl-fg);border-color:color-mix(in srgb,var(--dl-fg) 45%,transparent)}.dl-chip.add:hover .dl-icon{color:var(--dl-fg)}.dl-chip.disabled .dl-chip-name{text-decoration:line-through;color:var(--dl-fg-faint)}.dl-chip-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-dot{flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);opacity:.6}.dl-dot.online{background:var(--dl-ok);opacity:1;box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-empty{text-align:center;padding:40px 16px;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius)}.dl-empty .dl-icon-wrap{width:40px;height:40px;border-radius:12px;background:var(--dl-soft);margin-bottom:12px}.dl-empty .dl-icon{width:20px;height:20px}.dl-empty h3{margin:0 0 4px!important;font-size:16px;font-weight:500}.dl-empty p{margin:0 0 16px;color:var(--dl-fg-muted);font-size:14px}.dl-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:0 0 16px}.dl-toolbar .dl-muted{font-size:13px}@media(max-width:640px){.dl-slotbar,.dl-chips,.dl-quota{margin-left:0}.dl-btn-label{display:none}}.cbi-value.dl-block{display:block!important}.cbi-value.dl-block>.cbi-value-title{display:block;width:auto;float:none;text-align:left;padding:0 0 8px}.cbi-value.dl-block>.cbi-value-field{display:block;width:100%;margin:0}.dl-people-find{width:160px;min-width:0}.dl-people-find[hidden]{display:none}';var Ca="#modal_overlay{z-index:1100!important}.dl-dd{position:fixed;z-index:1200;min-width:200px;padding:4px;border-radius:12px;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:0 12px 32px #0000004d;display:flex;flex-direction:column}.dl-dd button{all:unset;cursor:pointer;display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;font-size:13px;color:var(--dl-fg)}.dl-dd button .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted)}.dl-dd button:hover,.dl-dd button:focus-visible{background:var(--dl-soft)}.dl-dd button.danger,.dl-dd button.danger .dl-icon{color:var(--dl-bad, #e5484d)}.dl-dd button.warn,.dl-dd button.warn .dl-icon{color:var(--dl-warn)}.dl-dd hr{border:0;border-top:1px solid var(--dl-line);margin:4px 0}.dl-chipbtn b{font-weight:500;font-size:11px;margin-left:6px;opacity:.6}.dl-setsub{margin:20px 0 8px!important;font-size:13px;font-weight:500;color:var(--dl-fg)}.dl-row-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.dl-more-row{display:flex;justify-content:center;padding:8px 0 16px}.dl-dsec-actions{display:flex;align-items:center;gap:12px}.dl-kv-act{display:inline-flex;align-items:center;gap:12px;flex-wrap:wrap}.dl-linkbtn,.dl-bento-head a,.dl-bento-foot a,.dl-panel-head a,.dl-dsec-head a,.dl-tile2-foot a{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:4px;height:26px;padding:0 9px;margin:-4px -6px;border-radius:8px;font-size:12px;font-weight:500;color:var(--dl-fg-muted);text-decoration:none!important;white-space:nowrap;transition:background .12s,color .12s}.dl-bento-head a,.dl-bento-foot a,.dl-panel-head a,.dl-dsec-head a,.dl-tile2-foot a{color:var(--dl-accent)}.dl-linkbtn:hover,.dl-bento-head a:hover,.dl-bento-foot a:hover,.dl-panel-head a:hover,.dl-dsec-head a:hover,.dl-tile2-foot a:hover{background:var(--dl-soft);color:var(--dl-fg);text-decoration:none!important}.dl-bento-head a:hover,.dl-bento-foot a:hover,.dl-panel-head a:hover,.dl-dsec-head a:hover,.dl-tile2-foot a:hover{background:color-mix(in srgb,var(--dl-accent) 12%,transparent);color:var(--dl-accent)}.dl-linkbtn:focus-visible,.dl-bento-head a:focus-visible,.dl-bento-foot a:focus-visible,.dl-panel-head a:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-linkbtn.danger:hover{color:var(--dl-bad);background:var(--dl-bad-wash)}.dl-ifcards{display:flex;flex-direction:column;gap:20px;margin:24px 0}.dl-ifcard .dl-setsec-body{gap:14px}.dl-iflead{display:flex;flex-direction:column;gap:2px;padding-top:14px;border-top:1px solid var(--dl-line)}.dl-iflead b{font-size:14px;font-weight:500}.dl-ifgroup h4{margin:0 0 8px!important;padding:0!important;font-size:11px!important;font-weight:500!important;letter-spacing:.06em;text-transform:uppercase;color:var(--dl-fg-muted);border:0!important;background:none!important}.dl-ifgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:8px}.dl-if{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;min-height:52px;padding:8px 12px 8px 10px;min-width:0;border:1px solid var(--dl-line);border-radius:10px;background:var(--dl-card);transition:background .15s,border-color .15s}.dl-if:hover{background:var(--dl-soft)}.dl-if:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-if-ic{width:30px;height:30px;border-radius:8px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-if-ic .dl-icon{width:16px;height:16px}.dl-if-main{display:flex;flex-direction:column;min-width:0;flex:1}.dl-if-name{font-size:13.5px;font-weight:500;color:var(--dl-fg);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-if-sub{font:11px/16px var(--dl-mono);color:var(--dl-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-if.sel{border-color:var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 9%,transparent)}.dl-if.sel .dl-if-ic{background:color-mix(in srgb,var(--dl-accent) 18%,transparent);color:var(--dl-accent)}.dl-if-check{color:var(--dl-accent);display:inline-flex}.dl-if-check .dl-icon{width:16px;height:16px}.dl-if.auto{border-color:color-mix(in srgb,var(--dl-ok) 55%,transparent);background:var(--dl-ok-wash);cursor:default}.dl-if.auto .dl-if-ic{background:color-mix(in srgb,var(--dl-ok) 18%,transparent);color:var(--dl-ok)}.dl-if-badge{display:inline-flex;align-items:center;gap:5px;font-size:10.5px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;flex:0 0 auto}.dl-if-badge.ok{color:var(--dl-ok)}.dl-if.off{cursor:default;opacity:.5}.dl-if.off:hover{background:var(--dl-card)}.dl-if.warn{border-color:color-mix(in srgb,var(--dl-warn) 60%,transparent)}.dl-if-wanctl{gap:10px;align-items:center}.dl-if-wanctl select{max-width:240px}.dl-if-summary{min-width:0;line-height:18px}.dl-warn{color:var(--dl-warn)}.dl-w-ip{width:160px}.dl-dnspick{padding-top:8px;border-top:1px solid var(--dl-line)}.dl-dnspick .dl-row-actions{gap:10px}.cbi-dropdown>ul:not(.dropdown) .dl-opt-note{display:none}.dl-note{display:flex;gap:8px;align-items:flex-start;padding:10px 12px;border-radius:10px;font-size:12.5px;line-height:18px;margin:0 0 10px;background:var(--dl-soft)}.dl-note.warn{background:var(--dl-warn-wash, color-mix(in srgb, var(--dl-warn) 14%, transparent))}.dl-note .dl-icon{width:15px;height:15px;flex:0 0 auto;margin-top:1px;color:var(--dl-warn)}.dl-stale{align-self:flex-start;margin-top:4px;font-size:10.5px}.dl-root .cbi-button.dl-btn-warn,.dl-btn-warn.cbi-button{background:var(--dl-warn-wash)!important;color:var(--dl-warn)!important;border-color:color-mix(in srgb,var(--dl-warn) 35%,transparent)!important}.dl-root .cbi-button.dl-btn-warn:hover,.dl-btn-warn.cbi-button:hover{background:color-mix(in srgb,var(--dl-warn) 24%,transparent)!important}.dl-btn-warn .dl-icon{color:var(--dl-warn)}.dl-srvtabs{display:flex;flex-wrap:wrap;gap:6px;padding:4px;margin:0 0 20px;border-radius:12px;background:var(--dl-soft);width:fit-content;max-width:100%}.dl-srvtab{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:8px;height:34px;padding:0 14px;border-radius:9px;font-size:13px;color:var(--dl-fg-muted);text-decoration:none!important;white-space:nowrap}.dl-srvtab b{font-weight:500}.dl-srvtab i.dot{width:7px;height:7px;border-radius:50%;background:var(--dl-fg-faint);flex:0 0 auto}.dl-srvtab i.dot.ok{background:var(--dl-ok);animation:dl-srv-pulse 2s ease-out infinite}.dl-srvtab i.dot.bad{background:var(--dl-bad)}.dl-srvtab i.dot.warn{background:var(--dl-warn)}@keyframes dl-srv-pulse{0%{box-shadow:0 0 color-mix(in srgb,var(--dl-ok) 55%,transparent)}70%,to{box-shadow:0 0 0 6px transparent}}@media(prefers-reduced-motion:reduce){.dl-srvtab i.dot.ok{animation:none}}.dl-srvtab:hover{color:var(--dl-fg);background:var(--dl-soft-hover)}.dl-srvtab.on{background:var(--dl-card);color:var(--dl-fg);box-shadow:0 1px 2px #0000002e,inset 0 0 0 1px var(--dl-line)}.dl-srvtab:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-srvtab.add{color:var(--dl-fg-muted)}.dl-srvtab.add .dl-icon{width:14px;height:14px}.dl-srvhead{display:flex;flex-direction:column;gap:14px;margin:0 0 20px}.dl-srvhead .dl-title-row{display:flex;align-items:center;gap:10px}.dl-srvhead .dl-h1{margin:0!important}.dl-metrics.compact .dl-metric{padding:14px 18px}.dl-metrics.compact .dl-metric-value{display:flex;align-items:center;gap:6px;font-size:18px;line-height:26px;min-width:0}.dl-metrics.compact .dl-metric-value>span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-metrics.compact .dl-metric-value .dl-mono{font-size:15px}.dl-metrics.compact .cbi-button{flex:0 0 auto}.dl-srvsections{margin:0 0 16px}.dl-srvbody>.dl-setsec,.dl-srvbody>.dl-ifcards{margin:0}.dl-srvbody .dl-ifcards{margin:0}.dl-metric-ic{display:inline-flex;align-items:center;gap:8px;font-size:16px}.dl-metric-ic .dl-icon{width:18px;height:18px;color:var(--dl-accent)}.dl-keyrow{display:inline-flex;align-items:center;gap:8px;min-width:0}.dl-keyrow code{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;background:none;padding:0}.dl-params{border:1px solid var(--dl-line);border-radius:12px;background:var(--dl-card)}.dl-params>summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;color:var(--dl-fg);user-select:none}.dl-params>summary::-webkit-details-marker{display:none}.dl-params>summary>.dl-icon-wrap{display:inline-flex;color:var(--dl-fg-muted);transition:transform .15s}.dl-params>summary>.dl-icon-wrap .dl-icon{width:15px;height:15px}.dl-params[open]>summary>.dl-icon-wrap{transform:rotate(90deg)}.dl-params>summary:focus{outline:none}.dl-params>summary:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px;border-radius:12px}.dl-params>summary:hover{background:var(--dl-soft);border-radius:12px}.dl-pcount{font-size:11px;padding:0 6px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:10px;padding:4px 14px 14px}.dl-pgroup{display:flex;flex-direction:column;gap:6px;padding:12px;border-radius:10px;background:var(--dl-soft);min-width:0}.dl-pgroup-head{display:flex;align-items:center;gap:8px;font-size:13px}.dl-pgroup-head b{font-weight:500}.dl-pgroup-head .dl-icon{width:14px;height:14px;color:var(--dl-fg-muted)}.dl-pgroup p{margin:0!important;font-size:12px;line-height:17px;color:var(--dl-fg-muted)}.dl-pvals{display:flex;flex-wrap:wrap;gap:4px;margin-top:2px}.dl-pv{display:inline-flex;align-items:stretch;max-width:100%;border-radius:6px;overflow:hidden;font:500 11.5px/22px var(--dl-mono);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-pv i{font-style:normal;padding:0 6px;background:var(--dl-card);color:var(--dl-fg-faint)}.dl-pv b{font-weight:500;padding:0 7px;color:var(--dl-fg);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}";var La=".dl-methods{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px}.dl-method{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;gap:10px;padding:14px;border-radius:12px;border:1px solid var(--dl-line);background:var(--dl-card);transition:border-color .15s,background .15s;min-width:0}.dl-method:hover{background:var(--dl-soft)}.dl-method:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-method.on{border-color:var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 8%,transparent);box-shadow:inset 0 0 0 1px var(--dl-accent)}.dl-method.off{cursor:not-allowed;opacity:.55}.dl-method.off:hover{background:var(--dl-card)}.dl-method-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}.dl-method-head .dl-pill{flex:none}.dl-method-head b{font-weight:500;font-size:14.5px;flex:1}.dl-method-ic{width:32px;height:32px;border-radius:9px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;color:var(--dl-fg-muted);flex:0 0 auto}.dl-method-ic .dl-icon{width:17px;height:17px}.dl-method.on .dl-method-ic{background:color-mix(in srgb,var(--dl-accent) 18%,transparent);color:var(--dl-accent)}.dl-method p{margin:0!important;font-size:12.5px;line-height:18px;color:var(--dl-fg-muted);flex:1}.dl-method-meters{display:flex;gap:16px}.dl-dots{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--dl-fg-faint)}.dl-dots-row{display:inline-flex;gap:3px}.dl-dots-row i{width:6px;height:6px;border-radius:50%;background:var(--dl-line)}.dl-dots-row i.on{background:var(--dl-fg-muted)}.dl-method.on .dl-dots-row i.on{background:var(--dl-accent)}.dl-method-foot{display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--dl-fg-faint);padding-top:8px;border-top:1px solid var(--dl-line)}.dl-method-foot .dl-icon{width:13px;height:13px;flex:0 0 auto}.dl-method.off .dl-method-foot{color:var(--dl-warn)}.dl-ibadge{display:inline-flex;align-items:center;gap:3px;height:22px;padding:0 6px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);flex:0 0 auto}.dl-ibadge .dl-icon{width:13px;height:13px}.dl-ibadge.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-ibadge.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-access{display:inline-flex;gap:4px;flex:0 0 auto}.dl-ibadge.lan{background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent)}.dl-ibadge.inet{background:var(--dl-ok-wash);color:var(--dl-ok)}";var Ma=".dl-addrbar{display:inline-flex;align-items:stretch;flex-wrap:nowrap;max-width:100%;margin-top:4px;border:1px solid var(--dl-line);border-radius:10px;background:var(--dl-card);overflow:hidden}.dl-addrbar-seg{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;gap:7px;padding:6px 12px;font-size:13px;color:var(--dl-fg-muted);border-left:1px solid var(--dl-line);white-space:nowrap;min-width:0}.dl-addrbar-seg:first-child{border-left:0}.dl-addrbar-seg .dl-icon{width:14px;height:14px;color:var(--dl-fg-faint);flex:0 0 auto}.dl-addrbar-seg .dl-mono{font-size:12.5px}.dl-addrbar-seg.main{cursor:pointer;color:var(--dl-fg)}.dl-addrbar-seg.main:hover{background:var(--dl-soft)}.dl-addrbar-seg.main:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px}.dl-addrbar-seg.main>.dl-icon-wrap:last-child .dl-icon{opacity:.7}.dl-bento{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));grid-template-rows:auto auto;gap:10px;margin:0 0 20px}.dl-person-devices{margin-bottom:16px}.dl-person-head{display:flex;flex-direction:column;margin:0 0 20px}.dl-person-head>.dl-pagehead{margin-bottom:0;align-items:flex-start}.dl-pnote{all:unset;box-sizing:border-box;cursor:pointer;align-self:flex-start;display:inline-flex;align-items:flex-start;gap:6px;margin:10px 0 0 62px;max-width:60ch;padding:6px 12px 6px 10px;border-radius:10px;font-size:13px;line-height:18px;white-space:pre-line;background:var(--dl-soft);color:var(--dl-fg);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-pnote:hover{background:var(--dl-soft-hover)}.dl-pnote .dl-icon{width:14px;height:14px;flex:none;margin-top:2px;color:var(--dl-fg-muted)}.dl-note-input{width:100%;box-sizing:border-box;min-height:80px;resize:vertical}.dl-dcard-trend{display:flex;align-items:flex-end;gap:12px;min-width:0}.dl-dcard-trend>.dl-stack{flex:none}.dl-dcard-trend b{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}.dl-dbars{flex:1;min-width:0;height:32px;display:flex;align-items:flex-end;--dl-gap: 2px}.dl-dbars i{flex:1;min-width:0;border-radius:2px;background:var(--dl-chart-1);opacity:.55}.dl-dbars i.zero{background:var(--dl-track);opacity:1}.dl-dbars i.hi{opacity:1}.dl-dbars>span:hover i{opacity:1;filter:brightness(1.2)}.dl-datechip{position:relative;display:inline-flex}.dl-date-hidden{position:absolute!important;left:0;bottom:0;width:1px!important;min-width:0!important;height:1px!important;opacity:0;pointer-events:none;border:0!important;padding:0!important;margin:0!important}.dl-chipbtn .dl-icon{width:13px;height:13px}.dl-chipbtn:has(.dl-icon){display:inline-flex;align-items:center;gap:5px}.dl-places{display:flex;align-items:center;gap:12px;padding:12px 16px;border:1px solid var(--dl-line);border-radius:var(--dl-radius);background:var(--dl-card);font-size:14px}.dl-places>.dl-icon{width:18px;height:18px;color:var(--dl-fg-muted);flex:none}.dl-person-live{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px}.dl-person-live .dl-bento-head{flex-wrap:nowrap;white-space:nowrap;min-width:0}.dl-person-live .dl-bento-head>*{min-width:0;overflow:hidden;text-overflow:ellipsis}.dl-person-live .dl-bento-head>:first-child{flex:none}.dl-person-live.solo{grid-template-columns:minmax(0,1fr)}.dl-person-live:not(.solo) .dl-bento-tile.month>.dl-bento-head:first-child{flex-wrap:wrap;row-gap:2px}.dl-person-live:not(.solo) .dl-bento-tile.month>.dl-bento-head:first-child>.dl-sub{flex-basis:100%}.dl-person-live>.dl-bento-tile,.dl-person-live>.dl-bento-tile.month{grid-column:auto;grid-row:auto}@media(max-width:760px){.dl-person-live{grid-template-columns:minmax(0,1fr)}}.dl-bento-tile{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:14px 16px;display:flex;flex-direction:column;gap:10px;min-width:0;box-shadow:var(--dl-shadow)}.dl-bento-tile.month{grid-column:1 / -1}.dl-onl-count{font-size:13px;line-height:22px;min-width:22px;padding:0 8px;border-radius:999px;background:var(--dl-soft);text-align:center;font-weight:500;font-variant-numeric:tabular-nums}.dl-onl-count.none{color:var(--dl-fg-faint)}.dl-onl-row{flex:1;display:flex;align-items:center;justify-content:center;gap:12px;min-width:0}.dl-onl-p{display:flex;flex-direction:column;align-items:center;gap:5px;width:104px;min-width:0;padding:6px 2px;border-radius:12px;color:var(--dl-fg)!important;text-decoration:none!important}.dl-onl-p:hover{background:var(--dl-soft)}.dl-onl-av{position:relative;width:42px;height:42px;border-radius:50%;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;font-size:13px;font-weight:500;box-shadow:0 0 0 2px var(--dl-ok)}.dl-onl-p.more .dl-onl-av{box-shadow:0 0 0 1px var(--dl-line);color:var(--dl-fg-muted)}.dl-onl-dev{position:absolute;right:-6.5px;bottom:-6.5px;width:20px;height:20px;border-radius:8.5px;border:1.5px solid transparent;background:var(--dl-card);display:inline-flex;align-items:center;justify-content:center;font-size:10px;color:var(--dl-fg-muted)}.dl-onl-dev .dl-icon-wrap{display:inline-flex}.dl-onl-dev .dl-icon{width:12px;height:12px}.dl-onl-name{font-size:12.5px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-onl-p .dl-sub{font-size:11px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-onl-row.grid{flex-wrap:wrap;align-content:center;gap:10px 8px;max-height:108px;overflow:hidden}.dl-onl-p.sm{width:auto;padding:4px}.dl-onl-p:hover .dl-onl-dev{background:linear-gradient(var(--dl-soft),var(--dl-soft)),var(--dl-card)}.dl-onl-p.sm:hover{background:none}.dl-onl-p.sm:hover .dl-onl-dev{background:var(--dl-card)}.dl-onl-p.sm .dl-onl-av{transition:box-shadow .15s ease}.dl-onl-p.sm:hover .dl-onl-av{box-shadow:0 0 0 2px var(--dl-ok),0 0 0 6px var(--dl-soft)}.dl-onl-p.sm.more:hover .dl-onl-av{box-shadow:0 0 0 1px var(--dl-line),0 0 0 6px var(--dl-soft)}.dl-onl-p.sm .dl-onl-av{width:36px;height:36px;font-size:11.5px}.dl-onl-meta{display:inline-flex;align-items:center;gap:3px;font-size:11px;color:var(--dl-fg-faint);max-width:100%;white-space:nowrap;overflow:hidden}.dl-onl-meta .dl-icon-wrap{display:inline-flex}.dl-onl-meta .dl-icon{width:12px;height:12px}.dl-onl-av.sm{width:34px;height:34px;font-size:11.5px}.dl-tip-float:has(.dl-hc){padding:0;white-space:normal;border-radius:16px}.dl-hc{width:280px;padding:14px;display:flex;flex-direction:column;gap:10px}.dl-hc-head{display:flex;align-items:center;gap:10px}.dl-hc-head .dl-stack{flex:1;min-width:0}.dl-hc-head b{font-size:14px;font-weight:500}.dl-hc-since{font-size:11.5px;color:var(--dl-ok)}.dl-hc-reach{display:inline-flex;gap:4px}.dl-hc-speed{border-radius:12px;background:var(--dl-soft);padding:10px 12px;display:flex;flex-direction:column;gap:6px}.dl-hc-speed-row{display:flex;align-items:baseline;gap:12px;font-size:13px;font-variant-numeric:tabular-nums}.dl-hc-chart{display:block;width:100%;height:30px}.dl-hc-chart .area{fill:color-mix(in srgb,var(--dl-chart-1) 16%,transparent)}.dl-hc-chart .dn{fill:none;stroke:var(--dl-chart-1);stroke-width:1.5;vector-effect:non-scaling-stroke}.dl-hc-chart .up{fill:none;stroke:var(--dl-ok);stroke-width:1.2;vector-effect:non-scaling-stroke}.dl-hc-devs{display:flex;flex-wrap:wrap;gap:6px}.dl-hc-dev{display:inline-flex;align-items:center;gap:5px;height:24px;padding:0 9px;border-radius:999px;background:var(--dl-soft);font-size:11.5px}.dl-hc-dev .dl-icon-wrap{display:inline-flex}.dl-hc-dev .dl-icon{width:12px;height:12px;color:var(--dl-fg-muted)}.dl-hc-foot{display:flex;align-items:center;gap:8px;font-size:11.5px}.dl-disg-id{display:flex;align-items:center;gap:10px}.dl-disg-id b{font-size:16px;font-weight:500}.dl-disg-ic{width:36px;height:36px;border-radius:11px;background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-disg-ic .dl-icon-wrap{display:inline-flex}.dl-disg-ic .dl-icon{width:18px;height:18px}.dl-disg-ic.off{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-disg-meters{display:grid;grid-template-columns:auto 1fr;gap:6px 10px;align-items:center;font-size:12px;color:var(--dl-fg-muted)}.dl-segs{display:inline-flex;gap:3px}.dl-segs i{width:18px;height:5px;border-radius:3px;background:var(--dl-track)}.dl-segs.acc i.on{background:var(--dl-accent)}.dl-segs.ok i.on{background:var(--dl-ok)}.dl-disg-chips{margin-top:auto;display:flex;flex-wrap:wrap;gap:5px}.dl-disg-chips span{font:11px/20px var(--dl-mono);padding:0 8px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);white-space:nowrap}.dl-onl-empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;font-size:13px;text-align:center}.dl-bento-head{display:flex;align-items:center;justify-content:space-between;gap:10px;min-width:0}.dl-bento-head.start{justify-content:flex-start}.dl-bento-big{font-family:inherit;font-size:28px;line-height:34px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-bento-big small{font-size:13px;font-weight:400;color:var(--dl-fg-faint);letter-spacing:0}.dl-avstack{display:inline-flex}.dl-avstack .dl-avatar{margin-left:-7px;box-shadow:0 0 0 2px var(--dl-card)}.dl-avstack .dl-avatar:first-child{margin-left:0}.dl-avatar.more{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-bento-list{display:flex;flex-direction:column;gap:2px}.dl-bento-row{display:flex;align-items:center;gap:10px;padding:8px;margin:0 -8px;border-radius:10px;color:var(--dl-fg)!important;text-decoration:none!important;min-width:0;transition:background .12s}.dl-bento-row:hover{background:var(--dl-soft)}.dl-bento-row:hover b{text-decoration:none}.dl-bento-row:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px}.dl-bento-row-main{display:flex;flex-direction:column;gap:1px;flex:1;min-width:0}.dl-bento-row-main b{font-weight:500;font-size:13.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-bento-row-main .dl-sub{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-bento-row.off b{color:var(--dl-fg-muted);font-weight:400}.dl-bento-row-val{display:flex;flex-direction:column;align-items:flex-end;font-size:13px;font-variant-numeric:tabular-nums;white-space:nowrap}.dl-bento-row-val small{font-size:11px;color:var(--dl-fg-faint)}.dl-bento-sep{font-size:11px;color:var(--dl-fg-faint);padding:12px 0 4px}.dl-bento-devs{display:inline-flex;gap:3px;color:var(--dl-fg-faint)}.dl-bento-devs .dl-icon{width:13px;height:13px}.dl-bento-devs .on{color:var(--dl-ok)}.dl-bento-foot{display:flex;align-items:center;gap:10px;margin-top:auto;padding-top:10px;border-top:1px solid var(--dl-line);color:var(--dl-fg)!important;text-decoration:none!important}.dl-bento-foot.split,.dl-bento-foot.end{justify-content:space-between}.dl-bento-foot.end>a:only-child{margin-left:auto}.dl-bento-empty{display:flex;align-items:center;gap:10px;padding:14px 0;font-size:13.5px;color:var(--dl-fg-muted)}.dl-bento-empty .dl-icon{width:18px;height:18px}.dl-split{display:flex;height:6px;border-radius:3px;overflow:hidden;background:var(--dl-soft)}.dl-split i{display:block;height:100%}.dl-split i.dn{background:var(--dl-accent)}.dl-split i.up{background:var(--dl-ok)}.dl-dn{color:var(--dl-accent)}.dl-up{color:var(--dl-ok)}.dl-bento-method{display:flex;align-items:center;gap:8px;font-size:18px;font-weight:500}.dl-bento-method .dl-icon{width:20px;height:20px;color:var(--dl-accent)}.dl-meter{display:inline-flex;gap:3px}.dl-meter i{width:16px;height:4px;border-radius:2px;background:var(--dl-line)}.dl-meter i.on{background:var(--dl-accent)}.dl-bento-total{font-size:16px;font-weight:500;margin-left:8px}.dl-bento-bars{display:flex;align-items:flex-end;height:54px;--dl-gap: 3px}.dl-bento-bars i{flex:1;min-width:0;border-radius:3px 3px 0 0;background:var(--dl-soft-hover);transition:background .15s}.dl-bento-bars i.future{height:4px;background:var(--dl-soft)}.dl-bento-bars>span:hover i:not(.hi){background:var(--dl-fg-faint)}.dl-bento-bars i.hi{background:var(--dl-accent)}@media(max-width:700px){.dl-addrbar{flex-wrap:wrap}}@media(max-width:900px){.dl-bento{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}.dl-bento-tile.online{grid-column:span 2}}@media(max-width:560px){.dl-bento{grid-template-columns:minmax(0,1fr)}.dl-bento-tile.online,.dl-bento-tile.month{grid-column:auto}}.dl-srvpagehead{display:flex;flex-direction:column;align-items:flex-start;gap:10px;margin:0 0 20px}.dl-srvpagehead>.dl-title-row{display:flex;align-items:center;gap:10px;width:100%;flex-wrap:wrap}.dl-srvpagehead .dl-actions{margin:0;flex-wrap:wrap}.dl-toolbar-end{display:flex;align-items:center;gap:8px;margin-left:auto;flex-wrap:nowrap;min-width:0}@media(max-width:640px){.dl-toolbar-end{flex-wrap:wrap;width:100%}}.dl-notices{margin:0 0 16px}.dl-notices .dl-need-row .dl-sub{overflow-wrap:anywhere}.dl-notices-more{font-size:13px;color:var(--dl-fg-muted);text-decoration:none}.dl-notices-more:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-speed-cols{display:grid;grid-template-columns:1fr 1fr;gap:12px}.dl-speed-col{display:flex;flex-direction:column;gap:2px;min-width:0}.dl-speed-val{font-size:20px;line-height:26px;font-weight:500;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-speed-today{display:flex;justify-content:space-between;gap:10px;font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;font-variant-numeric:tabular-nums}.dl-speed-today b{font-weight:500;color:var(--dl-fg)}.dl-speed-chart{display:block;width:100%;height:44px}.dl-speed-chart .area{fill:color-mix(in srgb,var(--dl-accent) 16%,transparent)}.dl-speed-chart .line{fill:none;stroke:var(--dl-accent);stroke-width:1.5;vector-effect:non-scaling-stroke}.dl-speed-chart .line.up{stroke:var(--dl-ok);stroke-width:1.2;opacity:.85}.dl-speed-wait{height:44px;display:flex;flex-direction:column;justify-content:flex-end;gap:6px;font-size:11px;color:var(--dl-fg-faint)}.dl-speed-wait i{display:block;height:1px;background:var(--dl-line);order:2}.dl-speed-val.off{color:var(--dl-fg-faint)}.dl-fld{display:flex;flex-direction:column;gap:8px;margin:0 0 16px}.dl-fld-label{font-size:13px;font-weight:500;color:var(--dl-fg)}.dl-fld .cbi-input-text{width:100%;box-sizing:border-box}.dl-kinds{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}.dl-kinds button{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;height:68px;border-radius:10px;border:1px solid var(--dl-line);color:var(--dl-fg-muted);font-size:12px;font-weight:500;text-align:center;min-width:0}.dl-kinds button .dl-icon{width:20px;height:20px}.dl-kinds button:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-kinds button:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-kinds button.on{border-color:var(--dl-accent);color:var(--dl-fg);background:color-mix(in srgb,var(--dl-accent) 10%,transparent);box-shadow:inset 0 0 0 1px var(--dl-accent)}.dl-kinds button.on .dl-icon{color:var(--dl-accent)}.dl-choices{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:8px}.dl-choice{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;gap:4px;padding:12px 14px;border-radius:12px;background:var(--dl-card);box-shadow:inset 0 0 0 1px var(--dl-line);transition:background .15s,box-shadow .15s}.dl-choice:hover{background:var(--dl-soft)}.dl-choice:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-choice.selected{box-shadow:inset 0 0 0 2px var(--dl-accent);background:var(--accent-a10, color-mix(in srgb, var(--dl-accent) 8%, transparent))}.dl-choice-title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--dl-fg)}.dl-choice-text{font-size:12px;line-height:16px;color:var(--dl-fg-muted)}.dl-attn-item>.cbi-button{margin-left:auto;flex:none;align-self:center}";var Ea='.dl-steps{display:flex;align-items:center;gap:8px;margin:0 0 16px;flex-wrap:wrap}.dl-step{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--dl-fg-faint)}.dl-step b{display:inline-flex;width:24px;height:24px;align-items:center;justify-content:center;border-radius:50%;background:var(--dl-soft);font-size:12px;font-weight:600}.dl-step.current{color:var(--dl-fg)}.dl-step.current b{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-step.done{color:var(--dl-fg-muted)}.dl-step.done b{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-step+.dl-step:before{content:"";width:24px;height:1px;background:var(--dl-line)}.dl-wizard .dl-panel>div{display:flex;flex-direction:column;gap:16px}.dl-wizard .dl-panel>div>p{margin:0!important;color:var(--dl-fg-muted)}.dl-wizard .dl-panel>div>.cbi-value{margin:0}.dl-wizard h4{font-size:14px;font-weight:500;margin:8px 0 -6px!important}.dl-wizard h4:first-child{margin-top:0!important}.dl-modal .cbi-tabmenu{margin-bottom:16px}.dl-modal .cbi-value.dl-live>.cbi-value-title{display:flex;flex-direction:column;gap:2px;text-align:left}.dl-modal .cbi-value.dl-live>.cbi-value-title>.dl-sub{white-space:normal}.dl-checklist{display:flex;flex-direction:column;gap:6px;margin:4px 0 8px}.dl-checklist label{display:flex;align-items:center;gap:8px;font-size:14px;cursor:pointer}.dl-checklist input{margin:0}.dl-invite{display:grid;grid-template-columns:250px minmax(0,1fr);gap:22px;align-items:start}.dl-invite img{display:block;width:100%;border-radius:18px;box-shadow:0 0 0 1px var(--dl-line)}.dl-invite-side{display:flex;flex-direction:column;gap:14px;min-width:0}.dl-invite-side>p{margin:0!important}.dl-invite-link{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;min-width:0;padding:11px 14px;border-radius:12px;background:var(--dl-soft);font:13px/18px var(--dl-mono);color:var(--dl-fg)}.dl-invite-link>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-invite-link>.dl-icon-wrap{flex:none;display:inline-flex}.dl-invite-link .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted);flex:none}.dl-invite-link:hover{background:var(--dl-soft-hover)}.dl-invite-link.alt{padding:8px 14px;font-size:12px;color:var(--dl-fg-muted)}.dl-invite-link>.dl-pill{flex:none}.dl-invite-steps{margin:0;padding-left:20px;list-style:decimal!important;font-size:13px;line-height:24px;color:var(--dl-fg-muted)}.dl-invite-steps b{color:var(--dl-fg);font-weight:500}.dl-invite-steps li{display:list-item!important;list-style:inherit!important;padding-left:4px}.dl-invite-actions{display:flex;gap:8px;flex-wrap:wrap}.modal:has(.dl-modal.wide){max-width:min(760px,94vw)!important;width:100%!important}@media(max-width:640px){.dl-invite{grid-template-columns:minmax(0,1fr)}.dl-invite img{max-width:260px;margin:0 auto}}.dl-toasts{position:fixed;left:50%;bottom:max(24px,env(safe-area-inset-bottom));transform:translate(-50%);z-index:100000;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none}.dl-toast{pointer-events:auto;display:inline-flex;align-items:center;gap:8px;max-width:min(520px,92vw);padding:10px 16px;border-radius:999px;background:var(--dl-fg);color:var(--dl-card);font-size:13px;line-height:18px;box-shadow:0 10px 30px #0000004d;opacity:0;transform:translateY(12px);transition:opacity .18s,transform .18s}.dl-toast.show{opacity:1;transform:none}.dl-toast .dl-icon-wrap{display:inline-flex}.dl-toast .dl-icon{width:15px;height:15px}.dl-toast.success .dl-icon{color:var(--dl-ok)}.dl-toast.error{background:var(--dl-bad);color:#fff}.dl-toast.error .dl-icon{color:#fff}.dl-toast.warning{background:var(--dl-warn);color:#111}.dl-toast.warning .dl-icon{color:#111}.dl-toast button{all:unset;cursor:pointer;display:inline-flex;margin-left:4px;opacity:.8}.dl-toast button:hover{opacity:1}';var Ta=".dl-setblock{display:flex;flex-direction:column;gap:8px;margin:0}.dl-addr-opts{display:flex;flex-direction:column;gap:6px}.dl-addr-opt{all:unset;box-sizing:border-box;cursor:pointer;display:grid;grid-template-columns:16px minmax(0,1fr) auto;gap:12px;align-items:center;padding:10px 14px;border-radius:12px;box-shadow:inset 0 0 0 1px var(--dl-line);min-width:0}.dl-addr-opt:hover{background:var(--dl-soft)}.dl-addr-opt.on{box-shadow:inset 0 0 0 1.5px var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 7%,transparent)}.dl-addr-opt .dl-mono{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-addr-opt .dl-stack{min-width:0}.dl-addr-opt input{width:100%}.dl-addr-opt.other{cursor:default}.dl-addr-opt.other:hover{background:none}.dl-addr-opt.other input{width:100%}.dl-addr-check{width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1.5px var(--dl-fg-faint);display:inline-flex;align-items:center;justify-content:center}.dl-addr-check .dl-icon-wrap{display:inline-flex}.dl-addr-check .dl-icon{width:12px;height:12px}.dl-addr-opt.on .dl-addr-check{background:var(--dl-accent);box-shadow:none;color:#fff}.dl-addr-opt.other .dl-addr-check{box-shadow:none;color:var(--dl-fg-muted)}.dl-addr-warn{display:inline-flex;align-items:center;gap:5px;font-size:12px;line-height:17px;color:var(--dl-warn)}.dl-addr-warn .dl-icon-wrap{display:inline-flex}.dl-addr-warn .dl-icon{width:13px;height:13px}.dl-pill.info{background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent)}.dl-links{border-radius:12px;background:var(--dl-soft);overflow:hidden}.dl-link-row{display:grid;grid-template-columns:18px minmax(0,1fr) auto;gap:10px;align-items:center;padding:11px 14px}.dl-link-row+.dl-link-row{border-top:1px solid var(--dl-line)}.dl-link-ic{display:inline-flex}.dl-link-ic .dl-icon{width:15px;height:15px}.dl-link-ic.ok .dl-icon{color:var(--dl-ok)}.dl-link-ic.warn .dl-icon{color:var(--dl-warn)}.dl-link-url{font-size:13px;color:var(--dl-fg-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-link-url b{font-weight:500;color:var(--dl-accent)}@media(max-width:640px){.dl-link-url,.dl-addr-opt .dl-mono,.dl-filecard .dl-ellipsis,.dl-invite-link>span:first-child{white-space:normal;overflow-wrap:anywhere}}.dl-ready-sum{display:flex;align-items:center;gap:12px;padding:12px 14px;border-radius:12px}.dl-ready-sum>.dl-icon-wrap{display:inline-flex}.dl-ready-sum>.dl-icon-wrap .dl-icon{width:18px;height:18px}.dl-ready-sum .dl-stack{flex:1;min-width:0}.dl-ready-sum b{font-weight:500;font-size:13px}.dl-ready-sum.ok{background:var(--dl-ok-wash)}.dl-ready-sum.ok b,.dl-ready-sum.ok .dl-icon{color:var(--dl-ok)}.dl-ready-sum.warn{background:var(--dl-warn-wash)}.dl-ready-sum.warn b,.dl-ready-sum.warn .dl-icon{color:var(--dl-warn)}.dl-ready-sum.error{background:var(--dl-bad-wash)}.dl-ready-sum.error b,.dl-ready-sum.error .dl-icon{color:var(--dl-bad)}.dl-check-chip{display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-soft);font-size:12px;color:var(--dl-fg-muted)}.dl-check-chip .dl-icon-wrap{display:inline-flex}.dl-check-chip .dl-icon{width:13px;height:13px;color:var(--dl-ok)}.dl-check-chip.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-check-chip.warn .dl-icon{color:var(--dl-warn)}.dl-check-chip.error{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-check-chip.error .dl-icon{color:var(--dl-bad)}.dl-ready-details{display:flex;flex-direction:column;gap:8px;padding:4px 2px}.dl-ready-details[hidden]{display:none}.dl-ready-item{display:flex;align-items:flex-start;gap:8px;font-size:13px;line-height:18px;min-width:0}.dl-ready-item .dl-icon-wrap{display:inline-flex;margin-top:1px}.dl-ready-item .dl-icon{width:15px;height:15px}.dl-ready-item.ok .dl-icon{color:var(--dl-ok)}.dl-ready-item.warn .dl-icon{color:var(--dl-warn)}.dl-ready-item.error .dl-icon{color:var(--dl-bad)}.dl-params-body{display:flex;flex-direction:column;gap:14px;padding:6px 14px 14px}.dl-params-body>.dl-setrow{margin:0;padding:0}.dl-pgrid.flush{padding:0;grid-template-columns:repeat(2,minmax(0,1fr))}@media(max-width:640px){.dl-pgrid.flush{grid-template-columns:minmax(0,1fr)}}.dl-qr-pane{display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center}.dl-qr{width:min(280px,72vw);aspect-ratio:1;background:#0a0a0a;border-radius:18px;overflow:hidden}.dl-qr.light{background:#fff;box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-qr svg{display:block;width:100%;height:100%}.dl-filecard{display:flex;align-items:center;gap:12px;padding:12px;border-radius:14px;background:var(--dl-soft);min-width:0}.dl-filecard>.dl-stack{flex:1;min-width:0}.dl-filecard-ic{width:40px;height:46px;border-radius:8px;flex:none;display:inline-flex;align-items:center;justify-content:center;font:10px var(--dl-mono);color:var(--dl-fg-muted);background:var(--dl-card);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-params>.dl-conf{margin:0;border-top:1px solid var(--dl-line);border-radius:0 0 12px 12px;background:none}.dl-conf-sec{color:var(--dl-accent)}.dl-conf-k{color:var(--dl-fg-faint)}.dl-conf-mask{padding:0 6px;border-radius:4px;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-params>summary .dl-chipbtn{height:26px;font-size:12px}.dl-conf{white-space:pre-wrap;word-break:break-all;max-height:22em;overflow:auto;font-family:var(--dl-mono);font-size:12px;line-height:18px;margin:0;padding:12px;border-radius:12px;background:var(--dl-soft)}.dl-key{width:100%;box-sizing:border-box;font-family:var(--dl-mono);font-size:12px;word-break:break-all;min-height:7em}.dl-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin:12px 0 0}.dl-link-box{display:flex;gap:6px;align-items:center;flex-wrap:wrap}.dl-link-box input{flex:1 1 18em;min-width:0;font-family:var(--dl-mono);font-size:12px}.dl-hint{font-size:12px;line-height:16px;color:var(--dl-fg-muted);margin:8px 0}.dl-divider{border:0;border-top:1px solid var(--dl-line);margin:16px 0}";var Sa=".dl-checks{list-style:none;margin:0;padding:0}.dl-checks li{display:flex;align-items:center;gap:12px;padding:12px 0;border-top:1px solid var(--dl-line)}.dl-checks li:first-child{border-top:0;padding-top:0}.dl-checks li:last-child{padding-bottom:0}.dl-check-icon{flex:0 0 auto;width:28px;height:28px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center}.dl-check-icon .dl-icon{width:14px;height:14px}.dl-check-icon.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-check-icon.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-check-icon.error{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-check-icon.skip{background:var(--dl-soft);color:var(--dl-fg-faint)}.dl-check-body{flex:1;min-width:0}.dl-check-title{font-size:14px;line-height:20px;font-weight:500}.dl-check-detail{font-size:12px;line-height:16px;color:var(--dl-fg-muted);overflow-wrap:anywhere}.dl-check-repaired{margin-top:2px;font-size:12px;line-height:16px;color:var(--dl-warn)}.dl-wd{margin:0 0 16px;display:flex;flex-direction:column;gap:14px}.dl-wd-head{display:flex;align-items:center;gap:12px;min-width:0}.dl-wd-head>.dl-stack{min-width:0}.dl-wd-title{font-size:16px;line-height:24px;font-weight:500}.dl-wd-tile{flex:none;width:36px;height:36px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-wd-tile.off{background:var(--dl-soft);color:var(--dl-fg-faint)}.dl-wd-tile .dl-icon{width:18px;height:18px}.dl-wd-foot{display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px;padding-top:14px;border-top:1px solid var(--dl-line)}.dl-wd-chips{display:flex;flex-wrap:wrap;gap:6px;flex:1 1 auto;min-width:0}.dl-wd-chips .dl-check-chip.error .dl-icon{color:var(--dl-bad)}.dl-warn-text{color:var(--dl-warn)!important}.dl-health-cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(440px,100%),1fr));gap:16px;align-items:start}.dl-health-cols>.dl-panel{margin:0;min-width:0}.dl-recent{display:flex;flex-direction:column}.dl-recent .dl-panel-head a{font-size:13px}.dl-recent-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:32px 16px;color:var(--dl-fg-muted);font-size:13px;border-top:1px solid var(--dl-line)}.dl-loading{margin:0;font-size:13px}.dl-diag-tabs{margin:0 0 16px}.dl-row.dl-slog-row{align-items:baseline}.dl-slog-row .dl-ev-tile{align-self:flex-start;margin-top:-1px}.dl-slog-row.has-detail{cursor:pointer}.dl-row.dl-slog-row.has-detail:hover{background:color-mix(in srgb,var(--sys) 11%,transparent)}.dl-slog-more{display:inline-flex;vertical-align:-2px;margin-left:6px;color:var(--dl-fg-faint);transform:rotate(90deg);transition:transform .15s}.dl-slog-more .dl-icon{width:14px;height:14px}.dl-slog-more.open{transform:rotate(-90deg)}.dl-slog-detail{margin:8px 0 2px;padding:8px 10px;border-radius:8px;background:var(--dl-soft);font-family:var(--dl-mono);font-size:12px;line-height:17px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--dl-fg-muted);cursor:text}.dl-table{width:100%;border-collapse:collapse;font-size:14px;line-height:20px}.dl-table th{text-align:left;font-weight:500;color:var(--dl-fg-faint);padding:0 8px 8px;border-bottom:1px solid var(--dl-line)}.dl-table td{padding:10px 8px;border-bottom:1px solid var(--dl-line);vertical-align:middle}.dl-table th:first-child,.dl-table td:first-child{padding-left:0}.dl-table th:last-child,.dl-table td:last-child{padding-right:0}.dl-table tr:last-child td{border-bottom:0}.dl-table .dl-right{text-align:right;white-space:nowrap}.dl-log{max-height:18em;overflow:auto;font-family:var(--dl-mono);font-size:12px;line-height:18px;margin:8px 0 0;padding:12px;white-space:pre-wrap;border-radius:12px;background:var(--dl-soft)}";var Pa=".dl-pagehead{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin:0 0 20px}.dl-h1{margin:0!important;padding:0!important;font-size:24px!important;line-height:32px!important;font-weight:500!important;border:0!important}.dl-title-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.dl-stack{display:flex;flex-direction:column;gap:2px;min-width:0}.dl-stack.gap4{gap:4px}.dl-stack.gap8{gap:8px}.dl-sub{font-size:12px;line-height:16px;color:var(--dl-fg-muted)}.dl-ok{color:var(--dl-ok)}.dl-warn{color:var(--dl-warn)}.dl-bad{color:var(--dl-bad)}.dl-icon-only{width:auto!important;min-width:0!important;aspect-ratio:1 / 1;padding:0!important;justify-content:center;display:inline-flex!important;align-items:center;border-radius:999px!important}.dl-panel.flush{padding:0;overflow:hidden}.dl-panel-head.pad{padding:16px 16px 12px;margin:0}.dl-col{display:flex;flex-direction:column;gap:16px;min-width:0}.dl-col>.dl-panel,.dl-col>section.dl-panel{margin:0}.dl-crumbs{display:flex;gap:8px;align-items:center;font-size:14px;margin:0 0 16px;color:var(--dl-fg-faint)}.dl-crumbs a{color:var(--dl-fg-faint)}.dl-crumbs a:hover{color:var(--dl-fg)}.dl-crumbs span:last-child{color:var(--dl-fg)}.dl-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);margin:0 0 16px;box-shadow:var(--dl-shadow)}.dl-metric{display:flex;flex-direction:column;gap:4px;padding:16px 20px;min-width:0}.dl-metric+.dl-metric{border-left:1px solid var(--dl-line)}.dl-metric-label{font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-metric-value{font-size:28px;line-height:36px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums;white-space:nowrap}.dl-metric-value .dl-faint{font-size:16px}.dl-metric-sub{font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@media(max-width:900px){.dl-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.dl-metric:nth-child(3){border-left:0}.dl-metric:nth-child(n+3){border-top:1px solid var(--dl-line)}}.dl-seg{display:inline-flex;gap:2px;padding:3px;border-radius:999px;background:var(--dl-soft);flex-wrap:wrap}.dl-seg button{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:6px;padding:4px 12px;border-radius:999px;font-size:13px;font-weight:500;color:var(--dl-fg-muted);white-space:nowrap}.dl-seg button:hover{color:var(--dl-fg)}.dl-seg button.on{background:var(--dl-soft-hover);color:var(--dl-fg)}.dl-seg.dl-srvsections{flex-wrap:nowrap;max-width:100%;overflow-x:auto;scrollbar-width:none}.dl-seg.dl-srvsections::-webkit-scrollbar{display:none}.dl-seg.dl-srvsections button{flex:none;white-space:nowrap}.dl-seg button:focus-visible{outline:2px solid var(--dl-ring)}.dl-seg button b{font-weight:500;font-size:11px;padding:0 6px;border-radius:999px;background:var(--dl-soft)}.dl-seg button b.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-seg.sm button{padding:2px 9px;font-size:11px}.dl-seg.wide{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));border-radius:12px;padding:4px}.dl-seg.wide button{flex-direction:column;justify-content:center;padding:8px 6px;border-radius:9px;gap:3px}.dl-seg.wide button.on{background:var(--dl-primary);color:var(--dl-primary-fg)}";var $a=`.dl-geomap{position:relative;border-top:1px solid var(--dl-line);background:transparent}.dl-map-status{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:var(--dl-fg-muted);font-size:13px;z-index:1;pointer-events:none}.dl-map-wrap{position:relative}.dl-map-legend{position:absolute;left:12px;bottom:12px;display:flex;gap:12px;align-items:center;padding:6px 12px;border-radius:999px;font-size:12px;background:color-mix(in srgb,var(--dl-card) 88%,transparent);border:1px solid var(--dl-line);backdrop-filter:blur(6px);z-index:2}.dl-map-legend span{display:inline-flex;align-items:center;gap:6px;color:var(--dl-fg-muted)}.dl-map-legend i.line{width:14px;height:0;border-top:2px dashed #8a8a8a}.dl-map-legend i.line.live{border-top-color:#3b82f6}.dl-map-off{padding:32px 16px;text-align:center;color:var(--dl-fg-muted);border-top:1px solid var(--dl-line)}.dl-mk{all:unset;cursor:pointer;position:relative;display:flex;align-items:center;justify-content:center;transition:opacity .2s}.dl-mk-hub{position:relative;display:flex;align-items:center;justify-content:center}.dl-mk-host{box-sizing:border-box;width:40px;height:40px;border-radius:11px;display:flex;align-items:center;justify-content:center;background:color-mix(in srgb,var(--dl-elevated) 60%,transparent);border:1px solid var(--dl-line);backdrop-filter:blur(6px);box-shadow:0 6px 16px #00000059}.dl-mk-host-tile{width:26px;height:26px;border-radius:7px;display:flex;align-items:center;justify-content:center;background:var(--dl-fg);color:var(--background, var(--dl-elevated))}.dl-mk-host-ic{width:14px;height:14px}.dl-mk-av{position:relative;box-sizing:border-box;width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:500;line-height:1;border:2px solid #8a8a8a;background:var(--dl-elevated);color:var(--dl-fg-muted);transition:box-shadow .2s}.dl-mk.online .dl-mk-av{border-color:#3b82f6;background:color-mix(in srgb,#3b82f6 22%,var(--dl-elevated));color:var(--dl-fg)}.dl-mk-badge{position:absolute;left:16px;bottom:-6px;height:16px;min-width:16px;padding:0 3px;border-radius:8px;border:2px solid var(--dl-elevated);background:#6b6b6b;color:#fff;display:flex;align-items:center;justify-content:center;gap:1px;font-size:9px;font-weight:600;white-space:nowrap;box-sizing:content-box}.dl-mk.online .dl-mk-badge{background:#3b82f6}.dl-mk-badge-ic{width:10px;height:10px;stroke-width:2.2}.dl-mk-badge:has(>svg:only-child){width:16px;min-width:0;padding:0}.dl-mk-tile{position:relative;width:26px;height:26px;border-radius:7px;display:flex;align-items:center;justify-content:center;background:color-mix(in srgb,var(--dl-fg) 18%,var(--dl-elevated));color:var(--dl-fg)}.dl-mk.place.online .dl-mk-tile{background:#3b82f6;color:#fff;box-shadow:0 2px 8px #3b82f659}.dl-mk-tile-ic{width:14px;height:14px}.dl-mk-tile-n{position:absolute;right:-5px;top:-5px;min-width:14px;height:14px;padding:0 3px;box-sizing:border-box;border-radius:7px;background:var(--dl-fg);color:var(--dl-elevated);font-size:9px;font-weight:600;line-height:14px;text-align:center}.dl-mk-when{display:block;text-align:center;color:var(--dl-fg-faint);font-weight:400}.dl-mk.place.online .dl-mk-when{color:#3b82f6}.dl-mk-tile.sm{width:18px;height:18px;border-radius:5px;font-size:9px;font-weight:600}.dl-dmap{border:1px solid var(--dl-line);border-radius:12px;overflow:hidden}.dl-dmap .dl-geomap{border-top:0}.dl-dplaces{display:flex;flex-direction:column;margin-top:4px}.dl-dplace-row{display:flex;align-items:center;gap:10px;padding:9px 2px;border-top:1px solid var(--dl-line);font-size:13px}.dl-dplace-row:first-child{border-top:0}.dl-dplace-n{flex:0 0 auto;width:20px;height:20px;border-radius:5px;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:600;background:color-mix(in srgb,var(--dl-fg) 18%,var(--dl-elevated));color:var(--dl-fg)}.dl-dplace-n.live{background:#3b82f6;color:#fff}.dl-dplace-n .dl-icon{width:12px;height:12px}.dl-dplace-now{color:#3b82f6}.dl-dplaces.strips .dl-dplace-row{position:relative;display:grid;grid-template-columns:20px minmax(0,1fr) auto;column-gap:10px;row-gap:9px;margin:0 -10px;padding:11px 10px;border-top:0;border-radius:10px;transition:background .15s}.dl-dplaces.strips .dl-dplace-row+.dl-dplace-row:before{content:"";position:absolute;left:10px;right:10px;top:0;height:1px;background:var(--dl-line)}.dl-dplaces.strips .dl-dplace-row:is(:hover,.cur){background:var(--dl-soft)}.dl-dplaces.strips .dl-dplace-row:is(:hover,.cur):before,.dl-dplaces.strips .dl-dplace-row:is(:hover,.cur)+.dl-dplace-row:before{opacity:0}.dl-dplace-strip{grid-column:2 / 4;position:relative;height:6px;border-radius:3px;background:var(--dl-track)}.dl-dplaces.can-replay .dl-dplace-strip{cursor:ew-resize;touch-action:none}.dl-dplace-strip i{position:absolute;top:0;bottom:0;min-width:2px;border-radius:2px;background:#8a8a8a}.dl-dplace-strip.live i{background:#3b82f6}.dl-dplaces.replay .dl-dplace-strip:after{content:"";position:absolute;left:var(--at);top:-4px;bottom:-4px;width:2px;margin-left:-1px;border-radius:1px;background:var(--dl-fg);box-shadow:0 0 0 2px var(--dialog-bg, var(--dl-elevated));pointer-events:none}.dl-dplace-axis{position:relative;height:16px;margin:4px 0 0 30px;font-size:11px;line-height:16px;color:var(--dl-fg-faint)}.dl-dplace-axis span{position:absolute;top:0;transform:translate(-50%);white-space:nowrap}.dl-dmap{position:relative}.dl-map-replay{position:absolute;left:10px;top:10px;z-index:3;display:flex;align-items:center;gap:6px}.dl-map-btn{all:unset;box-sizing:border-box;cursor:pointer;width:28px;height:28px;border-radius:8px;display:inline-flex;align-items:center;justify-content:center;background:var(--dl-elevated);border:1px solid var(--dl-line);color:var(--dl-fg)}.dl-map-btn:hover{background:color-mix(in srgb,var(--dl-fg) 8%,var(--dl-elevated))}.dl-map-btn:focus-visible{outline:2px solid var(--dl-ring)}.dl-map-btn .dl-icon{width:13px;height:13px}.dl-map-chip{display:inline-flex;align-items:center;height:28px;box-sizing:border-box;padding:0 10px;border-radius:8px;font-size:11.5px;white-space:nowrap;background:var(--dl-elevated);border:1px solid var(--dl-line);color:var(--dl-fg);font-variant-numeric:tabular-nums}.dl-mk.step .dl-mk-tile{transition:width .3s cubic-bezier(.2,.8,.2,1),height .3s cubic-bezier(.2,.8,.2,1),border-radius .3s,background-color .3s,color .3s,box-shadow .3s,transform .24s}.dl-mk.step .dl-mk-tile.sm .dl-mk-tile-ic{width:11px;height:11px}.dl-mk.step.faded>*{opacity:.5}.dl-mk.step:is(.online,.hl){z-index:2}.dl-mk.step.hl .dl-mk-tile{box-shadow:0 0 0 3px color-mix(in srgb,#3b82f6 55%,transparent)}.dl-mk.step.arrive .dl-mk-tile{animation:dl-mk-arrive .45s cubic-bezier(.2,.8,.2,1)}@keyframes dl-mk-arrive{0%{transform:scale(.8)}55%{transform:scale(1.12)}to{transform:scale(1)}}.dl-mk-when.inline{display:inline}.dl-mk>*{transition:opacity .15s;opacity:var(--dl-mk-fade, 1)}.dl-mk.merged,.dl-mk.piled{pointer-events:none}.dl-mk.dl-mk-new>*{transition:none}.dl-mk.merged>*,.dl-mk.piled>*{opacity:0}.dl-mk-hub{cursor:default}.dl-mk-host{position:relative}.dl-mk-host{transition:border-radius .22s ease,border-right-color .22s ease}.dl-mk-host.docked{border-top-right-radius:0;border-bottom-right-radius:0;border-right-color:transparent}.dl-mk-dock{position:absolute;left:100%;top:-1px;height:40px;box-sizing:border-box;display:flex;align-items:center;gap:6px;padding:0 10px 0 2px;border:1px solid var(--dl-line);border-left:0;border-radius:0 11px 11px 0;background:color-mix(in srgb,var(--dl-elevated) 60%,transparent);backdrop-filter:blur(6px);box-shadow:0 6px 16px #00000059;pointer-events:none;opacity:0;clip-path:inset(-24px 100% -24px 0);transition:clip-path .28s cubic-bezier(.2,.8,.2,1),opacity .2s ease}.dl-mk-host.docked .dl-mk-dock{pointer-events:auto;opacity:1;clip-path:inset(-24px -24px -24px 0)}.dl-mk-new .dl-mk-host,.dl-mk-new .dl-mk-dock{transition:none}.dl-mk-pile{position:relative;display:flex;justify-content:center}.dl-mk-pile-box{box-sizing:border-box;height:40px;display:flex;align-items:center;gap:6px;padding:0 10px 0 6px;border-radius:20px;cursor:zoom-in;background:color-mix(in srgb,var(--dl-elevated) 60%,transparent);border:1px solid var(--dl-line);backdrop-filter:blur(6px);box-shadow:0 6px 16px #00000059;animation:dl-plate-in .26s cubic-bezier(.2,.8,.2,1) both;transition:opacity .18s ease,transform .18s ease}.dl-mk-pile.out{pointer-events:none}.dl-mk-pile.out>*{opacity:0;transform:scale(.85);transition:opacity .18s ease,transform .18s ease}@keyframes dl-plate-in{0%{opacity:0;transform:scale(.85)}}.dl-mk-face{all:unset;position:relative;display:flex;cursor:pointer;transition:transform .18s ease,opacity .18s ease}.dl-mk-face>.dl-mk-badge{position:relative;left:auto;bottom:-8px;margin-left:-12px;align-self:center}.dl-mk-face.on .dl-mk-av{border-color:#3b82f6;background:color-mix(in srgb,#3b82f6 22%,var(--dl-elevated));color:var(--dl-fg)}.dl-mk-face.on .dl-mk-badge{background:#3b82f6}.dl-mk-face:hover .dl-mk-av{box-shadow:0 0 0 4px #3b82f640}.dl-mk-face.in{animation:dl-dock-in .24s cubic-bezier(.2,.8,.2,1) both}.dl-mk-face.out{transform:scale(.4);opacity:0;pointer-events:none}@keyframes dl-dock-in{0%{transform:scale(.4);opacity:0}}.dl-mk-more{font-size:11px;font-weight:600;color:var(--dl-fg-muted)}.dl-mk-av,.dl-mk-tile{transition:box-shadow .2s,transform .24s cubic-bezier(.2,.8,.2,1)}.dl-mk.merged .dl-mk-av,.dl-mk.merged .dl-mk-tile,.dl-mk.piled .dl-mk-av{transform:scale(.5)}.dl-mk-host,.dl-mk-dock,.dl-mk-pile-box{transition-property:border-radius,border-right-color,clip-path,opacity,height,width,padding,gap}.dl-mk-dock,.dl-mk-pile-box{transition-duration:.22s;transition-timing-function:cubic-bezier(.2,.8,.2,1)}.dl-mk-pile-box{position:relative}.dl-mk-more{transition:transform .22s cubic-bezier(.2,.8,.2,1),opacity .18s ease}.dl-mk-more.in{animation:dl-dock-in .24s ease both}.dl-mk-more.out{transform:scale(.4);opacity:0}.dl-mk-face .dl-mk-av{transition:box-shadow .2s,transform .24s cubic-bezier(.2,.8,.2,1),width .2s ease,height .2s ease,font-size .2s ease}.dl-mk-face{transition:transform .22s cubic-bezier(.2,.8,.2,1),opacity .18s ease,margin .2s ease}.dl-mk-face>.dl-mk-badge{max-width:48px;overflow:hidden;transition:opacity .2s ease,transform .2s ease,max-width .22s ease,margin .22s ease,padding .22s ease,border-width .22s ease,height .22s ease,min-width .22s ease,width .22s ease,bottom .22s ease}.dl-lod-far .dl-mk-host{width:32px;height:32px;border-radius:9px}.dl-lod-far .dl-mk-host.docked{border-radius:9px 0 0 9px}.dl-lod-far .dl-mk-host-tile{width:20px;height:20px;border-radius:6px}.dl-lod-far .dl-mk-host-ic{width:11px;height:11px}.dl-lod-far .dl-mk-dock{height:32px;gap:0;padding:0 4px 0 0;border-radius:0 9px 9px 0}.dl-lod-far .dl-mk-pile-box{height:32px;gap:0;padding:0 4px;border-radius:16px}.dl-lod-far .dl-mk-face+.dl-mk-face{margin-left:-6px}.dl-lod-far .dl-mk-face .dl-mk-av{width:22px;height:22px;font-size:8px;box-shadow:0 0 0 2px var(--dl-elevated)}.dl-lod-far .dl-mk-face>.dl-mk-badge{max-width:0;min-width:0;padding:0;margin-left:0;border-width:0;opacity:0;transform:scale(.5);pointer-events:none}.dl-lod-far .dl-mk-more{margin-left:4px;font-size:10px}.dl-mk-label{transition:opacity .2s ease}.dl-lod-far .dl-mk:not(.step) .dl-mk-label{opacity:0}.dl-lod-mid .dl-mk-host{width:36px;height:36px}.dl-lod-mid .dl-mk-dock,.dl-lod-mid .dl-mk-pile-box{height:36px}.dl-lod-mid .dl-mk-face .dl-mk-av{width:24px;height:24px;font-size:9px}.dl-lod-mid .dl-mk-face>.dl-mk-badge{height:12px;min-width:12px;margin-left:-10px;bottom:-7px}.dl-lod-mid .dl-mk-face>.dl-mk-badge:has(>svg:only-child){width:12px}.dl-lod-mid .dl-mk-face>.dl-mk-badge .dl-mk-badge-ic{width:8px;height:8px}@media(prefers-reduced-motion:reduce){.dl-mk-dock,.dl-mk-pile-box,.dl-mk-face,.dl-mk-av,.dl-mk-tile,.dl-mk.step .dl-mk-tile,.dl-mk-host,.dl-mk-face>.dl-mk-badge{transition:none;animation:none}}.dl-mk-hub:has(.dl-mk-host.docked) .dl-mk-host{cursor:zoom-in}.dl-mk-ptr{position:absolute;left:50%;top:50%;width:0;height:0;z-index:-1;pointer-events:none}.dl-mk-ptr .line{position:absolute;left:0;top:-.5px;height:1px;background:var(--dl-fg-faint);transform-origin:0 50%}.dl-mk-ptr .spot{position:absolute;left:-3.5px;top:-3.5px;width:7px;height:7px;border-radius:50%;box-sizing:border-box;border:1.5px solid #fff;background:#8a8a8a}.dl-mk.online .dl-mk-ptr .spot,.dl-mk.place.online .dl-mk-ptr .spot{background:#3b82f6}.dl-mk.dim>*{opacity:.18}.dl-mk.hl .dl-mk-av{box-shadow:0 0 0 4px #3b82f640}.dl-mk-label{position:absolute;left:50%;bottom:100%;margin-bottom:4px;transform:translate(-50%);white-space:nowrap;pointer-events:none;font-size:10px;line-height:14px;font-weight:500;color:var(--dl-fg)}.dl-mk-label.below{bottom:auto;top:100%;margin:4px 0 0}.dl-mk-label.chip{padding:2px 6px;border-radius:4px;font-size:11px;line-height:16px;font-weight:600;background:color-mix(in srgb,var(--background, var(--dl-card)) 80%,transparent);backdrop-filter:blur(8px)}.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact{margin:0 10px 10px 0;min-height:28px;padding:0;border-radius:8px;background:var(--dl-elevated);border:1px solid var(--dl-line);color:var(--dl-fg-muted);box-shadow:none;font-size:11px;line-height:26px}.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact:not(.maplibregl-compact-show){width:28px;height:28px;box-sizing:border-box}.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact.maplibregl-compact-show{padding:0 32px 0 10px}.dl-geomap .maplibregl-ctrl-attrib a{color:var(--dl-fg-muted)}.dl-geomap .maplibregl-ctrl-attrib-button{top:0;right:0;width:26px;height:26px;margin:0;border-radius:8px;background:none}.dl-geomap .maplibregl-ctrl-attrib-button:after{content:"";position:absolute;inset:5px;background:var(--dl-fg);-webkit-mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20Zm-1.2 8.2h2.4V17h-2.4v-6.8ZM12 6a1.4 1.4 0 1 0 0 2.8A1.4 1.4 0 0 0 12 6Z'/%3E%3C/svg%3E") center / contain no-repeat;mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20Zm-1.2 8.2h2.4V17h-2.4v-6.8ZM12 6a1.4 1.4 0 1 0 0 2.8A1.4 1.4 0 0 0 12 6Z'/%3E%3C/svg%3E") center / contain no-repeat}.dl-geomap .maplibregl-ctrl-attrib-button:focus{outline:none;box-shadow:none}.dl-geomap .maplibregl-ctrl-attrib-button:focus-visible{outline:2px solid var(--dl-ring)}.dl-map-card{position:absolute;right:12px;top:12px;z-index:3;min-width:200px;max-width:260px;padding:10px 12px;border-radius:10px;font-size:12px;line-height:20px;background:var(--dl-elevated);color:var(--dl-fg);border:1px solid var(--dl-line);box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));opacity:0;transition:opacity .2s;pointer-events:none}.dl-map-card.on{opacity:1}.dl-map-card-head b{font-weight:500}.dl-map-card-row{display:flex;justify-content:space-between;gap:12px;white-space:nowrap}.dl-popcard{position:fixed;z-index:2100;width:max-content;max-width:300px;padding:12px;border-radius:12px;box-sizing:border-box;background:var(--dl-elevated);color:var(--dl-fg);border:1px solid var(--dl-line);box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4))}.dl-popcard.away{visibility:hidden}.dl-popcard.leaving{pointer-events:none}.dl-popcard-tip{position:absolute;left:var(--tip-x, 50%);width:10px;height:10px;margin-left:-6px;box-sizing:border-box;background:var(--dl-elevated);border:solid var(--dl-line);transform:rotate(45deg)}.dl-popcard.above .dl-popcard-tip{bottom:-6px;border-width:0 1px 1px 0}.dl-popcard.below .dl-popcard-tip{top:-6px;border-width:1px 0 0 1px}.dl-popcard.above{transform-origin:var(--tip-x, 50%) 100%}.dl-popcard.below{transform-origin:var(--tip-x, 50%) 0}@media(prefers-reduced-motion:no-preference){.dl-popcard{animation:dl-pop-in .16s ease-out}.dl-popcard.leaving{animation:dl-pop-out .14s ease-in forwards}}@keyframes dl-pop-in{0%{opacity:0;transform:scale(.94)}to{opacity:1;transform:none}}@keyframes dl-pop-out{0%{opacity:1;transform:none}to{opacity:0;transform:scale(.94)}}.dl-pop{display:flex;flex-direction:column;gap:4px;font-size:12px;line-height:18px;min-width:210px}.dl-pop-head{display:flex;align-items:center;gap:8px;font-size:13px;margin-bottom:2px}.dl-pop-net{width:30px;height:30px;border-radius:9px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-pop-list{display:flex;flex-direction:column;margin:6px 0 0;max-height:116px;overflow-y:auto}.dl-pop-row{all:unset;cursor:pointer;display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:8px}.dl-pop-row:hover{background:var(--dl-soft)}.dl-pop-row:focus{outline:none}.dl-pop-row:focus-visible{outline:2px solid var(--dl-ring)}.dl-pop-name{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-pop-name b{font-weight:500}.dl-pop-dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);flex:0 0 auto}.dl-pop-dot.on{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-pop-actions{display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid var(--dl-line)}.dl-pop-actions .cbi-button{flex:1;height:28px!important;font-size:12px!important;justify-content:center}.dl-chartbox{position:relative}.dl-bars{display:flex;align-items:flex-end;gap:4px;border-bottom:1px solid var(--dl-line)}.dl-bar{flex:1;height:100%;display:flex;flex-direction:column-reverse;gap:1px;cursor:default;min-width:3px}.dl-bar i{display:block;border-radius:3px 3px 0 0}.dl-bar i.down{background:var(--dl-chart-1)}.dl-bar i.up{background:var(--dl-chart-2);opacity:.75;border-radius:3px 3px 0 0}.dl-bar:hover i{filter:brightness(1.25)}.dl-bar.empty{background:linear-gradient(to top,var(--dl-line) 2px,transparent 2px)}.dl-tip{position:absolute;top:-8px;transform:translate(-50%,-100%);padding:8px 10px;border-radius:10px;font-size:12px;line-height:18px;white-space:nowrap;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));pointer-events:none;z-index:3}.dl-tip-title{font-weight:500}.dl-tip-float{position:fixed;z-index:2000;color:var(--dl-fg)}.dl-meter,.dl-slots{cursor:default}.dl-axis{display:flex;justify-content:space-between;font-size:12px;color:var(--dl-fg-faint);margin-top:6px}.dl-legend i.down{background:var(--dl-chart-1)}.dl-legend i.up{background:var(--dl-chart-2)}.dl-spark{display:flex;align-items:flex-end;flex:0 0 auto;--dl-gap: 2px}.dl-spark i{flex:1;display:block;border-radius:2px 2px 0 0;background:var(--dl-chart-1);opacity:.85}.dl-spark i.zero{opacity:.22}.dl-spark>span:hover i:not(.zero){opacity:1;filter:brightness(1.25)}.dl-spark>span,.dl-dbars>span,.dl-bento-bars>span{flex:1;min-width:0;height:100%;display:flex;align-items:flex-end;padding:0 calc(var(--dl-gap) / 2)}.dl-spark>span:first-child,.dl-dbars>span:first-child,.dl-bento-bars>span:first-child{padding-left:0}.dl-spark>span:last-child,.dl-dbars>span:last-child,.dl-bento-bars>span:last-child{padding-right:0}`;var Da=`.dl-row{display:flex;align-items:center;gap:12px;padding:12px 16px;border-top:1px solid var(--dl-line);font-size:14px;line-height:20px;min-width:0}.dl-row.link{color:inherit;text-decoration:none}.dl-row.link:hover{background:var(--dl-soft)}.dl-row-main{flex:1;min-width:0;overflow-wrap:anywhere}.dl-row-main b{font-weight:500}.dl-attn{display:flex;flex-direction:column;gap:10px;padding:16px;border-top:1px solid var(--dl-line)}.dl-attn-item{display:flex;gap:10px;align-items:baseline;font-size:13px;color:var(--dl-fg-muted)}.dl-avatar.sm{width:26px;height:26px;font-size:10px;margin:0}.dl-avatar.lg{width:48px;height:48px;font-size:15px;margin:0}.dl-avatar.lg.online:after{width:12px;height:12px}.dl-list{border:1px solid var(--dl-line);border-radius:12px;overflow:hidden}.dl-list>.dl-row:first-child{border-top:0}.dl-ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-row-main.dl-stack{min-width:0}.dl-person-id{display:flex;align-items:center;gap:14px;min-width:0}.dl-grid-person{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);gap:16px;align-items:start}@media(max-width:1000px){.dl-grid-person{grid-template-columns:minmax(0,1fr)}}.dl-devsec{display:flex;flex-direction:column;gap:12px}.dl-devsec .dl-panel-head{margin:0}.dl-dgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.dl-dcard>.dl-dcard-head+*{margin-top:auto}@media(max-width:700px){.dl-dgrid{grid-template-columns:minmax(0,1fr)}}.dl-dgrid>.dl-dslot.add:only-child{grid-column:1 / -1}.dl-dcard{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:12px;min-width:0;box-shadow:var(--dl-shadow)}.dl-dcard.online{border-color:color-mix(in srgb,var(--dl-ok) 35%,transparent)}.dl-dcard.off{opacity:.7}.dl-dcard-head{display:flex;align-items:center;gap:12px}.dl-dcard-ic{width:40px;height:40px;border-radius:12px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-dcard-ic .dl-icon{width:20px;height:20px}.dl-dcard.online .dl-dcard-ic{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-dcard-title{all:unset;cursor:pointer;flex:1;min-width:0;display:flex;flex-direction:column}.dl-dcard-title b{font-weight:500;font-size:15px}.dl-dstat{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;min-width:0}.dl-dstat i.dot{flex:none}.dl-dstat.ok{color:var(--dl-ok)}.dl-dstat.warn{color:var(--dl-warn)}.dl-dstat i.dot,.dl-savebar i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint)}.dl-dstat i.dot.ok{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-dstat i.dot.warn{background:var(--dl-warn)}.dl-dcard-use{display:flex;align-items:flex-end;justify-content:space-between;gap:12px}.dl-dcard-foot{padding-top:10px;border-top:1px solid var(--dl-line);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-dslot.add{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:14px;min-height:0;border:1px dashed color-mix(in srgb,currentColor 18%,transparent);border-radius:14px;text-align:center;color:var(--dl-fg-muted);transition:background .15s,border-color .15s,color .15s}.dl-dslot.add .dl-stack{align-items:center}.dl-dslot.add:hover{border-color:color-mix(in srgb,currentColor 35%,transparent);color:var(--dl-fg)}.dl-dslot.add:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-dslot.add b{font-weight:500}.dl-dslot.add:hover{background:var(--dl-soft)}.dl-dslot-ic{width:36px;height:36px;border-radius:999px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-dslot.add:hover .dl-dslot-ic{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-tiles2{display:grid;gap:10px;margin-top:16px}.dl-tile2{border:1px solid var(--dl-line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:10px;min-width:0}.dl-tile2-label{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-tile2-row{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}.dl-tile2-value{font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums}.dl-tile2-value .dl-faint{font-size:14px;font-weight:400}.dl-tile2-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-top:10px;border-top:1px solid var(--dl-line);font-size:12px}.dl-stepper{display:inline-flex;align-items:stretch;height:32px;border:1px solid var(--input, var(--dl-line));border-radius:8px;overflow:hidden}.dl-stepper button{all:unset;cursor:pointer;width:32px;display:inline-flex;align-items:center;justify-content:center;font-size:16px;color:var(--dl-fg)}.dl-stepper button:hover{background:var(--dl-soft)}.dl-stepper button[disabled]{opacity:.35;cursor:not-allowed}.dl-stepper+.dl-stepper{margin-left:4px}.dl-step-select{border:0!important;border-left:1px solid var(--input, var(--dl-line))!important;border-right:1px solid var(--input, var(--dl-line))!important;border-radius:0!important;background:transparent!important;color:inherit;font:500 13px inherit;padding:0 10px!important;height:100%!important;min-width:0!important}.dl-slots{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:3px}.dl-slots i{height:4px;border-radius:999px;background:var(--dl-track);display:block}.dl-slots i.used{background:var(--dl-fg)}.dl-slots i.over{background:color-mix(in srgb,var(--dl-warn) 80%,transparent)}.dl-date{display:flex;align-items:center;gap:8px;flex:1 1 150px;min-width:0;box-sizing:border-box;height:34px;padding:0 10px;border:1px solid var(--input, var(--dl-line));border-radius:8px;color:var(--dl-fg-faint)}.dl-date input{border:0!important;background:transparent!important;box-shadow:none!important;padding:0!important;height:32px!important;color:var(--dl-fg);flex:1;min-width:0!important;width:100%!important}.dl-meter{position:relative;height:6px;border-radius:999px;background:var(--dl-track)}.dl-meter>i{display:block;height:100%;border-radius:999px;background:var(--dl-accent)}.dl-meter.warn>i{background:var(--dl-warn)}.dl-meter.bad>i{background:var(--dl-bad)}.dl-meter .mark{position:absolute;left:90%;top:-3px;width:1px;height:12px;background:var(--dl-warn)}.dl-meter.sm{height:4px}.dl-chips-row{display:flex;flex-wrap:wrap;gap:4px}.dl-chipbtn{all:unset;cursor:pointer;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-soft);font-size:12px;font-weight:500;display:inline-flex;align-items:center}.dl-chipbtn:hover{background:var(--dl-soft-hover)}.dl-chipbtn.on{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-switch{all:unset;cursor:pointer;position:relative;width:32px;height:20px;border-radius:999px;background:var(--switch-off, var(--dl-track));flex:0 0 auto;transition:background .15s}.dl-switch i{position:absolute;left:2px;top:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:left .15s;box-shadow:0 1px 2px #0000004d}.dl-switch.on{background:var(--dl-accent)}.dl-switch.on i{left:14px}.dl-switch:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-linkbox{display:flex;align-items:center;gap:8px;height:36px;padding:0 4px 0 12px;border:1px solid var(--input, var(--dl-line));border-radius:8px;background:var(--input-bg, transparent)}.dl-linkbox .dl-mono{flex:1;min-width:0;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dl-fg-muted)}.dl-linkbox .cbi-button{height:28px!important}.dl-pcard{display:grid;grid-template-columns:minmax(0,1fr) 260px;gap:20px;align-items:stretch;min-width:0}.dl-pcard-main{min-width:0}.dl-pcard-top{display:flex;align-items:center;gap:12px;min-width:0}.dl-pcard-top .dl-avatar{margin-right:0}.dl-pcard-who{flex:1;min-width:0}.dl-pcard-who .dl-slotbar{margin:3px 0 0}.dl-pside{display:flex;flex-direction:column;justify-content:space-between;gap:8px;padding-left:20px;border-left:1px solid var(--dl-line);min-width:0}.dl-pside-top{display:flex;align-items:center;justify-content:space-between;gap:8px}.dl-pside-state{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--dl-fg-muted)}.dl-pside-state.live{color:var(--dl-ok)}.dl-pside-foot{font-size:12px}.dl-pside .dl-use-num b{font-size:20px}.dl-none{display:none!important}.dl-pcard-actions{display:flex;gap:6px;flex:0 0 auto}.dl-pcard-actions .cbi-button{height:32px!important}.dl-icon-only .dl-btn-label{display:none}.dl-pill-ic{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0 8px;border-radius:999px;font-size:12px;white-space:nowrap;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pill-ic .dl-icon{width:12px;height:12px}.dl-pill-ic.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-pill-ic.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-use-num{display:flex;align-items:baseline;gap:6px;white-space:nowrap}.dl-use-num b{font-size:15px;font-weight:500}.dl-use-live{display:flex;align-items:center;gap:8px;font-size:12px;font-variant-numeric:tabular-nums}.dl-usebar{display:flex;gap:2px;height:6px;border-radius:999px;overflow:hidden;background:var(--dl-track)}.dl-usebar i{display:block;height:100%;min-width:3px;flex:0 1 0}.dl-usebar i.fill{flex:none;min-width:0;border-radius:999px;background:var(--dl-accent)}.dl-usebar.warn i.fill{background:var(--dl-warn)}.dl-usebar.bad i.fill{background:var(--dl-bad)}.dl-usebar .c0,.dl-swatch.c0{background:var(--dl-chart-1)}.dl-usebar .c1,.dl-swatch.c1{background:#8b7cf6}.dl-usebar .c2,.dl-swatch.c2{background:#2fb889}.dl-usebar .c3,.dl-swatch.c3{background:#d9a03f}.dl-usebar .c4,.dl-swatch.c4{background:var(--dl-fg-faint)}.dl-tip-row{display:flex;align-items:center;gap:8px;min-width:160px}.dl-tip-row b{margin-left:auto;font-weight:500}.dl-swatch{width:8px;height:8px;border-radius:2px;flex:none}.dl-card-name{color:var(--dl-fg)!important;text-decoration:none}.dl-card-name:hover{text-decoration:underline}.dl-chip-tag{font-size:11px;line-height:18px;padding:0 6px;border-radius:999px;background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-chip.live{background:var(--dl-ok-wash);color:color-mix(in srgb,var(--dl-ok) 35%,var(--dl-fg))}.dl-chip.live:hover{background:color-mix(in srgb,var(--dl-ok) 22%,transparent)}.dl-chip.live .dl-icon{color:var(--dl-ok)}.dl-fixes{display:flex;gap:6px;flex-wrap:wrap;margin:10px 0 0 44px}.dl-fix{all:unset;cursor:pointer;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-info-wash);color:var(--dl-info);font-size:12px;font-weight:500;display:inline-flex;align-items:center}.dl-fix:hover{filter:brightness(1.15)}@media(max-width:760px){.dl-pcard{grid-template-columns:1fr}.dl-pside{padding:12px 0 0;border-left:0;border-top:1px solid var(--dl-line)}.dl-fixes{margin-left:0}}.dl-select{height:34px!important;border-radius:999px!important;min-width:136px!important;width:auto!important;padding:0 34px 0 14px!important;appearance:none!important;-webkit-appearance:none!important;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238b8f98' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")!important;background-repeat:no-repeat!important;background-position:right 12px center!important;background-size:14px!important}.dl-savebar{position:fixed;left:50%;bottom:24px;transform:translate(-50%,160%);opacity:0;transition:transform .25s cubic-bezier(.2,.8,.2,1),opacity .2s;display:flex;align-items:center;gap:10px;padding:8px 8px 8px 18px;border-radius:999px;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:var(--shadow-2xl, 0 16px 32px -8px rgba(0,0,0,.5));z-index:60;pointer-events:none}.dl-savebar.show{transform:translate(-50%);opacity:1;pointer-events:auto}.dl-savebar-text{display:inline-flex;align-items:center;gap:8px;font-size:13px;font-weight:500}`;var Aa=".dl-toast strong{display:block;font-weight:500}.dl-toast div{opacity:.8;font-size:13px}.dl-drawer-overlay{position:fixed;inset:0;z-index:900;display:flex;justify-content:flex-end;background:transparent;transition:background .2s}.dl-drawer-overlay.open{background:var(--scrim, rgba(0,0,0,.45))}.dl-drawer{width:min(520px,100%);height:100%;display:flex;flex-direction:column;background:var(--dialog-bg, var(--dl-elevated));color:var(--dl-fg);border-left:1px solid var(--dl-line);box-shadow:var(--shadow-2xl, -16px 0 32px -8px rgba(0,0,0,.5));transform:translate(100%);transition:transform .22s cubic-bezier(.2,.8,.2,1)}.dl-drawer-overlay.open .dl-drawer{transform:none}.dl-drawer-head{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid var(--dl-line)}.dl-drawer-title{flex:1;min-width:0;display:flex;align-items:center;gap:12px}.dl-drawer-title h3{margin:0!important;padding:0!important;border:0!important;font-size:18px!important;line-height:26px;font-weight:500!important}.dl-drawer-x{all:unset;cursor:pointer;width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:var(--dl-fg-muted)}.dl-drawer-x:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-drawer-body{flex:1;overflow:auto;padding:20px}.dl-drawer-foot{padding:12px 20px;border-top:1px solid var(--dl-line)}.dl-drawer-actions{display:flex;align-items:center;gap:8px}.dl-dcard-ic.on{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-icon-only.sm{width:28px;height:28px!important}.dl-stack.gap12{gap:12px}.dl-stack.gap16{gap:16px}.dl-dstats{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid var(--dl-line);border-radius:14px;overflow:hidden}.dl-dstats-cell{display:flex;flex-direction:column;gap:4px;padding:12px 14px;min-width:0}.dl-dstats-cell.wide{grid-column:span 2;border-bottom:1px solid var(--dl-line)}.dl-dstats-cell+.dl-dstats-cell:not(.wide):last-child{border-left:1px solid var(--dl-line)}.dl-dstats-cell b{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}.dl-dstats-cell .dl-dstat{font-size:14px}.dl-dsec{border:1px solid var(--dl-line);border-radius:14px;padding:16px;display:flex;flex-direction:column;gap:12px}.dl-dsec-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.dl-dsec-head h4{margin:0!important;padding:0!important;font-size:14px!important;font-weight:500!important;border:0!important}.dl-dstat i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);display:inline-block}.dl-connect-body{min-height:60px}.dl-connect-body .dl-qr{width:min(240px,70vw)}.dl-kv2{display:flex;flex-direction:column}.dl-kvrow{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:9px 0;border-top:1px solid var(--dl-line);font-size:13px;min-width:0}.dl-kvrow:first-child{border-top:0;padding-top:0}.dl-kvrow-k{color:var(--dl-fg-muted);flex:0 0 auto}.dl-kvrow-v{min-width:0;text-align:right;overflow-wrap:anywhere}.dl-kvrow-v.copy{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:6px;min-width:0;color:var(--dl-fg)}.dl-kvrow-v.copy span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-kvrow-v.copy .dl-icon{width:13px;height:13px;color:var(--dl-fg-faint)}.dl-kvrow-v.copy:hover .dl-icon{color:var(--dl-fg)}@media(max-width:560px){.dl-drawer{width:100%}.dl-dstats{grid-template-columns:minmax(0,1fr)}.dl-dstats-cell.wide{grid-column:auto}.dl-dstats-cell+.dl-dstats-cell:not(.wide):last-child{border-left:0;border-top:1px solid var(--dl-line)}}.dl-dev-log{display:flex;flex-direction:column}.dl-dev-log-row{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--dl-line);font-size:13px;line-height:20px;min-width:0}.dl-dev-log-row:first-child{border-top:0;padding-top:0}.dl-dev-log-row .dl-row-main{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}";var Na=".dl-settings-main{min-width:0;display:flex;flex-direction:column;gap:20px}.dl-setsec{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);overflow:hidden;scroll-margin-top:88px;box-shadow:var(--dl-shadow)}.dl-setsec-body{padding:20px;display:flex;flex-direction:column;gap:14px}.dl-setsec-body h3{margin:0!important;padding:0!important;font-size:18px!important;line-height:26px;font-weight:500!important;border:0!important}.dl-setsec-body p{margin:0}.dl-setsec-head{display:flex;align-items:center;gap:10px}.dl-group{border:1px solid var(--dl-line);border-radius:14px;padding:2px 16px}.dl-group-head{display:flex;align-items:center;gap:12px;padding:14px 0 10px}.dl-group-head b{font-size:15px;font-weight:500}.dl-group-ic{width:32px;height:32px;border-radius:10px;background:var(--dl-soft);color:var(--dl-fg-muted);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-group-ic .dl-icon-wrap{display:inline-flex}.dl-group-ic .dl-icon{width:16px;height:16px}.dl-group-body>*{padding:12px 0;margin:0!important}.dl-group-body>*+*:not(.alert-message):not(.dl-params):not(.dl-note){border-top:1px solid var(--dl-line)}.dl-group-body>.alert-message,.dl-group-body>.dl-params{margin:12px 0!important}.dl-group-body>.alert-message{padding:10px 14px}.dl-group-body>.dl-params{padding:0}.dl-group-body>.dl-note{margin:0 0 14px!important;padding:10px 12px}.dl-group-body>.alert-message+*,.dl-group-body>.dl-params+*,.dl-group-body>.dl-note+*{border-top:0}.dl-group-body>.dl-row{border-left:0;border-right:0;border-bottom:0;padding-left:0;padding-right:0;background:none}.dl-group-body>.dl-row:first-child{border-top:0}.dl-setsec-foot{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 16px;padding:12px 20px;border-top:1px solid var(--dl-line);background:var(--dl-soft)}.dl-setsec.danger{border-color:color-mix(in srgb,var(--dl-bad) 40%,transparent)}.dl-setsec.danger .dl-setsec-foot{background:color-mix(in srgb,var(--dl-bad) 6%,transparent)}.dl-setrow{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,420px);align-items:center;gap:8px 24px}.dl-setrow.head{display:flex;justify-content:space-between;gap:16px}.dl-setrow-label{font-size:14px;font-weight:500}.dl-setrow-ctl{display:flex;justify-content:flex-end;min-width:0}.dl-setrow-ctl .dl-chips-row{justify-content:flex-end}.dl-setrow-ctl>input{width:100%}.dl-hostport{display:flex;align-items:center;gap:8px;flex:1;min-width:0;justify-content:flex-end}.dl-hostport input{flex:1;min-width:0}.dl-root input.dl-w-port,.dl-hostport input.dl-w-port{flex:0 0 90px;width:90px}.dl-root input.dl-w-range{flex:0 0 130px;width:130px}.dl-setrow .dl-sub.bad{color:var(--dl-bad)}.dl-suffixed{display:inline-flex;align-items:center;gap:6px}.dl-suffixed>span{color:var(--dl-fg-muted)}.dl-more summary{cursor:pointer;color:var(--dl-fg-muted);font-size:13px;margin-bottom:10px}.dl-more .dl-setrow+.dl-setrow{margin-top:10px}@media(max-width:760px){.dl-setrow:not(.head){grid-template-columns:minmax(0,1fr)}.dl-setrow-ctl,.dl-setrow-ctl .dl-chips-row{justify-content:flex-start}}.dl-need-ic{width:30px;height:30px;border-radius:9px;background:var(--dl-soft);color:var(--dl-fg-muted);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-need-ic .dl-icon-wrap{display:inline-flex}.dl-need-ic .dl-icon{width:15px;height:15px}.dl-need-row.bad .dl-need-ic,.dl-need-ic.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-need-row.warn .dl-need-ic,.dl-need-ic.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-need-ic.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-lh-main{display:flex;align-items:flex-start;gap:12px;min-width:0}.dl-lh-main>.dl-need-ic{margin-top:1px}.dl-sub .dl-mono{font-size:.92em}.dl-need-row>.cbi-button{flex:none}.dl-bk-row .dl-group-ic{width:30px;height:30px}.dl-bk-older>summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:8px;padding:11px 16px;border-top:1px solid var(--dl-line);font-size:13px;color:var(--dl-fg-muted);user-select:none}.dl-bk-older>summary::-webkit-details-marker{display:none}.dl-bk-older>summary:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-bk-older>summary .dl-icon-wrap{display:inline-flex;transition:transform .15s}.dl-bk-older>summary .dl-icon{width:14px;height:14px}.dl-bk-older[open]>summary .dl-icon-wrap{transform:rotate(90deg)}#dl-set-backups .dl-setsec-head h3+.dl-sub{margin-top:2px}#dl-set-backups .dl-setsec-foot>.dl-sub{flex:1 1 260px}.dl-bk-actions{flex:0 1 auto;justify-content:flex-end}@media(max-width:640px){#dl-set-backups .dl-setsec-foot>.dl-sub{flex-basis:100%}.dl-bk-actions{justify-content:flex-start}}.dl-upd{display:flex;flex-direction:column;gap:16px}.dl-upd>.dl-pagehead{margin:0 0 4px}.dl-upd-bad{color:var(--dl-bad)}";var Ha=".dl-comp-hero{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1fr)}.dl-comp-hero-main{padding:20px;display:flex;flex-direction:column;gap:12px;min-width:0}.dl-comp-hero-side{padding:20px;border-left:1px solid var(--dl-line);display:flex;flex-direction:column;gap:14px;min-width:0}.dl-comp-name{font-size:16px;font-weight:500}.dl-comp-hero-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap;min-width:0}.dl-comp-hero-head .dl-spacer{flex:1}.dl-comp-big{font-family:var(--dl-mono);font-size:26px;line-height:34px;letter-spacing:-.02em;display:flex;align-items:baseline;gap:10px}.dl-comp-big small{font-size:14px;color:var(--dl-accent)}.dl-comp-big small.dl-faint{color:var(--dl-fg-faint)}.dl-comp-verrow{display:flex;align-items:center;gap:4px 12px;flex-wrap:wrap;min-width:0}.dl-comp-verrow .dl-spacer{flex:1}.dl-comp-meta{font-size:13px}.dl-comp-bullets{margin:0;padding-left:18px;display:flex;flex-direction:column;gap:4px;color:var(--dl-fg-muted);font-size:13px}.dl-comp-bullets li{list-style:disc}.dl-comp-lead{margin:0}.dl-comp-more{align-self:flex-start;font-size:12px;color:var(--dl-fg-faint);margin-left:18px;padding:0!important}.dl-comp-more:hover{color:var(--dl-accent);background:none!important;text-decoration:underline;text-underline-offset:2px}.dl-comp-hero-main>.dl-comp-vers{margin-top:auto}.dl-comp-btns{display:flex;gap:8px;flex-wrap:nowrap;align-items:center;flex:none}.dl-comp-side-v{display:flex;align-items:center;gap:8px;font-size:14px;min-width:0;flex-wrap:wrap}.dl-comp-side-v .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted)}.dl-comp-side-v a{color:inherit;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-side-v a:hover{color:var(--dl-accent)}.dl-comp-cols{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1fr);gap:16px;align-items:start}.dl-comp-cols>.dl-panel>div>.dl-row:first-child{border-top:1px solid var(--dl-line)}.dl-comp-count{font-size:13px}.dl-comp-sub{font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-ic{display:inline-flex;gap:4px;flex:none}.dl-comp-ic .cbi-button{width:30px;height:30px;padding:0!important;justify-content:center;border-radius:999px!important}.dl-comp-ic .dl-btn-label{display:none}.dl-comp-ic .dl-icon{width:14px;height:14px}.dl-comp-ic .is-busy{pointer-events:none;opacity:.5}.dl-comp-ic .cbi-button.dl-comp-check{width:auto;padding:0 12px 0 10px!important;gap:6px;display:inline-flex;align-items:center;font-size:13px}.dl-row>.dl-pill,.dl-row>.cbi-button,.dl-row>.dl-comp-ic{flex:none}button.dl-pill.dl-comp-run{all:unset;display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:999px;font-size:12px;cursor:pointer;background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent)}.dl-comp-foldwrap{padding:0 16px 14px 60px}.dl-comp-fold .dl-params-body{gap:12px}.dl-comp-fold .dl-list>.dl-row{padding:10px 14px}.dl-comp-bver{font-size:12px;width:130px;text-align:right;flex:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-bact{width:84px;flex:none;display:flex;justify-content:flex-end}.dl-comp-warn{display:flex;align-items:flex-start;gap:8px;font-size:12px;line-height:18px;color:var(--dl-fg-muted)}.dl-comp-warn .dl-icon-wrap{display:inline-flex;flex:none;margin-top:2px}.dl-comp-warn .dl-icon{width:14px;height:14px;color:var(--dl-warn)}.dl-comp-empty{margin:0;padding:4px 16px 16px}@media(max-width:760px){.dl-comp-hero,.dl-comp-cols{grid-template-columns:minmax(0,1fr)}.dl-comp-hero-side{border-left:0;border-top:1px solid var(--dl-line)}.dl-comp-foldwrap{padding-left:16px}.dl-comp-bver{display:none}}.dl-comp-status{display:flex;align-items:center;gap:8px;font-size:13px;padding:9px 12px;border-radius:10px;background:var(--dl-soft);min-width:0}.dl-comp-status>.dl-icon-wrap{display:inline-flex;flex:none}.dl-comp-status .dl-icon{width:15px;height:15px}.dl-comp-status.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-comp-status.acc{background:color-mix(in srgb,var(--dl-accent) 12%,transparent);color:var(--dl-accent)}.dl-comp-status.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-comp-status.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-comp-status b{font-weight:600}.dl-comp-vers .dl-params-body{gap:0;padding:4px 14px 12px}.dl-comp-tag{display:flex;gap:6px;padding:6px 0 10px}.dl-comp-tag input{flex:1;min-width:0}.dl-comp-ver{display:flex;align-items:center;gap:8px;padding:7px 0;border-top:1px solid var(--dl-line);font-size:13px}.dl-comp-ver .dl-mono{min-width:52px}.dl-comp-ver .dl-sub{flex:1}.dl-comp-ver .cbi-button:not(.dl-icon-btn){height:26px!important;font-size:12px!important}.dl-comp-pager{display:flex;align-items:center;justify-content:space-between;padding-top:10px;border-top:1px solid var(--dl-line);font-size:12px}.dl-comp-pager .dl-linkbtn[disabled]{opacity:.4;cursor:default}.dl-comp-vers .dl-loading,.dl-comp-vers .dl-params-body>p{padding:6px 0 10px}.dl-op-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:14px}.dl-op-head .dl-spacer{flex:1}.dl-op-timer{display:inline-flex;align-items:center;gap:5px;font-variant-numeric:tabular-nums}.dl-op-timer .dl-icon,.dl-op-head .dl-linkbtn .dl-icon{width:14px;height:14px}.dl-op-loghead{display:flex;align-items:center;justify-content:space-between}.dl-op-loghead b{font-weight:500;font-size:13px}.dl-op .dl-log{max-height:16em;min-height:12em;margin-top:8px}.dl-op .dl-comp-status{margin:14px 0 0}.dl-op-actions{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap;width:100%}.dl-notes{max-height:55vh;overflow:auto;border-radius:12px;background:var(--dl-soft);padding:14px 16px;font-size:13px;line-height:20px;overflow-wrap:anywhere}.dl-notes h5{margin:10px 0 6px;font-size:14px;font-weight:500}.dl-notes h5:first-child{margin-top:0}.dl-notes p{margin:0 0 8px}.dl-notes ul{margin:0 0 10px;padding-left:18px}.dl-notes li{list-style:disc}.dl-notes code{font-family:var(--dl-mono);font-size:12px;padding:1px 5px;border-radius:6px;background:var(--dl-soft-hover)}.dl-notes pre{font-family:var(--dl-mono);font-size:12px;padding:10px;border-radius:8px;background:var(--dl-soft-hover);white-space:pre-wrap;margin:0 0 10px}.dl-notes a{color:var(--dl-accent)}";var za=".dl-chip.static{cursor:default}.dl-chip.static:hover{background:var(--dl-soft)}.dl-chip.static .dl-chip-name{font-weight:500}.dl-setrow.head .dl-chips-row,.dl-setrow.head .dl-note{margin-top:8px}.dl-setrow.head .dl-note{margin-bottom:0}.dl-setrow.head>.dl-lh-main,.dl-setrow.head>.dl-lh-main>.dl-stack{flex:1 1 auto;min-width:0}.dl-setrow.head>.dl-setrow-ctl:empty{display:none}.dl-setrow.head:has(>.dl-lh-main){align-items:flex-start}.dl-setrow.head>.dl-setrow-ctl{align-items:center;min-height:30px}.dl-netpick{margin-top:10px}.dl-boxrow{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:0;padding:10px 14px;border:1px solid var(--dl-line);border-radius:12px;font-size:13px;cursor:pointer}.dl-boxrow>.dl-switch{flex:none}.dl-ifpick{display:flex;flex-direction:column;gap:12px;padding:14px;border:1px solid var(--dl-line);border-radius:14px}.dl-iflead-row{display:flex;align-items:center;justify-content:space-between;gap:12px}.dl-host{align-items:flex-start}.dl-host>.dl-icon-wrap{margin-top:13px}.dl-host-body{flex:1;min-width:0;display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px}.dl-host-body>.dl-row-main{flex:1 1 160px}.dl-circle-dot{display:inline-block;width:8px;height:8px;border-radius:50%;flex:none}.dl-circles .dl-chip b{font-weight:500}.dl-circle-name{display:inline-flex;align-items:center;gap:8px;font-size:14px;font-weight:500}.dl-w400{font-weight:400}.dl-swatches{display:flex;flex-wrap:wrap;gap:8px}.dl-swatch{all:unset;cursor:pointer;width:22px;height:22px;border-radius:50%;background:var(--sw);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dl-fg) 12%,transparent)}.dl-swatch.on{box-shadow:0 0 0 2px var(--dl-card),0 0 0 4px var(--sw)}.dl-swatch:focus-visible{outline:2px solid var(--dl-ring);outline-offset:3px}.dl-circle-modal .dl-chipbtn b{margin-left:6px;font-weight:500;font-size:11px;opacity:.6}.dl-reach td:first-child b{font-weight:500}.dl-ev-host{white-space:nowrap}.dl-ev-host b{font-weight:500;color:var(--dl-fg)}.dl-reach{font-size:13px}.dl-reach th,.dl-reach td{white-space:nowrap;padding-left:6px;padding-right:6px}.dl-reach-wrap{overflow-x:auto}.dl-yes{display:inline-flex;align-items:center;gap:4px;color:var(--dl-ok)}.dl-yes .dl-icon-wrap{display:inline-flex}.dl-yes .dl-icon{width:14px;height:14px}.dl-check-form{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr) auto;align-items:start;gap:8px}.dl-check-form>.dl-faint{line-height:36px}.dl-check-end{display:flex;flex-direction:column;gap:6px;min-width:0}.dl-check-end>*{width:100%!important;min-width:0}@media(max-width:560px){.dl-check-form{grid-template-columns:minmax(0,1fr)}.dl-check-form>.dl-faint{display:none}}.dl-verdict{display:flex;align-items:baseline;gap:10px;padding:10px 12px;border-radius:12px}.dl-verdict b{font-weight:500}.dl-verdict.ok{background:var(--dl-ok-wash)}.dl-verdict.ok b{color:var(--dl-ok)}.dl-verdict.bad{background:var(--dl-bad-wash)}.dl-verdict.bad b{color:var(--dl-bad)}.dl-corehead{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:0 0 4px}.dl-corehead h3{margin:0!important}.dl-row-end{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}.dl-dcard.clickable{cursor:pointer}.dl-dcard.clickable:hover{border-color:color-mix(in srgb,var(--dl-fg) 22%,transparent)}";var rd=[ka,_a,Ca,La,Ma,Ea,Ta,Sa,Pa,$a,Da,Aa,Na,Ha,za].join(` -`);function Ra(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=rd,n}function kt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async s=>{let r=await e.render(s),a=document.createElement("div");return a.className="dl-root",a.append(Ra(),r),a},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var tx=kt(rn),nx=kt(yt),ox=kt(rn),sx=kt(Un),rx=kt(Fn),ax=kt(Jn),ix=kt(qn);function Ia(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var lx=Ia(""),dx=Ia("log");return baseclass.extend({ activity: dx, diagnostics: ax, health: lx, overview: tx, people: nx, person: rx, server: ox, settings: sx, updates: ix }); +`).trim()}async function mn(t,e,o,s){let r=n("div",{class:"dl-notes"},n("p",{class:"dl-muted dl-loading"},_("Loading release notes…"))),i=n("div",{class:"dl-op-head"}),a="";ae(o,[i,r],[H([v("copy")," ",_("Copy")],()=>xe(a,_("Release notes copied")))," ",de(_("Close"))],"wide");try{let l=await N.updatesNotes(t,e,s??"");a=Si(l.body||"");let d=Ei(l.url);dom.content(i,[l.published?n("span",{class:"dl-pill"},Ie(l.published)):"",l.prerelease?n("span",{class:"dl-pill warn"},_("Pre-release")):"",n("span",{class:"dl-spacer"}),d?n("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},[_("On GitHub")," ",v("open")]):""]),dom.content(r,a.trim()?Ti(a):n("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,n("p",{class:"dl-muted"},_e(l)))}}function hd(t){let e={"6h":_("checks every 6 h"),"12h":_("checks every 12 h"),"1d":_("checks daily"),"7d":_("checks weekly")};return e[t]??e["1d"]}var ns=t=>t?Ie(t):"";function fd(t){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(t)?.[1];return e||(t.length<=90?t:`${t.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function $i(t,e){let o=t.st,s=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,a=g=>()=>mn("app",g,m(_("What’s new in Dawnline %s"),g.replace(/^v/,""))),l=e?.tag&&(e.update||e.status==="latest")?gd(t,e.tag,e.update?o.version:""):null,d=e?.tag??i,c=s.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[s.interval]??24)*3600:0,p=(g,M)=>n("div",{class:"dl-stack gap4"},[n("span",{class:"dl-metric-label"},g),n("span",{class:"dl-comp-side-v"},M)]),u=[{label:_("What’s new"),ic:"file",run:a(i)},{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:m(_("Reinstall %s"),o.version),ic:"reset",warn:!0,run:()=>t.op("app:reinstall",_("Reinstalling Dawnline"),o.version)},r?{label:m(_("Roll back to %s"),r.version),ic:"archive",warn:!0,run:async()=>{await pe(m(_("Roll back to Dawnline %s?"),r.version),m(_("The copy kept on the router replaces %s. A backup of the settings is made first."),o.version),_("Roll back"))&&t.op("app:rollback",_("Rolling back Dawnline"),o.version)}}:null];return n("section",{class:"dl-panel flush dl-comp-hero"},[n("div",{class:"dl-comp-hero-main"},[n("div",{class:"dl-comp-hero-head"},[n("span",{class:"dl-group-ic"},v("sunrise")),n("b",{class:"dl-comp-name"},"Dawnline"),t.state("app",e,e?.latest??""),n("span",{class:"dl-spacer"}),t.round(()=>t.op("check:app",_("Checking Dawnline"),o.version),u,!0)]),n("div",{class:"dl-comp-verrow"},[n("div",{class:"dl-stack"},[n("div",{class:"dl-comp-big"},[o.version,e?.update?n("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?n("small",{class:"dl-faint"},m(_("release %s"),e.latest)):""]),n("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?m(_("released %s"),ns(e.published)):"":e?.status==="dev"?_("ahead of the latest release"):e?[_("latest release"),e.published?m(_("released %s"),ns(e.published)):""].filter(Boolean).join(" · "):_("not checked yet"))])]),l?.items.length?n("div",{class:"dl-stack gap4"},[n("ul",{class:"dl-comp-bullets"},l.items.map(g=>n("li",{},g))),l.total>l.items.length?n("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:a(d)},G(l.total-l.items.length,"+%s more in What’s new","+%s more in What’s new")):""]):"",e?.error?n("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?n("div",{class:"dl-comp-btns"},[H(_("Update now"),()=>t.op("app",_("Updating Dawnline"),o.version),"positive",{disabled:t.busy}),H(_("What’s new"),a(i))]):"",bd(t),vd(t)]),n("div",{class:"dl-comp-hero-side"},[p(_("Source"),[v("globe"),n("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p(_("Auto-update"),[s.auto?Se("ok",_("On")):Se("",_("Off")),n("span",{class:"dl-muted"},s.auto?s.mode==="immediate"?_("as soon as found"):m(s.interval==="7d"?_("weekly at %s"):_("daily at %s"),s.time):s.check?hd(s.interval):_("checks off"))]),p(_("Last check"),o.check?[ce(o.check.time,o.now),c>o.now?n("span",{class:"dl-faint"},`· ${m(_("next in %s"),st(c-o.now))}`):""]:[_("Never")]),p(_("Rollback"),r?[n("span",{class:"dl-mono"},r.version),n("span",{class:"dl-faint"},_("kept on flash"))]:[n("span",{class:"dl-muted"},s.keep?_("Kept after the next update"):_("Off"))])])])}function gd(t,e,o){if(t.notes.has(e))return t.notes.get(e)??null;t.notes.set(e,null);let s=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,a)=>a??"").trim();return(async()=>{let i=((await N.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(` +`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await N.updatesChanges(o,e).catch(()=>null))?.items??[]);let a={items:i.slice(0,3).map(l=>fd(s(l))),total:i.length};t.notes.set(e,a),a.items.length&&t.root.isConnected&&t.paint()})(),null}function Xn(t){return t==="ru"?_("Russian translation"):t}function vd(t){let e=(t.st.translations??[]).includes("ru"),o=be(e,Xn("ru"),r=>{t.op(r?"app:lang:ru":"app:nolang",r?_("Adding the Russian translation"):_("Removing the Russian translation"),t.st.version)});o.disabled=t.busy;let s=n("details",{class:"dl-params dl-comp-fold",open:t.langOpen?"open":null},[n("summary",{},[v("chevron"),n("span",{},_("Translation")),n("span",{class:"dl-sub"},e?_("Russian"):_("English only"))]),n("div",{class:"dl-params-body"},[n("div",{class:"dl-list"},[n("div",{class:"dl-row"},[n("span",{class:"dl-row-main dl-stack"},[n("b",{},Xn("ru")),n("span",{class:"dl-sub"},_("LuCI pages for Dawnline"))]),n("span",{class:"dl-comp-bact"},o)])])])]);return s.addEventListener("toggle",()=>t.langOpen=s.open),s}function bd(t){let e=n("div",{class:"dl-params-body"}),o=n("details",{class:"dl-params dl-comp-vers",open:t.versOpen?"open":null},[n("summary",{},[v("chevron"),n("span",{},_("Versions")),n("span",{class:"dl-sub"},_("install any release"))]),e]);return o.addEventListener("toggle",()=>{t.versOpen=o.open,t.versOpen&&eo(t,e)}),t.versOpen&&eo(t,e),o}async function eo(t,e){let o=ue("",{placeholder:_("Tag, e.g. 0.3.1"),class:"cbi-input-text dl-mono","aria-label":_("Release tag")}),s=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return F(_("Enter a release tag like 0.3.1"),"warning");Pi(t,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),s(o.value))});let r=n("div",{class:"dl-comp-tag"},[o,H(_("Install"),()=>s(o.value),"neutral",{disabled:t.busy})]),i=t.versPage,a=p=>{t.versPage=Math.max(1,t.versPage+p),eo(t,e)},l=p=>n("div",{class:"dl-comp-pager"},[n("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>a(-1)},_("← Newer")),n("span",{class:"dl-faint"},m(_("Page %s"),i)),n("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>a(1)},_("Older →"))]),d=t.versCache.get(i);if(!d){dom.content(e,[r,n("p",{class:"dl-muted dl-loading"},_("Loading versions…"))]);try{d=(await N.updatesReleases(i)).releases}catch(p){if(i!==t.versPage||!e.isConnected)return;dom.content(e,[r,n("div",{class:"dl-row-actions"},[n("span",{class:"dl-muted"},m(_("Failed to load versions: %s"),_e(p))),H(_("Try again"),()=>eo(t,e))]),l(!1)]);return}if(t.versCache.set(i,d),i!==t.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[r,n("p",{class:"dl-muted"},i>1?_("No more versions."):_("No versions found.")),l(!1)]);let c=t.st.version;dom.content(e,[r,...d.map(p=>{let u=p.tag.replace(/^v/,"");return n("div",{class:"dl-comp-ver"},[n("span",{class:"dl-mono"},u),n("span",{class:"dl-sub"},ns(p.published)),p.prerelease?Se("warn",_("Pre-release")):"",n("span",{class:"dl-comp-ic"},Pe("file",_("What’s new"),()=>mn("app",p.tag,m(_("What’s new in Dawnline %s"),u)))),u===c?Se("ok",_("Installed")):H(_("Install"),()=>Pi(t,p.tag),"neutral",{disabled:t.busy})])}),l(d.length>=5)])}async function Pi(t,e){let o=e.replace(/^v/,"");o.localeCompare(t.st.version,void 0,{numeric:!0})<0&&!await pe(m(_("Install Dawnline %s?"),o),m(_("It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong."),t.st.version),_("Install"))||t.op(`app@${e}`,m(_("Installing Dawnline %s"),o),t.st.version)}function Di(t,e){let o=t.st,s=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),a=e?.current??null,l=a?r[a]:void 0,d=!!e?.ru,c=o.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];a&&p&&u.push({label:_("Reinstall this build"),warn:!0,ic:"reset",run:()=>t.op(`amneziawg:${a}${d?":ru":""}`,_("Reinstalling AmneziaWG"),p)}),s&&u.push({label:m(_("Roll back to %s"),s.version),ic:"archive",warn:!0,run:async()=>{await pe(m(_("Roll back AmneziaWG to %s?"),s.version),_("The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds."),_("Roll back"))&&t.op("amneziawg:rollback",_("Rolling back AmneziaWG"),p??void 0)}});let g=[e?.release?{label:_("What’s new"),ic:"file",run:()=>mn("amneziawg",e.release,m(_("What’s new in the %s build"),l?.label??"AmneziaWG"),a??"slava")}:null,{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((b,f,T)=>b!==null||f>0&&T[f-1]!==null),M=o.tunnels??[],x=M.length?M.length===1?m(_("Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations."),M[0]):m(N_(M.length,"Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.","Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations."),V(M.length),M.join(", ")):_("Switching takes a few seconds. Devices keep their configurations."),h=M.length>1?m(_("%s and %s"),M.slice(0,-1).join(", "),M[M.length-1]):M[0],S=M.length?m(_("Switching restarts %s for a few seconds."),h):_("Switching takes a few seconds."),B=async b=>{let f=r[b];await pe(p?m(_("Switch to AmneziaWG %s?"),f.gen):m(_("Install AmneziaWG %s?"),f.gen),[m(_("The %s build, %s."),f.label,f.version),x,f.gen==="3.1"?_("Devices need AmneziaVPN 3.1 or newer."):""].filter(Boolean).join(" "),p?_("Switch"):_("Install"))&&t.op(`amneziawg:${b}${d?":ru":""}`,p?m(_("Switching to AmneziaWG %s"),f.gen):_("Installing AmneziaWG"),p??void 0)},P=b=>{let f=r[b],T=a===b&&!!p;return n("div",{class:"dl-row"},[n("span",{class:"dl-row-main dl-stack"},[n("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),n("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":_("every app")}`)]),n("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??_("none yet")),n("span",{class:"dl-comp-bact"},T?Se("ok",_("Active","build")):f.version?H(p?_("Switch"):_("Install"),()=>B(b),p?"neutral":"positive",{disabled:t.busy}):Se("",_("No build")))])},R=i.map(b=>r[b]?.newer?m(_("%s moves to %s with OpenWrt %s."),r[b].label,r[b].newer.gen,r[b].newer.tag.replace(/^v/,"")):"").filter(Boolean),w=be(d,_("Russian translation"),b=>{a&&t.op(`amneziawg:${a}${b?":ru":""}`,b?_("Adding the Russian translation"):_("Removing the Russian translation"),p??void 0)});w.disabled=!a||!p||t.busy;let k=t.awgOpen??!p,y=n("details",{class:"dl-params dl-comp-fold",open:k?"open":null},[n("summary",{},[v("chevron"),n("span",{},_("Build and translation"))]),n("div",{class:"dl-params-body"},[n("div",{class:"dl-list"},[...i.length?i.map(P):[n("div",{class:"dl-row"},n("span",{class:"dl-sub"},_("Check for updates to see the builds for this router.")))],n("div",{class:"dl-row"},[n("span",{class:"dl-row-main dl-stack"},[n("b",{},_("Russian translation")),n("span",{class:"dl-sub"},_("LuCI pages for AmneziaWG"))]),n("span",{class:"dl-comp-bact"},w)])]),p&&i.length||R.length?n("div",{class:`dl-comp-status ${p&&i.length?"warn":"acc"}`},[v(p&&i.length?"alert":"download"),n("span",{},[p&&i.length?n("b",{},S):"",...R.map(b=>` ${b}`)])]):""])]);y.addEventListener("toggle",()=>t.awgOpen=y.open);let O=[];return e?.update&&p&&a?O.push(H(m(_("Update to %s"),e.latest),()=>t.op(`amneziawg:${a}${d?":ru":""}`,_("Updating AmneziaWG"),p),"neutral",{disabled:t.busy})):O.push((e||c.length)&&!p?Se("warn",_("Not installed")):t.state("amneziawg",e,e?.latest??"")),O.push(t.round(()=>t.op("check:amneziawg",_("Checking AmneziaWG"),p??void 0),g)),[t.row("shield","AmneziaWG",[p?`${p}${e?.release?` · ${m(_("%s build"),e.release)}`:""}`:c.length?m(_("missing %s"),c.join(", ")):e?_("not installed"):_("version not checked")],O),n("div",{class:"dl-comp-foldwrap"},y)]}function xd(){return[{title:_("Home-like link"),sub:_("Policy routing and the veth pair"),pkgs:["ip-full","kmod-veth"],feature:"home"},{title:_("HTTPS for the portal"),sub:_("OpenSSL for uhttpd"),pkgs:["libustream-openssl","openssl-util"],feature:"https"},{title:_("Certificates (ACME)"),sub:_("Let’s Encrypt certificate for the portal"),pkgs:["acme","acme-acmesh-dnsapi"],feature:"acme",optional:!0}]}var os={home:"network",https:"lock",acme:"file"};function Ai(t,e){let o=t.st,s=e?.pkgs??{},r=xd().filter(c=>c.feature==="home"?o.home:o.portal),i=async(c,p,u=c)=>{await pe(m(_("Update %s?"),p),m(_("%s from the OpenWrt feeds. Services that use them restart for a moment."),u.join(", ")),_("Update"))&&t.op(`pkgs:${c.join(",")}`,m(_("Updating %s"),p))},a=[{label:_("Check system packages"),ic:"refresh",run:()=>t.op("check:packages",_("Checking system packages"))},{label:_("Open the OpenWrt package list"),ic:"globe",run:()=>window.open("https://openwrt.org/packages/start","_blank","noopener")}],l=0;return{rows:r.map(c=>{let p=c.pkgs.filter(h=>s[h]?.installed),u=[...new Set(p.flatMap(h=>[...s[h]?.latest?[h]:[],...s[h]?.with??[]]))],g=o.needs?.[c.feature]??c.pkgs.filter(h=>!s[h]?.installed),M=p.find(h=>s[h]?.latest),x=p.map(h=>`${h} ${s[h]?.installed??""}`).join(", ");return g.length?t.row(os[c.feature],c.title,[c.optional?_("not installed"):m(_("missing %s"),g.join(", "))],[H(_("Install"),()=>t.op(`pkgs:${g.join(",")}`,m(_("Installing %s"),c.title)),c.optional?"neutral":"positive",{disabled:t.busy}),n("span",{class:"dl-comp-ic"},t.more(a))]):e&&u.length?(l++,t.row(os[c.feature],c.title,M?[`${s[M].installed} → ${s[M].latest}`,u.length>1?` · +${u.length-1}`:""]:[u.join(", ")],[H(_("Update"),()=>i(p.filter(h=>s[h]?.latest||s[h]?.with?.length),c.title,u),"neutral",{disabled:t.busy}),n("span",{class:"dl-comp-ic"},t.more(a))])):t.row(os[c.feature],c.title,[x||c.sub],[t.state("pkgs",e,""),n("span",{class:"dl-comp-ic"},t.more(a))])}),updates:l,total:r.length}}function wd(t){return t==="app"?"Dawnline":t==="amneziawg"?"AmneziaWG":t==="pkgs"?_("System packages"):_("Components")}function yd(t){let e=/^(\d+) system packages?$/.exec(t)?.[1];return e?G(Number(e),"%s system package","%s system packages"):t}function Ni(t){let e=t.st,o=r=>{let i=ht(r.component??"app"),a=n("b",{},wd(i)),l="ok",d="check",c;if(r.kind==="found")l="accent",d="download",c=oe(r.auto?_("%s found by the automatic check"):_("%s found by a check"),n("b",{},(r.items??[]).map(yd).join(", ")));else if(r.state==="failed")l="bad",d="x",c=[...oe(r.kind==="install"?_("%s update failed"):_("%s check failed"),a),r.error?` · ${r.error}`:""];else if(/^app:(lang:|nolang$)/.test(r.component??"")){let p=/^app:lang:(.+)$/.exec(r.component??"")?.[1];c=p?oe(_("%s added by you"),n("b",{},Xn(p))):[_("Translation removed by you")]}else{let p=r.from&&r.to&&r.from!==r.to?`${r.from} → ${r.to}`:r.to??"";c=[...p?oe(r.auto?_("%s %s automatically"):_("%s %s by you"),a,p):oe(r.auto?_("%s updated automatically"):_("%s updated by you"),a),r.took?` · ${st(r.took)}`:""]}return n("div",{class:"dl-row"},[n("span",{class:`dl-ev-tile ev ${l}`},v(d)),n("span",{class:"dl-row-main"},c),n("span",{class:"dl-faint dl-nowrap",title:new Date(r.ts*1e3).toLocaleString(ie())},ce(r.ts,e.now))])},s=e.history??[];return n("section",{class:"dl-panel flush"},[n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Activity")),n("span",{class:"dl-spacer"}),n("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},_("All in Log →"))]),s.length?n("div",{},s.slice(0,8).map(o)):n("p",{class:"dl-sub dl-comp-empty"},_("Updates, and checks that found something, show up here."))])}var to=class{constructor(){this.root=n("div",{class:"dl-upd"});this.following=null;this.versOpen=!1;this.versPage=1;this.versCache=new Map;this.notes=new Map;this.awgOpen=null;this.langOpen=!1}load(){return N.updatesStatus()}render(e){return this.st=e,this.paint(),e.job?.state==="running"&&this.follow(e.job),poll.add(async()=>{if(!this.root.isConnected)return;let o=await N.updatesStatus().catch(()=>null);if(!o)return;let s=this.st;this.st=o,o.job?.state==="running"&&this.following!=="starting"&&o.job.id!==this.following&&this.follow(o.job),(o.job?.id!==s.job?.id||o.job?.state!==s.job?.state||o.job?.phase!==s.job?.phase||o.check?.time!==s.check?.time)&&this.paint()},5),this.root}get busy(){return this.st.job?.state==="running"}async refresh(e){this.st=e??await N.updatesStatus().catch(()=>null)??this.st,this.paint()}async op(e,o,s){if(this.busy||this.following==="starting"){F(_("Another component action is already running"),"warning");return}this.following="starting",this.paint();let r=ht(e),i=await dn(e,{title:o,version:s,onJob:a=>this.following=a.id,onDone:a=>this.refresh(a),onUpdate:a=>{let l=a.check?.components??{};r==="amneziawg"&&l.amneziawg?.current?this.op(`amneziawg:${l.amneziawg.current}${l.amneziawg.ru?":ru":""}`,_("Updating AmneziaWG"),l.amneziawg.installed??void 0):this.op("app",_("Updating Dawnline"),this.st.version)}});this.following==="starting"&&(this.following=i?.id??null),this.refresh()}async follow(e){this.following=e.id;let o={app:[_("Checking Dawnline"),_("Automatic update: Dawnline"),_("Updating Dawnline")],amneziawg:[_("Checking AmneziaWG"),_("Automatic update: AmneziaWG"),_("Updating AmneziaWG")],pkgs:[_("Checking system packages"),_("Automatic update: system packages"),_("Updating system packages")],all:[_("Checking components"),_("Automatic update: components"),_("Updating components")]};await dn(null,{title:(o[Wn(e)]??o.all)[e.action==="check"?0:e.auto?1:2],onDone:s=>this.refresh(s)},e)}paint(){let e=this.st,o=e.check?.components??{},s=e.firmware,r=Ai(this,o.packages),i=(e.needs?.awg??[]).length>0,l=(!i&&o.amneziawg?.update&&o.amneziawg.installed?1:0)+r.updates;dom.content(this.root,[n("div",{class:"dl-pagehead"},[n("div",{class:"dl-stack"},[n("h2",{class:"dl-h1"},_("Components")),n("span",{class:"dl-faint"},[s?.version?`OpenWrt ${s.version} · ${s.target}`:"",e.check?m(_("checked %s"),ce(e.check.time,e.now)):_("not checked yet")].filter(Boolean).join(" · "))]),n("div",{class:"dl-row-actions"},[n("a",{class:"cbi-button cbi-button-neutral dl-icon-btn",href:`${L.url("admin/network/dawnline/settings")}?section=updates`},[v("edit")," ",_("Settings")]),H([v("refresh")," ",_("Check all")],()=>this.op("check",_("Checking all components")),"neutral",{disabled:this.busy})])]),$i(this,o.app),n("div",{class:"dl-comp-cols"},[n("section",{class:"dl-panel flush"},[n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Components")),n("span",{class:"dl-spacer"}),n("span",{class:"dl-faint dl-comp-count"},i?l?`${_("AmneziaWG not installed")} · ${G(l,"%s update","%s updates")}`:_("AmneziaWG not installed"):!o.amneziawg&&!o.packages?"":l?m(N_(l,"%s of %s needs an update","%s of %s need an update"),V(l),V(1+r.total)):_("Everything is up to date"))]),n("div",{},[...Di(this,o.amneziawg),...r.rows])]),Ni(this)])])}state(e,o,s){let r=this.st.job;if(r?.state==="running"){let i=l=>l==="packages"?"pkgs":l,a=r.action==="check"?[i(r.component||"all")]:(r.component??"").split(" ").map(l=>i(ht(l)));if(a.includes(e)||a.includes("all"))return n("button",{type:"button",class:"dl-pill info dl-comp-run",title:_("Show progress"),click:()=>this.follow(r)},[r.action==="check"?_("Checking…"):_("Updating…")])}return o?o.error?Se("warn",_("Check failed"),o.error):o.update?Se("info",_("Update available")):o.status==="dev"?Se("info",_("Newer than release"),m(_("The latest release is %s"),s)):Se("ok",_("Up to date")):Se("",_("Not checked"))}more(e){let o=H([v("more")],()=>Te(o,e.filter((s,r,i)=>s!==null||r>0&&rs?{label:s.label,icon:v(s.ic),warn:s.warn,run:s.run}:null)),"neutral",{title:_("More"),"aria-label":_("More")});return o}round(e,o,s=!1){let r=this.busy?" is-busy":"",i;return s?i=H([v("refresh")," ",_("Check")],e,"neutral",{class:`cbi-button cbi-button-neutral dl-comp-check${r}`,"aria-label":_("Check for updates")}):(i=Pe("refresh",_("Check for updates"),e,"neutral",r.trim()),i.removeAttribute("title"),i.setAttribute("aria-label",_("Check for updates")),we(i,()=>[_("Check for updates")])),n("span",{class:"dl-comp-ic"},[i,this.more(o)])}row(e,o,s,r){return n("div",{class:"dl-row"},[n("span",{class:"dl-group-ic"},v(e)),n("span",{class:"dl-row-main dl-stack"},[n("b",{},o),n("span",{class:"dl-mono dl-faint dl-comp-sub"},s)]),...r])}};var Hi=(t,e)=>n("div",{class:"cbi-value"},[n("label",{class:"cbi-value-title"},t),n("div",{class:"cbi-value-field"},e)]);function zi(t){let e=t.st.servers.find(o=>o.id===t.p.server)?.name??_("Home");an(t.p,e)}async function Ri(t){let e=t.p,o=e.code_set??0,s=e.devices.filter(l=>l.created_by==="portal"&&l.created>=o),r=s.map(l=>n("input",{type:"checkbox",id:`dl-rm-${l.id}`,checked:"checked","data-id":l.id})),i=[n("p",{},_("The old link stops working right away."))];s.length&&i.push(n("p",{},_("Devices added through the old link keep working until they are removed. Remove them too:")),n("div",{class:"dl-checklist"},s.map((l,d)=>n("label",{for:`dl-rm-${l.id}`},[r[d],` ${l.name}`]))));let a=async()=>{let l=r.filter(c=>c.checked).map(c=>c.dataset.id),d=await q(()=>N.personRegen(e.id,l),l.length?G(l.length,"New link created, %s device removed","New link created, %s devices removed"):_("New link created"));d&&(le(),l.length&&await t.refresh(),d.link&&await xe(d.link,_("New link copied")))};ae(_("Create a new link?"),i,[de()," ",H(_("Create new link"),a,"negative")])}function ss(t){let e=n("textarea",{class:"cbi-input-textarea dl-note-input",rows:3,maxlength:500,placeholder:_("Only you see this")},t.p.note??"");ae(_("Note"),[e],[de()," ",H(_("Save"),async()=>{le(),await t.patch({note:e.value.trim()},e.value.trim()?_("Note saved"):_("Note removed"))},"positive")]),setTimeout(()=>e.focus(),50)}function Ii(t){let e=t.p,o=n("select",{class:"cbi-input-select"},[n("option",{value:"pause",selected:e.expire_action==="pause"?"selected":null},_("Pause access")),n("option",{value:"notify",selected:e.expire_action==="notify"?"selected":null},_("Keep access")),n("option",{value:"remove",selected:e.expire_action==="remove"?"selected":null},_("Remove their devices"))]),s=n("select",{class:"cbi-input-select"},[0,1,3,7,14].map(r=>n("option",{value:r,selected:e.expire_warn===r?"selected":null},r?G(r,"%s day before","%s days before"):_("Don’t warn"))));ae(_("When access ends"),[Hi(_("Then"),o),n("div",{class:"cbi-value"},[n("label",{class:"cbi-value-title"},_("Warn")),n("div",{class:"cbi-value-field"},[s,n("div",{class:"cbi-value-description"},_("Shown in their portal and on the Overview."))])])],[de()," ",H(_("Save"),async()=>{le(),await t.patch({expire_action:o.value,expire_warn:s.value},_("Saved"))},"positive")])}function Oi(t){let e=n("input",{type:"text",class:"cbi-input-text",value:t.p.name,maxlength:48}),o=Me(_("Name","person"),e,()=>je(e.value,[],_("Shown in their portal and apps.")));ae(_("Rename"),[o],[de()," ",H(_("Save"),async()=>{let s=o.help();if(s.bad){F(s.text,"warning");return}await t.patch({name:e.value.trim()},_("Renamed"))&&le()},"positive")]),setTimeout(()=>e.select(),50)}function Bi(t){let e=t.p,o=t.st.servers.filter(i=>i.id!==e.server),s=n("select",{class:"cbi-input-select"},o.map(i=>n("option",{value:i.id},`${i.name} · ${i.endpoint||_("no address")}:${i.port}`))),r=e.devices.length;ae(m(_("Move %s to another server"),e.name),[Hi(_("Server"),s),n("p",{class:"dl-muted"},r?G(r,"%s device gets a new address and stops connecting until it imports its configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.","%s devices get new addresses and stop connecting until they import their configuration again (from the personal link or from you). Circles and home networks of the old server are left behind."):_("They have no devices yet: nothing else changes."))],[de()," ",H(_("Move"),async()=>{await t.patch({server:s.value},m(_("Moved to %s"),o.find(i=>i.id===s.value)?.name??_("the server")))&&(le(),r&&F(_("Devices are marked “Update config” until they import again."),"info",6e3))},"positive")])}async function ji(t){let e=t.p;await pe(m(_("Delete %s?"),e.name),G(e.devices.length,"%s device is disconnected immediately and the personal link stops working.","All %s devices are disconnected immediately and the personal link stops working."),_("Delete"),!0)&&await q(()=>N.personDelete(e.id),_("Deleted"))&&(location.href=jt(e.server))}function Ui(t){let e=t.p,o=t.st,s=e.online?_("online now"):e.last_seen?m(_("last seen %s"),ce(e.last_seen,o.now)):_("never connected"),r=e.created?m(_("Added %s","date"),$e(qe(new Date(e.created*1e3)))):"",i=e.has_link??o.settings.portal_enabled,a=[{label:_("Rename"),icon:v("edit"),run:()=>Oi(t)},{label:e.note?_("Edit note"):_("Add note"),icon:v("file"),run:()=>ss(t)},...o.servers.length>1?[{label:_("Move to server…"),icon:v("server"),run:()=>Bi(t)}]:[],...i?[null,{label:_("Invite card"),icon:v("qr"),run:()=>zi(t)},{label:_("New link"),icon:v("key"),run:()=>Ri(t)}]:[],null,...e.paused?[]:[{label:_("Pause"),icon:v("pause"),warn:!0,run:()=>t.patch({paused:!0},_("Paused"))}],{label:_("Delete"),icon:v("trash"),danger:!0,run:()=>ji(t)}];return n("div",{class:"dl-person-head"},[n("div",{class:"dl-pagehead"},[n("div",{class:"dl-person-id"},[n("span",{class:`dl-avatar lg${e.online?" online":""}`},Oe(e.name)),n("div",{class:"dl-stack"},[n("div",{class:"dl-title-row"},[n("h2",{class:"dl-h1"},e.name),vs(e)]),n("span",{class:"dl-faint",title:r},`${m(N_(e.device_limit,"%s of %s device","%s of %s devices"),e.devices.length,e.device_limit)} · ${s}`)])]),n("div",{class:"dl-pcard-actions"},[e.paused?H([v("play"),` ${_("Resume")}`],()=>t.patch({paused:!1},_("Resumed")),"add"):"",i?Pe("link",_("Copy link"),()=>On(e.id),"neutral","dl-icon-only"):"",Pe("more",_("More"),l=>Te(l.currentTarget,a),"neutral","dl-icon-only")])]),e.note?n("button",{type:"button",class:"dl-pnote",title:_("Edit note"),click:()=>ss(t)},[v("file"),n("span",{},e.note)]):""])}function Wi(t){let e=t.p,o=t.series[t.series.length-1];return n("div",{class:`dl-person-live${e.online?"":" solo"}`},[e.online?pi(e.rate??[],t.st.now,o?[o.rx,o.tx]:[0,0]):"",Yn(t.series,m(_("%s this month"),se(e.month[0]+e.month[1])))])}async function kd(t,e){let o=await q(()=>N.deviceConfig(e.id,!0));o&&ae(m(_("Set up %s"),e.name),[await t.core.connectBlock(o,"qr")],[de(_("Close"))])}async function _d(t,e){let o=await q(()=>N.deviceConfig(e.id,!0));if(!o)return;if(!o.has_private_key){F(_("This device made its own keys in the browser; its configuration only exists there."),"warning");return}let s=t.core.file.make(o);Ae(s.name,s.text,"application/octet-stream")}function Gi(t){let e=t.p,o=t.st.now,s=d=>Ye(e,d,t.deviceOpts()),r=d=>c=>{c.target.closest("button:not(.dl-dcard-title), a")||s(d)},i=d=>H([v("more")],c=>Br(c.currentTarget,e,d,t.deviceOpts()),"neutral",{title:_("QR, file, key, rename, new keys, remove"),class:"cbi-button cbi-button-neutral dl-icon-only"}),a=vn(e.devices).map(d=>{let c=n("div",{class:"dl-dcard-head"},[n("span",{class:"dl-dcard-ic"},v(d.kind)),n("button",{type:"button",class:"dl-dcard-title",click:()=>s(d)},[n("b",{},d.name),xn(d,o,void 0,e),d.config_stale?n("span",{class:"dl-pill warn dl-stale"},_("Update config")):""]),i(d)]),p=n("div",{class:"dl-dcard-trend"},[n("div",{class:"dl-stack"},[n("b",{},se(d.month[0]+d.month[1])),n("span",{class:"dl-sub"},_("this month"))]),mi(t.devSeries[d.id]??[])]);return n("article",{class:`dl-dcard clickable${d.online?" online":""}${d.disabled?" off":""}`,click:r(d)},[c,d.handshake?p:d.disabled?n("div",{class:"dl-sub"},`${at(d.kind)} · ${m(d.created_by==="portal"?_("created %s in the portal."):_("created %s by you."),ce(d.created,o))}`):n("div",{class:"dl-chips-row"},[n("button",{type:"button",class:"dl-chipbtn",click:()=>kd(t,d)},[v("qr"),_("Show QR")]),n("button",{type:"button",class:"dl-chipbtn",click:()=>_d(t,d)},[v("download"),_("Config")])])])}),l=e.devices.length>=e.device_limit;return a.push(n("button",{type:"button",class:"dl-dslot add",click:()=>pt(e,t.deviceOpts())},[n("span",{class:"dl-dslot-ic"},v("plus")),n("span",{class:"dl-stack"},[n("b",{},_("Add device")),n("span",{class:"dl-sub"},l?`${_("Over the limit")} · ${m(_("%s of %s"),e.devices.length,e.device_limit)}`:m(_("%s of %s"),e.devices.length,e.device_limit))])])),n("section",{class:"dl-devsec"},[n("div",{class:"dl-panel-head"},[n("h3",{},_("Devices")),n("span",{class:"dl-sub"},m(_("%s online"),V(e.online)))]),n("div",{class:"dl-dgrid"},a)])}function Fi(t){let e=t.p,o=Ze([["device",_("Device’s own DNS")],["home",_("Home names")]],e.dns_mode,{label:"DNS",cls:"sm",optimistic:!1,onChange:r=>t.patch({dns_mode:r},r==="home"?_("Home names on - devices need their configuration again"):_("Device DNS - devices need their configuration again"))}),s=t.st.settings.home_dns_fallback;return n("div",{class:"dl-stack gap4 dl-dnspick"},[n("div",{class:"dl-row-actions"},[n("span",{class:"dl-sub"},"DNS"),o]),n("span",{class:"dl-sub"},e.dns_mode==="home"?s?oe(_("Names like %s work. Internet names are resolved at home, so they depend on the tunnel (%s takes over when it is down)."),n("span",{class:"dl-mono"},`nas.${t.st.settings.domain}`),n("span",{class:"dl-mono"},s)):oe(_("Names like %s work. Internet names are resolved at home, so they depend on the tunnel - with no fallback set, they stop when it is down."),n("span",{class:"dl-mono"},`nas.${t.st.settings.domain}`)):_("Internet keeps working exactly as without the VPN. Reach home devices by IP address."))])}function qi(t){let e=t.p,s=t.st.servers.find(i=>i.id===e.server)?.home??[];if(s.length<2)return"";let r=new Set(e.home_nets?.length?e.home_nets:s.map(i=>i.dev));return n("div",{class:"dl-stack gap4"},[n("div",{class:"dl-chips-row"},s.map(i=>Yt(i.dev,r.has(i.dev),()=>{let a=new Set(r);if(a.delete(i.dev)||a.add(i.dev),!a.size)return F(_("Keep at least one network, or choose Internet only."),"warning",5e3);let l=a.size===s.length?[]:[...a];t.patch({home_nets:l},l.length?m(_("%s reaches %s"),e.name,l.join(", ")):m(_("%s reaches every home network"),e.name))},{title:i.nets.join(", ")}))),n("span",{class:"dl-sub"},e.home_nets?.length?m(_("Home networks %s reaches. Networks added to the server later stay out."),e.name):m(_("Home networks %s reaches: all of them. Untick one to keep %s out of it."),e.name,e.name))])}function Ki(t){let e=new Set(t.p.services??[]);return n("div",{class:"dl-stack gap4"},[n("div",{class:"dl-chips-row"},t.st.services.map(o=>Yt(o.name,e.has(o.id),()=>{let s=new Set(e);s.delete(o.id)||s.add(o.id),t.patch({services:[...s]},s.size?_("Home services updated"):_("Whole home network"))},{title:`${o.address}${o.ports.length?` · ${o.ports.join(", ")}`:""}`}))),n("span",{class:"dl-sub"},e.size?_("Only the selected services at home."):_("Whole home network. Pick services to narrow it down."))])}function Vi(t){let e=t.p,o=t.st;if(o.servers.find(c=>c.id===e.server)?.mesh!=="circles"||!mt(e))return"";let r=o.circles.filter(c=>c.server===e.server),i=r.find(c=>c.id===e.circle),a=i?o.people.filter(c=>c.id!==e.id&&c.circle===i.id&&mt(c)).map(c=>c.name):[],l=n("button",{type:"button",class:"dl-chipbtn",click:()=>Te(l,[...r.map(c=>({label:c.name,icon:qo(c),run:()=>c.id!==e.circle&&t.patch({circle:c.id},m(_("%s is in %s"),e.name,c.name))})),e.circle?{label:_("No circle"),icon:v("x"),run:()=>t.patch({circle:""},m(_("%s is in no circle"),e.name))}:null,{label:_("New circle"),icon:v("plus"),run:()=>jn(o,e.server,null,()=>t.refresh())}])},_("Change")),d=i?o.people.filter(c=>c.circle===i.id&&mt(c)):[e];return n("div",{class:"dl-tile2"},[n("div",{class:"dl-tile2-label"},[n("span",{},_("Devices see each other")),l]),n("div",{class:"dl-tile2-row"},[n("span",{class:"dl-tile2-value"},i?i.name:_("No circle")),n("span",{class:"dl-avstack",title:d.map(c=>c.name).join(", ")},d.slice(0,5).map(c=>n("span",{class:"dl-avatar sm"},Oe(c.name))))]),n("span",{class:"dl-sub"},i?a.length?[e.name,...a].join(", "):m(_("Nobody else in %s yet"),i.name):m(_("Only %s's own devices"),e.name))])}function Yi(t){let e=t.p,o=t.st.now,s=n("div",{class:"dl-slots"});for(let a=0;a=e.device_limit,c=n("i",{class:d?"over":l?"used":""});we(c,()=>[n("div",{class:"dl-tip-title"},l?`${l.name}${d?` · ${_("over the limit")}`:""}`:_("Free slot")),n("div",{class:"dl-muted"},l?l.online?_("Connected"):l.handshake?m(_("Last seen %s"),ce(l.handshake,o)):_("Not set up yet"):_("They can add a device here"))]),s.appendChild(c)}let r=Math.max(1,e.devices.length),i=n("button",{type:"button","aria-label":_("Allow fewer devices"),disabled:e.device_limit<=r?"disabled":null,click:()=>t.patch({device_limit:String(e.device_limit-1)})},"−");return e.device_limit<=r&&e.devices.length>1&&we(i,()=>[n("div",{class:"dl-tip-title"},G(e.devices.length,"%s device in use","%s devices in use")),n("div",{class:"dl-muted"},_("Remove a device first to lower the limit"))]),n("div",{class:"dl-tile2"},[n("div",{class:"dl-tile2-label"},_("Devices")),n("div",{class:"dl-tile2-row"},[n("span",{class:"dl-tile2-value"},[String(e.devices.length),n("span",{class:"dl-faint"},` / ${e.device_limit}`)]),n("div",{class:"dl-stepper"},[i,n("button",{type:"button","aria-label":_("Allow more devices"),disabled:e.device_limit>=32?"disabled":null,click:()=>t.patch({device_limit:String(e.device_limit+1)})},"+")])]),s])}function Cd(t){return{internet:_("Browse the internet through your router. No access to devices at home, and home cannot reach theirs."),lan:_("Reach devices at home, and home reaches theirs. Internet stays on their own connection."),both:_("Home devices and the internet, all through your router. Home reaches their devices too.")}[t]}var Ji=/^([01]\d|2[0-3]):[0-5]\d$/;function Ld(t){let e=t.p,o=t.today,s=rt(e.expires,o),r=n("input",{type:"date",class:"dl-date-hidden",value:e.expires,tabindex:"-1","aria-hidden":"true"});r.addEventListener("change",()=>r.value&&t.patch({expires:r.value},m(_("Access until %s"),$e(r.value))));let i=(c,p)=>{let u=ms(e.expires&&(s??-1)>=0?e.expires:"",c,p,o);t.patch({expires:u},m(_("Access until %s"),$e(u)))},a=[["week",1,_("+1 week")],["month",1,_("+1 month")],["month",3,_("+3 months")],["year",1,_("+1 year")]].map(([c,p,u])=>n("button",{type:"button",class:"dl-chipbtn",click:()=>i(c,p)},u)),l=n("span",{class:"dl-datechip"},[n("button",{type:"button",class:"dl-chipbtn",click:()=>{r.focus({preventScroll:!0});try{r.showPicker()}catch{}}},[v("calendar"),e.expires?$e(e.expires):_("Date")]),r]),d={pause:_("pause access"),notify:_("keep access"),remove:_("remove their devices")}[e.expire_action];return n("div",{class:"dl-tile2"},[n("div",{class:"dl-tile2-label"},[n("span",{},_("Access ends")),e.expires?n("span",{class:s!=null&&s<0?"dl-bad":it(e,s)?"dl-warn":"dl-ok"},s!=null&&s<0?_("ended"):G(s??0,"%s day left","%s days left")):n("span",{class:"dl-faint"},_("no end date"))]),n("div",{class:"dl-chips-row"},[...a,l,e.expires?n("button",{type:"button",class:"dl-chipbtn",click:()=>t.patch({expires:""},_("No end date"))},_("No end")):""]),n("div",{class:"dl-tile2-foot"},[n("span",{class:"dl-muted"},e.expire_warn?m(N_(e.expire_warn,"When it ends: %s, warn %s day before","When it ends: %s, warn %s days before"),d,V(e.expire_warn)):m(_("When it ends: %s"),d)),n("a",{href:"#",click:c=>{c.preventDefault(),Ii(t)}},_("Change"))])])}function Md(t){let e=t.p,o=e.quota_used||e.month[0]+e.month[1],s=e.quota_limit?Math.min(100,e.quota_used/e.quota_limit*100):0,r=n("div",{class:`dl-meter${s>=100?" bad":s>=90?" warn":""}`},[n("i"),e.quota_limit?n("span",{class:"mark",title:_("Alert at 90%")}):""]);r.firstChild.style.width=`${s}%`,e.quota_limit&&we(r,()=>[n("div",{class:"dl-tip-title"},m(_("%s%% used"),V(s,1))),n("div",{class:"dl-muted"},`${m(_("%s of %s"),se(e.quota_used),se(e.quota_limit))} · ${m(_("%s left"),se(Math.max(0,e.quota_limit-e.quota_used)))}`),n("div",{class:"dl-faint"},_("Alert at 90%"))]);let i=Ze([["month",_("Monthly")],["total",_("Total")]],e.quota_period,{label:_("Data limit period"),cls:"sm",optimistic:!1,onChange:l=>t.patch({quota_period:l})}),a=[10,50,100].map(l=>n("button",{type:"button",class:`dl-chipbtn${e.quota_gb===l?" on":""}`,click:()=>t.patch({quota_gb:String(l)},m(_("Data limit %s GB"),V(l)))},`${V(l)} ${_("GB")}`));return a.push(n("button",{type:"button",class:`dl-chipbtn${e.quota_gb?"":" on"}`,click:()=>t.patch({quota_gb:""},_("No data limit"))},_("Unlimited"))),a.push(n("button",{type:"button",class:"dl-chipbtn",click:()=>{let l=n("input",{type:"number",class:"cbi-input-text dl-w-port",min:0,step:"any",value:e.quota_gb?String(e.quota_gb):""}),d=Me(_("Data limit (GB)"),l,()=>Tn(l.value,e.quota_period==="month"));ae(_("Data limit"),[d],[de()," ",H(_("Save"),async()=>{let c=d.help();if(c.bad){F(c.text,"warning");return}let p=l.value.trim();await t.patch({quota_gb:p},p&&Number(p)>0?m(_("Data limit %s GB"),V(Number(p))):_("No data limit"))&&le()},"positive")]),setTimeout(()=>l.select(),50)}},_("Custom"))),n("div",{class:"dl-tile2"},[n("div",{class:"dl-tile2-label"},[n("span",{},_("Data")),i]),n("div",{class:"dl-tile2-row"},[n("span",{class:"dl-tile2-value"},[se(o),e.quota_limit?n("span",{class:"dl-faint"},` ${m(_("of %s"),se(e.quota_limit))}`):n("span",{class:"dl-faint"},` · ${_("no limit")}`)]),e.quota_period==="month"?n("span",{class:"dl-sub"},_("resets on the 1st")):""]),e.quota_limit?r:"",n("div",{class:"dl-chips-row"},a),e.quota_gb&&e.quota_period==="month"?n("div",{class:"dl-tile2-foot"},[n("span",{class:"dl-muted"},e.bonus_gb?m(_("Includes +%s GB extra this month"),V(e.bonus_gb)):_("Need a little more this month?")),n("a",{href:"#",click:l=>{l.preventDefault(),t.patch({bonus_gb:String((e.bonus_gb||0)+10)},_("+10 GB this month"))}},_("+10 GB this month"))]):"",n("div",{class:"dl-tile2-foot"},[n("span",{class:"dl-muted"},m(_("%s in total"),se(e.total[0]+e.total[1]))),n("button",{type:"button",class:"dl-linkbtn danger",click:()=>It("person",e.id,e.name,()=>setTimeout(()=>t.refresh(),300))},_("Reset usage"))])])}function Ed(t){let e=t.p,o=!!e.hours,[s,r]=(e.hours||"07:00-23:00").split("-"),i=n("input",{type:"time",class:"cbi-input-text",value:s,"aria-label":_("From")}),a=n("input",{type:"time",class:"cbi-input-text",value:r,"aria-label":_("To")}),l=n("div",{class:"dl-tile2-row"},[i,n("span",{class:"dl-faint"},_("to","time range")),a]),d=()=>{let g=`${i.value}-${a.value}`;if(g!==e.hours){if(!Ji.test(i.value)||!Ji.test(a.value))return F(_("Enter both times, like 07:00 and 23:00."),"warning");if(i.value===a.value)return F(_("The start and the end must differ."),"warning");t.patch({hours:g},m(_("Allowed %s–%s"),i.value,a.value))}};l.addEventListener("focusout",g=>{l.contains(g.relatedTarget)||d()});for(let g of[i,a])g.addEventListener("keydown",M=>{M.key==="Enter"&&(M.preventDefault(),d())});let c=n("button",{type:"button",role:"switch","aria-checked":o?"true":"false",class:`dl-switch${o?" on":""}`,"aria-label":_("Limit hours"),click:()=>{if(o)return t.patch({hours:""},_("Any time"));c.classList.add("on"),c.setAttribute("aria-checked","true"),p.textContent=_("Set the hours, then press Enter"),u.appendChild(l),i.focus()}},n("i")),p=n("span",{},o?m(_("%s – %s (router time)"),s,r):_("Any time")),u=n("div",{class:"dl-tile2"},[n("div",{class:"dl-tile2-row"},[n("div",{class:"dl-stack"},[n("span",{class:"dl-tile2-label"},_("Allowed hours")),p]),c]),o?l:""]);return u}function Zi(t){let e=t.p,o=Ze(["internet","lan","both"].map(s=>[s,[v(s==="internet"?"globe":s==="lan"?"home":"shield"),s==="internet"?_("Internet"):s==="lan"?_("Home"):_("Both")]]),e.access,{label:_("Access"),cls:"wide",optimistic:!1,onChange:s=>t.patch({access:s},m(_("Access: %s"),bt(s)))});return n("section",{class:"dl-devsec","aria-label":_("Access and limits")},[n("div",{class:"dl-panel-head"},[n("h3",{},_("Access & limits"))]),n("div",{class:"dl-panel"},[n("div",{class:"dl-stack gap8"},[n("span",{class:"dl-tile2-label"},_("Can reach")),o,n("span",{class:"dl-sub"},Cd(e.access)),e.access==="lan"&&t.st.services.length?Ki(t):"",mt(e)?qi(t):"",e.access==="lan"?Fi(t):""]),n("div",{class:"dl-tiles2"},[Yi(t),Vi(t),Ld(t),Md(t),Ed(t)])])])}function Td(t){let e=t.st,o=n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Locations")),n("span",{class:"dl-spacer"}),e.geo.enabled?Bt("30d",r=>t.map?.setRange(r),!1):"",H(_("Hide"),()=>{t.mapOpen=!1,t.map?.destroy(),t.map=null,t.paintPlaces()},"neutral")]);if(!e.geo.enabled)return n("div",{class:"dl-panel flush"},[o,n("div",{class:"dl-map-off"},oe(_("Locations are off. %s."),n("a",{href:L.url("admin/network/dawnline/settings")},_("Turn them on in Settings"))))]);let s=new ct({openPerson:()=>{},openDevice:(r,i)=>{let a=t.p.devices.find(l=>l.id===i);a&&Ye(t.p,a,t.deviceOpts())}},"30d",280);return t.map=s,requestAnimationFrame(()=>s.mount(t.mapData())),n("div",{class:"dl-panel flush"},[o,s.el])}function Qi(t){let e=t.st;if(!e.geo.enabled)return n("div",{class:"dl-places"},[v("pin"),n("div",{class:"dl-stack"},[n("span",{},_("Locations are off")),n("span",{class:"dl-sub"},_("City-level, from the client IP"))]),n("span",{class:"dl-spacer"}),n("a",{class:"cbi-button cbi-button-neutral",href:L.url("admin/network/dawnline/settings")},_("Turn on"))]);if(t.mapOpen)return t.map&&t.parts.places.contains(t.map.el)?null:Td(t);let o=e.now-30*86400,s=e.geo.points.filter(a=>a.person===t.p.id&&a.ts>=o).sort((a,l)=>l.ts-a.ts),r=[...new Set(s.map(a=>a.city||a.country).filter(Boolean))],i=s[0];return n("div",{class:"dl-places"},[v("pin"),n("div",{class:"dl-stack"},[n("span",{},i?i.city||i.country:_("No locations yet")),n("span",{class:"dl-sub"},i?[G(r.length,"%s place in 30 days","%s places in 30 days"),i.org].filter(Boolean).join(" · "):_("Shown after a device connects"))]),n("span",{class:"dl-spacer"}),s.length?H(_("Show map"),()=>{t.mapOpen=!0,t.paintPlaces()},"neutral"):""])}function Xi(t){let e=t.p,o=t.st,s=t.events.filter(l=>l.person===e.id),r=[],i=[...s].reverse();for(let l=0;l1){let u=p.querySelector(".dl-row-main");dom.content(u,[...Zo(o,d).slice(0,3),n("span",{class:"dl-muted"},G(c,"%s time","%s times"))]),u.title=i.slice(l,l+c).map(g=>g.detail??"").join(` +`)}r.push(p),l+=c-1}let a=H([v("more")],()=>Te(a,[{label:_("Export CSV"),icon:v("download"),run:()=>Xe(o,s,"csv",e.id)},{label:_("Export JSON"),icon:v("download"),run:()=>Xe(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:v("trash"),danger:!0,run:()=>dt(m(_("Clear %s's activity"),e.name),m(_("Removes events about %s and their devices."),e.name),{person:e.id},()=>t.refresh())}]),"neutral",{title:_("Export or clear"),class:"cbi-button cbi-button-neutral dl-icon-only"});return n("div",{class:"dl-panel flush"},[n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Activity")),n("span",{class:"dl-sub"},s.length>10?m(_("latest 10 of %s"),V(s.length)):""),n("span",{class:"dl-spacer"}),a]),r.length?r:n("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var no=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,s,r]=await Promise.all([N.status(30),e?N.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?N.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:s?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o)return n("div",{class:"dl-empty"},[n("h3",{},_("Person not found")),n("p",{},_("They may have been removed.")),n("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},_("Back to Servers"))]);this.p=o;for(let a of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[a]=n("div",{});this.parts.devices.className="dl-person-devices";let s=n("div",{},[this.parts.crumbs,this.parts.head,n("div",{class:"dl-grid-person"},[n("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),n("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(a=>a.id===r.get("device"));return i?setTimeout(()=>Ye(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>pt(this.p,this.deviceOpts()),50),this.poller=nt({fetch:a=>{let l=a||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>s.isConnected,apply:(a,l)=>this.apply(a,l)}),s}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let s=this.st.people.find(r=>r.id===this.id);if(!s){o||(location.href=jt(this.p?.server));return}this.p=s,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let s=await q(()=>N.personUpdate(this.p.id,e),o);if(!s)return!1;this.poller?.claim();let r=this.st.people.findIndex(a=>a.id===this.p.id);return(i=s.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=s.person),this.p=s.person,this.paint(),!0}get today(){return Ge(this.series.length?this.series:this.st.series)}get core(){return Ot(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,server:this.st.servers.find(e=>e.id===this.p.server),events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return n("nav",{class:"dl-crumbs","aria-label":_("Breadcrumb")},[n("a",{href:jt(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),n("span",{},"/"),n("a",{href:jt(e.server)},_("People")),n("span",{},"/"),n("span",{},e.name)])}paint(e=!1){Ne(this.parts.crumbs,this.crumbs(),e),Ne(this.parts.head,Ui(this),e),Ne(this.parts.traffic,Wi(this),e),Ne(this.parts.devices,Gi(this),e),Ne(this.parts.limits,Zi(this),e),this.paintPlaces(e),Ne(this.parts.activity,Xi(this),e)}paintPlaces(e=!1){let o=Qi(this);o&&Ne(this.parts.places,o,e&&!this.mapOpen)}};var Sd={ok:"check",warn:"alert",error:"x",skip:"pause"},oo=class{constructor(e,o,s,r){this.el=n("div",{});this.wdEl=n("div",{});this.checksEl=n("div",{class:"dl-panel"});this.recentEl=n("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=n("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=s,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,n("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,s)}async run(e){let o=e?await Jn(e):await N.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[n("div",{class:"dl-panel-head"},[n("h3",{},_("Checks"))]),n("p",{class:"dl-muted dl-loading"},_("Running checks…"))]);return}let o=e.filter(a=>a.status==="error").length,s=e.filter(a=>a.status==="warn").length;dom.content(this.summary,o?yt("error",G(o,"%s problem needs attention.","%s problems need attention.")):s?yt("warn",G(s,"%s warning.","%s warnings.")):yt("ok",_("All checks passed.")));let r=new Map;for(let a of this.sl.watchdog.repairs)r.set(a.id,Math.max(r.get(a.id)??0,a.ts));let i=()=>this.run();dom.content(this.checksEl,[n("div",{class:"dl-panel-head"},[n("h3",{},_("Checks")),n("span",{class:"dl-spacer"}),H(_("Run again"),i)]),n("ul",{class:"dl-checks"},e.map(a=>n("li",{},[n("span",{class:`dl-check-icon ${a.status}`},v(Sd[a.status])),n("div",{class:"dl-check-body"},[n("div",{class:"dl-check-title"},a.title),n("div",{class:"dl-check-detail"},a.detail),r.has(a.id)?n("div",{class:"dl-check-repaired"},m(_("Repaired by the watchdog at %s"),Ft(r.get(a.id)))):""]),Qo(a,l=>void this.run(l),i)])))])}paintLive(e,o){this.sl=e,this.events=o;let s=e.watchdog,r=s.beat!=null&&s.now-s.beat>180,i=s.repairs.filter(d=>s.now-d.ts<86400),a=i[i.length-1],l=be(s.enabled,_("Watchdog repairs"),async d=>{await q(()=>N.settingsUpdate({watchdog:d?"1":"0"}),d?_("Watchdog on"):_("Watchdog off"))||vo(l,!d);let p=await N.serviceLog().catch(()=>null);p&&this.paintLive(p,this.events)});dom.content(this.wdEl,n("div",{class:"dl-panel dl-wd"},[n("div",{class:"dl-wd-head"},[n("span",{class:`dl-wd-tile${s.enabled?"":" off"}`},v("shield")),n("div",{class:"dl-stack"},[n("span",{class:"dl-wd-title"},_("Watchdog")),n("span",{class:"dl-sub"},s.enabled?_("Every minute it checks the tunnels and services and repairs what it can on its own."):_("Off: problems are only written to the log. Nothing is repaired on its own."))]),n("span",{class:"dl-spacer"}),l]),n("div",{class:"dl-wd-foot"},[n("div",{class:"dl-wd-chips"},s.targets.map(d=>n("span",{class:`dl-check-chip${d.ok?"":" error"}`,title:d.ok?_("OK"):d.tries?`${_("Not working")} · ${G(d.tries,"%s repair","%s repairs")}`:_("Not working")},[v(d.ok?"check":"x"),d.name]))),n("span",{class:`dl-sub${r?" dl-warn-text":""}`},r?m(_("The agent has not checked in for %s min; cron restarts it after 5."),V(Math.round((s.now-s.beat)/60))):[s.last?m(_("Looked %s"),ce(s.last,s.now)):_("Starts within a minute")," · ",i.length?m(N_(i.length,"%s repair today, last %s at %s","%s repairs today, last %s at %s"),V(i.length),a.name,Ft(a.ts)):_("no repairs today")])])])),this.paintRecent()}paintRecent(){let e=(this.sl.watchdog.now||Date.now()/1e3)-604800,o=[...this.events.map(r=>({ts:r.ts,ev:r})),...this.sl.log.map(r=>({ts:r.ts,sys:r}))].filter(r=>r.ts>=e&&Sn(r)).sort((r,i)=>i.ts-r.ts),s=n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Recent problems")),n("span",{class:"dl-spacer"}),o.length?n("a",{href:"#",click:r=>(r.preventDefault(),this.toLog())},`${_("All in Log")} →`):""]);if(!o.length){dom.content(this.recentEl,[s,n("div",{class:"dl-recent-empty"},[n("span",{class:"dl-check-icon ok"},v("check")),_("No problems in the last 7 days.")])]);return}dom.content(this.recentEl,[s,...o.slice(0,8).map(r=>{if(r.sys){let i=r.sys,a=`${i.ts}|${i.msg}`;return qn(i,this.open.has(a),()=>{this.open.delete(a)||this.open.add(a),this.paintRecent()},Ft(i.ts))}return ft(this.st,r.ev,{time:Ft(r.ts)})})])}};var so=300,Pd=["all","connections","people","system","problems"],ro=class{constructor(e,o,s){this.events=[];this.system=[];this.kind="all";this.shown=so;this.open=new Set;this.list=n("div",{});this.sub="";this.tabs=n("div",{class:"dl-seg",role:"tablist"});this.st=e,this.take(o),this.system=s,this.el=n("div",{},[n("div",{class:"dl-toolbar"},[this.tabs]),this.list]),this.paint()}actions(){let e=()=>this.kind==="all"?"":this.kind,o=i=>()=>{let a=this.filtered().reverse();Xe(this.st,a.filter(l=>l.ev).map(l=>l.ev),i,e(),a.filter(l=>l.sys).map(l=>l.sys))},s=H([v("download"),` ${_("Export")}`],()=>Te(s,[{label:_("CSV (spreadsheet)"),icon:v("download"),run:o("csv")},{label:"JSON",icon:v("download"),run:o("json")}])),r=H([v("trash"),` ${_("Clear")}`],()=>dt(_("Clear the log"),_("Removes events from the log on the router."),{},()=>this.reload(),this.kind==="all"?void 0:this.kind,!0));return[s,r]}take(e){this.events=e.events,this.policy=e.policy;let o=Rt.filter(r=>!e.policy.categories.includes(r)),s=Pn(e.policy);this.sub=o.length?`${s} ${m(_("Not recorded: %s."),o.map(r=>Ke(r).toLowerCase()).join(", "))}`:s}async reload(){let[e,o]=await Promise.all([N.events(2e4).catch(()=>null),N.serviceLog().catch(()=>null)]);e&&this.take(e),o&&(this.system=o.log),this.paint()}items(){return[...this.events.map(e=>({ts:e.ts,ev:e})),...this.system.map(e=>({ts:e.ts,sys:e}))].sort((e,o)=>o.ts-e.ts)}matches(e,o){return o==="all"?!0:o==="problems"?Sn(e):o==="system"?!!e.sys:!!e.ev&&Zt(e.ev.type)===o}filtered(){return this.items().filter(e=>this.matches(e,this.kind))}paintTabs(e){dom.content(this.tabs,Pd.map(o=>n("button",{type:"button",role:"tab",class:o===this.kind?"on":"","aria-selected":o===this.kind?"true":"false",click:()=>this.show(o)},[o==="all"?_("All"):o==="system"?_("System"):Ke(o),n("b",{},String(e.filter(s=>this.matches(s,o)).length))])))}show(e){this.kind=e,this.shown=so,this.paint()}paint(){this.paintTabs(this.items());let e=this.filtered();if(!e.length){dom.content(this.list,n("div",{class:"dl-empty"},[n("p",{},this.events.length||this.system.length?_("No events match."):_("The log is empty."))]));return}let o=[],s="",r=null;for(let i of e.slice(0,this.shown)){let a=li(i.ts);a!==s&&(s=a,r=n("div",{class:"dl-panel flush"},n("div",{class:"dl-panel-head pad"},n("h3",{},a))),o.push(r));let l=new Date(i.ts*1e3).toLocaleTimeString(ie(),{hour:"2-digit",minute:"2-digit"});if(i.sys){let d=`${i.sys.ts}|${i.sys.msg}`;r.appendChild(qn(i.sys,this.open.has(d),()=>{this.open.delete(d)||this.open.add(d),this.paint()},l))}else r.appendChild(ft(this.st,i.ev,{time:l}))}e.length>this.shown&&o.push(n("div",{class:"dl-more-row"},H(m(_("Show %s more of %s"),V(Math.min(so,e.length-this.shown)),V(e.length-this.shown)),()=>{this.shown+=so,this.paint()}))),dom.content(this.list,o)}};var $d=["health","log"],Dd=t=>t==="log"?_("Log"):_("Health"),rs=2e4,io=class{constructor(){this.tab=new URLSearchParams(location.search).get("tab")==="log"?"log":"health";this.segEl=n("div",{class:"dl-seg dl-srvsections dl-diag-tabs",role:"tablist","aria-label":_("Diagnostics")});this.subEl=n("span",{class:"dl-muted"});this.actionsEl=n("div",{class:"dl-row-actions"});this.bodyEl=n("div",{});this.eventsAt=0}load(){return this.eventsAt=Date.now(),Promise.all([N.status(1),N.events(rs),N.serviceLog()])}render([e,o,s]){return this.log=new ro(e,o,s.log),this.health=new oo(e,s,o.events,()=>{this.show("log"),this.log.show("problems")}),this.show(this.tab),nt({fetch:async()=>{let r=this.tab==="log",[i,a]=await Promise.all([N.serviceLog().catch(()=>null),r?N.events(rs).catch(()=>null):Promise.resolve(null)]);return i||a?{n:i,e:a}:null},every:10,active:()=>this.bodyEl.isConnected,apply:({n:r,e:i})=>this.take(r,i)}),n("div",{},[n("div",{class:"dl-pagehead"},[n("div",{class:"dl-stack"},[n("h2",{class:"dl-h1"},_("Diagnostics")),this.subEl]),this.actionsEl]),this.segEl,this.bodyEl])}take(e,o){o&&(this.log.take(o),this.eventsAt=Date.now()),e&&(this.log.system=e.log),e&&this.health.paintLive(e,o?.events??this.health.events),this.tab==="log"&&this.log.paint()}show(e){this.tab=e,dom.content(this.segEl,$d.map(o=>n("button",{type:"button",role:"tab",class:o===e?"on":"","aria-selected":o===e?"true":"false",click:()=>o!==this.tab&&this.show(o)},Dd(o)))),this.bodyEl.replaceChildren(e==="log"?this.log.el:this.health.el),this.subEl.textContent=e==="log"?this.log.sub:_("Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own."),dom.content(this.actionsEl,e==="log"?this.log.actions():""),e==="log"?(this.log.paint(),Date.now()-this.eventsAt>1e4&&N.events(rs).then(o=>this.take(null,o)).catch(()=>null)):this.health.checks||this.health.run()}};var ea=":root{--dl-card: var(--panel-bg, var(--background-color-high, transparent));--dl-elevated: var(--elevated, var(--background-color-high, Canvas));--dl-line: var(--border, var(--border-color-medium, color-mix(in srgb, currentColor 14%, transparent)));--dl-fg: var(--foreground, var(--text-color-highest, currentColor));--dl-soft: var(--muted, color-mix(in srgb, var(--dl-fg) 5%, transparent));--dl-soft-hover: var(--soft-hover, color-mix(in srgb, var(--dl-fg) 10%, transparent));--dl-fg-muted: var(--muted-foreground, color-mix(in srgb, currentColor 65%, transparent));--dl-fg-faint: var(--text-tertiary, color-mix(in srgb, currentColor 50%, transparent));--dl-accent: var(--accent, #3a83f7);--dl-ok: var(--success, #00a240);--dl-warn: var(--warning, #e25507);--dl-bad: var(--danger, #e02e2a);--dl-info: var(--info, #2c67c5);--dl-ok-wash: var(--success-a15, color-mix(in srgb, var(--dl-ok) 15%, transparent));--dl-warn-wash: var(--warning-a15, color-mix(in srgb, var(--dl-warn) 15%, transparent));--dl-bad-wash: var(--destructive-a15, color-mix(in srgb, var(--dl-bad) 15%, transparent));--dl-info-wash: var(--info-a15, color-mix(in srgb, var(--dl-info) 15%, transparent));--dl-track: var(--foreground-a10, color-mix(in srgb, var(--dl-fg) 10%, transparent));--dl-chart-1: var(--chart-blue, #3a83f7);--dl-chart-2: var(--chart-green, var(--dl-ok));--dl-ring: var(--ring, #3a83f7);--dl-primary: var(--primary, var(--dl-fg));--dl-primary-fg: var(--primary-foreground, var(--dl-elevated));--dl-mono: var(--font-mono, ui-monospace, Menlo, Consolas, monospace);--dl-shadow: var(--shadow-sm, none);--dl-radius: 16px}:root[data-darkmode=true]{--dl-card: var(--panel-bg, var(--background-color-low, transparent));--dl-elevated: var(--elevated, var(--background-color-low, Canvas));--dl-accent: var(--accent, #006efe);--dl-ok: var(--success, #40c977);--dl-warn: var(--warning, #ff8549);--dl-bad: var(--danger, #ff6764);--dl-info: var(--info, #5ba2fe);--dl-ring: var(--ring, #5ba2febc)}.dl-root,.dl-modal{cursor:default}:is(.dl-root,.dl-modal) :is(input:not([type=checkbox],[type=radio],[type=range],[type=button],[type=submit]),textarea,[contenteditable=true]){cursor:text}.dl-icon-wrap{display:inline-flex;align-items:center;justify-content:center;line-height:0}.dl-icon{width:16px;height:16px}.dl-icon-btn{display:inline-flex!important;align-items:center;gap:6px}.dl-muted{color:var(--dl-fg-muted)}.dl-faint,.dl-sep{color:var(--dl-fg-faint)}.dl-nowrap{white-space:nowrap}.dl-mono{font-family:var(--dl-mono);font-size:13px}.dl-spacer{flex:1}.dl-pill{display:inline-flex;align-items:center;gap:4px;height:20px;padding:0 8px;border-radius:999px;font-size:12px;line-height:20px;font-weight:500;white-space:nowrap;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pill.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-pill.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-pill.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-pill.accent{background:var(--dl-info-wash);color:var(--dl-info)}.dl-pill.off{opacity:.75}.dl-panel{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:16px;margin:0 0 16px;min-width:0;box-shadow:var(--dl-shadow)}.dl-panel-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin:0 0 12px}.dl-panel-head h3{margin:0!important;padding:0;font-size:16px;line-height:24px;font-weight:500;border:0;background:none}.dl-tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:0 0 16px}.dl-tile{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:14px 16px;min-width:0;box-shadow:var(--dl-shadow)}.dl-tile-label{font-size:12px;line-height:16px;font-weight:500;color:var(--dl-fg-faint)}.dl-tile-value{font-size:24px;line-height:32px;font-weight:500;margin-top:4px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;letter-spacing:-.01em}.dl-tile-sub{font-size:12px;line-height:16px;color:var(--dl-fg-muted);margin-top:2px;font-variant-numeric:tabular-nums}.dl-grid2{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:0 16px}@media(max-width:960px){.dl-grid2{grid-template-columns:minmax(0,1fr)}}.dl-chart{display:block;width:100%;height:120px}.dl-bar-down{fill:var(--dl-chart-1)}.dl-bar-up{fill:var(--dl-chart-2);opacity:.8}.dl-legend{display:flex;gap:16px;font-size:12px;color:var(--dl-fg-muted);margin-top:8px}.dl-legend i{display:inline-block;width:8px;height:8px;border-radius:999px;margin-right:6px;vertical-align:0}.dl-legend .down{background:var(--dl-chart-1)}.dl-legend .up{background:var(--dl-chart-2)}.dl-events{list-style:none;margin:0;padding:0}.dl-events li{display:flex;gap:12px;align-items:baseline;padding:8px 0;border-top:1px solid var(--dl-line);font-size:14px;line-height:20px;min-width:0}.dl-events li:first-child{border-top:0;padding-top:0}.dl-ev-time{flex:0 0 88px;color:var(--dl-fg-faint);font-variant-numeric:tabular-nums;white-space:nowrap;font-size:13px}.dl-ev-dot{flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);transform:translateY(-2px)}.dl-ev-dot.ok{background:var(--dl-ok)}.dl-ev-dot.warn{background:var(--dl-warn)}.dl-ev-dot.bad{background:var(--dl-bad)}.dl-ev-dot.accent{background:var(--dl-accent)}.dl-row>.dl-ev-dot,.dl-dev-log-row>.dl-ev-dot{margin:0 4px}.dl-ev-tile{flex:none;display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;margin:-2px -4px;border-radius:7px;background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent);align-self:center}.dl-ev-tile .dl-icon-wrap{display:inline-flex}.dl-ev-tile .dl-icon{width:14px;height:14px}.dl-row.dl-ev-by-admin{background:color-mix(in srgb,var(--dl-accent) 6%,transparent)}.dl-you{color:var(--dl-accent);font-weight:500}.dl-ev-kind{color:var(--dl-fg-faint)}.dl-slotbar{display:flex;align-items:center;gap:8px;margin:8px 0 0 44px}.dl-slotbar-segs{display:flex;gap:3px;flex:none;max-width:100%}.dl-slotbar-segs i{flex:1;min-width:2px;display:block;height:4px;border-radius:2px;background:var(--dl-soft-hover)}.dl-slotbar-segs i.used{background:var(--dl-fg-muted)}.dl-slotbar-text{font-size:12px;color:var(--dl-fg-faint);font-variant-numeric:tabular-nums}.dl-slotbar-segs i.over{background:color-mix(in srgb,var(--dl-warn) 80%,transparent)}.dl-ev-srv{flex:none;font-size:11px;line-height:18px;padding:0 8px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);white-space:nowrap}.dl-ev-by-system{--sys: var(--dl-fg-muted)}.dl-ev-by-system.ok{--sys: var(--dl-ok)}.dl-ev-by-system.warn{--sys: var(--dl-warn)}.dl-ev-by-system.bad{--sys: var(--dl-bad)}.dl-ev-tile.ev{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-ev-tile.ev.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-ev-tile.ev.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-ev-tile.ev.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-ev-tile.ev.accent{background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent)}.dl-ev-tile.sys{background:color-mix(in srgb,var(--sys) 16%,transparent);color:var(--sys)}.dl-row.dl-ev-by-system{background:color-mix(in srgb,var(--sys) 6%,transparent)}.dl-sys-src{color:var(--sys)}.dl-ev-by-system:not(.ok):not(.warn):not(.bad) .dl-sys-src{color:var(--dl-fg)}.dl-ev-text{min-width:0;overflow-wrap:anywhere}.dl-server{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}.dl-server-name{font-size:16px;line-height:24px;font-weight:500}.dl-kv{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:6px 24px;margin:12px 0 0;font-size:14px;line-height:20px}.dl-kv dt{color:var(--dl-fg-muted);font-weight:400;margin:0}.dl-kv dd{margin:0;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}";var ta='.dl-plist{display:block}.dl-plist>.dl-card{display:block;margin:0 0 12px;padding:16px;min-width:0;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);box-shadow:var(--dl-shadow)}.dl-plist>.dl-card.dl-filtered{display:none}.dl-plist>.dl-card.dl-off :is(.dl-card-name,.dl-avatar,.dl-access,.dl-slotbar,.dl-chips,.dl-pill-ic,.dl-use-num,.dl-pside-foot,.dl-pside-state){opacity:.45}.dl-plist>.dl-card.dl-off .dl-usebar i{background:var(--dl-fg-faint)}.dl-plist>.dl-card.dl-off .dl-chip-tag{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pcard:has(>.dl-pstrip){row-gap:14px}.dl-pstrip{grid-column:1 / -1;display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin:0 -16px -16px;padding:10px 16px;border-top:1px solid var(--dl-line);border-radius:0 0 var(--dl-radius) var(--dl-radius);font-size:14px;line-height:20px}.dl-pstrip.warn{background:color-mix(in srgb,var(--dl-warn) 7%,transparent)}.dl-pstrip.bad{background:color-mix(in srgb,var(--dl-bad) 7%,transparent)}.dl-pstrip-text{flex:1;min-width:0;display:flex;flex-wrap:wrap;align-items:baseline;gap:0 8px}.dl-pstrip-text b{font-weight:500}.dl-pstrip>.cbi-button{flex:none;height:32px!important}.dl-plist-none{color:var(--dl-fg-muted);text-align:center;padding:28px 16px;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius)}.dl-card-head{display:flex;align-items:center;flex-wrap:wrap;gap:6px 8px}.dl-avatar{flex:0 0 auto;width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;color:var(--dl-fg);background:var(--dl-soft);position:relative;margin-right:4px;letter-spacing:.02em}.dl-avatar.online:after{content:"";position:absolute;right:-1px;bottom:-1px;width:9px;height:9px;border-radius:50%;background:var(--dl-ok);box-shadow:0 0 0 2px var(--dl-card)}.dl-card-name{font-size:16px;line-height:24px;font-weight:500}.dl-card-slug{font-size:13px;color:var(--dl-fg-faint);font-family:var(--dl-mono)}.dl-quota{margin:8px 0 0 44px;max-width:320px;height:6px;border-radius:999px;background:var(--dl-track);overflow:hidden}.dl-quota>i{display:block;height:100%;background:var(--dl-accent);border-radius:999px}.dl-quota.warn>i{background:var(--dl-warn)}.dl-quota.bad>i{background:var(--dl-bad)}.dl-chips{display:flex;flex-wrap:wrap;gap:6px;margin:12px 0 0 44px}.dl-chip{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;max-width:240px;height:28px;padding:0 12px 0 10px;border-radius:999px;font-size:13px;background:var(--dl-soft);color:var(--dl-fg);transition:background .15s}.dl-chip:hover{background:var(--dl-soft-hover)}.dl-chip:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-chip .dl-icon{width:14px;height:14px;color:var(--dl-fg-muted)}.dl-chip.add{background:transparent;border:1px dashed color-mix(in srgb,var(--dl-fg) 28%,transparent);color:var(--dl-fg-muted)}.dl-chip.add:hover{background:var(--dl-soft);color:var(--dl-fg);border-color:color-mix(in srgb,var(--dl-fg) 45%,transparent)}.dl-chip.add:hover .dl-icon{color:var(--dl-fg)}.dl-chip.disabled .dl-chip-name{text-decoration:line-through;color:var(--dl-fg-faint)}.dl-chip-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-dot{flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);opacity:.6}.dl-dot.online{background:var(--dl-ok);opacity:1;box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-empty{text-align:center;padding:40px 16px;background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius)}.dl-empty .dl-icon-wrap{width:40px;height:40px;border-radius:12px;background:var(--dl-soft);margin-bottom:12px}.dl-empty .dl-icon{width:20px;height:20px}.dl-empty h3{margin:0 0 4px!important;font-size:16px;font-weight:500}.dl-empty p{margin:0 0 16px;color:var(--dl-fg-muted);font-size:14px}.dl-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:0 0 16px}.dl-toolbar .dl-muted{font-size:13px}@media(max-width:640px){.dl-slotbar,.dl-chips,.dl-quota{margin-left:0}.dl-btn-label{display:none}}.cbi-value.dl-block{display:block!important}.cbi-value.dl-block>.cbi-value-title{display:block;width:auto;float:none;text-align:left;padding:0 0 8px}.cbi-value.dl-block>.cbi-value-field{display:block;width:100%;margin:0}.dl-people-find{width:160px;min-width:0}.dl-people-find[hidden]{display:none}';var na="#modal_overlay{z-index:1100!important}.dl-dd{position:fixed;z-index:1200;min-width:200px;padding:4px;border-radius:12px;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:0 12px 32px #0000004d;display:flex;flex-direction:column}.dl-dd button{all:unset;cursor:pointer;display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;font-size:13px;color:var(--dl-fg)}.dl-dd button .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted)}.dl-dd button:hover,.dl-dd button:focus-visible{background:var(--dl-soft)}.dl-dd button.danger,.dl-dd button.danger .dl-icon{color:var(--dl-bad, #e5484d)}.dl-dd button.warn,.dl-dd button.warn .dl-icon{color:var(--dl-warn)}.dl-dd hr{border:0;border-top:1px solid var(--dl-line);margin:4px 0}.dl-chipbtn b{font-weight:500;font-size:11px;margin-left:6px;opacity:.6}.dl-setsub{margin:20px 0 8px!important;font-size:13px;font-weight:500;color:var(--dl-fg)}.dl-row-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.dl-more-row{display:flex;justify-content:center;padding:8px 0 16px}.dl-dsec-actions{display:flex;align-items:center;gap:12px}.dl-kv-act{display:inline-flex;align-items:center;gap:12px;flex-wrap:wrap}.dl-linkbtn,.dl-bento-head a,.dl-bento-foot a,.dl-panel-head a,.dl-dsec-head a,.dl-tile2-foot a{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:4px;height:26px;padding:0 9px;margin:-4px -6px;border-radius:8px;font-size:12px;font-weight:500;color:var(--dl-fg-muted);text-decoration:none!important;white-space:nowrap;transition:background .12s,color .12s}.dl-bento-head a,.dl-bento-foot a,.dl-panel-head a,.dl-dsec-head a,.dl-tile2-foot a{color:var(--dl-accent)}.dl-linkbtn:hover,.dl-bento-head a:hover,.dl-bento-foot a:hover,.dl-panel-head a:hover,.dl-dsec-head a:hover,.dl-tile2-foot a:hover{background:var(--dl-soft);color:var(--dl-fg);text-decoration:none!important}.dl-bento-head a:hover,.dl-bento-foot a:hover,.dl-panel-head a:hover,.dl-dsec-head a:hover,.dl-tile2-foot a:hover{background:color-mix(in srgb,var(--dl-accent) 12%,transparent);color:var(--dl-accent)}.dl-linkbtn:focus-visible,.dl-bento-head a:focus-visible,.dl-bento-foot a:focus-visible,.dl-panel-head a:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-linkbtn.danger:hover{color:var(--dl-bad);background:var(--dl-bad-wash)}.dl-ifcards{display:flex;flex-direction:column;gap:20px;margin:24px 0}.dl-ifcard .dl-setsec-body{gap:14px}.dl-iflead{display:flex;flex-direction:column;gap:2px;padding-top:14px;border-top:1px solid var(--dl-line)}.dl-iflead b{font-size:14px;font-weight:500}.dl-ifgroup h4{margin:0 0 8px!important;padding:0!important;font-size:11px!important;font-weight:500!important;letter-spacing:.06em;text-transform:uppercase;color:var(--dl-fg-muted);border:0!important;background:none!important}.dl-ifgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:8px}.dl-if{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;min-height:52px;padding:8px 12px 8px 10px;min-width:0;border:1px solid var(--dl-line);border-radius:10px;background:var(--dl-card);transition:background .15s,border-color .15s}.dl-if:hover{background:var(--dl-soft)}.dl-if:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-if-ic{width:30px;height:30px;border-radius:8px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-if-ic .dl-icon{width:16px;height:16px}.dl-if-main{display:flex;flex-direction:column;min-width:0;flex:1}.dl-if-name{font-size:13.5px;font-weight:500;color:var(--dl-fg);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-if-sub{font:11px/16px var(--dl-mono);color:var(--dl-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-if.sel{border-color:var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 9%,transparent)}.dl-if.sel .dl-if-ic{background:color-mix(in srgb,var(--dl-accent) 18%,transparent);color:var(--dl-accent)}.dl-if-check{color:var(--dl-accent);display:inline-flex}.dl-if-check .dl-icon{width:16px;height:16px}.dl-if.auto{border-color:color-mix(in srgb,var(--dl-ok) 55%,transparent);background:var(--dl-ok-wash);cursor:default}.dl-if.auto .dl-if-ic{background:color-mix(in srgb,var(--dl-ok) 18%,transparent);color:var(--dl-ok)}.dl-if-badge{display:inline-flex;align-items:center;gap:5px;font-size:10.5px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;flex:0 0 auto}.dl-if-badge.ok{color:var(--dl-ok)}.dl-if.off{cursor:default;opacity:.5}.dl-if.off:hover{background:var(--dl-card)}.dl-if.warn{border-color:color-mix(in srgb,var(--dl-warn) 60%,transparent)}.dl-if-wanctl{gap:10px;align-items:center}.dl-if-wanctl select{max-width:240px}.dl-if-summary{min-width:0;line-height:18px}.dl-warn{color:var(--dl-warn)}.dl-w-ip{width:160px}.dl-dnspick{padding-top:8px;border-top:1px solid var(--dl-line)}.dl-dnspick .dl-row-actions{gap:10px}.cbi-dropdown>ul:not(.dropdown) .dl-opt-note{display:none}.dl-note{display:flex;gap:8px;align-items:flex-start;padding:10px 12px;border-radius:10px;font-size:12.5px;line-height:18px;margin:0 0 10px;background:var(--dl-soft)}.dl-note.warn{background:var(--dl-warn-wash, color-mix(in srgb, var(--dl-warn) 14%, transparent))}.dl-note .dl-icon{width:15px;height:15px;flex:0 0 auto;margin-top:1px;color:var(--dl-warn)}.dl-stale{align-self:flex-start;margin-top:4px;font-size:10.5px}.dl-root .cbi-button.dl-btn-warn,.dl-btn-warn.cbi-button{background:var(--dl-warn-wash)!important;color:var(--dl-warn)!important;border-color:color-mix(in srgb,var(--dl-warn) 35%,transparent)!important}.dl-root .cbi-button.dl-btn-warn:hover,.dl-btn-warn.cbi-button:hover{background:color-mix(in srgb,var(--dl-warn) 24%,transparent)!important}.dl-btn-warn .dl-icon{color:var(--dl-warn)}.dl-srvtabs{display:flex;flex-wrap:wrap;gap:6px;padding:4px;margin:0 0 20px;border-radius:12px;background:var(--dl-soft);width:fit-content;max-width:100%}.dl-srvtab{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:8px;height:34px;padding:0 14px;border-radius:9px;font-size:13px;color:var(--dl-fg-muted);text-decoration:none!important;white-space:nowrap}.dl-srvtab b{font-weight:500}.dl-srvtab i.dot{width:7px;height:7px;border-radius:50%;background:var(--dl-fg-faint);flex:0 0 auto}.dl-srvtab i.dot.ok{background:var(--dl-ok);animation:dl-srv-pulse 2s ease-out infinite}.dl-srvtab i.dot.bad{background:var(--dl-bad)}.dl-srvtab i.dot.warn{background:var(--dl-warn)}@keyframes dl-srv-pulse{0%{box-shadow:0 0 color-mix(in srgb,var(--dl-ok) 55%,transparent)}70%,to{box-shadow:0 0 0 6px transparent}}@media(prefers-reduced-motion:reduce){.dl-srvtab i.dot.ok{animation:none}}.dl-srvtab:hover{color:var(--dl-fg);background:var(--dl-soft-hover)}.dl-srvtab.on{background:var(--dl-card);color:var(--dl-fg);box-shadow:0 1px 2px #0000002e,inset 0 0 0 1px var(--dl-line)}.dl-srvtab:focus-visible{outline:2px solid var(--dl-ring);outline-offset:1px}.dl-srvtab.add{color:var(--dl-fg-muted)}.dl-srvtab.add .dl-icon{width:14px;height:14px}.dl-srvhead{display:flex;flex-direction:column;gap:14px;margin:0 0 20px}.dl-srvhead .dl-title-row{display:flex;align-items:center;gap:10px}.dl-srvhead .dl-h1{margin:0!important}.dl-metrics.compact .dl-metric{padding:14px 18px}.dl-metrics.compact .dl-metric-value{display:flex;align-items:center;gap:6px;font-size:18px;line-height:26px;min-width:0}.dl-metrics.compact .dl-metric-value>span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-metrics.compact .dl-metric-value .dl-mono{font-size:15px}.dl-metrics.compact .cbi-button{flex:0 0 auto}.dl-srvsections{margin:0 0 16px}.dl-srvbody>.dl-setsec,.dl-srvbody>.dl-ifcards{margin:0}.dl-srvbody .dl-ifcards{margin:0}.dl-metric-ic{display:inline-flex;align-items:center;gap:8px;font-size:16px}.dl-metric-ic .dl-icon{width:18px;height:18px;color:var(--dl-accent)}.dl-keyrow{display:inline-flex;align-items:center;gap:8px;min-width:0}.dl-keyrow code{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;background:none;padding:0}.dl-params{border:1px solid var(--dl-line);border-radius:12px;background:var(--dl-card)}.dl-params>summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;color:var(--dl-fg);user-select:none}.dl-params>summary::-webkit-details-marker{display:none}.dl-params>summary>.dl-icon-wrap{display:inline-flex;color:var(--dl-fg-muted);transition:transform .15s}.dl-params>summary>.dl-icon-wrap .dl-icon{width:15px;height:15px}.dl-params[open]>summary>.dl-icon-wrap{transform:rotate(90deg)}.dl-params>summary:focus{outline:none}.dl-params>summary:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px;border-radius:12px}.dl-params>summary:hover{background:var(--dl-soft);border-radius:12px}.dl-pcount{font-size:11px;padding:0 6px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:10px;padding:4px 14px 14px}.dl-pgroup{display:flex;flex-direction:column;gap:6px;padding:12px;border-radius:10px;background:var(--dl-soft);min-width:0}.dl-pgroup-head{display:flex;align-items:center;gap:8px;font-size:13px}.dl-pgroup-head b{font-weight:500}.dl-pgroup-head .dl-icon{width:14px;height:14px;color:var(--dl-fg-muted)}.dl-pgroup p{margin:0!important;font-size:12px;line-height:17px;color:var(--dl-fg-muted)}.dl-pvals{display:flex;flex-wrap:wrap;gap:4px;margin-top:2px}.dl-pv{display:inline-flex;align-items:stretch;max-width:100%;border-radius:6px;overflow:hidden;font:500 11.5px/22px var(--dl-mono);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-pv i{font-style:normal;padding:0 6px;background:var(--dl-card);color:var(--dl-fg-faint)}.dl-pv b{font-weight:500;padding:0 7px;color:var(--dl-fg);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}";var oa=".dl-methods{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:10px}.dl-method{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;gap:10px;padding:14px;border-radius:12px;border:1px solid var(--dl-line);background:var(--dl-card);transition:border-color .15s,background .15s;min-width:0}.dl-method:hover{background:var(--dl-soft)}.dl-method:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-method.on{border-color:var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 8%,transparent);box-shadow:inset 0 0 0 1px var(--dl-accent)}.dl-method.off{cursor:not-allowed;opacity:.55}.dl-method.off:hover{background:var(--dl-card)}.dl-method-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}.dl-method-head .dl-pill{flex:none}.dl-method-head b{font-weight:500;font-size:14.5px;flex:1}.dl-method-ic{width:32px;height:32px;border-radius:9px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;color:var(--dl-fg-muted);flex:0 0 auto}.dl-method-ic .dl-icon{width:17px;height:17px}.dl-method.on .dl-method-ic{background:color-mix(in srgb,var(--dl-accent) 18%,transparent);color:var(--dl-accent)}.dl-method p{margin:0!important;font-size:12.5px;line-height:18px;color:var(--dl-fg-muted);flex:1}.dl-method-meters{display:flex;gap:16px}.dl-dots{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--dl-fg-faint)}.dl-dots-row{display:inline-flex;gap:3px}.dl-dots-row i{width:6px;height:6px;border-radius:50%;background:var(--dl-line)}.dl-dots-row i.on{background:var(--dl-fg-muted)}.dl-method.on .dl-dots-row i.on{background:var(--dl-accent)}.dl-method-foot{display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--dl-fg-faint);padding-top:8px;border-top:1px solid var(--dl-line)}.dl-method-foot .dl-icon{width:13px;height:13px;flex:0 0 auto}.dl-method.off .dl-method-foot{color:var(--dl-warn)}.dl-ibadge{display:inline-flex;align-items:center;gap:3px;height:22px;padding:0 6px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);flex:0 0 auto}.dl-ibadge .dl-icon{width:13px;height:13px}.dl-ibadge.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-ibadge.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-access{display:inline-flex;gap:4px;flex:0 0 auto}.dl-ibadge.lan{background:color-mix(in srgb,var(--dl-accent) 16%,transparent);color:var(--dl-accent)}.dl-ibadge.inet{background:var(--dl-ok-wash);color:var(--dl-ok)}";var sa=".dl-addrbar{display:inline-flex;align-items:stretch;flex-wrap:nowrap;max-width:100%;margin-top:4px;border:1px solid var(--dl-line);border-radius:10px;background:var(--dl-card);overflow:hidden}.dl-addrbar-seg{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;gap:7px;padding:6px 12px;font-size:13px;color:var(--dl-fg-muted);border-left:1px solid var(--dl-line);white-space:nowrap;min-width:0}.dl-addrbar-seg:first-child{border-left:0}.dl-addrbar-seg .dl-icon{width:14px;height:14px;color:var(--dl-fg-faint);flex:0 0 auto}.dl-addrbar-seg .dl-mono{font-size:12.5px}.dl-addrbar-seg.main{cursor:pointer;color:var(--dl-fg)}.dl-addrbar-seg.main:hover{background:var(--dl-soft)}.dl-addrbar-seg.main:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px}.dl-addrbar-seg.main>.dl-icon-wrap:last-child .dl-icon{opacity:.7}.dl-bento{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));grid-template-rows:auto auto;gap:10px;margin:0 0 20px}.dl-person-devices{margin-bottom:16px}.dl-person-head{display:flex;flex-direction:column;margin:0 0 20px}.dl-person-head>.dl-pagehead{margin-bottom:0;align-items:flex-start}.dl-pnote{all:unset;box-sizing:border-box;cursor:pointer;align-self:flex-start;display:inline-flex;align-items:flex-start;gap:6px;margin:10px 0 0 62px;max-width:60ch;padding:6px 12px 6px 10px;border-radius:10px;font-size:13px;line-height:18px;white-space:pre-line;background:var(--dl-soft);color:var(--dl-fg);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-pnote:hover{background:var(--dl-soft-hover)}.dl-pnote .dl-icon{width:14px;height:14px;flex:none;margin-top:2px;color:var(--dl-fg-muted)}.dl-note-input{width:100%;box-sizing:border-box;min-height:80px;resize:vertical}.dl-dcard-trend{display:flex;align-items:flex-end;gap:12px;min-width:0}.dl-dcard-trend>.dl-stack{flex:none}.dl-dcard-trend b{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}.dl-dbars{flex:1;min-width:0;height:32px;display:flex;align-items:flex-end;--dl-gap: 2px}.dl-dbars i{flex:1;min-width:0;border-radius:2px;background:var(--dl-chart-1);opacity:.55}.dl-dbars i.zero{background:var(--dl-track);opacity:1}.dl-dbars i.hi{opacity:1}.dl-dbars>span:hover i{opacity:1;filter:brightness(1.2)}.dl-datechip{position:relative;display:inline-flex}.dl-date-hidden{position:absolute!important;left:0;bottom:0;width:1px!important;min-width:0!important;height:1px!important;opacity:0;pointer-events:none;border:0!important;padding:0!important;margin:0!important}.dl-chipbtn .dl-icon{width:13px;height:13px}.dl-chipbtn:has(.dl-icon){display:inline-flex;align-items:center;gap:5px}.dl-places{display:flex;align-items:center;gap:12px;padding:12px 16px;border:1px solid var(--dl-line);border-radius:var(--dl-radius);background:var(--dl-card);font-size:14px}.dl-places>.dl-icon{width:18px;height:18px;color:var(--dl-fg-muted);flex:none}.dl-person-live{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px}.dl-person-live .dl-bento-head{flex-wrap:nowrap;white-space:nowrap;min-width:0}.dl-person-live .dl-bento-head>*{min-width:0;overflow:hidden;text-overflow:ellipsis}.dl-person-live .dl-bento-head>:first-child{flex:none}.dl-person-live.solo{grid-template-columns:minmax(0,1fr)}.dl-person-live:not(.solo) .dl-bento-tile.month>.dl-bento-head:first-child{flex-wrap:wrap;row-gap:2px}.dl-person-live:not(.solo) .dl-bento-tile.month>.dl-bento-head:first-child>.dl-sub{flex-basis:100%}.dl-person-live>.dl-bento-tile,.dl-person-live>.dl-bento-tile.month{grid-column:auto;grid-row:auto}@media(max-width:760px){.dl-person-live{grid-template-columns:minmax(0,1fr)}}.dl-bento-tile{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);padding:14px 16px;display:flex;flex-direction:column;gap:10px;min-width:0;box-shadow:var(--dl-shadow)}.dl-bento-tile.month{grid-column:1 / -1}.dl-onl-count{font-size:13px;line-height:22px;min-width:22px;padding:0 8px;border-radius:999px;background:var(--dl-soft);text-align:center;font-weight:500;font-variant-numeric:tabular-nums}.dl-onl-count.none{color:var(--dl-fg-faint)}.dl-onl-row{flex:1;display:flex;align-items:center;justify-content:center;gap:12px;min-width:0}.dl-onl-p{display:flex;flex-direction:column;align-items:center;gap:5px;width:104px;min-width:0;padding:6px 2px;border-radius:12px;color:var(--dl-fg)!important;text-decoration:none!important}.dl-onl-p:hover{background:var(--dl-soft)}.dl-onl-av{position:relative;width:42px;height:42px;border-radius:50%;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;font-size:13px;font-weight:500;box-shadow:0 0 0 2px var(--dl-ok)}.dl-onl-p.more .dl-onl-av{box-shadow:0 0 0 1px var(--dl-line);color:var(--dl-fg-muted)}.dl-onl-dev{position:absolute;right:-6.5px;bottom:-6.5px;width:20px;height:20px;border-radius:8.5px;border:1.5px solid transparent;background:var(--dl-card);display:inline-flex;align-items:center;justify-content:center;font-size:10px;color:var(--dl-fg-muted)}.dl-onl-dev .dl-icon-wrap{display:inline-flex}.dl-onl-dev .dl-icon{width:12px;height:12px}.dl-onl-name{font-size:12.5px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-onl-p .dl-sub{font-size:11px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-onl-row.grid{flex-wrap:wrap;align-content:center;gap:10px 8px;max-height:108px;overflow:hidden}.dl-onl-p.sm{width:auto;padding:4px}.dl-onl-p:hover .dl-onl-dev{background:linear-gradient(var(--dl-soft),var(--dl-soft)),var(--dl-card)}.dl-onl-p.sm:hover{background:none}.dl-onl-p.sm:hover .dl-onl-dev{background:var(--dl-card)}.dl-onl-p.sm .dl-onl-av{transition:box-shadow .15s ease}.dl-onl-p.sm:hover .dl-onl-av{box-shadow:0 0 0 2px var(--dl-ok),0 0 0 6px var(--dl-soft)}.dl-onl-p.sm.more:hover .dl-onl-av{box-shadow:0 0 0 1px var(--dl-line),0 0 0 6px var(--dl-soft)}.dl-onl-p.sm .dl-onl-av{width:36px;height:36px;font-size:11.5px}.dl-onl-meta{display:inline-flex;align-items:center;gap:3px;font-size:11px;color:var(--dl-fg-faint);max-width:100%;white-space:nowrap;overflow:hidden}.dl-onl-meta .dl-icon-wrap{display:inline-flex}.dl-onl-meta .dl-icon{width:12px;height:12px}.dl-onl-av.sm{width:34px;height:34px;font-size:11.5px}.dl-tip-float:has(.dl-hc){padding:0;white-space:normal;border-radius:16px}.dl-hc{width:280px;padding:14px;display:flex;flex-direction:column;gap:10px}.dl-hc-head{display:flex;align-items:center;gap:10px}.dl-hc-head .dl-stack{flex:1;min-width:0}.dl-hc-head b{font-size:14px;font-weight:500}.dl-hc-since{font-size:11.5px;color:var(--dl-ok)}.dl-hc-reach{display:inline-flex;gap:4px}.dl-hc-speed{border-radius:12px;background:var(--dl-soft);padding:10px 12px;display:flex;flex-direction:column;gap:6px}.dl-hc-speed-row{display:flex;align-items:baseline;gap:12px;font-size:13px;font-variant-numeric:tabular-nums}.dl-hc-chart{display:block;width:100%;height:30px}.dl-hc-chart .area{fill:color-mix(in srgb,var(--dl-chart-1) 16%,transparent)}.dl-hc-chart .dn{fill:none;stroke:var(--dl-chart-1);stroke-width:1.5;vector-effect:non-scaling-stroke}.dl-hc-chart .up{fill:none;stroke:var(--dl-ok);stroke-width:1.2;vector-effect:non-scaling-stroke}.dl-hc-devs{display:flex;flex-wrap:wrap;gap:6px}.dl-hc-dev{display:inline-flex;align-items:center;gap:5px;height:24px;padding:0 9px;border-radius:999px;background:var(--dl-soft);font-size:11.5px}.dl-hc-dev .dl-icon-wrap{display:inline-flex}.dl-hc-dev .dl-icon{width:12px;height:12px;color:var(--dl-fg-muted)}.dl-hc-foot{display:flex;align-items:center;gap:8px;font-size:11.5px}.dl-disg-id{display:flex;align-items:center;gap:10px}.dl-disg-id b{font-size:16px;font-weight:500}.dl-disg-ic{width:36px;height:36px;border-radius:11px;background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-disg-ic .dl-icon-wrap{display:inline-flex}.dl-disg-ic .dl-icon{width:18px;height:18px}.dl-disg-ic.off{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-disg-meters{display:grid;grid-template-columns:auto 1fr;gap:6px 10px;align-items:center;font-size:12px;color:var(--dl-fg-muted)}.dl-segs{display:inline-flex;gap:3px}.dl-segs i{width:18px;height:5px;border-radius:3px;background:var(--dl-track)}.dl-segs.acc i.on{background:var(--dl-accent)}.dl-segs.ok i.on{background:var(--dl-ok)}.dl-disg-chips{margin-top:auto;display:flex;flex-wrap:wrap;gap:5px}.dl-disg-chips span{font:11px/20px var(--dl-mono);padding:0 8px;border-radius:999px;background:var(--dl-soft);color:var(--dl-fg-muted);white-space:nowrap}.dl-onl-empty{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;font-size:13px;text-align:center}.dl-bento-head{display:flex;align-items:center;justify-content:space-between;gap:10px;min-width:0}.dl-bento-head.start{justify-content:flex-start}.dl-bento-big{font-family:inherit;font-size:28px;line-height:34px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-bento-big small{font-size:13px;font-weight:400;color:var(--dl-fg-faint);letter-spacing:0}.dl-avstack{display:inline-flex}.dl-avstack .dl-avatar{margin-left:-7px;box-shadow:0 0 0 2px var(--dl-card)}.dl-avstack .dl-avatar:first-child{margin-left:0}.dl-avatar.more{background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-bento-list{display:flex;flex-direction:column;gap:2px}.dl-bento-row{display:flex;align-items:center;gap:10px;padding:8px;margin:0 -8px;border-radius:10px;color:var(--dl-fg)!important;text-decoration:none!important;min-width:0;transition:background .12s}.dl-bento-row:hover{background:var(--dl-soft)}.dl-bento-row:hover b{text-decoration:none}.dl-bento-row:focus-visible{outline:2px solid var(--dl-ring);outline-offset:-2px}.dl-bento-row-main{display:flex;flex-direction:column;gap:1px;flex:1;min-width:0}.dl-bento-row-main b{font-weight:500;font-size:13.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-bento-row-main .dl-sub{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-bento-row.off b{color:var(--dl-fg-muted);font-weight:400}.dl-bento-row-val{display:flex;flex-direction:column;align-items:flex-end;font-size:13px;font-variant-numeric:tabular-nums;white-space:nowrap}.dl-bento-row-val small{font-size:11px;color:var(--dl-fg-faint)}.dl-bento-sep{font-size:11px;color:var(--dl-fg-faint);padding:12px 0 4px}.dl-bento-devs{display:inline-flex;gap:3px;color:var(--dl-fg-faint)}.dl-bento-devs .dl-icon{width:13px;height:13px}.dl-bento-devs .on{color:var(--dl-ok)}.dl-bento-foot{display:flex;align-items:center;gap:10px;margin-top:auto;padding-top:10px;border-top:1px solid var(--dl-line);color:var(--dl-fg)!important;text-decoration:none!important}.dl-bento-foot.split,.dl-bento-foot.end{justify-content:space-between}.dl-bento-foot.end>a:only-child{margin-left:auto}.dl-bento-empty{display:flex;align-items:center;gap:10px;padding:14px 0;font-size:13.5px;color:var(--dl-fg-muted)}.dl-bento-empty .dl-icon{width:18px;height:18px}.dl-split{display:flex;height:6px;border-radius:3px;overflow:hidden;background:var(--dl-soft)}.dl-split i{display:block;height:100%}.dl-split i.dn{background:var(--dl-accent)}.dl-split i.up{background:var(--dl-ok)}.dl-dn{color:var(--dl-accent)}.dl-up{color:var(--dl-ok)}.dl-bento-method{display:flex;align-items:center;gap:8px;font-size:18px;font-weight:500}.dl-bento-method .dl-icon{width:20px;height:20px;color:var(--dl-accent)}.dl-meter{display:inline-flex;gap:3px}.dl-meter i{width:16px;height:4px;border-radius:2px;background:var(--dl-line)}.dl-meter i.on{background:var(--dl-accent)}.dl-bento-total{font-size:16px;font-weight:500;margin-left:8px}.dl-bento-bars{display:flex;align-items:flex-end;height:54px;--dl-gap: 3px}.dl-bento-bars i{flex:1;min-width:0;border-radius:3px 3px 0 0;background:var(--dl-soft-hover);transition:background .15s}.dl-bento-bars i.future{height:4px;background:var(--dl-soft)}.dl-bento-bars>span:hover i:not(.hi){background:var(--dl-fg-faint)}.dl-bento-bars i.hi{background:var(--dl-accent)}@media(max-width:700px){.dl-addrbar{flex-wrap:wrap}}@media(max-width:900px){.dl-bento{grid-template-columns:minmax(0,1fr) minmax(0,1fr)}.dl-bento-tile.online{grid-column:span 2}}@media(max-width:560px){.dl-bento{grid-template-columns:minmax(0,1fr)}.dl-bento-tile.online,.dl-bento-tile.month{grid-column:auto}}.dl-srvpagehead{display:flex;flex-direction:column;align-items:flex-start;gap:10px;margin:0 0 20px}.dl-srvpagehead>.dl-title-row{display:flex;align-items:center;gap:10px;width:100%;flex-wrap:wrap}.dl-srvpagehead .dl-actions{margin:0;flex-wrap:wrap}.dl-toolbar-end{display:flex;align-items:center;gap:8px;margin-left:auto;flex-wrap:nowrap;min-width:0}@media(max-width:640px){.dl-toolbar-end{flex-wrap:wrap;width:100%}}.dl-notices{margin:0 0 16px}.dl-notices .dl-need-row .dl-sub{overflow-wrap:anywhere}.dl-notices-more{font-size:13px;color:var(--dl-fg-muted);text-decoration:none}.dl-notices-more:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-speed-cols{display:grid;grid-template-columns:1fr 1fr;gap:12px}.dl-speed-col{display:flex;flex-direction:column;gap:2px;min-width:0}.dl-speed-val{font-size:20px;line-height:26px;font-weight:500;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-speed-today{display:flex;justify-content:space-between;gap:10px;font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;font-variant-numeric:tabular-nums}.dl-speed-today b{font-weight:500;color:var(--dl-fg)}.dl-speed-chart{display:block;width:100%;height:44px}.dl-speed-chart .area{fill:color-mix(in srgb,var(--dl-accent) 16%,transparent)}.dl-speed-chart .line{fill:none;stroke:var(--dl-accent);stroke-width:1.5;vector-effect:non-scaling-stroke}.dl-speed-chart .line.up{stroke:var(--dl-ok);stroke-width:1.2;opacity:.85}.dl-speed-wait{height:44px;display:flex;flex-direction:column;justify-content:flex-end;gap:6px;font-size:11px;color:var(--dl-fg-faint)}.dl-speed-wait i{display:block;height:1px;background:var(--dl-line);order:2}.dl-speed-val.off{color:var(--dl-fg-faint)}.dl-fld{display:flex;flex-direction:column;gap:8px;margin:0 0 16px}.dl-fld-label{font-size:13px;font-weight:500;color:var(--dl-fg)}.dl-fld .cbi-input-text{width:100%;box-sizing:border-box}.dl-kinds{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}.dl-kinds button{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;height:68px;border-radius:10px;border:1px solid var(--dl-line);color:var(--dl-fg-muted);font-size:12px;font-weight:500;text-align:center;min-width:0}.dl-kinds button .dl-icon{width:20px;height:20px}.dl-kinds button:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-kinds button:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-kinds button.on{border-color:var(--dl-accent);color:var(--dl-fg);background:color-mix(in srgb,var(--dl-accent) 10%,transparent);box-shadow:inset 0 0 0 1px var(--dl-accent)}.dl-kinds button.on .dl-icon{color:var(--dl-accent)}.dl-choices{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:8px}.dl-choice{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;gap:4px;padding:12px 14px;border-radius:12px;background:var(--dl-card);box-shadow:inset 0 0 0 1px var(--dl-line);transition:background .15s,box-shadow .15s}.dl-choice:hover{background:var(--dl-soft)}.dl-choice:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-choice.selected{box-shadow:inset 0 0 0 2px var(--dl-accent);background:var(--accent-a10, color-mix(in srgb, var(--dl-accent) 8%, transparent))}.dl-choice-title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--dl-fg)}.dl-choice-text{font-size:12px;line-height:16px;color:var(--dl-fg-muted)}.dl-attn-item>.cbi-button{margin-left:auto;flex:none;align-self:center}";var ra='.dl-steps{display:flex;align-items:center;gap:8px;margin:0 0 16px;flex-wrap:wrap}.dl-step{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--dl-fg-faint)}.dl-step b{display:inline-flex;width:24px;height:24px;align-items:center;justify-content:center;border-radius:50%;background:var(--dl-soft);font-size:12px;font-weight:600}.dl-step.current{color:var(--dl-fg)}.dl-step.current b{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-step.done{color:var(--dl-fg-muted)}.dl-step.done b{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-step+.dl-step:before{content:"";width:24px;height:1px;background:var(--dl-line)}.dl-wizard .dl-panel>div{display:flex;flex-direction:column;gap:16px}.dl-wizard .dl-panel>div>p{margin:0!important;color:var(--dl-fg-muted)}.dl-wizard .dl-panel>div>.cbi-value{margin:0}.dl-wizard h4{font-size:14px;font-weight:500;margin:8px 0 -6px!important}.dl-wizard h4:first-child{margin-top:0!important}.dl-modal .cbi-tabmenu{margin-bottom:16px}.dl-modal .cbi-value.dl-live>.cbi-value-title{display:flex;flex-direction:column;gap:2px;text-align:left}.dl-modal .cbi-value.dl-live>.cbi-value-title>.dl-sub{white-space:normal}.dl-checklist{display:flex;flex-direction:column;gap:6px;margin:4px 0 8px}.dl-checklist label{display:flex;align-items:center;gap:8px;font-size:14px;cursor:pointer}.dl-checklist input{margin:0}.dl-invite{display:grid;grid-template-columns:250px minmax(0,1fr);gap:22px;align-items:start}.dl-invite img{display:block;width:100%;border-radius:18px;box-shadow:0 0 0 1px var(--dl-line)}.dl-invite-side{display:flex;flex-direction:column;gap:14px;min-width:0}.dl-invite-side>p{margin:0!important}.dl-invite-link{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;min-width:0;padding:11px 14px;border-radius:12px;background:var(--dl-soft);font:13px/18px var(--dl-mono);color:var(--dl-fg)}.dl-invite-link>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-invite-link>.dl-icon-wrap{flex:none;display:inline-flex}.dl-invite-link .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted);flex:none}.dl-invite-link:hover{background:var(--dl-soft-hover)}.dl-invite-link.alt{padding:8px 14px;font-size:12px;color:var(--dl-fg-muted)}.dl-invite-link>.dl-pill{flex:none}.dl-invite-steps{margin:0;padding-left:20px;list-style:decimal!important;font-size:13px;line-height:24px;color:var(--dl-fg-muted)}.dl-invite-steps b{color:var(--dl-fg);font-weight:500}.dl-invite-steps li{display:list-item!important;list-style:inherit!important;padding-left:4px}.dl-invite-actions{display:flex;gap:8px;flex-wrap:wrap}.modal:has(.dl-modal.wide){max-width:min(760px,94vw)!important;width:100%!important}@media(max-width:640px){.dl-invite{grid-template-columns:minmax(0,1fr)}.dl-invite img{max-width:260px;margin:0 auto}}.dl-toasts{position:fixed;left:50%;bottom:max(24px,env(safe-area-inset-bottom));transform:translate(-50%);z-index:100000;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none}.dl-toast{pointer-events:auto;display:inline-flex;align-items:center;gap:8px;max-width:min(520px,92vw);padding:10px 16px;border-radius:999px;background:var(--dl-fg);color:var(--dl-card);font-size:13px;line-height:18px;box-shadow:0 10px 30px #0000004d;opacity:0;transform:translateY(12px);transition:opacity .18s,transform .18s}.dl-toast.show{opacity:1;transform:none}.dl-toast .dl-icon-wrap{display:inline-flex}.dl-toast .dl-icon{width:15px;height:15px}.dl-toast.success .dl-icon{color:var(--dl-ok)}.dl-toast.error{background:var(--dl-bad);color:#fff}.dl-toast.error .dl-icon{color:#fff}.dl-toast.warning{background:var(--dl-warn);color:#111}.dl-toast.warning .dl-icon{color:#111}.dl-toast button{all:unset;cursor:pointer;display:inline-flex;margin-left:4px;opacity:.8}.dl-toast button:hover{opacity:1}';var ia=".dl-setblock{display:flex;flex-direction:column;gap:8px;margin:0}.dl-addr-opts{display:flex;flex-direction:column;gap:6px}.dl-addr-opt{all:unset;box-sizing:border-box;cursor:pointer;display:grid;grid-template-columns:16px minmax(0,1fr) auto;gap:12px;align-items:center;padding:10px 14px;border-radius:12px;box-shadow:inset 0 0 0 1px var(--dl-line);min-width:0}.dl-addr-opt:hover{background:var(--dl-soft)}.dl-addr-opt.on{box-shadow:inset 0 0 0 1.5px var(--dl-accent);background:color-mix(in srgb,var(--dl-accent) 7%,transparent)}.dl-addr-opt .dl-mono{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-addr-opt .dl-stack{min-width:0}.dl-addr-opt input{width:100%}.dl-addr-opt.other{cursor:default}.dl-addr-opt.other:hover{background:none}.dl-addr-opt.other input{width:100%}.dl-addr-check{width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1.5px var(--dl-fg-faint);display:inline-flex;align-items:center;justify-content:center}.dl-addr-check .dl-icon-wrap{display:inline-flex}.dl-addr-check .dl-icon{width:12px;height:12px}.dl-addr-opt.on .dl-addr-check{background:var(--dl-accent);box-shadow:none;color:#fff}.dl-addr-opt.other .dl-addr-check{box-shadow:none;color:var(--dl-fg-muted)}.dl-addr-warn{display:inline-flex;align-items:center;gap:5px;font-size:12px;line-height:17px;color:var(--dl-warn)}.dl-addr-warn .dl-icon-wrap{display:inline-flex}.dl-addr-warn .dl-icon{width:13px;height:13px}.dl-pill.info{background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent)}.dl-links{border-radius:12px;background:var(--dl-soft);overflow:hidden}.dl-link-row{display:grid;grid-template-columns:18px minmax(0,1fr) auto;gap:10px;align-items:center;padding:11px 14px}.dl-link-row+.dl-link-row{border-top:1px solid var(--dl-line)}.dl-link-ic{display:inline-flex}.dl-link-ic .dl-icon{width:15px;height:15px}.dl-link-ic.ok .dl-icon{color:var(--dl-ok)}.dl-link-ic.warn .dl-icon{color:var(--dl-warn)}.dl-link-url{font-size:13px;color:var(--dl-fg-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-link-url b{font-weight:500;color:var(--dl-accent)}@media(max-width:640px){.dl-link-url,.dl-addr-opt .dl-mono,.dl-filecard .dl-ellipsis,.dl-invite-link>span:first-child{white-space:normal;overflow-wrap:anywhere}}.dl-ready-sum{display:flex;align-items:center;gap:12px;padding:12px 14px;border-radius:12px}.dl-ready-sum>.dl-icon-wrap{display:inline-flex}.dl-ready-sum>.dl-icon-wrap .dl-icon{width:18px;height:18px}.dl-ready-sum .dl-stack{flex:1;min-width:0}.dl-ready-sum b{font-weight:500;font-size:13px}.dl-ready-sum.ok{background:var(--dl-ok-wash)}.dl-ready-sum.ok b,.dl-ready-sum.ok .dl-icon{color:var(--dl-ok)}.dl-ready-sum.warn{background:var(--dl-warn-wash)}.dl-ready-sum.warn b,.dl-ready-sum.warn .dl-icon{color:var(--dl-warn)}.dl-ready-sum.error{background:var(--dl-bad-wash)}.dl-ready-sum.error b,.dl-ready-sum.error .dl-icon{color:var(--dl-bad)}.dl-check-chip{display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-soft);font-size:12px;color:var(--dl-fg-muted)}.dl-check-chip .dl-icon-wrap{display:inline-flex}.dl-check-chip .dl-icon{width:13px;height:13px;color:var(--dl-ok)}.dl-check-chip.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-check-chip.warn .dl-icon{color:var(--dl-warn)}.dl-check-chip.error{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-check-chip.error .dl-icon{color:var(--dl-bad)}.dl-ready-details{display:flex;flex-direction:column;gap:8px;padding:4px 2px}.dl-ready-details[hidden]{display:none}.dl-ready-item{display:flex;align-items:flex-start;gap:8px;font-size:13px;line-height:18px;min-width:0}.dl-ready-item .dl-icon-wrap{display:inline-flex;margin-top:1px}.dl-ready-item .dl-icon{width:15px;height:15px}.dl-ready-item.ok .dl-icon{color:var(--dl-ok)}.dl-ready-item.warn .dl-icon{color:var(--dl-warn)}.dl-ready-item.error .dl-icon{color:var(--dl-bad)}.dl-params-body{display:flex;flex-direction:column;gap:14px;padding:6px 14px 14px}.dl-params-body>.dl-setrow{margin:0;padding:0}.dl-pgrid.flush{padding:0;grid-template-columns:repeat(2,minmax(0,1fr))}@media(max-width:640px){.dl-pgrid.flush{grid-template-columns:minmax(0,1fr)}}.dl-qr-pane{display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center}.dl-qr{width:min(280px,72vw);aspect-ratio:1;background:#0a0a0a;border-radius:18px;overflow:hidden}.dl-qr.light{background:#fff;box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-qr svg{display:block;width:100%;height:100%}.dl-filecard{display:flex;align-items:center;gap:12px;padding:12px;border-radius:14px;background:var(--dl-soft);min-width:0}.dl-filecard>.dl-stack{flex:1;min-width:0}.dl-filecard-ic{width:40px;height:46px;border-radius:8px;flex:none;display:inline-flex;align-items:center;justify-content:center;font:10px var(--dl-mono);color:var(--dl-fg-muted);background:var(--dl-card);box-shadow:inset 0 0 0 1px var(--dl-line)}.dl-params>.dl-conf{margin:0;border-top:1px solid var(--dl-line);border-radius:0 0 12px 12px;background:none}.dl-conf-sec{color:var(--dl-accent)}.dl-conf-k{color:var(--dl-fg-faint)}.dl-conf-mask{padding:0 6px;border-radius:4px;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-params>summary .dl-chipbtn{height:26px;font-size:12px}.dl-conf{white-space:pre-wrap;word-break:break-all;max-height:22em;overflow:auto;font-family:var(--dl-mono);font-size:12px;line-height:18px;margin:0;padding:12px;border-radius:12px;background:var(--dl-soft)}.dl-key{width:100%;box-sizing:border-box;font-family:var(--dl-mono);font-size:12px;word-break:break-all;min-height:7em}.dl-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin:12px 0 0}.dl-link-box{display:flex;gap:6px;align-items:center;flex-wrap:wrap}.dl-link-box input{flex:1 1 18em;min-width:0;font-family:var(--dl-mono);font-size:12px}.dl-hint{font-size:12px;line-height:16px;color:var(--dl-fg-muted);margin:8px 0}.dl-divider{border:0;border-top:1px solid var(--dl-line);margin:16px 0}";var aa=".dl-checks{list-style:none;margin:0;padding:0}.dl-checks li{display:flex;align-items:center;gap:12px;padding:12px 0;border-top:1px solid var(--dl-line)}.dl-checks li:first-child{border-top:0;padding-top:0}.dl-checks li:last-child{padding-bottom:0}.dl-check-icon{flex:0 0 auto;width:28px;height:28px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center}.dl-check-icon .dl-icon{width:14px;height:14px}.dl-check-icon.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-check-icon.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-check-icon.error{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-check-icon.skip{background:var(--dl-soft);color:var(--dl-fg-faint)}.dl-check-body{flex:1;min-width:0}.dl-check-title{font-size:14px;line-height:20px;font-weight:500}.dl-check-detail{font-size:12px;line-height:16px;color:var(--dl-fg-muted);overflow-wrap:anywhere}.dl-check-repaired{margin-top:2px;font-size:12px;line-height:16px;color:var(--dl-warn)}.dl-wd{margin:0 0 16px;display:flex;flex-direction:column;gap:14px}.dl-wd-head{display:flex;align-items:center;gap:12px;min-width:0}.dl-wd-head>.dl-stack{min-width:0}.dl-wd-title{font-size:16px;line-height:24px;font-weight:500}.dl-wd-tile{flex:none;width:36px;height:36px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-wd-tile.off{background:var(--dl-soft);color:var(--dl-fg-faint)}.dl-wd-tile .dl-icon{width:18px;height:18px}.dl-wd-foot{display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px;padding-top:14px;border-top:1px solid var(--dl-line)}.dl-wd-chips{display:flex;flex-wrap:wrap;gap:6px;flex:1 1 auto;min-width:0}.dl-wd-chips .dl-check-chip.error .dl-icon{color:var(--dl-bad)}.dl-warn-text{color:var(--dl-warn)!important}.dl-health-cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(440px,100%),1fr));gap:16px;align-items:start}.dl-health-cols>.dl-panel{margin:0;min-width:0}.dl-recent{display:flex;flex-direction:column}.dl-recent .dl-panel-head a{font-size:13px}.dl-recent-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:32px 16px;color:var(--dl-fg-muted);font-size:13px;border-top:1px solid var(--dl-line)}.dl-loading{margin:0;font-size:13px}.dl-diag-tabs{margin:0 0 16px}.dl-row.dl-slog-row{align-items:baseline}.dl-slog-row .dl-ev-tile{align-self:flex-start;margin-top:-1px}.dl-slog-row.has-detail{cursor:pointer}.dl-row.dl-slog-row.has-detail:hover{background:color-mix(in srgb,var(--sys) 11%,transparent)}.dl-slog-more{display:inline-flex;vertical-align:-2px;margin-left:6px;color:var(--dl-fg-faint);transform:rotate(90deg);transition:transform .15s}.dl-slog-more .dl-icon{width:14px;height:14px}.dl-slog-more.open{transform:rotate(-90deg)}.dl-slog-detail{margin:8px 0 2px;padding:8px 10px;border-radius:8px;background:var(--dl-soft);font-family:var(--dl-mono);font-size:12px;line-height:17px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--dl-fg-muted);cursor:text}.dl-table{width:100%;border-collapse:collapse;font-size:14px;line-height:20px}.dl-table th{text-align:left;font-weight:500;color:var(--dl-fg-faint);padding:0 8px 8px;border-bottom:1px solid var(--dl-line)}.dl-table td{padding:10px 8px;border-bottom:1px solid var(--dl-line);vertical-align:middle}.dl-table th:first-child,.dl-table td:first-child{padding-left:0}.dl-table th:last-child,.dl-table td:last-child{padding-right:0}.dl-table tr:last-child td{border-bottom:0}.dl-table .dl-right{text-align:right;white-space:nowrap}.dl-log{max-height:18em;overflow:auto;font-family:var(--dl-mono);font-size:12px;line-height:18px;margin:8px 0 0;padding:12px;white-space:pre-wrap;border-radius:12px;background:var(--dl-soft)}";var la=".dl-pagehead{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin:0 0 20px}.dl-h1{margin:0!important;padding:0!important;font-size:24px!important;line-height:32px!important;font-weight:500!important;border:0!important}.dl-title-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.dl-stack{display:flex;flex-direction:column;gap:2px;min-width:0}.dl-stack.gap4{gap:4px}.dl-stack.gap8{gap:8px}.dl-sub{font-size:12px;line-height:16px;color:var(--dl-fg-muted)}.dl-ok{color:var(--dl-ok)}.dl-warn{color:var(--dl-warn)}.dl-bad{color:var(--dl-bad)}.dl-icon-only{width:auto!important;min-width:0!important;aspect-ratio:1 / 1;padding:0!important;justify-content:center;display:inline-flex!important;align-items:center;border-radius:999px!important}.dl-panel.flush{padding:0;overflow:hidden}.dl-panel-head.pad{padding:16px 16px 12px;margin:0}.dl-col{display:flex;flex-direction:column;gap:16px;min-width:0}.dl-col>.dl-panel,.dl-col>section.dl-panel{margin:0}.dl-crumbs{display:flex;gap:8px;align-items:center;font-size:14px;margin:0 0 16px;color:var(--dl-fg-faint)}.dl-crumbs a{color:var(--dl-fg-faint)}.dl-crumbs a:hover{color:var(--dl-fg)}.dl-crumbs span:last-child{color:var(--dl-fg)}.dl-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);margin:0 0 16px;box-shadow:var(--dl-shadow)}.dl-metric{display:flex;flex-direction:column;gap:4px;padding:16px 20px;min-width:0}.dl-metric+.dl-metric{border-left:1px solid var(--dl-line)}.dl-metric-label{font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-metric-value{font-size:28px;line-height:36px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums;white-space:nowrap}.dl-metric-value .dl-faint{font-size:16px}.dl-metric-sub{font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@media(max-width:900px){.dl-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.dl-metric:nth-child(3){border-left:0}.dl-metric:nth-child(n+3){border-top:1px solid var(--dl-line)}}.dl-seg{display:inline-flex;gap:2px;padding:3px;border-radius:999px;background:var(--dl-soft);flex-wrap:wrap}.dl-seg button{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:6px;padding:4px 12px;border-radius:999px;font-size:13px;font-weight:500;color:var(--dl-fg-muted);white-space:nowrap}.dl-seg button:hover{color:var(--dl-fg)}.dl-seg button.on{background:var(--dl-soft-hover);color:var(--dl-fg)}.dl-seg.dl-srvsections{flex-wrap:nowrap;max-width:100%;overflow-x:auto;scrollbar-width:none}.dl-seg.dl-srvsections::-webkit-scrollbar{display:none}.dl-seg.dl-srvsections button{flex:none;white-space:nowrap}.dl-seg button:focus-visible{outline:2px solid var(--dl-ring)}.dl-seg button b{font-weight:500;font-size:11px;padding:0 6px;border-radius:999px;background:var(--dl-soft)}.dl-seg button b.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-seg.sm button{padding:2px 9px;font-size:11px}.dl-seg.wide{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));border-radius:12px;padding:4px}.dl-seg.wide button{flex-direction:column;justify-content:center;padding:8px 6px;border-radius:9px;gap:3px;white-space:normal;text-align:center;line-height:16px}.dl-seg.wide button.on{background:var(--dl-primary);color:var(--dl-primary-fg)}";var da=`.dl-geomap{position:relative;border-top:1px solid var(--dl-line);background:transparent}.dl-map-status{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:var(--dl-fg-muted);font-size:13px;z-index:1;pointer-events:none}.dl-map-wrap{position:relative}.dl-map-legend{position:absolute;left:12px;bottom:12px;display:flex;gap:12px;align-items:center;padding:6px 12px;border-radius:999px;font-size:12px;background:color-mix(in srgb,var(--dl-card) 88%,transparent);border:1px solid var(--dl-line);backdrop-filter:blur(6px);z-index:2}.dl-map-legend span{display:inline-flex;align-items:center;gap:6px;color:var(--dl-fg-muted)}.dl-map-legend i.line{width:14px;height:0;border-top:2px dashed #8a8a8a}.dl-map-legend i.line.live{border-top-color:#3b82f6}.dl-map-off{padding:32px 16px;text-align:center;color:var(--dl-fg-muted);border-top:1px solid var(--dl-line)}.dl-mk{all:unset;cursor:pointer;position:relative;display:flex;align-items:center;justify-content:center;transition:opacity .2s}.dl-mk-hub{position:relative;display:flex;align-items:center;justify-content:center}.dl-mk-host{box-sizing:border-box;width:40px;height:40px;border-radius:11px;display:flex;align-items:center;justify-content:center;background:color-mix(in srgb,var(--dl-elevated) 60%,transparent);border:1px solid var(--dl-line);backdrop-filter:blur(6px);box-shadow:0 6px 16px #00000059}.dl-mk-host-tile{width:26px;height:26px;border-radius:7px;display:flex;align-items:center;justify-content:center;background:var(--dl-fg);color:var(--background, var(--dl-elevated))}.dl-mk-host-ic{width:14px;height:14px}.dl-mk-av{position:relative;box-sizing:border-box;width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:500;line-height:1;border:2px solid #8a8a8a;background:var(--dl-elevated);color:var(--dl-fg-muted);transition:box-shadow .2s}.dl-mk.online .dl-mk-av{border-color:#3b82f6;background:color-mix(in srgb,#3b82f6 22%,var(--dl-elevated));color:var(--dl-fg)}.dl-mk-badge{position:absolute;left:16px;bottom:-6px;height:16px;min-width:16px;padding:0 3px;border-radius:8px;border:2px solid var(--dl-elevated);background:#6b6b6b;color:#fff;display:flex;align-items:center;justify-content:center;gap:1px;font-size:9px;font-weight:600;white-space:nowrap;box-sizing:content-box}.dl-mk.online .dl-mk-badge{background:#3b82f6}.dl-mk-badge-ic{width:10px;height:10px;stroke-width:2.2}.dl-mk-badge:has(>svg:only-child){width:16px;min-width:0;padding:0}.dl-mk-tile{position:relative;width:26px;height:26px;border-radius:7px;display:flex;align-items:center;justify-content:center;background:color-mix(in srgb,var(--dl-fg) 18%,var(--dl-elevated));color:var(--dl-fg)}.dl-mk.place.online .dl-mk-tile{background:#3b82f6;color:#fff;box-shadow:0 2px 8px #3b82f659}.dl-mk-tile-ic{width:14px;height:14px}.dl-mk-tile-n{position:absolute;right:-5px;top:-5px;min-width:14px;height:14px;padding:0 3px;box-sizing:border-box;border-radius:7px;background:var(--dl-fg);color:var(--dl-elevated);font-size:9px;font-weight:600;line-height:14px;text-align:center}.dl-mk-when{display:block;text-align:center;color:var(--dl-fg-faint);font-weight:400}.dl-mk.place.online .dl-mk-when{color:#3b82f6}.dl-mk-tile.sm{width:18px;height:18px;border-radius:5px;font-size:9px;font-weight:600}.dl-dmap{border:1px solid var(--dl-line);border-radius:12px;overflow:hidden}.dl-dmap .dl-geomap{border-top:0}.dl-dplaces{display:flex;flex-direction:column;margin-top:4px}.dl-dplace-row{display:flex;align-items:center;gap:10px;padding:9px 2px;border-top:1px solid var(--dl-line);font-size:13px}.dl-dplace-row:first-child{border-top:0}.dl-dplace-n{flex:0 0 auto;width:20px;height:20px;border-radius:5px;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:600;background:color-mix(in srgb,var(--dl-fg) 18%,var(--dl-elevated));color:var(--dl-fg)}.dl-dplace-n.live{background:#3b82f6;color:#fff}.dl-dplace-n .dl-icon{width:12px;height:12px}.dl-dplace-now{color:#3b82f6}.dl-dplaces.strips .dl-dplace-row{position:relative;display:grid;grid-template-columns:20px minmax(0,1fr) auto;column-gap:10px;row-gap:9px;margin:0 -10px;padding:11px 10px;border-top:0;border-radius:10px;transition:background .15s}.dl-dplaces.strips .dl-dplace-row+.dl-dplace-row:before{content:"";position:absolute;left:10px;right:10px;top:0;height:1px;background:var(--dl-line)}.dl-dplaces.strips .dl-dplace-row:is(:hover,.cur){background:var(--dl-soft)}.dl-dplaces.strips .dl-dplace-row:is(:hover,.cur):before,.dl-dplaces.strips .dl-dplace-row:is(:hover,.cur)+.dl-dplace-row:before{opacity:0}.dl-dplace-strip{grid-column:2 / 4;position:relative;height:6px;border-radius:3px;background:var(--dl-track)}.dl-dplaces.can-replay .dl-dplace-strip{cursor:ew-resize;touch-action:none}.dl-dplace-strip i{position:absolute;top:0;bottom:0;min-width:2px;border-radius:2px;background:#8a8a8a}.dl-dplace-strip.live i{background:#3b82f6}.dl-dplaces.replay .dl-dplace-strip:after{content:"";position:absolute;left:var(--at);top:-4px;bottom:-4px;width:2px;margin-left:-1px;border-radius:1px;background:var(--dl-fg);box-shadow:0 0 0 2px var(--dialog-bg, var(--dl-elevated));pointer-events:none}.dl-dplace-axis{position:relative;height:16px;margin:4px 0 0 30px;font-size:11px;line-height:16px;color:var(--dl-fg-faint)}.dl-dplace-axis span{position:absolute;top:0;transform:translate(-50%);white-space:nowrap}.dl-dmap{position:relative}.dl-map-replay{position:absolute;left:10px;top:10px;z-index:3;display:flex;align-items:center;gap:6px}.dl-map-btn{all:unset;box-sizing:border-box;cursor:pointer;width:28px;height:28px;border-radius:8px;display:inline-flex;align-items:center;justify-content:center;background:var(--dl-elevated);border:1px solid var(--dl-line);color:var(--dl-fg)}.dl-map-btn:hover{background:color-mix(in srgb,var(--dl-fg) 8%,var(--dl-elevated))}.dl-map-btn:focus-visible{outline:2px solid var(--dl-ring)}.dl-map-btn .dl-icon{width:13px;height:13px}.dl-map-chip{display:inline-flex;align-items:center;height:28px;box-sizing:border-box;padding:0 10px;border-radius:8px;font-size:11.5px;white-space:nowrap;background:var(--dl-elevated);border:1px solid var(--dl-line);color:var(--dl-fg);font-variant-numeric:tabular-nums}.dl-mk.step .dl-mk-tile{transition:width .3s cubic-bezier(.2,.8,.2,1),height .3s cubic-bezier(.2,.8,.2,1),border-radius .3s,background-color .3s,color .3s,box-shadow .3s,transform .24s}.dl-mk.step .dl-mk-tile.sm .dl-mk-tile-ic{width:11px;height:11px}.dl-mk.step.faded>*{opacity:.5}.dl-mk.step:is(.online,.hl){z-index:2}.dl-mk.step.hl .dl-mk-tile{box-shadow:0 0 0 3px color-mix(in srgb,#3b82f6 55%,transparent)}.dl-mk.step.arrive .dl-mk-tile{animation:dl-mk-arrive .45s cubic-bezier(.2,.8,.2,1)}@keyframes dl-mk-arrive{0%{transform:scale(.8)}55%{transform:scale(1.12)}to{transform:scale(1)}}.dl-mk-when.inline{display:inline}.dl-mk>*{transition:opacity .15s;opacity:var(--dl-mk-fade, 1)}.dl-mk.merged,.dl-mk.piled{pointer-events:none}.dl-mk.dl-mk-new>*{transition:none}.dl-mk.merged>*,.dl-mk.piled>*{opacity:0}.dl-mk-hub{cursor:default}.dl-mk-host{position:relative}.dl-mk-host{transition:border-radius .22s ease,border-right-color .22s ease}.dl-mk-host.docked{border-top-right-radius:0;border-bottom-right-radius:0;border-right-color:transparent}.dl-mk-dock{position:absolute;left:100%;top:-1px;height:40px;box-sizing:border-box;display:flex;align-items:center;gap:6px;padding:0 10px 0 2px;border:1px solid var(--dl-line);border-left:0;border-radius:0 11px 11px 0;background:color-mix(in srgb,var(--dl-elevated) 60%,transparent);backdrop-filter:blur(6px);box-shadow:0 6px 16px #00000059;pointer-events:none;opacity:0;clip-path:inset(-24px 100% -24px 0);transition:clip-path .28s cubic-bezier(.2,.8,.2,1),opacity .2s ease}.dl-mk-host.docked .dl-mk-dock{pointer-events:auto;opacity:1;clip-path:inset(-24px -24px -24px 0)}.dl-mk-new .dl-mk-host,.dl-mk-new .dl-mk-dock{transition:none}.dl-mk-pile{position:relative;display:flex;justify-content:center}.dl-mk-pile-box{box-sizing:border-box;height:40px;display:flex;align-items:center;gap:6px;padding:0 10px 0 6px;border-radius:20px;cursor:zoom-in;background:color-mix(in srgb,var(--dl-elevated) 60%,transparent);border:1px solid var(--dl-line);backdrop-filter:blur(6px);box-shadow:0 6px 16px #00000059;animation:dl-plate-in .26s cubic-bezier(.2,.8,.2,1) both;transition:opacity .18s ease,transform .18s ease}.dl-mk-pile.out{pointer-events:none}.dl-mk-pile.out>*{opacity:0;transform:scale(.85);transition:opacity .18s ease,transform .18s ease}@keyframes dl-plate-in{0%{opacity:0;transform:scale(.85)}}.dl-mk-face{all:unset;position:relative;display:flex;cursor:pointer;transition:transform .18s ease,opacity .18s ease}.dl-mk-face>.dl-mk-badge{position:relative;left:auto;bottom:-8px;margin-left:-12px;align-self:center}.dl-mk-face.on .dl-mk-av{border-color:#3b82f6;background:color-mix(in srgb,#3b82f6 22%,var(--dl-elevated));color:var(--dl-fg)}.dl-mk-face.on .dl-mk-badge{background:#3b82f6}.dl-mk-face:hover .dl-mk-av{box-shadow:0 0 0 4px #3b82f640}.dl-mk-face.in{animation:dl-dock-in .24s cubic-bezier(.2,.8,.2,1) both}.dl-mk-face.out{transform:scale(.4);opacity:0;pointer-events:none}@keyframes dl-dock-in{0%{transform:scale(.4);opacity:0}}.dl-mk-more{font-size:11px;font-weight:600;color:var(--dl-fg-muted)}.dl-mk-av,.dl-mk-tile{transition:box-shadow .2s,transform .24s cubic-bezier(.2,.8,.2,1)}.dl-mk.merged .dl-mk-av,.dl-mk.merged .dl-mk-tile,.dl-mk.piled .dl-mk-av{transform:scale(.5)}.dl-mk-host,.dl-mk-dock,.dl-mk-pile-box{transition-property:border-radius,border-right-color,clip-path,opacity,height,width,padding,gap}.dl-mk-dock,.dl-mk-pile-box{transition-duration:.22s;transition-timing-function:cubic-bezier(.2,.8,.2,1)}.dl-mk-pile-box{position:relative}.dl-mk-more{transition:transform .22s cubic-bezier(.2,.8,.2,1),opacity .18s ease}.dl-mk-more.in{animation:dl-dock-in .24s ease both}.dl-mk-more.out{transform:scale(.4);opacity:0}.dl-mk-face .dl-mk-av{transition:box-shadow .2s,transform .24s cubic-bezier(.2,.8,.2,1),width .2s ease,height .2s ease,font-size .2s ease}.dl-mk-face{transition:transform .22s cubic-bezier(.2,.8,.2,1),opacity .18s ease,margin .2s ease}.dl-mk-face>.dl-mk-badge{max-width:48px;overflow:hidden;transition:opacity .2s ease,transform .2s ease,max-width .22s ease,margin .22s ease,padding .22s ease,border-width .22s ease,height .22s ease,min-width .22s ease,width .22s ease,bottom .22s ease}.dl-lod-far .dl-mk-host{width:32px;height:32px;border-radius:9px}.dl-lod-far .dl-mk-host.docked{border-radius:9px 0 0 9px}.dl-lod-far .dl-mk-host-tile{width:20px;height:20px;border-radius:6px}.dl-lod-far .dl-mk-host-ic{width:11px;height:11px}.dl-lod-far .dl-mk-dock{height:32px;gap:0;padding:0 4px 0 0;border-radius:0 9px 9px 0}.dl-lod-far .dl-mk-pile-box{height:32px;gap:0;padding:0 4px;border-radius:16px}.dl-lod-far .dl-mk-face+.dl-mk-face{margin-left:-6px}.dl-lod-far .dl-mk-face .dl-mk-av{width:22px;height:22px;font-size:8px;box-shadow:0 0 0 2px var(--dl-elevated)}.dl-lod-far .dl-mk-face>.dl-mk-badge{max-width:0;min-width:0;padding:0;margin-left:0;border-width:0;opacity:0;transform:scale(.5);pointer-events:none}.dl-lod-far .dl-mk-more{margin-left:4px;font-size:10px}.dl-mk-label{transition:opacity .2s ease}.dl-lod-far .dl-mk:not(.step) .dl-mk-label{opacity:0}.dl-lod-mid .dl-mk-host{width:36px;height:36px}.dl-lod-mid .dl-mk-dock,.dl-lod-mid .dl-mk-pile-box{height:36px}.dl-lod-mid .dl-mk-face .dl-mk-av{width:24px;height:24px;font-size:9px}.dl-lod-mid .dl-mk-face>.dl-mk-badge{height:12px;min-width:12px;margin-left:-10px;bottom:-7px}.dl-lod-mid .dl-mk-face>.dl-mk-badge:has(>svg:only-child){width:12px}.dl-lod-mid .dl-mk-face>.dl-mk-badge .dl-mk-badge-ic{width:8px;height:8px}@media(prefers-reduced-motion:reduce){.dl-mk-dock,.dl-mk-pile-box,.dl-mk-face,.dl-mk-av,.dl-mk-tile,.dl-mk.step .dl-mk-tile,.dl-mk-host,.dl-mk-face>.dl-mk-badge{transition:none;animation:none}}.dl-mk-hub:has(.dl-mk-host.docked) .dl-mk-host{cursor:zoom-in}.dl-mk-ptr{position:absolute;left:50%;top:50%;width:0;height:0;z-index:-1;pointer-events:none}.dl-mk-ptr .line{position:absolute;left:0;top:-.5px;height:1px;background:var(--dl-fg-faint);transform-origin:0 50%}.dl-mk-ptr .spot{position:absolute;left:-3.5px;top:-3.5px;width:7px;height:7px;border-radius:50%;box-sizing:border-box;border:1.5px solid #fff;background:#8a8a8a}.dl-mk.online .dl-mk-ptr .spot,.dl-mk.place.online .dl-mk-ptr .spot{background:#3b82f6}.dl-mk.dim>*{opacity:.18}.dl-mk.hl .dl-mk-av{box-shadow:0 0 0 4px #3b82f640}.dl-mk-label{position:absolute;left:50%;bottom:100%;margin-bottom:4px;transform:translate(-50%);white-space:nowrap;pointer-events:none;font-size:10px;line-height:14px;font-weight:500;color:var(--dl-fg)}.dl-mk-label.below{bottom:auto;top:100%;margin:4px 0 0}.dl-mk-label.chip{padding:2px 6px;border-radius:4px;font-size:11px;line-height:16px;font-weight:600;background:color-mix(in srgb,var(--background, var(--dl-card)) 80%,transparent);backdrop-filter:blur(8px)}.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact{margin:0 10px 10px 0;min-height:28px;padding:0;border-radius:8px;background:var(--dl-elevated);border:1px solid var(--dl-line);color:var(--dl-fg-muted);box-shadow:none;font-size:11px;line-height:26px}.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact:not(.maplibregl-compact-show){width:28px;height:28px;box-sizing:border-box}.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact.maplibregl-compact-show{padding:0 32px 0 10px}.dl-geomap .maplibregl-ctrl-attrib a{color:var(--dl-fg-muted)}.dl-geomap .maplibregl-ctrl-attrib-button{top:0;right:0;width:26px;height:26px;margin:0;border-radius:8px;background:none}.dl-geomap .maplibregl-ctrl-attrib-button:after{content:"";position:absolute;inset:5px;background:var(--dl-fg);-webkit-mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20Zm-1.2 8.2h2.4V17h-2.4v-6.8ZM12 6a1.4 1.4 0 1 0 0 2.8A1.4 1.4 0 0 0 12 6Z'/%3E%3C/svg%3E") center / contain no-repeat;mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20Zm-1.2 8.2h2.4V17h-2.4v-6.8ZM12 6a1.4 1.4 0 1 0 0 2.8A1.4 1.4 0 0 0 12 6Z'/%3E%3C/svg%3E") center / contain no-repeat}.dl-geomap .maplibregl-ctrl-attrib-button:focus{outline:none;box-shadow:none}.dl-geomap .maplibregl-ctrl-attrib-button:focus-visible{outline:2px solid var(--dl-ring)}.dl-map-card{position:absolute;right:12px;top:12px;z-index:3;min-width:200px;max-width:260px;padding:10px 12px;border-radius:10px;font-size:12px;line-height:20px;background:var(--dl-elevated);color:var(--dl-fg);border:1px solid var(--dl-line);box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));opacity:0;transition:opacity .2s;pointer-events:none}.dl-map-card.on{opacity:1}.dl-map-card-head b{font-weight:500}.dl-map-card-row{display:flex;justify-content:space-between;gap:12px;white-space:nowrap}.dl-popcard{position:fixed;z-index:2100;width:max-content;max-width:300px;padding:12px;border-radius:12px;box-sizing:border-box;background:var(--dl-elevated);color:var(--dl-fg);border:1px solid var(--dl-line);box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4))}.dl-popcard.away{visibility:hidden}.dl-popcard.leaving{pointer-events:none}.dl-popcard-tip{position:absolute;left:var(--tip-x, 50%);width:10px;height:10px;margin-left:-6px;box-sizing:border-box;background:var(--dl-elevated);border:solid var(--dl-line);transform:rotate(45deg)}.dl-popcard.above .dl-popcard-tip{bottom:-6px;border-width:0 1px 1px 0}.dl-popcard.below .dl-popcard-tip{top:-6px;border-width:1px 0 0 1px}.dl-popcard.above{transform-origin:var(--tip-x, 50%) 100%}.dl-popcard.below{transform-origin:var(--tip-x, 50%) 0}@media(prefers-reduced-motion:no-preference){.dl-popcard{animation:dl-pop-in .16s ease-out}.dl-popcard.leaving{animation:dl-pop-out .14s ease-in forwards}}@keyframes dl-pop-in{0%{opacity:0;transform:scale(.94)}to{opacity:1;transform:none}}@keyframes dl-pop-out{0%{opacity:1;transform:none}to{opacity:0;transform:scale(.94)}}.dl-pop{display:flex;flex-direction:column;gap:4px;font-size:12px;line-height:18px;min-width:210px}.dl-pop-head{display:flex;align-items:center;gap:8px;font-size:13px;margin-bottom:2px}.dl-pop-net{width:30px;height:30px;border-radius:9px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-pop-list{display:flex;flex-direction:column;margin:6px 0 0;max-height:116px;overflow-y:auto}.dl-pop-row{all:unset;cursor:pointer;display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:8px}.dl-pop-row:hover{background:var(--dl-soft)}.dl-pop-row:focus{outline:none}.dl-pop-row:focus-visible{outline:2px solid var(--dl-ring)}.dl-pop-name{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-pop-name b{font-weight:500}.dl-pop-dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);flex:0 0 auto}.dl-pop-dot.on{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-pop-actions{display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid var(--dl-line)}.dl-pop-actions .cbi-button{flex:1;height:28px!important;font-size:12px!important;justify-content:center}.dl-chartbox{position:relative}.dl-bars{display:flex;align-items:flex-end;gap:4px;border-bottom:1px solid var(--dl-line)}.dl-bar{flex:1;height:100%;display:flex;flex-direction:column-reverse;gap:1px;cursor:default;min-width:3px}.dl-bar i{display:block;border-radius:3px 3px 0 0}.dl-bar i.down{background:var(--dl-chart-1)}.dl-bar i.up{background:var(--dl-chart-2);opacity:.75;border-radius:3px 3px 0 0}.dl-bar:hover i{filter:brightness(1.25)}.dl-bar.empty{background:linear-gradient(to top,var(--dl-line) 2px,transparent 2px)}.dl-tip{position:absolute;top:-8px;transform:translate(-50%,-100%);padding:8px 10px;border-radius:10px;font-size:12px;line-height:18px;white-space:nowrap;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));pointer-events:none;z-index:3}.dl-tip-title{font-weight:500}.dl-tip-float{position:fixed;z-index:2000;color:var(--dl-fg)}.dl-meter,.dl-slots{cursor:default}.dl-axis{display:flex;justify-content:space-between;font-size:12px;color:var(--dl-fg-faint);margin-top:6px}.dl-legend i.down{background:var(--dl-chart-1)}.dl-legend i.up{background:var(--dl-chart-2)}.dl-spark{display:flex;align-items:flex-end;flex:0 0 auto;--dl-gap: 2px}.dl-spark i{flex:1;display:block;border-radius:2px 2px 0 0;background:var(--dl-chart-1);opacity:.85}.dl-spark i.zero{opacity:.22}.dl-spark>span:hover i:not(.zero){opacity:1;filter:brightness(1.25)}.dl-spark>span,.dl-dbars>span,.dl-bento-bars>span{flex:1;min-width:0;height:100%;display:flex;align-items:flex-end;padding:0 calc(var(--dl-gap) / 2)}.dl-spark>span:first-child,.dl-dbars>span:first-child,.dl-bento-bars>span:first-child{padding-left:0}.dl-spark>span:last-child,.dl-dbars>span:last-child,.dl-bento-bars>span:last-child{padding-right:0}`;var ca=`.dl-row{display:flex;align-items:center;gap:12px;padding:12px 16px;border-top:1px solid var(--dl-line);font-size:14px;line-height:20px;min-width:0}.dl-row.link{color:inherit;text-decoration:none}.dl-row.link:hover{background:var(--dl-soft)}.dl-row-main{flex:1;min-width:0;overflow-wrap:anywhere}.dl-row-main b{font-weight:500}.dl-attn{display:flex;flex-direction:column;gap:10px;padding:16px;border-top:1px solid var(--dl-line)}.dl-attn-item{display:flex;gap:10px;align-items:baseline;font-size:13px;color:var(--dl-fg-muted)}.dl-avatar.sm{width:26px;height:26px;font-size:10px;margin:0}.dl-avatar.lg{width:48px;height:48px;font-size:15px;margin:0}.dl-avatar.lg.online:after{width:12px;height:12px}.dl-list{border:1px solid var(--dl-line);border-radius:12px;overflow:hidden}.dl-list>.dl-row:first-child{border-top:0}.dl-ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.dl-row-main.dl-stack{min-width:0}.dl-person-id{display:flex;align-items:center;gap:14px;min-width:0}.dl-grid-person{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);gap:16px;align-items:start}@media(max-width:1000px){.dl-grid-person{grid-template-columns:minmax(0,1fr)}}.dl-devsec{display:flex;flex-direction:column;gap:12px}.dl-devsec .dl-panel-head{margin:0}.dl-dgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.dl-dcard>.dl-dcard-head+*{margin-top:auto}@media(max-width:700px){.dl-dgrid{grid-template-columns:minmax(0,1fr)}}.dl-dgrid>.dl-dslot.add:only-child{grid-column:1 / -1}.dl-dcard{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:12px;min-width:0;box-shadow:var(--dl-shadow)}.dl-dcard.online{border-color:color-mix(in srgb,var(--dl-ok) 35%,transparent)}.dl-dcard.off{opacity:.7}.dl-dcard-head{display:flex;align-items:center;gap:12px}.dl-dcard-ic{width:40px;height:40px;border-radius:12px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-dcard-ic .dl-icon{width:20px;height:20px}.dl-dcard.online .dl-dcard-ic{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-dcard-title{all:unset;cursor:pointer;flex:1;min-width:0;display:flex;flex-direction:column}.dl-dcard-title b{font-weight:500;font-size:15px}.dl-dstat{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--dl-fg-muted);white-space:nowrap;min-width:0}.dl-dstat i.dot{flex:none}.dl-dstat.ok{color:var(--dl-ok)}.dl-dstat.warn{color:var(--dl-warn)}.dl-dstat i.dot,.dl-savebar i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint)}.dl-dstat i.dot.ok{background:var(--dl-ok);box-shadow:0 0 0 3px var(--dl-ok-wash)}.dl-dstat i.dot.warn{background:var(--dl-warn)}.dl-dcard-use{display:flex;align-items:flex-end;justify-content:space-between;gap:12px}.dl-dcard-foot{padding-top:10px;border-top:1px solid var(--dl-line);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dl-dslot.add{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:14px;min-height:0;border:1px dashed color-mix(in srgb,currentColor 18%,transparent);border-radius:14px;text-align:center;color:var(--dl-fg-muted);transition:background .15s,border-color .15s,color .15s}.dl-dslot.add .dl-stack{align-items:center}.dl-dslot.add:hover{border-color:color-mix(in srgb,currentColor 35%,transparent);color:var(--dl-fg)}.dl-dslot.add:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-dslot.add b{font-weight:500}.dl-dslot.add:hover{background:var(--dl-soft)}.dl-dslot-ic{width:36px;height:36px;border-radius:999px;background:var(--dl-soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--dl-fg-muted)}.dl-dslot.add:hover .dl-dslot-ic{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-tiles2{display:grid;gap:10px;margin-top:16px}.dl-tile2{border:1px solid var(--dl-line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:10px;min-width:0}.dl-tile2-label{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:12px;font-weight:500;color:var(--dl-fg-faint)}.dl-tile2-row{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}.dl-tile2-value{font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums}.dl-tile2-value .dl-faint{font-size:14px;font-weight:400}.dl-tile2-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-top:10px;border-top:1px solid var(--dl-line);font-size:12px}.dl-stepper{display:inline-flex;align-items:stretch;height:32px;border:1px solid var(--input, var(--dl-line));border-radius:8px;overflow:hidden}.dl-stepper button{all:unset;cursor:pointer;width:32px;display:inline-flex;align-items:center;justify-content:center;font-size:16px;color:var(--dl-fg)}.dl-stepper button:hover{background:var(--dl-soft)}.dl-stepper button[disabled]{opacity:.35;cursor:not-allowed}.dl-stepper+.dl-stepper{margin-left:4px}.dl-step-select{border:0!important;border-left:1px solid var(--input, var(--dl-line))!important;border-right:1px solid var(--input, var(--dl-line))!important;border-radius:0!important;background:transparent!important;color:inherit;font:500 13px inherit;padding:0 10px!important;height:100%!important;min-width:0!important}.dl-slots{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:3px}.dl-slots i{height:4px;border-radius:999px;background:var(--dl-track);display:block}.dl-slots i.used{background:var(--dl-fg)}.dl-slots i.over{background:color-mix(in srgb,var(--dl-warn) 80%,transparent)}.dl-date{display:flex;align-items:center;gap:8px;flex:1 1 150px;min-width:0;box-sizing:border-box;height:34px;padding:0 10px;border:1px solid var(--input, var(--dl-line));border-radius:8px;color:var(--dl-fg-faint)}.dl-date input{border:0!important;background:transparent!important;box-shadow:none!important;padding:0!important;height:32px!important;color:var(--dl-fg);flex:1;min-width:0!important;width:100%!important}.dl-meter{position:relative;height:6px;border-radius:999px;background:var(--dl-track)}.dl-meter>i{display:block;height:100%;border-radius:999px;background:var(--dl-accent)}.dl-meter.warn>i{background:var(--dl-warn)}.dl-meter.bad>i{background:var(--dl-bad)}.dl-meter .mark{position:absolute;left:90%;top:-3px;width:1px;height:12px;background:var(--dl-warn)}.dl-meter.sm{height:4px}.dl-chips-row{display:flex;flex-wrap:wrap;gap:4px}.dl-chipbtn{all:unset;cursor:pointer;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-soft);font-size:12px;font-weight:500;display:inline-flex;align-items:center}.dl-chipbtn:hover{background:var(--dl-soft-hover)}.dl-chipbtn.on{background:var(--dl-primary);color:var(--dl-primary-fg)}.dl-switch{all:unset;cursor:pointer;position:relative;width:32px;height:20px;border-radius:999px;background:var(--switch-off, var(--dl-track));flex:0 0 auto;transition:background .15s}.dl-switch i{position:absolute;left:2px;top:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:left .15s;box-shadow:0 1px 2px #0000004d}.dl-switch.on{background:var(--dl-accent)}.dl-switch.on i{left:14px}.dl-switch:focus-visible{outline:2px solid var(--dl-ring);outline-offset:2px}.dl-linkbox{display:flex;align-items:center;gap:8px;height:36px;padding:0 4px 0 12px;border:1px solid var(--input, var(--dl-line));border-radius:8px;background:var(--input-bg, transparent)}.dl-linkbox .dl-mono{flex:1;min-width:0;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--dl-fg-muted)}.dl-linkbox .cbi-button{height:28px!important}.dl-pcard{display:grid;grid-template-columns:minmax(0,1fr) 260px;gap:20px;align-items:stretch;min-width:0}.dl-pcard-main{min-width:0}.dl-pcard-top{display:flex;align-items:center;gap:12px;min-width:0}.dl-pcard-top .dl-avatar{margin-right:0}.dl-pcard-who{flex:1;min-width:0}.dl-pcard-who .dl-slotbar{margin:3px 0 0}.dl-pside{display:flex;flex-direction:column;justify-content:space-between;gap:8px;padding-left:20px;border-left:1px solid var(--dl-line);min-width:0}.dl-pside-top{display:flex;align-items:center;justify-content:space-between;gap:8px}.dl-pside-state{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--dl-fg-muted)}.dl-pside-state.live{color:var(--dl-ok)}.dl-pside-foot{font-size:12px}.dl-pside .dl-use-num b{font-size:20px}.dl-none{display:none!important}.dl-pcard-actions{display:flex;gap:6px;flex:0 0 auto}.dl-pcard-actions .cbi-button{height:32px!important}.dl-icon-only .dl-btn-label{display:none}.dl-pill-ic{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0 8px;border-radius:999px;font-size:12px;white-space:nowrap;background:var(--dl-soft);color:var(--dl-fg-muted)}.dl-pill-ic .dl-icon{width:12px;height:12px}.dl-pill-ic.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-pill-ic.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-use-num{display:flex;align-items:baseline;gap:6px;white-space:nowrap}.dl-use-num b{font-size:15px;font-weight:500}.dl-use-live{display:flex;align-items:center;gap:8px;font-size:12px;font-variant-numeric:tabular-nums}.dl-usebar{display:flex;gap:2px;height:6px;border-radius:999px;overflow:hidden;background:var(--dl-track)}.dl-usebar i{display:block;height:100%;min-width:3px;flex:0 1 0}.dl-usebar i.fill{flex:none;min-width:0;border-radius:999px;background:var(--dl-accent)}.dl-usebar.warn i.fill{background:var(--dl-warn)}.dl-usebar.bad i.fill{background:var(--dl-bad)}.dl-usebar .c0,.dl-swatch.c0{background:var(--dl-chart-1)}.dl-usebar .c1,.dl-swatch.c1{background:#8b7cf6}.dl-usebar .c2,.dl-swatch.c2{background:#2fb889}.dl-usebar .c3,.dl-swatch.c3{background:#d9a03f}.dl-usebar .c4,.dl-swatch.c4{background:var(--dl-fg-faint)}.dl-tip-row{display:flex;align-items:center;gap:8px;min-width:160px}.dl-tip-row b{margin-left:auto;font-weight:500}.dl-swatch{width:8px;height:8px;border-radius:2px;flex:none}.dl-card-name{color:var(--dl-fg)!important;text-decoration:none}.dl-card-name:hover{text-decoration:underline}.dl-chip-tag{font-size:11px;line-height:18px;padding:0 6px;border-radius:999px;background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-chip.live{background:var(--dl-ok-wash);color:color-mix(in srgb,var(--dl-ok) 35%,var(--dl-fg))}.dl-chip.live:hover{background:color-mix(in srgb,var(--dl-ok) 22%,transparent)}.dl-chip.live .dl-icon{color:var(--dl-ok)}.dl-fixes{display:flex;gap:6px;flex-wrap:wrap;margin:10px 0 0 44px}.dl-fix{all:unset;cursor:pointer;height:26px;padding:0 10px;border-radius:999px;background:var(--dl-info-wash);color:var(--dl-info);font-size:12px;font-weight:500;display:inline-flex;align-items:center}.dl-fix:hover{filter:brightness(1.15)}@media(max-width:760px){.dl-pcard{grid-template-columns:1fr}.dl-pside{padding:12px 0 0;border-left:0;border-top:1px solid var(--dl-line)}.dl-fixes{margin-left:0}}.dl-select{height:34px!important;border-radius:999px!important;min-width:136px!important;width:auto!important;padding:0 34px 0 14px!important;appearance:none!important;-webkit-appearance:none!important;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238b8f98' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")!important;background-repeat:no-repeat!important;background-position:right 12px center!important;background-size:14px!important}.dl-savebar{position:fixed;left:50%;bottom:24px;transform:translate(-50%,160%);opacity:0;transition:transform .25s cubic-bezier(.2,.8,.2,1),opacity .2s;display:flex;align-items:center;gap:10px;padding:8px 8px 8px 18px;border-radius:999px;background:var(--dl-elevated);border:1px solid var(--dl-line);box-shadow:var(--shadow-2xl, 0 16px 32px -8px rgba(0,0,0,.5));z-index:60;pointer-events:none}.dl-savebar.show{transform:translate(-50%);opacity:1;pointer-events:auto}.dl-savebar-text{display:inline-flex;align-items:center;gap:8px;font-size:13px;font-weight:500}`;var pa=".dl-toast strong{display:block;font-weight:500}.dl-toast div{opacity:.8;font-size:13px}.dl-drawer-overlay{position:fixed;inset:0;z-index:900;display:flex;justify-content:flex-end;background:transparent;transition:background .2s}.dl-drawer-overlay.open{background:var(--scrim, rgba(0,0,0,.45))}.dl-drawer{width:min(520px,100%);height:100%;display:flex;flex-direction:column;background:var(--dialog-bg, var(--dl-elevated));color:var(--dl-fg);border-left:1px solid var(--dl-line);box-shadow:var(--shadow-2xl, -16px 0 32px -8px rgba(0,0,0,.5));transform:translate(100%);transition:transform .22s cubic-bezier(.2,.8,.2,1)}.dl-drawer-overlay.open .dl-drawer{transform:none}.dl-drawer-head{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid var(--dl-line)}.dl-drawer-title{flex:1;min-width:0;display:flex;align-items:center;gap:12px}.dl-drawer-title h3{margin:0!important;padding:0!important;border:0!important;font-size:18px!important;line-height:26px;font-weight:500!important}.dl-drawer-x{all:unset;cursor:pointer;width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:var(--dl-fg-muted)}.dl-drawer-x:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-drawer-body{flex:1;overflow:auto;padding:20px}.dl-drawer-foot{padding:12px 20px;border-top:1px solid var(--dl-line)}.dl-drawer-actions{display:flex;align-items:center;gap:8px}.dl-dcard-ic.on{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-icon-only.sm{width:28px;height:28px!important}.dl-stack.gap12{gap:12px}.dl-stack.gap16{gap:16px}.dl-dstats{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid var(--dl-line);border-radius:14px;overflow:hidden}.dl-dstats-cell{display:flex;flex-direction:column;gap:4px;padding:12px 14px;min-width:0}.dl-dstats-cell.wide{grid-column:span 2;border-bottom:1px solid var(--dl-line)}.dl-dstats-cell+.dl-dstats-cell:not(.wide):last-child{border-left:1px solid var(--dl-line)}.dl-dstats-cell b{font-size:16px;font-weight:500;font-variant-numeric:tabular-nums}.dl-dstats-cell .dl-dstat{font-size:14px}.dl-dsec{border:1px solid var(--dl-line);border-radius:14px;padding:16px;display:flex;flex-direction:column;gap:12px}.dl-dsec-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.dl-dsec-head h4{margin:0!important;padding:0!important;font-size:14px!important;font-weight:500!important;border:0!important}.dl-dstat i.dot{width:6px;height:6px;border-radius:50%;background:var(--dl-fg-faint);display:inline-block}.dl-connect-body{min-height:60px}.dl-connect-body .dl-qr{width:min(240px,70vw)}.dl-kv2{display:flex;flex-direction:column}.dl-kvrow{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:9px 0;border-top:1px solid var(--dl-line);font-size:13px;min-width:0}.dl-kvrow:first-child{border-top:0;padding-top:0}.dl-kvrow-k{color:var(--dl-fg-muted);flex:0 0 auto}.dl-kvrow-v{min-width:0;text-align:right;overflow-wrap:anywhere}.dl-kvrow-v.copy{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:6px;min-width:0;color:var(--dl-fg)}.dl-kvrow-v.copy span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-kvrow-v.copy .dl-icon{width:13px;height:13px;color:var(--dl-fg-faint)}.dl-kvrow-v.copy:hover .dl-icon{color:var(--dl-fg)}@media(max-width:560px){.dl-drawer{width:100%}.dl-dstats{grid-template-columns:minmax(0,1fr)}.dl-dstats-cell.wide{grid-column:auto}.dl-dstats-cell+.dl-dstats-cell:not(.wide):last-child{border-left:0;border-top:1px solid var(--dl-line)}}.dl-dev-log{display:flex;flex-direction:column}.dl-dev-log-row{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--dl-line);font-size:13px;line-height:20px;min-width:0}.dl-dev-log-row:first-child{border-top:0;padding-top:0}.dl-dev-log-row .dl-row-main{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}";var ua=".dl-settings-main{min-width:0;display:flex;flex-direction:column;gap:20px}.dl-setsec{background:var(--dl-card);border:1px solid var(--dl-line);border-radius:var(--dl-radius);overflow:hidden;scroll-margin-top:88px;box-shadow:var(--dl-shadow)}.dl-setsec-body{padding:20px;display:flex;flex-direction:column;gap:14px}.dl-setsec-body h3{margin:0!important;padding:0!important;font-size:18px!important;line-height:26px;font-weight:500!important;border:0!important}.dl-setsec-body p{margin:0}.dl-setsec-head{display:flex;align-items:center;gap:10px}.dl-group{border:1px solid var(--dl-line);border-radius:14px;padding:2px 16px}.dl-group-head{display:flex;align-items:center;gap:12px;padding:14px 0 10px}.dl-group-head b{font-size:15px;font-weight:500}.dl-group-ic{width:32px;height:32px;border-radius:10px;background:var(--dl-soft);color:var(--dl-fg-muted);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-group-ic .dl-icon-wrap{display:inline-flex}.dl-group-ic .dl-icon{width:16px;height:16px}.dl-group-body>*{padding:12px 0;margin:0!important}.dl-group-body>*+*:not(.alert-message):not(.dl-params):not(.dl-note){border-top:1px solid var(--dl-line)}.dl-group-body>.alert-message,.dl-group-body>.dl-params{margin:12px 0!important}.dl-group-body>.alert-message{padding:10px 14px}.dl-group-body>.dl-params{padding:0}.dl-group-body>.dl-note{margin:0 0 14px!important;padding:10px 12px}.dl-group-body>.alert-message+*,.dl-group-body>.dl-params+*,.dl-group-body>.dl-note+*{border-top:0}.dl-group-body>.dl-row{border-left:0;border-right:0;border-bottom:0;padding-left:0;padding-right:0;background:none}.dl-group-body>.dl-row:first-child{border-top:0}.dl-setsec-foot{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 16px;padding:12px 20px;border-top:1px solid var(--dl-line);background:var(--dl-soft)}.dl-setsec.danger{border-color:color-mix(in srgb,var(--dl-bad) 40%,transparent)}.dl-setsec.danger .dl-setsec-foot{background:color-mix(in srgb,var(--dl-bad) 6%,transparent)}.dl-setrow{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,420px);align-items:center;gap:8px 24px}.dl-setrow.head{display:flex;justify-content:space-between;gap:16px}.dl-setrow-label{font-size:14px;font-weight:500}.dl-setrow-ctl{display:flex;justify-content:flex-end;min-width:0}.dl-setrow-ctl .dl-chips-row{justify-content:flex-end}.dl-setrow-ctl>input{width:100%}.dl-hostport{display:flex;align-items:center;gap:8px;flex:1;min-width:0;justify-content:flex-end}.dl-hostport input{flex:1;min-width:0}.dl-root input.dl-w-port,.dl-hostport input.dl-w-port{flex:0 0 90px;width:90px}.dl-root input.dl-w-range{flex:0 0 130px;width:130px}.dl-setrow .dl-sub.bad{color:var(--dl-bad)}.dl-suffixed{display:inline-flex;align-items:center;gap:6px}.dl-suffixed>span{color:var(--dl-fg-muted)}.dl-more summary{cursor:pointer;color:var(--dl-fg-muted);font-size:13px;margin-bottom:10px}.dl-more .dl-setrow+.dl-setrow{margin-top:10px}@media(max-width:760px){.dl-setrow:not(.head){grid-template-columns:minmax(0,1fr)}.dl-setrow-ctl,.dl-setrow-ctl .dl-chips-row{justify-content:flex-start}}.dl-need-ic{width:30px;height:30px;border-radius:9px;background:var(--dl-soft);color:var(--dl-fg-muted);display:inline-flex;align-items:center;justify-content:center;flex:none}.dl-need-ic .dl-icon-wrap{display:inline-flex}.dl-need-ic .dl-icon{width:15px;height:15px}.dl-need-row.bad .dl-need-ic,.dl-need-ic.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-need-row.warn .dl-need-ic,.dl-need-ic.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-need-ic.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-lh-main{display:flex;align-items:flex-start;gap:12px;min-width:0}.dl-lh-main>.dl-need-ic{margin-top:1px}.dl-sub .dl-mono{font-size:.92em}.dl-need-row>.cbi-button{flex:none}.dl-bk-row .dl-group-ic{width:30px;height:30px}.dl-bk-older>summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:8px;padding:11px 16px;border-top:1px solid var(--dl-line);font-size:13px;color:var(--dl-fg-muted);user-select:none}.dl-bk-older>summary::-webkit-details-marker{display:none}.dl-bk-older>summary:hover{background:var(--dl-soft);color:var(--dl-fg)}.dl-bk-older>summary .dl-icon-wrap{display:inline-flex;transition:transform .15s}.dl-bk-older>summary .dl-icon{width:14px;height:14px}.dl-bk-older[open]>summary .dl-icon-wrap{transform:rotate(90deg)}#dl-set-backups .dl-setsec-head h3+.dl-sub{margin-top:2px}#dl-set-backups .dl-setsec-foot>.dl-sub{flex:1 1 260px}.dl-bk-actions{flex:0 1 auto;justify-content:flex-end}@media(max-width:640px){#dl-set-backups .dl-setsec-foot>.dl-sub{flex-basis:100%}.dl-bk-actions{justify-content:flex-start}}.dl-upd{display:flex;flex-direction:column;gap:16px}.dl-upd>.dl-pagehead{margin:0 0 4px}.dl-upd-bad{color:var(--dl-bad)}";var ma=".dl-comp-hero{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1fr)}.dl-comp-hero-main{padding:20px;display:flex;flex-direction:column;gap:12px;min-width:0}.dl-comp-hero-side{padding:20px;border-left:1px solid var(--dl-line);display:flex;flex-direction:column;gap:14px;min-width:0}.dl-comp-name{font-size:16px;font-weight:500}.dl-comp-hero-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap;min-width:0}.dl-comp-hero-head .dl-spacer{flex:1}.dl-comp-big{font-family:var(--dl-mono);font-size:26px;line-height:34px;letter-spacing:-.02em;display:flex;align-items:baseline;gap:10px}.dl-comp-big small{font-size:14px;color:var(--dl-accent)}.dl-comp-big small.dl-faint{color:var(--dl-fg-faint)}.dl-comp-verrow{display:flex;align-items:center;gap:4px 12px;flex-wrap:wrap;min-width:0}.dl-comp-verrow .dl-spacer{flex:1}.dl-comp-meta{font-size:13px}.dl-comp-bullets{margin:0;padding-left:18px;display:flex;flex-direction:column;gap:4px;color:var(--dl-fg-muted);font-size:13px}.dl-comp-bullets li{list-style:disc}.dl-comp-lead{margin:0}.dl-comp-more{align-self:flex-start;font-size:12px;color:var(--dl-fg-faint);margin-left:18px;padding:0!important}.dl-comp-more:hover{color:var(--dl-accent);background:none!important;text-decoration:underline;text-underline-offset:2px}.dl-comp-hero-main>.dl-comp-vers{margin-top:auto}.dl-comp-btns{display:flex;gap:8px;flex-wrap:nowrap;align-items:center;flex:none}.dl-comp-side-v{display:flex;align-items:center;gap:8px;font-size:14px;min-width:0;flex-wrap:wrap}.dl-comp-side-v .dl-icon{width:15px;height:15px;color:var(--dl-fg-muted)}.dl-comp-side-v a{color:inherit;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-side-v a:hover{color:var(--dl-accent)}.dl-comp-cols{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(0,1fr);gap:16px;align-items:start}.dl-comp-cols>.dl-panel>div>.dl-row:first-child{border-top:1px solid var(--dl-line)}.dl-comp-count{font-size:13px}.dl-comp-sub{font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-ic{display:inline-flex;gap:4px;flex:none}.dl-comp-ic .cbi-button{width:30px;height:30px;padding:0!important;justify-content:center;border-radius:999px!important}.dl-comp-ic .dl-btn-label{display:none}.dl-comp-ic .dl-icon{width:14px;height:14px}.dl-comp-ic .is-busy{pointer-events:none;opacity:.5}.dl-comp-ic .cbi-button.dl-comp-check{width:auto;padding:0 12px 0 10px!important;gap:6px;display:inline-flex;align-items:center;font-size:13px}.dl-row>.dl-pill,.dl-row>.cbi-button,.dl-row>.dl-comp-ic{flex:none}button.dl-pill.dl-comp-run{all:unset;display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:999px;font-size:12px;cursor:pointer;background:color-mix(in srgb,var(--dl-accent) 14%,transparent);color:var(--dl-accent)}.dl-comp-foldwrap{padding:0 16px 14px 60px}.dl-comp-fold .dl-params-body{gap:12px}.dl-comp-fold .dl-list>.dl-row{padding:10px 14px}.dl-comp-bver{font-size:12px;width:130px;text-align:right;flex:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-comp-bact{width:84px;flex:none;display:flex;justify-content:flex-end}.dl-comp-warn{display:flex;align-items:flex-start;gap:8px;font-size:12px;line-height:18px;color:var(--dl-fg-muted)}.dl-comp-warn .dl-icon-wrap{display:inline-flex;flex:none;margin-top:2px}.dl-comp-warn .dl-icon{width:14px;height:14px;color:var(--dl-warn)}.dl-comp-empty{margin:0;padding:4px 16px 16px}@media(max-width:760px){.dl-comp-hero,.dl-comp-cols{grid-template-columns:minmax(0,1fr)}.dl-comp-hero-side{border-left:0;border-top:1px solid var(--dl-line)}.dl-comp-foldwrap{padding-left:16px}.dl-comp-bver{display:none}}.dl-comp-status{display:flex;align-items:center;gap:8px;font-size:13px;padding:9px 12px;border-radius:10px;background:var(--dl-soft);min-width:0}.dl-comp-status>.dl-icon-wrap{display:inline-flex;flex:none}.dl-comp-status .dl-icon{width:15px;height:15px}.dl-comp-status.ok{background:var(--dl-ok-wash);color:var(--dl-ok)}.dl-comp-status.acc{background:color-mix(in srgb,var(--dl-accent) 12%,transparent);color:var(--dl-accent)}.dl-comp-status.warn{background:var(--dl-warn-wash);color:var(--dl-warn)}.dl-comp-status.bad{background:var(--dl-bad-wash);color:var(--dl-bad)}.dl-comp-status b{font-weight:600}.dl-comp-vers .dl-params-body{gap:0;padding:4px 14px 12px}.dl-comp-tag{display:flex;gap:6px;padding:6px 0 10px}.dl-comp-tag input{flex:1;min-width:0}.dl-comp-ver{display:flex;align-items:center;gap:8px;padding:7px 0;border-top:1px solid var(--dl-line);font-size:13px}.dl-comp-ver .dl-mono{min-width:52px}.dl-comp-ver .dl-sub{flex:1}.dl-comp-ver .cbi-button:not(.dl-icon-btn){height:26px!important;font-size:12px!important}.dl-comp-pager{display:flex;align-items:center;justify-content:space-between;padding-top:10px;border-top:1px solid var(--dl-line);font-size:12px}.dl-comp-pager .dl-linkbtn[disabled]{opacity:.4;cursor:default}.dl-comp-vers .dl-loading,.dl-comp-vers .dl-params-body>p{padding:6px 0 10px}.dl-op-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:14px}.dl-op-head .dl-spacer{flex:1}.dl-op-timer{display:inline-flex;align-items:center;gap:5px;font-variant-numeric:tabular-nums}.dl-op-timer .dl-icon,.dl-op-head .dl-linkbtn .dl-icon{width:14px;height:14px}.dl-op-loghead{display:flex;align-items:center;justify-content:space-between}.dl-op-loghead b{font-weight:500;font-size:13px}.dl-op .dl-log{max-height:16em;min-height:12em;margin-top:8px}.dl-op .dl-comp-status{margin:14px 0 0}.dl-op-actions{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap;width:100%}.dl-notes{max-height:55vh;overflow:auto;border-radius:12px;background:var(--dl-soft);padding:14px 16px;font-size:13px;line-height:20px;overflow-wrap:anywhere}.dl-notes h5{margin:10px 0 6px;font-size:14px;font-weight:500}.dl-notes h5:first-child{margin-top:0}.dl-notes p{margin:0 0 8px}.dl-notes ul{margin:0 0 10px;padding-left:18px}.dl-notes li{list-style:disc}.dl-notes code{font-family:var(--dl-mono);font-size:12px;padding:1px 5px;border-radius:6px;background:var(--dl-soft-hover)}.dl-notes pre{font-family:var(--dl-mono);font-size:12px;padding:10px;border-radius:8px;background:var(--dl-soft-hover);white-space:pre-wrap;margin:0 0 10px}.dl-notes a{color:var(--dl-accent)}";var ha=".dl-chip.static{cursor:default}.dl-chip.static:hover{background:var(--dl-soft)}.dl-chip.static .dl-chip-name{font-weight:500}.dl-setrow.head .dl-chips-row,.dl-setrow.head .dl-note{margin-top:8px}.dl-setrow.head .dl-note{margin-bottom:0}.dl-setrow.head>.dl-lh-main,.dl-setrow.head>.dl-lh-main>.dl-stack{flex:1 1 auto;min-width:0}.dl-setrow.head>.dl-setrow-ctl:empty{display:none}.dl-setrow.head:has(>.dl-lh-main){align-items:flex-start}.dl-setrow.head>.dl-setrow-ctl{align-items:center;min-height:30px}.dl-netpick{margin-top:10px}.dl-boxrow{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:0;padding:10px 14px;border:1px solid var(--dl-line);border-radius:12px;font-size:13px;cursor:pointer}.dl-boxrow>.dl-switch{flex:none}.dl-ifpick{display:flex;flex-direction:column;gap:12px;padding:14px;border:1px solid var(--dl-line);border-radius:14px}.dl-iflead-row{display:flex;align-items:center;justify-content:space-between;gap:12px}.dl-host{align-items:flex-start}.dl-host>.dl-icon-wrap{margin-top:13px}.dl-host-body{flex:1;min-width:0;display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px}.dl-host-body>.dl-row-main{flex:1 1 160px}.dl-circle-dot{display:inline-block;width:8px;height:8px;border-radius:50%;flex:none}.dl-circles .dl-chip b{font-weight:500}.dl-circle-name{display:inline-flex;align-items:center;gap:8px;font-size:14px;font-weight:500}.dl-w400{font-weight:400}.dl-swatches{display:flex;flex-wrap:wrap;gap:8px}.dl-swatch{all:unset;cursor:pointer;width:22px;height:22px;border-radius:50%;background:var(--sw);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dl-fg) 12%,transparent)}.dl-swatch.on{box-shadow:0 0 0 2px var(--dl-card),0 0 0 4px var(--sw)}.dl-swatch:focus-visible{outline:2px solid var(--dl-ring);outline-offset:3px}.dl-circle-modal .dl-chipbtn b{margin-left:6px;font-weight:500;font-size:11px;opacity:.6}.dl-reach td:first-child b{font-weight:500}.dl-ev-host{white-space:nowrap}.dl-ev-host b{font-weight:500;color:var(--dl-fg)}.dl-reach{font-size:13px}.dl-reach th,.dl-reach td{white-space:nowrap;padding-left:6px;padding-right:6px}.dl-reach-wrap{overflow-x:auto}.dl-yes{display:inline-flex;align-items:center;gap:4px;color:var(--dl-ok)}.dl-yes .dl-icon-wrap{display:inline-flex}.dl-yes .dl-icon{width:14px;height:14px}.dl-check-form{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr) auto;align-items:start;gap:8px}.dl-check-form>.dl-faint{line-height:36px}.dl-check-end{display:flex;flex-direction:column;gap:6px;min-width:0}.dl-check-end>*{width:100%!important;min-width:0}@media(max-width:560px){.dl-check-form{grid-template-columns:minmax(0,1fr)}.dl-check-form>.dl-faint{display:none}}.dl-verdict{display:flex;align-items:baseline;gap:10px;padding:10px 12px;border-radius:12px}.dl-verdict b{font-weight:500}.dl-verdict.ok{background:var(--dl-ok-wash)}.dl-verdict.ok b{color:var(--dl-ok)}.dl-verdict.bad{background:var(--dl-bad-wash)}.dl-verdict.bad b{color:var(--dl-bad)}.dl-corehead{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:0 0 4px}.dl-corehead h3{margin:0!important}.dl-row-end{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}.dl-dcard.clickable{cursor:pointer}.dl-dcard.clickable:hover{border-color:color-mix(in srgb,var(--dl-fg) 22%,transparent)}";var Vd=[ea,ta,na,oa,sa,ra,ia,aa,la,da,ca,pa,ua,ma,ha].join(` +`);function fa(){let t=document.createElement("style");return t.dataset.dawnline="1",t.textContent=Vd,t}function Lt(t){return()=>{let e=new t;return Object.assign({load:()=>e.load(),render:async s=>{let r=await e.render(s),i=document.createElement("div");return i.className="dl-root",i.append(fa(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var ux=Lt(un),mx=Lt(Ct),hx=Lt(un),fx=Lt(Qn),gx=Lt(no),vx=Lt(io),bx=Lt(to);function ga(t){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${t?`?tab=${t}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var xx=ga(""),wx=ga("log");return baseclass.extend({ activity: wx, diagnostics: vx, health: xx, overview: ux, people: mx, person: gx, server: hx, settings: fx, updates: bx }); diff --git a/package/luci-app-dawnline/po/ru/dawnline.po b/package/luci-app-dawnline/po/ru/dawnline.po index 73cdde9..b58dd51 100644 --- a/package/luci-app-dawnline/po/ru/dawnline.po +++ b/package/luci-app-dawnline/po/ru/dawnline.po @@ -101,6 +101,20 @@ msgstr "%s - %s" msgid "%s - not repaired again (%d repairs didn't help)" msgstr "%s - больше не исправляется (исправления не помогли: %d)" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record." +msgid_plural "%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records." +msgstr[0] "%s AAAA → %s: это не публичный адрес роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эту запись AAAA." +msgstr[1] "%s AAAA → %s: это не публичные адреса роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эти записи AAAA." +msgstr[2] "%s AAAA → %s: это не публичные адреса роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эти записи AAAA." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router." +msgid_plural "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router." +msgstr[0] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эту запись AAAA или настройте IPv6 на роутере." +msgstr[1] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эти записи AAAA или настройте IPv6 на роутере." +msgstr[2] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эти записи AAAA или настройте IPv6 на роутере." + #: web/src/admin/cores/awg.ts msgid "%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you)." msgid_plural "%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)." @@ -158,6 +172,10 @@ msgstr "%s и %s" msgid "%s and %s are not in one circle" msgstr "%s и %s не в одном круге" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s and %s overlap: each packet type needs values of its own." +msgstr "%s и %s пересекаются: у каждого типа пакетов должны быть свои значения." + #: web/src/admin/cores/awg.ts msgid "%s applied" msgstr "Маскировка «%s» применена" @@ -446,6 +464,10 @@ msgstr "%s: доступ «Только интернет»." msgid "%s has Internet only: only DNS and the portal on the router." msgstr "%s: доступ «Только интернет», на роутере доступны только DNS и портал." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s has a tag that is not closed with >." +msgstr "%s: тег не закрыт символом >." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s has an invalid interface name \"%s\"." msgstr "У сервера %s недопустимое имя интерфейса «%s»." @@ -550,6 +572,10 @@ msgstr "%s теперь без круга" msgid "%s is kept down." msgstr "Сервер %s остановлен." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s" +msgstr "Сервер %s остановлен: в его маскировке есть значения, которые AmneziaWG не примет. %s" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)." msgstr "Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (установлен %s)." @@ -569,6 +595,10 @@ msgstr[2] "Не установлено: %s." msgid "%s is not a bridge, so Dawnline cannot join the LAN as a device." msgstr "%s - не мост, поэтому Dawnline не может подключиться к LAN как устройство." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s is not a common home subnet: the networks people connect from rarely use the same addresses." +msgstr "%s: не самая частая домашняя подсеть: сети, из которых подключаются люди, редко используют те же адреса." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc msgid "%s is not a package Dawnline manages" @@ -602,6 +632,10 @@ msgstr "%s на другом сервере" msgid "%s is on the internet" msgstr "%s в интернете" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24." +msgstr "%s: одна из самых распространённых домашних подсетей. В сети с такими же адресами люди с доступом к дому попадают к вам домой, а не в свою сеть: их принтер или телевизор там недоступен, пока они подключены, даже с обходом локальной сети. Это исправит более редкая подсеть для вашей домашней сети, например 10.37.12.0/24." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc msgid "%s is part of %s; choose %s instead." msgstr "%s входит в %s, выберите %s." @@ -658,6 +692,10 @@ msgstr[2] "%s пакетов мусора" msgid "%s left" msgstr "осталось %s" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s may not contain # or a line break." +msgstr "%s не может содержать # или перенос строки." + #: web/src/shared/format.ts msgid "%s min ago" msgstr "%s мин назад" @@ -678,8 +716,32 @@ msgid "%s moves to %s with OpenWrt %s." msgstr "Сборка %s перейдёт на AmneziaWG %s с OpenWrt %s." #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc -msgid "%s must be a number or range" -msgstr "%s: нужно число или диапазон" +msgid "%s must be a number or a range like 10-100, up to 65535." +msgstr "%s: нужно число или диапазон вида 10-100, не больше 65535." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a number or a range like 100-200, up to 4294967295." +msgstr "%s: нужно число или диапазон вида 100-200, не больше 4294967295." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a number or a range like 5-15, from 1 to 65535." +msgstr "%s: нужно число или диапазон вида 5-15, от 1 до 65535." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a whole number from 0 to 65535." +msgstr "%s: нужно целое число от 0 до 65535." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be at least 12 with header protection." +msgstr "%s: с защитой заголовков нужно не меньше 12." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be from %d to %d." +msgstr "%s: от %d до %d." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be on or off." +msgstr "%s: нужно on или off." #: package/luci-app-dawnline/root/usr/libexec/dawnline/updater msgid "%s needs a manual switch in Components" @@ -846,6 +908,10 @@ msgstr[2] "%s исправлений сегодня, последнее - %s в msgid "%s resumed" msgstr "%s: доступ возобновлён" +#: web/src/admin/device-link.ts +msgid "%s s" +msgstr "%s с" + #: web/src/admin/pages/settings/logs.ts msgid "%s since %s" msgstr "%s с %s" @@ -928,6 +994,10 @@ msgstr[0] "%s год" msgstr[1] "%s года" msgstr[2] "%s лет" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +msgid "%s · interface settings" +msgstr "%s · настройки интерфейса" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc msgid "%s · restored" msgstr "%s · восстановлено" @@ -944,6 +1014,17 @@ msgstr "%s → %s (Cloudflare). %s дойдёт до роутера, тольк msgid "%s → %s (this router)." msgstr "%s → %s (этот роутер)." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS." +msgid_plural "%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS." +msgstr[0] "%s → %s: только IPv6, и это не публичный адрес роутера: ни одно устройство не подключится. Проверьте DNS / DDNS." +msgstr[1] "%s → %s: только IPv6, и это не публичные адреса роутера: ни одно устройство не подключится. Проверьте DNS / DDNS." +msgstr[2] "%s → %s: только IPv6, и это не публичные адреса роутера: ни одно устройство не подключится. Проверьте DNS / DDNS." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router." +msgstr "%s → %s: только IPv6, но у роутера нет публичного IPv6-адреса: ни одно устройство не подключится. Проверьте DNS / DDNS или настройте IPv6 на роутере." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc msgid "%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)." msgstr "%s → %s: только IPv6, поэтому подключатся лишь устройства с IPv6 (у IPv4-адреса роутера %s нет имени)." @@ -983,6 +1064,10 @@ msgstr[2] "%s: %s устройств, город неизвестен" msgid "%s: %s of 4" msgstr "%s: %s из 4" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s: <%s> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or ." +msgstr "%s: тег <%s> не примут приложения AmneziaWG: используйте с чётным числом шестнадцатеричных цифр, , или с N от 1 до 1000 либо ." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "%s: the device's own network handles it." msgstr "%s: этот трафик идёт через собственную сеть устройства." @@ -1650,6 +1735,10 @@ msgstr "Приложения с AmneziaWG 3.1 (актуальный AmneziaVPN)" msgid "As soon as found" msgstr "Сразу" +#: web/src/admin/device-link.ts +msgid "As the server: %s" +msgstr "Как у сервера: %s" + #: web/src/admin/pages/settings/updates.ts msgid "At a set time" msgstr "В заданное время" @@ -1699,6 +1788,10 @@ msgstr "Автообновление компонентов" msgid "Automatic update: system packages" msgstr "Автообновление системных пакетов" +#: web/src/admin/device-link.ts +msgid "Automatic: %s" +msgstr "Автоматически: %s" + #: web/src/admin/cores/awg.ts #: web/src/shared/format.ts msgid "B" @@ -1806,8 +1899,8 @@ msgid "Blocked" msgstr "Заблокировано" #: web/src/admin/events/model.ts -msgid "Blocked portal sign-ins (tunnels and services are in the service log)" -msgstr "Заблокированные входы на портал (туннели и службы - в журнале служб)" +msgid "Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)" +msgstr "Заблокированные входы на портал и устройства, которые не могут нормально подключиться (туннели и службы - в журнале служб)" #: web/src/admin/access.ts #: web/src/admin/pages/person/limits.ts @@ -1893,6 +1986,7 @@ msgid "Certificates (ACME)" msgstr "Сертификаты (ACME)" #: web/src/admin/cores/awg.ts +#: web/src/admin/device-link.ts #: web/src/admin/pages/person/limits.ts #: web/src/admin/pages/person/pickers.ts #: web/src/admin/pages/server.ts @@ -1904,6 +1998,14 @@ msgstr "Изменить" msgid "Change limit" msgstr "Изменить лимит" +#: web/src/admin/device-link.ts +msgid "Change the MTU" +msgstr "Изменить MTU" + +#: web/src/admin/device-link.ts +msgid "Change the keep-alive" +msgstr "Изменить keep-alive" + #: web/src/admin/pages/server.ts msgid "Change the tunnel network" msgstr "Сменить сеть туннеля" @@ -1912,6 +2014,10 @@ msgstr "Сменить сеть туннеля" msgid "Changed network" msgstr "Сменило сеть" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +msgid "Changed: %s." +msgstr "Изменено: %s." + #: web/src/admin/pages/server.ts msgid "Changing it marks devices “Update config” until they import again" msgstr "После изменения устройства помечаются «Обновить конфигурацию», пока не импортируют её заново" @@ -2005,6 +2111,10 @@ msgstr "Выберите %s, чтобы включить его." msgid "Choose a device on at least one side." msgstr "Выберите устройство хотя бы с одной стороны." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "Choose a disguise on the Server page: it replaces the values set by hand." +msgstr "Выберите маскировку на странице сервера: она заменит значения, заданные вручную." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc msgid "Choose a free port between 1 and 65535 (not 22, 53, 80 or 443)." @@ -2099,6 +2209,10 @@ msgstr "Закрыть" msgid "Collecting… 1 point a minute" msgstr "Сбор данных… 1 точка в минуту" +#: web/src/admin/widgets/tiles.ts +msgid "Collecting… 1 point a second" +msgstr "Сбор данных… 1 точка в секунду" + #: web/src/admin/access.ts msgid "Colour" msgstr "Цвет" @@ -2154,6 +2268,10 @@ msgstr "Подключено с %s" msgid "Connection" msgstr "Подключение" +#: web/src/admin/events/model.ts +msgid "Connection keeps dropping" +msgstr "Связь постоянно рвётся" + #: package/luci-app-dawnline/root/usr/libexec/dawnline/agent #: web/src/admin/events/model.ts msgid "Connections" @@ -2228,6 +2346,10 @@ msgstr "Сервер %s не принял устройства: %s." msgid "Couldn't read the devices at home." msgstr "Не удалось получить список домашних устройств." +#: web/src/admin/widgets/tiles.ts +msgid "Couldn't read the live speed: %s" +msgstr "Не удалось получить скорость: %s" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc msgid "Couldn't save /etc/config/dawnline: %s. Is the flash full?" msgstr "Не удалось сохранить /etc/config/dawnline: %s. Возможно, заполнена флеш-память?" @@ -2453,6 +2575,7 @@ msgstr "Сведения" #: web/src/admin/logs.ts #: web/src/admin/map.ts +#: web/src/shared/format.ts msgid "Device" msgstr "Устройство" @@ -2468,6 +2591,18 @@ msgstr "Устройство %s подключилось" msgid "Device %s connected from %s" msgstr "Устройство %s подключилось с %s" +#: web/src/admin/events/render.ts +msgid "Device %s connects normally again" +msgstr "Устройство %s снова подключается нормально" + +#: web/src/admin/events/render.ts +msgid "Device %s has a connection problem" +msgstr "У устройства %s проблема с подключением" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: MTU %d is not between 1280 and 1500." +msgstr "Устройство %s (%s): MTU %d вне пределов от 1280 до 1500." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s of %s: address %s is also used by device %s of %s." msgstr "Устройство %s (%s): адрес %s уже занят устройством %s (%s)." @@ -2488,6 +2623,10 @@ msgstr "Устройство %s (%s): адрес %s принадлежит са msgid "Device %s of %s: address (none) is not a plain IPv4 address." msgstr "Устройство %s (%s): нет IPv4-адреса." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds." +msgstr "Устройство %s (%s): keep-alive %d вне пределов от 0 до 600 секунд." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s of %s: the preshared key is not a key." msgstr "Устройство %s (%s): общий ключ (PSK) некорректен." @@ -2500,6 +2639,10 @@ msgstr "Устройство %s (%s): приватный ключ некорре msgid "Device %s of %s: the public key is not a key." msgstr "Устройство %s (%s): публичный ключ некорректен." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: the public key is the server's own." +msgstr "Устройство %s (%s): публичный ключ совпадает с ключом сервера." + #: web/src/admin/events/render.ts msgid "Device %s went offline" msgstr "Устройство %s отключилось" @@ -2768,6 +2911,10 @@ msgstr "Пусто - адрес портала (%s)." msgid "Empty = the portal’s address." msgstr "Пусто - адрес портала." +#: web/src/admin/netcheck.ts +msgid "Empty: automatic. Lower it when big pages hang on this device." +msgstr "Пусто: автоматически. Уменьшите, если на этом устройстве зависают большие страницы." + #: web/src/admin/device.ts msgid "Enable" msgstr "Включить" @@ -2805,8 +2952,8 @@ msgid "Enter a circle name: up to 32 characters, without < > \" or \\." msgstr "Введите название круга: до 32 символов, без < > \" и обратной косой черты." #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc -msgid "Enter a device name (up to 48 characters)." -msgstr "Введите название устройства (до 48 символов)." +msgid "Enter a device name: up to %d letters, digits, spaces and - _ ." +msgstr "Введите название устройства: до %d букв, цифр, пробелов и - _ ." #: web/src/admin/netcheck.ts msgid "Enter a hostname or IP address." @@ -3028,6 +3175,14 @@ msgstr "Свободное место на роутере" msgid "From" msgstr "С" +#: web/src/admin/netcheck.ts +msgid "From 0 to 600 seconds." +msgstr "От 0 до 600 секунд." + +#: web/src/admin/netcheck.ts +msgid "From 1280 to 1500." +msgstr "От 1280 до 1500." + #: web/src/admin/access.ts msgid "From the rules on this server" msgstr "По правилам этого сервера" @@ -3113,6 +3268,10 @@ msgstr "HTTPS на этом порту, открыт на WAN." msgid "Handshake and key timers vary within these ranges instead of WireGuard’s fixed values." msgstr "Таймеры рукопожатия и ключей меняются в этих пределах вместо фиксированных значений WireGuard." +#: web/src/admin/events/model.ts +msgid "Handshake complete, but no data" +msgstr "Рукопожатие есть, но данных нет" + #: web/src/admin/pages/diagnostics/index.ts #: web/src/admin/pages/overview.ts msgid "Health" @@ -3190,6 +3349,10 @@ msgstr "Домашняя сеть" msgid "Home network + Internet" msgstr "Домашняя сеть и интернет" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "Home network addresses" +msgstr "Адреса домашней сети" + #: web/src/admin/pages/person/pickers.ts msgid "Home networks %s reaches. Networks added to the server later stay out." msgstr "%s: доступны отмеченные домашние сети. Сети, добавленные на сервер позже, останутся недоступны." @@ -3246,6 +3409,10 @@ msgstr "Как часто" msgid "How the portal listens (80 and 443 stay free)" msgstr "Как портал принимает подключения (80 и 443 остаются свободны)" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "I1-I5 together must be at most 2000 characters, not %d." +msgstr "I1–I5 вместе: не больше 2000 символов, сейчас %d." + #: web/src/admin/pages/overview.ts msgid "Idle right now" msgstr "Сейчас без трафика" @@ -3338,6 +3505,10 @@ msgstr "Устанавливать автоматически" msgid "Install it in Dawnline → Components." msgstr "Установите его в Dawnline → Компоненты." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page." +msgstr "Установите эту сборку AmneziaWG в Dawnline → Компоненты или смените маскировку на странице сервера." + #: web/src/admin/pkgs.ts msgid "Install the home-like link?" msgstr "Установить домашний маршрут?" @@ -3521,6 +3692,10 @@ msgstr "Карточка приглашения" msgid "Invite card for %s" msgstr "Карточка приглашения: %s" +#: web/src/admin/events/model.ts +msgid "It connects, but the connection breaks every few minutes: the network may be cutting it." +msgstr "Устройство подключается, но связь рвётся каждые несколько минут: возможно, её обрывает сеть." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "It is in the tunnel network %s." msgstr "Он входит в сеть туннеля %s." @@ -3549,6 +3724,10 @@ msgstr "Конфигурация устройства не направляет msgid "Its configuration sends it to the router" msgstr "Конфигурация устройства направляет этот трафик на роутер" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "Jmin must not be larger than Jmax." +msgstr "Jmin не может быть больше Jmax." + #: web/src/admin/cores/awg.ts msgid "Junk packets" msgstr "Мусорные пакеты" @@ -3586,13 +3765,19 @@ msgid "Keep the previous version" msgstr "Хранить прошлую версию" #: web/src/admin/cores/awg.ts +#: web/src/admin/device-link.ts msgid "Keep-alive" msgstr "Keep-alive" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc msgid "Keep-alive must be 0-600 seconds." msgstr "Keep-alive: от 0 до 600 секунд." +#: web/src/admin/device-link.ts +msgid "Keep-alive of %s" +msgstr "Keep-alive для «%s»" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc msgid "Keeping AmneziaWG %s for rollback" msgstr "Сохранение AmneziaWG %s для отката" @@ -3639,6 +3824,12 @@ msgstr "Не удалось создать ключ (нет случайных msgid "Key generation failed." msgstr "Не удалось создать ключ." +#: web/src/admin/device-link.ts +#: web/src/admin/device.ts +#: web/src/admin/events/model.ts +msgid "LAN Bypass" +msgstr "Обход локальной сети" + #: web/src/admin/widgets/tiles.ts msgid "Last 30 days" msgstr "За 30 дней" @@ -3673,6 +3864,10 @@ msgstr "Установлена последняя версия" msgid "Leave out https:// - just the name." msgstr "Без https:// - только имя." +#: web/src/admin/netcheck.ts +msgid "Letters, digits, spaces and - _ . only." +msgstr "Только буквы, цифры, пробелы и - _ ." + #: web/src/admin/pages/components/packages.ts msgid "Let’s Encrypt certificate for the portal" msgstr "Сертификат Let’s Encrypt для портала" @@ -3838,6 +4033,7 @@ msgstr "МБ" msgid "MTU is now automatic" msgstr ": MTU теперь выбирается автоматически" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc msgid "MTU must be 1280-1500." msgstr "MTU: от 1280 до 1500." @@ -3846,6 +4042,10 @@ msgstr "MTU: от 1280 до 1500." msgid "MTU must be 1280–1500, or empty for automatic." msgstr "MTU - от 1280 до 1500 или пусто для автоматического выбора." +#: web/src/admin/device-link.ts +msgid "MTU of %s" +msgstr "MTU для «%s»" + #: web/src/admin/pages/settings/portal.ts msgid "Made by the router: browsers warn until a certificate covers the address." msgstr "Создан роутером: браузеры будут предупреждать, пока у адреса нет настоящего сертификата." @@ -4482,6 +4682,7 @@ msgstr "Сейчас: %s." msgid "OK" msgstr "Работает" +#: web/src/admin/device-link.ts #: web/src/admin/disguise.ts #: web/src/admin/interfaces.ts #: web/src/admin/pages/components/hero.ts @@ -4528,6 +4729,7 @@ msgstr "Возраст нужно указать числом дней." msgid "Older →" msgstr "Старше →" +#: web/src/admin/device-link.ts #: web/src/admin/pages/components/hero.ts #: web/src/admin/pages/server.ts msgid "On" @@ -4541,6 +4743,14 @@ msgstr "На GitHub" msgid "On one of the networks %s reaches." msgstr "В одной из сетей, доступных для %s." +#: web/src/admin/events/model.ts +msgid "On two devices at once" +msgstr "На двух устройствах сразу" + +#: web/src/admin/device-link.ts +msgid "On, except %s (home)" +msgstr "Вкл., кроме %s (дом)" + #: web/src/admin/pages/server.ts msgid "One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page." msgstr "Ещё один сервер: другой порт или маскировка для сетей, где первый не проходит, или свои правила доступа к домашней сети. Людей переносят между серверами на их странице." @@ -4570,10 +4780,18 @@ msgstr "Доступны только устройства людей с дос msgid "Only home devices reach people's devices." msgstr "Связаться с устройствами людей могут только домашние устройства." +#: web/src/shared/name-guard.ts +msgid "Only letters, digits, - _ ." +msgstr "Только буквы, цифры, - _ ." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "Only people with home access reach other devices." msgstr "Связаться с другими устройствами могут только люди с доступом к домашней сети." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc +msgid "Only the admin can change how a device connects." +msgstr "Менять настройки подключения устройства может только администратор." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc msgid "Only the admin can turn devices off." msgstr "Отключать устройства может только администратор." @@ -4731,6 +4949,10 @@ msgstr "Страница %s" msgid "Parameters copied" msgstr "Параметры скопированы" +#: web/src/admin/cores/awg.ts +msgid "Parameters copied. The header protection key is in each device’s file." +msgstr "Параметры скопированы. Ключ защиты заголовков есть в файле каждого устройства." + #: web/src/admin/pages/settings/portal.ts msgid "Paths on the router. Leave both empty to pick a certificate automatically." msgstr "Пути на роутере. Оставьте оба поля пустыми, чтобы сертификат выбирался автоматически." @@ -5213,6 +5435,10 @@ msgstr "Переустановка AmneziaWG" msgid "Reinstalling Dawnline" msgstr "Переустановка Dawnline" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "RejectAfterTime must be at most 180 seconds." +msgstr "RejectAfterTime: не больше 180 секунд." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc msgid "Release %s has no %s: it stays as it is" msgstr "В релизе %s нет %s: остаётся как есть" @@ -5534,8 +5760,13 @@ msgstr "Русский" msgid "Russian translation" msgstr "Русский перевод" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size." +msgstr "S2 не может равняться S1 + 56: начальный и ответный пакеты рукопожатия будут одного размера." + #: web/src/admin/access.ts #: web/src/admin/cores/awg.ts +#: web/src/admin/device-link.ts #: web/src/admin/device.ts #: web/src/admin/interfaces.ts #: web/src/admin/pages/person/dialogs.ts @@ -5558,6 +5789,7 @@ msgid "Save to flash" msgstr "Запись во флеш-память" #: web/src/admin/access.ts +#: web/src/admin/device-link.ts #: web/src/admin/pages/person/dialogs.ts #: web/src/admin/pages/server.ts #: web/src/admin/pages/settings/defaults.ts @@ -5590,6 +5822,10 @@ msgstr "Отсканируйте в AmneziaVPN или любом приложе msgid "Screen sharing" msgstr "Общий экран" +#: web/src/admin/netcheck.ts +msgid "Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops." +msgstr "В секундах. Пусто: как у сервера. Чем дольше, тем меньше расход батареи, но за некоторыми NAT связь тогда рвётся." + #: web/src/admin/pages/overview.ts msgid "Seen recently" msgstr "Недавно в сети" @@ -5772,6 +6008,10 @@ msgstr "Показать карту" msgid "Show progress" msgstr "Показать ход выполнения" +#: web/src/admin/device.ts +msgid "Show the new configuration" +msgstr "Показать новую конфигурацию" + #: web/src/admin/pages/settings/map.ts msgid "Show where people connect from on the Overview and person pages, at city level." msgstr "Показывать в «Обзоре» и на страницах людей, откуда они подключаются, - с точностью до города." @@ -6018,6 +6258,15 @@ msgstr "Это то же самое устройство" msgid "The %s build, %s." msgstr "Сборка %s, версия %s." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc +msgid "The AmneziaWG update is installed and starts after a reboot." +msgstr "Обновление AmneziaWG установлено и заработает после перезагрузки." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "The AmneziaWG update waits for a reboot" +msgstr "Обновление AmneziaWG ждёт перезагрузки" + #: web/src/admin/pages/server.ts msgid "The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address." msgstr "Провайдер делит один адрес между многими абонентами: устройства смогут подключиться, только если он выдаст вам публичный адрес или IPv6. Спросите у провайдера или используйте имя DDNS, которое указывает на IPv6-адрес." @@ -6074,10 +6323,26 @@ msgstr "По умолчанию lan: устройства получат име msgid "The device is disconnected immediately and its configuration stops working." msgstr "Устройство сразу отключится, а его конфигурация перестанет работать." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "The devices in AmneziaWG could not be checked" +msgstr "Не удалось проверить устройства в AmneziaWG" + #: web/src/admin/netcheck.ts msgid "The device’s address at home." msgstr "Адрес устройства в домашней сети." +#: web/src/admin/device.ts +msgid "The device’s local network stays reachable while connected, except %s: your home network." +msgstr "Локальная сеть устройства остаётся доступной при подключении, кроме %s: это ваша домашняя сеть." + +#: web/src/admin/device.ts +msgid "The device’s local network stays reachable while connected." +msgstr "Локальная сеть устройства остаётся доступной при подключении." + +#: web/src/admin/events/model.ts +msgid "The device’s network may be blocking the connection." +msgstr "Возможно, сеть устройства блокирует подключение." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "The firewall lets it through" msgstr "Межсетевой экран пропускает трафик" @@ -6086,6 +6351,10 @@ msgstr "Межсетевой экран пропускает трафик" msgid "The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware." msgstr "Прошивка сменилась (ядро %s → %s): сборки AmneziaWG, установленной для прежней, больше нет. Установите сборку для этой прошивки." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "The header protection key is not a key." +msgstr "Ключ защиты заголовков некорректен." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "The id may use lowercase letters, digits and underscores." msgstr "В идентификаторе можно использовать строчные латинские буквы, цифры и подчёркивания." @@ -6147,8 +6416,8 @@ msgid "The new version did not answer in LuCI or its agent did not start. Try ag msgstr "Новая версия не ответила в LuCI, или её агент не запустился. Попробуйте ещё раз в «Компонентах» или установите её через install.sh, чтобы увидеть причину." #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc -msgid "The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update" -msgstr "Старый модуль ядра AmneziaWG всё ещё загружен (возможно, его использует другой интерфейс AmneziaWG): перезагрузите роутер, чтобы завершить обновление" +msgid "The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot." +msgstr "Старый модуль ядра остаётся загруженным (возможно, его использует другой интерфейс AmneziaWG): обновление AmneziaWG установлено и заработает после перезагрузки." #: web/src/admin/pages/person/dialogs.ts msgid "The old link stops working right away." @@ -6210,6 +6479,10 @@ msgstr "Роутер один раз отправляет сервису каж msgid "The router stopped answering. The job may still finish: reopen Components in a minute." msgstr "Роутер перестал отвечать. Задача ещё может завершиться: откройте «Компоненты» снова через минуту." +#: web/src/admin/events/model.ts +msgid "The same configuration connects from two places in turn. Give the other device its own." +msgstr "Одна и та же конфигурация подключается по очереди из двух мест. Дайте второму устройству собственную." + #: web/src/admin/pages/overview.ts msgid "The server is turned off" msgstr "Сервер выключен" @@ -6234,6 +6507,10 @@ msgstr "Перевод установлен." msgid "The translation is removed." msgstr "Перевод удалён." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "The tunnel could not be read, so its devices could not be checked." +msgstr "Туннель не удалось прочитать, поэтому его устройства не проверены." + #: web/src/admin/pages/server.ts msgid "The tunnel needs %s. Install the build made for this firmware, then create the server." msgstr "Для туннеля нужно: %s. Установите сборку для этой прошивки, затем создайте сервер." @@ -6304,6 +6581,10 @@ msgstr "Это устройство создало ключи в браузер msgid "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." msgstr "На устройстве устаревшая конфигурация: после настройки изменились сети или DNS. Импортируйте её заново с помощью QR-кода, ключа или файла ниже." +#: web/src/admin/events/model.ts +msgid "This device is using an outdated configuration." +msgstr "На этом устройстве устаревшая конфигурация." + #: web/src/admin/pages/person/devices.ts msgid "This device made its own keys in the browser; its configuration only exists there." msgstr "Это устройство создало ключи в браузере, поэтому его конфигурация есть только там." @@ -6550,6 +6831,10 @@ msgstr "UDP-порт: от 1 до 65535." msgid "UDP port: %s" msgstr "UDP-порт: %s" +#: web/src/admin/events/model.ts +msgid "Unable to complete the handshake" +msgstr "Не удаётся завершить рукопожатие" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc msgid "Unexpected entry in backup: %s" msgstr "Неожиданная запись в резервной копии: %s" @@ -6678,6 +6963,10 @@ msgstr[0] "Максимум %s символ (сейчас %s)." msgstr[1] "Максимум %s символа (сейчас %s)." msgstr[2] "Максимум %s символов (сейчас %s)." +#: web/src/shared/name-guard.ts +msgid "Up to %s characters." +msgstr "Не больше %s символов." + #: web/src/admin/pages/components/index.ts msgid "Up to date" msgstr "Актуально" @@ -7269,6 +7558,10 @@ msgstr "другая программа на этом роутере" msgid "answers again" msgstr "снова отвечает" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc +msgid "apk did not install %s %s (installed: %s)" +msgstr "apk не установил %s %s (установлено: %s)" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc msgid "apk did not reinstall the version that is already installed" msgstr "apk не переустановил уже установленную версию" @@ -7297,6 +7590,14 @@ msgstr "отсутствуют" msgid "as soon as found" msgstr "сразу при обнаружении" +#: web/src/admin/device-link.ts +msgid "as the server" +msgstr "как у сервера" + +#: web/src/admin/device-link.ts +msgid "automatic" +msgstr "автоматически" + #: package/luci-app-dawnline/root/usr/libexec/dawnline/updater msgid "automatic update failed" msgstr ": автоматическое обновление не удалось" @@ -7517,10 +7818,6 @@ msgstr ": ошибка (%s)" msgid "from the portal" msgstr "через портал" -#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc -msgid "h1-h4 must be distinct" -msgstr "h1-h4 должны быть разными" - #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "has an invalid interface name \"%s\"" msgstr ": недопустимое имя интерфейса «%s»" @@ -7569,6 +7866,14 @@ msgstr ": установлена сборка %s · %s" msgid "interface %s" msgstr "интерфейс %s" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +msgid "interface %s has Dawnline's settings again" +msgstr ": у интерфейса %s снова настройки Dawnline" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +msgid "interface %s was changed outside Dawnline" +msgstr ": интерфейс %s изменён не через Dawnline" + #: web/src/admin/access.ts msgid "internet" msgstr "интернет" @@ -7577,6 +7882,10 @@ msgstr "интернет" msgid "is kept down" msgstr ": остановлен" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "is kept down: its disguise has values AmneziaWG cannot take" +msgstr ": остановлен, в маскировке есть значения, которые AmneziaWG не примет" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "is kept down: its disguise needs AmneziaWG %s (installed: %s)" msgstr ": остановлен, для маскировки нужен AmneziaWG %s (установлен %s)" @@ -7637,6 +7946,10 @@ msgstr "кбит/с" msgid "keep access" msgstr "сохранить доступ" +#: web/src/admin/events/model.ts +msgid "keep-alive" +msgstr "keep-alive" + #: web/src/admin/events/model.ts msgid "kept in memory only (lost on reboot)" msgstr "только в памяти (пропадают при перезагрузке)" @@ -7657,6 +7970,10 @@ msgstr ": модуль ядра не загружен" msgid "last 15 min" msgstr "за 15 мин" +#: web/src/admin/widgets/tiles.ts +msgid "last 2 min" +msgstr "за 2 мин" + #: web/src/admin/pages/person/header.ts msgid "last seen %s" msgstr "в сети %s" @@ -7976,7 +8293,17 @@ msgstr "сервер «%s»" msgid "services" msgstr "сервисы" +#: web/src/admin/cores/awg.ts +msgctxt "key" +msgid "set" +msgstr "задан" + +#: web/src/admin/device-link.ts +msgid "set when it was added" +msgstr "выбрано при добавлении" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc msgid "setting it up again" msgstr "настраиваем заново" diff --git a/package/luci-app-dawnline/po/templates/dawnline.pot b/package/luci-app-dawnline/po/templates/dawnline.pot index cacfc24..739ea05 100644 --- a/package/luci-app-dawnline/po/templates/dawnline.pot +++ b/package/luci-app-dawnline/po/templates/dawnline.pot @@ -95,6 +95,18 @@ msgstr "" msgid "%s - not repaired again (%d repairs didn't help)" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record." +msgid_plural "%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records." +msgstr[0] "" +msgstr[1] "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router." +msgid_plural "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router." +msgstr[0] "" +msgstr[1] "" + #: web/src/admin/cores/awg.ts msgid "%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you)." msgid_plural "%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)." @@ -148,6 +160,10 @@ msgstr "" msgid "%s and %s are not in one circle" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s and %s overlap: each packet type needs values of its own." +msgstr "" + #: web/src/admin/cores/awg.ts msgid "%s applied" msgstr "" @@ -420,6 +436,10 @@ msgstr "" msgid "%s has Internet only: only DNS and the portal on the router." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s has a tag that is not closed with >." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s has an invalid interface name \"%s\"." msgstr "" @@ -523,6 +543,10 @@ msgstr "" msgid "%s is kept down." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)." msgstr "" @@ -541,6 +565,10 @@ msgstr[1] "" msgid "%s is not a bridge, so Dawnline cannot join the LAN as a device." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s is not a common home subnet: the networks people connect from rarely use the same addresses." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc msgid "%s is not a package Dawnline manages" @@ -574,6 +602,10 @@ msgstr "" msgid "%s is on the internet" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc msgid "%s is part of %s; choose %s instead." msgstr "" @@ -629,6 +661,10 @@ msgstr[1] "" msgid "%s left" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s may not contain # or a line break." +msgstr "" + #: web/src/shared/format.ts msgid "%s min ago" msgstr "" @@ -648,7 +684,31 @@ msgid "%s moves to %s with OpenWrt %s." msgstr "" #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc -msgid "%s must be a number or range" +msgid "%s must be a number or a range like 10-100, up to 65535." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a number or a range like 100-200, up to 4294967295." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a number or a range like 5-15, from 1 to 65535." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a whole number from 0 to 65535." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be at least 12 with header protection." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be from %d to %d." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be on or off." msgstr "" #: package/luci-app-dawnline/root/usr/libexec/dawnline/updater @@ -805,6 +865,10 @@ msgstr[1] "" msgid "%s resumed" msgstr "" +#: web/src/admin/device-link.ts +msgid "%s s" +msgstr "" + #: web/src/admin/pages/settings/logs.ts msgid "%s since %s" msgstr "" @@ -882,6 +946,10 @@ msgid_plural "%s years" msgstr[0] "" msgstr[1] "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +msgid "%s · interface settings" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc msgid "%s · restored" msgstr "" @@ -898,6 +966,16 @@ msgstr "" msgid "%s → %s (this router)." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS." +msgid_plural "%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS." +msgstr[0] "" +msgstr[1] "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc msgid "%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)." msgstr "" @@ -935,6 +1013,10 @@ msgstr[1] "" msgid "%s: %s of 4" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s: <%s> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or ." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "%s: the device's own network handles it." msgstr "" @@ -1597,6 +1679,10 @@ msgstr "" msgid "As soon as found" msgstr "" +#: web/src/admin/device-link.ts +msgid "As the server: %s" +msgstr "" + #: web/src/admin/pages/settings/updates.ts msgid "At a set time" msgstr "" @@ -1646,6 +1732,10 @@ msgstr "" msgid "Automatic update: system packages" msgstr "" +#: web/src/admin/device-link.ts +msgid "Automatic: %s" +msgstr "" + #: web/src/admin/cores/awg.ts #: web/src/shared/format.ts msgid "B" @@ -1753,7 +1843,7 @@ msgid "Blocked" msgstr "" #: web/src/admin/events/model.ts -msgid "Blocked portal sign-ins (tunnels and services are in the service log)" +msgid "Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)" msgstr "" #: web/src/admin/access.ts @@ -1840,6 +1930,7 @@ msgid "Certificates (ACME)" msgstr "" #: web/src/admin/cores/awg.ts +#: web/src/admin/device-link.ts #: web/src/admin/pages/person/limits.ts #: web/src/admin/pages/person/pickers.ts #: web/src/admin/pages/server.ts @@ -1851,6 +1942,14 @@ msgstr "" msgid "Change limit" msgstr "" +#: web/src/admin/device-link.ts +msgid "Change the MTU" +msgstr "" + +#: web/src/admin/device-link.ts +msgid "Change the keep-alive" +msgstr "" + #: web/src/admin/pages/server.ts msgid "Change the tunnel network" msgstr "" @@ -1859,6 +1958,10 @@ msgstr "" msgid "Changed network" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +msgid "Changed: %s." +msgstr "" + #: web/src/admin/pages/server.ts msgid "Changing it marks devices “Update config” until they import again" msgstr "" @@ -1952,6 +2055,10 @@ msgstr "" msgid "Choose a device on at least one side." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "Choose a disguise on the Server page: it replaces the values set by hand." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc msgid "Choose a free port between 1 and 65535 (not 22, 53, 80 or 443)." @@ -2046,6 +2153,10 @@ msgstr "" msgid "Collecting… 1 point a minute" msgstr "" +#: web/src/admin/widgets/tiles.ts +msgid "Collecting… 1 point a second" +msgstr "" + #: web/src/admin/access.ts msgid "Colour" msgstr "" @@ -2101,6 +2212,10 @@ msgstr "" msgid "Connection" msgstr "" +#: web/src/admin/events/model.ts +msgid "Connection keeps dropping" +msgstr "" + #: package/luci-app-dawnline/root/usr/libexec/dawnline/agent #: web/src/admin/events/model.ts msgid "Connections" @@ -2175,6 +2290,10 @@ msgstr "" msgid "Couldn't read the devices at home." msgstr "" +#: web/src/admin/widgets/tiles.ts +msgid "Couldn't read the live speed: %s" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc msgid "Couldn't save /etc/config/dawnline: %s. Is the flash full?" msgstr "" @@ -2400,6 +2519,7 @@ msgstr "" #: web/src/admin/logs.ts #: web/src/admin/map.ts +#: web/src/shared/format.ts msgid "Device" msgstr "" @@ -2415,6 +2535,18 @@ msgstr "" msgid "Device %s connected from %s" msgstr "" +#: web/src/admin/events/render.ts +msgid "Device %s connects normally again" +msgstr "" + +#: web/src/admin/events/render.ts +msgid "Device %s has a connection problem" +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: MTU %d is not between 1280 and 1500." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s of %s: address %s is also used by device %s of %s." msgstr "" @@ -2435,6 +2567,10 @@ msgstr "" msgid "Device %s of %s: address (none) is not a plain IPv4 address." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s of %s: the preshared key is not a key." msgstr "" @@ -2447,6 +2583,10 @@ msgstr "" msgid "Device %s of %s: the public key is not a key." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: the public key is the server's own." +msgstr "" + #: web/src/admin/events/render.ts msgid "Device %s went offline" msgstr "" @@ -2715,6 +2855,10 @@ msgstr "" msgid "Empty = the portal’s address." msgstr "" +#: web/src/admin/netcheck.ts +msgid "Empty: automatic. Lower it when big pages hang on this device." +msgstr "" + #: web/src/admin/device.ts msgid "Enable" msgstr "" @@ -2752,7 +2896,7 @@ msgid "Enter a circle name: up to 32 characters, without < > \" or \\." msgstr "" #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc -msgid "Enter a device name (up to 48 characters)." +msgid "Enter a device name: up to %d letters, digits, spaces and - _ ." msgstr "" #: web/src/admin/netcheck.ts @@ -2975,6 +3119,14 @@ msgstr "" msgid "From" msgstr "" +#: web/src/admin/netcheck.ts +msgid "From 0 to 600 seconds." +msgstr "" + +#: web/src/admin/netcheck.ts +msgid "From 1280 to 1500." +msgstr "" + #: web/src/admin/access.ts msgid "From the rules on this server" msgstr "" @@ -3060,6 +3212,10 @@ msgstr "" msgid "Handshake and key timers vary within these ranges instead of WireGuard’s fixed values." msgstr "" +#: web/src/admin/events/model.ts +msgid "Handshake complete, but no data" +msgstr "" + #: web/src/admin/pages/diagnostics/index.ts #: web/src/admin/pages/overview.ts msgid "Health" @@ -3137,6 +3293,10 @@ msgstr "" msgid "Home network + Internet" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "Home network addresses" +msgstr "" + #: web/src/admin/pages/person/pickers.ts msgid "Home networks %s reaches. Networks added to the server later stay out." msgstr "" @@ -3193,6 +3353,10 @@ msgstr "" msgid "How the portal listens (80 and 443 stay free)" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "I1-I5 together must be at most 2000 characters, not %d." +msgstr "" + #: web/src/admin/pages/overview.ts msgid "Idle right now" msgstr "" @@ -3285,6 +3449,10 @@ msgstr "" msgid "Install it in Dawnline → Components." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page." +msgstr "" + #: web/src/admin/pkgs.ts msgid "Install the home-like link?" msgstr "" @@ -3468,6 +3636,10 @@ msgstr "" msgid "Invite card for %s" msgstr "" +#: web/src/admin/events/model.ts +msgid "It connects, but the connection breaks every few minutes: the network may be cutting it." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "It is in the tunnel network %s." msgstr "" @@ -3496,6 +3668,10 @@ msgstr "" msgid "Its configuration sends it to the router" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "Jmin must not be larger than Jmax." +msgstr "" + #: web/src/admin/cores/awg.ts msgid "Junk packets" msgstr "" @@ -3533,13 +3709,19 @@ msgid "Keep the previous version" msgstr "" #: web/src/admin/cores/awg.ts +#: web/src/admin/device-link.ts msgid "Keep-alive" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc msgid "Keep-alive must be 0-600 seconds." msgstr "" +#: web/src/admin/device-link.ts +msgid "Keep-alive of %s" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc msgid "Keeping AmneziaWG %s for rollback" msgstr "" @@ -3586,6 +3768,12 @@ msgstr "" msgid "Key generation failed." msgstr "" +#: web/src/admin/device-link.ts +#: web/src/admin/device.ts +#: web/src/admin/events/model.ts +msgid "LAN Bypass" +msgstr "" + #: web/src/admin/widgets/tiles.ts msgid "Last 30 days" msgstr "" @@ -3620,6 +3808,10 @@ msgstr "" msgid "Leave out https:// - just the name." msgstr "" +#: web/src/admin/netcheck.ts +msgid "Letters, digits, spaces and - _ . only." +msgstr "" + #: web/src/admin/pages/components/packages.ts msgid "Let’s Encrypt certificate for the portal" msgstr "" @@ -3785,6 +3977,7 @@ msgstr "" msgid "MTU is now automatic" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc msgid "MTU must be 1280-1500." msgstr "" @@ -3793,6 +3986,10 @@ msgstr "" msgid "MTU must be 1280–1500, or empty for automatic." msgstr "" +#: web/src/admin/device-link.ts +msgid "MTU of %s" +msgstr "" + #: web/src/admin/pages/settings/portal.ts msgid "Made by the router: browsers warn until a certificate covers the address." msgstr "" @@ -4428,6 +4625,7 @@ msgstr "" msgid "OK" msgstr "" +#: web/src/admin/device-link.ts #: web/src/admin/disguise.ts #: web/src/admin/interfaces.ts #: web/src/admin/pages/components/hero.ts @@ -4473,6 +4671,7 @@ msgstr "" msgid "Older →" msgstr "" +#: web/src/admin/device-link.ts #: web/src/admin/pages/components/hero.ts #: web/src/admin/pages/server.ts msgid "On" @@ -4486,6 +4685,14 @@ msgstr "" msgid "On one of the networks %s reaches." msgstr "" +#: web/src/admin/events/model.ts +msgid "On two devices at once" +msgstr "" + +#: web/src/admin/device-link.ts +msgid "On, except %s (home)" +msgstr "" + #: web/src/admin/pages/server.ts msgid "One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page." msgstr "" @@ -4515,10 +4722,18 @@ msgstr "" msgid "Only home devices reach people's devices." msgstr "" +#: web/src/shared/name-guard.ts +msgid "Only letters, digits, - _ ." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "Only people with home access reach other devices." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc +msgid "Only the admin can change how a device connects." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc msgid "Only the admin can turn devices off." msgstr "" @@ -4676,6 +4891,10 @@ msgstr "" msgid "Parameters copied" msgstr "" +#: web/src/admin/cores/awg.ts +msgid "Parameters copied. The header protection key is in each device’s file." +msgstr "" + #: web/src/admin/pages/settings/portal.ts msgid "Paths on the router. Leave both empty to pick a certificate automatically." msgstr "" @@ -5156,6 +5375,10 @@ msgstr "" msgid "Reinstalling Dawnline" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "RejectAfterTime must be at most 180 seconds." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc msgid "Release %s has no %s: it stays as it is" msgstr "" @@ -5475,8 +5698,13 @@ msgstr "" msgid "Russian translation" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size." +msgstr "" + #: web/src/admin/access.ts #: web/src/admin/cores/awg.ts +#: web/src/admin/device-link.ts #: web/src/admin/device.ts #: web/src/admin/interfaces.ts #: web/src/admin/pages/person/dialogs.ts @@ -5499,6 +5727,7 @@ msgid "Save to flash" msgstr "" #: web/src/admin/access.ts +#: web/src/admin/device-link.ts #: web/src/admin/pages/person/dialogs.ts #: web/src/admin/pages/server.ts #: web/src/admin/pages/settings/defaults.ts @@ -5531,6 +5760,10 @@ msgstr "" msgid "Screen sharing" msgstr "" +#: web/src/admin/netcheck.ts +msgid "Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops." +msgstr "" + #: web/src/admin/pages/overview.ts msgid "Seen recently" msgstr "" @@ -5713,6 +5946,10 @@ msgstr "" msgid "Show progress" msgstr "" +#: web/src/admin/device.ts +msgid "Show the new configuration" +msgstr "" + #: web/src/admin/pages/settings/map.ts msgid "Show where people connect from on the Overview and person pages, at city level." msgstr "" @@ -5958,6 +6195,15 @@ msgstr "" msgid "The %s build, %s." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc +msgid "The AmneziaWG update is installed and starts after a reboot." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "The AmneziaWG update waits for a reboot" +msgstr "" + #: web/src/admin/pages/server.ts msgid "The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address." msgstr "" @@ -6014,10 +6260,26 @@ msgstr "" msgid "The device is disconnected immediately and its configuration stops working." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "The devices in AmneziaWG could not be checked" +msgstr "" + #: web/src/admin/netcheck.ts msgid "The device’s address at home." msgstr "" +#: web/src/admin/device.ts +msgid "The device’s local network stays reachable while connected, except %s: your home network." +msgstr "" + +#: web/src/admin/device.ts +msgid "The device’s local network stays reachable while connected." +msgstr "" + +#: web/src/admin/events/model.ts +msgid "The device’s network may be blocking the connection." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "The firewall lets it through" msgstr "" @@ -6026,6 +6288,10 @@ msgstr "" msgid "The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "The header protection key is not a key." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "The id may use lowercase letters, digits and underscores." msgstr "" @@ -6087,7 +6353,7 @@ msgid "The new version did not answer in LuCI or its agent did not start. Try ag msgstr "" #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc -msgid "The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update" +msgid "The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot." msgstr "" #: web/src/admin/pages/person/dialogs.ts @@ -6150,6 +6416,10 @@ msgstr "" msgid "The router stopped answering. The job may still finish: reopen Components in a minute." msgstr "" +#: web/src/admin/events/model.ts +msgid "The same configuration connects from two places in turn. Give the other device its own." +msgstr "" + #: web/src/admin/pages/overview.ts msgid "The server is turned off" msgstr "" @@ -6174,6 +6444,10 @@ msgstr "" msgid "The translation is removed." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +msgid "The tunnel could not be read, so its devices could not be checked." +msgstr "" + #: web/src/admin/pages/server.ts msgid "The tunnel needs %s. Install the build made for this firmware, then create the server." msgstr "" @@ -6242,6 +6516,10 @@ msgstr "" msgid "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." msgstr "" +#: web/src/admin/events/model.ts +msgid "This device is using an outdated configuration." +msgstr "" + #: web/src/admin/pages/person/devices.ts msgid "This device made its own keys in the browser; its configuration only exists there." msgstr "" @@ -6487,6 +6765,10 @@ msgstr "" msgid "UDP port: %s" msgstr "" +#: web/src/admin/events/model.ts +msgid "Unable to complete the handshake" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc msgid "Unexpected entry in backup: %s" msgstr "" @@ -6614,6 +6896,10 @@ msgid_plural "Up to %s characters (%s now)." msgstr[0] "" msgstr[1] "" +#: web/src/shared/name-guard.ts +msgid "Up to %s characters." +msgstr "" + #: web/src/admin/pages/components/index.ts msgid "Up to date" msgstr "" @@ -7204,6 +7490,10 @@ msgstr "" msgid "answers again" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc +msgid "apk did not install %s %s (installed: %s)" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc msgid "apk did not reinstall the version that is already installed" msgstr "" @@ -7232,6 +7522,14 @@ msgstr "" msgid "as soon as found" msgstr "" +#: web/src/admin/device-link.ts +msgid "as the server" +msgstr "" + +#: web/src/admin/device-link.ts +msgid "automatic" +msgstr "" + #: package/luci-app-dawnline/root/usr/libexec/dawnline/updater msgid "automatic update failed" msgstr "" @@ -7451,10 +7749,6 @@ msgstr "" msgid "from the portal" msgstr "" -#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc -msgid "h1-h4 must be distinct" -msgstr "" - #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "has an invalid interface name \"%s\"" msgstr "" @@ -7503,6 +7797,14 @@ msgstr "" msgid "interface %s" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +msgid "interface %s has Dawnline's settings again" +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +msgid "interface %s was changed outside Dawnline" +msgstr "" + #: web/src/admin/access.ts msgid "internet" msgstr "" @@ -7511,6 +7813,10 @@ msgstr "" msgid "is kept down" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "is kept down: its disguise has values AmneziaWG cannot take" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "is kept down: its disguise needs AmneziaWG %s (installed: %s)" msgstr "" @@ -7571,6 +7877,10 @@ msgstr "" msgid "keep access" msgstr "" +#: web/src/admin/events/model.ts +msgid "keep-alive" +msgstr "" + #: web/src/admin/events/model.ts msgid "kept in memory only (lost on reboot)" msgstr "" @@ -7591,6 +7901,10 @@ msgstr "" msgid "last 15 min" msgstr "" +#: web/src/admin/widgets/tiles.ts +msgid "last 2 min" +msgstr "" + #: web/src/admin/pages/person/header.ts msgid "last seen %s" msgstr "" @@ -7909,7 +8223,17 @@ msgstr "" msgid "services" msgstr "" +#: web/src/admin/cores/awg.ts +msgctxt "key" +msgid "set" +msgstr "" + +#: web/src/admin/device-link.ts +msgid "set when it was added" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc msgid "setting it up again" msgstr "" diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/agent b/package/luci-app-dawnline/root/usr/libexec/dawnline/agent index 41a1765..710ba75 100755 --- a/package/luci-app-dawnline/root/usr/libexec/dawnline/agent +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/agent @@ -2,7 +2,11 @@ // Dawnline agent (procd instance). Every second its watcher reads the tunnels // and, the moment a device connects, its session expires or it roams, logs // it, folds the counters, locates the new address and moves the revision the -// admin UI polls (presence.json, see dawnline.live). Every minute it: +// admin UI polls (presence.json, see dawnline.live). The same read tells when +// a device's link fails in a named way (link.json, dawnline.link), what it does +// right now for the portal's set-up sheet (setup.json) and the live meter's +// last two minutes, written out while someone looks (meter.json, dawnline.meter). +// Every minute it: // * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly) // * saves the activity log to flash as often as Settings says (or never) // * keeps the "like a home device" path and the Home-only resolver up @@ -26,6 +30,9 @@ import * as net from 'dawnline.net'; import * as store from 'dawnline.store'; import * as upd from 'dawnline.updates'; import * as awg from 'dawnline.awg'; +import * as builds from 'dawnline.awg_builds'; +import * as link from 'dawnline.link'; +import * as meter from 'dawnline.meter'; import { L_ } from 'dawnline.i18n'; const TICK = 60 * 1000; @@ -55,6 +62,12 @@ let last_states = null; // Who was online, kept in tmpfs so an agent restart (update, reload) does not // swallow connects that happened in between. let presence = read_json(live.PRESENCE, {}); +// What a link showed comes from the watcher's memory, which starts empty: a +// state shows again once it held (link.HOLD), a set-up state with the next +// read that tells it. The meter's points start again too, written at the next look. +write_json(live.LINK, {}, 0o600); +write_json(live.SETUP, {}, 0o600); +meter.stop(); let last_online = presence.online ?? {}; let last_endpoint = presence.endpoint ?? {}; let rev = +(presence.rev ?? 0); @@ -123,6 +136,8 @@ function record_rate(m) { write_json(`${RUN_DIR}/rate_people.json`, people, 0o644); } let last_sync = 0; +// Per server, how the agent's last sync of its devices went (dawnline.awg.sync_peers). +let last_peers = {}; let conf_mtime = null; let cert_mtime = null; @@ -166,22 +181,104 @@ function named(e) { /* ---------- the watcher ---------- */ // Per device: its latest real handshake, kept when apply re-adds the peer -// (its counters and handshake restart from zero, or it is briefly missing). -let last_hs = {}; -// The model, read again only when the config file changes (the watcher runs every second). -let wm = null, wm_sig = null; +// (its counters and handshake restart from zero, or it is briefly missing), +// and the public key it was seen with: new keys (Reconnect, New keys) end +// the old session, whatever its handshake said. +let last_hs = {}, last_key = {}; +// The model, read again only when the config file changes (the watcher runs +// every second), the tunnels it reads (live.tunnel_ifnames: a regex per +// server, compiled each time it runs, so not every second), each device's +// online window (live.online_windows: its keep-alive's, from the model) and +// the largest keepalive its server's disguise makes (link.keepalive_sizes). +let wm = null, wm_sig = null, wm_ifnames = [], wm_windows = {}, wm_ka = {}; +// netifd deletes and adds a tunnel's link each time it sets it up (a new +// ifindex): the devices come back only with the sync its hotplug starts, and +// then with no handshake until each one makes a new one. For this long after +// the link changed, a device missing from it keeps what was known of it, +// rather than a burst of disconnects and connects for everyone online. +const RESTART_GRACE = 45; +// Per tunnel: the link last seen (null while it is down), and until when its grace lasts. +let links = {}, grace = {}; + +/** A file's mtime and inode ('-' when it is missing): what the cached model depends on. */ +function file_sig(path) { + let st = stat(path); + return st ? `${st.mtime}/${st.inode}` : '-'; +} function watch_model() { // uci commits replace the file: a new inode even within the same second. - let st = stat(CONFIG_FILE); - let sig = st ? `${st.mtime}/${st.inode}` : null; + // Which servers are kept down (core.BLOCKED, written by apply) is in the + // model too: their interface names may be someone else's tunnels. + let sig = `${file_sig(CONFIG_FILE)} ${file_sig(core.BLOCKED)}`; if (wm == null || sig != wm_sig) { wm = core.load(); wm_sig = sig; + wm_ifnames = live.tunnel_ifnames(wm); + wm_windows = live.online_windows(wm); + wm_ka = link.keepalive_sizes(wm); } return wm; } +// Per device: how its link behaves (dawnline.link: a few recent events and +// what is shown), and whether what is shown (link.json) or the set-up states +// (setup.json) changed since they were written. +let link_hist = {}, link_dirty = false, setup_dirty = false; + +/** + * A device's read into its link history: its set-up state follows at once + * (link.setup, a few compares unless something happened); it is classified + * again when something happened or link.CHECK_EVERY passed (its spans age). + * Returns the change in what is shown (link.settle: { from, to }), or null. + */ +function watch_link(id, dev, peer, now, on) { + let h = link_hist[id] ??= link.fresh(now); + let moved = false; + if (peer) + moved = link.observe(h, peer, now, wm_ka[id] ?? link.KEEPALIVE); + else + link.gone(h); + if (link.setup(h, now, on, moved)) + setup_dirty = true; + if (!moved && now - h.checked < link.CHECK_EVERY) + return null; + h.checked = now; + link.prune(h, now); + h.raw = link.classify(h, now, on); + let change = link.settle(h, h.raw, now, on); + if (change) + link_dirty = true; + return change; +} + +// The live meter: the last sample and the last two minutes of points +// ([ ts, JSON ], newest last, meter.keep), kept whether anyone looks or not so +// that a look gets them at once; whether meter.json is out for a look now. +let meter_prev = null, meter_ring = [], meter_out = false; + +/** + * A meter point a second from this read, kept; meter.json written while + * someone looks (meter.wanted): all the points the first second of a look, + * then with each new one. Once nobody does, the file goes; the points stay. + */ +function watch_meter(m, d, now) { + let s = meter.sample(m, d, now); + let p = meter_prev ? meter.point(meter_prev, s) : null; + meter_prev = s; + if (p) + meter.keep(meter_ring, p); + if (!meter.wanted(now)) { + if (meter_out) + meter.stop(); + meter_out = false; + return; + } + if (p || !meter_out) + meter.save(meter_ring); + meter_out = true; +} + /** Move the revisions (all, and these people's) and save who is online. */ function save_presence(people) { rev++; @@ -303,43 +400,89 @@ function place_of(ip) { /* * One look at the tunnels. Connects (a new handshake from a device that was - * away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW; - * a phone asleep looks the same as one switched off, so silence alone is not - * enough) and roaming (a new address) are acted on at - * once: the log, the counters and the map, then the revision the UI polls. - * Only from a complete read: a failed one says nothing about anyone. + * away), disconnects (its session expired: no handshake within its online + * window, live.online_window; a phone asleep looks the same as one switched + * off, so silence alone is not enough) and roaming (a new address) are acted + * on at once: the log, the counters and the map, then the revision the UI polls. + * Only Dawnline's own tunnels are read, each on its own (one process with a + * single server): a tunnel that could not be read says nothing about its + * devices, which stay as they were. */ function watch() { - let d = awg.dump(); - if (!d.ok) - return; let m = watch_model(); + let d = awg.dump(wm_ifnames); let now = time(); - let events = [], people = {}, ips = []; + for (let ifn, r in d.reads) { + if (r == 'error') + continue; + let ix = d.ifaces[ifn]?.ifindex; + if (ifn in links && links[ifn] != ix) + grace[ifn] = now + RESTART_GRACE; + links[ifn] = ix; + } + for (let ifn in keys(links)) + if (!(ifn in d.reads)) { + delete links[ifn]; + delete grace[ifn]; + } + let events = [], people = {}, ips = [], failing = []; for (let id, dev in m.devices) { + let ifn = m.servers[m.people[dev.person]?.server]?.ifname; + if (d.reads[ifn] == 'error') + continue; let peer = d.peers[dev.public_key]; let ep = ''; + // New keys: offline until they shake hands, and a new link history. The + // old one's set-up session (its no data, or its data flowing) and its + // answers would otherwise be taken for the new configuration's. + if (last_key[id] != dev.public_key) { + if (last_key[id] != null) { + last_hs[id] = 0; + let h = link_hist[id]; + if (h?.state != null) { + link_dirty = true; + people[dev.person] = true; + } + if (h?.setup != null) + setup_dirty = true; + delete link_hist[id]; + } + last_key[id] = dev.public_key; + } if (peer) { last_hs[id] = max(last_hs[id] ?? 0, peer.handshake); ep = live.endpoint_ip(peer.endpoint); } // Not in the tunnel (turned off, paused, out of time or data): offline now, and online - // again only with a new handshake, not the one remembered from before. - else + // again only with a new handshake, not the one remembered from before. Unless its + // tunnel was just set up again and the sync has not brought it back yet. + else if (!(grace[ifn] > now)) last_hs[id] = 0; - let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW; + let on = last_hs[id] > 0 && now - last_hs[id] < (wm_windows[id] ?? live.ONLINE_WINDOW); let was = last_online[id]; + // What is shown changed: the person's pages read it again (link.json), also + // when it cleared without an event (the device stopped trying, or was paused). + let change = watch_link(id, dev, peer, now, on); + if (change) { + people[dev.person] = true; + let le = link.event_for(change, dev, on); + if (le) + push(failing, le); + } + // One configuration on two devices: its address goes back and forth all + // the time, which is no roaming (nor a reason to move the revision). + let flapping = link_hist[id].raw == 'shared' || link_hist[id].state == 'shared'; if (on && !was) { push(events, { type: 'connect', person: dev.person, device: id, detail: ep }); push(ips, ep); } else if (!on && was) push(events, { type: 'disconnect', person: dev.person, device: id }); - else if (on && ep && last_endpoint[id] && ep != last_endpoint[id]) { + else if (on && ep && last_endpoint[id] && ep != last_endpoint[id] && !flapping) { push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${ep}` }); push(ips, ep); } - if (on != !!was || (ep && ep != last_endpoint[id])) + if (on != !!was || (ep && ep != last_endpoint[id] && !flapping)) people[dev.person] = true; last_online[id] = on; if (ep) @@ -350,7 +493,29 @@ function watch() { delete last_online[id]; delete last_endpoint[id]; delete last_hs[id]; + delete last_key[id]; } + for (let id in keys(link_hist)) + if (!m.devices[id]) { + if (link_hist[id].state != null) + link_dirty = true; + if (link_hist[id].setup != null) + setup_dirty = true; + delete link_hist[id]; + } + if (link_dirty) { + write_json(live.LINK, link.shown(link_hist), 0o600); + link_dirty = false; + } + // The portal's set-up sheet polls for it: no revision moves with it. + if (setup_dirty) { + write_json(live.SETUP, link.setups(link_hist), 0o600); + setup_dirty = false; + } + // Merged per device for an hour: a link that keeps failing and coming back is one line. + for (let e in failing) + live.add_event_merged(e, 3600); + watch_meter(m, d, now); if (!length(keys(people))) return; save_presence(keys(people)); @@ -515,8 +680,9 @@ function check_usage_reset(m) { * Push devices and access rules when people's states changed, the config * file was written (by anyone: rpcd, the portal, the CLI, a restore), the * access table is gone (a flushed ruleset: the firewall alone would let every - * device reach everything, so the sync unloads them until it is back), or - * every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself. + * device reach everything, so the sync unloads them until it is back), a + * running tunnel holds other devices than it should (check_peers), or every + * RESYNC_EVERY seconds anyway. apply.sync reads the model again itself. */ function sync_runtime(t) { // uci commits replace the file: a new inode even within the same second. @@ -525,13 +691,32 @@ function sync_runtime(t) { let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) || (conf_mtime != null && mt != conf_mtime); if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) { - apply.sync(t.m, usage); + last_peers = apply.sync(t.m, usage).peers ?? {}; last_sync = time(); } conf_mtime = mt; last_states = t.states; } +/* + * A running tunnel without all of its devices, or with ones it should not + * have (set up again before its hotplug sync ran, an `awg set` by hand): the + * sync runs on this tick, not up to RESYNC_EVERY later. By the same choice + * of devices the sync makes (and Health compares); only where the agent's + * last sync took: a server that refuses its devices has said so in the + * service log and keeps the slower pace. + */ +function check_peers(t) { + for (let id, srv in t.m.servers) { + let last = last_peers[id] ?? 'ok'; + if (t.dmp?.reads?.[srv.ifname] != 'read' || (last != 'ok' && last != 'down')) + continue; + let diff = awg.peer_diff(awg.tunnel_devices(t.m, id, t.states), t.dmp, srv.ifname); + if (diff.missing || diff.extra) + last_sync = 0; + } +} + /* * The router's network changed under us: re-derive everything. Only a change * seen on two ticks in a row (a bridge recreated or an interface restarting @@ -568,7 +753,8 @@ const STEPS = [ } }, { who: L_('Traffic'), run: (t) => { t.reset = check_usage_reset(t.m); - live.collect(t.m, usage, live.dump(t.m)); + t.dmp = live.dump(t.m); + live.collect(t.m, usage, t.dmp); } }, { who: L_('Speed'), quiet: true, run: (t) => record_rate(t.m) }, { who: L_('People'), run: (t) => { @@ -577,8 +763,10 @@ const STEPS = [ check_expiry(t.m, t.events); } }, { who: L_('Access rules'), run: (t) => { - if (t.states) - sync_runtime(t); + if (!t.states) + return; + check_peers(t); + sync_runtime(t); } }, // Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons. { who: L_('Activity'), run: (t) => { @@ -624,7 +812,7 @@ function tick() { } else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated) usage = live.load_usage(); - let t = { m: null, pol: null, reset: false, events: [] }; + let t = { m: null, pol: null, reset: false, events: [], dmp: null }; for (let i, s in STEPS) if (i == 0 || t.m) step(i, s, () => s.run(t)); @@ -652,6 +840,8 @@ function shutdown() { live.persist_events(); geo.flush(); slog_trim(true); + // The live meter's file goes with it: a stopped agent's points are no speed now. + meter.stop(); // A clean stop: the next start is not a crash. unlink(watchdog.BEAT); } @@ -686,6 +876,9 @@ else if (live.uptime() < 600) slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline'); else slog('dawnline', 'info', sprintf(L_('started · version %s'), VERSION), null, 'Dawnline'); +// A module Dawnline did not install has no record of its kernel: without one +// Health cannot tell a firmware upgrade from a missing module. +builds.adopt(); uloop.init(); diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css index 7190c1b..a4234fa 100644 --- a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css @@ -1 +1 @@ -@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.knob:active{transform:scale(.8)}.knob .i{width:16px;height:16px}.knob.back .i{transform:rotate(180deg)}.knob[aria-expanded=true]{background:color-mix(in srgb,var(--knob),var(--text) 10%)}.btn{height:48px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:0 20px;font-size:16px;font-weight:500;letter-spacing:-.015em;user-select:none;-webkit-user-select:none;transition:transform .2s var(--ease-out),background-color .2s var(--ease-out),color .2s var(--ease-out)}.btn:active{transform:scale(.95)}.btn.block{width:100%}.btn.sm{height:40px;font-size:15px;padding:0 16px}.btn.accent{background:var(--accent);color:var(--accent-ink);font-weight:600}.btn.accent:hover{background:color-mix(in srgb,var(--accent) 82%,transparent)}.btn.tint{background:var(--accent-soft);color:var(--accent);font-weight:600}.btn.tint:hover{background:color-mix(in srgb,var(--accent) 20%,transparent)}.btn.tint:active{background:color-mix(in srgb,var(--accent) 24%,transparent)}.btn.soft{background:var(--knob);color:var(--text)}.btn.soft:hover{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.btn.red{background:var(--bad);color:#fff;font-weight:600}.busy{position:relative}.orb{position:absolute;inset:0;margin:auto;width:28px;height:28px;overflow:hidden;contain:strict;pointer-events:none}.orb i{position:absolute;left:50%;top:50%;width:7px;height:7px;margin:-3.5px 0 0 -3.5px;border-radius:50%;background:currentColor;animation:orb-converge 1.8s linear infinite both}.orb i:nth-child(2){animation:orb-breathe 1.8s ease-in-out infinite both}@keyframes orb-converge{0%{transform:translateY(-5px) scale(1);filter:blur(0);animation-timing-function:linear}10%{transform:translateY(-5px) scale(1);filter:blur(0);animation-timing-function:cubic-bezier(.55,0,1,.45)}22%{transform:translate(2.15px,-1.25px) scale(.72);filter:blur(.8px);animation-timing-function:cubic-bezier(.33,1,.68,1)}33%{transform:translate(4.3px,2.5px) scale(1);filter:blur(0);animation-timing-function:linear}43%{transform:translate(4.3px,2.5px) scale(1);filter:blur(0);animation-timing-function:cubic-bezier(.55,0,1,.45)}55%{transform:translateY(2.5px) scale(.72);filter:blur(.8px);animation-timing-function:cubic-bezier(.33,1,.68,1)}66%{transform:translate(-4.3px,2.5px) scale(1);filter:blur(0);animation-timing-function:linear}77%{transform:translate(-4.3px,2.5px) scale(1);filter:blur(0);animation-timing-function:cubic-bezier(.55,0,1,.45)}88%{transform:translate(-2.15px,-1.25px) scale(.72);filter:blur(.8px);animation-timing-function:cubic-bezier(.33,1,.68,1)}to{transform:translateY(-5px) scale(1);filter:blur(0)}}@keyframes orb-breathe{0%,to{opacity:.16;filter:blur(2.4px);transform:scale(1.2)}50%{opacity:.32;filter:blur(1.6px);transform:scale(.98)}}.field{height:48px;border-radius:var(--r-field);background:var(--field);display:flex;align-items:center;gap:12px;padding:0 4px 0 16px;overflow:hidden;transition:box-shadow .2s var(--ease-out)}.field:focus-within{box-shadow:inset 0 0 0 1.5px color-mix(in srgb,var(--text) 16%,transparent)}.field input{flex:1;min-width:0;border:0;outline:0;background:transparent;padding:0;font:500 16px/24px var(--font);color:var(--text);letter-spacing:-.012em}.field input::placeholder{color:var(--text-3)}.go{width:48px;height:40px;border-radius:12px;background:var(--knob);color:var(--text-3);display:grid;place-items:center;flex:none;transition:background-color .2s var(--ease-out),color .2s var(--ease-out),transform .2s var(--ease-out)}.go .i{width:20px;height:20px}.go.ready{background:var(--accent);color:var(--accent-ink)}.go.ready:active{transform:scale(.9)}.go:not(.ready){cursor:not-allowed}.seg{position:relative;display:flex;align-items:center;height:48px;padding:0 4px;border-radius:var(--r-field);background:var(--field)}.seg-pill{position:absolute;left:0;top:4px;height:40px;border-radius:12px;background:var(--seg);box-shadow:var(--seg-shadow);pointer-events:none}.seg-b{position:relative;z-index:1;height:40px;font-size:16px;font-weight:500;color:var(--text-3);white-space:nowrap;transition:color .2s var(--ease-out)}.seg-b.on{color:var(--text)}.seg-b:not(.on):hover{color:var(--text-2)}.appseg .seg-b{flex:0 0 56px;display:flex;align-items:center;justify-content:center;justify-content:safe center;gap:8px;padding:0 18px;overflow:hidden}.appseg .seg-b.on{flex:1 1 56px}.appseg .seg-b .i{width:20px;height:20px}.appseg .seg-l{max-width:0;opacity:0;margin-left:-8px;overflow:hidden;white-space:nowrap}.appseg .seg-b.on .seg-l{max-width:180px;opacity:1;margin-left:0}.appseg{container-type:inline-size}@container (max-width: 300px){.appseg .seg-b{flex-basis:44px;padding:0 12px}}.kinds{display:grid;grid-template-columns:repeat(var(--n, 4),minmax(0,1fr));gap:8px;position:relative;container-type:inline-size}.kind{position:relative;z-index:1;display:flex;flex-direction:column;align-items:center;gap:8px;min-width:0;color:var(--text-3);font-size:12px;line-height:16px;font-weight:500;transition:color .2s var(--ease-out)}.kind-tile{width:100%;height:56px;border-radius:14px;background:var(--field);display:grid;place-items:center;transition:background-color .2s var(--ease-out),transform .2s var(--ease-out),box-shadow .22s var(--ease-out)}.kind.on .kind-tile{box-shadow:inset 0 0 0 1.5px var(--accent)}.kind-lbl{white-space:nowrap}.kind:hover .kind-tile,.kind:focus-visible .kind-tile{background:var(--knob)}.kind:active .kind-tile{transform:scale(.94)}.kind:focus-visible{outline:none}.kind:focus-visible .kind-lbl,.kind.on{color:var(--text)}.kind .gi{width:26px;height:26px;filter:grayscale(1);opacity:.55;transition:filter .26s var(--ease-out),opacity .26s var(--ease-out)}.kind.on .gi{filter:none;opacity:1}@container (max-width: 330px){.kind-tile{height:50px}.kind{font-size:11.5px}}.or{display:flex;align-items:center;gap:12px;margin:22px 0;color:var(--text-3);font-size:12px;font-weight:500;letter-spacing:.06em}.or:before,.or:after{content:"";flex:1;height:1px;background:var(--line)}.badge{width:100%;text-align:left;display:flex;align-items:center;gap:12px;height:60px;padding:0 14px 0 12px;border-radius:18px;background:var(--field);transition:background-color .2s,transform .2s var(--ease-out)}.badge:hover{background:var(--knob)}.badge:active{transform:scale(.98)}.badge .b-ic{width:36px;height:36px;border-radius:10px;background:var(--text);color:var(--raised);display:grid;place-items:center;flex:none}.badge .b-ic .i{width:20px;height:20px}.badge .b-t{flex:1;min-width:0;display:flex;flex-direction:column}.badge .b-top{font-size:12px;line-height:16px;color:var(--text-2)}.badge .b-main{font-size:15px;line-height:20px;font-weight:500}.badge>.i{color:var(--text-3);width:16px;height:16px}.badge.primary .b-ic{background:var(--accent-soft);color:var(--accent)}.badges2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.badges2 .badge{padding:0 10px;gap:10px}.badges2 .badge>.i{display:none}.badges2 .b-ic{width:32px;height:32px}.hint{margin:0;font-size:13px;line-height:18px;color:var(--text-2)}.hint a,.hint button{color:var(--accent);font-weight:500}.howto{margin:0;padding:0;list-style:none;display:flex;flex-wrap:wrap;align-items:center;gap:6px;font-size:13px;color:var(--text-2)}.howto li{display:inline-flex;align-items:center;gap:6px}.howto li+li:before{content:"\203a";color:var(--text-3)}.howto b{color:var(--text);font-weight:500}.linkrow{display:flex;align-items:center;gap:8px;height:44px;padding:0 4px 0 14px;border-radius:14px;background:color-mix(in srgb,var(--knob) 72%,var(--field))}.view>.linkrow{background:var(--field)}.linkrow .mono{flex:1;min-width:0;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;user-select:all}.linkrow .knob{width:36px;height:36px;border-radius:10px;background:transparent}.linkrow .knob:hover{background:var(--knob)}.qrbox{position:relative;width:148px;height:148px;flex:none;border-radius:18px;overflow:hidden;background:var(--qr-bg)}.qrbox.light{box-shadow:inset 0 0 0 1px var(--line)}.qrbox.big{width:208px;height:208px;border-radius:24px;align-self:center}.qrbox.big+.linkrow{margin-top:16px}.qrbox.dense{width:100%;max-width:none;height:auto;aspect-ratio:1;align-self:stretch;border-radius:22px}.qrbox svg{display:block;width:100%;height:100%}.qrbox>svg.old{position:absolute;inset:0}.coderow{display:flex;gap:14px;align-items:flex-start}.coderow.stacked{flex-direction:column;align-items:stretch}.coderow .side{position:relative;display:flex;flex-direction:column;gap:8px;min-width:0;font-size:14px;line-height:20px;color:var(--text-2)}.coderow .side b{color:var(--text);font-weight:500}.side .words{display:flex;flex-direction:column;gap:8px}.side .words.old{position:absolute;left:0;right:0;top:0;pointer-events:none}.side .arr{color:var(--text-2);font-weight:400;margin:0 6px}@media(max-width:380px){.coderow{flex-direction:column}}@media(prefers-reduced-motion:reduce){.orb i{animation:none;opacity:.3;filter:blur(1.4px)}.orb i:first-child{opacity:1;filter:none}}.mt{position:relative}.mt-ib{display:inline-block;white-space:nowrap}.mt-new{white-space:nowrap}.mt-old{position:absolute;white-space:nowrap;pointer-events:none}.mt-new.w,.mt-old.w{white-space:inherit}.mt-new i,.mt-old i{font-style:normal;display:inline-block;white-space:pre}.bars{--gap: 3px;position:relative;display:flex;flex:none;margin-inline:calc(var(--gap) / -2)}.bars-week{--gap: 4px;transition:margin var(--fit)}.bars .col{display:flex;flex-direction:column;padding-inline:calc(var(--gap) / 2)}.bars-month .col{flex:1;min-width:0}.bars .half{display:flex;flex-direction:column}.bars .half.top{justify-content:flex-end;margin-bottom:3px}.bars i{display:block;border-radius:2.5px;transition:background-color .12s}.bars-week i{width:6px;border-radius:3px;transition:background-color .15s,width var(--fit),border-radius var(--fit)}.bars-week .col{transition:padding var(--fit)}.bars-week .axis{transition:left var(--fit),right var(--fit)}.bars .dn{background:color-mix(in srgb,var(--text) 24%,transparent)}.bars .up{background:color-mix(in srgb,var(--text) 11%,transparent)}.bars .today .dn{background:var(--accent)}.bars .today .up{background:color-mix(in srgb,var(--accent) 45%,transparent)}.bars .col:not(.future):hover .dn{background:var(--text-2)}.bars .col:not(.future):hover .up{background:color-mix(in srgb,var(--text-2) 50%,transparent)}.bars .today:hover .dn{background:color-mix(in srgb,var(--accent) 75%,var(--text))}.bars .future i{height:3px;background:color-mix(in srgb,var(--bar) 45%,transparent)}.bars .axis{position:absolute;left:calc(var(--gap) / 2);right:calc(var(--gap) / 2);height:1px;background:var(--line);pointer-events:none}.ud{display:inline-flex;flex-wrap:wrap;align-items:center;column-gap:10px;transition:column-gap var(--fit)}.ud>span{display:inline-flex;align-items:center;gap:2px;white-space:nowrap}.ud .i{width:.8em;height:.8em;stroke-width:2.2;color:var(--text-2)}.ud-dn .i{transform:rotate(90deg)}.ud-up{color:var(--text-2)}.ud-up .i{transform:rotate(-90deg);color:var(--text-3)}@media(prefers-reduced-motion:reduce){.bars-week,.bars-week .col,.bars-week .axis,.ud{transition:none}.bars-week i{transition:background-color .15s}}.acc{display:flex;flex-direction:column}.acc-row{background:var(--raised);overflow:hidden;border-radius:0;padding:0 8px;transition:background-color .15s}.acc-row.rt{border-top-left-radius:var(--r-row);border-top-right-radius:var(--r-row)}.acc-row.rb{border-bottom-left-radius:var(--r-row);border-bottom-right-radius:var(--r-row)}.acc-row.open{margin-block:10px}.acc-row.open:first-child{margin-top:0}.acc-row.open:last-child{margin-bottom:0}.acc-row:not(.open):not(.still):hover{background:color-mix(in srgb,var(--raised),var(--knob) 40%)}.acc-head{width:100%;display:flex;align-items:center;gap:10px;height:52px;padding:0 6px 0 8px;text-align:left}.acc-row.still .acc-head{cursor:default;padding-right:10px}.acc-head .gi{width:22px;height:22px}.acc-title{flex:1;min-width:0;font-size:15px;font-weight:500;letter-spacing:-.02em;display:flex;align-items:center;gap:8px}.acc-title .t{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.acc-val{display:flex;align-items:center;gap:8px;color:var(--text-2);font-size:14px;white-space:nowrap;transition:opacity .2s var(--ease-out),filter .2s var(--ease-out),transform .26s var(--ease-out)}.acc-val>span{display:inline-flex;align-items:center;gap:8px}.acc-row.open .acc-val.hide-open{opacity:0;filter:blur(4px);transform:translate(8px);pointer-events:none}.acc-chev{width:16px;height:16px;color:var(--text-2);transform:rotate(90deg);transition:transform var(--spring-soft-dur, .47s) var(--spring-soft, ease)}.acc-row.open .acc-chev{transform:rotate(-90deg)}.acc-body{display:none;padding:0 8px 16px 40px}.acc-row.open .acc-body,.acc-row.closing .acc-body{display:flex;flex-direction:column;gap:12px}.acc .desc{margin:0;font-size:14px;line-height:20px;opacity:.6}.acc.inset .acc-row{background:var(--field)}.acc.inset .acc-row:not(.open):not(.still):hover{background:color-mix(in srgb,var(--field),var(--knob) 50%)}.acc.inset .acc-body{padding-left:8px}.acc.inset .seg{background:color-mix(in srgb,var(--knob) 65%,var(--field))}@media(prefers-reduced-motion:reduce){.acc-chev{transition:none}}.edge-fade{position:fixed;left:0;right:0;z-index:30;pointer-events:none}.edge-fade.top{top:0;height:calc(80px + env(safe-area-inset-top,0px));opacity:0;transition:opacity .2s;background:linear-gradient(var(--bg) 0%,color-mix(in srgb,var(--bg) 75%,transparent) 50%,transparent 100%);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);-webkit-mask-image:linear-gradient(#000 0%,rgba(0,0,0,.88) 44%,transparent 100%);mask-image:linear-gradient(#000 0%,rgba(0,0,0,.88) 44%,transparent 100%)}body.scrolled .edge-fade.top{opacity:1}.edge-fade.bot{bottom:0;height:calc(96px + env(safe-area-inset-bottom,0px));background:linear-gradient(to top in oklab,var(--bg) 0%,transparent 100%)}.crumbs{display:flex;align-items:center;gap:10px;height:32px;margin:0 0 32px}.cr-mark{width:32px;height:32px;display:grid;place-items:center;flex:none}.logo{width:24px;height:24px;flex:none;overflow:hidden}.logo .sun,.logo .bar{fill:var(--text)}.cr-path{flex:1;min-width:0;display:flex;align-items:center;gap:6px;font-size:15px;line-height:22px;letter-spacing:-.15px;color:var(--text-2)}.cr-path span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cr-path .cur{color:var(--text);font-weight:500}.cr-path .i{width:14px;height:14px}.cr-lang{display:inline-flex;align-items:center;gap:4px;height:32px;padding:0 8px 0 12px;border-radius:999px;background:var(--knob);color:var(--text);font-size:14px;font-weight:500;letter-spacing:-.01em;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.cr-lang:hover{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.cr-lang:active{transform:scale(.94)}.cr-lang[aria-expanded=true]{background:color-mix(in srgb,var(--knob),var(--text) 10%)}.cr-down{width:14px;height:14px;color:var(--text-2);transform:rotate(90deg);transition:transform .2s var(--ease-out)}.cr-lang[aria-expanded=true] .cr-down{transform:rotate(-90deg)}.page{max-width:1072px;margin:0 auto;padding-left:var(--gutter-l);padding-right:var(--gutter-r);padding-block:calc(40px + env(safe-area-inset-top,0px)) 112px}.cols{display:grid;gap:40px}.cols>.access{order:-1}@media(min-width:960px){.cols{grid-template-columns:minmax(0,1fr) 384px;gap:36px;align-items:start}.cols>.access{order:0;position:sticky;top:calc(84px + env(safe-area-inset-top,0px))}}.sec-head{display:flex;align-items:baseline;gap:8px;padding:0 4px 12px}.sec-head h2{margin:0;font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.025em}.sec-head .aside{color:var(--text-3);font-size:14px;font-weight:500}.sec-head .aside.warn-t{color:var(--warn)}.note-s{margin:12px 4px 0;color:var(--text-3);font-size:13px;line-height:18px}.notice{display:flex;align-items:center;gap:14px;padding:14px 18px 14px 14px;border-radius:24px;background:var(--raised);margin:0 0 22px}.notice .gi{width:36px;height:36px}.notice .t{display:flex;flex-direction:column;min-width:0}.notice b{font-weight:500;font-size:15px;line-height:22px;letter-spacing:-.02em}.notice span{color:var(--text-2);font-size:14px;line-height:20px}.notice.warn{background:color-mix(in srgb,var(--warn) 10%,var(--raised));box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--warn) 22%,transparent)}.notice.bad{background:color-mix(in srgb,var(--bad) 10%,var(--raised));box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--bad) 22%,transparent)}.page.single{min-height:100vh;min-height:100dvh;display:flex;flex-direction:column;align-items:center;justify-content:center;padding-block:calc(24px + env(safe-area-inset-top,0px)) calc(24px + env(safe-area-inset-bottom,0px))}.page.single .crumbs{position:relative;left:12px;max-width:calc(100% - 84px);margin:0 0 16px}.page.single .cr-mark{position:absolute;right:calc(100% + 10px);top:0}.page.single .page-body{width:100%;max-width:400px}.page.single .gone{margin:0}.gone{max-width:400px;margin:12vh auto 0;padding:32px 24px 28px;border-radius:var(--r-sheet);background:var(--raised);text-align:center;display:flex;flex-direction:column;align-items:center}.gone .gi{width:56px;height:56px;margin-bottom:16px}.gone h1{margin:0;font-size:22px;line-height:28px;font-weight:500;letter-spacing:-.03em}.gone p{margin:6px 0 0;color:var(--text-2);text-wrap:balance}.dgrid{display:grid;gap:10px;grid-template-columns:minmax(0,1fr)}@media(min-width:560px){.dgrid{grid-template-columns:repeat(2,minmax(0,1fr))}}.dev{background:var(--raised);border-radius:var(--r-card);padding:8px;display:flex;flex-direction:column;gap:8px;min-width:0;container:card / inline-size;--fit: var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease)}.dev.is-here{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 32%,transparent)}.dev.off{opacity:.5}.dev-top{display:flex;align-items:center;gap:12px;padding:8px 6px 6px 10px}.dev-top .gi{width:32px;height:32px}.dev-id{flex:1;min-width:0;display:flex;flex-direction:column}.dev-name{font-size:16px;line-height:22px;font-weight:500;letter-spacing:-.02em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dev-stat{font-size:13px;line-height:18px;color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dev-stat.ok-t{color:var(--ok)}.dev-stat.warn-t{color:var(--warn)}.dev-stat.here-t{color:var(--accent)}.dev-use{margin-top:auto;background:var(--field);border-radius:var(--r-row);padding:12px 14px 12px 16px;display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:66px}.use-txt{display:flex;flex-direction:column;flex:1;min-width:0}.use-lbl{font-size:13px;line-height:18px;color:var(--text-2);white-space:nowrap}.use-val{font-size:17px;line-height:24px;font-weight:500;letter-spacing:-.02em;transition:font-size var(--fit),line-height var(--fit)}.dev .setup-btn{margin-top:auto}@container card (max-width: 313px){.use-val{font-size:15px;line-height:22px}.bars-week{--gap: 3px}.bars-week i{width:4px;border-radius:2px}}@container card (max-width: 253px){.use-val{font-size:14px;line-height:22px}.use-val .ud{column-gap:8px}}.dev.add{align-items:center;justify-content:center;min-height:144px;gap:10px;color:var(--text-2);font-weight:500;transition:background-color .2s var(--ease-out),transform .2s var(--ease-out)}.dev.add:hover{background:color-mix(in srgb,var(--raised),var(--knob) 45%)}.dev.add:active{transform:scale(.98)}.dev.add .gi{width:36px;height:36px}.dev.first{grid-column:1 / -1;align-items:center;text-align:center;padding:28px 24px 24px;gap:6px}.dev.first .gi{width:44px;height:44px;margin-bottom:8px}.dev.first b{font-size:18px;line-height:24px;font-weight:500;letter-spacing:-.02em}.dev.first p{margin:0 0 14px;color:var(--text-2);font-size:14px;line-height:20px;max-width:34ch;text-wrap:balance}.dev.first .btn{max-width:320px}.dgrid.snap .dev *{transition:none}@media(prefers-reduced-motion:reduce){.use-val{transition:none}}.reach2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.reach-tile{position:relative;display:flex;flex-direction:column;gap:1px;padding:12px 12px 12px 14px;border-radius:16px;background:var(--field);min-width:0}.reach-tile .rt-ic{width:28px;height:28px;margin-bottom:10px}.reach-tile b{font-size:14px;line-height:20px;font-weight:500;letter-spacing:-.015em}.reach-tile .rt-sub{font-size:12px;line-height:16px;color:var(--text-2)}.reach-tile .rt-mark{position:absolute;top:12px;right:12px;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;background:var(--ok-soft);color:var(--ok)}.reach-tile .rt-mark .i{width:12px;height:12px;stroke-width:2.4}.reach-tile.off b{color:var(--text-2)}.reach-tile.off .rt-sub{color:var(--text-3)}.reach-tile.off .rt-ic{opacity:.45}.reach-tile.off .rt-mark{background:var(--knob);color:var(--text-3)}.lbl-s{font-size:12px;font-weight:500;color:var(--text-2)}.names{display:flex;flex-wrap:wrap;gap:6px}.namechip{display:inline-flex;align-items:center;gap:8px;height:32px;padding:0 10px 0 12px;border-radius:10px;background:var(--field);font-family:var(--mono);font-size:13px;letter-spacing:0;transition:background-color .15s,transform .15s var(--ease-out)}.namechip:hover{background:var(--knob)}.namechip:active{transform:scale(.96)}.namechip .faint{color:var(--text-3)}.namechip .i{width:14px;height:14px;color:var(--text-2)}.ring{width:16px;height:16px;transform:rotate(-90deg)}.ring .trk{stroke:var(--bar)}.ring .arc{stroke:var(--accent)}.ring .arc.warn{stroke:var(--warn)}.ring .arc.bad{stroke:var(--bad)}.month{display:flex;flex-direction:column;gap:8px}.month-axis{position:relative;display:flex;justify-content:space-between;font-size:11px;color:var(--text-3);font-weight:500}.month-axis .td{position:absolute;transform:translate(-50%);color:var(--accent)}.month-axis .hide{visibility:hidden}.month-read{display:flex;justify-content:space-between;align-items:baseline;margin-top:10px;font-size:13px;color:var(--text-2)}.month-read>*{white-space:nowrap}.month-read .ud{color:var(--text);font-weight:500;font-size:15px;letter-spacing:-.02em}.meter{height:6px;border-radius:3px;background:var(--bar);overflow:hidden}.meter>i{display:block;height:100%;border-radius:3px;background:var(--accent)}.meter>i.warn{background:var(--warn)}.meter>i.bad{background:var(--bad)}.until{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 16px;border-radius:16px;background:var(--field)}.until-num{display:flex;flex-direction:column;min-width:0}.until-num b{font-size:36px;line-height:40px;font-weight:600;letter-spacing:-.045em}.until-num span{font-size:13px;line-height:18px;color:var(--text-2)}.until-num .until-sub{margin-top:8px;font-size:12px;color:var(--text-3)}.until.soon .until-num b{color:var(--warn)}.cal{display:flex;flex-direction:column;gap:6px;flex:none}.cal-h,.cal-g{display:grid;grid-template-columns:repeat(7,10px);gap:5px}.cal-h span{font-size:9px;line-height:10px;font-weight:600;color:var(--text-3);text-align:center}.cal-g i{width:10px;height:10px;border-radius:3px;background:color-mix(in srgb,var(--text) 16%,transparent)}.cal-g i.past{background:color-mix(in srgb,var(--text) 5%,transparent)}.cal-g i.today{background:var(--accent)}.cal-g i.end{background:transparent;box-shadow:inset 0 0 0 1.5px var(--accent)}.cal-g i.after{background:transparent}.until.soon .cal-g i.today{background:var(--warn)}.until.soon .cal-g i.end{box-shadow:inset 0 0 0 1.5px var(--warn)}.acc-row.opened .cal-g i{animation:cal-in .36s var(--ease-out) backwards;animation-delay:calc(var(--i) * 7ms)}@keyframes cal-in{0%{opacity:0;transform:scale(.4)}}.hours{display:flex;flex-direction:column;gap:8px;padding:14px 16px;border-radius:16px;background:var(--field)}.hours-top{display:flex;justify-content:space-between;align-items:baseline;font-size:13px;color:var(--text-2)}.hours-top b{color:var(--text);font-weight:500;font-size:15px;letter-spacing:-.02em}.hours-bar{position:relative;height:8px;border-radius:4px;background:color-mix(in srgb,var(--text) 8%,transparent)}.hours-bar i{position:absolute;top:0;bottom:0;border-radius:4px;background:color-mix(in srgb,var(--ok) 70%,transparent)}.hours-now{position:absolute;top:-4px;width:2px;height:16px;margin-left:-1px;border-radius:1px;background:var(--text);box-shadow:0 0 0 2px var(--field)}.hours-now.out{background:var(--warn)}.hours-axis{display:flex;justify-content:space-between;font-size:10px;color:var(--text-3);font-weight:500}@media(prefers-reduced-motion:reduce){.acc-row.opened .cal-g i{animation:none}}.sheet-root{position:fixed;inset:0;z-index:50;display:none}.sheet-root.open{display:block}.scrim{position:absolute;inset:0;background:var(--scrim);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.sheet{position:absolute;left:var(--gutter-l);right:var(--gutter-r);bottom:calc(16px + env(safe-area-inset-bottom,0px));margin:0 auto;max-width:400px;max-height:calc(100% - 32px - env(safe-area-inset-top,0px) - env(safe-area-inset-bottom,0px));background:var(--raised);border-radius:var(--r-sheet);box-shadow:var(--sheet-shadow);overflow:hidden;display:flex;flex-direction:column}@media(min-width:760px){.sheet-root.open{display:flex;align-items:center;justify-content:center}.sheet{position:relative;left:auto;right:auto;bottom:auto;margin:0;width:calc(100% - var(--gutter-l) - var(--gutter-r))}}.sheet .x{position:absolute;z-index:3;right:22px;top:22px}.vp{position:relative;overflow:hidden;flex:none}.sheet-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain}.view{padding:0 24px 24px;display:flex;flex-direction:column}.vhead{display:flex;align-items:center;gap:12px;height:76px;padding-right:44px;flex:none;cursor:grab;touch-action:none}.vhead h2{flex:1;margin:0;font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.vhead.center h2{text-align:center}.vhead.with-acts{padding-right:126px}.vsub{margin:-16px 0 18px;color:var(--text-2);font-size:14px;line-height:20px}.vhead.center+.vsub{text-align:center;margin:-6px auto 24px;max-width:32ch;text-wrap:balance}.kinds-note{margin:14px 2px 16px}.view>.hint.bad-t{margin-top:8px}.secure-note{margin-top:12px;text-align:center}.sheet-acts{position:absolute;z-index:3;top:22px;right:58px}.hpill{position:relative;display:flex;gap:2px}.hp-b{display:grid;place-items:center;width:38px;height:32px;background:var(--knob);color:var(--text);transition:background-color .15s,transform .15s var(--ease-out)}.hp-b:first-of-type{border-radius:16px 6px 6px 16px}.hp-b:last-of-type{border-radius:6px 16px 16px 6px}.hp-b .i{width:16px;height:16px}.hp-b:hover{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.hp-b:active{transform:scale(.94)}.hp-b.done{color:var(--ok)}.hp-tip{position:absolute;z-index:4;left:0;top:calc(100% + 8px);height:26px;padding:0 10px;display:flex;align-items:center;border-radius:999px;background:var(--toast);color:var(--toast-fg);font:500 12px/1 var(--font);letter-spacing:-.1px;white-space:nowrap;box-shadow:0 0 0 1px var(--line-glass),var(--pop-shadow);opacity:0;pointer-events:none;overflow:hidden;transform-origin:50% 0}.hp-tip.on{opacity:1}.hp-tip .tt{position:relative;display:inline-flex;justify-content:center;white-space:nowrap}.hp-tip .tt-m{position:absolute;left:0;top:0;visibility:hidden;white-space:nowrap}.sheet .x,.sheet-acts{transition:transform .15s var(--ease-out),background-color .15s,opacity .24s var(--ease-out),filter .24s var(--ease-out),scale .24s var(--ease-out)}.sheet.arrived .x,.sheet.arrived .sheet-acts,.sheet.asks .x{opacity:0;filter:blur(3px);scale:.9;pointer-events:none}.center-col,.ask{display:flex;flex-direction:column}.center-col{align-items:center;text-align:center}.ask{align-items:flex-start;text-align:left;padding-top:24px}.center-col.secure{padding-top:4px}:is(.center-col,.ask) .gi.xl{width:64px;height:64px;margin:8px 0 16px}.ask .gi.xl{margin:0 0 18px}:is(.center-col,.ask) h3{margin:0;font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.5px}:is(.center-col,.ask) p{margin:6px 0 22px;color:var(--text-2);font-size:15px;line-height:21px}.center-col p{max-width:30ch;text-wrap:balance}.ask p{text-wrap:pretty}.center-col.secure p{margin-top:0}.btnrow{display:flex;gap:8px;width:100%}.btnrow .btn{flex:1}.btnrow2{display:grid;gap:8px}.btnrow2 .btn{width:100%}.setup{display:flex;flex-direction:column}.setup .notice{margin:0 0 16px}.steps-gap{height:22px}.step{display:flex;gap:12px}.step+.step{margin-top:20px}.step-n{width:24px;height:24px;border-radius:50%;background:var(--knob);font-size:13px;font-weight:600;display:grid;place-items:center;flex:none}.step-b{flex:1;min-width:0;display:flex;flex-direction:column;gap:10px}.step-t{font-size:16px;line-height:24px;font-weight:500;letter-spacing:-.02em}.step-box{display:flex;flex-direction:column;gap:10px}.way{display:flex;flex-direction:column;padding:12px 14px;border-radius:20px;background:var(--field);margin-bottom:18px}.way-row{display:flex;align-items:center;gap:10px}.way-end{width:34px;height:34px;border-radius:11px;background:var(--knob);display:grid;place-items:center;flex:none;color:var(--text-2);transition:background-color .4s var(--ease-out),color .4s var(--ease-out)}.way-end .i{width:17px;height:17px}.way-end.home{color:var(--accent);background:color-mix(in srgb,var(--accent) 14%,transparent)}.way-track{position:relative;flex:1;height:8px}.way-track:before,.way-glow,.way-fill{content:"";position:absolute;inset:0;-webkit-mask:radial-gradient(circle,#000 1.4px,transparent 1.9px) 0 50% / 9px 8px repeat-x;mask:radial-gradient(circle,#000 1.4px,transparent 1.9px) 0 50% / 9px 8px repeat-x}.way-track:before{background:var(--text-3);opacity:.8}.way-glow{overflow:hidden;transition:opacity .2s var(--ease-out)}.way-glow i{position:absolute;inset:0;background:linear-gradient(90deg,transparent 32%,var(--accent) 50%,transparent 68%);transform:translate(-70%);animation:way-run 2s cubic-bezier(.45,0,.55,1) infinite}@keyframes way-run{0%{transform:translate(-70%)}72%,to{transform:translate(70%)}}.way-fill{background:var(--ok);clip-path:inset(0 100% 0 0);transition:clip-path .7s var(--ease-out) 80ms}.way.done .way-fill{clip-path:inset(0)}.way.done .way-glow,.way.stopped .way-glow{opacity:0}.way.done .way-end{color:var(--ok);background:var(--ok-soft)}.way.done .way-end.home{transition-delay:.6s}.way.done .way-end.home .i{animation:way-pop .42s var(--spring-bouncy, ease) .6s backwards}@keyframes way-pop{0%{transform:scale(.6)}to{transform:none}}.way-text{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:30px;margin-top:10px;text-align:center}.way-text .t{display:flex;flex-direction:column;align-items:center;min-width:0}.way-text b{position:relative;display:inline-flex;justify-content:center;white-space:nowrap;font-weight:500;font-size:14px;line-height:20px;transition:color .3s var(--ease-out)}.way-text .ws{color:var(--text-2);font-size:13px;line-height:18px}.way.done .way-text b{color:var(--ok)}.filecard{display:flex;flex-direction:column;gap:10px;padding:12px;border-radius:18px;background:var(--field)}.fc-row{display:flex;align-items:center;gap:12px;min-width:0}.filecard-ic{width:38px;height:46px;border-radius:9px;background:var(--knob);font:600 10px/1 var(--mono);display:grid;place-items:center;color:var(--text-2);flex:none}.filecard .t{flex:1;min-width:0;display:flex;flex-direction:column}.filecard .t .mono{font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.filecard .t span:last-child{font-size:12px;color:var(--text-2);line-height:16px}.confbar{display:flex;gap:8px}.conf{margin:0;padding:12px 14px;border-radius:14px;background:var(--field);font:12px/18px var(--mono);max-height:16rem;overflow:auto;white-space:pre;color:var(--text-2)}.conf .k{color:var(--text)}.conf .sec{color:var(--accent)}.conf .mask{color:var(--text-3);letter-spacing:1px}.osm{white-space:normal}.osm-ic{display:inline-grid;width:1.05em;height:1.05em;margin-right:.25em;vertical-align:-.16em}.osm-ic>svg{grid-area:1 / 1;width:100%;height:100%}.osm-ic .eye{fill:var(--field)}.osm-p{display:inline-block;white-space:pre}.scanline{display:flex;flex-wrap:wrap;align-items:baseline;column-gap:.3em}.scanline .osm{white-space:nowrap}@media(max-width:440px){.scanline{flex-direction:column;align-items:flex-start}}.way-text b .mt-old{color:var(--text-2)}@media(prefers-reduced-motion:reduce){.way-glow{display:none}.way-fill{transition:none}.way.done .way-end.home .i{animation:none}}.menu{position:fixed;z-index:60;min-width:224px;padding:6px;border-radius:20px;background:var(--field);box-shadow:var(--pop-shadow),inset 0 0 0 1px var(--line)}.menu-hl{position:absolute;left:6px;right:6px;top:6px;height:40px;border-radius:14px;background:var(--knob);opacity:0;transition:opacity .15s var(--ease-out);pointer-events:none}.menu-hl.moving{transition:opacity .15s var(--ease-out),transform var(--spring-quick-dur, .3s) var(--spring-quick, ease-out),background-color .15s}.menu-hl.bad{background:var(--bad-soft)}.menu-hl.warn{background:color-mix(in srgb,var(--warn) 13%,transparent)}.mi{position:relative;z-index:1;display:flex;align-items:center;gap:12px;width:100%;height:40px;padding:0 12px;border-radius:14px;font-size:14px;font-weight:500;text-align:left}.mi .i{width:16px;height:16px;color:var(--text-2)}.mi .i.off{visibility:hidden}.mi.warn,.mi.warn .i{color:var(--warn)}.mi.bad,.mi.bad .i{color:var(--bad)}.menu-sep{height:1px;margin:6px 12px;background:var(--line)}.toasts{position:fixed;left:0;right:0;height:42px;bottom:calc(24px + env(safe-area-inset-bottom,0px));z-index:70;display:flex;justify-content:center;align-items:flex-end;pointer-events:none;padding-left:var(--gutter-l);padding-right:var(--gutter-r)}.toast{position:absolute;display:flex;align-items:center;gap:8px;height:42px;padding:0 18px 0 13px;border-radius:999px;background:var(--toast);color:var(--toast-fg);font-size:14px;font-weight:500;box-shadow:var(--pop-shadow);white-space:nowrap}.toast .i{width:18px;height:18px;color:var(--ok)}.toast.bad .i{color:var(--bad)} +@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable;overflow-anchor:none}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.knob:active{transform:scale(.8)}.knob .i{width:16px;height:16px}.knob.back .i{transform:rotate(180deg)}.knob[aria-expanded=true]{background:color-mix(in srgb,var(--knob),var(--text) 10%)}.btn{height:48px;border-radius:999px;display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:0 20px;font-size:16px;font-weight:500;letter-spacing:-.015em;user-select:none;-webkit-user-select:none;transition:transform .2s var(--ease-out),background-color .2s var(--ease-out),color .2s var(--ease-out)}.btn:active{transform:scale(.95)}.btn.block{width:100%}.btn.sm{height:40px;font-size:15px;padding:0 16px}.btn.accent{background:var(--accent);color:var(--accent-ink);font-weight:600}.btn.accent:hover{background:color-mix(in srgb,var(--accent) 82%,transparent)}.btn.tint{background:var(--accent-soft);color:var(--accent);font-weight:600}.btn.tint:hover{background:color-mix(in srgb,var(--accent) 20%,transparent)}.btn.tint:active{background:color-mix(in srgb,var(--accent) 24%,transparent)}.btn.soft{background:var(--knob);color:var(--text)}.btn.soft:hover{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.btn.red{background:var(--bad);color:#fff;font-weight:600}.busy{position:relative}.orb{position:absolute;inset:0;margin:auto;width:28px;height:28px;overflow:hidden;contain:strict;pointer-events:none}.orb i{position:absolute;left:50%;top:50%;width:7px;height:7px;margin:-3.5px 0 0 -3.5px;border-radius:50%;background:currentColor;animation:orb-converge 1.8s linear infinite both}.orb i:nth-child(2){animation:orb-breathe 1.8s ease-in-out infinite both}@keyframes orb-converge{0%{transform:translateY(-5px) scale(1);filter:blur(0);animation-timing-function:linear}10%{transform:translateY(-5px) scale(1);filter:blur(0);animation-timing-function:cubic-bezier(.55,0,1,.45)}22%{transform:translate(2.15px,-1.25px) scale(.72);filter:blur(.8px);animation-timing-function:cubic-bezier(.33,1,.68,1)}33%{transform:translate(4.3px,2.5px) scale(1);filter:blur(0);animation-timing-function:linear}43%{transform:translate(4.3px,2.5px) scale(1);filter:blur(0);animation-timing-function:cubic-bezier(.55,0,1,.45)}55%{transform:translateY(2.5px) scale(.72);filter:blur(.8px);animation-timing-function:cubic-bezier(.33,1,.68,1)}66%{transform:translate(-4.3px,2.5px) scale(1);filter:blur(0);animation-timing-function:linear}77%{transform:translate(-4.3px,2.5px) scale(1);filter:blur(0);animation-timing-function:cubic-bezier(.55,0,1,.45)}88%{transform:translate(-2.15px,-1.25px) scale(.72);filter:blur(.8px);animation-timing-function:cubic-bezier(.33,1,.68,1)}to{transform:translateY(-5px) scale(1);filter:blur(0)}}@keyframes orb-breathe{0%,to{opacity:.16;filter:blur(2.4px);transform:scale(1.2)}50%{opacity:.32;filter:blur(1.6px);transform:scale(.98)}}.field{height:48px;border-radius:var(--r-field);background:var(--field);display:flex;align-items:center;gap:12px;padding:0 4px 0 16px;overflow:hidden;transition:box-shadow var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease)}.field:focus-within{box-shadow:inset 0 0 0 1.5px color-mix(in srgb,var(--text) 16%,transparent)}.field input{flex:1;min-width:0;border:0;outline:0;background:transparent;padding:0;font:500 16px/24px var(--font);color:var(--text);letter-spacing:-.012em}.field input::placeholder{color:var(--text-3)}.go{width:48px;height:40px;border-radius:12px;background:var(--knob);color:var(--text-3);display:grid;place-items:center;flex:none;transition:background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),transform .2s var(--ease-out)}.go .i{width:20px;height:20px}.go.ready{background:var(--accent);color:var(--accent-ink)}.go.ready:active{transform:scale(.9)}.go:not(.ready){cursor:not-allowed}.field.own-caret{position:relative}.field.own-caret input{caret-color:transparent}.caret{position:absolute;left:0;top:50%;width:2px;height:20px;margin-top:-10px;border-radius:1px;background:var(--accent);pointer-events:none;opacity:0;transition:opacity .1s linear;will-change:transform}.caret.on{opacity:1}.caret.on.blink{animation:caret-blink 1.2s ease-in-out infinite}@keyframes caret-blink{0%,38%{opacity:1}50%,88%{opacity:0}to{opacity:1}}.caret-mirror{position:absolute;left:-9999px;top:0;visibility:hidden;white-space:pre}.field.own-sel input{position:relative;z-index:1}.field.own-sel input::selection{background:transparent;color:var(--text)}.caret-sel{position:absolute;left:0;top:50%;height:22px;margin-top:-11px;border-radius:4px;background:color-mix(in srgb,var(--accent) 26%,transparent);pointer-events:none;opacity:0;transition:opacity .14s linear}.caret-hd{position:absolute;z-index:2;left:0;top:50%;width:2px;height:22px;margin-top:-11px;border-radius:1px;background:var(--accent);pointer-events:none;opacity:0;transition:opacity .14s linear}.caret-hd:after{content:"";position:absolute;left:50%;width:9px;height:9px;margin-left:-4.5px;border-radius:50%;background:var(--accent)}.caret-hd.s:after{top:-7px}.caret-hd.e:after{bottom:-7px}.field.selecting .caret-sel,.field.selecting .caret-hd{opacity:1}.field.saving input{color:transparent}.field.saving .caret{opacity:0!important;animation:none!important}.shim-clip{position:absolute;z-index:2;overflow:hidden;pointer-events:none}.shim{--shim-high: var(--text);--shim-base: color-mix(in oklab, var(--text) 38%, var(--raised));position:absolute;top:0;white-space:pre;-webkit-background-clip:text;background-clip:text;color:transparent}.seg{position:relative;display:flex;align-items:center;height:48px;padding:0 4px;border-radius:var(--r-field);background:var(--field)}.seg-pill{position:absolute;left:0;top:4px;height:40px;border-radius:12px;background:var(--seg);box-shadow:var(--seg-shadow);pointer-events:none}.seg-b{position:relative;z-index:1;height:40px;font-size:16px;font-weight:500;color:var(--text-3);white-space:nowrap;transition:color .2s var(--ease-out)}.seg-b.on{color:var(--text)}.seg-b:not(.on):hover{color:var(--text-2)}.appseg .seg-b{flex:0 0 56px;display:flex;align-items:center;justify-content:center;justify-content:safe center;gap:8px;padding:0 18px;overflow:hidden}.appseg .seg-b.on{flex:1 1 56px}.appseg .seg-b .i{width:20px;height:20px}.appseg .seg-l{max-width:0;opacity:0;margin-left:-8px;overflow:hidden;white-space:nowrap}.appseg .seg-b.on .seg-l{max-width:180px;opacity:1;margin-left:0}.appseg{container-type:inline-size}@container (max-width: 300px){.appseg .seg-b{flex-basis:44px;padding:0 12px}}.kinds{display:grid;grid-template-columns:repeat(var(--n, 4),minmax(0,1fr));gap:8px;position:relative;container-type:inline-size}.kind{position:relative;z-index:1;display:flex;flex-direction:column;align-items:center;gap:8px;min-width:0;color:var(--text-3);font-size:12px;line-height:16px;font-weight:500;transition:color .2s var(--ease-out)}.kind-tile{width:100%;height:56px;border-radius:14px;background:var(--field);display:grid;place-items:center;transition:background-color .2s var(--ease-out),transform .2s var(--ease-out),box-shadow .22s var(--ease-out)}.kind.on .kind-tile{box-shadow:inset 0 0 0 1.5px var(--accent)}.kind-lbl{white-space:nowrap}.kind:hover .kind-tile,.kind:focus-visible .kind-tile{background:var(--knob)}.kind:active .kind-tile{transform:scale(.94)}.kind:focus-visible{outline:none}.kind:focus-visible .kind-lbl,.kind.on{color:var(--text)}.kind .gi{width:26px;height:26px;filter:grayscale(1);opacity:.55;transition:filter .26s var(--ease-out),opacity .26s var(--ease-out)}.kind.on .gi{filter:none;opacity:1}@container (max-width: 330px){.kind-tile{height:50px}.kind{font-size:11.5px}}.swrow{width:100%;display:flex;align-items:center;gap:12px;padding:12px 12px 12px 14px;border-radius:16px;background:var(--field);color:var(--text);text-align:left;user-select:none;-webkit-user-select:none;transition:background-color .2s}.swrow:hover{background:color-mix(in srgb,var(--field),var(--knob) 50%)}.kinds+.swrow{margin:16px 0 12px}.swrow .gi{width:28px;height:28px;flex:none;transition:filter var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),opacity var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease)}.swrow:not(.on) .gi{filter:grayscale(1);opacity:.55}.sw-t{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}.sw-t b{font-size:15px;line-height:22px;font-weight:500;letter-spacing:-.015em}.sw-sub{font-size:13px;line-height:18px;color:var(--text-2)}.sw{position:relative;flex:none;width:44px;height:26px;border-radius:999px;background:var(--knob);transition:background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease)}.sw:after{content:"";position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:10px;background:var(--text-2);transition:transform var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),width var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease)}.swrow.on .sw{background:var(--accent)}.swrow.on .sw:after{transform:translate(18px);background:var(--accent-ink)}.swrow:active .sw:after{width:27px}.swrow.on:active .sw:after{transform:translate(11px)}.or{display:flex;align-items:center;gap:12px;margin:22px 0;color:var(--text-3);font-size:12px;font-weight:500;letter-spacing:.06em}.or:before,.or:after{content:"";flex:1;height:1px;background:var(--line)}.badge{width:100%;text-align:left;display:flex;align-items:center;gap:12px;height:60px;padding:0 14px 0 12px;border-radius:18px;background:var(--field);transition:background-color .2s,transform .2s var(--ease-out)}.badge:hover{background:var(--knob)}.badge:active{transform:scale(.98)}.badge .b-ic{width:36px;height:36px;border-radius:10px;background:var(--text);color:var(--raised);display:grid;place-items:center;flex:none}.badge .b-ic .i{width:20px;height:20px}.badge .b-t{flex:1;min-width:0;display:flex;flex-direction:column}.badge .b-top{font-size:12px;line-height:16px;color:var(--text-2)}.badge .b-main{font-size:15px;line-height:20px;font-weight:500}.badge>.i{color:var(--text-3);width:16px;height:16px}.badge.primary .b-ic{background:var(--accent-soft);color:var(--accent)}.badges2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.badges2 .badge{padding:0 10px;gap:10px}.badges2 .badge>.i{display:none}.badges2 .b-ic{width:32px;height:32px}.hint{margin:0;font-size:13px;line-height:18px;color:var(--text-2)}.hint.bad-t{color:var(--bad)}.hint a,.hint button{color:var(--accent);font-weight:500}.howto{margin:0;padding:0;list-style:none;display:flex;flex-wrap:wrap;align-items:center;gap:6px;font-size:13px;color:var(--text-2)}.howto li{display:inline-flex;align-items:center;gap:6px}.howto li+li:before{content:"\203a";color:var(--text-3)}.howto b{color:var(--text);font-weight:500}.linkrow{display:flex;align-items:center;gap:8px;height:44px;padding:0 4px 0 14px;border-radius:14px;background:color-mix(in srgb,var(--knob) 72%,var(--field))}.view>.linkrow{background:var(--field)}.linkrow .mono{flex:1;min-width:0;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;user-select:all}.linkrow .knob{width:36px;height:36px;border-radius:10px;background:transparent}.linkrow .knob:hover{background:var(--knob)}.qrbox{position:relative;width:148px;height:148px;flex:none;border-radius:18px;overflow:hidden;background:var(--qr-bg)}.qrbox.light{box-shadow:inset 0 0 0 1px var(--line)}.qrbox.big{width:208px;height:208px;border-radius:24px;align-self:center}.qrbox.big+.linkrow{margin-top:16px}.qrbox.dense{width:100%;max-width:none;height:auto;aspect-ratio:1;align-self:stretch;border-radius:22px}.qrbox svg{display:block;width:100%;height:100%}.qrbox>svg.old{position:absolute;inset:0}.coderow{display:flex;gap:14px;align-items:flex-start}.coderow.stacked{flex-direction:column;align-items:stretch}.coderow .side{position:relative;display:flex;flex-direction:column;gap:8px;min-width:0;font-size:14px;line-height:20px;color:var(--text-2)}.coderow .side b{color:var(--text);font-weight:500}.side .words{display:flex;flex-direction:column;gap:8px}.side .words.old{position:absolute;left:0;right:0;top:0;pointer-events:none}.side .arr{color:var(--text-2);font-weight:400;margin:0 6px}@media(max-width:380px){.coderow{flex-direction:column}}@media(prefers-reduced-motion:reduce){.orb i{animation:none;opacity:.3;filter:blur(1.4px)}.orb i:first-child{opacity:1;filter:none}.caret.on.blink{animation:none}}.mt{position:relative}.mt-ib{display:inline-block;white-space:nowrap}.mt-new{white-space:nowrap}.mt-old{position:absolute;white-space:nowrap;pointer-events:none}.mt-new.w,.mt-old.w{white-space:inherit}.mt-new i,.mt-old i{font-style:normal;display:inline-block;white-space:pre}.bars{--gap: 3px;position:relative;display:flex;flex:none;margin-inline:calc(var(--gap) / -2)}.bars-week{--gap: 4px;transition:margin var(--fit)}.bars .col{display:flex;flex-direction:column;padding-inline:calc(var(--gap) / 2)}.bars-month .col{flex:1;min-width:0}.bars .half{display:flex;flex-direction:column}.bars .half.top{justify-content:flex-end;margin-bottom:3px}.bars i{display:block;border-radius:2.5px;transition:background-color .12s}.bars-week i{width:6px;border-radius:3px;transition:background-color .15s,width var(--fit),border-radius var(--fit)}.bars-week .col{transition:padding var(--fit)}.bars-week .axis{transition:left var(--fit),right var(--fit)}.bars .dn{background:color-mix(in srgb,var(--text) 24%,transparent)}.bars .up{background:color-mix(in srgb,var(--text) 11%,transparent)}.bars .today .dn{background:var(--accent)}.bars .today .up{background:color-mix(in srgb,var(--accent) 45%,transparent)}.bars .col:not(.future):hover .dn{background:var(--text-2)}.bars .col:not(.future):hover .up{background:color-mix(in srgb,var(--text-2) 50%,transparent)}.bars .today:hover .dn{background:color-mix(in srgb,var(--accent) 75%,var(--text))}.bars .future i{height:3px;background:color-mix(in srgb,var(--bar) 45%,transparent)}.bars .axis{position:absolute;left:calc(var(--gap) / 2);right:calc(var(--gap) / 2);height:1px;background:var(--line);pointer-events:none}.ud{display:inline-flex;flex-wrap:wrap;align-items:center;column-gap:10px;transition:column-gap var(--fit)}.ud>span{display:inline-flex;align-items:center;gap:2px;white-space:nowrap}.ud .i{width:.8em;height:.8em;stroke-width:2.2;color:var(--text-2)}.ud-dn .i{transform:rotate(90deg)}.ud-up{color:var(--text-2)}.ud-up .i{transform:rotate(-90deg);color:var(--text-3)}@media(prefers-reduced-motion:reduce){.bars-week,.bars-week .col,.bars-week .axis,.ud{transition:none}.bars-week i{transition:background-color .15s}}.acc{display:flex;flex-direction:column}.acc-row{background:var(--raised);overflow:hidden;border-radius:0;padding:0 8px;transition:background-color .15s}.acc-row.rt{border-top-left-radius:var(--r-row);border-top-right-radius:var(--r-row)}.acc-row.rb{border-bottom-left-radius:var(--r-row);border-bottom-right-radius:var(--r-row)}.acc-row.open{margin-block:10px}.acc-row.open:first-child{margin-top:0}.acc-row.open:last-child{margin-bottom:0}.acc-row:not(.open):not(.still):hover{background:color-mix(in srgb,var(--raised),var(--knob) 40%)}.acc-head{width:100%;display:flex;align-items:center;gap:10px;height:52px;padding:0 6px 0 8px;text-align:left}.acc-row.still .acc-head{cursor:default;padding-right:10px}.acc-head .gi{width:22px;height:22px}.acc-title{flex:1;min-width:0;font-size:15px;font-weight:500;letter-spacing:-.02em;display:flex;align-items:center;gap:8px}.acc-title .t{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.acc-val{display:flex;align-items:center;gap:8px;color:var(--text-2);font-size:14px;white-space:nowrap;transition:opacity .2s var(--ease-out),filter .2s var(--ease-out),transform .26s var(--ease-out)}.acc-val>span{display:inline-flex;align-items:center;gap:8px}.acc-row.open>.acc-head>.acc-val.hide-open{opacity:0;filter:blur(4px);transform:translate(8px);pointer-events:none}.acc-chev{width:16px;height:16px;color:var(--text-2);transform:rotate(90deg);transition:transform var(--spring-soft-dur, .47s) var(--spring-soft, ease)}.acc-row.open>.acc-head>.acc-chev{transform:rotate(-90deg)}.acc-body{display:none;padding:0 8px 16px 40px}.acc-row.open>.acc-body,.acc-row.closing>.acc-body{display:flex;flex-direction:column;gap:12px}.acc .desc{margin:0;font-size:14px;line-height:20px;opacity:.6}.acc.inset .acc-row{background:var(--field)}.acc.inset .acc-row:not(.open):not(.still):hover{background:color-mix(in srgb,var(--field),var(--knob) 50%)}.acc.inset .acc-body{padding-left:8px}.acc.inset .seg,.acc.inset .badge{background:color-mix(in srgb,var(--knob) 65%,var(--field))}.acc.inset .badge:hover{background:var(--knob)}.acc.inset .filecard,.acc.inset .acc.inset .acc-row{background:color-mix(in srgb,var(--knob) 65%,var(--field))}.acc.inset .acc.inset .acc-row:not(.open):not(.still):hover{background:var(--knob)}.acc.inset .filecard-ic,.acc.inset .acc.inset .btn.soft{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.acc.inset .acc.inset .btn.soft:hover{background:color-mix(in srgb,var(--knob),var(--text) 12%)}.acc.inset .acc.inset .conf{background:var(--knob)}@media(prefers-reduced-motion:reduce){.acc-chev{transition:none}}.edge-fade{position:fixed;left:0;right:0;z-index:30;pointer-events:none}.edge-fade.top{top:0;height:calc(80px + env(safe-area-inset-top,0px));opacity:0;transition:opacity .2s;background:linear-gradient(var(--bg) 0%,color-mix(in srgb,var(--bg) 75%,transparent) 50%,transparent 100%);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);-webkit-mask-image:linear-gradient(#000 0%,rgba(0,0,0,.88) 44%,transparent 100%);mask-image:linear-gradient(#000 0%,rgba(0,0,0,.88) 44%,transparent 100%)}body.scrolled .edge-fade.top{opacity:1}.edge-fade.bot{bottom:0;height:calc(96px + env(safe-area-inset-bottom,0px));background:linear-gradient(to top in oklab,var(--bg) 0%,transparent 100%)}.crumbs{display:flex;align-items:center;gap:10px;height:32px;margin:0 0 32px}.cr-mark{width:32px;height:32px;display:grid;place-items:center;flex:none}.logo{width:24px;height:24px;flex:none;overflow:hidden}.logo .sun,.logo .bar{fill:var(--text)}.cr-path{flex:1;min-width:0;display:flex;align-items:center;gap:6px;font-size:15px;line-height:22px;letter-spacing:-.15px;color:var(--text-2)}.cr-path span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cr-path .cur{color:var(--text);font-weight:500}.cr-path .i{width:14px;height:14px}.cr-lang{display:inline-flex;align-items:center;gap:4px;height:32px;padding:0 8px 0 12px;border-radius:999px;background:var(--knob);color:var(--text);font-size:14px;font-weight:500;letter-spacing:-.01em;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.cr-lang:hover{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.cr-lang:active{transform:scale(.94)}.cr-lang[aria-expanded=true]{background:color-mix(in srgb,var(--knob),var(--text) 10%)}.cr-down{width:14px;height:14px;color:var(--text-2);transform:rotate(90deg);transition:transform .2s var(--ease-out)}.cr-lang[aria-expanded=true] .cr-down{transform:rotate(-90deg)}.page{max-width:1072px;margin:0 auto;padding-left:var(--gutter-l);padding-right:var(--gutter-r);padding-block:calc(40px + env(safe-area-inset-top,0px)) 112px}.cols{display:grid;gap:40px}.cols>.access{order:-1}@media(min-width:960px){.cols{grid-template-columns:minmax(0,1fr) 384px;gap:36px;align-items:start}.cols>.access{order:0;position:sticky;top:calc(84px + env(safe-area-inset-top,0px))}}.sec-head{display:flex;align-items:baseline;gap:8px;padding:0 4px 12px}.sec-head h2{margin:0;font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.025em}.sec-head .aside{color:var(--text-3);font-size:14px;font-weight:500}.sec-head .aside.warn-t{color:var(--warn)}.note-s{margin:12px 4px 0;color:var(--text-3);font-size:13px;line-height:18px}.notice-slot{display:flow-root;overflow-y:clip}.notice{display:flex;align-items:center;gap:14px;padding:14px 18px 14px 14px;border-radius:24px;background:var(--raised);margin:0 0 22px}.notice .gi{width:36px;height:36px}.notice .t{display:flex;flex-direction:column;min-width:0}.notice b{font-weight:500;font-size:15px;line-height:22px;letter-spacing:-.02em}.notice span{color:var(--text-2);font-size:14px;line-height:20px}.notice.warn{background:color-mix(in srgb,var(--warn) 10%,var(--raised));box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--warn) 22%,transparent)}.notice.bad{background:color-mix(in srgb,var(--bad) 10%,var(--raised));box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--bad) 22%,transparent)}.page.single{min-height:100vh;min-height:100dvh;display:flex;flex-direction:column;align-items:center;justify-content:center;padding-block:calc(24px + env(safe-area-inset-top,0px)) calc(24px + env(safe-area-inset-bottom,0px))}.page.single .crumbs{position:relative;left:12px;max-width:calc(100% - 84px);margin:0 0 16px}.page.single .cr-mark{position:absolute;right:calc(100% + 10px);top:0}.page.single .page-body{width:100%;max-width:400px}.page.single .gone{margin:0}.gone{max-width:400px;margin:12vh auto 0;padding:32px 24px 28px;border-radius:var(--r-sheet);background:var(--raised);text-align:center;display:flex;flex-direction:column;align-items:center}.gone .gi{width:56px;height:56px;margin-bottom:16px}.gone h1{margin:0;font-size:22px;line-height:28px;font-weight:500;letter-spacing:-.03em}.gone p{margin:6px 0 0;color:var(--text-2);text-wrap:balance}.dgrid{display:grid;gap:10px;grid-template-columns:minmax(0,1fr)}@media(min-width:560px){.dgrid{grid-template-columns:repeat(2,minmax(0,1fr))}}.dev{background:var(--raised);border-radius:var(--r-card);padding:8px;display:flex;flex-direction:column;gap:8px;min-width:0;container:card / inline-size;--fit: var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease)}.dev.is-here{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 32%,transparent)}.dev.off{opacity:.5}.dev-top{display:flex;align-items:center;gap:12px;padding:8px 6px 6px 10px}.dev-top .gi{width:32px;height:32px}.dev-id{flex:1;min-width:0;display:flex;flex-direction:column}.dev-name{font-size:16px;line-height:22px;font-weight:500;letter-spacing:-.02em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dev-stat{font-size:13px;line-height:18px;color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dev-stat.ok-t{color:var(--ok)}.dev-stat.warn-t{color:var(--warn)}.dev-stat.here-t{color:var(--accent)}.dev-stat.bad-t{color:var(--bad)}.dev-name.can-edit{align-self:flex-start;max-width:calc(100% + 12px);margin:0 -6px;padding:0 6px;border-radius:8px;cursor:text;outline:none;transition:background-color .15s var(--ease-out)}.dev-name.can-edit:hover{background:color-mix(in srgb,var(--raised),var(--text) 6%)}.dev-name.can-edit:focus-visible:not(.quiet){box-shadow:0 0 0 2px color-mix(in srgb,var(--accent) 60%,transparent)}.field.inline,.field.inline:focus-within{height:30px;margin:-4px -6px;padding:0 6px;gap:0;border-radius:8px;background:none;box-shadow:none;overflow:visible}.field.inline input{font:500 16px/22px var(--font);letter-spacing:-.02em}.dev-use{margin-top:auto;background:var(--field);border-radius:var(--r-row);padding:12px 14px 12px 16px;display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:66px}.use-txt{display:flex;flex-direction:column;flex:1;min-width:0}.use-lbl{font-size:13px;line-height:18px;color:var(--text-2);white-space:nowrap}.use-val{font-size:17px;line-height:24px;font-weight:500;letter-spacing:-.02em;transition:font-size var(--fit),line-height var(--fit)}.dev .setup-btn{margin-top:auto}@container card (max-width: 313px){.use-val{font-size:15px;line-height:22px}.bars-week{--gap: 3px}.bars-week i{width:4px;border-radius:2px}}@container card (max-width: 253px){.use-val{font-size:14px;line-height:22px}.use-val .ud{column-gap:8px}}.dev.add{align-items:center;justify-content:center;min-height:144px;gap:10px;color:var(--text-2);font-weight:500;transition:background-color .2s var(--ease-out),transform .2s var(--ease-out)}.dev.add:hover{background:color-mix(in srgb,var(--raised),var(--knob) 45%)}.dev.add:active{transform:scale(.98)}.dev.add .gi{width:36px;height:36px}.dev.first{grid-column:1 / -1;align-items:center;text-align:center;padding:28px 24px 24px;gap:6px}.dev.first .gi{width:44px;height:44px;margin-bottom:8px}.dev.first b{font-size:18px;line-height:24px;font-weight:500;letter-spacing:-.02em}.dev.first p{margin:0 0 14px;color:var(--text-2);font-size:14px;line-height:20px;max-width:34ch;text-wrap:balance}.dev.first .btn{max-width:320px}.dgrid.snap .dev *{transition:none}@media(prefers-reduced-motion:reduce){.use-val{transition:none}}.reach2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.reach-tile{position:relative;display:flex;flex-direction:column;gap:1px;padding:12px 12px 12px 14px;border-radius:16px;background:var(--field);min-width:0}.reach-tile .rt-ic{width:28px;height:28px;margin-bottom:10px}.reach-tile b{font-size:14px;line-height:20px;font-weight:500;letter-spacing:-.015em}.reach-tile .rt-sub{font-size:12px;line-height:16px;color:var(--text-2)}.reach-tile .rt-mark{position:absolute;top:12px;right:12px;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;background:var(--ok-soft);color:var(--ok)}.reach-tile .rt-mark .i{width:12px;height:12px;stroke-width:2.4}.reach-tile.off b{color:var(--text-2)}.reach-tile.off .rt-sub{color:var(--text-3)}.reach-tile.off .rt-ic{opacity:.45}.reach-tile.off .rt-mark{background:var(--knob);color:var(--text-3)}.lbl-s{font-size:12px;font-weight:500;color:var(--text-2)}.names{display:flex;flex-wrap:wrap;gap:6px}.namechip{display:inline-flex;align-items:center;gap:8px;height:32px;padding:0 10px 0 12px;border-radius:10px;background:var(--field);font-family:var(--mono);font-size:13px;letter-spacing:0;transition:background-color .15s,transform .15s var(--ease-out)}.namechip:hover{background:var(--knob)}.namechip:active{transform:scale(.96)}.namechip .faint{color:var(--text-3)}.namechip .i{width:14px;height:14px;color:var(--text-2)}.ring{width:16px;height:16px;transform:rotate(-90deg)}.ring .trk{stroke:var(--bar)}.ring .arc{stroke:var(--accent)}.ring .arc.warn{stroke:var(--warn)}.ring .arc.bad{stroke:var(--bad)}.month{display:flex;flex-direction:column;gap:8px}.month-axis{position:relative;display:flex;justify-content:space-between;font-size:11px;color:var(--text-3);font-weight:500}.month-axis .td{position:absolute;transform:translate(-50%);color:var(--accent)}.month-axis .hide{visibility:hidden}.month-read{display:flex;justify-content:space-between;align-items:baseline;margin-top:10px;font-size:13px;color:var(--text-2)}.month-read>*{white-space:nowrap}.month-read .ud{color:var(--text);font-weight:500;font-size:15px;letter-spacing:-.02em}.meter{height:6px;border-radius:3px;background:var(--bar);overflow:hidden}.meter>i{display:block;height:100%;border-radius:3px;background:var(--accent)}.meter>i.warn{background:var(--warn)}.meter>i.bad{background:var(--bad)}.until{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 16px;border-radius:16px;background:var(--field)}.until-num{display:flex;flex-direction:column;min-width:0}.until-num b{font-size:36px;line-height:40px;font-weight:600;letter-spacing:-.045em}.until-num span{font-size:13px;line-height:18px;color:var(--text-2)}.until-num .until-sub{margin-top:8px;font-size:12px;color:var(--text-3)}.until.soon .until-num b{color:var(--warn)}.cal{display:flex;flex-direction:column;gap:6px;flex:none}.cal-h,.cal-g{display:grid;grid-template-columns:repeat(7,10px);gap:5px}.cal-h span{font-size:9px;line-height:10px;font-weight:600;color:var(--text-3);text-align:center}.cal-g i{width:10px;height:10px;border-radius:3px;background:color-mix(in srgb,var(--text) 16%,transparent)}.cal-g i.past{background:color-mix(in srgb,var(--text) 5%,transparent)}.cal-g i.today{background:var(--accent)}.cal-g i.end{background:transparent;box-shadow:inset 0 0 0 1.5px var(--accent)}.cal-g i.after{background:transparent}.until.soon .cal-g i.today{background:var(--warn)}.until.soon .cal-g i.end{box-shadow:inset 0 0 0 1.5px var(--warn)}.acc-row.opened .cal-g i{animation:cal-in .36s var(--ease-out) backwards;animation-delay:calc(var(--i) * 7ms)}@keyframes cal-in{0%{opacity:0;transform:scale(.4)}}.hours{display:flex;flex-direction:column;gap:8px;padding:14px 16px;border-radius:16px;background:var(--field)}.hours-top{display:flex;justify-content:space-between;align-items:baseline;font-size:13px;color:var(--text-2)}.hours-top b{color:var(--text);font-weight:500;font-size:15px;letter-spacing:-.02em}.hours-bar{position:relative;height:8px;border-radius:4px;background:color-mix(in srgb,var(--text) 8%,transparent)}.hours-bar i{position:absolute;top:0;bottom:0;border-radius:4px;background:color-mix(in srgb,var(--ok) 70%,transparent)}.hours-now{position:absolute;top:-4px;width:2px;height:16px;margin-left:-1px;border-radius:1px;background:var(--text);box-shadow:0 0 0 2px var(--field)}.hours-now.out{background:var(--warn)}.hours-axis{display:flex;justify-content:space-between;font-size:10px;color:var(--text-3);font-weight:500}@media(prefers-reduced-motion:reduce){.acc-row.opened .cal-g i{animation:none}}.sheet-root{position:fixed;inset:0;z-index:50;display:none}.sheet-root.open{display:block}.scrim{position:absolute;inset:0;background:var(--scrim);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.sheet{position:absolute;left:var(--gutter-l);right:var(--gutter-r);bottom:calc(16px + env(safe-area-inset-bottom,0px));margin:0 auto;max-width:400px;max-height:calc(100% - 32px - env(safe-area-inset-top,0px) - env(safe-area-inset-bottom,0px));background:var(--raised);border-radius:var(--r-sheet);box-shadow:var(--sheet-shadow);overflow:hidden;display:flex;flex-direction:column}@media(min-width:760px){.sheet-root.open{display:flex;align-items:center;justify-content:center}.sheet{position:relative;left:auto;right:auto;bottom:auto;margin:0;width:calc(100% - var(--gutter-l) - var(--gutter-r))}}.sheet .x{position:absolute;z-index:3;right:22px;top:22px}.vp{position:relative;overflow:hidden;flex:none}.sheet-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain}.view{padding:0 24px 24px;display:flex;flex-direction:column}.vhead{display:flex;align-items:center;gap:12px;height:76px;padding-right:44px;flex:none;cursor:grab;touch-action:none}.vhead h2{flex:1;margin:0;font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.vhead.center h2{text-align:center}.vhead.with-acts{padding-right:126px}.vsub{margin:-16px 0 18px;color:var(--text-2);font-size:14px;line-height:20px}.vhead.center+.vsub{text-align:center;margin:-6px auto 24px;max-width:32ch;text-wrap:balance}.view>.hint.bad-t{margin-top:8px}.secure-note{margin-top:12px;text-align:center}.sheet-acts{position:absolute;z-index:3;top:22px;right:58px}.hpill{position:relative;display:flex;gap:2px}.hp-b{display:grid;place-items:center;width:38px;height:32px;background:var(--knob);color:var(--text);transition:background-color .15s,transform .15s var(--ease-out)}.hp-b:first-of-type{border-radius:16px 6px 6px 16px}.hp-b:last-of-type{border-radius:6px 16px 16px 6px}.hp-b .i{width:16px;height:16px}.hp-b:hover{background:color-mix(in srgb,var(--knob),var(--text) 6%)}.hp-b:active{transform:scale(.94)}.hp-b.done{color:var(--ok)}.hp-tip{position:absolute;z-index:4;left:0;top:calc(100% + 8px);height:26px;padding:0 10px;display:flex;align-items:center;border-radius:999px;background:var(--toast);color:var(--toast-fg);font:500 12px/1 var(--font);letter-spacing:-.1px;white-space:nowrap;box-shadow:0 0 0 1px var(--line-glass),var(--pop-shadow);opacity:0;pointer-events:none;overflow:hidden;transform-origin:50% 0}.hp-tip.on{opacity:1}.hp-tip .tt{position:relative;display:inline-flex;justify-content:center;white-space:nowrap}.hp-tip .tt-m{position:absolute;left:0;top:0;visibility:hidden;white-space:nowrap}.sheet .x,.sheet-acts{transition:transform .15s var(--ease-out),background-color .15s,opacity .24s var(--ease-out),filter .24s var(--ease-out),scale .24s var(--ease-out)}.sheet.arrived .x,.sheet.arrived .sheet-acts,.sheet.asks .x{opacity:0;filter:blur(3px);scale:.9;pointer-events:none}.center-col,.ask{display:flex;flex-direction:column}.center-col{align-items:center;text-align:center}.ask{align-items:flex-start;text-align:left;padding-top:24px}.center-col.secure{padding-top:4px}:is(.center-col,.ask) .gi.xl{width:64px;height:64px;margin:8px 0 16px}.ask .gi.xl{margin:0 0 18px}:is(.center-col,.ask) h3{margin:0;font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.5px}:is(.center-col,.ask) p{margin:6px 0 22px;color:var(--text-2);font-size:15px;line-height:21px}.center-col p{max-width:30ch;text-wrap:balance}.ask p{text-wrap:pretty}.center-col.secure p{margin-top:0}.btnrow{display:flex;gap:8px;width:100%}.btnrow .btn{flex:1}.btnrow2{display:grid;gap:8px}.btnrow2 .btn{width:100%}.setup{display:flex;flex-direction:column}.setup .notice{margin:0 0 16px}.steps-gap{height:22px}.step{display:flex;gap:12px}.step+.step{margin-top:20px}.step[hidden]+.step{margin-top:0}.step-n{width:24px;height:24px;border-radius:50%;background:var(--knob);font-size:13px;font-weight:600;display:grid;place-items:center;flex:none}.step-b{flex:1;min-width:0;display:flex;flex-direction:column;gap:10px}.step-t{font-size:16px;line-height:24px;font-weight:500;letter-spacing:-.02em}.step-box{display:flex;flex-direction:column;gap:10px}.way{display:flex;flex-direction:column;padding:12px 14px;border-radius:20px;background:var(--field);margin-bottom:18px}.way-row{display:flex;align-items:center;gap:10px}.way-end{width:34px;height:34px;border-radius:11px;background:var(--knob);display:grid;place-items:center;flex:none;color:var(--text-2);transition:background-color .4s var(--ease-out),color .4s var(--ease-out)}.way-end .i{width:17px;height:17px}.way-end.home{color:var(--accent);background:color-mix(in srgb,var(--accent) 14%,transparent)}.way-track{position:relative;flex:1;height:8px}.way-track:before,.way-glow,.way-fill{content:"";position:absolute;inset:0;-webkit-mask:radial-gradient(circle,#000 1.4px,transparent 1.9px) 0 50% / 9px 8px repeat-x;mask:radial-gradient(circle,#000 1.4px,transparent 1.9px) 0 50% / 9px 8px repeat-x}.way-track:before{background:var(--text-3);opacity:.8}.way-glow{overflow:hidden}.way-glow>span{position:absolute;inset:0;transition:opacity .2s var(--ease-out)}.way.trying .run,.way.done .run,.way.nodata .run,.way.stopped .run,.way:not(.trying) .knock{opacity:0}.way-glow i{position:absolute;inset:0;background:linear-gradient(90deg,transparent 32%,var(--accent) 50%,transparent 68%);transform:translate(-70%);animation:way-run 2s cubic-bezier(.45,0,.55,1) infinite}@keyframes way-run{0%{transform:translate(-70%)}72%,to{transform:translate(70%)}}.way-fill{background:var(--ok);clip-path:inset(0 100% 0 0);transition:clip-path .7s var(--ease-out) 80ms}.way.done .way-fill{clip-path:inset(0)}.way.done .way-end{color:var(--ok);background:var(--ok-soft)}.way.done .way-end.home,.way.nodata .way-end.home{transition-delay:.6s}.way.done .way-end.home .i{animation:way-dip .12s cubic-bezier(.45,0,.55,1) .48s,way-pop var(--spring-bouncy-dur, 572ms) var(--spring-bouncy, ease) .6s}@keyframes way-dip{to{transform:scale(.6)}}@keyframes way-pop{0%{transform:scale(.6)}to{transform:none}}.way-text{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:30px;margin-top:10px;text-align:center}.way-text .t{display:flex;flex-direction:column;align-items:center;min-width:0}.way-text b{position:relative;display:inline-flex;justify-content:center;white-space:nowrap;font-weight:500;font-size:14px;line-height:20px;transition:color .3s var(--ease-out)}.way-text .ws{color:var(--text-2);font-size:13px;line-height:18px}.way.done .way-text b{color:var(--ok)}.way-glow .knock i{background:linear-gradient(90deg,transparent 32%,var(--warn) 50%,transparent 68%);animation:way-knock 1.8s cubic-bezier(.45,0,.55,1) infinite}@keyframes way-knock{0%{transform:translate(-70%)}48%{transform:translate(34%)}62%{transform:translate(26%);opacity:1}86%,to{transform:translate(-70%);opacity:0}}.way-break{position:absolute;right:-2px;top:-5px;width:2px;height:18px;opacity:0;transition:opacity .2s var(--ease-out)}.way.trying .way-break{opacity:1}.way-break i{position:absolute;inset:0;border-radius:2px;background:var(--warn);transform:rotate(18deg);animation:way-break 1.8s cubic-bezier(.45,0,.55,1) infinite}@keyframes way-break{0%,40%{opacity:.25;transform:rotate(18deg) scaleY(.7)}50%{opacity:1;transform:rotate(18deg) scaleY(1.15)}70%,to{opacity:.25;transform:rotate(18deg) scaleY(.7)}}.way.trying .way-end.home{color:var(--warn);background:color-mix(in srgb,var(--warn) 14%,transparent)}.way.trying .way-text b,.way.nodata .way-text b{color:var(--warn)}.way.nodata .way-fill{clip-path:inset(0)}.way.nodata .way-end{color:var(--ok);background:var(--ok-soft)}.way-pkt{position:absolute;top:50%;left:0;width:8px;height:8px;margin-top:-4px;border-radius:50%;background:var(--warn);box-shadow:0 0 10px color-mix(in srgb,var(--warn) 70%,transparent);opacity:0;animation:way-drop 2.2s cubic-bezier(.45,0,.55,1) infinite}.way-pkt.b{animation-delay:1.1s}@keyframes way-drop{0%{left:0;opacity:0;transform:none}8%{opacity:1}46%{left:48%;opacity:1;transform:none}66%,to{left:54%;opacity:0;transform:translateY(16px) scale(.5)}}.filecard{display:flex;flex-direction:column;gap:10px;padding:12px;border-radius:18px;background:var(--field)}.fc-row{display:flex;align-items:center;gap:12px;min-width:0}.filecard-ic{width:38px;height:46px;border-radius:9px;background:var(--knob);font:600 10px/1 var(--mono);display:grid;place-items:center;color:var(--text-2);flex:none}.filecard .t{flex:1;min-width:0;display:flex;flex-direction:column}.filecard .t .mono{font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.filecard .t span:last-child{font-size:12px;color:var(--text-2);line-height:16px}.confbar{display:flex;gap:8px}.conf{margin:0;padding:12px 14px;border-radius:14px;background:var(--field);font:12px/18px var(--mono);max-height:16rem;overflow:auto;white-space:pre;color:var(--text-2)}.conf .k{color:var(--text)}.conf .sec{color:var(--accent)}.conf .mask{color:var(--text-3);letter-spacing:1px}.osm{white-space:normal}.osm-ic{display:inline-grid;width:1.05em;height:1.05em;margin-right:.25em;vertical-align:-.16em}.osm-ic>svg{grid-area:1 / 1;width:100%;height:100%}.osm-ic .eye{fill:var(--field)}.osm-p{display:inline-block;white-space:pre}.scanline{display:flex;flex-wrap:wrap;align-items:baseline;column-gap:.3em}.scanline .osm{white-space:nowrap}@media(max-width:440px){.scanline{flex-direction:column;align-items:flex-start}}.way-text b .mt-old{color:var(--text-2)}@media(prefers-reduced-motion:reduce){.way-glow{display:none}.way-fill{transition:none}.way.done .way-end.home .i,.way-break i{animation:none}.way-pkt{display:none}}.menu{position:fixed;z-index:60;min-width:224px;padding:6px;border-radius:20px;background:var(--field);box-shadow:var(--pop-shadow),inset 0 0 0 1px var(--line)}.menu-hl{position:absolute;left:6px;right:6px;top:6px;height:40px;border-radius:14px;background:var(--knob);opacity:0;transition:opacity .15s var(--ease-out);pointer-events:none}.menu-hl.moving{transition:opacity .15s var(--ease-out),transform var(--spring-quick-dur, .3s) var(--spring-quick, ease-out),background-color .15s}.menu-hl.bad{background:var(--bad-soft)}.menu-hl.warn{background:color-mix(in srgb,var(--warn) 13%,transparent)}.mi{position:relative;z-index:1;display:flex;align-items:center;gap:12px;width:100%;height:40px;padding:0 12px;border-radius:14px;font-size:14px;font-weight:500;text-align:left}.mi .i{width:16px;height:16px;color:var(--text-2)}.mi .i.off{visibility:hidden}.mi.warn,.mi.warn .i{color:var(--warn)}.mi.bad,.mi.bad .i{color:var(--bad)}.menu-sep{height:1px;margin:6px 12px;background:var(--line)}.toasts{position:fixed;left:0;right:0;height:42px;bottom:calc(24px + env(safe-area-inset-bottom,0px));z-index:70;display:flex;justify-content:center;align-items:flex-end;pointer-events:none;padding-left:var(--gutter-l);padding-right:var(--gutter-r)}.toast{position:absolute;display:flex;align-items:center;gap:8px;height:42px;padding:0 18px 0 13px;border-radius:999px;background:var(--toast);color:var(--toast-fg);font-size:14px;font-weight:500;box-shadow:var(--pop-shadow);white-space:nowrap}.toast .i{width:18px;height:18px;color:var(--ok)}.toast.bad .i{color:var(--bad)} diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js index c404498..bbde402 100644 --- a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js @@ -1,6 +1,6 @@ -"use strict";(()=>{var fs=Object.create;var or=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var ms=Object.getOwnPropertyNames;var gs=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty;var ys=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var bs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ms(t))!vs.call(e,o)&&o!==n&&or(e,o,{get:()=>t[o],enumerable:!(r=hs(t,o))||r.enumerable});return e};var xs=(e,t,n)=>(n=e!=null?fs(gs(e)):{},bs(t||!e||!e.__esModule?or(n,"default",{value:e,enumerable:!0}):n,e));var Vr=ys((Ur,Fr)=>{"use strict";var Kr=(function(){var e=function(d,v){var a=236,h=17,p=d,A=n[v],u=null,c=0,T=null,w=[],C={},I=function(M,k){c=p*4+17,u=(function(y){for(var L=new Array(y),S=0;S=7&&le(M),T==null&&(T=se(p,A,w)),Y(T,k)},G=function(M,k){for(var y=-1;y<=7;y+=1)if(!(M+y<=-1||c<=M+y))for(var L=-1;L<=7;L+=1)k+L<=-1||c<=k+L||(0<=y&&y<=6&&(L==0||L==6)||0<=L&&L<=6&&(y==0||y==6)||2<=y&&y<=4&&2<=L&&L<=4?u[M+y][k+L]=!0:u[M+y][k+L]=!1)},V=function(){for(var M=0,k=0,y=0;y<8;y+=1){I(!0,y);var L=o.getLostPoint(C);(y==0||M>L)&&(M=L,k=y)}return k},J=function(){for(var M=8;M>y&1)==1;u[Math.floor(y/3)][y%3+c-8-3]=L}for(var y=0;y<18;y+=1){var L=!M&&(k>>y&1)==1;u[y%3+c-8-3][Math.floor(y/3)]=L}},ue=function(M,k){for(var y=A<<3|k,L=o.getBCHTypeInfo(y),S=0;S<15;S+=1){var R=!M&&(L>>S&1)==1;S<6?u[S][8]=R:S<8?u[S+1][8]=R:u[c-15+S][8]=R}for(var S=0;S<15;S+=1){var R=!M&&(L>>S&1)==1;S<8?u[8][c-S-1]=R:S<9?u[8][15-S-1+1]=R:u[8][15-S-1]=R}u[c-8][8]=!M},Y=function(M,k){for(var y=-1,L=c-1,S=7,R=0,q=o.getMaskFunction(k),z=c-1;z>0;z-=2)for(z==6&&(z-=1);;){for(var X=0;X<2;X+=1)if(u[L][z-X]==null){var ie=!1;R>>S&1)==1);var K=q(L,z-X);K&&(ie=!ie),u[L][z-X]=ie,S-=1,S==-1&&(R+=1,S=7)}if(L+=y,L<0||c<=L){L-=y,y=-y;break}}},te=function(M,k){for(var y=0,L=0,S=0,R=new Array(k.length),q=new Array(k.length),z=0;z=0?tr.getAt(nr):0}}for(var rr=0,K=0;Kz*8)throw"code length overflow. ("+S.getLengthInBits()+">"+z*8+")";for(S.getLengthInBits()+4<=z*8&&S.put(0,4);S.getLengthInBits()%8!=0;)S.putBit(!1);for(;!(S.getLengthInBits()>=z*8||(S.put(a,8),S.getLengthInBits()>=z*8));)S.put(h,8);return te(S,L)};C.addData=function(M,k){k=k||"Byte";var y=null;switch(k){case"Numeric":y=f(M);break;case"Alphanumeric":y=E(M);break;case"Byte":y=x(M);break;case"Kanji":y=b(M);break;default:throw"mode:"+k}w.push(y),T=null},C.isDark=function(M,k){if(M<0||c<=M||k<0||c<=k)throw M+","+k;return u[M][k]},C.getModuleCount=function(){return c},C.make=function(){if(p<1){for(var M=1;M<40;M++){for(var k=m.getRSBlocks(M,A),y=g(),L=0;L";for(var S=0;S';y+=""}return y+="",y+="",y},C.createSvgTag=function(M,k,y,L){var S={};typeof arguments[0]=="object"&&(S=arguments[0],M=S.cellSize,k=S.margin,y=S.alt,L=S.title),M=M||2,k=typeof k=="undefined"?M*4:k,y=typeof y=="string"?{text:y}:y||{},y.text=y.text||null,y.id=y.text?y.id||"qrcode-description":null,L=typeof L=="string"?{text:L}:L||{},L.text=L.text||null,L.id=L.text?L.id||"qrcode-title":null;var R=C.getModuleCount()*M+k*2,q,z,X,ie,K="",ye;for(ye="l"+M+",0 0,"+M+" -"+M+",0 0,-"+M+"z ",K+=''+ne(L.text)+"":"",K+=y.text?''+ne(y.text)+"":"",K+='',K+='":k+=">";break;case"&":k+="&";break;case'"':k+=""";break;default:k+=L;break}}return k},Bt=function(M){var k=1;M=typeof M=="undefined"?k*2:M;var y=C.getModuleCount()*k+M*2,L=M,S=y-M,R,q,z,X,ie,K={"██":"█","█ ":"▀"," █":"▄"," ":" "},ye={"██":"▀","█ ":"▀"," █":" "," ":" "},be="";for(R=0;R=S?ye[ie]:K[ie];be+=` -`}return y%2&&M>0?be.substring(0,be.length-y-1)+Array(y+1).join("▀"):be.substring(0,be.length-1)};return C.createASCII=function(M,k){if(M=M||1,M<2)return Bt(k);M-=1,k=typeof k=="undefined"?M*2:k;var y=C.getModuleCount()*M+k*2,L=k,S=y-k,R,q,z,X,ie=Array(M+1).join("██"),K=Array(M+1).join(" "),ye="",be="";for(R=0;R>>8),A.push(T&255)):A.push(h)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=(function(){var d=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,a=7973,h=21522,p={},A=function(u){for(var c=0;u!=0;)c+=1,u>>>=1;return c};return p.getBCHTypeInfo=function(u){for(var c=u<<10;A(c)-A(v)>=0;)c^=v<=0;)c^=a<5&&(T+=3+I-5)}for(var w=0;w=256;)p-=255;return d[p]},h})();function l(d,v){if(typeof d.length=="undefined")throw d.length+"/"+v;var a=(function(){for(var p=0;p>>7-h%8&1)==1},a.put=function(h,p){for(var A=0;A>>p-A-1&1)==1)},a.getLengthInBits=function(){return v},a.putBit=function(h){var p=Math.floor(v/8);d.length<=p&&d.push(0),h&&(d[p]|=128>>>v%8),v+=1},a},f=function(d){var v=t.MODE_NUMBER,a=d,h={};h.getMode=function(){return v},h.getLength=function(u){return a.length},h.write=function(u){for(var c=a,T=0;T+2>>8&255)*192+(w&255),u.put(w,13),T+=2}if(T>>8)},v.writeBytes=function(a,h,p){h=h||0,p=p||a.length;for(var A=0;A0&&(a+=","),a+=d[h];return a+="]",a},v},H=function(){var d=0,v=0,a=0,h="",p={},A=function(c){h+=String.fromCharCode(u(c&63))},u=function(c){if(!(c<0)){if(c<26)return 65+c;if(c<52)return 97+(c-26);if(c<62)return 48+(c-52);if(c==62)return 43;if(c==63)return 47}throw"n:"+c};return p.writeByte=function(c){for(d=d<<8|c&255,v+=8,a+=1;v>=6;)A(d>>>v-6),v-=6},p.flush=function(){if(v>0&&(A(d<<6-v),d=0,v=0),a%3!=0)for(var c=3-a%3,T=0;T=v.length){if(p==0)return-1;throw"unexpected end of file./"+p}var c=v.charAt(a);if(a+=1,c=="=")return p=0,-1;if(c.match(/^\s$/))continue;h=h<<6|u(c.charCodeAt(0)),p+=6}var T=h>>>p-8&255;return p-=8,T};var u=function(c){if(65<=c&&c<=90)return c-65;if(97<=c&&c<=122)return c-97+26;if(48<=c&&c<=57)return c-48+52;if(c==43)return 62;if(c==47)return 63;throw"c:"+c};return A},B=function(d,v){var a=d,h=v,p=new Array(d*v),A={};A.setPixel=function(w,C,I){p[C*a+w]=I},A.write=function(w){w.writeString("GIF87a"),w.writeShort(a),w.writeShort(h),w.writeByte(128),w.writeByte(0),w.writeByte(0),w.writeByte(0),w.writeByte(0),w.writeByte(0),w.writeByte(255),w.writeByte(255),w.writeByte(255),w.writeString(","),w.writeShort(0),w.writeShort(0),w.writeShort(a),w.writeShort(h),w.writeByte(0);var C=2,I=c(C);w.writeByte(C);for(var G=0;I.length-G>255;)w.writeByte(255),w.writeBytes(I,G,255),G+=255;w.writeByte(I.length-G),w.writeBytes(I,G,I.length-G),w.writeByte(0),w.writeString(";")};var u=function(w){var C=w,I=0,G=0,V={};return V.write=function(J,re){if(J>>>re)throw"length over";for(;I+re>=8;)C.writeByte(255&(J<>>=8-I,G=0,I=0;G=J<0&&C.writeByte(G)},V},c=function(w){for(var C=1<>6,128|i&63):i<55296||i>=57344?r.push(224|i>>12,128|i>>6&63,128|i&63):(o++,i=65536+((i&1023)<<10|n.charCodeAt(o)&1023),r.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}return r}return t(e)}})();(function(e){typeof define=="function"&&define.amd?define([],e):typeof Ur=="object"&&(Fr.exports=e())})(function(){return Kr})});var sr={s:{'"%s" already exists.':"Устройство «%s» уже есть.",'"%s" is already taken.':"Идентификатор «%s» уже занят.","%s (Android: %s)":"%s (на Android: %s)","%s (router time)":"%s (по времени роутера)","%s can't use the network interface %s: it exists and isn't Dawnline's.":"Сервер %s не может использовать сетевой интерфейс %s: он уже существует и создан не Dawnline.","%s connected":"Подключено: %s","%s d ago":"%s дн. назад","%s h ago":"%s ч назад",'%s has an invalid interface name "%s".':"У сервера %s недопустимое имя интерфейса «%s».","%s has no room for every device on %s.":"В подсети %s не хватит адресов для всех устройств сервера %s.","%s in total":"%s всего","%s is kept down.":"Сервер %s остановлен.","%s is kept down: its disguise needs AmneziaWG %s (installed: %s).":"Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (установлен %s).","%s is kept down: its disguise needs AmneziaWG %s (installed: none).":"Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (не установлен).","%s left":"осталось %s","%s min ago":"%s мин назад","%s must be a number or range":"%s: нужно число или диапазон","%s of %s":"%s из %s","%s of %s GB":"%s из %s ГБ","%s of %s GB this month":"%s из %s ГБ в этом месяце","%s of %s in total.":"Всего %s из %s.","%s options":"Действия с устройством %s","%s this month":"%s в этом месяце","%s your time":"%s по вашему времени","%sd %sh":"%s д %s ч","%sh %sm":"%s ч %s мин","%sm":"%s мин","A total for your whole access, it does not reset.":"Считается за весь срок доступа и не обнуляется.","APK file on":"APK-файл на","Access %s":"Доступ %s","Access ended":"Доступ закончился","Access must be lan, internet or both.":"Доступ должен быть lan, internet или both.","Access paused":"Доступ на паузе","Access until":"Доступ до",Active:"Активен","WireGuard appAdd Tunnel":"Добавить туннель","Add a device":"Добавить устройство","Add device":"Добавить устройство","Add it from the device":"Добавить с самого устройства","Add the connection":"Добавьте подключение","Add this device":"Добавить это устройство","Add this phone":"Добавить этот телефон","Add your first device":"Добавьте первое устройство","Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.":"Сейчас добавить устройство нельзя: VPN-сервер не готов. Обратитесь к тому, кто прислал вам эту ссылку.","Address copied":"Адрес скопирован","Already has the app":"Приложение уже установлено","AmneziaWG is not installed (%s): install it in Dawnline → Components.":"AmneziaWG не установлен (%s): установите его в Dawnline → Компоненты.","AmneziaWG is not installed: install it in Dawnline → Components.":"AmneziaWG не установлен: установите его в Dawnline → Компоненты.","Android phone":"Телефон Android","Android tablet":"Планшет Android","Ask for a new one.":"Попросите новую.",B:"Б",Back:"Назад",Breadcrumb:"Навигационная цепочка",Cancel:"Отмена","Circle %s: server %s does not exist.":"Круг %s: сервера %s нет.",Close:"Закрыть","Close this and open it again to keep checking.":"Закройте окно и откройте его снова, чтобы проверить ещё раз.",Configuration:"Конфигурация","Configuration copied":"Конфигурация скопирована","Confirm the import and connect":"Подтвердите импорт и подключитесь",Connect:"Подключить",Connected:"Подключено","Connected, no data left":"Подключено, трафик закончился","Connected, outside your hours":"Подключено, вне часов доступа","Connection settings only travel encrypted":"Настройки подключения передаются только в зашифрованном виде","AmneziaVPN appContinue":"Продолжить",Copied:"Скопировано",Copy:"Скопировать","Copy %s":"Скопировать %s","Copy %s config":"Скопировать конфигурацию %s","Copy IP address":"Скопировать IP-адрес","Copy local address":"Скопировать локальный адрес","Copy or save the connection":"Скопировать или сохранить подключение","Copy the configuration":"Скопировать конфигурацию","Copy the key":"Скопировать ключ","in a sentenceCopy the key":"Скопируйте ключ","Copy the link":"Скопировать ссылку","Copying is blocked here. Select the text and copy it by hand.":"Копирование здесь заблокировано. Выделите текст и скопируйте его вручную.","Create connection":"Создать подключение","WireGuard appCreate from QR code":"Создать из QR-кода","WireGuard appCreate from file or archive":"Создать из файла или архива","Cross-site request refused.":"Запрос с другого сайта отклонён.","Data limit must be a positive number of GB.":"Лимит трафика должен быть положительным числом ГБ.","Data limit reached":"Лимит трафика исчерпан","Data this month":"Трафик за месяц","Data used":"Трафик всего","Device %s of %s: address %s is also used by device %s of %s.":"Устройство %s (%s): адрес %s уже занят устройством %s (%s).","Device %s of %s: address %s is not a plain IPv4 address.":"Устройство %s (%s): адрес %s не является обычным IPv4-адресом.","Device %s of %s: address %s is outside %s's tunnel %s.":"Устройство %s (%s): адрес %s вне туннеля сервера %s (%s).","Device %s of %s: address %s is the router's own address on %s.":"Устройство %s (%s): адрес %s принадлежит самому роутеру на сервере %s.","Device %s of %s: address (none) is not a plain IPv4 address.":"Устройство %s (%s): нет IPv4-адреса.","Device %s of %s: the preshared key is not a key.":"Устройство %s (%s): общий ключ (PSK) некорректен.","Device %s of %s: the private key is not a key.":"Устройство %s (%s): приватный ключ некорректен.","Device %s of %s: the public key is not a key.":"Устройство %s (%s): публичный ключ некорректен.","Device %s: person %s does not exist.":"Устройство %s: человека %s нет.","Device limit must be between 1 and 32.":"Лимит устройств: от 1 до 32.","Device limit reached (%d).":"Достигнут лимит устройств (%d).","Device name":"Имя устройства","Device not found.":"Устройство не найдено.","Device removed":"Устройство удалено","Devices at home":"Устройства дома","Devices at home and on this VPN reach yours as %s":"Устройства дома и в этом VPN обращаются к вашим по адресу %s",Disabled:"Отключено",Download:"Скачать","Download %s config":"Скачать конфигурацию %s","Download for Linux":"Скачать для Linux","Download for Mac":"Скачать для Mac","Download for Windows":"Скачать для Windows","Download from":"Скачать с сайта","Download on the":"Загрузите в","Download the file":"Скачать файл","Download the key":"Скачать ключ",Downloaded:"Получено","End date must be YYYY-MM-DD.":"Дата окончания должна быть в формате ГГГГ-ММ-ДД.","Endpoint must be a hostname or IP address.":"Адрес сервера должен быть именем хоста или IP-адресом.","Ends %s":"Закончится %s","Enter a device name (up to 48 characters).":"Введите название устройства (до 48 символов).",Expired:"Срок истёк","Extra data must be a positive number of GB.":"Дополнительный трафик должен быть положительным числом ГБ.","For computers and routers":"Для компьютеров и роутеров",GB:"ГБ","Gbit/s":"Гбит/с","Get %s":"Установите %s","Get %s on the %s and come back here.":"Установите %s на %s и вернитесь сюда.","Get %s on the router":"Установите %s на роутер","Get it on":"Доступно в","Hide key":"Скрыть ключ","Home network":"Домашняя сеть","Home network + Internet":"Домашняя сеть и интернет","Hours must look like 07:00-23:00.":"Часы доступа указываются так: 07:00-23:00.","Hours, router time":"Часы доступа, время роутера","Hours, your time":"Часы доступа, ваше время","IP address copied":"IP-адрес скопирован","WireGuard appImport Tunnel(s) from File…":"Импорт туннелей из файла…","WireGuard appImport from file or archive":"Импорт из файла или архива","Import the configuration":"Импортируйте конфигурацию","WireGuard appImport tunnel(s) from file…":"Импорт туннелей из файла…","In %s:":"В %s:",Included:"Есть доступ","AmneziaVPN appInsert":"Вставить","Install from":"Установить с сайта","Interface name: 1-12 lowercase letters, digits or _.":"Имя интерфейса: 1–12 строчных латинских букв, цифр или _.",Internet:"Интернет","Invalid JSON.":"Некорректный JSON.","Invalid public key.":"Недопустимый публичный ключ.","It ended on %s.":"Доступ закончился %s.","It gets new keys and its current settings stop working. Set it up again with the new ones that open next.":"Устройство получит новые ключи, а текущие настройки перестанут работать. Настройте его заново с новыми - они откроются следом.","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.":"Устройство получит новые ключи. Сейчас вы подключены через его текущие настройки: через несколько секунд после подтверждения связь прервётся. Добавьте новые - они откроются следом.","Its connection stops working at once. You can add it again later.":"Подключение сразу перестанет работать. Устройство можно будет добавить снова.",KB:"КБ","Key copied":"Ключ скопирован","Key generation failed (is amneziawg-tools installed?).":"Не удалось создать ключ (установлен ли amneziawg-tools?).","Key generation failed (no random data).":"Не удалось создать ключ (нет случайных данных).","Key generation failed.":"Не удалось создать ключ.",Language:"Язык","Last 7 days":"За 7 дней","Last connected %s":"В сети %s","Link copied":"Ссылка скопирована","Linux PC":"Компьютер с Linux",MB:"МБ","Mbit/s":"Мбит/с","Method not allowed.":"Метод не поддерживается.",Mobile:"Мобильный","Monthly data must be a positive number of GB.":"Месячный лимит трафика должен быть положительным числом ГБ.",Name:"Имя","No connection yet":"Подключения пока нет","No data limit. The count starts again on the 1st.":"Лимита трафика нет. Счёт начинается заново 1-го числа.","No end date":"Бессрочно","No free address left on %s.":"На сервере %s не осталось свободных адресов.","No free addresses left in the server subnet.":"В подсети сервера не осталось свободных адресов.","No limit":"Без лимита","No server":"Нет сервера","No server yet":"Сервера пока нет","Not found.":"Не найден.","Not included":"Нет доступа","Not on the %s right now?":"Открыли на другом %s?","Not set up yet":"Ещё не настроено","Nothing gets through until it resets.":"Ничего не проходит, пока лимит не обнулится.","Nothing opened? %s and add it in the app.":"Ничего не открылось? %s и добавьте его в приложении.","Now, %s":"Сейчас %s",OR:"ИЛИ","Official release on GitHub":"Официальная версия на GitHub","On %s.":"Дата окончания - %s.","On GitHub":"На GitHub","Only the admin can turn devices off.":"Отключать устройства может только администратор.","stepOpen %s":"Откройте %s","Open %s.":"Доступ открыт %s.","Open a terminal in the folder with the file":"Откройте терминал в папке с файлом","Open in AmneziaVPN":"Открыть в AmneziaVPN","Open on another device":"Открыть на другом устройстве","Open on the device":"Открыть на устройстве","Open securely":"Открыть по HTTPS","Open the link securely":"Откройте защищённую ссылку","Open this link on the %s to set it up there.":"Откройте эту ссылку на %s, чтобы настроить его там.","Open this link over HTTPS to get the connection settings.":"Чтобы получить настройки подключения, откройте эту ссылку по HTTPS.","Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.":"Откройте эту страницу в Safari или Chrome: магазин отсюда откроется, а передача в приложение - нет.","Open your link on the %s":"Откройте свою ссылку на %s","OpenWrt packages":"Пакеты OpenWrt","OpenWrt packages + kmod":"Пакеты OpenWrt + kmod",Other:"Другое","Other devices at home reach yours as %s":"Другие устройства дома обращаются к вашим по адресу %s","Out of data":"Трафик закончился","Outside allowed hours":"Вне часов доступа","Outside your hours":"Вне часов доступа",PC:"Компьютер",Paused:"На паузе","Person %s: circle %s does not exist.":"Человек %s: круга %s нет.","Person %s: has the same personal link as %s.":"Человек %s: личная ссылка совпадает со ссылкой человека %s.","Person %s: home service %s does not exist.":"Человек %s: домашнего сервиса %s нет.","Person %s: server %s does not exist.":"Человек %s: сервера %s нет.",Phone:"Телефон","Phones and tablets get a smaller packet size that suits mobile networks.":"У телефонов и планшетов пакеты меньше - так лучше для мобильных сетей.","Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app.":"Выберите AmneziaVPN в меню «Поделиться». Его там нет? %s и добавьте его в приложении.","Pick the file and connect":"Выберите файл и подключитесь","Point its camera at the code: the link opens there.":"Наведите камеру устройства на код - ссылка откроется на нём.","Point its camera at the code: this page opens there.":"Наведите камеру устройства на код - там откроется эта страница.","Point its camera at the code: your page opens there with this device ready to add.":"Наведите камеру устройства на код - там откроется ваша страница, и его можно будет сразу добавить.","Port must be 1-65535.":"Порт: от 1 до 65535.","QR code":"QR-код","AmneziaVPN appQR code":"QR-код",Reconnect:"Переподключить","Reconnect %s":"Переподключить %s","Reconnect %s?":"Переподключить «%s»?",Remove:"Удалить","Remove %s?":"Удалить «%s»?",Rename:"Переименовать","Rename %s":"Переименовать «%s»",Renamed:"Переименовано","Request failed (%s)":"Не удалось выполнить запрос (%s)","Request too large.":"Слишком большой запрос.","Resets on the 1st.":"Обнуляется 1-го числа.",Router:"Роутер",Run:"Выполните",Save:"Сохранить","WireGuard appScan from QR code":"Сканировать QR-код","Send it to the %s":"Отправить на %s","Send it to the %s in a message or a note, then in AmneziaVPN: %s.":"Отправьте его на %s в сообщении или заметке, затем в AmneziaVPN: %s.","Send it to the %s, then import %s in %s.":"Отправьте его на %s, затем импортируйте %s в %s.","Send to AmneziaVPN":"Отправить в AmneziaVPN","Server is disabled":"Сервер выключен","Server is turned off":"Сервер выключен","Set up %s":"Настроить %s","Set up a server first.":"Сначала настройте сервер.","Settings changed":"Настройки изменились","Settings changed, update needed":"Настройки изменились, нужно обновить","Share as a file":"Поделиться файлом","Share file":"Поделиться файлом","Share the file":"Поделиться файлом","Share the link":"Поделиться ссылкой","Show key":"Показать ключ","Straight into %s":"Сразу в %s","Subnet must look like 10.77.0.0/24.":"Подсеть указывается так: 10.77.0.0/24.","Subnet overlaps %s.":"Подсеть пересекается с %s.",TB:"ТБ",Tablet:"Планшет","Tap “%s” and connect":"Нажмите «%s» и подключитесь","The APK is for phones without Google Play, or where the store hides the app.":"APK - для телефонов без Google Play или если магазин скрывает приложение.","The admin has turned this device off.":"Администратор отключил это устройство.","The app goes on the %s.":"Приложение ставится на %s.","The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).":"Браузер может предупредить, что сертификату нельзя доверять: это собственный сертификат роутера. Продолжите переход («Дополнительные» → «Перейти на сайт»).","The connection":"Подключение","The connection as one key":"Подключение одним ключом","The id may use lowercase letters, digits and underscores.":"В идентификаторе можно использовать строчные латинские буквы, цифры и подчёркивания.","The packages and the file for OpenWrt":"Пакеты и файл для OpenWrt","The page could not load":"Не удалось загрузить страницу","The person has no server.":"У человека нет сервера.","Then come back here and tap":"Затем вернитесь сюда и нажмите","Then import it in the app":"Затем импортируйте его в приложении","This device":"Это устройство","This key is already in use.":"Этот ключ уже используется.","This link no longer works":"Эта ссылка больше не работает","This page is open without encryption. To add or set up a device, open the same link over HTTPS:":"Эта страница открыта без шифрования. Чтобы добавить или настроить устройство, откройте ту же ссылку по HTTPS:","Through the router":"Через роутер",Today:"Сегодня","Too many changes in a short time. Try again in a few minutes.":"Слишком много изменений за короткое время. Попробуйте ещё раз через несколько минут.","Two steps, about a minute":"Два шага, около минуты","Two steps, about a minute: get the app, then add the connection.":"Два шага, около минуты: установите приложение, затем добавьте подключение.","Unknown DNS choice.":"Неизвестный вариант DNS.","Unknown action.":"Неизвестное действие.","Unknown circle.":"Неизвестный круг.","Unknown device.":"Неизвестное устройство.","Unknown end action.":"Неизвестное действие по окончании доступа.","Unknown person.":"Неизвестный человек.","Unknown server.":"Неизвестный сервер.","Unknown service %s.":"Неизвестный сервис %s.",Uploaded:"Отправлено","Waiting for the connection":"Ждём подключения","Warning must be 0-60 days.":"Предупреждать можно за 0–60 дней.","What is it?":"Что это за устройство?","Windows PC":"Компьютер с Windows",Yesterday:"Вчера","You already have a device with this name.":"У вас уже есть устройство с таким именем.","You haven’t been added to one.":"Вас ещё не добавили ни на один сервер.","Your access":"Ваш доступ","Your access has ended.":"Ваш доступ закончился.","Your access is paused.":"Ваш доступ на паузе.","Your devices":"Ваши устройства","Your devices can’t connect until it’s enabled again.":"Ваши устройства не подключатся, пока его снова не включат.","Your devices can’t connect until it’s extended.":"Ваши устройства не подключатся, пока доступ не продлят.","Your devices can’t connect until it’s resumed.":"Ваши устройства не подключатся, пока доступ не возобновят.","bit/s":"бит/с",computer:"компьютер","on thecomputer":"компьютере",device:"устройство","on thedevice":"устройстве",ended:"закончился","ends today":"закончится сегодня","ends tomorrow":"закончится завтра","h1-h4 must be distinct":"h1-h4 должны быть разными","just now":"только что","kbit/s":"кбит/с",name:"имя",never:"никогда","no limit":"без лимита",phone:"телефон","on thephone":"телефоне",router:"роутер","on therouter":"роутере",tablet:"планшет","on thetablet":"планшете","this device":"это устройство"},p:{"%s already has %d device. Remove one first to lower the limit to %d.":["%s: уже %d устройство. Чтобы снизить лимит до %d, сначала удалите одно из них.","%s: уже %d устройства. Чтобы снизить лимит до %d, сначала удалите одно из них.","%s: уже %d устройств. Чтобы снизить лимит до %d, сначала удалите одно из них."],"%s day":["%s день","%s дня","%s дней"],"%s of %s slot free":["Свободно %s из %s места","Свободно %s из %s мест","Свободно %s из %s мест"],"You have reached your limit of %s device":["Достигнут лимит - %s устройство","Достигнут лимит - %s устройства","Достигнут лимит - %s устройств"],"You have reached your limit of %s device. Remove one to add another.":["Достигнут лимит - %s устройство. Удалите одно, чтобы добавить новое.","Достигнут лимит - %s устройства. Удалите одно, чтобы добавить новое.","Достигнут лимит - %s устройств. Удалите одно, чтобы добавить новое."],"day left":["день остался","дня осталось","дней осталось"],"ends in %s day":["закончится через %s день","закончится через %s дня","закончится через %s дней"]}};var It=[{code:"en",name:"English"},{code:"ru",name:"Русский"}],Ms={ru:[sr]},ir={en:e=>e!==1?1:0,ru:e=>e%10===1&&e%100!==11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2},lr="dl.lang";function ks(e,t){var r,o;let n=i=>i&&It.some(l=>l.code===i)?i:null;return(o=(r=n(e))!=null?r:t.map(i=>n(i.toLowerCase().split(/[-_]/)[0])).find(Boolean))!=null?o:"en"}var rt="en",Mn=[],cr=[],dr=(e,t)=>t?`${t}${e}`:e;function ur(e,t){let n=dr(e,t);for(let r of Mn)if(n in r.s)return r.s[n];return e}function Cs(e,t,n,r){var l,m,g;let o=dr(t,r),i=(l=Mn.find(f=>o in f.p))==null?void 0:l.p[o];return(g=i==null?void 0:i[((m=ir[rt])!=null?m:ir.en)(e)])!=null?g:e===1?t:n}var Qe=()=>rt,pr=e=>ur(e);function kn(e,t=!0){var n;if(rt=It.some(r=>r.code===e)?e:"en",Mn=(n=Ms[rt])!=null?n:[],document.documentElement.lang=rt,t)try{localStorage.setItem(lr,rt)}catch{}cr.forEach(r=>r())}function fr(e){cr.push(e)}function _s(){try{return localStorage.getItem(lr)}catch{return null}}Object.assign(globalThis,{_:ur,N_:Cs});var ar;kn(ks(_s(),(ar=navigator.languages)!=null&&ar.length?navigator.languages:[navigator.language]),!1);var hr={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 Gt(e,t="dl-icon"){var r;let n=(r=hr[e])!=null?r:hr.phone;return``}function mr(e,t){let n=r=>{r==null||r===!1||(Array.isArray(r)?r.forEach(n):e.appendChild(typeof r=="string"?document.createTextNode(r):r))};t.forEach(n)}function s(e,t={},...n){let r=document.createElement(e);for(let[o,i]of Object.entries(t))i==null||i===!1||(o.startsWith("on")&&typeof i=="function"?r.addEventListener(o.slice(2),i):o==="class"?r.className=String(i):i===!0?r.setAttribute(o,""):r.setAttribute(o,String(i)));return mr(r,n),r}function We(e,...t){e.replaceChildren(),mr(e,t)}function Re(e){let t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstElementChild}var W=(e,t="i")=>Re(Gt(e,t));var Ae=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function ot(e,t,n=1){let r=Math.sqrt(e/n),o=t/(2*Math.sqrt(e*n)),i=f=>{if(o<.999){let O=r*Math.sqrt(1-o*o);return 1-Math.exp(-o*r*f)*(Math.cos(O*f)+o*r/O*Math.sin(O*f))}if(o<=1.001)return 1-Math.exp(-r*f)*(1+r*f);let E=Math.sqrt(o*o-1),x=-r*(o-E),b=-r*(o+E);return 1-(b*Math.exp(x*f)-x*Math.exp(b*f))/(b-x)},l=0;for(let f=0;f<3;f+=.004)Math.abs(1-i(f))>.0015&&(l=f);l+=.004;let m=[];for(let f=0;f<=64;f++)m.push(+i(l*f/64).toFixed(4));m[64]=1;let g=Math.round(l*1e3);return{duration:g,easing:`linear(${m.join(", ")})`,at:f=>f>=g?1:i(f/1e3)}}var Te=ot(300,20),U=ot(300,35),xe=ot(520,24),vr=ot(520,46),Le=ot(380,28),gr=ot(900,60),j="cubic-bezier(0.23, 1, 0.32, 1)",Z="cubic-bezier(0.55, 0, 1, 0.45)",Cn="cubic-bezier(0.32, 0.72, 0, 1)";function yr(e){e.style.setProperty("--spring-bouncy",Te.easing),e.style.setProperty("--spring-bouncy-dur",`${Te.duration}ms`),e.style.setProperty("--spring-smooth",U.easing),e.style.setProperty("--spring-smooth-dur",`${U.duration}ms`),e.style.setProperty("--spring-soft",Le.easing),e.style.setProperty("--spring-soft-dur",`${Le.duration}ms`),e.style.setProperty("--spring-quick",gr.easing),e.style.setProperty("--spring-quick-dur",`${gr.duration}ms`)}function $(e,t,n){var r;return Ae()?t.some(o=>"opacity"in o)?e.animate(t.map(o=>"opacity"in o?{opacity:o.opacity}:{}),{duration:Math.min(Number((r=n.duration)!=null?r:200),160),easing:"ease-out",fill:n.fill}):e.animate(t,{...n,duration:0,delay:0}):e.animate(t,n)}function br(e,t){return e<=0||t<=0?0:(1-1/(e*.55/t+1))*t}function xr(e,t,n){return e<=0||t<-.1?!1:t>.4||e>n/3}function Es(){return(typeof document=="undefined"?"":document.documentElement.lang)||"en"}function Ce(){let e=Es();return e==="en"?"en-GB":e}function N(e,...t){let n=0;return e.replace(/%([%sd])/g,(r,o)=>{var i;return o==="%"?"%":String((i=t[n++])!=null?i:"")})}function we(e,t){return e.toLocaleString(Ce(),t===void 0?void 0:{minimumFractionDigits:t,maximumFractionDigits:t})}function ze(e,t,n){return N(N_(e,t,n),we(e))}function st(e,...t){let n=0;return e.split(/(%[%sd])/).filter(Boolean).map(r=>r==="%%"?"%":r==="%s"||r==="%d"?t[n++]:r)}function Ts(e,t,n){let r=0;for(;e>=n&&r=100||r===0?we(Math.round(e)):we(e,1)} ${t[r]}`}function Be(e){return Ts(!e||e<0?0:e,[_("B"),_("KB"),_("MB"),_("GB"),_("TB")],1024)}function wr(e,t=Date.now()/1e3){if(!e)return _("never");let n=Math.max(0,Math.round(t-e));return n<60?_("just now"):n<3600?N(_("%s min ago"),Math.floor(n/60)):n<86400?N(_("%s h ago"),Math.floor(n/3600)):n<86400*30?N(_("%s d ago"),Math.floor(n/86400)):new Date(e*1e3).toLocaleDateString(Ce(),{day:"numeric",month:"short",year:"numeric"})}function Wt(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function Se(e){let[t,n,r]=e.split("-").map(Number);return new Date(t,(n||1)-1,r||1,12)}function Ls(e){return(typeof e=="string"?/^\d{4}-\d{2}-\d{2}$/.test(e)?Se(e):new Date(e):e).toLocaleDateString(Ce(),{day:"numeric",month:"short",year:"numeric"})}function zt(e){return e?Ls(e):""}function As(e,t){let n=r=>{let[o,i,l]=r.split("-").map(Number);return Date.UTC(o,i-1,l)};return Math.round((n(e)-n(t))/864e5)}function it(e,t){let n=Se(e);return n.setDate(n.getDate()+t),Wt(n)}function qt(e,t=Date.now()){if(!e)return null;let n=typeof t=="number"?Wt(new Date(t)):t,r=As(e,n);return r>=0?r+1:r}function wt(e,t){return t!=null&&t>0&&e.expire_warn>0&&t<=e.expire_warn}function Mr(e){return e<=1?_("ends today"):e===2?_("ends tomorrow"):ze(e,"ends in %s day","ends in %s days")}function kr(e){return{lan:_("Home network"),internet:_("Internet"),both:_("Home network + Internet")}[e]}function Kt(e){return{computer:_("PC"),phone:_("Phone"),tablet:_("Tablet"),router:_("Router"),other:_("Other")}[e]}function Ut(e){let t=n=>n.disabled?3:n.online?0:n.handshake?1:2;return e.map((n,r)=>[n,r]).sort((n,r)=>t(n[0])-t(r[0])||n[1]-r[1]).map(([n])=>n)}var ce={vpn:"AmneziaVPN",awg:"AmneziaWG",wg:"WireGuard"};function _r(e,t=0){return/iPhone|iPad|iPod/.test(e)||/Macintosh/.test(e)&&t>1?"ios":/Android/.test(e)?"android":/Windows/.test(e)?"windows":/Mac OS X|Macintosh/.test(e)?"mac":/CrOS/.test(e)?"unknown":/Linux|X11/.test(e)?"linux":"unknown"}var Er=e=>/Telegram|FBAN|FBAV|Instagram|VKClient|Line\//i.test(e);function Tr(e,t){return e==="router"||t==="unknown"?!1:e==="phone"||e==="tablet"?t==="ios"||t==="android":e==="computer"?t==="windows"||t==="mac"||t==="linux":!0}function Lr(e){let t=[{id:"vpn",name:ce.vpn},{id:"awg",name:ce.awg}];return e==="off"&&t.push({id:"wg",name:ce.wg}),t}var Ft="https://github.com/amnezia-vpn/amnezia-client/releases/latest",Cr=e=>({href:e,top:_("APK file on"),main:"GitHub",mark:"github",why:_("The APK is for phones without Google Play, or where the store hides the app.")});function Ar(e,t){var l;let n=_("Download on the"),r=_("Get it on"),o=_("Official release on GitHub");return(l={vpn:{ios:{href:"https://apps.apple.com/app/amneziavpn/id1600529900",top:n,main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=org.amnezia.vpn",top:r,main:"Google Play",mark:"googleplay",alt:Cr(Ft)},windows:{href:Ft,top:o,main:_("Download for Windows"),mark:"windows"},mac:{href:Ft,top:o,main:_("Download for Mac"),mark:"apple"},linux:{href:Ft,top:o,main:_("Download for Linux"),mark:"linux"}},awg:{ios:{href:"https://apps.apple.com/us/app/amneziawg/id6478942365",top:n,main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=org.amnezia.awg",top:r,main:"Google Play",mark:"googleplay",alt:Cr("https://github.com/amnezia-vpn/amneziawg-android/releases")},windows:{href:"https://github.com/amnezia-vpn/amneziawg-windows-client/releases",top:o,main:_("Download for Windows"),mark:"windows"},mac:{href:"https://apps.apple.com/us/app/amneziawg/id6478942365",top:n,main:"Mac App Store",mark:"appstore"},linux:{href:"https://github.com/amnezia-vpn/amneziawg-tools",top:_("On GitHub"),main:"amneziawg-tools",mark:"linux"}},wg:{ios:{href:"https://apps.apple.com/app/wireguard/id1441195209",top:n,main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=com.wireguard.android",top:r,main:"Google Play",mark:"googleplay"},windows:{href:"https://www.wireguard.com/install/",top:_("Download from"),main:"wireguard.com",mark:"windows"},mac:{href:"https://apps.apple.com/app/wireguard/id1451685025",top:n,main:"Mac App Store",mark:"appstore"},linux:{href:"https://www.wireguard.com/install/",top:_("Install from"),main:"wireguard.com",mark:"linux"}}}[e][t])!=null?l:null}var Sr=e=>e==="wg"?{href:"https://openwrt.org/docs/guide-user/services/vpn/wireguard/start",top:_("OpenWrt packages"),main:"wireguard-tools",mark:"openwrt"}:{href:"https://openwrt.org/packages/start",top:_("OpenWrt packages + kmod"),main:"amneziawg-tools",mark:"openwrt"},_n=e=>e==="android",kt=e=>`${e.replace(/\.conf$/i,"")}.vpn`,qe=(...e)=>e.join(" → ");function Mt(e){return{ios:{file:qe("+",_("Create from file or archive","WireGuard app")),qr:qe("+",_("Create from QR code","WireGuard app"))},android:{file:qe("+",_("Import from file or archive","WireGuard app")),qr:qe("+",_("Scan from QR code","WireGuard app"))},mac:{file:qe("+",_("Import Tunnel(s) from File…","WireGuard app"))},windows:{file:qe(_("Add Tunnel","WireGuard app"),_("Import tunnel(s) from file…","WireGuard app"))}}[e]}function Ct(e,t="unknown"){var r;if(e==="vpn")return qe("+",_("QR code","AmneziaVPN app"));let n=(r=Mt(t))==null?void 0:r.qr;return n!=null?n:N(_("%s (Android: %s)"),Mt("ios").qr,Mt("android").qr.replace(/^.* → /,""))}function Vt(e,t="unknown"){var n;return e==="vpn"?qe("+",_("Insert","AmneziaVPN app")):((n=Mt(t))!=null?n:Mt("android")).file}var Pr=()=>N(_("Tap “%s” and connect"),_("Continue","AmneziaVPN app"));function Dr(e,t,n,r){if(t==="linux")return[[_("Open a terminal in the folder with the file"),""],[`${_("Run")} `,`sudo ${e==="wg"?"wg-quick":"awg-quick"} up ./${n}`]];let o=Vt(e,t);return[[N(_("Open %s","step"),ce[e]),""],[o.replace(/ → [^→]*$/," → "),o.replace(/^.* → /,"")],[r?_("Confirm the import and connect"):_("Pick the file and connect"),""]]}function $r(e){return{ios:"iPhone / iPad",android:"Android",windows:"Windows",mac:"Mac",linux:"Linux",unknown:_("this device")}[e]}var Hr=(e,t)=>`${e}#setup=${t}`;function Or(e){var t,n;return(n=(t=/^#setup=(d_[0-9a-f]{8})$/.exec(e))==null?void 0:t[1])!=null?n:null}var Rr=e=>`${e}#add`,Br=e=>e==="#add",En=(e,t=!1)=>(t?{phone:_("phone","on the"),tablet:_("tablet","on the"),computer:_("computer","on the"),router:_("router","on the"),other:_("device","on the")}:{phone:_("phone"),tablet:_("tablet"),computer:_("computer"),router:_("router"),other:_("device")})[e];var oe=null,pe=()=>oe;function Me(e){oe=e}var Ss=document.getElementById("app"),Nr,at=(Nr=Ss.dataset.base)!=null?Nr:"",Ir=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(at)?at.slice(1):"",lt=()=>location.origin+location.pathname,Ne=()=>{var e;return(e=oe==null?void 0:oe.today)!=null?e:Wt(new Date)},ct=()=>{var e;return(e=oe==null?void 0:oe.now)!=null?e:Date.now()/1e3},Yt=()=>_r(navigator.userAgent,navigator.maxTouchPoints),Ps=()=>(oe==null?void 0:oe.server.awg_disguise)===!1,Gr=()=>{var e;return(e=oe==null?void 0:oe.server.preset)!=null?e:Ps()?"off":"max"},Wr=()=>(oe==null?void 0:oe.https_url)||null,Je=()=>(oe==null?void 0:oe.server.name)||"Dawnline",zr=()=>{};function qr(e){zr=e}var _e=(e={})=>zr(e);var Ke=class extends Error{constructor(n,r,o){super(r);this.status=n;this.httpsUrl=o}};async function fe(e,t){let n=await fetch(`${at}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{"Accept-Language":Qe()}:{"Content-Type":"application/json","Accept-Language":Qe()},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),r=null;try{r=await n.json()}catch{}if(!n.ok)throw new Ke(n.status,r!=null&&r.error?pr(r.error):N(_("Request failed (%s)"),n.status),(r==null?void 0:r.https_url)||void 0);return r}var jt=e=>e instanceof Ke&&(e.status===404||e.status===401);var jr=xs(Vr(),1),Ds=e=>``,Yr="#0a0a0a",$s="#f2f2f2",Hs={night:[Yr,$s],day:["#ffffff",Yr]},Ln=e=>e.length>300,dt=e=>+e.toFixed(2);function Tn(e,t,n,r,o){return`M${dt(e+o)} ${dt(t)}h${dt(n-2*o)}a${o} ${o} 0 0 1 ${o} ${o}v${dt(r-2*o)}a${o} ${o} 0 0 1 -${o} ${o}h-${dt(n-2*o)}a${o} ${o} 0 0 1 -${o} -${o}v-${dt(r-2*o)}a${o} ${o} 0 0 1 ${o} -${o}z`}function Qr(e,t=3,n=!0,r="plain"){let o=Ln(e),i=r!=="plain",[l,m]=i?Hs[r]:["#fff","#000"],g=(0,jr.default)(0,o?"L":"H");g.addData(e,"Byte"),g.make();let f=g.getModuleCount(),E=f+t*2,x=n&&!o?Math.round(f*.22):0;x&&(f-x)%2&&x++;let b=(f-x)/2,O=b+x,H=(a,h)=>x>0&&a>=b&&a=b&&hi&&(h<7&&a<7||h<7&&a>=f-7||h>=f-7&&a<7),B="";if(i){let a=o?.48:.42;for(let h=0;h${Ds(i?l:"#fff")}`}let v=``;return i?`${v}${d}`:`${v}${d}`}var Jr={opacity:1,filter:"blur(0px)",transform:"none"},Os={opacity:0,filter:"blur(5px)",transform:"scale(.86)"},Xr={opacity:0,filter:"blur(5px)",transform:"scale(.6)"},Zr={duration:180,easing:Z,fill:"forwards"},Qt={duration:340,delay:70,easing:j,fill:"backwards"},eo=Qt.delay+Qt.duration,Jt=new WeakMap;function An(e){let t=getComputedStyle(e);return{opacity:t.opacity,filter:t.filter==="none"?"blur(0px)":t.filter,transform:t.transform}}function to(e){var t;for(let n of[...e.childNodes])n.nodeType===Node.TEXT_NODE&&((t=n.textContent)!=null&&t.trim())&&n.replaceWith(s("span",{},n.textContent));return[...e.children].filter(n=>!n.classList.contains("orb"))}function no(e,t){var r;let n=(r=Jt.get(e))!=null?r:[];Jt.set(e,t),n.forEach(o=>o.cancel())}function ro(e){var o;(o=e.querySelector(":scope > .orb"))==null||o.remove();let t=to(e),n=t.map(An),r=s("span",{class:"orb","aria-hidden":"true"},s("i"),s("i"));e.append(r),e.classList.add("busy"),e.setAttribute("aria-busy","true"),no(e,[...t.map((i,l)=>$(i,[n[l],Os],Zr)),$(r,[Xr,Jr],Qt)])}function oo(e){let t=e.querySelector(":scope > .orb"),n=to(e),r=[...t?[$(t,[An(t),Xr],Zr)]:[],...n.map(o=>$(o,[An(o),Jr],Qt))];no(e,r),e.removeAttribute("aria-busy"),Promise.all(r.map(o=>o.finished)).then(()=>{Jt.get(e)===r&&(Jt.delete(e),r.forEach(o=>o.cancel()),t==null||t.remove(),e.classList.remove("busy"))},()=>{})}var so=e=>[...e].map(t=>s("i",{},t)),ut=new WeakMap,_t=e=>{var t,n,r;return(r=(n=(t=ut.get(e))==null?void 0:t.text)!=null?n:e.textContent)!=null?r:""};function Dn(e){let t=document.createRange();return t.selectNodeContents(e),t.getBoundingClientRect()}function io(e){var i;let t=e.firstChild;if(!t||t.nodeType!==Node.TEXT_NODE)return[];let n=document.createRange(),r=[],o=0;for(let l of(i=t.textContent)!=null?i:"")n.setStart(t,o),n.setEnd(t,o+l.length),r.push(n.getBoundingClientRect().left),o+=l.length;return r.map(l=>l-r[0])}function ao(e,t){let n=[...e.children];if(!n.length)return;let r=n[0].getBoundingClientRect().left;n.forEach((o,i)=>{if(!i||t[i]===void 0)return;let l=r+t[i]-o.getBoundingClientRect().left;Math.abs(l)>.01&&(o.style.marginLeft=`${l}px`)})}function Rs(e,t){let n=0;for(;nnew Array(i.length+1).fill(0));for(let g=o.length-1;g>=0;g--)for(let f=i.length-1;f>=0;f--)l[g][f]=o[g]===i[f]?l[g+1][f+1]+1:Math.max(l[g+1][f],l[g][f+1]);let m=[];for(let g=0;g=l[g][f+1]?g++:f++;for(let g=r;g>0;g--)m.push([e.length-g,t.length-g]);return m}function Xt(e){let t=ut.get(e);t&&(clearTimeout(t.timer),ut.delete(e),e.getAnimations().forEach(n=>n.cancel()),e.classList.remove("mt","mt-ib"),e.textContent=t.text)}function Pe(e,t){Xt(e),e.textContent=t}function ee(e,t,n=_t(e),r={}){var le,ue;let{whole:o=!1,at:i}=r,l=((le=r.glide)!=null?le:!0)&&!i,m=ut.has(e)?e.getBoundingClientRect().width:null;if(Xt(e),n===t||Ae()||!e.getClientRects().length){e.textContent=t;return}let g=getComputedStyle(e),f=o&&g.display==="inline";g.display==="inline"&&!o&&e.classList.add("mt-ib"),g.position==="static"&&e.classList.add("mt");let E=null,x=i!=null?i:null,b=[];x||(e.textContent=n,E=e.getBoundingClientRect(),x=Dn(e),b=io(e)),e.textContent=t;let O=e.getBoundingClientRect(),H=io(e),P=(ue=m!=null?m:E==null?void 0:E.width)!=null?ue:O.width,B=l&&!f&&!!E&&Math.abs(O.width-P)>.5,D=!B||!E||Math.abs(O.left-E.left)<.5?"start":Math.abs(O.right-E.right)<.5?"end":"middle",d=s("span",{class:o?"mt-new w":"mt-new"},o?t:so(t)),v=s("span",{class:o?"mt-old w":"mt-old","aria-hidden":"true"},o?n:so(n));o&&(v.style.width=`${x.width+1}px`),e.replaceChildren(d,v),B&&$(e,[{width:`${P}px`},{width:`${O.width}px`}],{duration:U.duration,easing:U.easing,fill:"forwards"});let a=e.getBoundingClientRect(),h=(Y,te)=>{v.style.top=`${te}px`,D==="end"?v.style.right=`${-Y}px`:D==="middle"?(v.style.left="50%",v.style.translate=`calc(-50% + ${Y}px) 0`):v.style.left=`${Y}px`},p=D==="end"?x.right-a.right:D==="middle"?(x.left+x.right-a.left-a.right)/2:x.left-a.left;h(p,x.top-a.top);let A=Dn(v);if(h(p+x.left-A.left,x.top-a.top+x.top-A.top),o){$(v,[{opacity:1,filter:"blur(0px)"},{opacity:0,filter:"blur(4px)"}],{duration:180,easing:Z,fill:"forwards"}),$(d,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"blur(0px)"}],{duration:280,delay:60,easing:j,fill:"backwards"});let Y=Math.max(340,B?U.duration:0)+40;ut.set(e,{text:t,timer:window.setTimeout(()=>Xt(e),Y)});return}ao(d,H),ao(v,b);let u=[...v.children],c=[...d.children],T=Rs([...n],[...t]),w=new Set(T.map(([Y])=>Y)),C=new Set(T.map(([,Y])=>Y));T.forEach(([Y,te])=>{let se=u[Y].getBoundingClientRect(),ne=c[te].getBoundingClientRect();u[Y].style.visibility="hidden",(Math.abs(se.left-ne.left)>.5||Math.abs(se.top-ne.top)>.5)&&$(c[te],[{transform:`translate(${se.left-ne.left}px, ${se.top-ne.top}px)`},{transform:"none"}],{duration:U.duration,easing:U.easing})});let I=u.filter((Y,te)=>!w.has(te)),G=c.filter((Y,te)=>!C.has(te)),V=Math.min(12,160/Math.max(1,I.length)),J=Math.min(22,260/Math.max(1,G.length));I.forEach((Y,te)=>$(Y,[{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:"blur(4px)",transform:"translateY(-0.45em)"}],{duration:220,delay:te*V,easing:Z,fill:"forwards"})),G.forEach((Y,te)=>$(Y,[{opacity:0,filter:"blur(4px)",transform:"translateY(0.45em)"},{opacity:1,filter:"blur(0px)",transform:"none"}],{duration:380,delay:120+te*J,easing:j,fill:"backwards"}));let re=Math.max(220+I.length*V,G.length?120+G.length*J+380:0,B||T.length?U.duration:0)+40;ut.set(e,{text:t,timer:window.setTimeout(()=>Xt(e),re)})}function Zt(e){return new Map([...e.querySelectorAll("[data-t]")].map(t=>[t.dataset.t,_t(t)]))}function en(e,t){e.querySelectorAll("[data-t]").forEach(n=>{var i;let r=t.get(n.dataset.t),o=(i=n.textContent)!=null?i:"";r!==void 0&&r!==o&&ee(n,o,r)})}var lo=e=>`${e.tagName}.${[...e.classList].filter(t=>t!=="mt"&&t!=="mt-ib").join(" ")}`,co=e=>e.outerHTML.replace(/\bgl\d+/g,"gl");function Bs(e){let t=new Map,n=(r,o)=>r.childNodes.forEach((i,l)=>{var E,x;let m=`${o}/${l}`;if(i.nodeType===Node.TEXT_NODE){if((E=i.textContent)!=null&&E.trim()){let b=document.createRange();b.selectNodeContents(i);let O=b.getBoundingClientRect();t.set(m,{kind:"#text",text:i.textContent,svg:"",at:O,words:O,node:i})}return}if(!(i instanceof Element))return;let g=i instanceof SVGElement?co(i):"",f=i instanceof HTMLElement&&!g?Dn((x=i.querySelector(":scope > .mt-new"))!=null?x:i):null;t.set(m,{kind:lo(i),text:i instanceof HTMLElement?_t(i):"",svg:g,at:i.getBoundingClientRect(),words:f,node:i}),g||n(i,m)});return n(e,""),t}var Sn=e=>$(e,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"blur(0px)"}],{duration:280,delay:60,easing:j,fill:"backwards"});function tn(e,t){var O;let n=Bs(e),r=e.getBoundingClientRect();if(We(e,t),!n.size||Ae())return;let o=e.getBoundingClientRect(),i=H=>H&&new DOMRect(H.left-r.left+o.left,H.top-r.top+o.top,H.width,H.height),l=[],m=[],g=new Set,f=(H,P,B)=>{var v;let D=H.parentElement,d=B?(v=n.get(B))==null?void 0:v.at:r;P!=null&&P.at&&P.node instanceof Element&&m.push(D&&d?[P.node,P.at,D,d]:[P.node,P.at,e,r]),l.push(()=>Sn(H))},E=(H,P,B)=>{let D=H.getBoundingClientRect(),d=P.left-r.left-(D.left-o.left),v=P.top-r.top-(D.top-o.top),a=d-B[0],h=v-B[1];return(Math.abs(a)>.5||Math.abs(h)>.5)&&$(H,[{transform:`translate(${a}px, ${h}px)`},{transform:"none"}],{duration:U.duration,easing:U.easing}),[d,v]},x=(H,P,B)=>[...H.childNodes].forEach((D,d)=>{var A,u;let v=`${P}/${d}`;g.add(v);let a=n.get(v);if(D.nodeType===Node.TEXT_NODE){let c=(A=D.textContent)!=null?A:"";if(!c.trim()||(a==null?void 0:a.kind)==="#text"&&a.text===c)return;let T=s("span",{},c);D.replaceWith(T),a!=null&&a.at&&E(T,a.at,B),l.push(()=>{var w;return(a==null?void 0:a.kind)==="#text"&&c.length<=40&&a.text.length<=40?ee(T,c,a.text,{whole:!0,at:(w=i(a.words))!=null?w:void 0}):Sn(T)});return}if(!(D instanceof Element))return;let h=D.getBoundingClientRect();if(!a||a.kind!==lo(D)||a.at&&Math.abs(a.at.height-h.height)>1&&!(D instanceof SVGElement))return f(D,a,P);let p=a.at?E(D,a.at,B):B;if(D instanceof SVGElement){a.svg!==co(D)&&l.push(()=>Sn(D));return}if(!D.children.length&&D instanceof HTMLElement){let c=(u=D.textContent)!=null?u:"";c!==a.text&&l.push(()=>{var T;return c.length<=40&&a.text.length<=40?ee(D,c,a.text,{whole:!0,at:(T=i(a.words))!=null?T:void 0}):f(D,a,P)});return}x(D,v,p)});x(e,"",[0,0]);for(let[H,P]of n)!g.has(H)&&H.lastIndexOf("/")===0&&P.at&&P.node instanceof Element&&m.push([P.node,P.at,e,r]);l.forEach(H=>H());let b=new Map;for(let[,,H]of m)!b.has(H)&&getComputedStyle(H).position==="static"&&H.classList.add("mt"),b.set(H,((O=b.get(H))!=null?O:0)+1);for(let[H,P,B,D]of m){let d=H;d.style.position="absolute",d.style.margin="0",d.style.left=`${P.left-D.left-B.clientLeft}px`,d.style.top=`${P.top-D.top-B.clientTop}px`,d.style.width=`${P.width}px`,d.style.pointerEvents="none",d.setAttribute("aria-hidden","true"),B.appendChild(d),$(d,[{opacity:1,filter:"blur(0px)"},{opacity:0,filter:"blur(4px)"}],{duration:180,easing:Z,fill:"forwards"}).onfinish=()=>{d.remove();let v=b.get(B)-1;b.set(B,v),v||B.classList.remove("mt")}}}var Ns='',Pn=()=>[W("apple"),Re(Ns)];function Is(e,t){if(e===t)return["",e,e,""];let n=e.split(" "),r=t.split(" "),o=0;for(;og?d[2]:d[1],E=d=>s("span",{class:"osm-p"},d),x=()=>{l=o.findIndex(d=>d[1]!==d[2]),l<0&&(g=0),i=o.map(d=>({pre:E(d[0]),word:E(f(d)),suf:E(d[3])})),m=l>=0?s("span",{class:"osm-ic"},Pn()[g]):null,n.replaceChildren(...i.flatMap((d,v)=>[v?s("span",{class:"arr"},"›"):null,d.pre,v===l?m:null,d.word,d.suf]).filter(d=>!!d))},b={width:"1.05em",marginRight:"0.25em"},O=d=>$(d,[{opacity:1,filter:"blur(0px)",...b},{opacity:0,filter:"blur(3px)",width:"0px",marginRight:"0px"}],{duration:220,easing:Z,fill:"forwards"}).onfinish=()=>d.remove(),H=d=>$(d,[{opacity:0,filter:"blur(3px)",width:"0px",marginRight:"0px"},{opacity:1,filter:"blur(0px)",...b}],{duration:U.duration,easing:U.easing}),P=(d,v)=>{r.setAttribute("aria-label",(d===v?d:N(_("%s (Android: %s)"),d,v.split(" → ").pop())).replace(/ → /g," › "));let a=d.split(" → "),h=v.split(" → "),p=a.map((u,c)=>{var T;return Is(u,(T=h[c])!=null?T:u)});if(!i.length||p.length!==o.length)return o=p,x();let A=l;o=p,l=o.findIndex(u=>u[1]!==u[2]),l<0&&(g=0),o.forEach((u,c)=>{ee(i[c].pre,u[0],void 0,{whole:!0}),ee(i[c].word,f(u),void 0,{whole:!0}),ee(i[c].suf,u[3],void 0,{whole:!0})}),l!==A&&(m&&O(m),m=l>=0?s("span",{class:"osm-ic"},Pn()[g]):null,m&&(i[l].word.before(m),H(m)))};P(e,t);let B=()=>{if(!r.isConnected)return clearInterval(D);if(l<0||!m||!r.offsetParent)return;g=1-g,ee(i[l].word,f(o[l]));let d=m.firstElementChild,v=Pn()[g];if(Ae()){d.replaceWith(v);return}m.appendChild(v),$(d,[{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:"blur(3px)",transform:"scale(.5) rotate(-40deg)"}],{duration:200,easing:Z,fill:"forwards"}).onfinish=()=>d.remove(),$(v,[{opacity:0,filter:"blur(3px)",transform:"scale(.5) rotate(40deg)"},{opacity:1,filter:"blur(0px)",transform:"none"}],{duration:xe.duration,delay:80,easing:xe.easing,fill:"backwards"})},D=window.setInterval(B,3e3);return{el:r,set:P}}var nn=null,Et=null,po=0,fo=(e,t,n)=>$(e,t,{duration:n,easing:Z,fill:"forwards"}).onfinish=()=>e.remove();function ke(e,t=!1){nn!=null||(nn=document.body.appendChild(s("div",{class:"toasts"}))),Et&&fo(Et,[{opacity:1},{opacity:0,transform:"scale(.96)",filter:"blur(4px)"}],140);let n=s("div",{class:`toast${t?" bad":""}`,role:"status"},W(t?"alert":"check"),s("span",{},e));nn.appendChild(n),Et=n,$(n,[{opacity:0,transform:"translateY(18px) scale(.9)",filter:"blur(6px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Te.duration,easing:Te.easing}),clearTimeout(po),po=window.setTimeout(()=>{Et===n&&(Et=null,fo(n,[{opacity:1},{opacity:0,transform:"translateY(6px) scale(.96)",filter:"blur(4px)"}],180))},2400)}function $n(e,t){var r;let n=W(t,(r=e.getAttribute("class"))!=null?r:"i");return e.replaceWith(n),$(n,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:xe.duration,easing:xe.easing}),n}function Gs(e){if(e.classList.contains("copied"))return;let t=e.querySelector("svg.i"),n=e.querySelector(".lbl, .b-main"),r=n?_t(n):"";e.classList.add("copied");let o=t?$n(t,"check"):null;n&&ee(n,_("Copied")),setTimeout(()=>{o&&t&&o.replaceWith(t),n&&ee(n,r),e.classList.remove("copied")},1600)}async function he(e,t=_("Copied"),n){try{await navigator.clipboard.writeText(e)}catch{let r=s("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let o=document.execCommand("copy");if(r.remove(),!o)return ke(_("Copying is blocked here. Select the text and copy it by hand."),!0)}n instanceof Element&&Gs(n),ke(t)}function Xe(e,t){var o;let n=navigator;if(Yt()!=="ios"||typeof n.share!="function"||typeof File=="undefined")return null;let r=new File([t],e,{type:"application/octet-stream"});return(o=n.canShare)!=null&&o.call(n,{files:[r]})?async()=>{try{await n.share({files:[r]})}catch(i){(i==null?void 0:i.name)!=="AbortError"&&rn(e,t)}}:null}function rn(e,t){let n=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),r=s("a",{href:n,download:e,class:"offscreen"});document.body.appendChild(r),r.click(),setTimeout(()=>{URL.revokeObjectURL(n),r.remove()},1e3)}function Tt(e,t){let n=Xe(e,t);n?n():rn(e,t)}async function Ze(e,t){if(e.disabled)return;e.disabled=!0,ro(e);let n=performance.now();try{await t()}finally{let r=Ae()?0:eo-(performance.now()-n);r>0&&await new Promise(o=>setTimeout(o,r)),oo(e),e.disabled=!1}}var Hn=matchMedia("(prefers-color-scheme: light)"),Ws=()=>Hn.matches?"day":"night";function On(e,t){var n,r;e.dataset.qr=t,e.classList.toggle("dense",Ln(t)),e.classList.toggle("light",Hn.matches),e.innerHTML=Qr(t,3,!0,Ws()),e.dataset.mods=String((r=(n=e.firstElementChild)==null?void 0:n.viewBox.baseVal.width)!=null?r:0)}function Lt(e,t=!1){let n=s("div",{class:`qrbox${t?" big":""}`});return On(n,e),n}Hn.addEventListener("change",()=>document.querySelectorAll(".qrbox[data-qr]").forEach(e=>{var t;(t=e.querySelector("svg.old"))==null||t.remove(),On(e,e.dataset.qr)}));function Rn(e,t){let n=Lt(e),r=s("div",{class:"words"},t),o=s("div",{class:"side"},r),i=s("div",{class:`coderow${n.classList.contains("dense")?" stacked":""}`},n,o);return{el:i,swap(l,m){let g=n.dataset.qr===l?null:n.querySelector("svg");if(g){On(n,l),i.classList.toggle("stacked",n.classList.contains("dense"));let E=n.querySelector("svg");g.classList.add("old"),n.appendChild(g),$(E,[{opacity:0},{opacity:1}],{duration:200,easing:j}),$(g,[{opacity:1},{opacity:0}],{duration:220,delay:110,easing:Z,fill:"forwards"}).onfinish=()=>g.remove()}if(!m)return;let f=r;r=s("div",{class:"words"},m),o.appendChild(r),f.classList.add("old"),$(r,[{opacity:0,filter:"blur(3px)"},{opacity:1,filter:"blur(0px)"}],{duration:220,easing:j}),$(f,[{opacity:1,filter:"blur(0px)"},{opacity:0,filter:"blur(3px)"}],{duration:200,delay:90,easing:Z,fill:"forwards"}).onfinish=()=>f.remove()}}}function pt(e){let t=typeof navigator.share=="function";return s("div",{class:"linkrow"},s("span",{class:"mono"},e.replace(/^https?:\/\//,"")),s("button",{type:"button",class:"knob","aria-label":_("Copy the link"),onclick:n=>he(e,_("Link copied"),n.currentTarget)},W("copy")),t?s("button",{type:"button",class:"knob","aria-label":_("Share the link"),onclick:()=>navigator.share({url:e,title:Je()}).catch(()=>{})},W("share")):null)}var et=null,Ie=null,At=()=>!!et;function De(e=!1){let t=et;if(t){if(et=null,Ie==null||Ie.setAttribute("aria-expanded","false"),Ie=null,e){t.remove();return}$(t,[{opacity:1},{opacity:0,transform:"scale(.96)",filter:"blur(3px)"}],{duration:120,easing:Z,fill:"forwards"}).onfinish=()=>t.remove()}}function on(e,t){var f,E;if(Ie===e&&et)return De();De(!0);let n=t.filter((x,b)=>x||b>0&&t[b-1]&&t.slice(b+1).some(Boolean)),r=s("span",{class:"menu-hl"}),o=s("div",{class:"menu",role:"menu"},r);for(let x of n){if(!x){o.appendChild(s("div",{class:"menu-sep"}));continue}let b=s("button",{type:"button",role:x.checked===void 0?"menuitem":"menuitemradio","aria-checked":x.checked===void 0?null:String(x.checked),class:`mi ${(f=x.tone)!=null?f:""}`,onclick:()=>{De(),x.run()}},x.checked===void 0?W((E=x.icon)!=null?E:""):W("check",x.checked?"i":"i off"),s("span",{},x.label));b.addEventListener("pointerenter",()=>{var O;r.className=`menu-hl${r.style.opacity==="1"?" moving":""} ${(O=x.tone)!=null?O:""}`,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 i=e.getBoundingClientRect(),l=o.offsetWidth,m=o.offsetHeight,g=i.bottom+8+m{let t=e.target;et&&!et.contains(t)&&!(Ie!=null&&Ie.contains(t))&&De()});addEventListener("scroll",()=>De(),{passive:!0});var de,$e,F,Bn,mt,Fe,ae,Ue=[],sn=null,Nn=null,St=!1,ft=null,He=()=>!!(de!=null&&de.classList.contains("open")),gt=400,ho=80,zs=3.2,vt=()=>matchMedia("(min-width: 760px)").matches,ht=gt,In=null;function yt(){var o;if(!de||!He())return null;if(!vt())return F.style.maxWidth&&(F.style.maxWidth=""),ht=gt,null;let e=[...ae.querySelectorAll(".qrbox.dense")].find(i=>{let l=i.closest(".acc-row");return i.offsetWidth&&(!l||l.classList.contains("open"))&&!i.closest(".leaving")}),t=gt;if(e){let i=Math.min(innerWidth-32-ho,innerHeight-120);t=Math.max(gt,Math.round(Math.min(+((o=e.dataset.mods)!=null?o:0)*zs,i)+ho))}let n=e&&e!==In?e:null;if(In=e!=null?e:null,Math.abs(t-ht)<8)return n?{from:t,want:t,reveal:n}:null;let r=parseFloat(getComputedStyle(F).maxWidth)||ht;return ht=t,F.getAnimations().filter(i=>{var l;return(l=i.effect)==null?void 0:l.getKeyframes().some(m=>"maxWidth"in m)}).forEach(i=>i.cancel()),F.style.maxWidth=`${t}px`,{from:r,want:t,reveal:n}}function bt(e){if(!e)return;Math.abs(e.from-e.want)>1&&$(F,[{maxWidth:`${e.from}px`},{maxWidth:`${e.want}px`}],{duration:U.duration,easing:U.easing});let t=e.reveal;t&&setTimeout(()=>{if(!t.isConnected)return;let n=Fe.getBoundingClientRect(),r=t.getBoundingClientRect(),o=r.bottom>n.bottom-16?r.bottom-n.bottom+16:r.topme()},W("x")),mt=s("div",{class:"sheet-acts"}),ae=s("div",{class:"vp"}),Fe=s("div",{class:"sheet-scroll"},ae),F=s("div",{class:"sheet",role:"dialog","aria-modal":"true"},Bn,mt,Fe),$e=s("div",{class:"scrim",onclick:()=>me()}),de=s("div",{class:"sheet-root","aria-hidden":"true"},$e,F),document.body.appendChild(de),new ResizeObserver(()=>bt(yt())).observe(ae),Us()}function mo(e){F.setAttribute("aria-label",e.label),Bn.setAttribute("aria-label",_("Close")),F.setAttribute("role",e.asks?"alertdialog":"dialog"),F.classList.toggle("asks",!!e.asks)}function an(){let e=Nn;Nn=null,e==null||e()}function go(e){Nn=e}function tt(e){sn=e}function ge(e){if(de||qs(),De(!0),an(),He()){Ue=[e],Gn(e());return}ft=document.activeElement instanceof HTMLElement?document.activeElement:null,Ue=[e],sn=null,ht=gt,In=null,F.style.maxWidth="",F.classList.remove("arrived");let t=e();ae.replaceChildren(t.el),vo(t,!1),mo(t),de.classList.add("open"),de.setAttribute("aria-hidden","false"),document.body.classList.add("locked");let n=yt();if(n&&bt({...n,from:n.want}),F.getAnimations().forEach(r=>r.cancel()),$e.getAnimations().forEach(r=>r.cancel()),F.style.transform="",vt()?$(F,[{opacity:0,transform:"scale(.9)",filter:"blur(4px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Le.duration,easing:Le.easing}):$(F,[{transform:"translateY(calc(100% + 40px))"},{transform:"none"}],{duration:500,easing:Cn}),$($e,[{opacity:0},{opacity:1}],vt()?{duration:Le.duration,easing:Le.easing}:{duration:420,easing:"ease-out"}),!St)try{history.pushState({sheet:!0},""),St=!0}catch{}}function me(e=!1){if(!He()||de.dataset.closing)return;an(),St&&(St=!1,history.back()),document.body.classList.remove("locked");let t=()=>{de.classList.remove("open"),de.setAttribute("aria-hidden","true"),delete de.dataset.closing,F.style.transform="",$e.style.opacity="",F.getAnimations().forEach(i=>i.cancel()),$e.getAnimations().forEach(i=>i.cancel()),ae.getAnimations().forEach(i=>i.cancel()),ae.replaceChildren(),mt.replaceChildren(),F.classList.remove("arrived"),F.style.maxWidth="",ht=gt,Ue=[],ft!=null&&ft.isConnected&&ft.focus({preventScroll:!0}),ft=null;let o=sn;sn=null,o==null||o()};if(e)return t();de.dataset.closing="1";let n=getComputedStyle(F).transform;F.getAnimations().forEach(o=>o.cancel()),$($e,[{opacity:getComputedStyle($e).opacity},{opacity:0}],vt()?{duration:120,easing:Z,fill:"forwards"}:{duration:320,easing:"ease-out",fill:"forwards"});let r=n==="none"?"none":n;$(F,vt()?[{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))"}],vt()?{duration:120,easing:Z,fill:"forwards"}:{duration:420,easing:Cn,fill:"forwards"}).onfinish=t}addEventListener("popstate",()=>{He()&&(St=!1,me())});function vo(e,t=!0){var o;let n=(o=e.acts)!=null?o:null,r=mt.firstElementChild;if(n!==r){if(!t||r&&n&&r.dataset.key===n.dataset.key)return mt.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&&(mt.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 Gn(e){mo(e),vo(e),F.classList.remove("arrived");let t=[...ae.children],n=ae.getBoundingClientRect().height;ae.getAnimations().forEach(i=>i.cancel()),t.forEach(i=>{i.classList.add("leaving"),Object.assign(i.style,{position:"absolute",left:"0",right:"0",top:"0",pointerEvents:"none"}),i.inert=!0}),ae.appendChild(e.el),e.el.style.pointerEvents="none",setTimeout(()=>e.el.style.pointerEvents="",320),Fe.scrollTop=0;let r=yt(),o=e.el.getBoundingClientRect().height;$(ae,[{height:`${n}px`},{height:`${o}px`}],{duration:360,easing:"cubic-bezier(.25,1,.5,1)"}),bt(r),t.forEach(i=>$(i,[{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=()=>i.remove()),$(e.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 ln(e){if(!He())return ge(e);an(),Ue.push(e),Gn(e())}function Ks(){Ue.length<2||(an(),Ue.pop(),Gn(Ue[Ue.length-1]()))}function yo(e,t=[]){if(!He())return e();let n=ae.getBoundingClientRect().height;ae.getAnimations().forEach(g=>g.cancel());let r=ae.lastElementChild,o=new Map;r==null||r.querySelectorAll("*").forEach(g=>{(!(g instanceof SVGElement)||g instanceof SVGSVGElement)&&o.set(g,g.getBoundingClientRect())}),e();let i=yt(),l=ae.getBoundingClientRect().height;Math.abs(l-n)>1&&$(ae,[{height:`${n}px`},{height:`${l}px`}],{duration:U.duration,easing:U.easing}),bt(i);let m=new Set;for(let[g,f]of o){if(!g.isConnected||!f.width||!f.height)continue;let E=g.getBoundingClientRect();if(!E.width||!E.height)continue;let x=f.left-E.left,b=f.top-E.top;if(Math.abs(x)<.5&&Math.abs(b)<.5)continue;m.add(g);let O=g.parentElement;for(;O&&O!==r&&!m.has(O);)O=O.parentElement;O&&O!==r||$(g,[{transform:`translate(${x}px, ${b}px)`},{transform:"none"}],{duration:U.duration,easing:U.easing})}for(let g of t)g&&$(g,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:j})}function bo(){F==null||F.classList.add("arrived")}var xo=()=>Fe==null?void 0:Fe.scrollTo({top:0,behavior:"smooth"}),Wn=e=>He()&&ae.contains(e)&&!e.closest(".leaving");function Us(){let e=null;F.addEventListener("pointerdown",n=>{let r=n.target;!r.closest(".vhead")||r.closest("button, a, input")||(e={y:n.clientY,t:performance.now(),dy:0,v:0},F.setPointerCapture(n.pointerId))}),F.addEventListener("pointermove",n=>{if(!e)return;let r=n.clientY-e.y,o=performance.now(),i=r>0?r:-br(-r,F.offsetHeight);e.v=(i-e.dy)/Math.max(1,o-e.t),e.dy=i,e.t=o,F.style.transform=`translateY(${i}px)`,$e.style.opacity=String(Math.max(0,1-Math.max(0,i)/420))});let t=()=>{if(!e)return;let{dy:n,v:r}=e;if(e=null,xr(n,r,F.offsetHeight))return me();let o=F.style.transform;F.style.transform="",$e.style.opacity="",n!==0&&$(F,[{transform:o},{transform:"none"}],{duration:U.duration,easing:U.easing})};F.addEventListener("pointerup",t),F.addEventListener("pointercancel",t)}function Ee(e,t={}){return s("div",{class:`vhead${t.back?" center":""}${t.acts?" with-acts":""}`},t.back?s("button",{type:"button",class:"knob back","aria-label":_("Back"),onclick:Ks},W("chevron")):null,s("h2",{},e))}var Ge=e=>s("p",{class:"vsub"},e),Ve=(...e)=>s("p",{class:"hint"},...e);function wo(){ge(()=>{let e=lt();return{el:s("div",{class:"view"},Ee(_("Open on another device")),Ge(_("Point its camera at the code: this page opens there.")),Lt(e,!0),pt(e)),label:_("Open on another device")}})}var Fs='',dn=null,Pt=null,cn=null;function zn(e){if(Pt)return Pt;dn=s("header",{class:"crumbs"}),Pt=s("div",{class:"page-body"}),e.replaceChildren(s("div",{class:"edge-fade top","aria-hidden":"true"}),s("div",{class:"edge-fade bot","aria-hidden":"true"}),cn=s("main",{class:"page"},dn,Pt));let t=()=>document.body.classList.toggle("scrolled",scrollY>2);return addEventListener("scroll",t,{passive:!0}),t(),Pt}function qn(e){cn==null||cn.classList.toggle("single",e)}function Vs(){let e=s("button",{type:"button",class:"cr-lang","aria-label":_("Language"),"aria-haspopup":"menu","aria-expanded":"false"},s("span",{},Qe().toUpperCase()),W("chevron","i cr-down"));return e.addEventListener("click",()=>on(e,It.map(t=>({label:t.name,checked:t.code===Qe(),run:()=>t.code!==Qe()&&kn(t.code)})))),e}function Kn(e=!1,t=!1){var o;if(!dn)return;let n=e?null:(o=pe())==null?void 0:o.person,r=s("span",{class:n?"":"cur","aria-current":n?null:"page"},Je());dn.replaceChildren(s("span",{class:"cr-mark"},Re(Fs)),s("nav",{class:"cr-path","aria-label":_("Breadcrumb")},r,n?[W("chevron"),s("span",{class:"cur","aria-current":"page"},n.name)]:null),...t?[]:[Vs()],...n&&!t?[s("button",{type:"button",class:"knob cr-qr","aria-label":_("Open on another device"),onclick:wo},W("qr"))]:[])}function ko(e,t,n=10){let r=m=>(Se(m).getDay()+6)%7,o=it(e,-r(e)),i=it(t,6-r(t)),l=[];for(let m=o;m<=i;m=it(m,1))if(l.push({day:m,kind:mn*7)return null;return l}var Ys=/^([01]?\d|2[0-3]):([0-5]\d)$/;function Mo(e){let t=Ys.exec(e.trim());return t?+t[1]*60+ +t[2]:null}var Dt=e=>(e%1440+1440)%1440,nt=e=>`${String(Math.floor(Dt(e)/60)).padStart(2,"0")}:${String(Dt(e)%60).padStart(2,"0")}`;function un(e,t,n){let[r,o]=e.split("-"),i=Mo(r!=null?r:""),l=Mo(o!=null?o:"");if(i==null||l==null)return null;let m=t==null?0:n-t;return{from:Dt(i+m),to:Dt(l+m),yours:t!=null}}var Co=e=>e.fromDt(Math.floor(e/60)+t);function Eo(e){let t=Se(e);return{days:new Date(t.getFullYear(),t.getMonth()+1,0).getDate(),day:t.getDate()}}var To={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:''}},js=()=>Gt("amnezia","").replace(/^]*>/,"").replace(/<\/svg>$/,""),Qs=0;function Js(e,t="grey",n="gi"){var l;let r=(l=To[e])!=null?l:To.other,o=`gl${++Qs}`,i=r.d===null?`${js()}`:`${r.d}`;return``}var Q=(e,t="grey",n="gi")=>Re(Js(e,t,n));function pn(e,t,n,r){return s("div",{class:`notice ${e}`},Q(t,e==="bad"?"red":"orange"),s("div",{class:"t"},n?s("b",{},n):null,s("span",{},r)))}function Xs(e){var r;let t=un(e,(r=pe())==null?void 0:r.tz_offset,-new Date().getTimezoneOffset());if(!t)return N(_("%s (router time)"),e.replace("-","–"));let n=`${nt(t.from)}–${nt(t.to)}`;return N(t.yours?_("%s your time"):_("%s (router time)"),n)}function Un(e){switch(e.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"),N(_("Open %s."),Xs(e.hours))];default:return["pause",_("Access paused"),_("Your devices can’t connect until it’s resumed.")]}}function Lo(e){if(e.state!=="active")return pn(e.state==="quota"||e.state==="expired"?"bad":"warn",...Un(e));let t=qt(e.expires,Ne());return wt(e,t)?pn("warn","calendar",N(_("Access %s"),Mr(t)),N(_("On %s."),zt(e.expires))):null}var Ao=3,So=e=>e.reduce((t,[n,r])=>[t[0]+n,t[1]+r],[0,0]);function Zs(e,t){let n=Math.max(1,...e.map(l=>l[1])),r=Math.max(1,...e.map(l=>l[0])),o=Math.round((t-Ao)*Math.min(.8,Math.max(.55,n/(n+r)))),i=t-Ao-o;return{top:o,bottom:i,scale:Math.min(o/n,i/r)}}function fn(e,t,n,r=0){let{top:o,bottom:i,scale:l}=Zs(e,n),m=(E,x,b,O)=>{let H=s("i",{class:O});H.style.height=`${Math.max(2,Math.round(b*l))}px`;let P=s("div",{class:`half ${E}`},H);return P.style.height=`${x}px`,P},g=s("div",{class:`bars ${t}`,"aria-hidden":"true"});g.style.height=`${n}px`;let f=e.map(([E,x],b)=>g.appendChild(s("div",{class:`col${b===e.length-1?" today":""}`},m("top",o,x,"dn"),m("bottom",i,E,"up"))));for(let E=0;Es("span",{class:o,title:i},W("arrow"),s("span",{class:"offscreen"},i),l),n=s("span",{class:"num","data-t":`${e}:dn`}),r=s("span",{class:"num","data-t":`${e}:up`});return{el:s("span",{class:"ud"},t("ud-dn",_("Downloaded"),n),t("ud-up",_("Uploaded"),r)),set([o,i]){Pe(n,Be(i)),Pe(r,Be(o))}}}function ei(e){let t=s("div",{class:"view"},Ee(_("Open the link securely")),Ge(_("Connection settings only travel encrypted")),s("div",{class:"center-col secure"},Q("lock","blue","gi xl"),s("p",{},_("This page is open without encryption. To add or set up a device, open the same link over HTTPS:"))),s("a",{class:"btn accent block",href:e},W("lock"),s("span",{},_("Open securely"))),Ve(_("The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).")));return t.lastElementChild.classList.add("secure-note"),{el:t,label:_("Open the link securely")}}var $t=e=>ge(()=>ei(e));function xt(){let e=Wr();return e?($t(e),!0):!1}var ti={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:""},ni={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 ri(e){let t={};for(let[n,r]of Object.entries(ni))e[n]!=null&&e[n]!==""&&(t[r]=String(e[n]));return t}function oi(e,t){var g;let n=e.amnezia,r=(g=n.obfuscation)!=null?g:{},o=f=>r[f]!=null&&r[f]!==""?String(r[f]):ti[f],i=n.host.replace(/^\[(.*)\]$/,"$1"),l={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"),...ri(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:e.conf.replace(/\r?\n/g,`\r -`),hostName:i,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},m={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(l),port:String(n.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return n.dns[0]&&(m.dns1=n.dns[0]),n.dns[1]&&(m.dns2=n.dns[1]),m}function si(e){let t="";for(let n=0;ne.replace(/^vpn:\/\//,"");var Do=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"];function Ye(e,t={}){let n=s("div",{class:`acc${t.inset?" inset":""}`}),r=e.map((f,E)=>{var D;let x=f.body.filter(d=>!!d),b=!x.length,O=[f.icon,s("span",{class:"acc-title"},s("span",{class:"t"},f.title),(D=f.tag)!=null?D:null),f.val?s("span",{class:`acc-val${f.valHide?" hide-open":""}`},f.val):null],H=E===t.open&&!b,P=b?s("div",{class:"acc-head"},...O):s("button",{type:"button",class:"acc-head","aria-expanded":String(H),onclick:()=>g(B)},...O,W("chevron","i acc-chev")),B=s("div",{class:`acc-row${b?" still":""}${H?" open":""}`},P,s("div",{class:"acc-body"},...x));return n.appendChild(B),B}),o=f=>f.querySelector(".acc-body"),i=()=>r.forEach((f,E)=>{let x=f.classList.contains("open");f.classList.toggle("rt",E===0||x||r[E-1].classList.contains("open")),f.classList.toggle("rb",E===r.length-1||x||r[E+1].classList.contains("open"))}),l=f=>{let E=getComputedStyle(f),x={};for(let b of Do)x[b]=b==="height"?`${f.getBoundingClientRect().height}px`:E[b];return x},m=()=>r.forEach(f=>{var E;return(E=f.querySelector("button.acc-head"))==null?void 0:E.setAttribute("aria-expanded",String(f.classList.contains("open")))});function g(f){var H;let E=r.map(l);r.forEach(P=>P.getAnimations().forEach(B=>B.cancel())),r.forEach(P=>o(P).getAnimations().forEach(B=>B.cancel()));let x=!f.classList.contains("open"),b=r.filter(P=>P.classList.contains("open")&&(P===f||x));r.forEach(P=>{P.classList.remove("closing"),P!==f&&P.classList.remove("open","opened")}),f.classList.toggle("open",x),f.classList.toggle("opened",x),i();let O=yt();r.forEach((P,B)=>{let D=l(P);Do.some(d=>E[B][d]!==D[d])&&(b.includes(P)&&P.classList.add("closing"),$(P,[E[B],D],{duration:Le.duration,easing:Le.easing}).onfinish=()=>P.classList.remove("closing"))}),b.forEach(P=>$(o(P),[{opacity:1},{opacity:0,filter:"blur(2px)"}],{duration:160,easing:Z,fill:"forwards"})),x&&$(o(f),[{opacity:0,filter:"blur(2px)"},{opacity:1,filter:"blur(0px)"}],{duration:300,easing:"cubic-bezier(0,0,.58,1)"}),bt(O),m(),(H=t.onToggle)==null||H.call(t,r.indexOf(f),x,!1)}return i(),{el:n,openIndex:()=>r.findIndex(f=>f.classList.contains("open")),setOpen(f){r.forEach((E,x)=>E.classList.toggle("open",x===f&&!E.classList.contains("still"))),i(),m(),r.forEach((E,x)=>{var b;return(b=t.onToggle)==null?void 0:b.call(t,x,E.classList.contains("open"),!0)})}}}function $o(e,t,n){let r=s("span",{class:"seg-pill"}),o=s("div",{class:"seg appseg",role:"tablist"},r),i=e.map(b=>{let O=s("button",{type:"button",class:"seg-b",role:"tab","aria-label":b.label,title:b.label,onclick:()=>x(b.value)},W(b.icon),s("span",{class:"seg-l"},b.label));return O.dataset.v=b.value,o.appendChild(O),O}),l=b=>b.querySelector(".seg-l"),m=()=>i.forEach(b=>{let O=b.dataset.v===t;b.classList.toggle("on",O),b.setAttribute("aria-selected",String(O))}),g=()=>{let b=i.find(O=>O.dataset.v===t);return b&&b.offsetWidth?[b.offsetLeft,o.clientWidth-b.offsetLeft-b.offsetWidth]:null},f=()=>{let b=g();b&&(r.style.left=`${b[0]}px`,r.style.right=`${b[1]}px`)},E=0;function x(b){if(b===t)return;let O=i.findIndex(C=>C.dataset.v===t),H=i.findIndex(C=>C.dataset.v===b),P=getComputedStyle(r),B=parseFloat(P.left)||0,D=parseFloat(P.right)||0,d=i.map(C=>parseFloat(getComputedStyle(C).flexGrow)||0),v=l(i[O]),a=v.getBoundingClientRect().width;[...i,...i.map(l)].forEach(C=>C.getAnimations().forEach(I=>I.cancel())),t=b,m(),i.forEach((C,I)=>{let G=I===H?1:0;d[I]!==G&&$(C,[{flexGrow:d[I]},{flexGrow:G}],{duration:U.duration,easing:U.easing})}),$(v,[{opacity:1,maxWidth:`${a}px`,marginLeft:"0px"},{opacity:0,maxWidth:"0px",marginLeft:"-8px"}],{duration:220,easing:"ease-out"}),$(l(i[H]),[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,delay:70,easing:j,fill:"backwards"});let h=H>O,p=Ae()?U:vr,A=performance.now(),u=Math.max(U.duration,p.duration),c=h?U:p,T=h?p:U;cancelAnimationFrame(E);let w=()=>{let C=Ae()?u:performance.now()-A,I=g();if(!I){E=0;return}r.style.left=`${B+(I[0]-B)*c.at(C)}px`,r.style.right=`${D+(I[1]-D)*T.at(C)}px`,E=C{E||f()}).observe(o),{el:o,sync(b){b!==t&&(t=b,m(),f())}}}var Ro={vpn:"amnezia",awg:"amneziawg",wg:"wireguard"},Bo=e=>`dl.app.${e.id}`;function No(e){try{let t=localStorage.getItem(Bo(e));return t==="vpn"||t==="awg"||t==="wg"?t:null}catch{return null}}function Io(e,t){try{localStorage.setItem(Bo(e),t)}catch{}}function je(e,t=!1){var i,l;let n=[s("span",{class:"b-ic"},W(e.mark)),s("span",{class:"b-t"},s("span",{class:"b-top"},e.top),s("span",{class:"b-main"},e.main)),W(e.onclick||(i=e.href)!=null&&i.startsWith("vpn:")?"chevron":"open")],r=`badge${t?" primary":""}`;if(e.onclick)return s("button",{type:"button",class:r,onclick:e.onclick},n);let o=(l=e.href)==null?void 0:l.startsWith("vpn:");return s("a",{class:r,href:e.href,target:o?null:"_blank",rel:"noopener noreferrer"},n)}function Go(e,t,n){let r=n?Sr(e):Ar(e,t);return r?r.alt?[s("div",{class:"badges2"},je(r),je(r.alt)),Ve(r.alt.why)]:[je(r)]:[Ve(N(_("Get %s on the %s and come back here."),ce[e],$r(t)))]}var Ho=e=>s("ol",{class:"howto"},e.map(([t,n])=>s("li",{},t.replace(/ → $/," ›"),n?[" ",s("b",{},n)]:null))),ai=(e,t)=>s("button",{type:"button",onclick:t},e);function Wo(e){let t=e.app(),n=ce[t],r=e.pf==="ios"||e.pf==="android",o=e.same()&&r,i=g=>he(e.key,_("Key copied"),g.currentTarget),l=t==="vpn"&&o&&!_n(e.pf)?Xe(kt(e.cfg.filename),e.key):null;if(t==="vpn"&&o&&(_n(e.pf)||l))return[je(l?{top:_("Then come back here and tap"),main:_("Send to AmneziaVPN"),mark:"amnezia",onclick:()=>void l()}:{href:e.key,top:_("Then come back here and tap"),main:_("Open in AmneziaVPN"),mark:"amnezia"},!0),Ve(...st(l?_("Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app."):_("Nothing opened? %s and add it in the app."),ai(_("Copy the key","in a sentence"),i)))];if(t==="vpn"){let g=Vt("vpn");return[je({top:_("The connection as one key"),main:_("Copy the key"),mark:"copy",onclick:i},!0),Ho([[N(_("Open %s","step"),n),""],[g.replace(/ → [^→]*$/," → "),g.replace(/^.* → /,"")],[Pr(),""]])]}let m=r?Xe(e.cfg.filename,e.cfg.conf):null;return[je(m?{top:e.same()?N(_("Straight into %s"),n):N(_("Send it to the %s"),e.there),main:_("Share the file"),mark:"share",onclick:()=>void m()}:{top:_("Then import it in the app"),main:_("Download the file"),mark:"download",onclick:()=>rn(e.cfg.filename,e.cfg.conf)},!0),Ho(Dr(t,e.pf,e.cfg.filename,!!m&&e.same()))]}function zo(e){let t=e.app(),n=(o,i,l)=>s("button",{type:"button",class:"btn soft sm",onclick:l},W(o),s("span",{class:"lbl"},i));if(t==="vpn"){let o=kt(e.cfg.filename),i=!!Xe(o,e.key);return[s("p",{class:"desc"},N(_("Send it to the %s in a message or a note, then in AmneziaVPN: %s."),e.there,Vt("vpn").replace(/ → /g," › "))),s("div",{class:"btnrow2"},n("copy",_("Copy the key"),l=>he(e.key,_("Key copied"),l.currentTarget)),n(i?"share":"download",i?_("Share as a file"):_("Download the key"),()=>Tt(o,e.key)))]}let r=!!Xe(e.cfg.filename,e.cfg.conf);return[s("p",{class:"desc"},...st(_("Send it to the %s, then import %s in %s."),e.there,s("b",{},e.cfg.filename),ce[t])),s("div",{class:"btnrow2"},n(r?"share":"download",r?_("Share the file"):_("Download the file"),()=>Tt(e.cfg.filename,e.cfg.conf)),n("copy",_("Copy the configuration"),o=>he(e.cfg.conf,_("Configuration copied"),o.currentTarget)))]}function Oo(e,t){if(/^\s*\[.+\]\s*$/.test(e))return s("span",{class:"sec"},e);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(e);if(!n)return document.createTextNode(e);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(e)?t?s("span",{class:"secret"},n[2]):s("span",{class:"mask"},"••••••••••••••••"):n[2];return s("span",{},s("span",{class:"k"},n[1])," ",o)}function qo(e){let t=!1,n=s("pre",{class:"conf"}),r=()=>n.replaceChildren(...e.conf.split(` -`).flatMap((x,b)=>b?[` -`,Oo(x,t)]:[Oo(x,t)]));r();let o=!!Xe(e.filename,e.conf),i=W("key"),l=s("span",{},_("Show key")),m=s("button",{type:"button",class:"btn soft sm",onclick:()=>{t=!t,i=$n(i,t?"x":"key"),ee(l,t?_("Hide key"):_("Show key")),r(),n.querySelectorAll(".mask, .secret").forEach(x=>$(x,[{filter:"blur(4px)",opacity:.4},{filter:"none",opacity:1}],{duration:320,easing:j}))}},i,l),g=s("button",{type:"button",class:"btn soft sm",onclick:x=>he(e.conf,_("Configuration copied"),x.currentTarget)},W("copy"),s("span",{class:"lbl"},_("Copy"))),f=s("div",{class:"filecard"},s("div",{class:"fc-row"},s("span",{class:"filecard-ic"},".conf"),s("span",{class:"t"},s("span",{class:"mono"},e.filename),s("span",{},_("For computers and routers")))),s("button",{type:"button",class:"btn accent sm block",onclick:()=>Tt(e.filename,e.conf)},W(o?"open":"download"),s("span",{},o?_("Share file"):_("Download")))),E=Ye([{icon:Q("file"),title:_("Configuration"),body:[s("div",{class:"confbar"},m,g),n]}],{inset:!0});return s("div",{class:"step-box"},f,E.el)}function Ko(e){let t=s("span",{class:"osm-p"},ce[e]),n=uo(Ct(e,"ios"),Ct(e,"android"));return{el:s("span",{class:"scanline"},s("span",{},...st(_("In %s:"),t)),n.el),set(r){ee(t,ce[r],void 0,{whole:!0}),n.set(Ct(r,"ios"),Ct(r,"android"))}}}function Uo(e){let t=s("span",{class:"tt"}),n=s("span",{class:"tt-m"}),r=s("span",{class:"hp-tip","aria-hidden":"true"},t,n),o=s("button",{type:"button",class:"hp-b",onclick:()=>Tt(e().file,e().text)},W("download")),i=s("button",{type:"button",class:"hp-b"},W("copy")),l=s("div",{class:"hpill",role:"group","aria-label":_("The connection"),"data-key":"conn"},o,i,r),m=null,g=0,f=0,E=a=>{var h;return a===i&&i.classList.contains("done")?_("Copied"):(h=a.getAttribute("aria-label"))!=null?h:""},x=(a,h)=>{n.textContent=h;let p=n.offsetWidth+20;return Math.min(a.offsetLeft+a.offsetWidth/2,l.offsetWidth+46-p/2)},b=a=>`translateX(${a}px) translateX(-50%)`,O=a=>{let h=getComputedStyle(r).transform;r.getAnimations().forEach(p=>p.cancel()),r.style.transform=b(a),$(r,[{transform:h},{transform:b(a)}],{duration:U.duration,easing:U.easing})},H=a=>ee(t,a),P=a=>{if(clearTimeout(g),m===a&&r.classList.contains("on"))return;if(m=a,r.classList.contains("on")){let p=E(a);return O(x(a,p)),H(p)}let h=()=>{let p=E(a);Pe(t,p);let A=x(a,p);r.getAnimations().forEach(u=>u.cancel()),r.style.transform=b(A),r.classList.add("on"),$(r,[{opacity:0,transform:`${b(A)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:b(A),filter:"blur(0px)"}],{duration:220,easing:j})};performance.now(){clearTimeout(g),m=null,r.classList.contains("on")&&(f=performance.now()+500,r.classList.remove("on"),$(r,[{opacity:1},{opacity:0}],{duration:120,easing:"ease-out"}))};for(let a of[o,i])a.addEventListener("pointerenter",h=>{h.pointerType==="mouse"&&P(a)}),a.addEventListener("focus",()=>{a.matches(":focus-visible")&&P(a)}),a.addEventListener("blur",B);l.addEventListener("pointerleave",B);let D=a=>{let h=W(a);i.querySelector("svg").replaceWith(h),$(h,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:xe.duration,easing:xe.easing})},d=()=>{if(m!==i||!r.classList.contains("on"))return;let a=E(i);O(x(i,a)),H(a)},v=0;return i.addEventListener("click",()=>{let a=e();he(a.text,a.msg),clearTimeout(v),i.classList.contains("done")||(i.classList.add("done"),D("check"),d()),v=window.setTimeout(()=>{i.classList.remove("done"),D("copy"),d()},1600)}),{el:l,sync(){let a=e().app;o.setAttribute("aria-label",N(_("Download %s config"),a)),i.setAttribute("aria-label",N(_("Copy %s config"),a))}}}function Vo(e){let t=s("b",{},_("Waiting for the connection")),n=s("span",{class:"ws",hidden:!0}),r=s("div",{class:"way",role:"status","aria-live":"polite"},s("div",{class:"way-row"},s("span",{class:"way-end"},W(e.kind)),s("span",{class:"way-track"},s("span",{class:"way-glow"},s("i")),s("span",{class:"way-fill"})),s("span",{class:"way-end home"},W("server"))),s("div",{class:"way-text"},s("span",{class:"t"},t,n)));return{el:r,connected(){r.classList.add("done"),ee(t,N(_("%s connected"),e.name))},gaveUp(){r.classList.add("stopped"),ee(t,_("No connection yet")),n.textContent=_("Close this and open it again to keep checking."),n.hidden=!1,$(t.parentElement,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:j})}}}function Yo(e,t=4){window.setTimeout(async()=>{var n;try{let r=await fe("state");Me(r),At()||_e(),!((n=r.person.devices.find(o=>o.id===e))!=null&&n.online)&&t>1&&Yo(e,t-1)}catch{}},1500)}function jo(e,t,n){let r=ct(),o=0,i=0,l=!1,m=Date.now(),g=async()=>{if(o=0,!l){if(Date.now()-m>6e5){l=!0,n();return}if(document.hidden)return f();try{let x=await fe("state");Me(x);let b=x.person.devices.find(O=>O.id===e.id);if(b&&b.handshake>r){l=!0,t(),b.online||Yo(e.id);return}}catch(x){if(jt(x)){l=!0;return}}i++,f()}},f=()=>{!l&&!o&&(o=window.setTimeout(g,i<6?5e3:i<12?15e3:3e4))},E=()=>{!document.hidden&&!l&&!o&&g()};return document.addEventListener("visibilitychange",E),f(),()=>{l=!0,o&&clearTimeout(o),document.removeEventListener("visibilitychange",E)}}var Fo=e=>new Promise(t=>setTimeout(t,e));async function Qo(e,t,n){e.connected(),bo(),xo(),await Fo(400),Wn(e.el)&&(t.style.overflow="hidden",$(t,[{height:`${t.offsetHeight}px`,opacity:1,filter:"none"},{height:"0px",opacity:0,filter:"blur(4px)"}],{duration:520,easing:j,fill:"forwards"}),$(e.el,[{marginBottom:"18px"},{marginBottom:"0px"}],{duration:520,easing:j,fill:"forwards"}),await Fo(2400),Wn(e.el)&&(tt(()=>_e({flash:n.id})),me()))}async function li(e){try{return await fe(`devices/${e.id}/config`)}catch(t){return t instanceof Ke&&t.httpsUrl?$t(t.httpsUrl):ke(t.message,!0),null}}async function mn(e,t){if(xt())return;let n=async()=>{let r=await li(e);if(!r)return;let o=await Fn(r,r.server);ge(()=>Xo(e,r,o))};t instanceof HTMLButtonElement?await Ze(t,n):await n()}async function gn(e,t){let n=await Fn(t,t.server);ln(()=>Xo(e,t,n))}function Jo(e,t,n){return s("div",{class:"step"},s("span",{class:"step-n"},e),s("div",{class:"step-b"},typeof t=="string"?s("span",{class:"step-t"},t):t,n))}function ci(e,t,n){let r=e.hidden?0:e.getBoundingClientRect().height;if(e.getAnimations().forEach(m=>m.cancel()),n){e.hidden=t;return}e.style.overflow="hidden",e.hidden=!1;let o=t?0:e.getBoundingClientRect().height,[i,l]=t?[1,0]:[0,1];$(e,[{height:`${r}px`,opacity:i,filter:`blur(${4-i*4}px)`},{height:`${o}px`,opacity:l,filter:`blur(${4-l*4}px)`}],{duration:U.duration,easing:U.easing}).onfinish=()=>{e.style.overflow="",e.hidden=t}}function Xo(e,t,n){var Y,te;let r=Yt(),o=Lr(Gr()),i=e.kind==="phone"||e.kind==="tablet",l=e.kind==="router",m=Tr(e.kind,r),g=m?"same":l?"router":i?"away":"pc-away",f=En(e.kind),E=En(e.kind,!0),x=o.filter(se=>!l||se.id!=="vpn"),b=(Y=No(e))!=null?Y:l?"awg":"vpn";x.some(se=>se.id===b)||(b=x[0].id);let O={d:e,cfg:t,key:n,pf:r,there:f,app:()=>b,same:()=>m},H=[],P=()=>{if(x.length<2)return null;let se=$o(x.map(ne=>({value:ne.id,label:ne.name,icon:Ro[ne.id]})),b,ne=>{b=ne,Io(e,ne),H.forEach(Bt=>Bt.sync(ne)),yo(c)});return H.push(se),se.el},B=s("span",{class:"step-t"}),D=s("div",{class:"step-box"}),d=s("div",{class:"step-box"}),v=s("div",{class:"step-box"}),a=s("div",{class:"step-box"}),h=null,p=null,A=null,u=g==="away"?Uo(()=>({...b==="vpn"?{text:n,msg:_("Key copied"),file:kt(t.filename)}:{text:t.conf,msg:_("Configuration copied"),file:t.filename},app:ce[b]})):null;function c(){ee(B,l?N(_("Get %s on the router"),ce[b]):N(_("Get %s"),ce[b]),void 0,{whole:!0}),tn(D,Go(b,r,l)),l?d.firstChild||We(d,qo(t)):tn(d,Wo(O));let se=b==="vpn"?Po(n):t.conf;h&&p&&h.el.isConnected?A!==b&&(h.swap(se),p.set(b)):(p=Ko(b),h=Rn(se,[p.el]),v.replaceChildren(h.el)),A=b,tn(a,zo(O)),u==null||u.sync()}c();let T=Hr(lt(),e.id),w=()=>[i?Rn(T,[s("span",{},_("Point its camera at the code: the link opens there."))]).el:s("p",{class:"desc"},N(_("Open this link on the %s to set it up there."),E)),pt(T)],C=()=>Jo("1",B,[P(),D]),I=()=>Jo("2",l?_("Import the configuration"):_("Add the connection"),[d]),G=s("div",{class:"setup"});if(Er(navigator.userAgent)&&G.appendChild(pn("warn","shield",null,_("Open this page in Safari or Chrome: the store opens from here, but the app handoff does not."))),g==="same"){let se=s("div",{class:"steps-wrap"},s("div",{class:"steps-gap"}),C(),I()),ne=Ye([{icon:Q("link"),title:N(_("Not on the %s right now?"),E),body:w()}],{inset:!0,onToggle:(Bt,M,k)=>ci(se,M,k)});G.append(ne.el,se)}else g==="router"?G.append(C(),I()):g==="away"?G.appendChild(Ye([{icon:Q("link"),title:N(_("Open your link on the %s"),E),body:w()},{icon:Q("app"),title:_("Already has the app"),body:[P(),v]}],{inset:!0,open:1}).el):G.appendChild(Ye([{icon:Q("link"),title:N(_("Open your link on the %s"),E),body:w()},{icon:Q("key"),title:_("Copy or save the connection"),body:[P(),a]}],{inset:!0,open:0}).el);let V=Vo(e),J=!1;go(jo(e,()=>{J||(J=!0,Qo(V,G,e))},V.gaveUp)),tt(()=>_e());let re=g==="same"?_("Two steps, about a minute"):l?_("The packages and the file for OpenWrt"):N(_("The app goes on the %s."),f),le=N(_("Set up %s"),e.name);return{el:s("div",{class:"view"},Ee(le,{acts:!!u}),Ge(re),V.el,G),label:le,acts:(te=u==null?void 0:u.el)!=null?te:null}}var ve=navigator.userAgent,ts=/iPad/.test(ve)||/Macintosh/.test(ve)&&navigator.maxTouchPoints>1;function Ot(){return ts||/Tablet/i.test(ve)||/Android/.test(ve)&&!/Mobile/.test(ve)?"tablet":/Android|iPhone|Mobile/i.test(ve)?"phone":"computer"}var di=[[/^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"]],Vn="",ui=(async()=>{var t;let e=navigator.userAgentData;if(!e||!/Android/.test(ve))return"";try{let n=((t=(await e.getHighEntropyValues(["model"])).model)!=null?t:"").trim();if(!n||n==="K")return"";let r=di.find(([o])=>o.test(n));Vn=r?`${r[1]} (${n})`:/^SM-/.test(n)?`Galaxy ${n}`:n}catch{}return Vn})();function pi(e){return/iPhone/.test(ve)?"iPhone":ts?"iPad":/Android/.test(ve)?Vn||(e==="tablet"?_("Android tablet"):_("Android phone")):/CrOS/.test(ve)?"Chromebook":/Mac OS X/.test(ve)?"Mac":/Windows/.test(ve)?_("Windows PC"):/Linux/.test(ve)?_("Linux PC"):Kt(e)}var Zo=e=>e==="mobile"?_("Mobile"):Kt(e),Ht=e=>e==="phone"||e==="tablet"?"mobile":e,es=e=>e!=="mobile"?e:Ot()==="tablet"?"tablet":"phone";function Rt(){let e=pe();if(!(!e||e.locked)){if(!e.can_add)return ke(ze(e.person.device_limit,"You have reached your limit of %s device","You have reached your limit of %s devices"),!0);xt()||ge(fi)}}function fi(){let e=pe(),t=e.person,n=["computer","mobile","router","other"].filter(d=>e.kinds.some(v=>Ht(v)===d)),r=n.includes(Ht(Ot()))?Ht(Ot()):n[0],o=!1,i=new Set(t.devices.map(d=>d.name.toLowerCase())),l=d=>{let v=d===Ht(Ot())?pi(es(d)):Kt(d==="mobile"?"phone":d);if(!i.has(v.toLowerCase()))return v;for(let a=2;a<20;a++)if(!i.has(`${v} ${a}`.toLowerCase()))return`${v} ${a}`;return v},m=s("div",{class:"kinds",role:"radiogroup","aria-label":_("What is it?")});m.style.setProperty("--n",String(n.length));let g=n.map(d=>{let v=s("button",{type:"button",class:"kind",role:"radio","aria-label":Zo(d),onclick:()=>O(d)},s("span",{class:"kind-tile"},Q(d,"blue")),s("span",{class:"kind-lbl"},Zo(d)));return m.appendChild(v),v}),f=s("input",{type:"text",maxlength:48,required:!0,"aria-label":_("Name"),autocomplete:"off"}),E=s("button",{class:"go ready",type:"submit","aria-label":_("Create connection")},W("arrow")),x=s("p",{class:"hint bad-t",hidden:!0}),b=d=>{if(!x.hidden)return ee(x,d);x.textContent=d,x.hidden=!1,$(x,[{opacity:0,transform:"translateY(-4px)"},{opacity:1,transform:"none"}],{duration:220,easing:j})};f.value=l(r),f.addEventListener("input",()=>{o=!0,E.classList.toggle("ready",!!f.value.trim()),x.hidden=!0}),ui.then(()=>{!o&&r===Ht(Ot())&&(f.value=l(r))});function O(d){r=d,g.forEach((v,a)=>{let h=n[a]===d;v.classList.toggle("on",h),v.setAttribute("aria-checked",String(h))}),o||(f.value=l(d),E.classList.add("ready"))}O(r);let H=s("form",{class:"field",autocomplete:"off"},f,E);H.addEventListener("submit",d=>{d.preventDefault();let v=f.value.trim();if(v){if(i.has(v.toLowerCase()))return b(_("You already have a device with this name."));Ze(E,async()=>{try{let a=await fe("devices",{name:v,kind:es(r)});Me(a.state),_e({pop:a.id});let h=a.state.person.devices.find(p=>p.id===a.id);await gn(h,a.config)}catch(a){if(a instanceof Ke&&a.httpsUrl)return $t(a.httpsUrl);b(a.message)}})}});let P=s("button",{type:"button",class:"btn soft block",onclick:()=>ln(hi)},W("qr"),s("span",{},_("Add it from the device"))),B=t.device_limit-t.devices.length,D=s("div",{class:"view"},Ee(_("Add a device")),Ge(N(N_(t.device_limit,"%s of %s slot free","%s of %s slots free"),we(B),we(t.device_limit))),m,Ve(_("Phones and tablets get a smaller packet size that suits mobile networks.")),H,x,s("div",{class:"or"},_("OR")),P);return D.querySelector(".hint").classList.add("kinds-note"),{el:D,label:_("Add a device")}}function hi(){let e=Rr(lt());return{el:s("div",{class:"view"},Ee(_("Open on the device"),{back:!0}),Ge(_("Point its camera at the code: your page opens there with this device ready to add.")),Lt(e,!0),pt(e)),label:_("Open on the device")}}function ns(e){let t=s("button",{type:"button",class:`btn ${e.cls}`,onclick:r=>Ze(r.currentTarget,e.run)},s("span",{},e.action));return{el:s("div",{class:"view"},s("div",{class:"ask"},Q(e.icon,e.tone,"gi xl"),s("h3",{},e.title),s("p",{},e.text),s("div",{class:"btnrow"},s("button",{type:"button",class:"btn soft",onclick:()=>me()},_("Cancel")),t))),label:e.title,asks:!0}}function rs(e){ge(()=>{let t=s("input",{type:"text",maxlength:48,"aria-label":_("Device name"),autocomplete:"off"});t.value=e.name;let n=s("button",{class:"go",type:"submit","aria-label":_("Save")},W("check"));t.addEventListener("input",()=>n.classList.toggle("ready",!!t.value.trim()&&t.value.trim()!==e.name));let r=s("form",{class:"field",autocomplete:"off"},t,n);r.addEventListener("submit",i=>{i.preventDefault();let l=t.value.trim();!l||l===e.name||Ze(n,async()=>{try{let m=await fe(`devices/${e.id}`,{action:"rename",name:l});Me(m.state),tt(()=>{_e(),ke(_("Renamed"))}),me()}catch(m){ke(m.message,!0)}})}),setTimeout(()=>t.select(),60);let o=N(_("Rename %s"),e.name);return{el:s("div",{class:"view"},Ee(o),r),label:o}})}function Yn(e){var n;if(xt())return;let t=((n=pe())==null?void 0:n.here)===e.id;ge(()=>ns({icon:"refresh",tone:"orange",title:N(_("Reconnect %s?"),e.name),text:t?_("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 fe(`devices/${e.id}`,{action:"reconnect"});Me(o.state),_e(),await gn((r=o.state.person.devices.find(i=>i.id===e.id))!=null?r:{...e,handshake:0},o.config)}catch(o){ke(o.message,!0)}}}))}function os(e){ge(()=>ns({icon:"trash",tone:"red",title:N(_("Remove %s?"),e.name),text:_("Its connection stops working at once. You can add it again later."),action:_("Remove"),cls:"red",run:async()=>{try{let t=await fe(`devices/${e.id}`,{action:"delete"});Me(t.state),tt(()=>{let n=document.querySelector(`.dev[data-id="${CSS.escape(e.id)}"]`),r=()=>{_e(),ke(_("Device removed"))};if(!n)return r();$(n,[{opacity:1,transform:"none",filter:"none"},{opacity:0,transform:"scale(.9)",filter:"blur(6px)"}],{duration:220,easing:Z,fill:"forwards"}).onfinish=r}),me()}catch(t){ke(t.message,!0)}}}))}var jn=(e,t)=>e.access!=="internet"&&e.state==="active"&&!t.disabled;function mi(e,t){return e.disabled?["",_("Disabled")]:e.config_stale&&e.handshake?["warn-t",_("Settings changed")]:e.online&&t.state==="quota"?["warn-t",_("Connected, no data left")]:e.online&&t.state==="hours"?["warn-t",_("Connected, outside your hours")]:e.online?["ok-t",_("Connected")]:e.handshake?["",N(_("Last connected %s"),wr(e.handshake,ct()))]:["warn-t",_("Not set up yet")]}function gi(e,t){return[...jn(t.person,e)?[{label:_("Copy IP address"),icon:"copy",run:()=>he(e.address,_("IP address copied"))},...e.hostname?[{label:_("Copy local address"),icon:"home",run:()=>he(e.hostname,_("Address copied"))}]:[],null]:[],...e.disabled?[]:[{label:_("Rename"),icon:"edit",run:()=>rs(e)},{label:_("Reconnect"),icon:"refresh",tone:"warn",run:()=>Yn(e)},{label:_("Remove"),icon:"trash",tone:"bad",run:()=>os(e)}]]}function vi(e){return e===0?_("Today"):e===1?_("Yesterday"):Se(it(Ne(),-e)).toLocaleDateString(Ce(),{weekday:"short",day:"numeric",month:"short"})}function yi(e){let t=So(e.spark),n=s("span",{class:"use-lbl"},_("Last 7 days")),r=hn(e.id);r.set(t);let o=fn(e.spark,"bars-week",34);return o.cols.forEach((i,l)=>{let m=e.spark.length-1-l;i.addEventListener("pointerenter",()=>{Pe(n,vi(m)),r.set(e.spark[l])}),i.addEventListener("pointerleave",()=>{Pe(n,_("Last 7 days")),r.set(t)})}),s("div",{class:"dev-use"},s("div",{class:"use-txt"},n,s("span",{class:"use-val"},r.el)),o.el)}function bi(e,t){let n=t.person,r=!!t.locked,o=t.here===e.id,[i,l]=o?["here-t",_("This device")]:mi(e,n),m=!e.handshake&&!e.disabled,g=e.config_stale&&!m&&!r&&!e.disabled,f=!o&&e.handshake&&!e.online&&!e.disabled&&!e.config_stale?new Date(e.handshake*1e3).toLocaleString(Ce()):g?_("Settings changed, update needed"):l,E=gi(e,t),x=r||!E.length?null:s("button",{type:"button",class:"knob more","aria-label":N(_("%s options"),e.name),"aria-haspopup":"menu","aria-expanded":"false"},W("more"));return x==null||x.addEventListener("click",()=>on(x,E)),s("article",{class:`dev${o?" is-here":""}${e.disabled?" off":""}`,"data-id":e.id},s("div",{class:"dev-top"},Q(e.kind,o?"blue":"grey"),s("div",{class:"dev-id"},s("span",{class:"dev-name","data-t":`${e.id}:name`},e.name),s("span",{class:`dev-stat ${i}`,title:f,"data-t":`${e.id}:stat`},l)),x),m&&r?null:m?s("button",{type:"button",class:"btn tint block setup-btn","aria-label":N(_("Set up %s"),e.name),onclick:b=>mn(e,b.currentTarget)},W("qr"),s("span",{},_("Connect"))):g?s("button",{type:"button",class:"btn tint block setup-btn","aria-label":N(_("Reconnect %s"),e.name),onclick:()=>Yn(e)},W("refresh"),s("span",{},_("Reconnect"))):yi(e))}var xi=e=>s("div",{class:"dev first","data-id":"first"},Q("plus","blue"),s("b",{},_("Add your first device")),s("p",{},_("Two steps, about a minute: get the app, then add the connection.")),s("button",{type:"button",class:"btn accent block",onclick:Rt},W("plus"),s("span",{},e?_("Add this phone"):_("Add this device")))),wi=()=>s("button",{type:"button",class:"dev add","data-id":"add",onclick:Rt},Q("plus"),s("span",{},_("Add device")));function ss(){let e=s("div",{class:"dgrid"});return Mi(e),s("section",{class:"devices",id:"devices","aria-label":_("Your devices")},s("div",{class:"sec-head"},s("h2",{},_("Your devices")),s("span",{class:"aside num"})),e,s("p",{class:"note-s limit",hidden:!0}))}function Mi(e){let t=0;new ResizeObserver(()=>{var r,o;let n=(o=(r=e.querySelector(".dev"))==null?void 0:r.getBoundingClientRect().width)!=null?o:0;Math.abs(n-t)>16&&(e.classList.add("snap"),requestAnimationFrame(()=>requestAnimationFrame(()=>e.classList.remove("snap")))),t=n}).observe(e)}function is(e,t,n={}){let r=t.person,o=e.querySelector(".dgrid"),i=o.childElementCount>0,l=new Map([...o.querySelectorAll("[data-id]")].map(D=>[D.dataset.id,D.getBoundingClientRect()])),m=Zt(o),f=Ut(r.devices).sort((D,d)=>+(d.id===t.here)-+(D.id===t.here)).map(D=>bi(D,t)),E=t.locked?0:Math.max(0,r.device_limit-r.devices.length),x=matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent);!r.devices.length&&E?f.push(xi(x)):t.can_add&&!t.locked&&f.push(wi()),o.classList.toggle("empty",!r.devices.length),o.replaceChildren(...f);for(let D of f){let d=l.get(D.dataset.id),v=D.getBoundingClientRect();D.dataset.id===n.pop?$(D,[{opacity:0,transform:"scale(.9)",filter:"blur(6px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Te.duration,easing:Te.easing}):d&&(d.left!==v.left||d.top!==v.top)?$(D,[{transform:`translate(${d.left-v.left}px, ${d.top-v.top}px)`},{transform:"none"}],{duration:U.duration,easing:U.easing}):!d&&i&&$(D,[{opacity:0,transform:"scale(.9)",filter:"blur(6px)"},{opacity:getComputedStyle(D).opacity,transform:"none",filter:"none"}],{duration:U.duration,delay:60,easing:U.easing,fill:"backwards"}),D.dataset.id===n.flash&&D.animate([{boxShadow:"inset 0 0 0 1.5px var(--ok)"},{boxShadow:"inset 0 0 0 1.5px transparent"}],{duration:1800,easing:"ease-out"})}i&&en(o,m);let b=e.querySelector(".sec-head .aside"),O=N(_("%s of %s"),we(r.devices.length),we(r.device_limit));i?ee(b,O):b.textContent=O,b.classList.toggle("warn-t",r.devices.length>r.device_limit);let H=e.querySelector(".limit"),P=H.hidden,B=t.can_add||!!t.locked;if(H.textContent=ze(r.device_limit,"You have reached your limit of %s device. Remove one to add another.","You have reached your limit of %s devices. Remove one to add another."),H.getAnimations().forEach(D=>D.cancel()),i&&!P&&B){let D=$(H,[{opacity:1,filter:"none"},{opacity:0,filter:"blur(4px)"}],{duration:200,easing:Z,fill:"forwards"});D.onfinish=()=>{H.hidden=!0,D.cancel()}}else H.hidden=B,i&&P&&!B&&$(H,[{opacity:0,transform:"translateY(6px)",filter:"blur(4px)"},{opacity:1,transform:"none",filter:"none"}],{duration:420,easing:j})}var Qn=e=>s("p",{class:"desc"},e),yn=(e,t)=>`${(e/t*100).toFixed(2)}%`,as=e=>Se(e).toLocaleDateString(Ce(),{day:"numeric",month:"short"});function ki(e){let t=(n,r,o,i)=>s("div",{class:`reach-tile${n?"":" off"}`},Q(r,n?"blue":"grey","gi rt-ic"),s("b",{},o),s("span",{class:"rt-sub"},n?i:_("Not included")),s("span",{class:"rt-mark","aria-label":n?_("Included"):_("Not included")},W(n?"check":"minus")));return s("div",{class:"reach2"},t(e!=="internet","home",_("Home network"),_("Devices at home")),t(e!=="lan","globe",_("Internet"),_("Through the router")))}function Ci(e,t){let n=Ut(e.devices).filter(m=>m.hostname&&jn(e,m));if(!n.length)return[];let r=n[0].hostname,o=r.indexOf("."),i=o>0?r.slice(o):"",l=s("span",{class:"mono"},`${_("name")}${i}`);return[s("span",{class:"lbl-s"},...st(t?_("Devices at home and on this VPN reach yours as %s"):_("Other devices at home reach yours as %s"),l)),s("div",{class:"names"},n.map(m=>{let g=m.hostname.indexOf(".");return s("button",{type:"button",class:"namechip",title:m.name,"aria-label":N(_("Copy %s"),m.hostname),onclick:f=>he(m.hostname,_("Address copied"),f.currentTarget)},s("span",{},g>0?[m.hostname.slice(0,g),s("span",{class:"faint"},m.hostname.slice(g))]:m.hostname),W("copy"))}))]}function _i(e){let t=2*Math.PI*6,n=e>=100?" bad":e>=90?" warn":"";return Re(``)}function Ei(e){let t=s("i",{class:e>=100?"bad":e>=90?"warn":""});return t.style.width=`${e.toFixed(1)}%`,s("div",{class:"meter"},t)}function Ti(e,t,n){let{days:r,day:o}=Eo(Ne()),i=Array.from({length:o},(H,P)=>{var B,D;return(D=(B=e.month_days)==null?void 0:B[P])!=null?D:[0,0]}),l=H=>as(`${Ne().slice(0,8)}${String(H).padStart(2,"0")}`),m=hn("m"),g=e.quota_limit?N(_("%s left"),Be(Math.max(0,e.quota_limit-t))):_("No limit"),f=s("span",{class:"num","data-t":"m-left"},g),E=(H,P)=>{m.set(H),Pe(f,P?l(P):g),f.classList.toggle("bad-t",!P&&e.state==="quota")};E(e.month);let x=fn(i,"bars-month",64,r-o);x.cols.forEach((H,P)=>{H.addEventListener("pointerenter",()=>E(i[P],P+1)),H.addEventListener("pointerleave",()=>E(e.month))});let b=s("span",{class:"td"},_("Today"));b.style.left=yn(o-.5,r);let O=s("div",{class:"month-axis"},s("span",{class:o<=4?"hide":""},l(1)),b,s("span",{class:o>=r-3?"hide":""},l(r)));return s("div",{class:"month"},x.el,O,s("div",{class:"month-read"},m.el,f),e.quota_limit?Ei(n):null)}function Li(e,t){let n=l=>Se(l).toLocaleDateString(Ce(),{weekday:"short",day:"numeric",month:"short"}),r=Array.from({length:7},(l,m)=>new Date(2024,0,1+m,12).toLocaleDateString(Ce(),{weekday:"narrow"})),o=ko(Ne(),e.expires),i=o?s("div",{class:"cal","aria-hidden":"true"},s("div",{class:"cal-h"},r.map(l=>s("span",{},l))),s("div",{class:"cal-g"},o.map((l,m)=>{let g=s("i",{class:l.kind,title:n(l.day)});return g.style.setProperty("--i",String(m)),g}))):null;return s("div",{class:`until${wt(e,t)?" soon":""}`},s("div",{class:"until-num"},s("b",{class:"num"},we(t)),s("span",{},N_(t,"day left","days left")),s("span",{class:"until-sub"},N(_("Ends %s"),n(e.expires)))),i)}function Ai(e,t){let n=-new Date().getTimezoneOffset(),r=un(e,t,n);if(!r)return null;let o=_o(ct(),r.yours?n:t!=null?t:n),i=Co(r),l=i.some(([f,E])=>o>=f&&os("span",{},f))))}function Si(e,t=1){let n=e.person,r=n.quota_used||n.month[0]+n.month[1],o=n.quota_limit?Math.min(100,r/n.quota_limit*100):0,i=n.quota_period==="total"&&!!n.quota_gb,l=qt(n.expires,Ne()),m=n.expires?s("span",{class:"until-val"},s("span",{class:"num","data-t":"until-date"},as(n.expires)),l!=null?s("span",{class:`num ${l<0?"bad-t":wt(n,l)?"warn-t":"ok-t"}`,"data-t":"until-left"},l>=0?ze(l,"%s day","%s days"):_("ended")):null):s("span",{},_("No end date")),g=[n.expires?l!=null&&l<0?Qn(N(_("It ended on %s."),zt(n.expires))):Li(n,l!=null?l:0):null,n.hours?Ai(n.hours,e.tz_offset):null];return Ye([{icon:Q(n.access==="internet"?"globe":n.access==="lan"?"home":"shield"),title:kr(n.access),body:[ki(n.access),...Ci(n,!!e.server.device_mesh)]},{icon:Q("chart"),title:i?_("Data used"):_("Data this month"),val:s("span",{class:"data-val"},n.quota_limit?_i(o):null,s("span",{class:"num","data-t":"data-val"},`${Be(r)} ${n.quota_limit?`/ ${Be(n.quota_limit)}`:`· ${_("no limit")}`}`)),valHide:!0,body:[i?Qn(N(_("%s of %s in total."),Be(r),Be(n.quota_limit))):Ti(n,r,o),Qn(n.quota_limit?i?_("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:Q("calendar"),title:_("Access until"),val:m,valHide:!!n.expires&&(l!=null?l:0)>=0,body:g}],{open:t})}function ls(){return s("section",{class:"access",id:"access","aria-label":_("Your access")},s("div",{class:"sec-head"},s("h2",{},_("Your access"))),s("div",{class:"acc-slot"}))}var vn=null;function cs(e,t){let n=Si(t,vn?vn.openIndex():1),r=Zt(e);e.querySelector(".acc-slot").replaceChildren(n.el),vn&&en(e,r),vn=n}yr(document.documentElement);var bn=document.getElementById("app"),Oe=null,Jn=!1,xn=()=>{};function ds(){let e=[...bn.querySelectorAll(".crumbs, .notice, .sec-head, .dgrid > *, .note-s:not([hidden]), .acc-slot .acc-row, .gone")].map(n=>({el:n,at:n.getBoundingClientRect()})).sort((n,r)=>Math.round(n.at.top)-Math.round(r.at.top)||n.at.left-r.at.left).map(n=>n.el),t=e.map(n=>getComputedStyle(n).opacity);e.forEach((n,r)=>$(n,[{opacity:0,transform:"translateY(10px)",filter:"blur(4px)"},{opacity:t[r],transform:"none",filter:"none"}],{duration:520,delay:60+r*40,easing:j,fill:"backwards"})),bn.querySelectorAll(".logo .sun").forEach(n=>$(n,[{transform:"translateY(7px)"},{transform:"none"}],{duration:900,delay:150,easing:j,fill:"backwards"})),Jn=!0}function Xn(e={}){let t=pe();if(!t)return;if(xn=Xn,t.person.state==="paused"){document.title=Je();let[r,o,i]=Un(t.person);return Zn(r,o,i,!1,"orange")}let n=zn(bn);qn(!1),Kn(),document.title=Je(),Oe||(Oe={notice:s("div",{class:"notice-slot"}),devices:ss(),access:ls()},We(n,Oe.notice,s("div",{class:"cols"},Oe.devices,Oe.access))),We(Oe.notice,Lo(t.person)),is(Oe.devices,t,e),cs(Oe.access,t),Jn||ds()}qr(Xn);function Zn(e,t,n,r=!1,o="grey"){Oe=null;let i=zn(bn);qn(!0),Kn(r,!0),We(i,s("div",{class:"gone"},Q(e,o),s("h1",{},t),s("p",{},n))),Jn||ds()}function er(){Me(null),me(!0),xn=er,Zn("key",_("This link no longer works"),_("Ask for a new one."),!0)}function us(e){xn=()=>us(e),Zn("server",_("The page could not load"),e)}function ps(){let e=pe(),t=Or(location.hash),n=Br(location.hash);if(!e||!t&&!n)return;if(history.replaceState(null,"",location.pathname+location.search),n)return Rt();let r=e.person.devices.find(o=>o.id===t);r&&!r.handshake&&!r.disabled&&!e.locked&&mn(r)}addEventListener("hashchange",ps);async function Pi(){try{Me(await fe("state")),!He()&&!At()&&Xn(),ps()}catch(e){jt(e)?er():pe()||us(e.message)}}fr(()=>{De(!0),Oe=null,xn()});document.addEventListener("keydown",e=>{e.key==="Escape"&&(At()?De(!0):He()&&me(!0))});!at||!Ir?er():Pi();})(); +"use strict";(()=>{var Si=Object.create;var Oo=Object.defineProperty;var Ai=Object.getOwnPropertyDescriptor;var Hi=Object.getOwnPropertyNames;var Di=Object.getPrototypeOf,$i=Object.prototype.hasOwnProperty;var Pi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Oi=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Hi(t))!$i.call(e,r)&&r!==n&&Oo(e,r,{get:()=>t[r],enumerable:!(o=Ai(t,r))||o.enumerable});return e};var Ri=(e,t,n)=>(n=e!=null?Si(Di(e)):{},Oi(t||!e||!e.__esModule?Oo(n,"default",{value:e,enumerable:!0}):n,e));var Lr=Pi((kr,Cr)=>{"use strict";var Er=(function(){var e=function(y,w){var p=236,u=17,l=y,v=n[w],h=null,d=0,L=null,M=[],H={},q=function(k,T){d=l*4+17,h=(function(E){for(var D=new Array(E),$=0;$=7&&Z(k),L==null&&(L=nn(l,v,M)),de(L,T)},R=function(k,T){for(var E=-1;E<=7;E+=1)if(!(k+E<=-1||d<=k+E))for(var D=-1;D<=7;D+=1)T+D<=-1||d<=T+D||(0<=E&&E<=6&&(D==0||D==6)||0<=D&&D<=6&&(E==0||E==6)||2<=E&&E<=4&&2<=D&&D<=4?h[k+E][T+D]=!0:h[k+E][T+D]=!1)},W=function(){for(var k=0,T=0,E=0;E<8;E+=1){q(!0,E);var D=r.getLostPoint(H);(E==0||k>D)&&(k=D,T=E)}return T},N=function(){for(var k=8;k>E&1)==1;h[Math.floor(E/3)][E%3+d-8-3]=D}for(var E=0;E<18;E+=1){var D=!k&&(T>>E&1)==1;h[E%3+d-8-3][Math.floor(E/3)]=D}},oe=function(k,T){for(var E=v<<3|T,D=r.getBCHTypeInfo(E),$=0;$<15;$+=1){var I=!k&&(D>>$&1)==1;$<6?h[$][8]=I:$<8?h[$+1][8]=I:h[d-15+$][8]=I}for(var $=0;$<15;$+=1){var I=!k&&(D>>$&1)==1;$<8?h[8][d-$-1]=I:$<9?h[8][15-$-1+1]=I:h[8][15-$-1]=I}h[d-8][8]=!k},de=function(k,T){for(var E=-1,D=d-1,$=7,I=0,B=r.getMaskFunction(T),G=d-1;G>0;G-=2)for(G==6&&(G-=1);;){for(var X=0;X<2;X+=1)if(h[D][G-X]==null){var ne=!1;I>>$&1)==1);var Y=B(D,G-X);Y&&(ne=!ne),h[D][G-X]=ne,$-=1,$==-1&&(I+=1,$=7)}if(D+=E,D<0||d<=D){D-=E,E=-E;break}}},ke=function(k,T){for(var E=0,D=0,$=0,I=new Array(T.length),B=new Array(T.length),G=0;G=0?Do.getAt($o):0}}for(var Po=0,Y=0;YG*8)throw"code length overflow. ("+$.getLengthInBits()+">"+G*8+")";for($.getLengthInBits()+4<=G*8&&$.put(0,4);$.getLengthInBits()%8!=0;)$.putBit(!1);for(;!($.getLengthInBits()>=G*8||($.put(p,8),$.getLengthInBits()>=G*8));)$.put(u,8);return ke($,D)};H.addData=function(k,T){T=T||"Byte";var E=null;switch(T){case"Numeric":E=f(k);break;case"Alphanumeric":E=C(k);break;case"Byte":E=g(k);break;case"Kanji":E=b(k);break;default:throw"mode:"+T}M.push(E),L=null},H.isDark=function(k,T){if(k<0||d<=k||T<0||d<=T)throw k+","+T;return h[k][T]},H.getModuleCount=function(){return d},H.make=function(){if(l<1){for(var k=1;k<40;k++){for(var T=c.getRSBlocks(k,v),E=m(),D=0;D";for(var $=0;$';E+=""}return E+="",E+="",E},H.createSvgTag=function(k,T,E,D){var $={};typeof arguments[0]=="object"&&($=arguments[0],k=$.cellSize,T=$.margin,E=$.alt,D=$.title),k=k||2,T=typeof T=="undefined"?k*4:T,E=typeof E=="string"?{text:E}:E||{},E.text=E.text||null,E.id=E.text?E.id||"qrcode-description":null,D=typeof D=="string"?{text:D}:D||{},D.text=D.text||null,D.id=D.text?D.id||"qrcode-title":null;var I=H.getModuleCount()*k+T*2,B,G,X,ne,Y="",fe;for(fe="l"+k+",0 0,"+k+" -"+k+",0 0,-"+k+"z ",Y+=''+Ce(D.text)+"":"",Y+=E.text?''+Ce(E.text)+"":"",Y+='',Y+='":T+=">";break;case"&":T+="&";break;case'"':T+=""";break;default:T+=D;break}}return T},et=function(k){var T=1;k=typeof k=="undefined"?T*2:k;var E=H.getModuleCount()*T+k*2,D=k,$=E-k,I,B,G,X,ne,Y={"██":"█","█ ":"▀"," █":"▄"," ":" "},fe={"██":"▀","█ ":"▀"," █":" "," ":" "},ce="";for(I=0;I=$?fe[ne]:Y[ne];ce+=` +`}return E%2&&k>0?ce.substring(0,ce.length-E-1)+Array(E+1).join("▀"):ce.substring(0,ce.length-1)};return H.createASCII=function(k,T){if(k=k||1,k<2)return et(T);k-=1,T=typeof T=="undefined"?k*2:T;var E=H.getModuleCount()*k+T*2,D=T,$=E-T,I,B,G,X,ne=Array(k+1).join("██"),Y=Array(k+1).join(" "),fe="",ce="";for(I=0;I>>8),v.push(L&255)):v.push(u)}}return v}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var y=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],w=1335,p=7973,u=21522,l={},v=function(h){for(var d=0;h!=0;)d+=1,h>>>=1;return d};return l.getBCHTypeInfo=function(h){for(var d=h<<10;v(d)-v(w)>=0;)d^=w<=0;)d^=p<5&&(L+=3+q-5)}for(var M=0;M=256;)l-=255;return y[l]},u})();function i(y,w){if(typeof y.length=="undefined")throw y.length+"/"+w;var p=(function(){for(var l=0;l>>7-u%8&1)==1},p.put=function(u,l){for(var v=0;v>>l-v-1&1)==1)},p.getLengthInBits=function(){return w},p.putBit=function(u){var l=Math.floor(w/8);y.length<=l&&y.push(0),u&&(y[l]|=128>>>w%8),w+=1},p},f=function(y){var w=t.MODE_NUMBER,p=y,u={};u.getMode=function(){return w},u.getLength=function(h){return p.length},u.write=function(h){for(var d=p,L=0;L+2>>8&255)*192+(M&255),h.put(M,13),L+=2}if(L>>8)},w.writeBytes=function(p,u,l){u=u||0,l=l||p.length;for(var v=0;v0&&(p+=","),p+=y[u];return p+="]",p},w},S=function(){var y=0,w=0,p=0,u="",l={},v=function(d){u+=String.fromCharCode(h(d&63))},h=function(d){if(!(d<0)){if(d<26)return 65+d;if(d<52)return 97+(d-26);if(d<62)return 48+(d-52);if(d==62)return 43;if(d==63)return 47}throw"n:"+d};return l.writeByte=function(d){for(y=y<<8|d&255,w+=8,p+=1;w>=6;)v(y>>>w-6),w-=6},l.flush=function(){if(w>0&&(v(y<<6-w),y=0,w=0),p%3!=0)for(var d=3-p%3,L=0;L=w.length){if(l==0)return-1;throw"unexpected end of file./"+l}var d=w.charAt(p);if(p+=1,d=="=")return l=0,-1;if(d.match(/^\s$/))continue;u=u<<6|h(d.charCodeAt(0)),l+=6}var L=u>>>l-8&255;return l-=8,L};var h=function(d){if(65<=d&&d<=90)return d-65;if(97<=d&&d<=122)return d-97+26;if(48<=d&&d<=57)return d-48+52;if(d==43)return 62;if(d==47)return 63;throw"c:"+d};return v},F=function(y,w){var p=y,u=w,l=new Array(y*w),v={};v.setPixel=function(M,H,q){l[H*p+M]=q},v.write=function(M){M.writeString("GIF87a"),M.writeShort(p),M.writeShort(u),M.writeByte(128),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(0),M.writeByte(255),M.writeByte(255),M.writeByte(255),M.writeString(","),M.writeShort(0),M.writeShort(0),M.writeShort(p),M.writeShort(u),M.writeByte(0);var H=2,q=d(H);M.writeByte(H);for(var R=0;q.length-R>255;)M.writeByte(255),M.writeBytes(q,R,255),R+=255;M.writeByte(q.length-R),M.writeBytes(q,R,q.length-R),M.writeByte(0),M.writeString(";")};var h=function(M){var H=M,q=0,R=0,W={};return W.write=function(N,U){if(N>>>U)throw"length over";for(;q+U>=8;)H.writeByte(255&(N<>>=8-q,R=0,q=0;R=N<0&&H.writeByte(R)},W},d=function(M){for(var H=1<>6,128|s&63):s<55296||s>=57344?o.push(224|s>>12,128|s>>6&63,128|s&63):(r++,s=65536+((s&1023)<<10|n.charCodeAt(r)&1023),o.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63))}return o}return t(e)}})();(function(e){typeof define=="function"&&define.amd?define([],e):typeof kr=="object"&&(Cr.exports=e())})(function(){return Er})});var Ro={s:{'"%s" already exists.':"Устройство «%s» уже есть.",'"%s" is already taken.':"Идентификатор «%s» уже занят.","%s (Android: %s)":"%s (на Android: %s)","%s (router time)":"%s (по времени роутера)","%s and %s overlap: each packet type needs values of its own.":"%s и %s пересекаются: у каждого типа пакетов должны быть свои значения.","%s can't use the network interface %s: it exists and isn't Dawnline's.":"Сервер %s не может использовать сетевой интерфейс %s: он уже существует и создан не Dawnline.","%s connected":"Подключено: %s","%s d ago":"%s дн. назад","%s h ago":"%s ч назад","%s has a tag that is not closed with >.":"%s: тег не закрыт символом >.",'%s has an invalid interface name "%s".':"У сервера %s недопустимое имя интерфейса «%s».","%s has no room for every device on %s.":"В подсети %s не хватит адресов для всех устройств сервера %s.","%s in total":"%s всего","%s is kept down.":"Сервер %s остановлен.","%s is kept down: its disguise has values AmneziaWG cannot take. %s":"Сервер %s остановлен: в его маскировке есть значения, которые AmneziaWG не примет. %s","%s is kept down: its disguise needs AmneziaWG %s (installed: %s).":"Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (установлен %s).","%s is kept down: its disguise needs AmneziaWG %s (installed: none).":"Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (не установлен).","%s left":"осталось %s","%s may not contain # or a line break.":"%s не может содержать # или перенос строки.","%s min ago":"%s мин назад","%s must be a number or a range like 10-100, up to 65535.":"%s: нужно число или диапазон вида 10-100, не больше 65535.","%s must be a number or a range like 100-200, up to 4294967295.":"%s: нужно число или диапазон вида 100-200, не больше 4294967295.","%s must be a number or a range like 5-15, from 1 to 65535.":"%s: нужно число или диапазон вида 5-15, от 1 до 65535.","%s must be a whole number from 0 to 65535.":"%s: нужно целое число от 0 до 65535.","%s must be at least 12 with header protection.":"%s: с защитой заголовков нужно не меньше 12.","%s must be from %d to %d.":"%s: от %d до %d.","%s must be on or off.":"%s: нужно on или off.","%s of %s":"%s из %s","%s of %s GB":"%s из %s ГБ","%s of %s GB this month":"%s из %s ГБ в этом месяце","%s of %s in total.":"Всего %s из %s.","%s options":"Действия с устройством %s","%s this month":"%s в этом месяце","%s your time":"%s по вашему времени","%s: <%s> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or .":"%s: тег <%s> не примут приложения AmneziaWG: используйте с чётным числом шестнадцатеричных цифр, , или с N от 1 до 1000 либо .","%sd %sh":"%s д %s ч","%sh %sm":"%s ч %s мин","%sm":"%s мин","A total for your whole access, it does not reset.":"Считается за весь срок доступа и не обнуляется.","APK file on":"APK-файл на","Access %s":"Доступ %s","Access ended":"Доступ закончился","Access must be lan, internet or both.":"Доступ должен быть lan, internet или both.","Access paused":"Доступ на паузе","Access until":"Доступ до",Active:"Активен","WireGuard appAdd Tunnel":"Добавить туннель","Add a device":"Добавить устройство","Add device":"Добавить устройство","Add it from the device":"Добавить с самого устройства","Add the connection":"Добавьте подключение","Add the connection again":"Добавить заново","Add this device":"Добавить это устройство","Add this phone":"Добавить этот телефон","Add your first device":"Добавьте первое устройство","Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.":"Сейчас добавить устройство нельзя: VPN-сервер не готов. Обратитесь к тому, кто прислал вам эту ссылку.","Address copied":"Адрес скопирован","Already has the app":"Приложение уже установлено","AmneziaWG is not installed (%s): install it in Dawnline → Components.":"AmneziaWG не установлен (%s): установите его в Dawnline → Компоненты.","AmneziaWG is not installed: install it in Dawnline → Components.":"AmneziaWG не установлен: установите его в Dawnline → Компоненты.","Android phone":"Телефон Android","Android tablet":"Планшет Android","Ask for a new one.":"Попросите новую.",B:"Б",Back:"Назад",Breadcrumb:"Навигационная цепочка",Cancel:"Отмена","Can’t finish connecting":"Не удаётся подключиться","Circle %s: server %s does not exist.":"Круг %s: сервера %s нет.",Close:"Закрыть","Close this and open it again to keep checking.":"Закройте окно и откройте его снова, чтобы проверить ещё раз.",Configuration:"Конфигурация","Configuration copied":"Конфигурация скопирована","Confirm the import and connect":"Подтвердите импорт и подключитесь",Connect:"Подключить",Connected:"Подключено","Connected, but no data":"Подключено, но данных нет","Connected, no data left":"Подключено, трафик закончился","Connected, outside your hours":"Подключено, вне часов доступа","Connection keeps dropping":"Связь постоянно рвётся","Connection settings only travel encrypted":"Настройки подключения передаются только в зашифрованном виде","AmneziaVPN appContinue":"Продолжить",Copied:"Скопировано",Copy:"Скопировать","Copy %s":"Скопировать %s","Copy %s config":"Скопировать конфигурацию %s","Copy IP address":"Скопировать IP-адрес","Copy local address":"Скопировать локальный адрес","Copy or save the connection":"Скопировать или сохранить подключение","Copy the configuration":"Скопировать конфигурацию","Copy the key":"Скопировать ключ","in a sentenceCopy the key":"Скопируйте ключ","Copy the link":"Скопировать ссылку","Copying is blocked here. Select the text and copy it by hand.":"Копирование здесь заблокировано. Выделите текст и скопируйте его вручную.","Create connection":"Создать подключение","WireGuard appCreate from QR code":"Создать из QR-кода","WireGuard appCreate from file or archive":"Создать из файла или архива","Cross-site request refused.":"Запрос с другого сайта отклонён.","Data limit must be a positive number of GB.":"Лимит трафика должен быть положительным числом ГБ.","Data limit reached":"Лимит трафика исчерпан","Data this month":"Трафик за месяц","Data used":"Трафик всего",Device:"Устройство","Device %s of %s: MTU %d is not between 1280 and 1500.":"Устройство %s (%s): MTU %d вне пределов от 1280 до 1500.","Device %s of %s: address %s is also used by device %s of %s.":"Устройство %s (%s): адрес %s уже занят устройством %s (%s).","Device %s of %s: address %s is not a plain IPv4 address.":"Устройство %s (%s): адрес %s не является обычным IPv4-адресом.","Device %s of %s: address %s is outside %s's tunnel %s.":"Устройство %s (%s): адрес %s вне туннеля сервера %s (%s).","Device %s of %s: address %s is the router's own address on %s.":"Устройство %s (%s): адрес %s принадлежит самому роутеру на сервере %s.","Device %s of %s: address (none) is not a plain IPv4 address.":"Устройство %s (%s): нет IPv4-адреса.","Device %s of %s: keep-alive %d is not between 0 and 600 seconds.":"Устройство %s (%s): keep-alive %d вне пределов от 0 до 600 секунд.","Device %s of %s: the preshared key is not a key.":"Устройство %s (%s): общий ключ (PSK) некорректен.","Device %s of %s: the private key is not a key.":"Устройство %s (%s): приватный ключ некорректен.","Device %s of %s: the public key is not a key.":"Устройство %s (%s): публичный ключ некорректен.","Device %s of %s: the public key is the server's own.":"Устройство %s (%s): публичный ключ совпадает с ключом сервера.","Device %s: person %s does not exist.":"Устройство %s: человека %s нет.","Device limit must be between 1 and 32.":"Лимит устройств: от 1 до 32.","Device limit reached (%d).":"Достигнут лимит устройств (%d).","Device name":"Имя устройства","Device not found.":"Устройство не найдено.","Device removed":"Устройство удалено","Devices at home":"Устройства дома","Devices at home and on this VPN reach yours as %s":"Устройства дома и в этом VPN обращаются к вашим по адресу %s",Disabled:"Отключено",Download:"Скачать","Download %s config":"Скачать конфигурацию %s","Download for Linux":"Скачать для Linux","Download for Mac":"Скачать для Mac","Download for Windows":"Скачать для Windows","Download from":"Скачать с сайта","Download on the":"Загрузите в","Download the file":"Скачать файл","Download the key":"Скачать ключ",Downloaded:"Получено","End date must be YYYY-MM-DD.":"Дата окончания должна быть в формате ГГГГ-ММ-ДД.","Endpoint must be a hostname or IP address.":"Адрес сервера должен быть именем хоста или IP-адресом.","Ends %s":"Закончится %s","Enter a device name: up to %d letters, digits, spaces and - _ .":"Введите название устройства: до %d букв, цифр, пробелов и - _ .","Except %s: those addresses lead to the home network.":"Кроме %s: эти адреса ведут в домашнюю сеть.",Expired:"Срок истёк","Extra data must be a positive number of GB.":"Дополнительный трафик должен быть положительным числом ГБ.","For computers and routers":"Для компьютеров и роутеров",GB:"ГБ","Gbit/s":"Гбит/с","Get %s":"Установите %s","Get %s on the %s and come back here.":"Установите %s на %s и вернитесь сюда.","Get %s on the router":"Установите %s на роутер","Get it on":"Доступно в","Give the device a name.":"Дайте устройству название.","Handshake complete, but no data":"Рукопожатие есть, но данных нет","Hide key":"Скрыть ключ","Home network":"Домашняя сеть","Home network + Internet":"Домашняя сеть и интернет","Hours must look like 07:00-23:00.":"Часы доступа указываются так: 07:00-23:00.","Hours, router time":"Часы доступа, время роутера","Hours, your time":"Часы доступа, ваше время","I1-I5 together must be at most 2000 characters, not %d.":"I1–I5 вместе: не больше 2000 символов, сейчас %d.","IP address copied":"IP-адрес скопирован","WireGuard appImport Tunnel(s) from File…":"Импорт туннелей из файла…","WireGuard appImport from file or archive":"Импорт из файла или архива","Import the configuration":"Импортируйте конфигурацию","Import the configuration again":"Импортировать заново","WireGuard appImport tunnel(s) from file…":"Импорт туннелей из файла…","In %s:":"В %s:",Included:"Есть доступ","AmneziaVPN appInsert":"Вставить","Install from":"Установить с сайта","Interface name: 1-12 lowercase letters, digits or _.":"Имя интерфейса: 1–12 строчных латинских букв, цифр или _.",Internet:"Интернет","Invalid JSON.":"Некорректный JSON.","Invalid public key.":"Недопустимый публичный ключ.","It connects, but the connection breaks every few minutes. Another network may help.":"Устройство подключается, но связь рвётся каждые несколько минут. Может помочь другая сеть.","It ended on %s.":"Доступ закончился %s.","It gets new keys and its current settings stop working. Set it up again with the new ones that open next.":"Устройство получит новые ключи, а текущие настройки перестанут работать. Настройте его заново с новыми - они откроются следом.","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 reaches the router, but the connection never completes. The network may be blocking it.":"Устройство доходит до роутера, но подключение не завершается. Возможно, его блокирует сеть.","Its connection stops working at once. You can add it again later.":"Подключение сразу перестанет работать. Устройство можно будет добавить снова.","Jmin must not be larger than Jmax.":"Jmin не может быть больше Jmax.",KB:"КБ","Keep-alive must be 0-600 seconds.":"Keep-alive: от 0 до 600 секунд.","Key copied":"Ключ скопирован","Key generation failed (is amneziawg-tools installed?).":"Не удалось создать ключ (установлен ли amneziawg-tools?).","Key generation failed (no random data).":"Не удалось создать ключ (нет случайных данных).","Key generation failed.":"Не удалось создать ключ.","LAN Bypass":"Обход локальной сети",Language:"Язык","Last 7 days":"За 7 дней","Last connected %s":"В сети %s","Link copied":"Ссылка скопирована","Linux PC":"Компьютер с Linux",MB:"МБ","MTU must be 1280-1500.":"MTU: от 1280 до 1500.","Mbit/s":"Мбит/с","Method not allowed.":"Метод не поддерживается.",Mobile:"Мобильный","Monthly data must be a positive number of GB.":"Месячный лимит трафика должен быть положительным числом ГБ.",Name:"Имя","No connection yet":"Подключения пока нет","No data limit. The count starts again on the 1st.":"Лимита трафика нет. Счёт начинается заново 1-го числа.","No end date":"Бессрочно","No free address left on %s.":"На сервере %s не осталось свободных адресов.","No free addresses left in the server subnet.":"В подсети сервера не осталось свободных адресов.","No limit":"Без лимита","No server":"Нет сервера","No server yet":"Сервера пока нет","Not found.":"Не найден.","Not included":"Нет доступа","Not on the %s right now?":"Открыли на другом %s?","Not set up yet":"Ещё не настроено","Nothing gets through until it resets.":"Ничего не проходит, пока лимит не обнулится.","Nothing opened? %s and add it in the app.":"Ничего не открылось? %s и добавьте его в приложении.","Now, %s":"Сейчас %s",OR:"ИЛИ","Official release on GitHub":"Официальная версия на GitHub","On %s.":"Дата окончания - %s.","On GitHub":"На GitHub","On two devices at once":"На двух устройствах сразу","Only letters, digits, - _ .":"Только буквы, цифры, - _ .","Only the admin can change how a device connects.":"Менять настройки подключения устройства может только администратор.","Only the admin can turn devices off.":"Отключать устройства может только администратор.","stepOpen %s":"Откройте %s","Open %s.":"Доступ открыт %s.","Open a terminal in the folder with the file":"Откройте терминал в папке с файлом","Open in AmneziaVPN":"Открыть в AmneziaVPN","Open on another device":"Открыть на другом устройстве","Open on the device":"Открыть на устройстве","Open securely":"Открыть по HTTPS","Open the link securely":"Откройте защищённую ссылку","Open this link on the %s to set it up there.":"Откройте эту ссылку на %s, чтобы настроить его там.","Open this link over HTTPS to get the connection settings.":"Чтобы получить настройки подключения, откройте эту ссылку по HTTPS.","Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.":"Откройте эту страницу в Safari или Chrome: магазин отсюда откроется, а передача в приложение - нет.","Open your link on the %s":"Откройте свою ссылку на %s","OpenWrt packages":"Пакеты OpenWrt","OpenWrt packages + kmod":"Пакеты OpenWrt + kmod",Other:"Другое","Other devices at home reach yours as %s":"Другие устройства дома обращаются к вашим по адресу %s","Out of data":"Трафик закончился","Outside allowed hours":"Вне часов доступа","Outside your hours":"Вне часов доступа",PC:"Компьютер",Paused:"На паузе","Person %s: circle %s does not exist.":"Человек %s: круга %s нет.","Person %s: has the same personal link as %s.":"Человек %s: личная ссылка совпадает со ссылкой человека %s.","Person %s: home service %s does not exist.":"Человек %s: домашнего сервиса %s нет.","Person %s: server %s does not exist.":"Человек %s: сервера %s нет.",Phone:"Телефон","Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app.":"Выберите AmneziaVPN в меню «Поделиться». Его там нет? %s и добавьте его в приложении.","Pick the file and connect":"Выберите файл и подключитесь","Point its camera at the code: the link opens there.":"Наведите камеру устройства на код - ссылка откроется на нём.","Point its camera at the code: this page opens there.":"Наведите камеру устройства на код - там откроется эта страница.","Point its camera at the code: your page opens there with this device ready to add.":"Наведите камеру устройства на код - там откроется ваша страница, и его можно будет сразу добавить.","Port must be 1-65535.":"Порт: от 1 до 65535.","QR code":"QR-код","AmneziaVPN appQR code":"QR-код",Reconnect:"Переподключить","Reconnect %s":"Переподключить %s","Reconnect %s?":"Переподключить «%s»?","RejectAfterTime must be at most 180 seconds.":"RejectAfterTime: не больше 180 секунд.",Remove:"Удалить","Remove %s?":"Удалить «%s»?",Rename:"Переименовать","Rename %s":"Переименовать «%s»","Request failed (%s)":"Не удалось выполнить запрос (%s)","Request too large.":"Слишком большой запрос.","Resets on the 1st.":"Обнуляется 1-го числа.","Return to save, Esc to cancel":"Return сохраняет, Esc отменяет",Router:"Роутер",Run:"Выполните","S2 must not be S1 + 56: the handshake initiation and response would have the same size.":"S2 не может равняться S1 + 56: начальный и ответный пакеты рукопожатия будут одного размера.","WireGuard appScan from QR code":"Сканировать QR-код","Send it to the %s":"Отправить на %s","Send it to the %s in a message or a note, then in AmneziaVPN: %s.":"Отправьте его на %s в сообщении или заметке, затем в AmneziaVPN: %s.","Send it to the %s, then import %s in %s.":"Отправьте его на %s, затем импортируйте %s в %s.","Send to AmneziaVPN":"Отправить в AmneziaVPN","Server is disabled":"Сервер выключен","Server is turned off":"Сервер выключен","Set it up again":"Настроить заново","Set up %s":"Настроить %s","Set up a server first.":"Сначала настройте сервер.","Settings changed":"Настройки изменились","Settings changed, update needed":"Настройки изменились, нужно обновить","Share as a file":"Поделиться файлом","Share file":"Поделиться файлом","Share the file":"Поделиться файлом","Share the link":"Поделиться ссылкой","Show key":"Показать ключ","Straight into %s":"Сразу в %s","Subnet must look like 10.77.0.0/24.":"Подсеть указывается так: 10.77.0.0/24.","Subnet overlaps %s.":"Подсеть пересекается с %s.",TB:"ТБ",Tablet:"Планшет","Tap “%s” and connect":"Нажмите «%s» и подключитесь","That name is taken.":"Это имя уже занято.","The APK is for phones without Google Play, or where the store hides the app.":"APK - для телефонов без Google Play или если магазин скрывает приложение.","The admin has turned this device off.":"Администратор отключил это устройство.","The app goes on the %s.":"Приложение ставится на %s.","The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).":"Браузер может предупредить, что сертификату нельзя доверять: это собственный сертификат роутера. Продолжите переход («Дополнительные» → «Перейти на сайт»).","The configuration is too long for a code. Scan this one to open your link on the %s instead.":"Конфигурация слишком длинная для QR-кода. Отсканируйте этот код, чтобы открыть свою ссылку на %s.","The connection":"Подключение","The connection as one key":"Подключение одним ключом","The header protection key is not a key.":"Ключ защиты заголовков некорректен.","The id may use lowercase letters, digits and underscores.":"В идентификаторе можно использовать строчные латинские буквы, цифры и подчёркивания.","The key is too long for a code. Scan this one to open your link on the %s instead.":"Ключ слишком длинный для QR-кода. Отсканируйте этот код, чтобы открыть свою ссылку на %s.","The packages and the file for OpenWrt":"Пакеты и файл для OpenWrt","The page could not load":"Не удалось загрузить страницу","The person has no server.":"У человека нет сервера.","The router can’t use what it sends: reconnect it.":"Роутер не принимает то, что отправляет устройство: переподключите его.","Then come back here and tap":"Затем вернитесь сюда и нажмите","Then import it in the app":"Затем импортируйте его в приложении","This connection is on two devices and they push each other out. Add the other one as its own device.":"Это подключение стоит на двух устройствах, и они вытесняют друг друга. Добавьте второе как отдельное устройство.","This device":"Это устройство","This device is using an outdated configuration.":"На этом устройстве устаревшая конфигурация.","This key is already in use.":"Этот ключ уже используется.","This link no longer works":"Эта ссылка больше не работает","This page is open without encryption. To add or set up a device, open the same link over HTTPS:":"Эта страница открыта без шифрования. Чтобы добавить или настроить устройство, откройте ту же ссылку по HTTPS:","Through the router":"Через роутер",Today:"Сегодня","Too many changes in a short time. Try again in a few minutes.":"Слишком много изменений за короткое время. Попробуйте ещё раз через несколько минут.","Two steps, about a minute":"Два шага, около минуты","Two steps, about a minute: get the app, then add the connection.":"Два шага, около минуты: установите приложение, затем добавьте подключение.","Unable to complete the handshake":"Не удаётся завершить рукопожатие","Unknown DNS choice.":"Неизвестный вариант DNS.","Unknown action.":"Неизвестное действие.","Unknown circle.":"Неизвестный круг.","Unknown device.":"Неизвестное устройство.","Unknown end action.":"Неизвестное действие по окончании доступа.","Unknown person.":"Неизвестный человек.","Unknown server.":"Неизвестный сервер.","Unknown service %s.":"Неизвестный сервис %s.","Up to %s characters.":"Не больше %s символов.",Uploaded:"Отправлено","Waiting for the connection":"Ждём подключения","Warning must be 0-60 days.":"Предупреждать можно за 0–60 дней.","What is it?":"Что это за устройство?","Windows PC":"Компьютер с Windows",Yesterday:"Вчера","You already have a device with this name.":"У вас уже есть устройство с таким именем.","You haven’t been added to one.":"Вас ещё не добавили ни на один сервер.","Your access":"Ваш доступ","Your access has ended.":"Ваш доступ закончился.","Your access is paused.":"Ваш доступ на паузе.","Your devices":"Ваши устройства","Your devices can’t connect until it’s enabled again.":"Ваши устройства не подключатся, пока его снова не включат.","Your devices can’t connect until it’s extended.":"Ваши устройства не подключатся, пока доступ не продлят.","Your devices can’t connect until it’s resumed.":"Ваши устройства не подключатся, пока доступ не возобновят.","Your local network stays reachable while connected.":"Ваша локальная сеть остаётся доступной при подключении.","Your network may be blocking the connection.":"Возможно, ваша сеть блокирует подключение.","bit/s":"бит/с",computer:"компьютер","on thecomputer":"компьютере",device:"устройство","on thedevice":"устройстве",ended:"закончился","ends today":"закончится сегодня","ends tomorrow":"закончится завтра","just now":"только что","kbit/s":"кбит/с",name:"имя",never:"никогда","no limit":"без лимита",phone:"телефон","on thephone":"телефоне",router:"роутер","on therouter":"роутере",tablet:"планшет","on thetablet":"планшете","this device":"это устройство"},p:{"%s already has %d device. Remove one first to lower the limit to %d.":["%s: уже %d устройство. Чтобы снизить лимит до %d, сначала удалите одно из них.","%s: уже %d устройства. Чтобы снизить лимит до %d, сначала удалите одно из них.","%s: уже %d устройств. Чтобы снизить лимит до %d, сначала удалите одно из них."],"%s day":["%s день","%s дня","%s дней"],"%s of %s slot free":["Свободно %s из %s места","Свободно %s из %s мест","Свободно %s из %s мест"],"You have reached your limit of %s device":["Достигнут лимит - %s устройство","Достигнут лимит - %s устройства","Достигнут лимит - %s устройств"],"You have reached your limit of %s device. Remove one to add another.":["Достигнут лимит - %s устройство. Удалите одно, чтобы добавить новое.","Достигнут лимит - %s устройства. Удалите одно, чтобы добавить новое.","Достигнут лимит - %s устройств. Удалите одно, чтобы добавить новое."],"day left":["день остался","дня осталось","дней осталось"],"ends in %s day":["закончится через %s день","закончится через %s дня","закончится через %s дней"]}};var rn=[{code:"en",name:"English"},{code:"ru",name:"Русский"}],Bi={ru:[Ro]},No={en:e=>e!==1?1:0,ru:e=>e%10===1&&e%100!==11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2},Io="dl.lang";function Ii(e,t){var o,r;let n=s=>s&&rn.some(i=>i.code===s)?s:null;return(r=(o=n(e))!=null?o:t.map(s=>n(s.toLowerCase().split(/[-_]/)[0])).find(Boolean))!=null?r:"en"}var lt="en",Xn=[],Wo=[],Fo=(e,t)=>t?`${t}${e}`:e;function Go(e,t){let n=Fo(e,t);for(let o of Xn)if(n in o.s)return o.s[n];return e}function Wi(e,t,n,o){var i,c,m;let r=Fo(t,o),s=(i=Xn.find(f=>r in f.p))==null?void 0:i.p[r];return(m=s==null?void 0:s[((c=No[lt])!=null?c:No.en)(e)])!=null?m:e===1?t:n}var tt=()=>lt,qo=e=>Go(e);function Jn(e,t=!0){var n;if(lt=rn.some(o=>o.code===e)?e:"en",Xn=(n=Bi[lt])!=null?n:[],document.documentElement.lang=lt,t)try{localStorage.setItem(Io,lt)}catch{}Wo.forEach(o=>o())}function Ko(e){Wo.push(e)}function Fi(){try{return localStorage.getItem(Io)}catch{return null}}Object.assign(globalThis,{_:Go,N_:Wi});var Bo;Jn(Ii(Fi(),(Bo=navigator.languages)!=null&&Bo.length?navigator.languages:[navigator.language]),!1);var Vo={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 sn(e,t="dl-icon"){var o;let n=(o=Vo[e])!=null?o:Vo.phone;return``}function zo(e,t){let n=o=>{o==null||o===!1||(Array.isArray(o)?o.forEach(n):e.appendChild(typeof o=="string"?document.createTextNode(o):o))};t.forEach(n)}function a(e,t={},...n){let o=document.createElement(e);for(let[r,s]of Object.entries(t))s==null||s===!1||(r.startsWith("on")&&typeof s=="function"?o.addEventListener(r.slice(2),s):r==="class"?o.className=String(s):s===!0?o.setAttribute(r,""):o.setAttribute(r,String(s)));return zo(o,n),o}function Ne(e,...t){e.replaceChildren(),zo(e,t)}function Ae(e){let t=document.createElement("template");return t.innerHTML=e.trim(),t.content.firstElementChild}var z=(e,t="i")=>Ae(sn(e,t));var se=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function dt(e,t,n=1){let o=Math.sqrt(e/n),r=t/(2*Math.sqrt(e*n)),s=f=>{if(r<.999){let x=o*Math.sqrt(1-r*r);return 1-Math.exp(-r*o*f)*(Math.cos(x*f)+r*o/x*Math.sin(x*f))}if(r<=1.001)return 1-Math.exp(-o*f)*(1+o*f);let C=Math.sqrt(r*r-1),g=-o*(r-C),b=-o*(r+C);return 1-(b*Math.exp(g*f)-g*Math.exp(b*f))/(b-g)},i=0;for(let f=0;f<3;f+=.004)Math.abs(1-s(f))>.0015&&(i=f);i+=.004;let c=[];for(let f=0;f<=64;f++)c.push(+s(i*f/64).toFixed(4));c[64]=1;let m=Math.round(i*1e3);return{duration:m,easing:`linear(${c.join(", ")})`,at:f=>f>=m?1:s(f/1e3)}}var De=dt(300,20),K=dt(300,35),Te=dt(520,24),Yo=dt(520,46),Le=dt(380,28),Uo=dt(900,60),Q="cubic-bezier(0.23, 1, 0.32, 1)",J="cubic-bezier(0.55, 0, 1, 0.45)",Zn="cubic-bezier(0.32, 0.72, 0, 1)";function jo(e){e.style.setProperty("--spring-bouncy",De.easing),e.style.setProperty("--spring-bouncy-dur",`${De.duration}ms`),e.style.setProperty("--spring-smooth",K.easing),e.style.setProperty("--spring-smooth-dur",`${K.duration}ms`),e.style.setProperty("--spring-soft",Le.easing),e.style.setProperty("--spring-soft-dur",`${Le.duration}ms`),e.style.setProperty("--spring-quick",Uo.easing),e.style.setProperty("--spring-quick-dur",`${Uo.duration}ms`)}function O(e,t,n){var o;return se()?t.some(r=>"opacity"in r)?e.animate(t.map(r=>"opacity"in r?{opacity:r.opacity}:{}),{duration:Math.min(Number((o=n.duration)!=null?o:200),160),easing:"ease-out",fill:n.fill}):e.animate(t,{...n,duration:0,delay:0}):e.animate(t,n)}function Qo(e,t){return e<=0||t<=0?0:(1-1/(e*.55/t+1))*t}function Xo(e,t){return e<=0||t<=0?0:e*t/(.55*Math.max(1,t-e))}function Jo(e,t,n){return e<=0||t<-.1?!1:t>.4||e>n/3}function Gi(){return(typeof document=="undefined"?"":document.documentElement.lang)||"en"}function He(){let e=Gi();return e==="en"?"en-GB":e}function V(e,...t){let n=0;return e.replace(/%([%sd])/g,(o,r)=>{var s;return r==="%"?"%":String((s=t[n++])!=null?s:"")})}function me(e,t){return e.toLocaleString(He(),t===void 0?void 0:{minimumFractionDigits:t,maximumFractionDigits:t})}function Ue(e,t,n){return V(N_(e,t,n),me(e))}function ut(e,...t){let n=0;return e.split(/(%[%sd])/).filter(Boolean).map(o=>o==="%%"?"%":o==="%s"||o==="%d"?t[n++]:o)}function qi(e,t,n){let o=0;for(;e>=n&&o=100||o===0?me(Math.round(e)):me(e,1)} ${t[o]}`}function Be(e){return qi(!e||e<0?0:e,[_("B"),_("KB"),_("MB"),_("GB"),_("TB")],1024)}function Zo(e,t=Date.now()/1e3){if(!e)return _("never");let n=Math.max(0,Math.round(t-e));return n<60?_("just now"):n<3600?V(_("%s min ago"),Math.floor(n/60)):n<86400?V(_("%s h ago"),Math.floor(n/3600)):n<86400*30?V(_("%s d ago"),Math.floor(n/86400)):new Date(e*1e3).toLocaleDateString(He(),{day:"numeric",month:"short",year:"numeric"})}function an(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function $e(e){let[t,n,o]=e.split("-").map(Number);return new Date(t,(n||1)-1,o||1,12)}function Ki(e){return(typeof e=="string"?/^\d{4}-\d{2}-\d{2}$/.test(e)?$e(e):new Date(e):e).toLocaleDateString(He(),{day:"numeric",month:"short",year:"numeric"})}function cn(e){return e?Ki(e):""}function Vi(e,t){let n=o=>{let[r,s,i]=o.split("-").map(Number);return Date.UTC(r,s-1,i)};return Math.round((n(e)-n(t))/864e5)}function pt(e,t){let n=$e(e);return n.setDate(n.getDate()+t),an(n)}function ln(e,t=Date.now()){if(!e)return null;let n=typeof t=="number"?an(new Date(t)):t,o=Vi(e,n);return o>=0?o+1:o}function $t(e,t){return t!=null&&t>0&&e.expire_warn>0&&t<=e.expire_warn}function er(e){return e<=1?_("ends today"):e===2?_("ends tomorrow"):Ue(e,"ends in %s day","ends in %s days")}function tr(e){return{lan:_("Home network"),internet:_("Internet"),both:_("Home network + Internet")}[e]}var dn=20,zi=[[128,191],[215,215],[247,247],[8192,11263],[12288,12351],[55296,63743],[65024,65039],[65072,65103],[65279,65279],[65520,65535],[126976,130047],[917504,917631]],Ui=/^[A-Za-z0-9 ._-]$/,Yi=/^[\p{L}\p{M}\p{N}]$/u;function un(e){var n;let t=(n=e.codePointAt(0))!=null?n:0;return t<128?Ui.test(e):!zi.some(([o,r])=>t>=o&&t<=r)&&Yi.test(e)}function eo(e){let t=[...e];return t.length<=dn&&t.every(un)}function ft(e,t=""){return[...[...e].map(r=>un(r)?r:" ").join("").replace(/\s+/g," ").trim()||_("Device")].slice(0,Math.max(1,dn-[...t].length)).join("").trimEnd()+t}function to(e){return e==="other"?_("Device"):no(e)}function no(e){return{computer:_("PC"),phone:_("Phone"),tablet:_("Tablet"),router:_("Router"),other:_("Other")}[e]}function pn(e){let t=n=>n.disabled?3:n.online?0:n.handshake?1:2;return e.map((n,o)=>[n,o]).sort((n,o)=>t(n[0])-t(o[0])||n[1]-o[1]).map(([n])=>n)}function nr(e){return e.map(t=>t.endsWith(".0/24")?`${t.slice(0,-5)}.x`:t).join(", ")}var he={vpn:"AmneziaVPN",awg:"AmneziaWG",wg:"WireGuard"};function rr(e,t=0){return/iPhone|iPad|iPod/.test(e)||/Macintosh/.test(e)&&t>1?"ios":/Android/.test(e)?"android":/Windows/.test(e)?"windows":/Mac OS X|Macintosh/.test(e)?"mac":/CrOS/.test(e)?"unknown":/Linux|X11/.test(e)?"linux":"unknown"}var sr=e=>/Telegram|FBAN|FBAV|Instagram|VKClient|Line\//i.test(e);function ir(e,t,n=!1){return e==="router"||t==="unknown"?!1:e==="phone"||e==="tablet"?t==="ios"||t==="android":e==="computer"?t==="windows"||t==="mac"||t==="linux":n||t==="windows"||t==="mac"||t==="linux"}function ar(e){let t=[{id:"vpn",name:he.vpn},{id:"awg",name:he.awg}];return e==="off"&&t.push({id:"wg",name:he.wg}),t}var fn="https://github.com/amnezia-vpn/amnezia-client/releases/latest",or=e=>({href:e,top:_("APK file on"),main:"GitHub",mark:"github",why:_("The APK is for phones without Google Play, or where the store hides the app.")});function cr(e,t){var i;let n=_("Download on the"),o=_("Get it on"),r=_("Official release on GitHub");return(i={vpn:{ios:{href:"https://apps.apple.com/app/amneziavpn/id1600529900",top:n,main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=org.amnezia.vpn",top:o,main:"Google Play",mark:"googleplay",alt:or(fn)},windows:{href:fn,top:r,main:_("Download for Windows"),mark:"windows"},mac:{href:fn,top:r,main:_("Download for Mac"),mark:"apple"},linux:{href:fn,top:r,main:_("Download for Linux"),mark:"linux"}},awg:{ios:{href:"https://apps.apple.com/us/app/amneziawg/id6478942365",top:n,main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=org.amnezia.awg",top:o,main:"Google Play",mark:"googleplay",alt:or("https://github.com/amnezia-vpn/amneziawg-android/releases")},windows:{href:"https://github.com/amnezia-vpn/amneziawg-windows-client/releases",top:r,main:_("Download for Windows"),mark:"windows"},mac:{href:"https://apps.apple.com/us/app/amneziawg/id6478942365",top:n,main:"Mac App Store",mark:"appstore"},linux:{href:"https://github.com/amnezia-vpn/amneziawg-tools",top:_("On GitHub"),main:"amneziawg-tools",mark:"linux"}},wg:{ios:{href:"https://apps.apple.com/app/wireguard/id1441195209",top:n,main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=com.wireguard.android",top:o,main:"Google Play",mark:"googleplay"},windows:{href:"https://www.wireguard.com/install/",top:_("Download from"),main:"wireguard.com",mark:"windows"},mac:{href:"https://apps.apple.com/app/wireguard/id1451685025",top:n,main:"Mac App Store",mark:"appstore"},linux:{href:"https://www.wireguard.com/install/",top:_("Install from"),main:"wireguard.com",mark:"linux"}}}[e][t])!=null?i:null}var lr=e=>e==="wg"?{href:"https://openwrt.org/docs/guide-user/services/vpn/wireguard/start",top:_("OpenWrt packages"),main:"wireguard-tools",mark:"openwrt"}:{href:"https://openwrt.org/packages/start",top:_("OpenWrt packages + kmod"),main:"amneziawg-tools",mark:"openwrt"},oo=e=>e==="android",Ot=e=>`${e.replace(/\.conf$/i,"")}.vpn`,Ye=(...e)=>e.join(" → ");function Pt(e){return{ios:{file:Ye("+",_("Create from file or archive","WireGuard app")),qr:Ye("+",_("Create from QR code","WireGuard app"))},android:{file:Ye("+",_("Import from file or archive","WireGuard app")),qr:Ye("+",_("Scan from QR code","WireGuard app"))},mac:{file:Ye("+",_("Import Tunnel(s) from File…","WireGuard app"))},windows:{file:Ye(_("Add Tunnel","WireGuard app"),_("Import tunnel(s) from file…","WireGuard app"))}}[e]}function Rt(e,t="unknown"){var o;if(e==="vpn")return Ye("+",_("QR code","AmneziaVPN app"));let n=(o=Pt(t))==null?void 0:o.qr;return n!=null?n:V(_("%s (Android: %s)"),Pt("ios").qr,Pt("android").qr.replace(/^.* → /,""))}function mn(e,t="unknown"){var n;return e==="vpn"?Ye("+",_("Insert","AmneziaVPN app")):((n=Pt(t))!=null?n:Pt("android")).file}var dr=()=>V(_("Tap “%s” and connect"),_("Continue","AmneziaVPN app"));function ur(e,t,n,o){if(t==="linux")return[[_("Open a terminal in the folder with the file"),""],[`${_("Run")} `,`sudo ${e==="wg"?"wg-quick":"awg-quick"} up ./${n}`]];let r=mn(e,t);return[[V(_("Open %s","step"),he[e]),""],[r.replace(/ → [^→]*$/," → "),r.replace(/^.* → /,"")],[o?_("Confirm the import and connect"):_("Pick the file and connect"),""]]}function pr(e){return{ios:"iPhone / iPad",android:"Android",windows:"Windows",mac:"Mac",linux:"Linux",unknown:_("this device")}[e]}var fr=(e,t)=>`${e}#setup=${t}`;function mr(e){var t,n;return(n=(t=/^#setup=(d_[0-9a-f]{8})$/.exec(e))==null?void 0:t[1])!=null?n:null}var hr=e=>`${e}#add`,gr=e=>e==="#add",ro=(e,t=!1)=>(t?{phone:_("phone","on the"),tablet:_("tablet","on the"),computer:_("computer","on the"),router:_("router","on the"),other:_("device","on the")}:{phone:_("phone"),tablet:_("tablet"),computer:_("computer"),router:_("router"),other:_("device")})[e];var re=null,ue=()=>re;function ye(e){re=e}var ji=document.getElementById("app"),yr,mt=(yr=ji.dataset.base)!=null?yr:"",vr=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(mt)?mt.slice(1):"",ht=()=>location.origin+location.pathname,Ie=()=>{var e;return(e=re==null?void 0:re.today)!=null?e:an(new Date)},gt=()=>{var e;return(e=re==null?void 0:re.now)!=null?e:Date.now()/1e3},hn=()=>rr(navigator.userAgent,navigator.maxTouchPoints),Qi=()=>(re==null?void 0:re.server.awg_disguise)===!1,br=()=>{var e;return(e=re==null?void 0:re.server.preset)!=null?e:Qi()?"off":"max"},xr=()=>(re==null?void 0:re.https_url)||null,nt=()=>(re==null?void 0:re.server.name)||"Dawnline",wr=()=>{};function Mr(e){wr=e}var _e=(e={})=>wr(e);var je=class extends Error{constructor(n,o,r){super(o);this.status=n;this.httpsUrl=r}};async function ge(e,t){let n=await fetch(`${mt}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{"Accept-Language":tt()}:{"Content-Type":"application/json","Accept-Language":tt()},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),o=null;try{o=await n.json()}catch{}if(!n.ok)throw new je(n.status,o!=null&&o.error?qo(o.error):V(_("Request failed (%s)"),n.status),(o==null?void 0:o.https_url)||void 0);return o}var gn=e=>e instanceof je&&(e.status===404||e.status===401);var _r=Ri(Lr(),1),Xi=e=>``,Tr="#0a0a0a",Ji="#f2f2f2",Zi={night:[Tr,Ji],day:["#ffffff",Tr]},yn=e=>e.length>300,Nt=null;function Sr(e){if((Nt==null?void 0:Nt.text)===e)return Nt.qr;let t=(0,_r.default)(0,yn(e)?"L":"H");return t.addData(e,"Byte"),t.make(),Nt={text:e,qr:t},t}function ea(e){try{return Sr(e),!0}catch{return!1}}var ta=1600,Ar=e=>e.length<=ta&&ea(e),yt=e=>+e.toFixed(2);function so(e,t,n,o,r){return`M${yt(e+r)} ${yt(t)}h${yt(n-2*r)}a${r} ${r} 0 0 1 ${r} ${r}v${yt(o-2*r)}a${r} ${r} 0 0 1 -${r} ${r}h-${yt(n-2*r)}a${r} ${r} 0 0 1 -${r} -${r}v-${yt(o-2*r)}a${r} ${r} 0 0 1 ${r} -${r}z`}function Hr(e,t=3,n=!0,o="plain"){let r=yn(e),s=o!=="plain",[i,c]=s?Zi[o]:["#fff","#000"],m=Sr(e),f=m.getModuleCount(),C=f+t*2,g=n&&!r?Math.round(f*.22):0;g&&(f-g)%2&&g++;let b=(f-g)/2,x=b+g,S=(p,u)=>g>0&&p>=b&&p=b&&us&&(u<7&&p<7||u<7&&p>=f-7||u>=f-7&&p<7),F="";if(s){let p=r?.48:.42;for(let u=0;u${Xi(s?i:"#fff")}`}let w=``;return s?`${w}${y}`:`${w}${y}`}var Dr={opacity:1,filter:"blur(0px)",transform:"none"},na={opacity:0,filter:"blur(5px)",transform:"scale(.86)"},$r={opacity:0,filter:"blur(5px)",transform:"scale(.6)"},Pr={duration:180,easing:J,fill:"forwards"},Bt={duration:340,delay:70,easing:Q,fill:"backwards"},Or=Bt.delay+Bt.duration,vn=new WeakMap;function bn(e){let t=getComputedStyle(e);return{opacity:t.opacity,filter:t.filter==="none"?"blur(0px)":t.filter,transform:t.transform}}function Rr(e){var t;for(let n of[...e.childNodes])n.nodeType===Node.TEXT_NODE&&((t=n.textContent)!=null&&t.trim())&&n.replaceWith(a("span",{},n.textContent));return[...e.children].filter(n=>!n.classList.contains("orb"))}function Nr(e,t){var o;let n=(o=vn.get(e))!=null?o:[];vn.set(e,t),n.forEach(r=>r.cancel())}function Br(e){let t=Rr(e),n=t.map(bn),o=e.querySelector(":scope > .orb"),r=o!=null?o:a("span",{class:"orb","aria-hidden":"true"},a("i"),a("i"));o||e.append(r),e.classList.add("busy"),e.setAttribute("aria-busy","true"),Nr(e,[...t.map((s,i)=>O(s,[n[i],na],Pr)),O(r,[o?bn(o):$r,Dr],o?{...Bt,delay:0}:Bt)])}function Ir(e){let t=e.querySelector(":scope > .orb"),n=Rr(e),o=[...t?[O(t,[bn(t),$r],Pr)]:[],...n.map(r=>O(r,[bn(r),Dr],Bt))];Nr(e,o),e.removeAttribute("aria-busy"),Promise.all(o.map(r=>r.finished)).then(()=>{vn.get(e)===o&&(vn.delete(e),o.forEach(r=>r.cancel()),t==null||t.remove(),e.classList.remove("busy"))},()=>{})}var Wr=e=>[...e].map(t=>a("i",{},t)),ot=new WeakMap,ve=e=>{var t,n,o;return(o=(n=(t=ot.get(e))==null?void 0:t.text)!=null?n:e.textContent)!=null?o:""},wn={opacity:1,filter:"blur(0px)"},oa=e=>e.opacity>.99&&(e.filter==="none"||e.filter==="blur(0px)");function rt(e){let t=getComputedStyle(e),n=e.querySelector(":scope > .mt-new"),o=n&&getComputedStyle(n);return{opacity:+t.opacity*(o?+o.opacity:1),filter:t.filter==="none"&&o?o.filter:t.filter}}function Mn(e){let t=document.createRange();return t.selectNodeContents(e),t.getBoundingClientRect()}function ra(e){let t=document.createRange();return t.selectNodeContents(e),t.getBoundingClientRect()}function Fr(e){var s;let t=e.firstChild;if(!t||t.nodeType!==Node.TEXT_NODE)return[];let n=document.createRange(),o=[],r=0;for(let i of(s=t.textContent)!=null?s:"")n.setStart(t,r),n.setEnd(t,r+i.length),o.push(n.getBoundingClientRect().left),r+=i.length;return o.map(i=>i-o[0])}function Gr(e,t){let n=[...e.children];n.length&&n.forEach((o,r)=>{if(!r||t[r]===void 0)return;let s=n[0].getBoundingClientRect().left+t[r]-o.getBoundingClientRect().left;Math.abs(s)>.01&&(o.style.marginLeft=`${s}px`)})}function sa(e,t){let n=0;for(;nnew Array(s.length+1).fill(0));for(let m=r.length-1;m>=0;m--)for(let f=s.length-1;f>=0;f--)i[m][f]=r[m]===s[f]?i[m+1][f+1]+1:Math.max(i[m+1][f],i[m][f+1]);let c=[];for(let m=0;m=i[m][f+1]?m++:f++;for(let m=o;m>0;m--)c.push([e.length-m,t.length-m]);return c}function xn(e){let t=ot.get(e);t&&(clearTimeout(t.timer),ot.delete(e),e.getAnimations().forEach(n=>n.cancel()),e.classList.remove("mt","mt-ib"),e.textContent=t.text)}function ae(e,t){xn(e),e.textContent=t}function ia(e){let t=e.querySelector(":scope > .mt-new");if(!t)return null;let n=[...e.querySelectorAll(":scope > .mt-old")],o=Mn(t);return t.remove(),n.forEach(r=>r.remove()),{words:t,at:o,going:n}}function te(e,t,n=ve(e),o={}){var Ce,et,k,T,E,D,$,I;let{whole:r=!1,at:s}=o,i=ot.get(e);if(i&&n===i.text&&t===i.text)return;let c=((Ce=o.glide)!=null?Ce:!0)&&!s,m=i?e.getBoundingClientRect():null,f=i&&n===i.text&&!se()&&e.getClientRects().length?ia(e):null;if(xn(e),n===t||se()||!e.getClientRects().length){e.textContent=t;return}let C=getComputedStyle(e),g=r&&C.display==="inline";C.display==="inline"&&!r&&e.classList.add("mt-ib"),C.position==="static"&&e.classList.add("mt");let b=f?m:null,x=(k=(et=f==null?void 0:f.at)!=null?et:s)!=null?k:null,S=[];x||(e.textContent=n,b=e.getBoundingClientRect(),x=Mn(e),S=Fr(e)),e.textContent=t;let P=e.getBoundingClientRect(),F=Fr(e),A=(E=(T=m==null?void 0:m.width)!=null?T:b==null?void 0:b.width)!=null?E:P.width,y=c&&!g&&!!b&&Math.abs(P.width-A)>.5,w=!y||!b||Math.abs(P.left-b.left)<.5?"start":Math.abs(P.right-b.right)<.5?"end":"middle",p=a("span",{class:r?"mt-new w":"mt-new"},r?t:Wr(t)),u=(D=f==null?void 0:f.words)!=null?D:a("span",{class:r?"mt-old w":"mt-old"},r?n:Wr(n));if(u.classList.replace("mt-new","mt-old"),u.setAttribute("aria-hidden","true"),u.classList.contains("w")&&(u.style.width=`${x.width+1}px`),e.replaceChildren(p,u),f&&e.append(...f.going),o.color){u.style.color=o.color;let B=getComputedStyle(e).color;B!==o.color&&O(p,[{color:o.color},{color:B}],{duration:280,easing:Q})}y&&O(e,[{width:`${A}px`},{width:`${P.width}px`}],{duration:K.duration,easing:K.easing,fill:"forwards"});let l=e.getBoundingClientRect(),v=(B,G)=>{u.style.top=`${G}px`,w==="end"?u.style.right=`${-B}px`:w==="middle"?(u.style.left="50%",u.style.translate=`calc(-50% + ${B}px) 0`):u.style.left=`${B}px`},h=w==="end"?x.right-l.right:w==="middle"?(x.left+x.right-l.left-l.right)/2:x.left-l.left;v(h,x.top-l.top);let d=!f&&(($=u.querySelector("i"))==null?void 0:$.firstChild),L=d?ra(d):Mn(u);v(h+x.left-L.left,x.top-l.top+x.top-L.top);let M=f?rt(u):(I=o.shows)!=null?I:wn,H=()=>{let B=u.getAnimations();O(u,[{opacity:M.opacity,filter:M.filter},{opacity:0,filter:"blur(4px)"}],{duration:180*M.opacity,easing:J,fill:"forwards"}),B.forEach(G=>G.cancel())};if(r){H(),O(p,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"blur(0px)"}],{duration:280,delay:60,easing:Q,fill:"backwards"});let B=Math.max(340,y?K.duration:0)+40;ot.set(e,{text:t,timer:window.setTimeout(()=>xn(e),B)});return}Gr(p,F),f||Gr(u,S);let q=u.classList.contains("w")?[]:[...u.children],R=[...p.children],W=q.length?sa([...n],[...t]):[],N=new Set(W.map(([B])=>B)),U=new Set(W.map(([,B])=>B));W.forEach(([B,G])=>{let X=q[B].getBoundingClientRect(),ne=R[G].getBoundingClientRect(),Y=f?rt(q[B]):M;q[B].style.visibility="hidden";let fe=Math.abs(X.left-ne.left)>.5||Math.abs(X.top-ne.top)>.5,ce=oa(Y)?null:Y;(fe||ce)&&O(R[G],[{transform:`translate(${X.left-ne.left}px, ${X.top-ne.top}px)`,...ce},{transform:"none",...ce&&wn}],{duration:K.duration,easing:K.easing})});let Z=f?[]:q.filter((B,G)=>!N.has(G));f&&H();let oe=R.filter((B,G)=>!U.has(G)),de=Math.min(12,160/Math.max(1,Z.length)),ke=Math.min(22,260/Math.max(1,oe.length));Z.forEach((B,G)=>O(B,[{opacity:M.opacity,filter:M.filter,transform:"none"},{opacity:0,filter:"blur(4px)",transform:"translateY(-0.45em)"}],{duration:220,delay:G*de,easing:J,fill:"forwards"})),oe.forEach((B,G)=>O(B,[{opacity:0,filter:"blur(4px)",transform:"translateY(0.45em)"},{opacity:1,filter:"blur(0px)",transform:"none"}],{duration:380,delay:120+G*ke,easing:Q,fill:"backwards"}));let nn=Math.max(220+Z.length*de,oe.length?120+oe.length*ke+380:0,y||W.length?K.duration:0)+40;ot.set(e,{text:t,timer:window.setTimeout(()=>xn(e),nn)})}function It(e){return new Map([...e.querySelectorAll("[data-t]")].map(t=>[t.dataset.t,{text:ve(t),color:getComputedStyle(t).color}]))}function Wt(e,t,n=[]){e.querySelectorAll("[data-t]").forEach(o=>{let r=t.get(o.dataset.t),s=ve(o);!r||r.text===s||ot.has(o)||n.some(i=>i.contains(o))||te(o,s,r.text,{color:r.color})})}var Kr=e=>e instanceof HTMLElement||e instanceof SVGElement,io=e=>Kr(e)?e:a("span",{},e),co=e=>`${e.tagName}.${[...e.classList].filter(t=>t!=="mt"&&t!=="mt-ib").join(" ")}`,Vr=e=>e.outerHTML.replace(/\bgl\d+/g,"gl"),Qe=new Map,En=new WeakMap,zr=new WeakSet;function aa(e,t){for(let n=e.parentElement;n&&n!==t;n=n.parentElement)if(Qe.has(n))return!0;return!1}function ca(e){var n;let t=(n=En.get(e))!=null?n:0;!t&&getComputedStyle(e).position==="static"&&(e.classList.add("mt"),zr.add(e)),En.set(e,t+1)}function qr(e){var n;let t=((n=En.get(e))!=null?n:1)-1;En.set(e,t),!t&&zr.delete(e)&&e.classList.remove("mt")}function vt(e,t,n,o,r=wn){let s=Qe.get(e);if(s&&qr(s),ca(n),Qe.set(e,n),e.style.position="absolute",e.style.margin="0",e.style.left=`${t.left-o.left-n.clientLeft}px`,e.style.top=`${t.top-o.top-n.clientTop}px`,e.style.right="",e.style.translate="",e.style.width=`${t.width}px`,e.style.pointerEvents="none",e.setAttribute("aria-hidden","true"),n.appendChild(e),s)return;let i=e.getAnimations(),c=O(e,[{opacity:r.opacity,filter:r.filter},{opacity:0,filter:"blur(4px)"}],{duration:180*r.opacity,easing:J,fill:"forwards"});i.forEach(m=>m.cancel()),c.onfinish=c.oncancel=()=>{let m=Qe.get(e);m&&(Qe.delete(e),qr(m),e.remove())}}function la(e){let t=new Map,n=(o,r)=>o.childNodes.forEach((s,i)=>{var C,g;let c=`${r}/${i}`;if(s.nodeType===Node.TEXT_NODE){if((C=s.textContent)!=null&&C.trim()){let b=document.createRange();b.selectNodeContents(s);let x=b.getBoundingClientRect();t.set(c,{kind:"#text",text:s.textContent,svg:"",at:x,words:x,node:s,shows:wn})}return}if(!(s instanceof Element)||Qe.has(s)||s.classList.contains("mt-old"))return;let m=s instanceof SVGElement?Vr(s):"",f=s instanceof HTMLElement&&!m?Mn((g=s.querySelector(":scope > .mt-new"))!=null?g:s):null;t.set(c,{kind:co(s),text:s instanceof HTMLElement?ve(s):"",svg:m,at:s.getBoundingClientRect(),words:f,node:s,shows:rt(s)}),m||n(s,c)});return n(e,""),t}function da(e,t,n){let o={duration:K.duration,easing:K.easing};if(!(e instanceof HTMLElement)||getComputedStyle(e).display!=="inline")return O(e,[{transform:`translate(${t}px, ${n}px)`},{transform:"none"}],o);let r=e.style.position;getComputedStyle(e).position==="static"&&(e.style.position="relative");let s=O(e,[{left:`${t}px`,top:`${n}px`},{left:"0px",top:"0px"}],o);return s.onfinish=s.oncancel=()=>e.style.position=r,s}function We(e,t){var r,s;let n=+getComputedStyle(e).opacity,o=(r=t==null?void 0:t.opacity)!=null?r:0;O(e,[{opacity:o,filter:(s=t==null?void 0:t.filter)!=null?s:"blur(4px)"},{opacity:n,filter:"blur(0px)"}],{duration:280*Math.min(1,Math.max(0,n-o)/(n||1)),delay:t?0:60,easing:Q,fill:"backwards"})}function Xe(e,t){let n=la(e),o=e.getBoundingClientRect(),r=[...Qe.keys(),...e.querySelectorAll(".mt-old")].filter(A=>e.contains(A)&&!aa(A,e)&&Kr(A)).map(A=>({g:A,at:A.getBoundingClientRect(),over:A.parentElement,shows:Qe.has(A)?void 0:rt(A)})),s=new Map([...n].map(([A,y])=>[y.node,A]));Ne(e,t);let i=new Map,c=()=>r.forEach(({g:A,at:y,over:w,shows:p})=>{let u=w&&s.get(w),l=u&&i.get(u),v=u&&n.get(u);l&&v&&v.at&&v.kind===co(l)?vt(A,y,l,v.at,p):vt(A,y,e,o,p)});if(!n.size||se())return c(),[];let m=e.getBoundingClientRect(),f=A=>A&&new DOMRect(A.left-o.left+m.left,A.top-o.top+m.top,A.width,A.height),C=[],g=[],b=new Set,x=[],S=(A,y,w)=>{var l;let p=A.parentElement,u=w?(l=n.get(w))==null?void 0:l.at:o;y!=null&&y.at&&g.push(p&&u?[io(y.node),y.at,p,u,y.shows]:[io(y.node),y.at,e,o,y.shows]),x.push(A),C.push(()=>We(A))},P=(A,y,w)=>{let p=A.getBoundingClientRect(),u=y.left-o.left-(p.left-m.left),l=y.top-o.top-(p.top-m.top),v=u-w[0],h=l-w[1];return(Math.abs(v)>.5||Math.abs(h)>.5)&&da(A,v,h),[u,l]},F=(A,y,w)=>[...A.childNodes].forEach((p,u)=>{var q,R;let l=`${y}/${u}`;b.add(l);let v=n.get(l);if(p.nodeType===Node.TEXT_NODE){let W=(q=p.textContent)!=null?q:"";if(!W.trim())return;let N=v&&(v.kind==="#text"||v.node instanceof HTMLElement&&!v.node.children.length)?v.text:null,U=v&&v.shows.opacity<.99?v.shows:null;if(N===W&&!U)return;let Z=a("span",{},W);if(p.replaceWith(Z),N===null||Math.max(W.length,N.length)>40)return S(Z,v,y);v!=null&&v.at&&P(Z,v.at,w),C.push(()=>{var oe;return N===W?We(Z,U):te(Z,W,N,{whole:!0,at:(oe=f(v.words))!=null?oe:void 0,shows:v.shows})});return}if(!(p instanceof Element))return;i.set(l,p);let h=p.getBoundingClientRect(),d=p instanceof SVGElement;if(!v||v.kind!==co(p)||(d?v.svg!==Vr(p):v.at&&Math.abs(v.at.height-h.height)>1))return S(p,v,y);let L=v.at?P(p,v.at,w):w,M=+getComputedStyle(p).opacity,H=Math.abs(v.shows.opacity-M)>.01?v.shows:null;if(d){H&&C.push(()=>We(p,H));return}if(!p.children.length&&p instanceof HTMLElement){let W=(R=p.textContent)!=null?R:"";if(W===v.text||p.dataset.t)H&&C.push(()=>We(p,H));else if(W.length<=40&&v.text.length<=40){let N={opacity:Math.min(1,v.shows.opacity/(M||1)),filter:v.shows.filter};C.push(()=>{var U;return te(p,W,v.text,{whole:!0,at:(U=f(v.words))!=null?U:void 0,shows:N})})}else S(p,v,y);return}H&&C.push(()=>We(p,H)),F(p,l,L)});F(e,"",[0,0]);for(let[A,y]of n)!b.has(A)&&A.lastIndexOf("/")===0&&y.at&&g.push([io(y.node),y.at,e,o,y.shows]);C.forEach(A=>A());for(let[A,y,w,p,u]of g)vt(A,y,w,p,u);return c(),x}var ua='',ao=()=>[z("apple"),Ae(ua)];function pa(e,t){if(e===t)return["",e,e,""];let n=e.split(" "),o=t.split(" "),r=0;for(;rm?y[2]:y[1],C=y=>a("span",{class:"osm-p"},y),g=()=>{i=r.findIndex(y=>y[1]!==y[2]),i<0&&(m=0),s=r.map(y=>({pre:C(y[0]),word:C(f(y)),suf:C(y[3])})),c=i>=0?a("span",{class:"osm-ic"},ao()[m]):null,n.replaceChildren(...s.flatMap((y,w)=>[w?a("span",{class:"arr"},"›"):null,y.pre,w===i?c:null,y.word,y.suf]).filter(y=>!!y))},b={width:"1.05em",marginRight:"0.25em"},x=y=>{let w=getComputedStyle(y),p=Math.min(1,parseFloat(w.width)/(1.05*parseFloat(w.fontSize))||0),u=y.getAnimations();O(y,[{opacity:w.opacity,filter:w.filter,width:w.width,marginRight:w.marginRight},{opacity:0,filter:"blur(3px)",width:"0px",marginRight:"0px"}],{duration:220*p,easing:J,fill:"forwards"}).onfinish=()=>y.remove(),u.forEach(l=>l.cancel())},S=y=>O(y,[{opacity:0,filter:"blur(3px)",width:"0px",marginRight:"0px"},{opacity:1,filter:"blur(0px)",...b}],{duration:K.duration,easing:K.easing}),P=(y,w)=>{o.setAttribute("aria-label",(y===w?y:V(_("%s (Android: %s)"),y,w.split(" → ").pop())).replace(/ → /g," › "));let p=y.split(" → "),u=w.split(" → "),l=p.map((h,d)=>{var L;return pa(h,(L=u[d])!=null?L:h)});if(!s.length||l.length!==r.length)return r=l,g();let v=i;r=l,i=r.findIndex(h=>h[1]!==h[2]),i<0&&(m=0),r.forEach((h,d)=>{te(s[d].pre,h[0],void 0,{whole:!0}),te(s[d].word,f(h),void 0,{whole:!0}),te(s[d].suf,h[3],void 0,{whole:!0})}),i!==v&&(c&&x(c),c=i>=0?a("span",{class:"osm-ic"},ao()[m]):null,c&&(s[i].word.before(c),S(c)))};P(e,t);let F=()=>{if(!o.isConnected)return clearInterval(A);if(i<0||!c||!o.offsetParent)return;m=1-m,te(s[i].word,f(r[i]));let y=c.firstElementChild,w=ao()[m];if(se()){y.replaceWith(w);return}c.appendChild(w),O(y,[{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:"blur(3px)",transform:"scale(.5) rotate(-40deg)"}],{duration:200,easing:J,fill:"forwards"}).onfinish=()=>y.remove(),O(w,[{opacity:0,filter:"blur(3px)",transform:"scale(.5) rotate(40deg)"},{opacity:1,filter:"blur(0px)",transform:"none"}],{duration:Te.duration,delay:80,easing:Te.easing,fill:"backwards"})},A=window.setInterval(F,3e3);return{el:o,set:P}}var kn=null,Ft=null,Yr=0;function jr(e,t,n){let o=getComputedStyle(e),r=O(e,[{opacity:o.opacity,transform:o.transform,filter:o.filter},t],{duration:n,easing:J,fill:"forwards"});e.getAnimations().forEach(s=>s!==r&&s.cancel()),r.onfinish=()=>e.remove()}function Pe(e,t=!1){kn!=null||(kn=document.body.appendChild(a("div",{class:"toasts"}))),Ft&&jr(Ft,{opacity:0,transform:"scale(.96)",filter:"blur(4px)"},140);let n=a("div",{class:`toast${t?" bad":""}`,role:"status"},z(t?"alert":"check"),a("span",{},e));kn.appendChild(n),Ft=n,O(n,[{opacity:0,transform:"translateY(18px) scale(.9)",filter:"blur(6px)"},{opacity:1,transform:"none",filter:"none"}],{duration:De.duration,easing:De.easing}),clearTimeout(Yr),Yr=window.setTimeout(()=>{Ft===n&&(Ft=null,jr(n,{opacity:0,transform:"translateY(6px) scale(.96)",filter:"blur(4px)"},180))},2400)}function Qr(e,t){var o;let n=typeof t=="string"?z(t,(o=e.getAttribute("class"))!=null?o:"i"):t;return e.replaceWith(n),O(n,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Te.duration,easing:Te.easing}),n}function fa(e){if(e.classList.contains("copied"))return;let t=e.querySelector("svg.i"),n=e.querySelector(".lbl, .b-main"),o=n?ve(n):"";e.classList.add("copied");let r=t?Qr(t,"check"):null;n&&te(n,_("Copied")),setTimeout(()=>{r&&t&&Qr(r,t),n&&te(n,o),e.classList.remove("copied")},1600)}async function be(e,t=_("Copied"),n){try{await navigator.clipboard.writeText(e)}catch{let o=a("textarea",{class:"offscreen"},e);document.body.appendChild(o),o.select();let r=document.execCommand("copy");if(o.remove(),!r)return Pe(_("Copying is blocked here. Select the text and copy it by hand."),!0)}n instanceof Element&&fa(n),Pe(t)}function st(e,t){var r;let n=navigator;if(hn()!=="ios"||typeof n.share!="function"||typeof File=="undefined")return null;let o=new File([t],e,{type:"application/octet-stream"});return(r=n.canShare)!=null&&r.call(n,{files:[o]})?async()=>{try{await n.share({files:[o]})}catch(s){(s==null?void 0:s.name)!=="AbortError"&&Cn(e,t)}}:null}function Cn(e,t){let n=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),o=a("a",{href:n,download:e,class:"offscreen"});document.body.appendChild(o),o.click(),setTimeout(()=>{URL.revokeObjectURL(n),o.remove()},1e3)}function Gt(e,t){let n=st(e,t);n?n():Cn(e,t)}async function bt(e,t){if(e.disabled)return;e.disabled=!0,Br(e);let n=performance.now();try{await t()}finally{let o=se()?0:Or-(performance.now()-n);o>0&&await new Promise(r=>setTimeout(r,o)),Ir(e),e.disabled=!1}}var Ln=matchMedia("(prefers-color-scheme: light)"),ma=()=>Ln.matches?"day":"night";function lo(e){let t=Ae(Hr(e,3,!0,ma()));return t.dataset.qr=e,t}function Xr(e,t){e.dataset.qr=t.dataset.qr,e.classList.toggle("dense",yn(t.dataset.qr)),e.classList.toggle("light",Ln.matches),e.dataset.mods=String(t.viewBox.baseVal.width)}function qt(e,t=!1){let n=a("div",{class:`qrbox${t?" big":""}`}),o=lo(e);return n.append(o),Xr(n,o),n}Ln.addEventListener("change",()=>document.querySelectorAll(".qrbox[data-qr]").forEach(e=>{e.querySelectorAll(":scope > svg[data-qr]").forEach(t=>t.replaceChildren(...lo(t.dataset.qr).childNodes)),e.classList.toggle("light",Ln.matches)}));function ha(e){let t=getComputedStyle(e);return{opacity:t.opacity,filter:t.filter==="none"?"blur(0px)":t.filter}}function uo(e,t,n){let o=x=>!!n&&!Ar(x),r=t,s=o(e),i=qt(s?n.text:e),c=a("div",{class:"words"},s?n.words():r),m=a("div",{class:"side"},c),f=a("div",{class:`coderow${i.classList.contains("dense")?" stacked":""}`},i,m),C=null,g=new WeakSet,b=x=>{var H,q;let S=[...i.querySelectorAll(":scope > svg")],P=new Map(S.map(R=>[R,+getComputedStyle(R).opacity])),F=getComputedStyle(i),A=i.getBoundingClientRect(),y=parseFloat(F.borderTopLeftRadius)*new DOMMatrix(F.transform).a,w=(H=S.find(R=>R.dataset.qr===x))!=null?H:lo(x),p=S.indexOf(w);p<0&&i.prepend(w);let u=S.slice(p+1).filter(R=>!g.has(R)),l=S.slice(0,Math.max(0,p)),v=[w,...u].flatMap(R=>R.getAnimations());g.delete(w),Xr(i,w),f.classList.toggle("stacked",i.classList.contains("dense"));let h=(q=P.get(w))!=null?q:0;O(w,[{opacity:h},{opacity:1}],{duration:200*(1-h),easing:Q}).onfinish=()=>{l.forEach(R=>R.remove()),w.classList.remove("old")},u.forEach(R=>{R.classList.add("old"),g.add(R),O(R,[{opacity:P.get(R)},{opacity:0}],{duration:220*P.get(R),delay:110,easing:J,fill:"both"}).onfinish=()=>R.remove()}),v.forEach(R=>R.cancel()),C==null||C.cancel(),C=null;let d=i.getBoundingClientRect(),L=A.width/d.width,M=A.height/d.height;A.width&&d.width&&(Math.abs(L-1)>.005||Math.abs(M-1)>.005)&&(C=O(i,[{transform:`scale(${L}, ${M})`,transformOrigin:"0 0",borderRadius:`${y/L}px`},{transform:"none",transformOrigin:"0 0",borderRadius:getComputedStyle(i).borderTopLeftRadius}],{duration:K.duration,easing:K.easing}))};return{el:f,swap(x,S){S&&(r=S);let P=s;s=o(x);let F=s?n.text:x;i.dataset.qr!==F&&b(F);let A=s?n.words():S!=null?S:P?r:null;if(s&&P&&A.map(u=>u.textContent).join("")===c.textContent&&(A=null),!A)return;let y=c,w=ha(y),p=y.getAnimations();c=a("div",{class:"words"},A),m.appendChild(c),y.classList.add("old"),O(c,[{opacity:0,filter:"blur(3px)"},{opacity:1,filter:"blur(0px)"}],{duration:220,easing:Q}),O(y,[w,{opacity:0,filter:"blur(3px)"}],{duration:200,delay:90,easing:J,fill:"both"}).onfinish=()=>y.remove(),p.forEach(u=>u.cancel())}}}function xt(e){let t=typeof navigator.share=="function";return a("div",{class:"linkrow"},a("span",{class:"mono"},e.replace(/^https?:\/\//,"")),a("button",{type:"button",class:"knob","aria-label":_("Copy the link"),onclick:n=>be(e,_("Link copied"),n.currentTarget)},z("copy")),t?a("button",{type:"button",class:"knob","aria-label":_("Share the link"),onclick:()=>navigator.share({url:e,title:nt()}).catch(()=>{})},z("share")):null)}var it=null,Fe=null,Kt=()=>!!it;function Oe(e=!1){let t=it;if(!t)return;if(it=null,Fe==null||Fe.setAttribute("aria-expanded","false"),Fe=null,e){t.remove();return}let n=getComputedStyle(t),o=O(t,[{opacity:n.opacity,transform:n.transform,filter:n.filter},{opacity:0,transform:"scale(.96)",filter:"blur(3px)"}],{duration:120,easing:J,fill:"forwards"});t.getAnimations().forEach(r=>r!==o&&r.cancel()),o.onfinish=()=>t.remove()}function Tn(e,t){var f,C;if(Fe===e&&it)return Oe();Oe(!0);let n=t.filter((g,b)=>g||b>0&&t[b-1]&&t.slice(b+1).some(Boolean)),o=a("span",{class:"menu-hl"}),r=a("div",{class:"menu",role:"menu"},o);for(let g of n){if(!g){r.appendChild(a("div",{class:"menu-sep"}));continue}let b=a("button",{type:"button",role:g.checked===void 0?"menuitem":"menuitemradio","aria-checked":g.checked===void 0?null:String(g.checked),class:`mi ${(f=g.tone)!=null?f:""}`,onclick:()=>{Oe(),g.run()}},g.checked===void 0?z((C=g.icon)!=null?C:""):z("check",g.checked?"i":"i off"),a("span",{},g.label));b.addEventListener("pointerenter",()=>{var S;let x=+getComputedStyle(o).opacity>.01;o.className=`menu-hl${x?" moving":""} ${(S=g.tone)!=null?S:""}`,o.style.transform=`translateY(${b.offsetTop-6}px)`,o.style.opacity="1"}),r.appendChild(b)}r.addEventListener("pointerleave",()=>o.style.opacity="0"),document.body.appendChild(r);let s=e.getBoundingClientRect(),i=r.offsetWidth,c=r.offsetHeight,m=s.bottom+8+c{let t=e.target;it&&!it.contains(t)&&!(Fe!=null&&Fe.contains(t))&&Oe()});addEventListener("scroll",()=>Oe(),{passive:!0});var ie,le,j,fo,Et,Ge,xe,Je=[],_n=null,mo=null,Sn=null,Vt=!1,wt=null,es=0,Re=()=>!!(ie!=null&&ie.classList.contains("open")),zt=(e,...t)=>e.getAnimations().filter(n=>{var o;return(o=n.effect)==null?void 0:o.getKeyframes().some(r=>t.some(s=>s in r))}),kt=400,Jr=80,ga=3.2,Ct=()=>matchMedia("(min-width: 760px)").matches,Mt=kt,ho=null;function Lt(){var r;if(!ie||!Re())return null;if(!Ct())return j.style.maxWidth&&(j.style.maxWidth=""),Mt=kt,null;let e=[...xe.querySelectorAll(".qrbox.dense")].find(s=>{let i=s.closest(".acc-row");return s.offsetWidth&&(!i||i.classList.contains("open"))&&!s.closest(".leaving")}),t=kt;if(e){let s=Math.min(innerWidth-32-Jr,innerHeight-120);t=Math.max(kt,Math.round(Math.min(+((r=e.dataset.mods)!=null?r:0)*ga,s)+Jr))}let n=e&&e!==ho?e:null;if(ho=e!=null?e:null,Math.abs(t-Mt)<8)return n?{from:t,want:t,reveal:n}:null;let o=parseFloat(getComputedStyle(j).maxWidth)||Mt;return Mt=t,zt(j,"maxWidth").forEach(s=>s.cancel()),j.style.maxWidth=`${t}px`,{from:o,want:t,reveal:n}}function Tt(e){if(!e)return;Math.abs(e.from-e.want)>1&&O(j,[{maxWidth:`${e.from}px`},{maxWidth:`${e.want}px`}],{duration:K.duration,easing:K.easing});let t=e.reveal;t&&setTimeout(()=>{if(!t.isConnected)return;let n=Ge.getBoundingClientRect(),o=t.getBoundingClientRect(),r=o.bottom>n.bottom-16?o.bottom-n.bottom+16:o.topSe()},z("x")),Et=a("div",{class:"sheet-acts"}),xe=a("div",{class:"vp"}),Ge=a("div",{class:"sheet-scroll"},xe),j=a("div",{class:"sheet",role:"dialog","aria-modal":"true"},fo,Et,Ge),le=a("div",{class:"scrim",onclick:()=>Se()}),ie=a("div",{class:"sheet-root","aria-hidden":"true"},le,j),ie.addEventListener("click",e=>{performance.now()>=es||(e.preventDefault(),e.stopPropagation())},!0),document.body.appendChild(ie),new ResizeObserver(()=>Tt(Lt())).observe(xe),ba()}function ts(e){j.setAttribute("aria-label",e.label),fo.setAttribute("aria-label",_("Close")),j.setAttribute("role",e.asks?"alertdialog":"dialog"),j.classList.toggle("asks",!!e.asks)}function Ut(){let e=mo;mo=null,e==null||e()}function ns(e){mo=e}function _t(e){_n=e}function we(e){if(ie||ya(),Oe(!0),ie.dataset.closing){Sn=e;return}if(Ut(),Re()){Je=[e],go(e());return}wt=document.activeElement instanceof HTMLElement?document.activeElement:null,es=performance.now()+320,Je=[e],_n=null,Mt=kt,ho=null,j.style.maxWidth="",j.classList.remove("arrived");let t=e();xe.replaceChildren(t.el),rs(t,!1),ts(t),ie.classList.add("open"),ie.setAttribute("aria-hidden","false"),document.body.classList.add("locked");let n=Lt();if(n&&Tt({...n,from:n.want}),j.getAnimations().forEach(o=>o.cancel()),le.getAnimations().forEach(o=>o.cancel()),j.style.transform="",Ct()?O(j,[{opacity:0,transform:"scale(.9)",filter:"blur(4px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Le.duration,easing:Le.easing}):O(j,[{transform:"translateY(calc(100% + 40px))"},{transform:"none"}],{duration:500,easing:Zn}),O(le,[{opacity:0},{opacity:1}],Ct()?{duration:Le.duration,easing:Le.easing}:{duration:420,easing:"ease-out"}),!Vt)try{history.pushState({sheet:!0},""),history.scrollRestoration="manual",Vt=!0}catch{}}function Se(e=!1){if(!Re())return;if(ie.dataset.closing){e&&(Sn=null,po());return}if(Ut(),Vt&&(Vt=!1,history.back()),document.body.classList.remove("locked"),e)return po();ie.dataset.closing="1";let t=getComputedStyle(j),n=t.transform,o=t.opacity,r=t.filter==="none"?"blur(0px)":t.filter,s=getComputedStyle(le).opacity;zt(j,"transform","opacity").forEach(i=>i.cancel()),le.getAnimations().forEach(i=>i.cancel()),O(le,[{opacity:s},{opacity:0}],Ct()?{duration:120,easing:J,fill:"forwards"}:{duration:320,easing:"ease-out",fill:"forwards"}),O(j,Ct()?[{opacity:o,transform:n,filter:r},{opacity:0,transform:`${n==="none"?"":n} scale(.96)`.trim(),filter:"blur(3px)"}]:[{transform:n},{transform:"translateY(calc(100% + 40px))"}],Ct()?{duration:120,easing:J,fill:"forwards"}:{duration:420,easing:Zn,fill:"forwards"}).onfinish=po}function po(){Ut(),ie.classList.remove("open"),ie.setAttribute("aria-hidden","true"),delete ie.dataset.closing,j.style.transform="",le.style.opacity="",j.getAnimations().forEach(n=>n.cancel()),le.getAnimations().forEach(n=>n.cancel()),xe.replaceChildren(),Et.replaceChildren(),j.classList.remove("arrived"),j.style.maxWidth="",Mt=kt,Je=[],wt!=null&&wt.isConnected&&wt.focus({preventScroll:!0}),wt=null;let e=_n;_n=null,e==null||e();let t=Sn;Sn=null,t&&we(t)}var os=()=>{var e;return!!((e=history.state)!=null&&e.sheet)};addEventListener("popstate",()=>{if(!Re()){os()&&history.back();return}Vt=!1,Se()});os()&&history.back();function rs(e,t=!0){var r;let n=(r=e.acts)!=null?r:null,o=Et.firstElementChild;if(n!==o){if(!t||o&&n&&o.dataset.key===n.dataset.key)return Et.replaceChildren(...n?[n]:[]);o&&(Object.assign(o.style,{position:"absolute",right:"0",top:"0",pointerEvents:"none"}),O(o,[{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=()=>o.remove()),n&&(Et.appendChild(n),O(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 ss(e,t,n){if(!e)return;zt(e,"marginBottom").forEach(r=>r.cancel());let o=t-xe.getBoundingClientRect().height;Math.abs(o)>1&&O(e,[{marginBottom:`${o}px`},{marginBottom:"0px"}],n)}function go(e){ts(e),rs(e),j.classList.remove("arrived");let t=xe.getBoundingClientRect().height,n=Ge.scrollTop,o=[...xe.children],r=o.map(c=>(c.classList.contains("leaving")&&parseFloat(c.style.top)||0)-n),s=o.filter(c=>!c.classList.contains("leaving")),i=s.map(c=>{let m=getComputedStyle(c);return{opacity:m.opacity,transform:m.transform,filter:m.filter}});o.forEach((c,m)=>{c.classList.add("leaving"),Object.assign(c.style,{position:"absolute",left:"0",right:"0",top:`${r[m]}px`,pointerEvents:"none"}),c.inert=!0}),xe.appendChild(e.el),e.el.style.pointerEvents="none",setTimeout(()=>e.el.style.pointerEvents="",320),Ge.scrollTop=0,Tt(Lt()),ss(e.el,t,{duration:360,easing:"cubic-bezier(.25,1,.5,1)"}),s.forEach((c,m)=>{let f=c.getAnimations();O(c,[i[m],{opacity:0,transform:"scale(.96)",filter:"blur(2px)"}],{duration:200*+i[m].opacity,easing:"cubic-bezier(.2,0,0,1)",fill:"forwards"}).onfinish=()=>c.remove(),f.forEach(C=>C.cancel())}),O(e.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 An(e){if(!Re()||ie.dataset.closing)return we(e);Ut(),Je.push(e),go(e())}function va(){Je.length<2||ie.dataset.closing||(Ut(),Je.pop(),go(Je[Je.length-1]()))}function Hn(e,t=[]){if(!Re())return e();let n=xe.lastElementChild,o=new Map;n==null||n.querySelectorAll("*").forEach(i=>{(!(i instanceof SVGElement)||i instanceof SVGSVGElement)&&o.set(i,i.getBoundingClientRect())});let r=xe.getBoundingClientRect().height;e(),Tt(Lt()),ss(n,r,{duration:K.duration,easing:K.easing});let s=new Set;for(let[i,c]of o){if(!i.isConnected||!c.width||!c.height)continue;let m=i.getBoundingClientRect();if(!m.width||!m.height)continue;let f=c.left-m.left,C=c.top-m.top;if(Math.abs(f)<.5&&Math.abs(C)<.5)continue;s.add(i);let g=i.parentElement;for(;g&&g!==n&&!s.has(g);)g=g.parentElement;g&&g!==n||O(i,[{transform:`translate(${f}px, ${C}px)`},{transform:"none"}],{duration:K.duration,easing:K.easing,composite:"add"})}for(let i of t)i&&O(i,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:Q})}function is(e=!0){j==null||j.classList.toggle("arrived",e)}var as=()=>Ge==null?void 0:Ge.scrollTo({top:0,behavior:"smooth"}),Yt=e=>Re()&&xe.contains(e)&&!e.closest(".leaving"),Zr=e=>Math.max(0,1-Math.max(0,e)/420);function ba(){let e=null;j.addEventListener("pointerdown",n=>{let o=n.target;if(!o.closest(".vhead")||o.closest("button, a, input")||ie.dataset.closing||zt(j,"opacity").length)return;let r=new DOMMatrixReadOnly(getComputedStyle(j).transform).m42,s=+getComputedStyle(le).opacity;zt(j,"transform").forEach(c=>c.cancel()),le.getAnimations().forEach(c=>c.cancel()),r&&(j.style.transform=`translateY(${r}px)`),s!==1&&(le.style.opacity=String(s));let i=r<0?-Xo(-r,j.offsetHeight):r;e={y:n.clientY-i,t:performance.now(),dy:r,v:0,y0:r,off:s-Zr(r)},j.setPointerCapture(n.pointerId)}),j.addEventListener("pointermove",n=>{if(!e)return;let o=n.clientY-e.y,r=performance.now(),s=o>0?o:-Qo(-o,j.offsetHeight);e.v=(s-e.dy)/Math.max(1,r-e.t),e.dy=s,e.t=r,j.style.transform=`translateY(${s}px)`,le.style.opacity=String(Math.min(1,Math.max(0,Zr(s)+e.off)))});let t=()=>{if(!e)return;let{dy:n,v:o,y0:r}=e;if(e=null,n!==r&&Jo(n,o,j.offsetHeight))return Se();let s=j.style.transform,i=getComputedStyle(le).opacity;j.style.transform="",le.style.opacity="";let c={duration:K.duration,easing:K.easing};n!==0&&O(j,[{transform:s},{transform:"none"}],c),+i!=1&&O(le,[{opacity:i},{opacity:1}],c)};j.addEventListener("pointerup",t),j.addEventListener("pointercancel",t)}function qe(e,t={}){return a("div",{class:`vhead${t.back?" center":""}${t.acts?" with-acts":""}`},t.back?a("button",{type:"button",class:"knob back","aria-label":_("Back"),onclick:va},z("chevron")):null,a("h2",{},e))}var Ke=e=>a("p",{class:"vsub"},e),St=(...e)=>a("p",{class:"hint"},...e);function cs(){we(()=>{let e=ht();return{el:a("div",{class:"view"},qe(_("Open on another device")),Ke(_("Point its camera at the code: this page opens there.")),qt(e,!0),xt(e)),label:_("Open on another device")}})}var xa='',$n=null,At=null,Dn=null;function yo(e){if(At)return At;$n=a("header",{class:"crumbs"}),At=a("div",{class:"page-body"}),e.replaceChildren(a("div",{class:"edge-fade top","aria-hidden":"true"}),a("div",{class:"edge-fade bot","aria-hidden":"true"}),Dn=a("main",{class:"page"},$n,At));let t=()=>document.body.classList.toggle("scrolled",scrollY>2);return addEventListener("scroll",t,{passive:!0}),t(),At}function ls(){let e=At;if(!e)return()=>{};let t=e.getBoundingClientRect(),n=innerHeight-t.top-(document.documentElement.scrollHeight-scrollY-t.bottom);return e.getAnimations().forEach(o=>o.cancel()),e.style.minHeight=`${n}px`,()=>{let o=e.lastElementChild,r=o?o.getBoundingClientRect().bottom-e.getBoundingClientRect().top:0;e.style.minHeight="",rTn(e,rn.map(t=>({label:t.name,checked:t.code===tt(),run:()=>t.code!==tt()&&Jn(t.code)})))),e}function bo(e=!1,t=!1){var r;if(!$n)return;let n=e?null:(r=ue())==null?void 0:r.person,o=a("span",{class:n?"":"cur","aria-current":n?null:"page"},nt());$n.replaceChildren(a("span",{class:"cr-mark"},Ae(xa)),a("nav",{class:"cr-path","aria-label":_("Breadcrumb")},o,n?[z("chevron"),a("span",{class:"cur","aria-current":"page"},n.name)]:null),...t?[]:[wa()],...n&&!t?[a("button",{type:"button",class:"knob cr-qr","aria-label":_("Open on another device"),onclick:cs},z("qr"))]:[])}function us(e,t,n=10){let o=c=>($e(c).getDay()+6)%7,r=pt(e,-o(e)),s=pt(t,6-o(t)),i=[];for(let c=r;c<=s;c=pt(c,1))if(i.push({day:c,kind:cn*7)return null;return i}var Ma=/^([01]?\d|2[0-3]):([0-5]\d)$/;function ds(e){let t=Ma.exec(e.trim());return t?+t[1]*60+ +t[2]:null}var jt=e=>(e%1440+1440)%1440,at=e=>`${String(Math.floor(jt(e)/60)).padStart(2,"0")}:${String(jt(e)%60).padStart(2,"0")}`;function Pn(e,t,n){let[o,r]=e.split("-"),s=ds(o!=null?o:""),i=ds(r!=null?r:"");if(s==null||i==null)return null;let c=t==null?0:n-t;return{from:jt(s+c),to:jt(i+c),yours:t!=null}}var ps=e=>e.fromjt(Math.floor(e/60)+t);function ms(e){let t=$e(e);return{days:new Date(t.getFullYear(),t.getMonth()+1,0).getDate(),day:t.getDate()}}var hs={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:''},lan:{b:'',f:'',d:''}},Ea=()=>sn("amnezia","").replace(/^]*>/,"").replace(/<\/svg>$/,""),ka=0;function Ca(e,t="grey",n="gi"){var i;let o=(i=hs[e])!=null?i:hs.other,r=`gl${++ka}`,s=o.d===null?`${Ea()}`:`${o.d}`;return``}var ee=(e,t="grey",n="gi")=>Ae(Ca(e,t,n));function On(e,t,n,o){return a("div",{class:`notice ${e}`},ee(t,e==="bad"?"red":"orange"),a("div",{class:"t"},n?a("b",{},n):null,a("span",{},o)))}function La(e){var o;let t=Pn(e,(o=ue())==null?void 0:o.tz_offset,-new Date().getTimezoneOffset());if(!t)return V(_("%s (router time)"),e.replace("-","–"));let n=`${at(t.from)}–${at(t.to)}`;return V(t.yours?_("%s your time"):_("%s (router time)"),n)}function xo(e){switch(e.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"),V(_("Open %s."),La(e.hours))];default:return["pause",_("Access paused"),_("Your devices can’t connect until it’s resumed.")]}}function Ta(e){if(e.state!=="active")return On(e.state==="quota"||e.state==="expired"?"bad":"warn",...xo(e));let t=ln(e.expires,Ie());return $t(e,t)?On("warn","calendar",V(_("Access %s"),er(t)),V(_("On %s."),cn(e.expires))):null}function gs(e,t,n){let o=Ta(t);if(!n)return Ne(e,o);let r=e.getBoundingClientRect().height,s=!!e.querySelector(":scope > .notice:not([aria-hidden])");e.getAnimations().forEach(c=>c.cancel()),Xe(e,o),o&&!s&&We(o);let i=e.getBoundingClientRect().height;Math.abs(i-r)>.5&&O(e,[{height:`${r}px`},{height:`${i}px`}],{duration:K.duration,easing:K.easing})}var ys=3,vs=e=>e.reduce((t,[n,o])=>[t[0]+n,t[1]+o],[0,0]);function _a(e,t){let n=Math.max(1,...e.map(i=>i[1])),o=Math.max(1,...e.map(i=>i[0])),r=Math.round((t-ys)*Math.min(.8,Math.max(.55,n/(n+o)))),s=t-ys-r;return{top:r,bottom:s,scale:Math.min(r/n,s/o)}}function Rn(e,t,n,o=0){let{top:r,bottom:s,scale:i}=_a(e,n),c=(C,g,b,x)=>{let S=a("i",{class:x});S.style.height=`${Math.max(2,Math.round(b*i))}px`;let P=a("div",{class:`half ${C}`},S);return P.style.height=`${g}px`,P},m=a("div",{class:`bars ${t}`,"aria-hidden":"true"});m.style.height=`${n}px`;let f=e.map(([C,g],b)=>m.appendChild(a("div",{class:`col${b===e.length-1?" today":""}`},c("top",r,g,"dn"),c("bottom",s,C,"up"))));for(let C=0;Ca("span",{class:r,title:s},z("arrow"),a("span",{class:"offscreen"},s),i),n=a("span",{class:"num","data-t":`${e}:dn`}),o=a("span",{class:"num","data-t":`${e}:up`});return{el:a("span",{class:"ud"},t("ud-dn",_("Downloaded"),n),t("ud-up",_("Uploaded"),o)),set([r,s]){ae(n,Be(s)),ae(o,Be(r))}}}var Sa=Array.from({length:31},(e,t)=>{let n=t/30;return 14*Math.exp(-4.2*n)*Math.sin(n*Math.PI*2*3.6)}),bs=700,Aa=800;function Ha(e){e.getAnimations().filter(s=>s.id==="redden").forEach(s=>s.cancel());let t=getComputedStyle(e),o=`${e.classList.contains("field")?"inset ":""}0 0 0 1.5px ${t.getPropertyValue("--bad").trim()||"#e5484d"}`,r=bs+Aa;e.animate([{boxShadow:o,offset:0},{boxShadow:o,offset:bs/r,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}],{duration:r,id:"redden"})}function Ve(e,t={}){if(t.ring!==!1&&Ha(e),typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches)return;let n=getComputedStyle(e).transform,o=n&&n!=="none"?new DOMMatrix(n).m41:0;e.getAnimations().filter(r=>r.id==="shake").forEach(r=>r.cancel()),e.animate(Sa.map((r,s)=>({transform:`translateX(${(s===0?o:r).toFixed(2)}px)`})),{duration:520,easing:"linear",id:"shake"})}function xs(e){return[...e].every(un)?V(_("Up to %s characters."),me(dn)):_("Only letters, digits, - _ .")}function Bn(e,t=e,n=()=>{},o={}){let r=()=>typeof t=="function"?t():t,s=e.value;e.addEventListener("beforeinput",i=>{var g,b,x,S,P;if(s=e.value,i.inputType.startsWith("delete")||i.isComposing||i.inputType==="insertCompositionText")return;let c=(x=(b=i.data)!=null?b:(g=i.dataTransfer)==null?void 0:g.getData("text/plain"))!=null?x:"",m=(S=e.selectionStart)!=null?S:e.value.length,f=(P=e.selectionEnd)!=null?P:m,C=e.value.slice(0,m)+c+e.value.slice(f);eo(C)||(i.preventDefault(),Ve(r(),o),n(xs(C)))}),e.addEventListener("input",i=>{var C;if(i instanceof InputEvent&&i.inputType.startsWith("delete")||eo(e.value)){s=e.value,n(null);return}let m=e.value,f=Math.min((C=e.selectionStart)!=null?C:s.length,s.length);e.value=s,e.setSelectionRange(f,f),i.stopImmediatePropagation(),Ve(r(),o),n(xs(m))})}var Da=16.67;function $a(e,t){if(t>15)return e.x=e.t,e.v=0,!1;let n=Math.min(2.5,Math.max(0,t));return e.v+=(e.t-e.x)*.12*n,e.v*=Math.pow(.62,n),e.x+=e.v*n,Math.abs(e.t-e.x)<.05&&Math.abs(e.v)<.05?(e.x=e.t,e.v=0,!1):!0}function Pa(e,t){let n=s=>Math.min(e.left+e.width,Math.max(e.left,e.left+t(e.value.slice(0,s))-e.scroll)),o=n(e.start),r=e.end===e.start?o:n(e.end);return{caret:e.backward?o:r,start:o,end:r,range:e.start!==e.end}}var Oa=["fontFamily","fontSize","fontWeight","letterSpacing","fontFeatureSettings","fontVariationSettings"];function In(e){let t=e.querySelector("input");if(!t)return;let n=matchMedia("(pointer: fine)").matches;e.classList.add("own-caret"),n&&e.classList.add("own-sel");let o=a("span",{class:"caret-sel"}),r=a("span",{class:"caret-hd s"}),s=a("span",{class:"caret-hd e"}),i=a("span",{class:"caret"}),c=a("span",{class:"caret-mirror","aria-hidden":"true"});e.append(o,r,s,i,c);let m=N=>{c.textContent=N;let U=e.getBoundingClientRect().width;return c.getBoundingClientRect().width*(U?e.offsetWidth/U:1)},f=()=>{var N,U;return Pa({value:t.value,start:(N=t.selectionStart)!=null?N:0,end:(U=t.selectionEnd)!=null?U:0,backward:t.selectionDirection==="backward",left:t.offsetLeft,width:t.clientWidth,scroll:t.scrollLeft},m)},C=()=>({x:0,v:0,t:0}),g=C(),b=C(),x=C(),S=[g,b,x],P=(N,U)=>{N.x=N.t=U,N.v=0},F=!1,A=()=>document.activeElement===t,y=()=>{i.style.transform=`translateX(${(g.x-1).toFixed(2)}px)`,o.style.transform=`translateX(${Math.min(b.x,x.x).toFixed(2)}px)`,o.style.width=`${Math.abs(x.x-b.x).toFixed(2)}px`,r.style.transform=`translateX(${(b.x-1).toFixed(2)}px)`,s.style.transform=`translateX(${(x.x-1).toFixed(2)}px)`},w=0,p=0,u=N=>{let U=p?(N-p)/Da:1;p=N;let Z=!1;for(let oe of S)$a(oe,U)&&(Z=!0);y(),w=Z?requestAnimationFrame(u):0,w||(p=0)},l=()=>{if(se())return S.forEach(N=>P(N,N.t)),y();w||(w=requestAnimationFrame(u))},v=!0,h=0,d=0,L=!1,M=0,H=()=>{if(!A())return clearTimeout(h),i.classList.remove("on","blink"),e.classList.remove("selecting"),F=!1,y();if(v){let U=getComputedStyle(t);for(let Z of Oa)c.style[Z]=U[Z]}let N=f();if(v&&(S.forEach(U=>P(U,N.start)),v=!1),N.range&&n)F||(clearTimeout(d),L||(b.x=x.x=g.x,b.v=x.v=0),L=!1),F=!0,b.t=N.start,x.t=N.end,g.t=N.caret,e.classList.add("selecting"),i.classList.remove("on","blink");else if(N.range){i.classList.remove("on","blink");return}else F?(e.classList.remove("selecting"),clearTimeout(d),L=!0,d=window.setTimeout(()=>{L=!1,!F&&(P(b,g.t),P(x,g.t),y())},160)):L||(P(b,N.start),P(x,N.start)),F=!1,performance.now()-M<400?P(g,N.caret):g.t=N.caret,i.classList.add("on"),i.classList.remove("blink"),clearTimeout(h),h=window.setTimeout(()=>{A()&&i.classList.add("blink")},500);l()},q=0,R=()=>{q||(q=requestAnimationFrame(()=>{q=0,H()}))};for(let N of["pointerdown","pointerup"])t.addEventListener(N,()=>M=performance.now());for(let N of["input","keydown","keyup","pointerup","select","scroll"])t.addEventListener(N,R);t.addEventListener("pointermove",N=>{N.buttons&&R()});let W=()=>{A()&&R()};t.addEventListener("focus",()=>{v=!0,document.addEventListener("selectionchange",W),R()}),t.addEventListener("blur",()=>{document.removeEventListener("selectionchange",W),R()})}var ws={opacity:0,transform:"translateY(-4px)",filter:"blur(4px)"},Ms={opacity:1,transform:"none",filter:"none"};function Es(){let e=a("p",{class:"hint bad-t",hidden:!0}),t=m=>Yt(e)?Hn(m):m(),n=null,o=0,r=()=>{let m=getComputedStyle(e);return{opacity:m.opacity,transform:m.transform,filter:m.filter}},s=(m,f,C)=>{let g=n;n=O(e,[m,f],C),g==null||g.cancel()};return{el:e,say:m=>{if(e.hidden)return t(()=>{ae(e,m),e.hidden=!1}),s(ws,Ms,{duration:220,easing:Q});let f=o?r():null;te(e,m),f&&(clearTimeout(o),o=0,s(f,Ms,{duration:220,easing:Q}))},unsay:()=>{if(e.hidden||o)return;let m=r();ae(e,ve(e)),s(m,ws,{duration:180,easing:J,fill:"forwards"}),o=window.setTimeout(()=>{o=0,t(()=>{e.hidden=!0,n==null||n.cancel(),n=null})},170)}}}function Ra(e){let t=a("div",{class:"view"},qe(_("Open the link securely")),Ke(_("Connection settings only travel encrypted")),a("div",{class:"center-col secure"},ee("lock","blue","gi xl"),a("p",{},_("This page is open without encryption. To add or set up a device, open the same link over HTTPS:"))),a("a",{class:"btn accent block",href:e},z("lock"),a("span",{},_("Open securely"))),St(_("The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).")));return t.lastElementChild.classList.add("secure-note"),{el:t,label:_("Open the link securely")}}var Qt=e=>we(()=>Ra(e));function Ht(){let e=xr();return e?(Qt(e),!0):!1}var Na={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"",s4:"",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Ba={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 Ia(e){let t={};for(let[n,o]of Object.entries(Ba))e[n]!=null&&e[n]!==""&&(t[o]=String(e[n]));return t}function Wa(e,t){var m;let n=e.amnezia,o=(m=n.obfuscation)!=null?m:{},r=f=>o[f]!=null&&o[f]!==""?String(o[f]):Na[f],s=n.host.replace(/^\[(.*)\]$/,"$1"),i={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...Ia(o),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:e.conf.replace(/\r?\n/g,`\r +`),hostName:s,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},c={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(i),port:String(n.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:s};return n.dns[0]&&(c.dns1=n.dns[0],c.dns2=n.dns[1]||n.dns[0]),c}function Fa(e){let t="";for(let n=0;ne.replace(/^vpn:\/\//,"");var Cs=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],qa={opacity:0,filter:"blur(2px)"};function Ls(e,t,n){let o=e.getAnimations();O(e,t,n),o.forEach(r=>r.cancel())}var Ka=new Set(["offset","computedOffset","easing","composite"]),Va=e=>e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`);function Dt(...e){let t=[],n=[],o=new Set;for(let s of e)for(let i=s;i&&!o.has(i);i=i.parentElement)if(o.add(i),!(!(i instanceof HTMLElement)||i.classList.contains("closing")))for(let c of i.getAnimations()){let m=c.playState==="running"&&c.effect instanceof KeyframeEffect?c.effect.getKeyframes():[],f=m[m.length-1];if(f&&("width"in f||"maxWidth"in f)&&n.push({a:c,t:c.currentTime}),!(f!=null&&f.height)||f.height==="0px")continue;let C=getComputedStyle(i),g={},b={};for(let x of Object.keys(f))Ka.has(x)||(g[x]=C.getPropertyValue(Va(x)),b[x]=f[x]);t.push({el:i,a:c,t:c.currentTime,cur:g,to:b})}if(!t.length)return;[...t,...n].forEach(s=>s.a.cancel());let r=t.map(s=>getComputedStyle(s.el).height);for(let s of n)s.a.play(),s.a.currentTime=s.t;t.forEach((s,i)=>{s.a.play(),Math.abs(parseFloat(r[i])-parseFloat(String(s.to.height)))<.5?s.a.currentTime=s.t:s.a.effect.setKeyframes([s.cur,{...s.to,height:r[i]}])})}function ze(e,t={}){let n=a("div",{class:`acc${t.inset?" inset":""}`}),o=e.map((g,b)=>{var w;let x=g.body.filter(p=>!!p),S=!x.length,P=[g.icon,a("span",{class:"acc-title"},a("span",{class:"t"},g.title),(w=g.tag)!=null?w:null),g.val?a("span",{class:`acc-val${g.valHide?" hide-open":""}`},g.val):null],F=b===t.open&&!S,A=S?a("div",{class:"acc-head"},...P):a("button",{type:"button",class:"acc-head","aria-expanded":String(F),onclick:()=>C(y)},...P,z("chevron","i acc-chev")),y=a("div",{class:`acc-row${S?" still":""}${F?" open":""}`},A,a("div",{class:"acc-body"},...x));return n.appendChild(y),y}),r=g=>g.querySelector(".acc-body"),s=()=>o.forEach((g,b)=>{let x=g.classList.contains("open");g.classList.toggle("rt",b===0||x||o[b-1].classList.contains("open")),g.classList.toggle("rb",b===o.length-1||x||o[b+1].classList.contains("open"))}),i=g=>{let b=getComputedStyle(g),x={};for(let S of Cs)x[S]=S==="height"?`${g.getBoundingClientRect().height}px`:b[S];return x},c=()=>o.forEach(g=>{var b;return(b=g.querySelector("button.acc-head"))==null?void 0:b.setAttribute("aria-expanded",String(g.classList.contains("open")))}),m=g=>g.classList.contains("open")||g.classList.contains("closing"),f=g=>{if(!m(g))return qa;let b=getComputedStyle(r(g));return{opacity:b.opacity,filter:b.filter==="none"?"blur(0px)":b.filter}};function C(g){var w,p;let b=o.map(i),x=o.map(f),S=(w=t.hold)==null?void 0:w.call(t);o.forEach(u=>u.getAnimations().forEach(l=>l.cancel()));let P=!g.classList.contains("open"),F=o.filter(u=>m(u)&&!(u===g&&P));o.forEach(u=>{u.classList.remove("closing"),u!==g&&u.classList.remove("open")}),g.classList.toggle("open",P),P&&g.classList.add("opened"),s();let A=Lt(),y=o.map(i);if(S==null||S(),Dt(n.parentElement),o.forEach((u,l)=>{let v=()=>{u.classList.remove("closing"),u.classList.contains("open")||u.classList.remove("opened")};if(!Cs.some(h=>b[l][h]!==y[l][h]))return v();F.includes(u)&&u.classList.add("closing"),O(u,[b[l],y[l]],{duration:Le.duration,easing:Le.easing}).onfinish=v}),F.forEach(u=>{let l=x[o.indexOf(u)];Ls(r(u),[l,{opacity:0,filter:"blur(2px)"}],{duration:160*Number(l.opacity),easing:J,fill:"forwards"})}),P){let u=x[o.indexOf(g)];Ls(r(g),[u,{opacity:1,filter:"blur(0px)"}],{duration:300*(1-Number(u.opacity)),easing:"cubic-bezier(0,0,.58,1)"})}Tt(A),c(),(p=t.onToggle)==null||p.call(t,o.indexOf(g),P,!1)}return s(),{el:n,openIndex:()=>o.findIndex(g=>g.classList.contains("open")),setOpen(g){o.forEach((b,x)=>{[b,r(b)].forEach(P=>P.getAnimations().forEach(F=>F.cancel()));let S=x===g&&!b.classList.contains("still");b.classList.toggle("open",S),b.classList.remove("closing"),S||b.classList.remove("opened")}),s(),c(),o.forEach((b,x)=>{var S;return(S=t.onToggle)==null?void 0:S.call(t,x,b.classList.contains("open"),!0)})}}}function za(e,t){let n=Math.min(1,Math.max(0,e.opacity));if(t)return{duration:280*(1-n),delay:70*(1-n)};let o=Math.max(n,e.full>0?Math.min(1,e.width/e.full):0);return{duration:o>.01?220*o:0,delay:0}}function Ts(e,t,n){let o=a("span",{class:"seg-pill"}),r=a("div",{class:"seg appseg",role:"tablist"},o),s=e.map(b=>{let x=a("button",{type:"button",class:"seg-b",role:"tab","aria-label":b.label,title:b.label,onclick:()=>g(b.value)},z(b.icon),a("span",{class:"seg-l"},b.label));return x.dataset.v=b.value,r.appendChild(x),x}),i=b=>b.querySelector(".seg-l"),c=()=>s.forEach(b=>{let x=b.dataset.v===t;b.classList.toggle("on",x),b.setAttribute("aria-selected",String(x))}),m=()=>{let b=s.find(x=>x.dataset.v===t);return b&&b.offsetWidth?[b.offsetLeft,r.clientWidth-b.offsetLeft-b.offsetWidth]:null},f=()=>{let b=m();b&&(o.style.left=`${b[0]}px`,o.style.right=`${b[1]}px`)},C=0;function g(b){if(b===t)return;let x=s.findIndex(R=>R.dataset.v===t),S=s.findIndex(R=>R.dataset.v===b),P=getComputedStyle(o),F=parseFloat(P.left)||0,A=parseFloat(P.right)||0,y=s.map(R=>parseFloat(getComputedStyle(R).flexGrow)||0),w=s.map(R=>getComputedStyle(R).flexBasis),p=s.map(i),u=p.map(R=>{let W=getComputedStyle(R);return{width:R.getBoundingClientRect().width,opacity:+W.opacity,filter:W.filter,marginLeft:W.marginLeft}});[...s,...p].forEach(R=>R.getAnimations().forEach(W=>W.cancel())),t=b,c();let l=p[S].getBoundingClientRect().width;s.forEach((R,W)=>{let N=W===S?1:0,U=getComputedStyle(R).flexBasis;(y[W]!==N||w[W]!==U)&&O(R,[{flexGrow:y[W],flexBasis:w[W]},{flexGrow:N,flexBasis:U}],{duration:K.duration,easing:K.easing})}),p.forEach((R,W)=>{let N=u[W],U=za({...N,full:R.scrollWidth},W===S);if(W!==S){U.duration&&O(R,[{opacity:N.opacity,maxWidth:`${N.width}px`,marginLeft:N.marginLeft,filter:N.filter},{opacity:0,maxWidth:"0px",marginLeft:"-8px",filter:N.filter}],{duration:U.duration,easing:"ease-out"});return}O(R,[{maxWidth:`${N.width}px`,marginLeft:N.marginLeft},{maxWidth:`${l}px`,marginLeft:"0px"}],{duration:K.duration,easing:K.easing}),O(R,[{opacity:N.opacity,filter:N.opacity?N.filter:"blur(4px)"},{opacity:1,filter:"none"}],{...U,easing:Q,fill:"backwards"})});let v=S>x,h=se()?K:Yo,d=performance.now(),L=Math.max(K.duration,h.duration),M=v?K:h,H=v?h:K;cancelAnimationFrame(C);let q=()=>{let R=se()?L:performance.now()-d,W=m();if(!W){C=0;return}o.style.left=`${F+(W[0]-F)*M.at(R)}px`,o.style.right=`${A+(W[1]-A)*H.at(R)}px`,C=R{C||f()}).observe(r),{el:r,sync(b){b!==t&&(t=b,c(),f())}}}var Ds={vpn:"amnezia",awg:"amneziawg",wg:"wireguard"},$s=e=>`dl.app.${e.id}`;function Ps(e){try{let t=localStorage.getItem($s(e));return t==="vpn"||t==="awg"||t==="wg"?t:null}catch{return null}}function Os(e,t){try{localStorage.setItem($s(e),t)}catch{}}function Ze(e,t=!1){var s,i;let n=[a("span",{class:"b-ic"},z(e.mark)),a("span",{class:"b-t"},a("span",{class:"b-top"},e.top),a("span",{class:"b-main"},e.main)),z(e.onclick||(s=e.href)!=null&&s.startsWith("vpn:")?"chevron":"open")],o=`badge${t?" primary":""}`;if(e.onclick)return a("button",{type:"button",class:o,onclick:e.onclick},n);let r=(i=e.href)==null?void 0:i.startsWith("vpn:");return a("a",{class:o,href:e.href,target:r?null:"_blank",rel:"noopener noreferrer"},n)}function Rs(e,t,n){let o=n?lr(e):cr(e,t);return o?o.alt?[a("div",{class:"badges2"},Ze(o),Ze(o.alt)),St(o.alt.why)]:[Ze(o)]:[St(V(_("Get %s on the %s and come back here."),he[e],pr(t)))]}var _s=e=>a("ol",{class:"howto"},e.map(([t,n])=>a("li",{},t.replace(/ → $/," ›"),n?[" ",a("b",{},n)]:null))),Ua=(e,t)=>a("button",{type:"button",onclick:t},e);function Ns(e){let t=e.app(),n=he[t],o=e.pf==="ios"||e.pf==="android",r=e.same()&&o,s=m=>be(e.key,_("Key copied"),m.currentTarget),i=t==="vpn"&&r&&!oo(e.pf)?st(Ot(e.cfg.filename),e.key):null;if(t==="vpn"&&r&&(oo(e.pf)||i))return[Ze(i?{top:_("Then come back here and tap"),main:_("Send to AmneziaVPN"),mark:"amnezia",onclick:()=>void i()}:{href:e.key,top:_("Then come back here and tap"),main:_("Open in AmneziaVPN"),mark:"amnezia"},!0),St(...ut(i?_("Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app."):_("Nothing opened? %s and add it in the app."),Ua(_("Copy the key","in a sentence"),s)))];if(t==="vpn"){let m=mn("vpn");return[Ze({top:_("The connection as one key"),main:_("Copy the key"),mark:"copy",onclick:s},!0),_s([[V(_("Open %s","step"),n),""],[m.replace(/ → [^→]*$/," → "),m.replace(/^.* → /,"")],[dr(),""]])]}let c=o?st(e.cfg.filename,e.cfg.conf):null;return[Ze(c?{top:e.same()?V(_("Straight into %s"),n):V(_("Send it to the %s"),e.there),main:_("Share the file"),mark:"share",onclick:()=>void c()}:{top:_("Then import it in the app"),main:_("Download the file"),mark:"download",onclick:()=>Cn(e.cfg.filename,e.cfg.conf)},!0),_s(ur(t,e.pf,e.cfg.filename,!!c&&e.same()))]}function Bs(e){let t=e.app(),n=(r,s,i)=>a("button",{type:"button",class:"btn soft sm",onclick:i},z(r),a("span",{class:"lbl"},s));if(t==="vpn"){let r=Ot(e.cfg.filename),s=!!st(r,e.key);return[a("p",{class:"desc"},V(_("Send it to the %s in a message or a note, then in AmneziaVPN: %s."),e.there,mn("vpn").replace(/ → /g," › "))),a("div",{class:"btnrow2"},n("copy",_("Copy the key"),i=>be(e.key,_("Key copied"),i.currentTarget)),n(s?"share":"download",s?_("Share as a file"):_("Download the key"),()=>Gt(r,e.key)))]}let o=!!st(e.cfg.filename,e.cfg.conf);return[a("p",{class:"desc"},...ut(_("Send it to the %s, then import %s in %s."),e.there,a("b",{},e.cfg.filename),he[t])),a("div",{class:"btnrow2"},n(o?"share":"download",o?_("Share the file"):_("Download the file"),()=>Gt(e.cfg.filename,e.cfg.conf)),n("copy",_("Copy the configuration"),r=>be(e.cfg.conf,_("Configuration copied"),r.currentTarget)))]}function Ya(e){e.style.opacity="0",e.style.visibility="hidden"}function Is(e,t){let n=a("span",{},e,t);n.style.display="inline-grid";for(let o of[e,t])o.style.gridArea="1 / 1";return Ya(t),n}function Wn(e,t,n){let o=getComputedStyle(e),r={opacity:o.opacity,filter:o.filter==="none"?"blur(0px)":o.filter,transform:o.transform},s=e.getAnimations();e.style.opacity=t?"":"0",e.style.visibility="";let i=t?O(e,[r,{opacity:1,filter:"blur(0px)",transform:"none"}],{duration:320,easing:Q}):O(e,[r,n],{duration:200,easing:J});t||(i.onfinish=()=>e.style.visibility="hidden"),s.forEach(c=>c.cancel())}var Ss={opacity:0,filter:"blur(4px)",transform:"none"},As={opacity:0,filter:"blur(3px)",transform:"scale(.6)"};function Hs(e){if(/^\s*\[.+\]\s*$/.test(e))return a("span",{class:"sec"},e);let t=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(e);if(!t)return document.createTextNode(e);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(e)?Is(a("span",{class:"mask"},"••••••••••••••••"),a("span",{class:"secret"},t[2])):t[2];return a("span",{},a("span",{class:"k"},t[1])," ",o)}function Ws(e){let t=!1,n=a("pre",{class:"conf"},e.conf.split(` +`).flatMap((g,b)=>b?[` +`,Hs(g)]:[Hs(g)])),o=!!st(e.filename,e.conf),r=z("key"),s=z("x"),i=a("span",{},_("Show key")),c=a("button",{type:"button",class:"btn soft sm",onclick:()=>{t=!t,te(i,t?_("Hide key"):_("Show key")),n.querySelectorAll(".secret").forEach(g=>Wn(g,t,Ss)),n.querySelectorAll(".mask").forEach(g=>Wn(g,!t,Ss)),Wn(r,!t,As),Wn(s,t,As)}},Is(r,s),i),m=a("button",{type:"button",class:"btn soft sm",onclick:g=>be(e.conf,_("Configuration copied"),g.currentTarget)},z("copy"),a("span",{class:"lbl"},_("Copy"))),f=a("div",{class:"filecard"},a("div",{class:"fc-row"},a("span",{class:"filecard-ic"},".conf"),a("span",{class:"t"},a("span",{class:"mono"},e.filename),a("span",{},_("For computers and routers")))),a("button",{type:"button",class:"btn accent sm block",onclick:()=>Gt(e.filename,e.conf)},z(o?"open":"download"),a("span",{},o?_("Share file"):_("Download")))),C=ze([{icon:ee("file"),title:_("Configuration"),body:[a("div",{class:"confbar"},c,m),n]}],{inset:!0});return a("div",{class:"step-box"},f,C.el)}function Fs(e){let t=a("span",{class:"osm-p"},he[e]),n=Ur(Rt(e,"ios"),Rt(e,"android"));return{el:a("span",{class:"scanline"},a("span",{},...ut(_("In %s:"),t)),n.el),set(o){te(t,he[o],void 0,{whole:!0}),n.set(Rt(o,"ios"),Rt(o,"android"))}}}function Gs(e){let t=a("span",{class:"tt"}),n=a("span",{class:"tt-m"}),o=a("span",{class:"hp-tip","aria-hidden":"true"},t,n),r=a("button",{type:"button",class:"hp-b",onclick:()=>Gt(e().file,e().text)},z("download")),s=a("button",{type:"button",class:"hp-b"},z("copy")),i=a("div",{class:"hpill",role:"group","aria-label":_("The connection"),"data-key":"conn"},r,s,o),c=null,m=0,f=0,C=l=>{var v;return l===s&&s.classList.contains("done")?_("Copied"):(v=l.getAttribute("aria-label"))!=null?v:""},g=(l,v)=>{n.textContent=v;let h=n.offsetWidth+20;return Math.min(l.offsetLeft+l.offsetWidth/2,i.offsetWidth+46-h/2)},b=l=>`translateX(${l}px) translateX(-50%)`,x=()=>{let l=getComputedStyle(o);return{opacity:l.opacity,filter:l.filter==="none"?"blur(0px)":l.filter,transform:l.transform}},S=(l,v)=>{let h=o.getAnimations();O(o,l,v),h.forEach(d=>d.cancel())},P=l=>{let v=x();o.style.transform=b(l),S([v,{opacity:1,filter:"blur(0px)",transform:b(l)}],{duration:K.duration,easing:K.easing})},F=l=>te(t,l),A=l=>{if(clearTimeout(m),c===l&&o.classList.contains("on"))return;if(c=l,o.classList.contains("on")||+getComputedStyle(o).opacity>0){let h=C(l);return o.classList.add("on"),P(g(l,h)),F(h)}let v=()=>{let h=C(l);ae(t,h);let d=g(l,h);o.style.transform=b(d),o.classList.add("on"),S([{opacity:0,transform:`${b(d)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:b(d),filter:"blur(0px)"}],{duration:220,easing:Q})};performance.now(){if(clearTimeout(m),c=null,!o.classList.contains("on"))return;f=performance.now()+500;let l=x();o.classList.remove("on"),S([l,{...l,opacity:0}],{duration:120,easing:"ease-out"})};for(let l of[r,s])l.addEventListener("pointerenter",v=>{v.pointerType==="mouse"&&A(l)}),l.addEventListener("focus",()=>{l.matches(":focus-visible")&&A(l)}),l.addEventListener("blur",v=>{i.contains(v.relatedTarget)||y()});i.addEventListener("pointerleave",y);let w=l=>{let v=z(l);s.querySelector("svg").replaceWith(v),O(v,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Te.duration,easing:Te.easing})},p=()=>{if(c!==s||!o.classList.contains("on"))return;let l=C(s);P(g(s,l)),F(l)},u=0;return s.addEventListener("click",()=>{let l=e();be(l.text,l.msg),clearTimeout(u),s.classList.contains("done")||(s.classList.add("done"),w("check"),p()),u=window.setTimeout(()=>{s.classList.remove("done"),w("copy"),p()},1600)}),{el:i,sync(){let l=e().app;r.setAttribute("aria-label",V(_("Download %s config"),l)),s.setAttribute("aria-label",V(_("Copy %s config"),l))}}}function qs(e,t){var n,o,r;return e?((n=e.setup)==null?void 0:n.state)==="trying"?"trying":e.handshake<=t?"waiting":((o=e.setup)==null?void 0:o.state)==="flowing"?"connected":((r=e.setup)==null?void 0:r.state)==="nodata"?"nodata":"waiting":"waiting"}function ja(e,t){switch(e){case"trying":return[_("Unable to complete the handshake"),_("Your network may be blocking the connection.")];case"connected":return[V(_("%s connected"),t.name),""];case"nodata":return[_("Handshake complete, but no data"),_("This device is using an outdated configuration.")];case"waiting":return[_("Waiting for the connection"),""]}}var Ks={waiting:"",trying:"trying",connected:"done",nodata:"nodata"};function Us(e){let t=a("b",{},_("Waiting for the connection")),n=a("span",{class:"ws",hidden:!0}),o=a("span",{class:"t"},t,n),r=a("div",{class:"way-text"},o),s=a("span",{class:"way-track"},a("span",{class:"way-glow"},a("span",{class:"run"},a("i")),a("span",{class:"knock"},a("i"))),a("span",{class:"way-fill"}),a("span",{class:"way-break"},a("i"))),i=a("div",{class:"way",role:"status","aria-live":"polite"},a("div",{class:"way-row"},a("span",{class:"way-end"},z(e.kind)),s,a("span",{class:"way-end home"},z("server"))),r),c=(x,S)=>{r.getAnimations().forEach(A=>A.cancel()),o.getAnimations().forEach(A=>A.cancel());let P=r.offsetHeight;r.style.overflow="",x!==P&&(r.style.overflow="hidden",O(r,[{height:`${x}px`},{height:`${P}px`}],{duration:340,easing:Q}).onfinish=()=>{r.style.overflow=""});let F=S-o.getBoundingClientRect().top;Math.abs(F)>.5&&O(o,[{transform:`translateY(${F}px)`},{transform:"none"}],{duration:340,easing:Q})},m=()=>{var S;let x=document.createRange();return x.selectNodeContents((S=n.querySelector(":scope > .mt-new"))!=null?S:n),x.getBoundingClientRect()},f="",C=0,g=x=>{if(x===f)return;f=x,clearTimeout(C);let S=!n.hidden,P=getComputedStyle(n),F={opacity:P.opacity,filter:P.filter};if(!x){if(!S)return;n.getAnimations().forEach(u=>u.cancel()),O(n,[F,{opacity:0,filter:"blur(4px)"}],{duration:180,easing:Q,fill:"forwards"}),C=window.setTimeout(()=>{let u=r.offsetHeight,l=o.getBoundingClientRect().top;n.hidden=!0,n.getAnimations().forEach(v=>v.cancel()),c(u,l)},170);return}let A=r.offsetHeight,y=o.getBoundingClientRect().top;if(!S){ae(n,x),n.hidden=!1,c(A,y),O(n,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:300,easing:Q,delay:60,fill:"backwards"});return}let w=ve(n),p=m();ae(n,x),c(A,y),te(n,x,w,{whole:!0,at:p}),n.getAnimations().forEach(u=>u.cancel()),+F.opacity<1&&O(n,[F,{opacity:1,filter:"none"}],{duration:300,easing:Q})},b=x=>{let S=s.querySelectorAll(".way-pkt:not(.out)");if(x){S.length||s.append(a("span",{class:"way-pkt"}),a("span",{class:"way-pkt b"}));return}S.forEach(P=>{P.classList.add("out");let F=getComputedStyle(P).opacity;O(P,[{opacity:F},{opacity:0}],{duration:200,easing:J,fill:"forwards"}).onfinish=()=>P.remove()})};return{el:i,set(x){i.classList.remove("trying","nodata","done","stopped"),Ks[x]&&i.classList.add(Ks[x]);let[S,P]=ja(x,e);te(t,S),g(P),b(x==="nodata")},gaveUp(){i.classList.remove("trying","nodata","done"),i.classList.add("stopped"),b(!1),te(t,_("No connection yet")),g(_("Close this and open it again to keep checking."))}}}function Ys(e,t=4){window.setTimeout(async()=>{var n;try{let o=await ge("state");ye(o),Kt()||_e(),!((n=o.person.devices.find(r=>r.id===e))!=null&&n.online)&&t>1&&Ys(e,t-1)}catch{}},1500)}var Vs=new Set;function js(e,t,n){let o=gt(),r=0,s=0,i=!1,c="waiting",m=Date.now(),f=async()=>{if(r=0,!i){if(c!=="connected"&&Date.now()-m>6e5){i=!0,n();return}if(document.hidden)return C();try{let x=await ge("state");if(ye(x),i)return;let S=x.person.devices.find(F=>F.id===e.id),P=qs(S,o);P!==c&&(P==="connected"&&S&&!S.online&&Ys(e.id),c=P,t(P))}catch(x){if(gn(x)){i=!0;return}}s++,C()}},C=()=>{!i&&!r&&(r=window.setTimeout(f,s<6?5e3:s<12?15e3:3e4))},g=()=>{!document.hidden&&!i&&!r&&f()},b=()=>{i||(r&&clearTimeout(r),f())};return document.addEventListener("visibilitychange",g),Vs.add(b),C(),()=>{i=!0,r&&clearTimeout(r),document.removeEventListener("visibilitychange",g),Vs.delete(b)}}var Fn=new WeakSet;function Gn(e,t,n){if(Fn.has(e)===t)return;if(t?Fn.add(e):Fn.delete(e),se()){if(e.getAnimations().forEach(c=>c.cancel()),!t){e.hidden=!1,O(e,[{opacity:0},{opacity:1}],{duration:n});return}O(e,[{opacity:1},{opacity:0}],{duration:n,fill:"forwards"}).onfinish=()=>{Fn.has(e)&&(e.hidden=!0)};return}e.hidden=!1;let o=getComputedStyle(e),r={height:`${e.getBoundingClientRect().height}px`,marginTop:o.marginTop,marginBottom:o.marginBottom,opacity:o.opacity,filter:o.filter};e.getAnimations().forEach(c=>c.cancel());let s=getComputedStyle(e),i=t?{height:"0px",marginTop:"0px",marginBottom:"0px",opacity:0,filter:"blur(4px)"}:{height:`${e.getBoundingClientRect().height}px`,marginTop:s.marginTop,marginBottom:s.marginBottom,opacity:1,filter:"none"};e.style.overflow="hidden",O(e,[r,i],{duration:n,easing:Q,fill:t?"forwards":"none"}).onfinish=()=>{t||(e.style.overflow="")}}function zs(e,t){let n=getComputedStyle(e).marginBottom;e.getAnimations().forEach(r=>r.cancel());let o=t?"0px":getComputedStyle(e).marginBottom;O(e,[{marginBottom:n},{marginBottom:o}],{duration:520,easing:Q,fill:t?"forwards":"none"})}function Qa(e,t){let n=e.rest,o=n.getBoundingClientRect().height;if(!e.shape(t))return;n.getAnimations().forEach(s=>s.cancel());let r=n.getBoundingClientRect().height;n.style.overflow="hidden",O(n,[{height:`${o}px`},{height:`${r}px`}],{duration:420,easing:Q}).onfinish=()=>{n.style.overflow=""},O(n,[{opacity:.4,filter:"blur(2px)"},{opacity:1,filter:"none"}],{duration:320,easing:Q})}function Qs(e,t,n){let o=!1,r=[],s=(c,m)=>r.push(window.setTimeout(m,c));return{seen:c=>{if(r.forEach(clearTimeout),r=[],t.set(c),Gn(n.sub,c!=="waiting",380),is(c==="connected"),c==="connected"){as(),s(400,()=>{Yt(t.el)&&(o=!0,Gn(n.rest,!0,520),zs(t.el,!0),s(2400,()=>{Yt(t.el)&&(_t(()=>_e({flash:e.id})),Se())}))});return}if(!o)return Qa(n,c);o=!1,n.shape(c),Gn(n.rest,!1,520),zs(t.el,!1)},gaveUp(){Gn(n.sub,!0,380),t.gaveUp()}}}async function Xa(e){try{return await ge(`devices/${e.id}/config`)}catch(t){return t instanceof je&&t.httpsUrl?Qt(t.httpsUrl):Pe(t.message,!0),null}}async function qn(e,t,n=!1){if(Ht())return;let o=async()=>{let r=await Xa(e);if(!r)return;let s=await wo(r,r.server);we(()=>ei(e,r,s,n))};t instanceof HTMLButtonElement?await bt(t,o):await o()}async function Kn(e,t){let n=await wo(t,t.server);An(()=>ei(e,t,n))}function Xs(e,t,n){return a("div",{class:"step"},a("span",{class:"step-n"},e),a("div",{class:"step-b"},typeof t=="string"?a("span",{class:"step-t"},t):t,n))}var Js={height:"0px",opacity:0,filter:"blur(4px)"};function Ja(e,t,n){let o=getComputedStyle(e),r=e.hidden?Js:{height:`${e.getBoundingClientRect().height}px`,opacity:o.opacity,filter:o.filter==="none"?"blur(0px)":o.filter};if(e.getAnimations().forEach(i=>i.cancel()),e.hidden=t,Dt(e.parentElement),n){e.style.overflow="";return}e.style.overflow="hidden",e.hidden=!1;let s=t?Js:{height:`${e.getBoundingClientRect().height}px`,opacity:1,filter:"blur(0px)"};O(e,[r,s],{duration:K.duration,easing:K.easing}).onfinish=()=>{e.style.overflow="",e.hidden=t}}var Za=e=>{var t;return[...(t=e==null?void 0:e.querySelectorAll("button:not([disabled]), a[href], input:not([disabled])"))!=null?t:[]].find(n=>n.getClientRects().length>0)};function Zs(e,t,n,o){let[r,s]=[...t.children].slice(-2),i=t.querySelector(":scope > .steps-gap"),c=[...s.querySelectorAll(":scope > .step-n, :scope > .step-b > .step-t")],m="steps",f=null;return C=>{let g=C==="trying"?"again":C==="nodata"?"conn":"steps";if(g===m)return!1;m=g;let b=document.activeElement,x=b instanceof HTMLElement&&(t.contains(b)||!!(n!=null&&n.el.contains(b))||!!(f!=null&&f.contains(b)));f==null||f.remove(),f=null,n==null||n.setOpen(-1),n&&(n.el.hidden=g!=="steps");let S=g==="conn"||g==="again"&&o;for(let P of[i,r,...c])P&&(P.hidden=S);if(g==="steps")e.append(t);else{let P=g==="again"?_("Set it up again"):o?_("Import the configuration again"):_("Add the connection again");f=ze([{icon:ee("refresh","blue"),title:P,body:[t]}],{inset:!0,open:g==="conn"?0:-1}).el,e.append(f)}if(x){let P=b.isConnected&&b.getClientRects().length?b:g==="again"?f==null?void 0:f.querySelector(".acc-head"):Za(S?s:t);P==null||P.focus({preventScroll:!0})}return!0}}function ei(e,t,n,o=!1){var Ce,et;let r=hn(),s=ar(br()),i=e.kind==="phone"||e.kind==="tablet",c=e.kind==="router",m=ir(e.kind,r,o),f=m?"same":c?"router":i?"away":"pc-away",C=ro(e.kind),g=ro(e.kind,!0),b=s.filter(k=>!c||k.id!=="vpn"),x=(Ce=Ps(e))!=null?Ce:c?"awg":"vpn";b.some(k=>k.id===x)||(x=b[0].id);let S={d:e,cfg:t,key:n,pf:r,there:C,app:()=>x,same:()=>m},P=[],F=()=>{if(b.length<2)return null;let k=Ts(b.map(T=>({value:T.id,label:T.name,icon:Ds[T.id]})),x,T=>{x=T,Os(e,T),P.forEach(E=>E.sync(T)),Hn(H),Dt(A,y,w,p,u)});return P.push(k),k.el},A=a("span",{class:"step-t"}),y=a("div",{class:"step-box"}),w=a("div",{class:"step-box"}),p=a("div",{class:"step-box"}),u=a("div",{class:"step-box"}),l=fr(ht(),e.id),v={text:l,words:()=>[a("span",{},x==="vpn"?V(_("The key is too long for a code. Scan this one to open your link on the %s instead."),g):V(_("The configuration is too long for a code. Scan this one to open your link on the %s instead."),g))]},h=null,d=null,L=null,M=f==="away"?Gs(()=>({...x==="vpn"?{text:n,msg:_("Key copied"),file:Ot(t.filename)}:{text:t.conf,msg:_("Configuration copied"),file:t.filename},app:he[x]})):null;function H(){if(te(A,c?V(_("Get %s on the router"),he[x]):V(_("Get %s"),he[x]),void 0,{whole:!0}),Xe(y,Rs(x,r,c)),c?w.firstChild||Ne(w,Ws(t)):Xe(w,Ns(S)),f==="away"){let k=x==="vpn"?ks(n):t.conf;h&&d&&h.el.isConnected?L!==x&&(h.swap(k),d.set(x)):(d=Fs(x),h=uo(k,[d.el],v),p.replaceChildren(h.el)),L=x}Xe(u,Bs(S)),M==null||M.sync()}H();let q=()=>[i?uo(l,[a("span",{},_("Point its camera at the code: the link opens there."))]).el:a("p",{class:"desc"},V(_("Open this link on the %s to set it up there."),g)),xt(l)],R=()=>Xs("1",A,[F(),y]),W=()=>Xs("2",c?_("Import the configuration"):_("Add the connection"),[w]),N=a("div",{class:"setup"});sr(navigator.userAgent)&&N.appendChild(On("warn","shield",null,_("Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.")));let U=()=>!1;if(f==="same"){let k=a("div",{class:"steps-wrap"},a("div",{class:"steps-gap"}),R(),W()),T=ze([{icon:ee("link"),title:V(_("Not on the %s right now?"),g),body:q()}],{inset:!0,onToggle:(E,D,$)=>Ja(k,D,$)});N.append(T.el,k),U=Zs(N,k,T,!1)}else if(f==="router"){let k=a("div",{class:"steps-wrap"},R(),W());N.append(k),U=Zs(N,k,null,!0)}else f==="away"?N.appendChild(ze([{icon:ee("link"),title:V(_("Open your link on the %s"),g),body:q()},{icon:ee("app"),title:_("Already has the app"),body:[F(),p]}],{inset:!0,open:1}).el):N.appendChild(ze([{icon:ee("link"),title:V(_("Open your link on the %s"),g),body:q()},{icon:ee("key"),title:_("Copy or save the connection"),body:[F(),u]}],{inset:!0,open:0}).el);let Z=Ke(f==="same"?_("Two steps, about a minute"):c?_("The packages and the file for OpenWrt"):V(_("The app goes on the %s."),C)),oe=Us(e),de=Qs(e,oe,{sub:Z,rest:N,shape:U});ns(js(e,de.seen,de.gaveUp)),_t(()=>_e());let ke=V(_("Set up %s"),e.name);return{el:a("div",{class:"view"},qe(ke,{acts:!!M}),Z,oe.el,N),label:ke,acts:(et=M==null?void 0:M.el)!=null?et:null}}var Me=navigator.userAgent,oi=/iPad/.test(Me)||/Macintosh/.test(Me)&&navigator.maxTouchPoints>1;function Jt(){return oi||/Tablet/i.test(Me)||/Android/.test(Me)&&!/Mobile/.test(Me)?"tablet":/Android|iPhone|Mobile/i.test(Me)?"phone":"computer"}var ec=[[/^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"]],Mo="",tc=(async()=>{var t;let e=navigator.userAgentData;if(!e||!/Android/.test(Me))return"";try{let n=((t=(await e.getHighEntropyValues(["model"])).model)!=null?t:"").trim();if(!n||n==="K")return"";let o=ec.find(([r])=>r.test(n));Mo=o?`${o[1]} (${n})`:/^SM-/.test(n)?`Galaxy ${n}`:n}catch{}return Mo})();function nc(e){return/iPhone/.test(Me)?"iPhone":oi?"iPad":/Android/.test(Me)?Mo||(e==="tablet"?_("Android tablet"):_("Android phone")):/CrOS/.test(Me)?"Chromebook":/Mac OS X/.test(Me)?"Mac":/Windows/.test(Me)?_("Windows PC"):/Linux/.test(Me)?_("Linux PC"):to(e)}var ti=e=>e==="mobile"?_("Mobile"):no(e),Xt=e=>e==="phone"||e==="tablet"?"mobile":e,ni=e=>e!=="mobile"?e:Jt()==="tablet"?"tablet":"phone";function oc(e,t){var c,m;let n=getComputedStyle(e),o=e.hidden?{h:0,o:0,b:4,m:-1}:{h:e.getBoundingClientRect().height,o:+n.opacity,b:+((m=(c=n.filter.match(/blur\(([\d.]+)px\)/))==null?void 0:c[1])!=null?m:0),m:parseFloat(n.marginTop)||0};e.getAnimations().forEach(f=>f.cancel()),e.hidden=!1,e.style.overflow="hidden";let r=t?{h:e.scrollHeight,o:1,b:0,m:0}:{h:0,o:0,b:4,m:-1},s=f=>({height:`${f.h}px`,opacity:f.o,filter:f.b?`blur(${f.b}px)`:"none",marginTop:`${f.m}px`}),i=O(e,[s(o),s(r)],{duration:K.duration,easing:K.easing,fill:"forwards"});i.onfinish=()=>{e.hidden=!t,e.style.overflow="",i.cancel()}}function Zt(){let e=ue();if(!e||e.locked)return;if(!e.can_add)return Pe(Ue(e.person.device_limit,"You have reached your limit of %s device","You have reached your limit of %s devices"),!0);if(Ht())return;let t={bypass:!1};we(()=>rc(t))}function rc(e){var v,h;let t=ue(),n=t.person,o=["computer","mobile","router","other"].filter(d=>t.kinds.some(L=>Xt(L)===d)),r=o.includes(Xt(Jt()))?Xt(Jt()):o[0],s=e.pick&&o.includes(e.pick)?e.pick:r,i=new Set(n.devices.map(d=>d.name.toLowerCase())),c=d=>{let L=d===Xt(Jt())?nc(ni(d)):to(d==="mobile"?"phone":d);if(!i.has(ft(L).toLowerCase()))return ft(L);for(let M=2;M<20;M++)if(!i.has(ft(L,` ${M}`).toLowerCase()))return ft(L,` ${M}`);return ft(L)},m=a("div",{class:"kinds",role:"radiogroup","aria-label":_("What is it?")});m.style.setProperty("--n",String(o.length));let f=o.map(d=>{let L=a("button",{type:"button",class:"kind",role:"radio","aria-label":ti(d),onclick:()=>y(d)},a("span",{class:"kind-tile"},ee(d,"blue")),a("span",{class:"kind-lbl"},ti(d)));return m.appendChild(L),L}),C=(v=t.server.home)!=null?v:[],g=C.length?a("span",{class:"sw-sub sw-note",hidden:!e.bypass},V(_("Except %s: those addresses lead to the home network."),nr(C))):null,b=a("button",{type:"button",class:e.bypass?"swrow on":"swrow",role:"switch","aria-checked":String(e.bypass),onclick:()=>{e.bypass=!e.bypass,b.classList.toggle("on",e.bypass),b.setAttribute("aria-checked",String(e.bypass)),g&&oc(g,e.bypass)}},ee("lan","blue"),a("span",{class:"sw-t"},a("b",{},_("LAN Bypass")),a("span",{class:"sw-sub"},_("Your local network stays reachable while connected.")),g),a("span",{class:"sw","aria-hidden":"true"})),x=a("input",{type:"text","aria-label":_("Name"),autocomplete:"off","data-1p-ignore":!0}),S=a("button",{class:"go ready",type:"submit","aria-label":_("Create connection")},z("arrow")),{el:P,say:F,unsay:A}=Es();Bn(x,()=>w,d=>d?F(d):A()),x.value=(h=e.name)!=null?h:c(s),S.classList.toggle("ready",!!x.value.trim()),x.addEventListener("input",()=>{e.name=x.value,S.classList.toggle("ready",!!x.value.trim()),A()}),tc.then(()=>{e.name===void 0&&s===Xt(Jt())&&(x.value=c(s))});function y(d){s=e.pick=d,f.forEach((L,M)=>{let H=o[M]===d;L.classList.toggle("on",H),L.setAttribute("aria-checked",String(H))}),e.name===void 0&&(x.value=c(d),S.classList.add("ready"))}y(s);let w=a("form",{class:"field",autocomplete:"off"},x,S);In(w),w.addEventListener("submit",d=>{d.preventDefault();let L=x.value.trim();if(!L)return Ve(w);if(i.has(L.toLowerCase()))return Ve(w),F(_("You already have a device with this name."));bt(S,async()=>{try{let M=await ge("devices",{name:L,kind:ni(s),lan_bypass:e.bypass});ye(M.state),_e({pop:M.id});let H=M.state.person.devices.find(q=>q.id===M.id);await Kn(H,M.config)}catch(M){if(M instanceof je&&M.httpsUrl)return Qt(M.httpsUrl);Ve(w),F(M.message)}})});let p=a("button",{type:"button",class:"btn soft block",onclick:()=>An(sc)},z("qr"),a("span",{},_("Add it from the device"))),u=n.device_limit-n.devices.length;return{el:a("div",{class:"view"},qe(_("Add a device")),Ke(V(N_(n.device_limit,"%s of %s slot free","%s of %s slots free"),me(u),me(n.device_limit))),m,b,w,P,a("div",{class:"or"},_("OR")),p),label:_("Add a device")}}function sc(){let e=hr(ht());return{el:a("div",{class:"view"},qe(_("Open on the device"),{back:!0}),Ke(_("Point its camera at the code: your page opens there with this device ready to add.")),qt(e,!0),xt(e)),label:_("Open on the device")}}function ri(e){let t=a("button",{type:"button",class:`btn ${e.cls}`,onclick:o=>bt(o.currentTarget,e.run)},a("span",{},e.action));return{el:a("div",{class:"view"},a("div",{class:"ask"},ee(e.icon,e.tone,"gi xl"),a("h3",{},e.title),a("p",{},e.text),a("div",{class:"btnrow"},a("button",{type:"button",class:"btn soft",onclick:()=>Se()},_("Cancel")),t))),label:e.title,asks:!0}}function Eo(e){var n;if(Ht())return;let t=((n=ue())==null?void 0:n.here)===e.id;we(()=>ri({icon:"refresh",tone:"orange",title:V(_("Reconnect %s?"),e.name),text:t?_("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 o;try{let r=await ge(`devices/${e.id}`,{action:"reconnect"});ye(r.state),_e(),await Kn((o=r.state.person.devices.find(s=>s.id===e.id))!=null?o:{...e,handshake:0},r.config)}catch(r){Pe(r.message,!0)}}}))}function si(e){we(()=>ri({icon:"trash",tone:"red",title:V(_("Remove %s?"),e.name),text:_("Its connection stops working at once. You can add it again later."),action:_("Remove"),cls:"red",run:async()=>{try{let t=await ge(`devices/${e.id}`,{action:"delete"});ye(t.state),_t(()=>{let n=document.querySelector(`.dev[data-id="${CSS.escape(e.id)}"]`),o=()=>{_e(),Pe(_("Device removed"))};if(!n)return o();O(n,[{opacity:1,transform:"none",filter:"none"},{opacity:0,transform:"scale(.9)",filter:"blur(6px)"}],{duration:220,easing:J,fill:"forwards"}).onfinish=o}),Se()}catch(t){Pe(t.message,!0)}}}))}function ic(e,t,n,o){let r=(s,i,c)=>3*s*c*(1-c)**2+3*i*c*c*(1-c)+c**3;return s=>{let i=0,c=1;for(let m=0;m<24;m++){let f=(i+c)/2;r(e,n,f)e,Vn=class{constructor(t,n){this.paint=n;this.stop=null;this.v=t}to(t,n,o,r=0){return this.halt(),new Promise(s=>{let i=0,c=this.v,m=C=>{i||(i=C+r,c=this.v);let g=n<=0?1:Math.min(1,Math.max(0,(C-i)/n));C>=i&&(this.v=c+(t-c)*o(g),this.paint()),g<1?f=requestAnimationFrame(m):(this.stop=null,s(!0))},f=requestAnimationFrame(m);this.stop=()=>{cancelAnimationFrame(f),this.stop=null,s(!1)}})}halt(){var t;(t=this.stop)==null||t.call(this)}},cc=2.2,lc=[[-1,0],[-.5,.5],[-.2,.9],[0,1],[.2,.9],[.5,.5],[1,0]],ai=e=>`${(e*100).toFixed(1)}%`;function dc(e,t){let n=`color-mix(in oklab, var(--shim-high) ${ai(t)}, var(--shim-base))`,o=lc.map(([r,s])=>`color-mix(in oklab, var(--shim-high) ${ai(s)}, ${n}) calc(${(e*100).toFixed(2)}% + ${((2*e-1+r)*cc).toFixed(3)}em)`);return`linear-gradient(90deg, ${n}, ${o.join(", ")}, ${n})`}var uc=["fontFamily","fontSize","fontWeight","letterSpacing","fontFeatureSettings","fontVariationSettings"],ci=1.8,pc=.32,fc=480;function li(e,t){let n=getComputedStyle(t),o=a("span",{class:"shim"},t.value),r=a("span",{class:"shim-clip","aria-hidden":"true"},o);for(let g of uc)o.style[g]=n[g];Object.assign(r.style,{left:`${t.offsetLeft}px`,top:`${t.offsetTop}px`,width:`${t.clientWidth}px`,height:`${t.offsetHeight}px`}),Object.assign(o.style,{left:`${-t.scrollLeft}px`,lineHeight:`${t.offsetHeight}px`});let s=se(),i=()=>o.style.backgroundImage=dc(c.v,m.v),c=new Vn(0,i),m=new Vn(1,i);i(),e.append(r),e.classList.add("saving"),e.setAttribute("aria-busy","true");let f=!s,C=async g=>{f&&(c.v>=1&&(c.v=0),await c.to(1,ci*1e3*(1-c.v),ac,g*1e3)&&C(ci*pc))};return C(.12),m.to(0,s?0:240,ii),async()=>{f=!1,c.halt(),await m.to(1,s?0:fc,ii),e.classList.remove("saving"),e.removeAttribute("aria-busy"),r.remove()}}var ui=["ok-t","warn-t","here-t","bad-t"];function en(e,t,n,o=t){let r=getComputedStyle(e).color;for(let s of ui)e.classList.toggle(s,s===n);e.title=o,te(e,t,void 0,{color:r})}function di(e){e&&(e.classList.add("quiet"),e.addEventListener("blur",()=>e.classList.remove("quiet"),{once:!0}),e.focus({preventScroll:!0}))}var pe=null,pi=()=>!!pe;function fi(e,t){var P,F;if((pe==null?void 0:pe.id)===e.id)return;pe==null||pe.cancel();let n=t.querySelector(".dev-name"),o=t.querySelector(".dev-stat");if(!n||!o)return;let r={text:(P=o.textContent)!=null?P:"",tone:(F=ui.find(A=>o.classList.contains(A)))!=null?F:"",title:o.title},s=matchMedia("(pointer: fine)").matches?_("Return to save, Esc to cancel"):"",i=a("input",{type:"text","aria-label":_("Device name"),autocomplete:"off",spellcheck:"false",enterkeyhint:"done","data-1p-ignore":!0});i.value=e.name;let c=a("form",{class:"field inline",autocomplete:"off"},i);Bn(i,c,A=>A&&en(o,A,"bad-t"),{ring:!1}),i.addEventListener("input",()=>{o.classList.contains("bad-t")&&en(o,s||r.text,s?"":r.tone,s||r.title)}),n.after(c),n.hidden=!0,s&&en(o,s,""),In(c),i.focus();let m=()=>i.setSelectionRange(0,i.value.length);m(),requestAnimationFrame(()=>document.activeElement===i&&i.selectionStart===i.selectionEnd&&m());let f=!1,C=(A,y)=>{(pe==null?void 0:pe.id)===e.id&&(pe=null),document.removeEventListener("pointerdown",x,!0),i.removeEventListener("blur",S),A&&(n.textContent=A),n.hidden=!1,c.remove(),A||en(o,r.text,r.tone,r.title),y&&(A?requestAnimationFrame(()=>di(document.querySelector(`.dev-name[data-t="${CSS.escape(`${e.id}:name`)}"]`))):di(n))},g=A=>{en(o,A,"bad-t"),Ve(c,{ring:!1}),i.focus()},b=async()=>{var p,u;let A=i.value.trim();if(f)return;if(!A)return g(_("Give the device a name."));if(A===e.name)return C(null,!0);if(((u=(p=ue())==null?void 0:p.person.devices)!=null?u:[]).some(l=>l.id!==e.id&&l.name.toLowerCase()===A.toLowerCase()))return g(_("That name is taken."));f=!0,i.readOnly=!0;let w=li(c,i);try{let l=await ge(`devices/${e.id}`,{action:"rename",name:A});ye(l.state),await w(),C(A,!0),_e()}catch(l){await w(),i.readOnly=!1,g(l.message)}finally{f=!1}};c.addEventListener("submit",A=>{A.preventDefault(),b()}),i.addEventListener("keydown",A=>{A.key!=="Escape"||f||(A.preventDefault(),A.stopPropagation(),C(null,!0))});let x=A=>{f||c.contains(A.target)||C(null,!1)},S=()=>setTimeout(()=>{(pe==null?void 0:pe.id)!==e.id||f||!document.hasFocus()||c.contains(document.activeElement)||C(null,!1)});i.addEventListener("blur",S),document.addEventListener("pointerdown",x,!0),pe={id:e.id,cancel:()=>C(null,!1)}}var Co=(e,t)=>e.access!=="internet"&&e.state==="active"&&!t.disabled;function mc(e){switch(e){case"trying":return[_("Can’t finish connecting"),_("It reaches the router, but the connection never completes. The network may be blocking it.")];case"dropped":return[_("Connected, but no data"),_("The router can’t use what it sends: reconnect it.")];case"shared":return[_("On two devices at once"),_("This connection is on two devices and they push each other out. Add the other one as its own device.")];case"unstable":return[_("Connection keeps dropping"),_("It connects, but the connection breaks every few minutes. Another network may help.")]}}function hc(e,t){return e.disabled?["",_("Disabled")]:e.config_stale&&e.handshake?["warn-t",_("Settings changed")]:e.online&&t.state==="quota"?["warn-t",_("Connected, no data left")]:e.online&&t.state==="hours"?["warn-t",_("Connected, outside your hours")]:e.link?["warn-t",...mc(e.link.state)]:e.online?["ok-t",_("Connected")]:e.handshake?["",V(_("Last connected %s"),Zo(e.handshake,gt()))]:["warn-t",_("Not set up yet")]}function gc(e,t){let n=a("span",{class:"dev-name","data-t":`${e.id}:name`},e.name);return t&&(n.classList.add("can-edit"),n.setAttribute("role","button"),n.tabIndex=0,n.setAttribute("aria-label",V(_("Rename %s"),e.name)),n.addEventListener("click",()=>ko(e)),n.addEventListener("keydown",o=>{o.key!=="Enter"&&o.key!==" "||(o.preventDefault(),ko(e))})),n}function ko(e){let t=document.querySelector(`.dev[data-id="${CSS.escape(e.id)}"]`);t&&fi(e,t)}function yc(e,t){return[...Co(t.person,e)?[{label:_("Copy IP address"),icon:"copy",run:()=>be(e.address,_("IP address copied"))},...e.hostname?[{label:_("Copy local address"),icon:"home",run:()=>be(e.hostname,_("Address copied"))}]:[],null]:[],...e.disabled?[]:[{label:_("Rename"),icon:"edit",run:()=>ko(e)},{label:_("Reconnect"),icon:"refresh",tone:"warn",run:()=>Eo(e)},{label:_("Remove"),icon:"trash",tone:"bad",run:()=>si(e)}]]}function vc(e){return e===0?_("Today"):e===1?_("Yesterday"):$e(pt(Ie(),-e)).toLocaleDateString(He(),{weekday:"short",day:"numeric",month:"short"})}function bc(e){let t=vs(e.spark),n=a("span",{class:"use-lbl"},_("Last 7 days")),o=Nn(e.id);o.set(t);let r=Rn(e.spark,"bars-week",34);return r.cols.forEach((s,i)=>{let c=e.spark.length-1-i;s.addEventListener("pointerenter",()=>{ae(n,vc(c)),o.set(e.spark[i])}),s.addEventListener("pointerleave",()=>{ae(n,_("Last 7 days")),o.set(t)})}),a("div",{class:"dev-use"},a("div",{class:"use-txt"},n,a("span",{class:"use-val"},o.el)),r.el)}function xc(e,t){var S;let n=t.person,o=!!t.locked,r=t.here===e.id,[s,i,c]=r?["here-t",_("This device")]:hc(e,n),m=!e.handshake&&!e.disabled,f=e.config_stale&&!m&&!o&&!e.disabled,C=(e.config_stale||((S=e.link)==null?void 0:S.state)==="dropped")&&!m&&!o&&!e.disabled,g=c!=null?c:!r&&e.handshake&&!e.online&&!e.disabled&&!e.config_stale?new Date(e.handshake*1e3).toLocaleString(He()):f?_("Settings changed, update needed"):i,b=yc(e,t),x=o||!b.length?null:a("button",{type:"button",class:"knob more","aria-label":V(_("%s options"),e.name),"aria-haspopup":"menu","aria-expanded":"false"},z("more"));return x==null||x.addEventListener("click",()=>Tn(x,b)),a("article",{class:`dev${r?" is-here":""}${e.disabled?" off":""}`,"data-id":e.id},a("div",{class:"dev-top"},ee(e.kind,r?"blue":"grey"),a("div",{class:"dev-id"},gc(e,!e.disabled&&!o),a("span",{class:`dev-stat ${s}`,title:g,"data-t":`${e.id}:stat`},i),c?a("span",{class:"offscreen"},c):null),x),m&&o?null:m?a("button",{type:"button",class:"btn tint block setup-btn","aria-label":V(_("Set up %s"),e.name),onclick:P=>qn(e,P.currentTarget)},z("qr"),a("span",{},_("Connect"))):C?a("button",{type:"button",class:"btn tint block setup-btn","aria-label":V(_("Reconnect %s"),e.name),onclick:()=>Eo(e)},z("refresh"),a("span",{},_("Reconnect"))):bc(e))}var wc=e=>a("div",{class:"dev first","data-id":"first"},ee("plus","blue"),a("b",{},_("Add your first device")),a("p",{},_("Two steps, about a minute: get the app, then add the connection.")),a("button",{type:"button",class:"btn accent block",onclick:Zt},z("plus"),a("span",{},e?_("Add this phone"):_("Add this device")))),Mc=()=>a("button",{type:"button",class:"dev add","data-id":"add",onclick:Zt},ee("plus"),a("span",{},_("Add device")));function hi(){let e=a("div",{class:"dgrid"});return Ec(e),a("section",{class:"devices",id:"devices","aria-label":_("Your devices")},a("div",{class:"sec-head"},a("h2",{},_("Your devices")),a("span",{class:"aside num"})),e,a("p",{class:"note-s limit",hidden:!0}))}function Ec(e){let t=0;new ResizeObserver(()=>{var o,r;let n=(r=(o=e.querySelector(".dev"))==null?void 0:o.getBoundingClientRect().width)!=null?r:0;Math.abs(n-t)>16&&(e.classList.add("snap"),requestAnimationFrame(()=>requestAnimationFrame(()=>e.classList.remove("snap")))),t=n}).observe(e)}var gi="ring",yi=e=>e.querySelector(":scope > .dev-use, :scope > .setup-btn"),vi=e=>{var t;return e?e.classList.contains("dev-use")?"use":(t=e.textContent)!=null?t:"":""};function Lo(e){let t=e.querySelector(".limit"),n=[...e.querySelectorAll(".dgrid > [data-id]:not([aria-hidden])")].map(o=>{let r=yi(o),s=o.getAnimations().find(i=>i.id===gi);return[o.dataset.id,{el:o,at:o.getBoundingClientRect(),shows:rt(o),foot:r&&{el:r,kind:vi(r),at:r.getBoundingClientRect(),shows:rt(r)},ring:s?Number(s.currentTime):null}]});return{cards:new Map(n),note:t.hidden?null:t.getBoundingClientRect()}}function kc(e,t){let n=getComputedStyle(e).boxShadow;e.animate([{boxShadow:"inset 0 0 0 1.5px var(--ok)"},{boxShadow:n==="none"?"inset 0 0 0 1.5px transparent":n}],{duration:1800,easing:"ease-out",id:gi}).currentTime=t}function bi(e,t,n={},o=Lo(e)){var y,w;let r=t.person,s=e.querySelector(".dgrid"),i=s.childElementCount>0,c=It(s),f=pn(r.devices).sort((p,u)=>+(u.id===t.here)-+(p.id===t.here)).map(p=>xc(p,t)),C=t.locked?0:Math.max(0,r.device_limit-r.devices.length),g=matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent);!r.devices.length&&C?f.push(wc(g)):t.can_add&&!t.locked&&f.push(Mc()),s.classList.toggle("empty",!r.devices.length),s.replaceChildren(...f);let b=f.map(p=>p.getBoundingClientRect().height);f.forEach((p,u)=>{var h,d;let l=o.cards.get(p.dataset.id);if(!l||p.dataset.id===n.pop)return;let v=yi(p);((d=(h=l.foot)==null?void 0:h.kind)!=null?d:"")!==vi(v)&&(l.foot&&vt(l.foot.el,l.foot.at,p,l.at,l.foot.shows),v&&We(v)),Math.abs(l.at.height-b[u])>.5&&(p.style.overflow="clip",O(p,[{height:`${l.at.height}px`},{height:`${b[u]}px`}],{duration:K.duration,easing:K.easing}).onfinish=()=>p.style.overflow="")});for(let p of f){let u=(y=o.cards.get(p.dataset.id))==null?void 0:y.at,l=p.getBoundingClientRect();p.dataset.id===n.pop?O(p,[{opacity:0,transform:"scale(.9)",filter:"blur(6px)"},{opacity:1,transform:"none",filter:"none"}],{duration:De.duration,easing:De.easing}):u&&(u.left!==l.left||u.top!==l.top)?O(p,[{transform:`translate(${u.left-l.left}px, ${u.top-l.top}px)`},{transform:"none"}],{duration:K.duration,easing:K.easing}):!u&&i&&O(p,[{opacity:0,transform:"scale(.9)",filter:"blur(6px)"},{opacity:getComputedStyle(p).opacity,transform:"none",filter:"none"}],{duration:K.duration,delay:60,easing:K.easing,fill:"backwards"});let v=p.dataset.id===n.flash?0:(w=o.cards.get(p.dataset.id))==null?void 0:w.ring;v!=null&&kc(p,v)}let x=new Set(f.map(p=>p.dataset.id)),S=s.getBoundingClientRect();for(let[p,u]of o.cards)x.has(p)||(u.el.style.height=`${u.at.height}px`,vt(u.el,u.at,s,S,u.shows));i&&Wt(s,c);let P=e.querySelector(".sec-head .aside"),F=V(_("%s of %s"),me(r.devices.length),me(r.device_limit));i?te(P,F):P.textContent=F,P.classList.toggle("warn-t",r.devices.length>r.device_limit);let A=e.querySelector(".limit");A.textContent=Ue(r.device_limit,"You have reached your limit of %s device. Remove one to add another.","You have reached your limit of %s devices. Remove one to add another."),Cc(A,t.can_add||!!t.locked,i,o.note)}function Cc(e,t,n,o){let r=getComputedStyle(e),s={opacity:r.opacity,filter:r.filter,transform:r.transform,height:`${e.offsetHeight}px`,marginTop:r.marginTop},i=e.getAnimations(),c=!e.hidden;if(n&&t&&c){let m=O(e,[{opacity:s.opacity,filter:s.filter,transform:s.transform},{opacity:0,filter:"blur(4px)",transform:s.transform}],{duration:200*+s.opacity,easing:J,fill:"forwards"}),f=se()?null:O(e,[{height:s.height,marginTop:s.marginTop},{height:"0px",marginTop:"0px"}],{duration:K.duration,easing:K.easing,fill:"forwards"});i.forEach(C=>C.cancel()),(f!=null?f:m).onfinish=()=>{e.hidden=!0,m.cancel(),f==null||f.cancel()}}else i.forEach(m=>m.cancel()),e.hidden=t;if(!n||t)return mi(e,o);c?i.length&&O(e,[s,{opacity:1,filter:"none",transform:"none",height:`${e.offsetHeight}px`,marginTop:getComputedStyle(e).marginTop}],{duration:K.duration,easing:K.easing}):O(e,[{opacity:0,transform:"translateY(6px)",filter:"blur(4px)"},{opacity:1,transform:"none",filter:"none"}],{duration:420,easing:Q}),mi(e,o)}function mi(e,t){if(!t||e.hidden)return;let n=t.top-e.getBoundingClientRect().top;Math.abs(n)>.5&&O(e,[{translate:`0 ${n}px`},{translate:"0 0"}],{duration:K.duration,easing:K.easing})}var To=e=>a("p",{class:"desc"},e),zn=(e,t)=>`${(e/t*100).toFixed(2)}%`,xi=e=>$e(e).toLocaleDateString(He(),{day:"numeric",month:"short"});function Lc(e){let t=(n,o,r,s)=>a("div",{class:`reach-tile${n?"":" off"}`},ee(o,n?"blue":"grey","gi rt-ic"),a("b",{},r),a("span",{class:"rt-sub"},n?s:_("Not included")),a("span",{class:"rt-mark","aria-label":n?_("Included"):_("Not included")},z(n?"check":"minus")));return a("div",{class:"reach2"},t(e!=="internet","home",_("Home network"),_("Devices at home")),t(e!=="lan","globe",_("Internet"),_("Through the router")))}function Tc(e,t){let n=pn(e.devices).filter(c=>c.hostname&&Co(e,c));if(!n.length)return[];let o=n[0].hostname,r=o.indexOf("."),s=r>0?o.slice(r):"",i=a("span",{class:"mono"},`${_("name")}${s}`);return[a("span",{class:"lbl-s"},...ut(t?_("Devices at home and on this VPN reach yours as %s"):_("Other devices at home reach yours as %s"),i)),a("div",{class:"names"},n.map(c=>{let m=c.hostname.indexOf(".");return a("button",{type:"button",class:"namechip",title:c.name,"aria-label":V(_("Copy %s"),c.hostname),onclick:f=>be(c.hostname,_("Address copied"),f.currentTarget)},a("span",{},m>0?[c.hostname.slice(0,m),a("span",{class:"faint"},c.hostname.slice(m))]:c.hostname),z("copy"))}))]}function _c(e){let t=2*Math.PI*6,n=e>=100?" bad":e>=90?" warn":"";return Ae(``)}function Sc(e){let t=a("i",{class:e>=100?"bad":e>=90?"warn":""});return t.style.width=`${e.toFixed(1)}%`,a("div",{class:"meter"},t)}function Ac(e,t,n){let{days:o,day:r}=ms(Ie()),s=Array.from({length:r},(S,P)=>{var F,A;return(A=(F=e.month_days)==null?void 0:F[P])!=null?A:[0,0]}),i=S=>xi(`${Ie().slice(0,8)}${String(S).padStart(2,"0")}`),c=Nn("m"),m=e.quota_limit?V(_("%s left"),Be(Math.max(0,e.quota_limit-t))):_("No limit"),f=a("span",{class:"num","data-t":"m-left"},m),C=(S,P)=>{c.set(S),ae(f,P?i(P):m),f.classList.toggle("bad-t",!P&&e.state==="quota")};C(e.month);let g=Rn(s,"bars-month",64,o-r);g.cols.forEach((S,P)=>{S.addEventListener("pointerenter",()=>C(s[P],P+1)),S.addEventListener("pointerleave",()=>C(e.month))});let b=a("span",{class:"td"},_("Today"));b.style.left=zn(r-.5,o);let x=a("div",{class:"month-axis"},a("span",{class:r<=4?"hide":""},i(1)),b,a("span",{class:r>=o-3?"hide":""},i(o)));return a("div",{class:"month"},g.el,x,a("div",{class:"month-read"},c.el,f),e.quota_limit?Sc(n):null)}function Hc(e,t){let n=i=>$e(i).toLocaleDateString(He(),{weekday:"short",day:"numeric",month:"short"}),o=Array.from({length:7},(i,c)=>new Date(2024,0,1+c,12).toLocaleDateString(He(),{weekday:"narrow"})),r=us(Ie(),e.expires),s=r?a("div",{class:"cal","aria-hidden":"true"},a("div",{class:"cal-h"},o.map(i=>a("span",{},i))),a("div",{class:"cal-g"},r.map((i,c)=>{let m=a("i",{class:i.kind,title:n(i.day)});return m.style.setProperty("--i",String(c)),m}))):null;return a("div",{class:`until${$t(e,t)?" soon":""}`},a("div",{class:"until-num"},a("b",{class:"num"},me(t)),a("span",{},N_(t,"day left","days left")),a("span",{class:"until-sub"},V(_("Ends %s"),n(e.expires)))),s)}function Dc(e,t){let n=-new Date().getTimezoneOffset(),o=Pn(e,t,n);if(!o)return null;let r=fs(gt(),o.yours?n:t!=null?t:n),s=ps(o),i=s.some(([f,C])=>r>=f&&ra("span",{},f))))}function $c(e,t=1){let n=e.person,o=n.quota_used||n.month[0]+n.month[1],r=n.quota_limit?Math.min(100,o/n.quota_limit*100):0,s=n.quota_period==="total"&&!!n.quota_gb,i=ln(n.expires,Ie()),c=n.expires?a("span",{class:"until-val"},a("span",{class:"num","data-t":"until-date"},xi(n.expires)),i!=null?a("span",{class:`num ${i<0?"bad-t":$t(n,i)?"warn-t":"ok-t"}`,"data-t":"until-left"},i>=0?Ue(i,"%s day","%s days"):_("ended")):null):a("span",{},_("No end date")),m=[n.expires?i!=null&&i<0?To(V(_("It ended on %s."),cn(n.expires))):Hc(n,i!=null?i:0):null,n.hours?Dc(n.hours,e.tz_offset):null];return ze([{icon:ee(n.access==="internet"?"globe":n.access==="lan"?"home":"shield"),title:tr(n.access),body:[Lc(n.access),...Tc(n,!!e.server.device_mesh)]},{icon:ee("chart"),title:s?_("Data used"):_("Data this month"),val:a("span",{class:"data-val"},n.quota_limit?_c(r):null,a("span",{class:"num","data-t":"data-val"},`${Be(o)} ${n.quota_limit?`/ ${Be(n.quota_limit)}`:`· ${_("no limit")}`}`)),valHide:!0,body:[s?To(V(_("%s of %s in total."),Be(o),Be(n.quota_limit))):Ac(n,o,r),To(n.quota_limit?s?_("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:ee("calendar"),title:_("Access until"),val:c,valHide:!!n.expires&&(i!=null?i:0)>=0,body:m}],{open:t,hold:ls})}function wi(){return a("section",{class:"access",id:"access","aria-label":_("Your access")},a("div",{class:"sec-head"},a("h2",{},_("Your access"))),a("div",{class:"acc-slot"}))}function Un(e,t=!1){let n=e.cloneNode(!0),o=e.querySelectorAll("[data-t]");return n.querySelectorAll("[data-t]").forEach((r,s)=>{r.textContent=ve(o[s]),r.classList.remove("mt","mt-ib")}),(t?n.innerHTML:n.outerHTML).replace(/\bgl\d+/g,"gl")}function Pc(e,t){let n=[...e.children],o=[...t.children];if(n.length!==o.length||n.some((s,i)=>s.classList.contains("still")!==o[i].classList.contains("still")))return null;let r=[];return n.forEach((s,i)=>{var g;let[c,m]=[...s.children],[f,C]=[...o[i].children];for(let b of c.querySelectorAll("[data-t]")){let x=f.querySelector(`[data-t="${b.dataset.t}"]`);x&&ve(b)!==x.textContent&&ae(b,(g=x.textContent)!=null?g:"")}c.children.length!==f.children.length?c.replaceChildren(...f.childNodes):[...f.children].forEach((b,x)=>{let S=c.children[x];Un(S)!==Un(b)&&(S.tagName===b.tagName&&S.className===b.className?S.replaceChildren(...b.childNodes):S.replaceWith(b))}),r.push(...Mi(s,m,C))}),r}var tn=new WeakMap;function Mi(e,t,n){if(tn.has(t))return tn.set(t,n),[];if(Un(t,!0)===Un(n,!0))return[];if(!e.classList.contains("open")&&!e.classList.contains("closing"))return t.replaceChildren(...n.childNodes),[];let o=[...t.querySelectorAll(".cal-g i")].flatMap(c=>c.getAnimations());if(o.length)return tn.set(t,n),Promise.all(o.map(c=>c.finished.catch(()=>{}))).then(()=>{let c=tn.get(t);if(tn.delete(t),!e.isConnected)return;let m=It(t);Wt(t,m,Mi(e,t,c))}),[];e.classList.remove("opened");let r=e.getBoundingClientRect().height,s=e.getAnimations().length>0,i=Xe(t,[...n.childNodes]);if(s)Dt(t);else{let c=e.getBoundingClientRect().height;Math.abs(c-r)>.5&&O(e,[{height:`${r}px`},{height:`${c}px`}],{duration:K.duration,easing:K.easing})}return i}var ct=null;function Ei(e,t){let n=e.querySelector(".acc-slot"),o=$c(t,ct?ct.openIndex():1),r=It(e),s=!!ct,i=ct&&n.contains(ct.el)?Pc(ct.el,o.el):null;i||(n.replaceChildren(o.el),ct=o),s&&Wt(e,r,i!=null?i:[])}jo(document.documentElement);var Yn=document.getElementById("app"),Ee=null,_o=!1,jn=()=>{};function ki(){let e=[...Yn.querySelectorAll(".crumbs, .notice, .sec-head, .dgrid > *, .note-s:not([hidden]), .acc-slot .acc-row, .gone")].map(r=>({el:r,at:r.getBoundingClientRect()})).sort((r,s)=>Math.round(r.at.top)-Math.round(s.at.top)||r.at.left-s.at.left),t=e.map(r=>r.el),n=e.filter(r=>r.at.bottom<=0).length,o=t.map(r=>getComputedStyle(r).opacity);t.forEach((r,s)=>O(r,[{opacity:0,transform:"translateY(10px)",filter:"blur(4px)"},{opacity:o[s],transform:"none",filter:"none"}],{duration:520,delay:60+Math.max(0,s-n)*40,easing:Q,fill:"backwards"})),Yn.querySelectorAll(".logo .sun").forEach(r=>O(r,[{transform:"translateY(7px)"},{transform:"none"}],{duration:900,delay:150,easing:Q,fill:"backwards"})),_o=!0}function So(e={}){let t=ue();if(!t)return;if(jn=So,t.person.state==="paused"){document.title=nt();let[s,i,c]=xo(t.person);return Ao(s,i,c,!1,"orange")}let n=yo(Yn);vo(!1),bo(),document.title=nt(),n.style.minHeight=`${n.offsetHeight}px`;let o=!Ee;Ee||(Ee={notice:a("div",{class:"notice-slot"}),devices:hi(),access:wi()},Ne(n,Ee.notice,a("div",{class:"cols"},Ee.devices,Ee.access)));let r=Lo(Ee.devices);if(gs(Ee.notice,t.person,!o),Ei(Ee.access,t),bi(Ee.devices,t,e,r),n.getBoundingClientRect(),n.style.minHeight="",!_o){let s=Oc();s&&scrollTo(0,s),ki()}}Mr(So);var Ci=`dl.y:${location.pathname}`;function Li(){if(Ee)try{sessionStorage.setItem(Ci,String(Math.round(scrollY)))}catch{}}function Oc(){var t;let e=(t=performance.getEntriesByType("navigation")[0])==null?void 0:t.type;if(e!=="reload"&&e!=="back_forward")return 0;try{return Number(sessionStorage.getItem(Ci))||0}catch{return 0}}addEventListener("pagehide",Li);document.addEventListener("visibilitychange",()=>{document.hidden&&Li()});function Ao(e,t,n,o=!1,r="grey"){Ee=null;let s=yo(Yn);vo(!0),bo(o,!0),Ne(s,a("div",{class:"gone"},ee(e,r),a("h1",{},t),a("p",{},n))),_o||ki()}function Ho(){ye(null),Se(!0),jn=Ho,Ao("key",_("This link no longer works"),_("Ask for a new one."),!0)}function Ti(e){jn=()=>Ti(e),Ao("server",_("The page could not load"),e)}function _i(){let e=ue(),t=mr(location.hash),n=gr(location.hash);if(!e||!t&&!n)return;if(history.replaceState(null,"",location.pathname+location.search),n)return Zt();let o=e.person.devices.find(r=>r.id===t);o&&!o.handshake&&!o.disabled&&!e.locked&&qn(o,null,!0)}addEventListener("hashchange",_i);async function Rc(){try{ye(await ge("state")),!Re()&&!Kt()&&!pi()&&So(),_i()}catch(e){gn(e)?Ho():ue()||Ti(e.message)}}Ko(()=>{Oe(!0),Ee=null,jn()});document.addEventListener("keydown",e=>{e.key==="Escape"&&(Kt()?Oe(!0):Re()&&Se(!0))});!mt||!vr?Ho():Rc();})(); diff --git a/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json b/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json index 328e887..4b2b1f0 100644 --- a/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json +++ b/package/luci-app-dawnline/root/usr/share/rpcd/acl.d/luci-app-dawnline.json @@ -6,6 +6,7 @@ "luci.dawnline": [ "rev", "status", + "meter", "setup_defaults", "health", "service_log", diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc index 4ee50e7..f44ac46 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc @@ -115,9 +115,9 @@ function peer_of(dmp, d) { return dmp.peers[d.public_key]; } -/** What the device sends to the router: its configuration's AllowedIPs. */ +/** What the device sends to the router: its configuration's AllowedIPs (its own, with lan_bypass). */ function routed(m, srv, p, d) { - return awg.allowed_ips(m, srv, p); + return awg.allowed_ips(m, srv, p, d); } /** The home network (interface) of a server that holds an address. */ @@ -204,6 +204,12 @@ function from_device(m, d, t, states, dmp, snap) { return steps; } + // A device that keeps its own local network out of the tunnel (lan_bypass; + // Home only is the same either way) sends a private address there, router + // or home address alike: it never reaches this router's rules. + if (d.lan_bypass && p.access != 'lan' && !in_nets(t.ip, allowed)) + return stop(steps, via(t.ip)); + // The router itself. if (index(router_addrs(snap), t.ip) >= 0) { let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m))); @@ -301,17 +307,20 @@ function to_device(m, ip, d, states, dmp, snap) { return steps; } -/** `from` and `to`: a device id, or an IPv4 address (optionally :port). */ -export function check(m, from, to) { +/** + * `from` and `to`: a device id, or an IPv4 address (optionally :port). + * `ctx` = { states, dmp, snap } (a test's own); read from the router when not + * given. Returns { ok, steps: [{ ok, title, detail }] }. + */ +export function check(m, from, to, ctx) { let a = parse_target(m, from), b = parse_target(m, to); if (!a) die(sprintf(_('"%s" is not a device or an IPv4 address.'), from)); if (!b) die(sprintf(_('"%s" is not a device or an IPv4 address.'), to)); - let usage = core.load_usage(); - let states = view.states(m, usage); - let dmp = live.dump(m); - let snap = net.snapshot(true); + let states = ctx?.states ?? view.states(m, core.load_usage()); + let dmp = ctx?.dmp ?? live.dump(m); + let snap = ctx?.snap ?? net.snapshot(true); let steps; if (a.dev) steps = from_device(m, a.dev, b, states, dmp, snap); 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 9290ce1..4d1680e 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 @@ -1,8 +1,9 @@ -// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client -// configurations (.conf, AmneziaVPN key), the netifd options of a server's -// tunnel, its peers (`awg syncconf`, no restart), live counters, the words for -// why a tunnel is kept down (blocked_text) and what the watchdog and Health -// check about it. Plain WireGuard is AmneziaWG with the disguise off. +// Dawnline — the AmneziaWG core: keys, disguise (obfuscation) and the values +// AmneziaWG refuses, client configurations (.conf, AmneziaVPN key), the +// netifd options of a server's tunnel, its peers (`awg syncconf`, no +// restart), live counters, the words for why a tunnel is kept down +// (blocked_text) and what the watchdog and Health check about it. Plain +// WireGuard is AmneziaWG with the disguise off. import { readfile, stat, unlink } from 'fs'; import { @@ -11,6 +12,7 @@ import { } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as net from 'dawnline.net'; +import { ipv6_groups } from 'dawnline.schema'; import * as pkg from 'dawnline.pkg'; import * as builds from 'dawnline.awg_builds'; import { _, L_ } from 'dawnline.i18n'; @@ -29,7 +31,7 @@ const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh'; /** The packages AmneziaWG comes in (the Components tab installs them). */ const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ]; // A module constant, compiled once (a literal is compiled each time it runs): -// dump() checks it on every line of `awg show all dump`, every second. +// dump() checks it on every line of each tunnel's `awg show dump`, every second. const DIGITS = /^[0-9]+$/; /** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */ @@ -138,7 +140,9 @@ function rand_h(used) { } } -// caps() answers from here while the tool, the protocol script and the module file are the same. +// caps() answers from here while the tool, the protocol script, the module +// file, the install record and the loaded module are the same (tmpfs: a +// reboot starts over). const CAPS = `${RUN_DIR}/awg-caps.json`; /** @@ -146,15 +150,20 @@ const CAPS = `${RUN_DIR}/awg-caps.json`; * options it passes on) and the `awg` tool (the keys it accepts) say what the * tools know, the kernel module's package version what the kernel runs, and * a feature counts only when both have it (tools 3.1 over a 2.0 module would - * configure header protection that the kernel silently lacks): + * configure header protection that the kernel silently lacks). While an + * update waits for a reboot (its old module stayed loaded) the kernel runs + * the generation from before it, as the install recorded it: * v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0) * v3 — header protection, trailers, padding, timing (AWG 3.1) * tools / kmod — their generations ('1.0', '2.0', '3.1'; null unknown) * mismatch — the two differ + * pending — an installed module waits for a reboot (dawnline.awg_builds) */ export function caps() { let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? ''); - let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}`; + let core = builds.module_core(); + let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}` + + `/${stat(builds.RECORD)?.mtime ?? 0}/${core ?? 0}`; let cached = read_json(CAPS, null); if (cached?.key == key && cached.caps) return cached.caps; @@ -163,12 +172,15 @@ export function caps() { let t2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0; let t3 = t2 && index(script, 'awg_header_protection_key') >= 0 && tool != ''; let tools = !stat(TOOL) ? null : t3 ? '3.1' : t2 ? '2.0' : '1.0'; - // A module installed by hand has no package: then the tools are believed. - let kmod = builds.gen(pkg.version('kmod-amneziawg')); + // A module installed by hand has no package, so no generation (also when + // a pending update replaces it): then the tools are believed. + let rec = read_json(builds.RECORD, null), boot = builds.boot_id(); + let kmod = builds.running_gen(rec, boot, core, pkg.version('kmod-amneziawg')); let out = { v2: t2 && (kmod == null || kmod != '1.0'), v3: t3 && (kmod == null || kmod == '3.1'), tools, kmod, mismatch: tools != null && kmod != null && tools != kmod, + pending: builds.pending(rec, boot, core), }; ensure_dir(RUN_DIR); write_json(CAPS, { key, caps: out }, 0o644); @@ -241,18 +253,24 @@ function dns_answer() { * offers Balanced or Maximum instead. */ export function obf_preset(name) { - if (name == 'max') + if (name == 'max') { + // 32 random bytes, as `awg genkey` makes them (no process). Without + // one the server would come up with weak or no header protection. + let hpk = genpsk(); + if (!valid_key(hpk)) + die(_('Key generation failed (no random data).')); return { jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50', s1: '12', s2: '12', s3: '12', s4: '12', h1: '1', h2: '2', h3: '3', h4: '4', i1: dns_query(), i2: dns_answer(), - header_protection_key: sh_out('awg genkey'), + header_protection_key: hpk, content_padding_addition: '10-100', rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180', keepalive_timeout: '5-15', max_handshake_attempts: '15-20', random_trailers: 'on', disable_cookies: 'on', }; + } if (name == 'off') return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }; let o = {}; @@ -278,38 +296,222 @@ export function obf_preset(name) { return o; }; +/* ---------- disguise values AmneziaWG refuses ---------- */ -export function obf_errors(o) { +// Checked with ltrim, not regexes: this module loads with every portal request. +const DEC = '0123456789', HEX = '0123456789abcdefABCDEF'; + +/** A whole number in digits up to `top`, or null (no spaces: callers trim where the tools drop them). */ +function uint(v, top) { + let s = `${v}`; + if (s == '' || length(s) > 10 || ltrim(s, DEC) != '') + return null; + return +s <= top ? +s : null; +} + +/** A number or a range as AmneziaWG writes them ("5", "5-15"), each end up to `top`: [ lo, hi ], or null. */ +function uint_range(v, top) { + let p = split(trim(`${v}`), '-'); + let lo = length(p) <= 2 ? uint(p[0], top) : null; + let hi = length(p) == 2 ? uint(p[1], top) : lo; + return lo != null && hi != null && lo <= hi ? [ lo, hi ] : null; +} + +/** Value `k` of disguise values `o` is set. */ +function given(o, k) { + return o[k] != null && o[k] != ''; +} + +/** + * Packet types H1-H4: a number or a range each, apart from the others (the + * kernel refuses an overlap). One not given keeps WireGuard's own type, 1-4. + */ +function headers_unsafe(o, errs) { + let hs = []; + for (let i = 1; i <= 4; i++) { + let r = given(o, `h${i}`) ? uint_range(o[`h${i}`], 4294967295) : [ i, i ]; + if (!r) + push(errs, sprintf(_('%s must be a number or a range like 100-200, up to 4294967295.'), OBF_CONF[`h${i}`])); + push(hs, r); + } + for (let i = 0; i < 4; i++) + for (let j = i + 1; j < 4; j++) + if (hs[i] && hs[j] && hs[i][0] <= hs[j][1] && hs[j][0] <= hs[i][1]) + push(errs, sprintf(_('%s and %s overlap: each packet type needs values of its own.'), OBF_CONF[`h${i + 1}`], OBF_CONF[`h${j + 1}`])); +} + +/** + * One tag of a signature packet as both the kernel and amneziawg-go read it: + * fixed bytes (an even number of hex digits), , , + * (N random bytes, letters, digits; a negative N writes past the packet in + * the kernel, kmod #267) or (the time). is the kernel's alone and + * , , amneziawg-go's: devices on the other refuse them. + */ +function itag_ok(tag) { + if (tag == 't') + return true; + let sp = index(tag, ' '); + if (sp < 0) + return false; + let key = substr(tag, 0, sp), val = substr(tag, sp + 1); + if (key == 'b') + return length(val) > 2 && length(val) % 2 == 0 && substr(val, 0, 2) == '0x' && ltrim(substr(val, 2), HEX) == ''; + if (key == 'r' || key == 'rc' || key == 'rd') + return (uint(val, 1000) ?? 0) >= 1; + return false; +} + +/** What is wrong with signature packet `name` (I1-I5) holding `s`, as a sentence; null when nothing. */ +function itag_error(name, s) { + // In a .conf file `#` starts a comment and a line break ends the line: the rest would be lost. + if (index(s, '#') >= 0 || index(s, '\n') >= 0 || index(s, '\r') >= 0) + return sprintf(_('%s may not contain # or a line break.'), name); + // Text between tags is skipped by both parsers. + for (let a = index(s, '<'); a >= 0; a = index(s, '<')) { + let b = index(substr(s, a), '>'); + if (b < 0) + return sprintf(_('%s has a tag that is not closed with >.'), name); + let tag = substr(s, a + 1, b - 1); + if (!itag_ok(tag)) + return sprintf(_('%s: <%s> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or .'), + name, length(tag) > 24 ? `${substr(tag, 0, 24)}…` : tag); + s = substr(s, a + b + 1); + } + return null; +} + +/** Signature packets I1-I5: their tags, and all of them in one device's configuration (one QR code). */ +function itags_unsafe(o, errs) { + let total = 0; + for (let k in [ 'i1', 'i2', 'i3', 'i4', 'i5' ]) { + if (!given(o, k)) + continue; + total += length(`${o[k]}`); + let e = itag_error(OBF_CONF[k], `${o[k]}`); + if (e) + push(errs, e); + } + if (total > 2000) + push(errs, sprintf(_('I1-I5 together must be at most 2000 characters, not %d.'), total)); +} + +/** + * What in disguise values `o` AmneziaWG would refuse, crash on or break + * devices with: what an import, a restore or a hand edit in uci must never + * hand to the kernel (dawnline.backup, dawnline.netifd). Only those rules, + * none of Dawnline's own bounds (obf_errors): a backup the kernel takes stays + * usable. Sentences in the reader's language; [] when the values are safe. + */ +export function obf_unsafe(o) { + o ??= {}; let errs = []; - for (let k, r in OBF_SPEC) { - let v = o[k]; - if (v == null || v == '') - continue; - if (!match(v, DIGITS) || +v < r[0] || +v > r[1]) - push(errs, `${k}=${v} (${r[0]}-${r[1]})`); + let num = (k) => given(o, k) ? uint(trim(`${o[k]}`), 65535) : 0; + // 16-bit numbers for the tools; Jmin above Jmax sizes junk past its buffer (kmod #225). + for (let k in [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4' ]) + if (num(k) == null) + push(errs, sprintf(_('%s must be a whole number from 0 to 65535.'), OBF_CONF[k])); + if (given(o, 'jmin') && given(o, 'jmax') && num('jmin') != null && num('jmax') != null && num('jmin') > num('jmax')) + push(errs, _('Jmin must not be larger than Jmax.')); + headers_unsafe(o, errs); + // Header protection: a 32-byte key, and every padding at least the 12 bytes of its nonce (the kernel checks). + if (given(o, 'header_protection_key')) { + if (!valid_key(o.header_protection_key)) + push(errs, _('The header protection key is not a key.')); + for (let k in [ 's1', 's2', 's3', 's4' ]) + if (num(k) != null && num(k) < 12) + push(errs, sprintf(_('%s must be at least 12 with header protection.'), OBF_CONF[k])); } - if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax) - push(errs, 'jmin > jmax'); - if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2) - push(errs, 's1 + 56 = s2'); - let hs = {}; - for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) { - let v = o[k]; - if (v == null || v == '') - continue; - if (!match(v, /^[0-9]+(-[0-9]+)?$/)) - push(errs, sprintf(_('%s must be a number or range'), k)); - else if (hs[v]) - push(errs, _('h1-h4 must be distinct')); - hs[v] = true; + // 3.1 timers and counts: 0 alone is the kernel's default; a 0 in a range + // would fire at once. Keys are dropped after 180 seconds whatever is set. + for (let k in [ 'rekey_after_time', 'rekey_timeout', 'reject_after_time', 'keepalive_timeout', 'max_handshake_attempts' ]) { + let r = given(o, k) ? uint_range(o[k], 65535) : [ 0, 0 ]; + if (!r || (r[0] == 0 && r[1] > 0)) + push(errs, sprintf(_('%s must be a number or a range like 5-15, from 1 to 65535.'), OBF_CONF[k])); + else if (k == 'reject_after_time' && r[1] > 180) + push(errs, _('RejectAfterTime must be at most 180 seconds.')); } + if (given(o, 'content_padding_addition') && !uint_range(o.content_padding_addition, 65535)) + push(errs, sprintf(_('%s must be a number or a range like 10-100, up to 65535.'), OBF_CONF.content_padding_addition)); + // What both netifd and the .conf parser read as a switch. + for (let k in [ 'random_trailers', 'disable_cookies' ]) + if (given(o, k) && index([ 'on', 'off', '1', '0' ], `${o[k]}`) < 0) + push(errs, sprintf(_('%s must be on or off.'), OBF_CONF[k])); + itags_unsafe(o, errs); return errs; }; +/** + * What is wrong with the disguise values of a server Dawnline sets up: what + * AmneziaWG refuses (obf_unsafe), and Dawnline's own bounds on top (junk that + * stays under the path MTU, a handshake initiation and response that never + * share a size). Its presets pass it. Sentences in the reader's language; [] + * when the values are fine. + */ +export function obf_errors(o) { + o ??= {}; + let errs = obf_unsafe(o); + for (let k, r in OBF_SPEC) { + let n = given(o, k) ? uint(trim(`${o[k]}`), 65535) : null; + if (n != null && (n < r[0] || n > r[1])) + push(errs, sprintf(_('%s must be from %d to %d.'), OBF_CONF[k], r[0], r[1])); + } + if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2) + push(errs, _('S2 must not be S1 + 56: the handshake initiation and response would have the same size.')); + return errs; +}; +/** + * Disguise values `o` as anyone who may read the status sees them: all but + * the header protection key, a secret every device of the server shares + * (with it and the server's public key, captured traffic can be unmasked). + * Devices get it in their own configuration (client_config). + */ +export function obf_public(o) { + let out = { ...(o ?? {}) }; + delete out.header_protection_key; + return out; +}; -export function allowed_ips(m, srv, p) { - if (p.access == 'lan') { +/* + * Everything but a device's own local network, for a device whose local + * network stays outside the tunnel (lan_bypass): every IPv4 address outside + * the private ranges the access table drops for internet people anyway + * (dawnline.nft PRIVATE4: 10/8, 172.16/12, 192.168/16, 100.64/10, + * 169.254/16, 224/3), and every IPv6 address outside fc00::/7, fe80::/10 + * and ff00::/8. Fixed lists (tests/ucode/awg.test.uc proves each is exactly + * that complement); what of the private ranges goes through the tunnel after + * all (DNS, home) is added to them. + */ +export const BYPASS4 = [ + '0.0.0.0/5', '8.0.0.0/7', '11.0.0.0/8', '12.0.0.0/6', '16.0.0.0/4', '32.0.0.0/3', '64.0.0.0/3', '96.0.0.0/6', + '100.0.0.0/10', '100.128.0.0/9', '101.0.0.0/8', '102.0.0.0/7', '104.0.0.0/5', '112.0.0.0/4', '128.0.0.0/3', '160.0.0.0/5', + '168.0.0.0/8', '169.0.0.0/9', '169.128.0.0/10', '169.192.0.0/11', '169.224.0.0/12', '169.240.0.0/13', '169.248.0.0/14', + '169.252.0.0/15', '169.255.0.0/16', '170.0.0.0/7', '172.0.0.0/12', '172.32.0.0/11', '172.64.0.0/10', '172.128.0.0/9', + '173.0.0.0/8', '174.0.0.0/7', '176.0.0.0/4', '192.0.0.0/9', '192.128.0.0/11', '192.160.0.0/13', '192.169.0.0/16', + '192.170.0.0/15', '192.172.0.0/14', '192.176.0.0/12', '192.192.0.0/10', '193.0.0.0/8', '194.0.0.0/7', '196.0.0.0/6', + '200.0.0.0/5', '208.0.0.0/4', +]; +export const BYPASS6 = [ '::/1', '8000::/2', 'c000::/3', 'e000::/4', 'f000::/5', 'f800::/6', 'fe00::/9', 'fec0::/10' ]; + +/** An IPv6 address BYPASS6 leaves out: in fc00::/7, fe80::/10 or ff00::/8 (the first 16 bits decide). False for anything else. */ +function private6(a) { + let g = ipv6_groups(a)?.[0]; + return g != null && ((g & 0xfe00) == 0xfc00 || (g & 0xffc0) == 0xfe80 || (g & 0xff00) == 0xff00); +} + +/** + * What a device sends into the tunnel (its AllowedIPs; the server's peer + * line stays its address/32). Home only: the person's home networks, the + * tunnel network or the router's address, and the DNS. Internet: everything, + * or with `dev.lan_bypass` everything but the device's own local network + * (BYPASS4, BYPASS6), every DNS server it is given (IPv4 and IPv6) and for + * home access what Home only gets. Without `dev`, as for a device without + * lan_bypass. + */ +export function allowed_ips(m, srv, p, dev) { + if (p.access != 'lan' && !dev?.lan_bypass) + return [ '0.0.0.0/0', '::/0' ]; + let home = () => { let nets = core.person_home(srv, p).nets; // With devices reaching each other, the whole tunnel network (the router's // address is in it); otherwise only the router's own address. @@ -318,13 +520,27 @@ export function allowed_ips(m, srv, p) { push(nets, srv.subnet); else if (a) push(nets, `${a}/32`); + return nets; + }; + let dns = core.client_dns(m, srv, p); + if (p.access == 'lan') { // The resolver address must be reachable through the tunnel too (not the fallback). - let dns = core.client_dns(m, srv, p)[0]; - if (dns) - push(nets, `${dns}/32`); + let nets = home(); + if (dns[0]) + push(nets, `${dns[0]}/32`); return net.collapse(nets); } - return [ '0.0.0.0/0', '::/0' ]; + // Every DNS server stays in the tunnel: a private one left out would be + // asked on whatever network the device is on (a public one is in the rest). + let nets = [ ...BYPASS4 ], nets6 = []; + for (let a in dns) + if (ip2int(a) != null) + push(nets, `${a}/32`); + else if (private6(a)) + push(nets6, `${a}/128`); + if (p.access == 'both') + push(nets, ...home()); + return [ ...net.collapse(nets), ...BYPASS6, ...uniq(nets6) ]; }; @@ -372,6 +588,48 @@ function client_obf(srv, dev) { return o; } +/** + * The keep-alive `dev` gets (its own or the server's, core.device_keepalive) + * as [ lo, hi ] seconds; null when it is off (0). With 3.1 (header + * protection: its apps take ranges) jittered over ten seconds like the other + * timers, since a fixed beat would be the one regular thing left. The online + * window follows its upper end (dawnline.live). + */ +export function keepalive_range(srv, dev) { + let k = core.device_keepalive(srv, dev); + if (!(k > 0)) + return null; + return srv.obf?.header_protection_key ? [ k, k + 10 ] : [ k, k ]; +}; + +/** + * The longest an idle device goes between two handshakes, in seconds; null + * when its keep-alive is off (an idle device then sends nothing at all). Its + * keep-alive packets are what it sends, and the first one after its key's + * rekey time (RekeyAfterTime, WireGuard's 120 s; past 180 s the key is + * refused anyway) starts a handshake (kmod send.c keep_key_fresh): up to one + * keep-alive past that time, or each keep-alive once they are further apart. + */ +export function idle_handshake(srv, dev) { + let ka = keepalive_range(srv, dev); + if (!ka) + return null; + let rekey = min(uint_range(srv.obf?.rekey_after_time ?? '', 65535)?.[1] || 120, 180); + return ka[0] > rekey ? ka[1] : rekey + ka[1]; +}; + +/** + * keepalive_range() as the apps write it ("25-35", "25"); null when off. The + * .conf and the AmneziaVPN key carry the same text (AmneziaVPN hands it on as + * written, ranges included). + */ +function keepalive_text(srv, dev) { + let r = keepalive_range(srv, dev); + if (!r) + return null; + return r[0] == r[1] ? `${r[0]}` : `${r[0]}-${r[1]}`; +} + export function client_config(m, dev) { let p = m.people[dev.person]; let srv = p ? m.servers[p.server] : null; @@ -379,7 +637,7 @@ export function client_config(m, dev) { return null; let host = core.endpoint_host(m, srv); let ep = index(host, ':') >= 0 && substr(host, 0, 1) != '[' ? `[${host}]` : host; - let allowed = allowed_ips(m, srv, p); + let allowed = allowed_ips(m, srv, p, dev); let dns = core.client_dns(m, srv, p); let mtu = core.device_mtu(srv, dev); let lines = [ '[Interface]' ]; @@ -401,10 +659,9 @@ export function client_config(m, dev) { push(lines, `PresharedKey = ${dev.preshared_key}`); push(lines, `AllowedIPs = ${join(', ', allowed)}`); push(lines, `Endpoint = ${ep}:${srv.port}`); - // With 3.1 (its apps take ranges) the keep-alive is jittered like the - // other timers; a fixed beat would be the one regular thing left. - if (srv.keepalive > 0) - push(lines, `PersistentKeepalive = ${srv.obf.header_protection_key ? `${srv.keepalive}-${srv.keepalive + 10}` : srv.keepalive}`); + let keepalive = keepalive_text(srv, dev); + if (keepalive) + push(lines, `PersistentKeepalive = ${keepalive}`); return { name: dev.name, person: p.name, @@ -424,7 +681,7 @@ export function client_config(m, dev) { client_pub_key: dev.public_key, psk_key: dev.preshared_key, server_pub_key: srv.public_key, - persistent_keep_alive: `${srv.keepalive}`, + persistent_keep_alive: keepalive ?? '0', obfuscation: obf, }, }; @@ -448,12 +705,63 @@ export function netifd_options(srv) { }; for (let k in core.OBF_KEYS) o[`awg_${k}`] = srv.obf[k]; + // DisableCookies is the devices' alone (their .conf and key keep it): on + // the server it would turn off WireGuard's own defence against a flood of + // handshakes (cookie replies and a per-address limit, only ever under + // load), and anyone who held a configuration could keep both cores busy. + // Null takes it off an interface that had it. + o.awg_disable_cookies = null; return o; }; /** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */ export const SOFT_STATES = [ 'active', 'quota', 'hours' ]; +/** + * The devices sync_peers() loads into server `sid`'s tunnel, in the model's + * order (an empty list when none). Pure: the model and the people's states + * (apply.states_for). Health and the agent compare a running tunnel with it. + */ +export function tunnel_devices(m, sid, states) { + let out = []; + let own = m.servers?.[sid]?.public_key; + for (let did, d in m.devices) { + let p = m.people[d.person]; + // One malformed line makes syncconf refuse the whole server: such a device + // stays out (Health's Data check names it), and so does one with the + // server's own key, which the kernel silently ignores (it would look + // missing for ever). Over the data limit or outside the allowed hours the + // tunnel stays: the access table blocks everything but the portal, which + // says why (a silent handshake failure would look like a broken VPN). + if (p && p.server == sid && !d.disabled && index(SOFT_STATES, states[p.id]) >= 0 && valid_key(d.public_key) && ip2int(d.address) != null && + (!own || d.public_key != own)) + push(out, d); + } + return out; +}; + +/** + * How the peers dump() read on `ifname` differ from the devices that belong + * there (tunnel_devices): { loaded, missing, extra }, counted by key, not by + * number (a stale peer standing in for a missing one would make the numbers + * match). Pure. + */ +export function peer_diff(devs, dmp, ifname) { + let want = {}; + for (let d in devs) + want[d.public_key] = true; + let loaded = 0, extra = 0, found = 0; + for (let k, p in dmp.peers) + if (p.ifname == ifname) { + loaded++; + if (want[k]) + found++; + else + extra++; + } + return { loaded, missing: length(keys(want)) - found, extra }; +}; + /** Push the peer list of every server to the kernel without restarting it. */ export function sync_peers(m, states) { ensure_dir(RUN_DIR); @@ -467,15 +775,7 @@ export function sync_peers(m, states) { continue; } let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ]; - for (let did, d in m.devices) { - let p = m.people[d.person]; - // One malformed line makes syncconf refuse the whole server: such a device - // stays out (Health's Data check names it). Over the data limit or - // outside the allowed hours the tunnel stays: the access table blocks - // everything but the portal, which says why (a silent handshake failure - // would look like a broken VPN). - if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null) - continue; + for (let d in tunnel_devices(m, id, states)) { push(lines, '[Peer]', `PublicKey = ${d.public_key}`); if (d.preshared_key) push(lines, `PresharedKey = ${d.preshared_key}`); @@ -492,39 +792,83 @@ export function sync_peers(m, states) { return res; }; -/** - * Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }. - * Lines are told apart by their shape, not their length (each AmneziaWG - * generation adds fields to the interface line): an interface line carries - * its private and public key and a port, a peer line the peer's key, a - * preshared key or "(none)" and an endpoint. The tool fails when any one - * interface can't be read, but still prints the others: with `wanted` (the - * ifnames that matter) `ok` means those were all read, so another tunnel's - * trouble is not ours. +/** The interface's index while it exists (a new one each time netifd sets the tunnel up), else null. */ +function ifindex(ifname) { + let s = trim(readfile(`/sys/class/net/${ifname}/ifindex`) ?? ''); + return s != '' ? +s : null; +} + +/* + * One interface's `awg show dump` into `out` (see dump()). Lines are + * told apart by their shape, not their length (each AmneziaWG generation adds + * fields to the interface line): an interface line carries its private and + * public key and a port, a peer line the peer's key, a preshared key or + * "(none)" and an endpoint. Unlike `show all`, the lines have no ifname. */ -export function dump(wanted) { - let r = sh('awg show all dump'); - let out = { ok: r.code == 0, ifaces: {}, peers: {} }; - for (let line in split(r.out, '\n')) { - let f = split(line, '\t'); - if (length(f) < 5 || !valid_key(f[1])) - continue; - let key2 = valid_key(f[2]); - if (key2 && match(f[3] ?? '', DIGITS)) - out.ifaces[f[0]] = { public_key: f[2], port: +f[3] }; - else if (length(f) >= 9 && (key2 || f[2] == '(none)')) { - let ep = f[3] == '(none)' ? '' : f[3]; - out.peers[f[1]] = { - ifname: f[0], - endpoint: ep, - handshake: +f[5], - rx: +f[6], - tx: +f[7], - }; - } +function read_iface(out, ifname) { + // Read around the call: a link set up again in between gave counters of either one. + let before = ifindex(ifname); + // Not there (a tunnel netifd could not bring up, AmneziaWG gone after an + // upgrade): no process to learn it. One that appears is read next time. + if (before == null) { + out.reads[ifname] = 'down'; + return; } - if (!out.ok && type(wanted) == 'array') - out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0; + let r = sh(`awg show ${q(ifname)} dump`); + let ix = ifindex(ifname); + let iface = null, peers = {}; + if (r.code == 0) + for (let line in split(r.out, '\n')) { + let f = split(line, '\t'); + if (length(f) < 4 || !valid_key(f[0])) + continue; + let key2 = valid_key(f[1]); + if (key2 && match(f[2], DIGITS)) + iface = { public_key: f[1], port: +f[2], ifindex: ix }; + else if (length(f) >= 8 && (key2 || f[1] == '(none)')) + peers[f[0]] = { + ifname, + endpoint: f[2] == '(none)' ? '' : f[2], + handshake: +f[4], + rx: +f[5], + tx: +f[6], + }; + } + let read = iface != null; + // Gone during the read: its peers and their counters are gone with it. + if (ix == null) { + out.reads[ifname] = 'down'; + return; + } + if (!read || ix != before) { + out.reads[ifname] = 'error'; + out.ok = false; + return; + } + out.reads[ifname] = 'read'; + out.ifaces[ifname] = iface; + for (let k, p in peers) + out.peers[k] = p; +} + +/** + * Dawnline's own tunnels, one `awg show dump` each for `ifnames` + * (live.tunnel_ifnames): never `all`, so another AmneziaWG interface on the + * router (a client tunnel with long I1-I5, say) neither slows the 1-second + * watcher down nor has its keys read. Returns { ok, reads: { ifname: 'read' | + * 'down' | 'error' }, ifaces: { ifname: { public_key, port, ifindex } }, + * peers: { pubkey: { ifname, endpoint, handshake, rx, tx } } }, with only + * what was read in `ifaces` and `peers`: + * down the interface does not exist (/sys/class/net has no such link; + * no process is started for it): its peers and counters are gone + * error it exists but could not be read (or was set up again during the + * read): that says nothing about its peers + * `ok` is false when any of them is 'error' (true for an empty list). + */ +export function dump(ifnames) { + let out = { ok: true, reads: {}, ifaces: {}, peers: {} }; + for (let ifn in ifnames ?? []) + read_iface(out, ifn); return out; }; @@ -544,6 +888,8 @@ export function server_state(srv) { * { code: 'ifname', ifname } the interface name is invalid * { code: 'taken', ifname } network. exists and isn't Dawnline's * { code: 'disguise', need, installed } obf_unsupported() + * { code: 'disguise_invalid' } obf_unsafe() finds values AmneziaWG refuses + * (said again from the server's values when read) * Files written by older versions hold the English fragment ("has an invalid * interface name …"), shown as it is. */ @@ -559,9 +905,20 @@ export function blocked_note(r) { if (r.code == 'disguise') return r.installed ? sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: %s)'), r.need, r.installed) : sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: none)'), r.need); + if (r.code == 'disguise_invalid') + return L_('is kept down: its disguise has values AmneziaWG cannot take'); return L_('is kept down'); }; +/** What to do about a reason (blocked_note), for the service log's details. */ +export function blocked_fix(r) { + if (r?.code == 'disguise') + return L_('Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.'); + if (r?.code == 'disguise_invalid') + return L_('Choose a disguise on the Server page: it replaces the values set by hand.'); + return L_('Choose another interface name in the server settings.'); +}; + /** * Why the server's tunnel is kept down (`srv.blocked`), as a sentence with * its name in the reader's language: what the admin UI shows. Null when it @@ -581,6 +938,9 @@ export function blocked_text(srv) { return r.installed ? sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: %s).'), srv.name, r.need, r.installed) : sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: none).'), srv.name, r.need); + // Which values, from the server's own (the reason is kept as a code). + if (r.code == 'disguise_invalid') + return trim(sprintf(_('%s is kept down: its disguise has values AmneziaWG cannot take. %s'), srv.name, join(' ', obf_unsafe(srv.obf)))); return sprintf(_('%s is kept down.'), srv.name); }; @@ -637,7 +997,7 @@ export function probes(m, ctx) { push(out, { id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null, problem: blocked_note(why), back: L_('AmneziaWG is running again'), - detail: () => L_('Choose another interface name in the server settings.'), + detail: () => blocked_fix(why), }); continue; } diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg_builds.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg_builds.uc index 034036b..d2a6980 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg_builds.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg_builds.uc @@ -1,8 +1,12 @@ // Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish // builds per OpenWrt release and target (the kernel module must match the -// firmware). Used by the updater and the Components RPCs. +// firmware), and the record of what was installed on which kernel and boot +// (an update whose module could not be swapped starts with the next boot: +// until then caps() and Health go by the module that still runs). Used by +// the updater, the Components RPCs, dawnline.awg and Health. Installing +// itself is dawnline.upd_awg. -import { readfile } from 'fs'; +import { readfile, stat } from 'fs'; import { connect } from 'ubus'; import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util'; import * as pkg from 'dawnline.pkg'; @@ -36,19 +40,52 @@ export function firmware() { /** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */ export const RECORD = `${DATA_DIR}/awg.json`; +/** This boot (a new one loads the module on disk), or null when the kernel does not say. */ +export function boot_id() { + return trim(readfile('/proc/sys/kernel/random/boot_id') ?? '') || null; +}; + +/** + * The size in memory of the loaded kernel module, or null when none is + * loaded. sysfs has no version for it, but builds differ in size: a module + * reloaded by hand ends a wait for a reboot (pending()). + */ +export function module_core() { + let n = int(trim(readfile('/sys/module/amneziawg/coresize') ?? '')); + return n > 0 ? n : null; +}; + /** * Remember which build was installed on which kernel. After a firmware * upgrade the module is gone (it was built for that kernel): Health can then - * say so and offer the build for the new one (dawnline.health). + * say so and offer the build for the new one (dawnline.health). `run` comes + * from an install: prev_gen and prev_core, the module that ran before it + * (module_now()), and reloaded, false while that one stays loaded until the + * next boot. null for a module Dawnline did not install (adopt()). */ -export function record(source, tag, packages) { +export function record(source, tag, packages, run) { ensure_dir(DATA_DIR, 0o700); write_json(RECORD, { osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''), - source, tag, packages, installed: time(), + source, tag, packages, installed: time(), boot: boot_id(), + prev_gen: run?.prev_gen ?? null, prev_core: run?.prev_core ?? null, reloaded: run?.reloaded ?? null, }, 0o600); }; +/** + * A record for a module Dawnline did not install (install.sh, by hand, or + * before Dawnline kept records), so kernel_changed() notices the next + * firmware upgrade: the kernel it is for, source null, `installed` the time + * Dawnline first saw it. Only when there is no record and the module is + * loaded or on disk for the running kernel. The agent calls it when it starts. + */ +export function adopt() { + let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? ''); + if (stat(RECORD) || (!stat('/sys/module/amneziawg') && (rel == '' || !stat(`/lib/modules/${rel}/amneziawg.ko`)))) + return; + record(null, null, null, null); +}; + /** * The firmware the recorded AmneziaWG build was for, when it is not this one * (and the module is gone): { was, now, tag, source }, else null. @@ -88,6 +125,42 @@ export function gen(version) { return '2.0'; }; +/** + * An installed update that waits for a reboot: the install could not swap + * the kernel module (the old one stayed loaded), this is still the boot it + * ran in, and the module loaded is still the one from before it (core: + * module_core() now). Pure: rec is the record or null. + */ +export function pending(rec, boot, core) { + return rec?.reloaded === false && rec.boot != null && rec.boot == boot && core != null && rec.prev_core == core; +}; + +/** + * The AmneziaWG generation of the kernel module that runs: the one from + * before the install while it waits for a reboot (pending(); null when that + * module had no package), else the installed package's version (gen()). + * Pure, with the record, this boot and module_core() passed in. + */ +export function running_gen(rec, boot, core, version) { + return pending(rec, boot, core) ? rec.prev_gen : gen(version); +}; + +/** + * The kernel module loaded now, taken before an install changes packages: + * { core, gen, pending }. core is null when none is loaded; gen is what it + * runs (running_gen(), from `version`, the kmod-amneziawg package installed + * now); pending, an earlier update that still waits for a reboot. + */ +export function module_now(version) { + let rec = read_json(RECORD, null), boot = boot_id(), core = module_core(); + return { core, gen: core == null ? null : running_gen(rec, boot, core, version), pending: pending(rec, boot, core) }; +}; + +/** The installed AmneziaWG update waits for a reboot (pending(), for Health and Components). */ +export function waits_for_reboot() { + return pending(read_json(RECORD, null), boot_id(), module_core()); +}; + /** The installed AmneziaWG packages: { name: version | null }. */ export function installed() { let r = {}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc index 8eeda5d..396d752 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc @@ -1,7 +1,8 @@ // Dawnline — backups (tar.gz of the config and its data files), restoring // them, and the JSON export / import. Whatever comes back in is checked first: // only Dawnline's own regular files, and servers that cannot take over one of -// the router's own interfaces or networks. +// the router's own interfaces or networks, or hand the kernel disguise values +// AmneziaWG refuses. import { readfile, stat, unlink, lsdir, rename } from 'fs'; import { cursor } from 'uci'; @@ -9,6 +10,7 @@ import { q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION } from 'dawnline.util'; import * as core from 'dawnline.core'; +import * as awg from 'dawnline.awg'; import * as live from 'dawnline.live'; import * as apply from 'dawnline.apply'; import * as net from 'dawnline.net'; @@ -39,9 +41,10 @@ const MAX_UNPACKED = 16 * 1024 * 1024; /** * What is wrong with a configuration about to replace the current one * (cursor `c` holds it): each server must have a valid, unique interface - * name that is not one of the router's own interfaces, a free subnet and a - * unique port, and the people and devices must be consistent - * (core.model_errors). [] when it can be used. + * name that is not one of the router's own interfaces, a free subnet, a + * unique port and disguise values AmneziaWG takes (awg.obf_unsafe), and the + * people and devices must be consistent (core.model_errors). [] when it can + * be used. */ export function config_errors(c) { let m = core.load(c); @@ -52,7 +55,7 @@ export function config_errors(c) { let internal = values(net.INTERNAL); let ifnames = {}, ports = {}, subnets = []; for (let id, srv in m.servers) { - for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ])) + for (let e in [ ...core.server_errors(m, srv, [ ...foreign, ...subnets ]), ...awg.obf_unsafe(srv.obf) ]) push(errs, sprintf(_('Server %s: %s'), srv.name, e)); if (ifnames[srv.ifname]) push(errs, sprintf(_('Server %s: interface %s is also used by %s.'), srv.name, srv.ifname, ifnames[srv.ifname])); 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 5114bb4..c4ea77f 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 @@ -4,7 +4,7 @@ import { cursor } from 'uci'; import { - valid_name, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int, + valid_name, valid_device_name, DEVICE_NAME_MAX, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int, rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq } from 'dawnline.util'; import { _, N_ } from 'dawnline.i18n'; @@ -199,6 +199,13 @@ export function load(c) { created: toint(r.created, 0), created_by: r.created_by ?? 'admin', disabled: bool(r.disabled, false), + // The device's own link values (admin only): 0 / null = the server's + // (device_mtu, device_keepalive). Out of range is kept as read, so + // model_errors can name it; the configuration then uses the server's. + mtu: toint(r.mtu, 0), + keepalive: r.keepalive == null || r.keepalive == '' ? null : toint(r.keepalive, null), + // Its own local network stays outside the tunnel (awg.allowed_ips). + lan_bypass: bool(r.lan_bypass, false), }; m.devices[id] = d; if (m.people[d.person]) @@ -367,18 +374,40 @@ export function alloc_address(m, srv) { */ const AUTO_MTU = 1380; const MOBILE_MTU = 1280; +/** What an MTU set by hand may be (the server's and a device's alike). */ +export const MTU_RANGE = [ 1280, 1500 ]; +/** What a keep-alive set by hand may be, in seconds (0 = off). */ +export const KEEPALIVE_RANGE = [ 0, 600 ]; + +function in_range(n, r) { + return type(n) == 'int' && n >= r[0] && n <= r[1]; +} /** The server's tunnel MTU: the one set, or automatic for its disguise. */ export function tunnel_mtu(srv) { return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0)); }; -/** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */ +/** + * The MTU a device's configuration carries: the device's own when the admin + * set one, else the tunnel's, at most 1280 for phones and tablets. + */ export function device_mtu(srv, dev) { + if (in_range(dev.mtu, MTU_RANGE)) + return dev.mtu; let mtu = tunnel_mtu(srv); return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu; }; +/** + * The keep-alive a device's configuration carries, in seconds (0 = off): the + * device's own when the admin set one, else the server's. Both ends never + * have to agree on it (the server's peers carry none), so it is the device's. + */ +export function device_keepalive(srv, dev) { + return in_range(dev?.keepalive, KEEPALIVE_RANGE) ? dev.keepalive : srv.keepalive; +}; + export function endpoint_host(m, srv) { return srv.endpoint || m.settings.portal_host || ''; }; @@ -649,6 +678,8 @@ export function update_person(c, m, id, a) { * Add a device for a person. `opts.keys` = { private_key?, public_key, * preshared_key } from dawnline.awg (or a public key the browser generated). * `opts.by` is 'admin' or 'portal'; the portal is held to the device limit. + * `opts.lan_bypass` true keeps the device's own local network outside the + * tunnel (awg.allowed_ips). */ export function create_device(c, m, person_id, name, kind, opts) { opts ??= {}; @@ -659,8 +690,8 @@ export function create_device(c, m, person_id, name, kind, opts) { if (!srv) fail(_('The person has no server.')); name = trim(name ?? ''); - if (!valid_name(name)) - fail(_('Enter a device name (up to 48 characters).')); + if (!valid_device_name(name)) + fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX)); if (index(KINDS, kind) < 0) kind = 'other'; if (opts.by == 'portal' && length(p.devices) >= p.device_limit) @@ -677,10 +708,15 @@ export function create_device(c, m, person_id, name, kind, opts) { for (let o, d in m.devices) if (d.public_key == k.public_key) fail(_('This key is already in use.')); + // A server's own key (it is in every configuration): the kernel would silently ignore such a peer. + for (let sid, s in m.servers) + if (s.public_key == k.public_key) + fail(_('This key is already in use.')); let id = `d_${rand_hex(4)}`; let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '', - preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false }; + preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false, + mtu: 0, keepalive: null, lan_bypass: opts.lan_bypass === true }; c.set(CONFIG, id, 'device'); c.set(CONFIG, id, 'person', person_id); c.set(CONFIG, id, 'name', name); @@ -691,6 +727,8 @@ export function create_device(c, m, person_id, name, kind, opts) { c.set(CONFIG, id, f, dev[f]); c.set(CONFIG, id, 'created', `${dev.created}`); c.set(CONFIG, id, 'created_by', dev.created_by); + if (dev.lan_bypass) + c.set(CONFIG, id, 'lan_bypass', '1'); // Keep the in-memory model consistent for callers that continue. m.devices[id] = dev; @@ -703,8 +741,8 @@ export function rename_device(c, m, id, name) { if (!d) fail(_('Unknown device.')); name = trim(name ?? ''); - if (!valid_name(name)) - fail(_('Enter a device name (up to 48 characters).')); + if (!valid_device_name(name)) + fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX)); for (let o in m.people[d.person]?.devices ?? []) if (o != id && lc(m.devices[o].name) == lc(name)) fail(sprintf(_('"%s" already exists.'), name)); @@ -712,6 +750,45 @@ export function rename_device(c, m, id, name) { d.name = name; }; +/** + * The admin's link settings of a device: `a` = { mtu?, keepalive?, + * lan_bypass? }, only keys present change; '' takes a number back to the + * server's (0 is a keep-alive of its own: off). Each is in the device's + * configuration alone (the server's peers carry neither), so a change asks + * that device to import again and touches nothing on the router. Returns the + * names of the options that changed. + */ +export function set_device_link(c, m, id, a) { + let d = m.devices[id]; + if (!d) + fail(_('Unknown device.')); + let changed = []; + let put = (k, v, was) => { + if (v == was) + return; + if (v == null) + c.delete(CONFIG, id, k); + else + c.set(CONFIG, id, k, `${v}`); + push(changed, k); + }; + let number = (v, r, msg) => { + let s = trim(`${v}`); + if (s == '') + return null; + if (!match(s, /^[0-9]{1,4}$/) || +s < r[0] || +s > r[1]) + fail(msg); + return +s; + }; + if (a.mtu != null) + put('mtu', number(a.mtu, MTU_RANGE, _('MTU must be 1280-1500.')), d.mtu || null); + if (a.keepalive != null) + put('keepalive', number(a.keepalive, KEEPALIVE_RANGE, _('Keep-alive must be 0-600 seconds.')), d.keepalive); + if (a.lan_bypass != null) + put('lan_bypass', a.lan_bypass === true ? 1 : null, d.lan_bypass ? 1 : null); + return changed; +}; + export function delete_device(c, m, id) { let d = m.devices[id]; if (!d) @@ -781,10 +858,12 @@ export function server_errors(m, srv, others_subnets) { * an address outside their server's subnet, the server's own address, a * prefix on it or one shared with another device (the access sets are keyed * by address, and one bad peer line makes `awg syncconf` refuse the whole - * server), malformed keys, people and devices pointing at servers, people, - * circles or services that do not exist, and two people with one link. [] when - * it is consistent. Import, restore and Health check it; the runtime sync - * skips what it would reject (dawnline.awg, dawnline.nft). + * server), malformed keys, an MTU or keep-alive of their own out of range, + * people and devices pointing at servers, people, circles or services that do + * not exist, and two people with one link. [] when it is consistent. Import, + * restore and Health check it; the runtime sync skips what it would reject + * (dawnline.awg, dawnline.nft), and a configuration takes the server's value + * for a link value out of range (device_mtu, device_keepalive). */ export function model_errors(m) { let errs = []; @@ -816,6 +895,11 @@ export function model_errors(m) { say(_('Device %s of %s: the private key is not a key.')); if (d.preshared_key != '' && !valid_key(d.preshared_key)) say(_('Device %s of %s: the preshared key is not a key.')); + // Its own link values (0 / null: the server's); one out of range is never used. + if (d.mtu && !in_range(d.mtu, MTU_RANGE)) + say(_('Device %s of %s: MTU %d is not between 1280 and 1500.'), d.mtu); + if (d.keepalive != null && !in_range(d.keepalive, KEEPALIVE_RANGE)) + say(_('Device %s of %s: keep-alive %d is not between 0 and 600 seconds.'), d.keepalive); let n = ip2int(d.address); if (n == null) { if (d.address) @@ -825,6 +909,9 @@ export function model_errors(m) { continue; } let srv = m.servers[p.server]; + // AmneziaWG ignores a peer with the interface's own key (dawnline.awg tunnel_devices leaves it out). + if (srv?.public_key && d.public_key == srv.public_key) + say(_("Device %s of %s: the public key is the server's own.")); let t = srv ? parse_cidr(srv.subnet) : null; if (t && (n < t.first || n > t.last)) say(_("Device %s of %s: address %s is outside %s's tunnel %s."), d.address, srv.name, srv.subnet); diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc index e226ec9..56499ea 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc @@ -39,11 +39,15 @@ function own(m, id, opts) { return d; } -/** New device with fresh keys (or the browser's public key): { id, config }. */ +/** + * New device with fresh keys (or the browser's public key): { id, config }. + * `opts.lan_bypass` true keeps its own local network outside the tunnel. + */ export function add(person, name, kind, opts) { opts ??= {}; let by = opts.by ?? 'admin'; - let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) })); + let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, + { by, keys: awg.new_keys(opts.public_key || null), lan_bypass: opts.lan_bypass === true })); let s = apply.sync(); let m = core.load(); live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by }); @@ -52,14 +56,21 @@ export function add(person, name, kind, opts) { }; /** - * Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only - * the admin turns devices off. Returns the runtime sync. + * Rename and/or turn a device off or on, or change how it connects (`ch` = + * { name?, disabled?, mtu?, keepalive?, lan_bypass? }, see + * core.set_device_link); only the admin turns devices off or changes the + * rest. Returns the runtime sync ({} after a change of the link values alone: + * they are in the device's configuration, nothing on the router changes). */ export function update(id, ch, opts) { opts ??= {}; let by = opts.by ?? 'admin'; if (ch.disabled != null && by != 'admin') die(_('Only the admin can turn devices off.')); + let link = ch.mtu != null || ch.keepalive != null || ch.lan_bypass != null; + if (link && by != 'admin') + die(_('Only the admin can change how a device connects.')); + let linked = []; let d0 = store.transact((c, m) => { let d = own(m, id, opts); let was = { ...d }; @@ -71,18 +82,28 @@ export function update(id, ch, opts) { else c.delete(core.CONFIG, id, 'disabled'); } + if (link) + linked = core.set_device_link(c, m, id, ch); return was; }); - let r = apply.sync(); + let r = ch.name != null || ch.disabled != null ? apply.sync() : {}; if (ch.disabled != null && !!ch.disabled != !!d0.disabled) live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by }); else if (ch.name != null && ch.name != d0.name) live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by }); + // The option names, as person_changed lists a person's. + if (length(linked)) + live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: join(', ', linked), by }); return r; }; -/** New keys for a device: returns its new configuration. */ -export function rotate(id, opts) { +/* + * New keys for a device: returns its new configuration, marked as issued (it + * goes to the set-up sheet; the device then waits for it as "Not set up yet", + * not as "settings changed"). Only through reconnect: new keys always mean + * setting the device up again. + */ +function rotate(id, opts) { opts ??= {}; let by = opts.by ?? 'admin'; store.transact((c, m) => { @@ -104,14 +125,15 @@ export function rotate(id, opts) { if (s?.warning) cfg.warning = s.warning; return cfg; -}; +} /** * Set a device up from scratch (a new phone, the app reinstalled, settings - * the admin changed): new keys, so the configuration it holds stops working - * with the sync, and it counts as not set up until it connects with the new - * one. The usage keeps the old keys' last handshake: awg.handshake_since hides - * it. Returns the new configuration, as rotate. + * the admin changed; the portal's Reconnect and the admin's New keys): new + * keys, so the configuration it holds stops working with the sync, and it + * counts as not set up until it connects with the new one. The usage keeps + * the old keys' last handshake: awg.handshake_since hides it. Returns the new + * configuration (with `warning` when the sync did not fully take). */ export function reconnect(id, opts) { opts ??= {}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc index ce9c7e1..1531773 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc @@ -223,23 +223,138 @@ export function wan_kind(wan) { return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public'; }; +const HEX = '0123456789abcdef'; + +// An IPv6 address as its 32 hex digits, so two spellings of one address +// compare equal (2001:DB8::1, 2001:db8:0::1, as typed or as a tool prints +// it); null when it is none. No regex: the router's addresses and a name's +// AAAA records go through it on every look. +function ip6_full(s) { + if (type(s) != 'string') + return null; + let halves = split(lc(s), '::'); + if (length(halves) > 2) + return null; + let head = halves[0] != '' ? split(halves[0], ':') : []; + let tail = length(halves) == 2 && halves[1] != '' ? split(halves[1], ':') : []; + let gap = 8 - length(head) - length(tail); + if (length(halves) == 2 ? gap < 1 : gap != 0) + return null; + let groups = [ ...head ]; + for (let i = 0; i < gap; i++) + push(groups, '0'); + push(groups, ...tail); + let out = ''; + for (let g in groups) { + if (length(g) < 1 || length(g) > 4 || ltrim(g, HEX) != '') + return null; + out += substr(`0000${g}`, length(g)); + } + return out; +} + +/** + * The router's public IPv6 addresses in `ip -6 -j addr show scope global` + * output (`links`), on any interface: a DDNS client may publish the LAN's + * address from the delegated prefix, which reaches the router too. Unique + * local addresses (fc00::/7: OpenWrt gives the LAN one even without IPv6 + * from the ISP) and failed duplicates do not count: nothing reaches them from + * outside. [] when there is none. + */ +export function own_ipv6(links) { + let out = []; + for (let l in (type(links) == 'array' ? links : [])) + for (let a in l?.addr_info ?? []) { + let k = ip6_full(a?.local); + if (k && a.family == 'inet6' && !a.dadfailed && substr(k, 0, 2) != 'fc' && substr(k, 0, 2) != 'fd') + push(out, a.local); + } + return out; +}; + +// The router's public IPv6 addresses (own_ipv6), or null when `ip` could not tell. +function router_ipv6() { + let out = sh_out('ip -6 -j addr show scope global'); + if (out == null) + return null; + try { + let links = json(out || '[]'); + return type(links) == 'array' ? own_ipv6(links) : null; + } + catch (e) { + // No JSON (an `ip` without -j): unknown, so the AAAA records get no verdict. + return null; + } +} + +// What the facts are made from, read on the router. +function endpoint_reads(srv, host) { + let ips = host ? lookup.resolve(host) : []; + // The router's IPv6 only when the name has some to compare with. + return { + ips, wan: srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan'), + router6: length(filter(ips, (a) => ip2int(a) == null)) ? router_ipv6() : null, + }; +} + /** * What a public address points at, for Health and the "as you type" check on * the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare, - * here (an IPv4 of it is this router's WAN), v6_only }. + * here (an IPv4 of it is this router's WAN), v6_only, router6 (the router's + * public IPv6 addresses, own_ipv6; null when unknown, or not read because the + * name has no IPv6), foreign6 (its IPv6 addresses that are none of those, all + * of them when the router has none; null while router6 is), here6 (it has + * IPv6 addresses and each is one of the router's) }. `reads` (a test's) + * stands for what is read on the router: { ips, wan, router6 }. */ -export function endpoint_facts(srv, host) { - let ips = host ? lookup.resolve(host) : []; - let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan'); +export function endpoint_facts(srv, host, reads) { + let r = reads ?? endpoint_reads(srv, host); + let ips = r.ips ?? [], wan = r.wan ?? null; let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null); + let own = r.router6 != null ? map(r.router6, ip6_full) : null; + let foreign6 = own != null ? filter(ips6, (a) => index(own, ip6_full(a)) < 0) : null; return { - host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan), + host, ips, ips4, ips6, wan, kind: wan_kind(wan), cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0, here: wan != null && index(ips4, wan) >= 0, v6_only: !length(ips4) && length(ips6) > 0, + router6: r.router6 ?? null, foreign6, + here6: foreign6 != null && length(ips6) > 0 && !length(foreign6), }; }; +/* + * The name's IPv6 addresses that do not reach this router from outside, in + * words, or null (each is a public one of the router, or those are unknown). + * A name with IPv4 too: devices that prefer IPv6 take these and fail, the + * others connect. + */ +function aaaa_words(f) { + let bad = f.foreign6 ?? [], n = length(bad); + if (!n) + return null; + if (!length(f.router6)) + return sprintf(N_(n, '%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.', + '%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router.'), + f.host, join(', ', bad)); + return sprintf(N_(n, '%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.', + '%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.'), + f.host, join(', ', bad)); +} + +// An IPv6-only name none of whose addresses is a public one of the router: no device connects. Null otherwise. +function v6_only_unreached(f) { + let n = length(f.foreign6 ?? []); + if (!n || n < length(f.ips6)) + return null; + if (!length(f.router6)) + return sprintf(_('%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.'), + f.host, join(', ', f.ips6)); + return sprintf(N_(n, '%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.', + '%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.'), + f.host, join(', ', f.ips6)); +} + /** * The facts in words, in the language of the call: { status: ok|warn|error, text } * (text a whole sentence). `proto_note` names what must get through ("UDP 4500"). @@ -252,18 +367,28 @@ export function endpoint_words(f, proto_note) { if (f.cloudflare) return { status: 'error', text: sprintf(_("%s → %s (Cloudflare). %s reaches the router only if this name is DNS-only there, or use the router's IP."), f.host, join(', ', f.ips), proto_note) }; - if (f.v6_only) + let v6 = aaaa_words(f); + if (f.v6_only) { + let none = v6_only_unreached(f); + if (none != null || v6 != null) + return { status: 'warn', text: none ?? v6 }; return { status: f.kind == 'public' ? 'warn' : 'ok', text: f.kind == 'public' ? sprintf(_("%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."), f.host, join(', ', f.ips6), f.wan) : sprintf(_('%s → %s: IPv6 only, so only devices with IPv6 connect.'), f.host, join(', ', f.ips6)) }; + } + let v4 = null; if (f.kind == 'cgnat' || f.kind == 'private') - return { status: 'warn', text: f.kind == 'cgnat' + v4 = f.kind == 'cgnat' ? sprintf(_('The WAN address %s is CGNAT (shared by the ISP): %s cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.'), f.wan, proto_note) - : sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note) }; - if (f.wan && !f.here) - return { status: 'warn', text: sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan) }; + : sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note); + else if (f.wan && !f.here) + v4 = sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan); + // Two separate facts, each a sentence of its own: the IPv4 one first. + if (v4 != null || v6 != null) + return { status: 'warn', text: join(' ', filter([ v4, v6 ], (x) => x != null)) }; // Without the router's WAN address only the facts: names and addresses, no words. - return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, f.wan) : `${f.host} → ${join(', ', f.ips)}` }; + return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, join(', ', [ f.wan, ...(f.here6 ? f.ips6 : []) ])) + : `${f.host} → ${join(', ', f.ips)}` }; }; /** What a public address resolves to and whether that reaches this router (for a core's protocol). */ @@ -332,9 +457,53 @@ function awg_check() { } if (!st.handler) return check('awg', title, 'error', no_proto(), 'netrestart', _('The network doesn’t know AmneziaWG yet')); + // The install could not swap the loaded module: the old one runs until the next boot (dawnline.awg_builds). + if (builds.waits_for_reboot()) + return check('awg', title, 'warn', _('The AmneziaWG update is installed and starts after a reboot.'), null, + _('The AmneziaWG update waits for a reboot')); return check('awg', title, 'ok', _('Kernel module, awg tool and the netifd protocol are present.')); } +/** + * The /24s home routers come with out of the box. A home network on one of + * them is very likely the same as the network a person connects from, and + * home access then takes those addresses into the tunnel: their own printer or + * TV is out of reach while connected, LAN Bypass or not. + */ +const COMMON_HOME = [ + '192.168.0.0/24', '192.168.1.0/24', '192.168.2.0/24', '192.168.3.0/24', '192.168.8.0/24', '192.168.10.0/24', + '192.168.31.0/24', '192.168.50.0/24', '192.168.88.0/24', '192.168.100.0/24', '192.168.178.0/24', + '10.0.0.0/24', '10.1.1.0/24', +]; + +/** The home networks in `nets` that overlap a common out-of-the-box subnet. */ +export function common_home(nets) { + return filter(nets ?? [], (n) => { + let a = parse_cidr(n); + return a && length(filter(COMMON_HOME, (c) => cidr_overlaps(a, parse_cidr(c)))); + }); +}; + +/** + * Whether the server's home networks are on a common subnet, while anyone on + * it has home access (otherwise nothing of home goes into the tunnel). A + * warning on Health only: advice, not a fault, so no notice elsewhere. + */ +function home_check(m, id, srv, label) { + let reach = filter(values(m.people), (p) => p.server == id && (p.access == 'lan' || p.access == 'both')); + let nets = net.server_net(srv).nets; + if (!length(reach) || !length(nets)) + return null; + let bad = common_home(nets); + let c = check(`homenet_${id}`, _('Home network addresses') + label, length(bad) ? 'warn' : 'ok', + length(bad) + ? sprintf(_('%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24.'), join(', ', bad)) + : sprintf(_('%s is not a common home subnet: the networks people connect from rarely use the same addresses.'), join(', ', nets)), + null); + c.problem = null; + return c; +} + /** Checks of a server's AmneziaWG tunnel. */ function awg_checks(m, id, srv, label, fwc, dmp, rep) { let out = []; @@ -350,26 +519,15 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) { !st ? sprintf(_('%s does not exist.'), srv.ifname) : length(codes) ? sprintf(_('%s is down: %s.'), srv.ifname, join(', ', codes)) : sprintf(_('%s is down.'), srv.ifname), up ? null : (st ? 'ifup:' + srv.ifname : 'apply'), down)); - if (up) { - // By key, not by count: a stale peer standing in for a missing one would - // make the numbers match. - let states = apply.states_for(m, core.load_usage()); - let wanted = {}, expected = 0; - for (let did, d in m.devices) { - let p = m.people[d.person]; - if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) { - wanted[d.public_key] = true; - expected++; - } - } - let loaded = {}, actual = 0; - for (let k, p in dmp.peers) - if (p.ifname == srv.ifname) { - loaded[k] = true; - actual++; - } - let missing = length(filter(keys(wanted), (k) => !loaded[k])); - let extra = length(filter(keys(loaded), (k) => !wanted[k])); + // The devices the sync loads, by the same choice the agent compares with every minute. + if (up && dmp.reads[srv.ifname] == 'error') + push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, 'warn', + _('The tunnel could not be read, so its devices could not be checked.'), null, + _('The devices in AmneziaWG could not be checked') + label)); + else if (up) { + let devs = awg.tunnel_devices(m, id, apply.states_for(m, core.load_usage())); + let diff = awg.peer_diff(devs, dmp, srv.ifname); + let expected = length(devs), missing = diff.missing, extra = diff.extra, actual = diff.loaded; let same = !missing && !extra; push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, same ? 'ok' : 'warn', same ? sprintf(N_(actual, '%d device is loaded in the tunnel.', '%d devices are loaded in the tunnel.'), actual) : @@ -406,6 +564,9 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) { push(out, check(`subnet_${id}`, _('AmneziaWG subnet is unique') + label, length(overlaps) ? 'error' : 'ok', length(overlaps) ? sprintf(_('%s overlaps %s.'), srv.subnet, join(', ', overlaps)) : sprintf(_('%s does not overlap other networks.'), srv.subnet), null, _('AmneziaWG subnet overlaps another network') + label)); + let home = home_check(m, id, srv, label); + if (home) + push(out, home); return out; } diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/link.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/link.uc new file mode 100644 index 0000000..5965b5e --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/link.uc @@ -0,0 +1,433 @@ +// Dawnline — how each device's link behaves, from the counters the agent's +// watcher reads every second (dawnline.awg.dump): a device that knocks but +// never finishes connecting, one whose configuration is in use on two devices, +// one whose traffic the router drops, one whose connection keeps breaking. +// +// The agent keeps one history per device in memory (fresh(), observe(): a few +// events of the last HISTORY seconds, not one entry per tick), classifies it +// (classify(), pure) and shows a state only once it held HOLD seconds +// (settle()). It writes what is shown to dawnline.live.LINK on a change; the +// read side (live.dump's `link`, view.device_view) is dawnline.live's, so the +// portal never loads this module. Who is online stays live.PRESENCE's. +// +// The same history tells the set-up sheet, at once and without HOLD, what a +// device that is being set up does right now (setup_state(), setup()): it +// knocks without finishing, data flows, or it connected but nothing it sends +// comes through. The agent writes that to dawnline.live.SETUP on a change. +// +// What the counters mean (kmod 3.1, receive.c and send.c): +// * an accepted handshake initiation adds exactly INITIATION bytes to the +// peer's rx: the S1 prefix and any trailer are cut off and the header +// protection is undone in place before update_rx_stats(skb->len). The +// router answers it; its own handshake time moves only when the first +// packet under the new keys arrives. +// * a keepalive adds KEEPALIVE plus its content padding; a handshake +// response (the router initiated) RESPONSE; data 32 + its padded length. +// Plain data is a multiple of 16, so 148, 296 and 444 never are data. +// * a data packet the router then drops (its source is not the device's +// address: an old configuration after renumbering; this is what moves +// the interface's rx_frame_errors) adds nothing to rx, but the router +// still answers it with a keepalive within KeepaliveTimeout (about 10 s). + +/** Seconds of events kept per device. */ +export const HISTORY = 600; +/** A state is shown once it held this long (a flapping mobile link passes). */ +export const HOLD = 180; +/** A device is classified at least this often when nothing happened (its spans age). */ +export const CHECK_EVERY = 15; + +/** Bytes an accepted initiation adds to rx (sizeof(struct message_handshake_initiation)). */ +export const INITIATION = 148; +/** Bytes a handshake response adds to rx (the router initiated). */ +export const RESPONSE = 92; +/** Bytes an empty data packet adds to rx, before content padding. */ +export const KEEPALIVE = 32; +// Random trailers without content padding: a keepalive grows up to a full packet. +const TRAILER_MAX = 1500; +// Initiations a device sends at most in one second (retries are 5 s apart). +const KNOCKS_PER_TICK = 3; + +/** trying: at least TRY_KNOCKS accepted initiations within TRY_SPAN seconds while not online. */ +export const TRY_SPAN = 120; +export const TRY_KNOCKS = 3; +/* + * Churning: at least CHURN_COUNT handshakes within CHURN_SPAN seconds, with + * CHURN_COUNT - 1 of the gaps under CHURN_GAP seconds. A device that is + * there renews its keys every 100-120 s (RekeyAfterTime), more only when + * its packets get nothing back (KeepaliveTimeout + RekeyTimeout, ~15 s). + */ +export const CHURN_SPAN = 300; +export const CHURN_COUNT = 4; +export const CHURN_GAP = 45; +/** shared: while churning, the endpoint (ip:port) went back to an earlier one this often. */ +export const SHARE_RETURNS = 2; +/* + * dropped: online with a handshake within DROP_HS seconds, nothing but + * handshakes and keepalives received for DROP_SPAN seconds, and the router + * sent something at least DROP_ANSWERS times in that span with nothing + * coming in (its keepalives answering packets it dropped), under DROP_TX + * bytes in all (a real download is far more). + */ +export const DROP_SPAN = 180; +export const DROP_HS = 240; +export const DROP_ANSWERS = 6; +export const DROP_TX = 65536; + +/** Every state classify() can give. */ +export const STATES = [ 'trying', 'shared', 'dropped', 'unstable' ]; + +/* + * The set-up sheet's trying: at least SETUP_KNOCKS accepted initiations + * within SETUP_SPAN seconds, none of them followed by a handshake. A device + * retries every 5 s, so it shows with the second (5-6 s in) and goes about + * 15 s after the last. + */ +export const SETUP_SPAN = 20; +export const SETUP_KNOCKS = 2; +/* + * nodata: online for SETUP_QUIET seconds since the handshake its session + * began with, nothing but handshakes and keepalives in since, and the router + * answered at least once with nothing coming in (a keepalive for data it + * dropped, about 10 s after it: an old address in the configuration). An + * idle device gets no answers, so it never shows. + */ +export const SETUP_QUIET = 15; + +// Per list, the newest entries kept (a device whose endpoint flips every second). +const KEEP = 64; + +function keep(list, entry) { + push(list, entry); + if (length(list) > KEEP) + shift(list); +} + +/** + * A new, empty history for a device first seen at `now`. Fields: rx, tx + * (the counters last read, null before the first read), hs (the newest + * handshake), ep (the endpoint), data (when rx last carried data), hsev + * (handshake times), epev ([ ts, ip:port, the one before ] endpoint + * changes), knocks (times + * of accepted initiations), ans ([ ts, bytes ] the router sent with nothing + * received), state/since (what is shown), pend (a state waiting for HOLD), + * raw (the last classification), checked (when it was made); for the set-up + * sheet (setup()): on (online at the last read), sess (the handshake its + * online stretch began with, 0 while away), setup ({ state, since } or null) + * and due (when setup_state() may change with time alone, 0 for never). + */ +export function fresh(now) { + return { + start: now, rx: null, tx: null, hs: 0, ep: null, data: 0, + hsev: [], epev: [], knocks: [], ans: [], + state: null, since: 0, pend: null, raw: null, checked: 0, + on: false, sess: 0, setup: null, due: 0, + }; +}; + +/** + * The largest rx a keepalive adds for a server's disguise: KEEPALIVE plus + * the top of its ContentPaddingAddition, or a full packet with random + * trailers and no content padding (the apps get the server's values). + */ +export function keepalive_max(srv) { + let o = srv?.obf ?? {}; + let cpa = split(`${o.content_padding_addition ?? ''}`, '-'); + let hi = +(cpa[length(cpa) - 1]); + if (o.content_padding_addition != null && o.content_padding_addition != '' && hi > 0) + return KEEPALIVE + hi; + if (o.random_trailers == 'on' || o.random_trailers == '1') + return KEEPALIVE + TRAILER_MAX; + return KEEPALIVE; +}; + +/** keepalive_max() for each device's server: { device id: bytes }. */ +export function keepalive_sizes(m) { + let out = {}; + for (let id, d in m.devices) + out[id] = keepalive_max(m.servers[m.people[d.person]?.server]); + return out; +}; + +/** An rx increment made of accepted initiations only. */ +export function knock(drx) { + return drx > 0 && drx % INITIATION == 0 && drx <= KNOCKS_PER_TICK * INITIATION; +}; + +/** + * An rx increment that carried no data: nothing, or one keepalive of up to + * `ka` bytes (keepalive_max); in the second a handshake completed (`shook`) + * also the handshake messages that came with it. Outside that second a + * handshake message is never counted in: with a padded keepalive their + * sums would cover every small packet (a DNS query, an ACK) up to some + * 670 bytes, and a device with light traffic would look like one whose + * data never comes through. + */ +export function bare(drx, ka, shook) { + if (drx <= 0) + return true; + if (!shook) + return drx >= KEEPALIVE && drx <= ka; + if (drx > KNOCKS_PER_TICK * INITIATION + RESPONSE + ka) + return false; + for (let k = 0; k <= KNOCKS_PER_TICK; k++) + for (let r = 0; r <= 1; r++) { + let rest = drx - k * INITIATION - r * RESPONSE; + if (rest == 0 || (rest >= KEEPALIVE && rest <= ka)) + return true; + } + return false; +}; + +/** + * Fold one read of the device's peer ({ endpoint, handshake, rx, tx } from + * awg.dump) at `now` into its history `h`; `ka` is its keepalive_max(). + * Returns true when something worth classifying again happened (a + * handshake, a new endpoint, a knock, an answer, data after a quiet span). + * Counters that went down (the peer re-added, its tunnel set up again) + * start a new baseline. + */ +export function observe(h, peer, now, ka) { + let changed = false; + let shook = peer.handshake > h.hs; + if (shook) { + keep(h.hsev, peer.handshake); + h.hs = peer.handshake; + changed = true; + } + if (peer.endpoint != h.ep) { + if (h.ep != null && peer.endpoint != '') { + keep(h.epev, [ now, peer.endpoint, h.ep ]); + changed = true; + } + h.ep = peer.endpoint; + } + if (h.rx == null || peer.rx < h.rx || peer.tx < h.tx) { + h.rx = peer.rx; + h.tx = peer.tx; + return changed; + } + let drx = peer.rx - h.rx, dtx = peer.tx - h.tx; + h.rx = peer.rx; + h.tx = peer.tx; + if (drx > 0) { + if (!shook && knock(drx)) { + keep(h.knocks, now); + changed = true; + } + else if (!bare(drx, ka, shook)) { + if (now - h.data >= DROP_SPAN) + changed = true; + h.data = now; + } + } + else if (dtx > 0) { + keep(h.ans, [ now, dtx ]); + changed = true; + } + return changed; +}; + +/** The device's peer is not in its tunnel: the next read starts a new baseline. */ +export function gone(h) { + h.rx = null; + h.tx = null; +}; + +/** Forget events older than HISTORY seconds. */ +export function prune(h, now) { + let cut = now - HISTORY; + h.hsev = filter(h.hsev, (t) => t > cut); + h.knocks = filter(h.knocks, (t) => t > cut); + h.epev = filter(h.epev, (e) => e[0] > cut); + h.ans = filter(h.ans, (e) => e[0] > cut); +}; + +/** Endpoint changes within the span that went back to an endpoint seen before in it (A → B → A → B: 2). */ +function returns(h, now) { + let seen = null, n = 0; + for (let e in h.epev) + if (now - e[0] < CHURN_SPAN) { + if (seen == null) { + seen = {}; + seen[e[2]] = true; + } + if (seen[e[1]]) + n++; + seen[e[1]] = true; + } + return n; +} + +function churning(h, now) { + let hs = filter(h.hsev, (t) => now - t < CHURN_SPAN); + if (length(hs) < CHURN_COUNT) + return false; + let short = 0; + for (let i = 1; i < length(hs); i++) + if (hs[i] - hs[i - 1] < CHURN_GAP) + short++; + return short >= CHURN_COUNT - 1; +} + +function dropped(h, now) { + if (now - h.start < DROP_SPAN || now - h.data < DROP_SPAN || !(h.hs > 0 && now - h.hs < DROP_HS)) + return false; + let n = 0, bytes = 0; + for (let a in h.ans) + if (now - a[0] < DROP_SPAN) { + n++; + bytes += a[1]; + } + return n >= DROP_ANSWERS && bytes < DROP_TX; +} + +/** + * What the history says about the device at `now` (`on`: it is online, as + * the watcher decides it): null (nothing wrong, or nothing to tell), or + * 'trying' not online, but its initiations reach the router and are + * answered, and it never finishes connecting (the network + * may block it, or its configuration is out of date: a + * stale preshared key looks the same) + * 'shared' connecting over and over from two or more alternating + * endpoints (ip:port): one configuration on two devices + * 'unstable' connecting over and over from one place: the connection + * keeps breaking + * 'dropped' connected, but nothing it sends gets through: the router + * drops it (an old address in its configuration) + */ +export function classify(h, now, on) { + if (!on) { + let n = 0; + for (let t in h.knocks) + if (now - t < TRY_SPAN) + n++; + return n >= TRY_KNOCKS ? 'trying' : null; + } + if (churning(h, now)) + return returns(h, now) >= SHARE_RETURNS ? 'shared' : 'unstable'; + return dropped(h, now) ? 'dropped' : null; +}; + +/** + * Turn a classification into what is shown (h.state, h.since): a state, or + * a change of state, shows once classify() gave it for HOLD seconds (since + * = when it began); nothing wrong shows at once when the device is online + * (it works), else after HOLD as well. Returns the change, { from, to } + * (either may be null), or null when what is shown stays. + */ +export function settle(h, raw, now, on) { + if (raw == h.state) { + h.pend = null; + return null; + } + let since = now; + if (raw != null || !on) { + if (h.pend == null || h.pend.state != raw) { + h.pend = { state: raw, since: now }; + return null; + } + if (now - h.pend.since < HOLD) + return null; + since = h.pend.since; + } + let from = h.state; + h.state = raw; + h.since = raw != null ? since : 0; + h.pend = null; + return { from, to: raw }; +}; + +/** + * What the device's link does at `now` for the set-up sheet (pure; `on`: it + * is online, as the watcher decides it): { state, due }. state is + * 'trying' its initiations reach the router and are answered, and no + * handshake follows (SETUP_KNOCKS within SETUP_SPAN): the + * network blocks the answers, or the configuration is not this + * device's any more + * 'flowing' online, and data came in during this session (since h.sess) + * 'nodata' online for SETUP_QUIET seconds, nothing but handshakes and + * keepalives came in, and the router answered packets it + * dropped: an old address in the configuration + * null none of these (waiting, idle, or away) + * due: when the state may change with time alone (a knock ages out, the + * quiet span ends), 0 for never: anything else comes with a read. + */ +export function setup_state(h, now, on) { + let n = 0; + for (let i = length(h.knocks) - 1; i >= 0; i--) { + let t = h.knocks[i]; + if (t <= h.hs || now - t >= SETUP_SPAN) + break; + if (++n == SETUP_KNOCKS) + return { state: 'trying', due: t + SETUP_SPAN }; + } + if (!on || !h.sess) + return { state: null, due: 0 }; + if (h.data >= h.sess) + return { state: 'flowing', due: 0 }; + if (now - h.sess < SETUP_QUIET) + return { state: null, due: h.sess + SETUP_QUIET }; + let a = h.ans[length(h.ans) - 1]; + return { state: a != null && a[0] >= h.sess ? 'nodata' : null, due: 0 }; +}; + +/** + * Bring h.setup to setup_state() after a read at `now` (`moved`: what + * observe() returned). Most reads cost a few compares: the state is worked + * out again only when something happened, the device came or went, data + * came in while it is not 'flowing', or its `due` time came. Returns true + * when h.setup changed ({ state, since: when it began } or null). + */ +export function setup(h, now, on, moved) { + // A session begins with the handshake that brought the device online. + if (!on) + h.sess = 0; + else if (!h.sess) + h.sess = h.hs; + let came = on != h.on; + h.on = on; + let cur = h.setup?.state; + if (!moved && !came && !(h.due && now >= h.due) && !(h.data == now && cur != 'flowing')) + return false; + let s = setup_state(h, now, on); + h.due = s.due; + if (s.state == cur) + return false; + h.setup = s.state != null ? { state: s.state, since: now } : null; + return true; +}; + +/** setup() of every device: { device id: { state, since } }, devices with none left out. */ +export function setups(hist) { + let out = {}; + for (let id, h in hist) + if (h.setup != null) + out[id] = h.setup; + return out; +}; + +/** What is shown for every device: { device id: { state, since } }, devices with nothing to show left out. */ +export function shown(hist) { + let out = {}; + for (let id, h in hist) + if (h.state != null) + out[id] = { state: h.state, since: h.since }; + return out; +}; + +/** + * The activity event for a change settle() made, or null: device_failing + * (detail: the new state) when a state shows, device_recovered (detail: + * the state it had) when it clears while the device is online. One that + * clears while the device is away (it stopped trying, it was paused) logs + * nothing: nobody saw it work. + */ +export function event_for(change, dev, on) { + if (!change) + return null; + if (change.to != null) + return { type: 'device_failing', person: dev.person, device: dev.id, detail: change.to }; + if (on && change.from != null) + return { type: 'device_recovered', person: dev.person, device: dev.id, detail: change.from }; + return null; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc index 6c0b3c0..5726ec9 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc @@ -11,11 +11,14 @@ import { iface_status as util_iface_status, RUN_DIR, DATA_DIR } from 'dawnline.util'; import * as awg from 'dawnline.awg'; +import * as core from 'dawnline.core'; import * as schema from 'dawnline.schema'; // Online while the WireGuard session lives: it is dropped 180 s after its // handshake, and a device that is there renews it every 2 min (a little slack // for a renewal that needs a retry). One that left goes offline 1-3 min later. +// The shortest window: a device whose keep-alive is longer gets more +// (online_window), or it would flap between its handshakes. export const ONLINE_WINDOW = 190; /** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */ export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`; @@ -31,6 +34,8 @@ export const CATEGORY = { person_added: 'people', person_removed: 'people', person_changed: 'people', paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people', server_down: 'problems', server_up: 'problems', portal_blocked: 'problems', + // A device's link (dawnline.link): failing in a named way, and working again. + device_failing: 'problems', device_recovered: 'problems', }; export const CATEGORIES = [ 'connections', 'people', 'problems' ]; @@ -95,24 +100,90 @@ export const PRESENCE = `${RUN_DIR}/presence.json`; const BEAT = `${RUN_DIR}/agent.beat`; const BEAT_STALE = 180; +/** The agent runs (its heartbeat is fresh): what its watcher wrote counts. */ +function agent_running() { + let beat = +(read_json(BEAT, 0) ?? 0); + return beat > 0 && time() - beat <= BEAT_STALE; +} + /** What the watcher sees, or null when the agent isn't running. */ export function presence() { - let beat = +(read_json(BEAT, 0) ?? 0); - if (!beat || time() - beat > BEAT_STALE) - return null; - return read_json(PRESENCE, null); + return agent_running() ? read_json(PRESENCE, null) : null; }; /** - * Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint, - * handshake, rx, tx } }, presence }. See dawnline.awg. + * Written by the agent's watcher when what it shows changes (dawnline.link): + * { device id: { state: 'trying' | 'shared' | 'dropped' | 'unstable', since } }, + * only devices whose link fails in one of these ways (link.classify()). */ -export function dump(m) { - // Only Dawnline's own tunnels decide `ok`: another AmneziaWG interface on - // the router that cannot be read is not our trouble. - let mine = m ? map(filter(values(m.servers), (s) => s.private_key && s.enabled), (s) => s.ifname) : null; - let d = awg.dump(mine); - d.presence = presence(); +export const LINK = `${RUN_DIR}/link.json`; + +/** + * Written by the agent's watcher when it changes (dawnline.link.setup, at + * once, without LINK's hold): what each device's link does right now, for the + * set-up sheet: { device id: { state: 'trying' | 'flowing' | 'nodata', since } }, + * devices with none of these left out. + */ +export const SETUP = `${RUN_DIR}/setup.json`; + +/** + * The interfaces of the servers that run: enabled, with keys and an + * interface that is Dawnline's (core.tunnels: never another tunnel that + * took the name); with `sid`, only that server's. What dawnline.awg.dump() + * reads; an empty list when none. + */ +export function tunnel_ifnames(m, sid) { + let out = []; + for (let id, srv in m.servers) + if (srv.enabled && (sid == null || id == sid)) + for (let t in core.tunnels(srv)) + push(out, t.ifname); + return out; +}; + +/** + * How long after its last handshake a device still counts as online, in + * seconds: ONLINE_WINDOW, or 30 s more than an idle device with its + * keep-alive goes between handshakes (awg.idle_handshake) when that is + * longer. A device that sends nothing renews its session only with its + * keep-alive: with one of about 95-120 s, or over 160 s, the fixed window + * would see it leave and come back between two handshakes. Keep-alive off: + * ONLINE_WINDOW. + */ +export function online_window(srv, dev) { + let h = srv ? awg.idle_handshake(srv, dev) : null; + return h != null ? max(ONLINE_WINDOW, h + 30) : ONLINE_WINDOW; +}; + +/** online_window() of every device (with `sid`, of that server's): { device id: seconds }. */ +export function online_windows(m, sid) { + let out = {}; + for (let id, d in m.devices) { + let s = m.people[d.person]?.server; + if (sid == null || s == sid) + out[id] = online_window(m.servers[s], d); + } + return out; +}; + +/** + * Dawnline's tunnels as dawnline.awg.dump() reads them (only those, each on + * its own: { ok, reads, ifaces, peers: { public key: { ifname, endpoint, + * handshake, rx, tx } } }), plus `presence`, the agent watcher's, `windows`, + * each device's online_window() (online() without the agent), `link`, the + * watcher's LINK ({} without the agent: its states would be stale), and + * `setup`, its SETUP (null without the agent: nobody tells data from a bare + * handshake then, view.device_view goes by the handshake). With `sid` only + * that server's tunnel is read (one person's page needs no other: one `awg` + * process, not one per server). + */ +export function dump(m, sid) { + let d = awg.dump(tunnel_ifnames(m, sid)); + let up = agent_running(); + d.presence = up ? read_json(PRESENCE, null) : null; + d.windows = online_windows(m, sid); + d.link = up ? (read_json(LINK, null) ?? {}) : {}; + d.setup = up ? (read_json(SETUP, null) ?? {}) : null; return d; }; @@ -121,7 +192,7 @@ export function online(dmp, id, peer) { let p = dmp?.presence?.online; if (p) return !!(peer && p[id]); - return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW); + return !!(peer && peer.handshake > 0 && time() - peer.handshake < (dmp?.windows?.[id] ?? ONLINE_WINDOW)); }; // "203.0.113.7:41821", "[2001:db8::1]:41821". A module constant, compiled once: @@ -218,34 +289,36 @@ function offline(rec) { /** * Fold the current kernel counters into `usage`. Counters restart from zero - * when a peer is re-added or the interface restarts; a drop is treated as a - * reset. Returns the per-device live view keyed by device id. + * when a peer is re-added or its tunnel is set up again; a drop is treated + * as a reset, and so is a new link (each record keeps the interface index + * its counters were read on: new counters that already passed the old ones + * would be counted short). Returns the per-device live view keyed by device id. * * A device missing from the dump had its counters reset only when its tunnel - * was actually read: an interface the tool couldn't read says nothing, and - * forgetting the last counters there would count them again on the next good - * read. A failed read with nothing in it changes nothing at all. + * was read or is down (dawnline.awg.dump's `reads`): one the tool couldn't + * read says nothing, and forgetting the last counters there would count them + * again on the next good read. */ export function collect(m, usage, d) { d ??= dump(m); let ts = time(); let live = {}; - if (d.ok === false && !length(d.peers)) { - for (let id in keys(m.devices)) - live[id] = offline(usage.devices[id]); - return live; - } for (let id, dev in m.devices) { let rec = usage.devices[id] ??= { raw: [ 0, 0 ] }; let peer = d.peers[dev.public_key]; if (!peer) { let ifname = m.servers[m.people[dev.person]?.server]?.ifname; - if (d.ok !== false || d.ifaces[ifname] != null) + if (d.reads[ifname] != 'error') rec.raw = [ 0, 0 ]; live[id] = offline(rec); continue; } let raw = rec.raw ?? [ 0, 0 ]; + let link = d.ifaces[peer.ifname]?.ifindex; + if (link != null && rec.ifindex != null && link != rec.ifindex) + raw = [ 0, 0 ]; + if (link != null) + rec.ifindex = link; let drx = peer.rx >= raw[0] ? peer.rx - raw[0] : peer.rx; let dtx = peer.tx >= raw[1] ? peer.tx - raw[1] : peer.tx; rec.raw = [ peer.rx, peer.tx ]; @@ -266,7 +339,7 @@ export function collect(m, usage, d) { delete rec.ips[ips[i]]; } live[id] = { - online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW, + online: peer.handshake > 0 && ts - peer.handshake < online_window(m.servers[m.people[dev.person]?.server], dev), handshake: peer.handshake || rec.handshake || 0, endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '', present: true, @@ -373,7 +446,10 @@ export function add_event(e) { add_events([ e ]); }; -/** Like add_event, but folds into the previous event of the same kind and person within `window` s. */ +/** + * Like add_event, but folds into the previous event of the same kind, person + * and device (when it has one) within `window` s. + */ export function add_event_merged(e, window) { let pol = policy(); if (index(pol.categories, category_of(e.type)) < 0) @@ -382,7 +458,7 @@ export function add_event_merged(e, window) { let ev = load_events(); let last = ev[length(ev) - 1]; let ts = time(); - if (last && last.type == e.type && last.person == e.person && ts - last.ts < (window ?? 120)) { + if (last && last.type == e.type && last.person == e.person && last.device == e.device && ts - last.ts < (window ?? 120)) { let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]); last.detail = join(', ', filter(parts, (x) => x != '')); last.ts = ts; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc index 206b625..b288d90 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc @@ -397,6 +397,23 @@ function load_ns_rules(p) { return slow ? { fast: false, slow, err: load(false) } : { fast: true }; } +/** + * The policy rules plan `p` wants (pure), in order: [{ pref, iif, to, table }] + * (to null: all). Per server interface: DNS to the netns address through the + * netns, home networks and the tunnel network by main, the rest into the netns. + */ +export function rules(p) { + let out = []; + let rule = (pref, iif, to, table) => push(out, { pref, iif, to, table }); + for (let s in p?.servers ?? []) { + rule(PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}`); + for (let n in s.direct) + rule(PREF_MAIN, s.ifname, n, 'main'); + rule(PREF_LOOP, s.ifname, null, `${p.table}`); + } + return out; +}; + /** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */ function current_rules(ifnames) { let out = []; @@ -411,31 +428,58 @@ function current_rules(ifnames) { } -function rule_key(pref, iif, to, table) { - // `ip -j rule` shows a /32 destination without its length. - if (to && index(to, '/') < 0) - to += '/32'; - return `${pref} ${iif} ${to ?? 'all'} ${table}`; +// A rule of ours with a source (none of rules() has one) is told apart, so it is removed. +function rule_key(pref, from, iif, to, table) { + // `ip -j rule` shows a /32 source or destination without its length. + let full = (n) => n && index(n, '/') < 0 ? `${n}/32` : n; + return `${pref} ${full(from) ?? 'all'} ${iif} ${full(to) ?? 'all'} ${table}`; } -function sync_rules(p, ifnames) { - let want = []; - for (let s in p?.servers ?? []) { - push(want, [ PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}` ]); - for (let n in s.direct) - push(want, [ PREF_MAIN, s.ifname, n, 'main' ]); - push(want, [ PREF_LOOP, s.ifname, null, `${p.table}` ]); +/** + * A source or destination as `ip -j rule` has it ("10.9.0.2", or with its + * length), or null for all: a rule without a source shows `"src": "all"` + * (iproute2 prints "from all"), one without a destination no `dst`. + */ +function rule_net(addr, len) { + return addr && addr != 'all' ? `${addr}${len != null ? '/' + len : ''}` : null; +} + +/** The command that removes one of current_rules(). */ +function rule_del(r) { + let from = rule_net(r.src, r.srclen), to = rule_net(r.dst, r.dstlen); + return `ip -4 rule del priority ${r.priority}${from ? ' from ' + from : ''} iif ${q(r.iif)}${to ? ' to ' + to : ''} lookup ${r.table}`; +} + +/** + * The commands that turn rules `current` (ours, as `ip -j -4 rule show` + * prints them) into rules(p) (pure): the missing ones added first, then the + * ones no longer wanted removed, so a device's traffic never falls between + * two rules while others change. [] when they are as wanted. + */ +export function rule_cmds(p, current) { + let have = {}, want = {}, cmds = [], twice = []; + for (let r in current) { + let k = rule_key(r.priority, rule_net(r.src, r.srclen), r.iif, rule_net(r.dst, r.dstlen), r.table); + if (have[k]) + push(twice, rule_del(r)); + have[k] = r; } - let have = map(current_rules(ifnames), (r) => rule_key(r.priority, r.iif, r.dst ? `${r.dst}${r.dstlen != null ? '/' + r.dstlen : ''}` : null, r.table)); - let wantk = map(want, (w) => rule_key(w[0], w[1], w[2] ?? null, w[3])); - if (join('\n', sort(have)) == join('\n', sort(wantk))) - return []; - let cmds = []; - for (let r in current_rules(ifnames)) - push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`); - for (let w in want) - push(cmds, `ip -4 rule add priority ${w[0]} iif ${q(w[1])}${w[2] ? ' to ' + w[2] : ''} lookup ${w[3]}`); + for (let w in rules(p)) { + let k = rule_key(w.pref, null, w.iif, w.to, w.table); + if (!have[k] && !want[k]) + push(cmds, `ip -4 rule add priority ${w.pref} iif ${q(w.iif)}${w.to ? ' to ' + w.to : ''} lookup ${w.table}`); + want[k] = true; + } + for (let k, r in have) + if (!want[k]) + push(cmds, rule_del(r)); + // The same rule twice (one deletion removes one of them). + push(cmds, ...twice); return cmds; +}; + +function sync_rules(p, ifnames) { + return rule_cmds(p, current_rules(ifnames)); } function tunnel_ifnames() { @@ -455,9 +499,7 @@ export function remove(ifnames) { // Read while the link is there: the entry is ours when it carries the netns's MAC. let held = last?.dev ? used_addresses(last.dev)[last.address] : null; let stale = type(held) == 'string' && index([ last.mac, our_mac() ], held) >= 0; - let cmds = []; - for (let r in current_rules(ifnames)) - push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`); + let cmds = map(current_rules(ifnames), rule_del); if (last?.table) push(cmds, `ip -4 route flush table ${last.table}`); if (exists(TX_ROOT)) diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/meter.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/meter.uc new file mode 100644 index 0000000..29ae17d --- /dev/null +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/meter.uc @@ -0,0 +1,149 @@ +// Dawnline — the live meter (the Overview's Speed now): each server's +// throughput, one point a second over the last two minutes. +// +// The meter RPC (dawnline.rpc.status) calls want() and read(); the agent's +// watcher makes a point from every read it already does (sample(), point()) +// and keeps the last two minutes in memory (keep()) whether anyone looks or +// not, so a look gets them all at once. It writes them to FILE (save()) only +// while WANT is younger than WANT_FOR seconds: the first second of a look, +// then with each new point. When WANT goes stale it removes FILE: with nobody +// looking the watcher pays a little arithmetic and one stat() a second, and +// writes nothing. FILE holds server ids and byte rates only, no keys, names +// or personal codes. Who is online and the per-minute rates are not here +// (dawnline.live, the agent's tick). +// +// Bytes are the peers' counters (dawnline.awg.dump): tx includes the +// disguise (S prefixes, padding, junk), rx the packets as they were +// received without their prefix, so both are close to what is on the wire. + +import { writefile, stat, unlink } from 'fs'; +import { read_json, write_file, ensure_dir, RUN_DIR } from 'dawnline.util'; + +/** Touched by every meter RPC: the watcher samples while it is fresh. */ +export const WANT = `${RUN_DIR}/meter.want`; +/** The points, written by the watcher each second while WANT is fresh. */ +export const FILE = `${RUN_DIR}/meter.json`; +/** Seconds after the last meter RPC the watcher keeps sampling. */ +export const WANT_FOR = 10; +/** Points kept: two minutes, one a second. */ +export const POINTS = 120; + +/** Ask the watcher to sample for the next WANT_FOR seconds (the meter RPC). */ +export function want() { + ensure_dir(RUN_DIR); + writefile(WANT, `${time()}`); +}; + +/** Someone asked for the meter within WANT_FOR seconds of `now`. */ +export function wanted(now) { + let st = stat(WANT); + return st != null && now - st.mtime < WANT_FOR && st.mtime - now < WANT_FOR; +}; + +/** + * What the watcher wrote, for the RPC: { now, want: WANT_FOR, keep: POINTS, + * ts (newest point, 0 for none), points } with only the points newer than + * `since` when it is given (a page that polls asks for what it lacks). + * No points when nobody asked within WANT_FOR seconds or the agent is not + * running: FILE is gone (the agent removes it as it stops and starts), or, + * from one that died while someone looked, its newest point is over + * WANT_FOR seconds old (ts then stops moving). + */ +export function read(since) { + let f = read_json(FILE, null); + let ts = +(f?.ts ?? 0); + let pts = type(f?.points) == 'array' && time() - ts <= WANT_FOR ? f.points : []; + if (since > 0) + pts = filter(pts, (p) => p.ts > since); + return { now: time(), want: WANT_FOR, keep: POINTS, ts: ts, points: pts }; +}; + +/** Monotonic seconds, with the fraction: the gap between two samples. */ +function mono() { + let c = clock(true); + return c[0] + c[1] / 1e9; +} + +/** + * One sample at `now` from the dump the watcher just read (`d`): { t, ts, + * servers: [ server id ] (those whose tunnel was read), dev: { device id: + * [ rx, tx, server id ] } (its peer's counters, on those servers) }. Nothing + * but the dump is read. + */ +export function sample(m, d, now) { + let s = { t: mono(), ts: now, servers: [], dev: {} }; + let read = {}; + for (let sid, srv in m.servers) + if (d.reads[srv.ifname] == 'read') { + read[sid] = true; + push(s.servers, sid); + } + for (let id, dev in m.devices) { + let peer = d.peers[dev.public_key]; + let sid = m.people[dev.person]?.server; + if (peer && read[sid]) + s.dev[id] = [ peer.rx, peer.tx, sid ]; + } + return s; +}; + +/** A counter's change, 0 when it went down (a tunnel set up again starts from zero). */ +function delta(a, b) { + return (b ?? 0) >= (a ?? 0) ? (b ?? 0) - (a ?? 0) : 0; +} + +/** + * The point between samples `a` and `b`, null when they are not a second or + * so apart (the first sample, a stalled watcher): { ts, servers: { server + * id: [ rx, tx ] } }, bytes per second of its devices together (rx what came + * from them, tx what went to them, as a server's per-minute `rate`), for + * every server whose tunnel `b` read ([ 0, 0 ] when nothing moved). A device + * is counted from its second sample on, on the server it was on in both. + */ +export function point(a, b) { + let dt = b.t - a.t; + if (!(dt > 0.2 && dt < 5)) + return null; + let sum = {}; + for (let sid in b.servers) + sum[sid] = [ 0, 0 ]; + for (let id, v in b.dev) { + let o = a.dev[id]; + if (!o || o[2] != v[2]) + continue; + sum[v[2]][0] += delta(o[0], v[0]); + sum[v[2]][1] += delta(o[1], v[1]); + } + let p = { ts: b.ts, servers: {} }; + for (let sid, v in sum) + p.servers[sid] = [ int(v[0] / dt), int(v[1] / dt) ]; + return p; +}; + +/** + * Keep point `p` in `ring` ([ [ ts, the point as JSON ] ], newest last; each + * point is turned into text once, when it is made, not again every second for + * as long as it is kept): at most POINTS of them, none older than POINTS + * seconds before `p` (the watcher may have stalled in between) and none from + * its second or later (the clock went back). + */ +export function keep(ring, p) { + while (length(ring) && ring[length(ring) - 1][0] >= p.ts) + pop(ring); + push(ring, [ p.ts, sprintf('%J', p) ]); + while (length(ring) > POINTS || ring[0][0] <= p.ts - POINTS) + shift(ring); +}; + +/** Write the points kept in `ring` (keep()) to FILE. */ +export function save(ring) { + let ts = length(ring) ? ring[length(ring) - 1][0] : 0; + ensure_dir(RUN_DIR); + write_file(FILE, `{"ts":${ts},"points":[${join(',', map(ring, (r) => r[1]))}]}`, 0o644); +}; + +/** Nobody looks any more: FILE goes (the next look gets the points kept then). */ +export function stop() { + if (stat(FILE)) + unlink(FILE); +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc index fa056ee..caeb9da 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc @@ -4,6 +4,7 @@ // tunnel of your own, one from an imported config) is left alone and the // server is reported instead. Why a server is kept down is kept in // core.BLOCKED as a code with its values (awg.blocked_text says it). +// drift() tells the watchdog when one of them was edited outside Dawnline. import { cursor } from 'uci'; import { stat, unlink, writefile } from 'fs'; @@ -30,6 +31,14 @@ export function owner(ifname, c) { return c.get('network', ifname, '_dawnline') ?? ''; }; +/** What sync() writes into network. apart from the markers: what netifd sets the tunnel up from. */ +function options(srv) { + let o = awg.netifd_options(srv); + o.disabled = srv.enabled ? null : '1'; + o.auto = srv.enabled ? null : '0'; + return o; +} + /** Bring network config in line with the servers; true when it changed. */ export function sync(m) { let c = cursor(); @@ -70,13 +79,15 @@ export function sync(m) { 'Dawnline never changes interfaces it did not create. Choose another interface name for this server.'); continue; } + // Disguise values AmneziaWG refuses or crashes on (a hand edit in uci; + // import and restore refuse them) never reach setconf and the kernel. // A disguise this build cannot run (a 3.1 preset after a rollback to // 2.0): the kernel would drop those options silently and run a tunnel // no device can reach. Down, and said so, until the build or the // disguise is changed. - let why = tools ? awg.obf_unsupported(srv.obf) : null; + let why = !tools ? null : length(awg.obf_unsafe(srv.obf)) ? { code: 'disguise_invalid' } : awg.obf_unsupported(srv.obf); if (why) { - block(srv, why, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.'); + block(srv, why, awg.blocked_fix(why)); continue; } delete srv.blocked; @@ -85,17 +96,16 @@ export function sync(m) { continue; // Per server: with several, each changed one has to be brought up again. let mine = uci_section(c, 'network', ifn, 'interface'); - let set = (opt, val) => { - if (uci_put(c, 'network', ifn, opt, val)) + for (let k, v in options(srv)) + if (uci_put(c, 'network', ifn, k, v)) mine = true; - }; - for (let k, v in awg.netifd_options(srv)) - set(k, v); - set('disabled', srv.enabled ? null : '1'); - set('auto', srv.enabled ? null : '0'); - set('_dawnline', id); + // The markers are saved, but netifd does not read them: a renamed server + // keeps its tunnel and every session in it. + if (uci_put(c, 'network', ifn, '_dawnline', id)) + changed = true; // For the log once the server is gone. - set('_dawnline_name', srv.name); + if (uci_put(c, 'network', ifn, '_dawnline_name', srv.name)) + changed = true; if (mine) { changed = true; push(touched, ifn); @@ -125,6 +135,9 @@ export function sync(m) { if (changed) { c.commit('network'); ack_config([ 'network' ]); + } + // Only the markers changed: nothing for netifd to read (it ignores them, and so does a reload). + if (length(touched) || length(stale)) { system('ubus call network reload'); for (let ifn in touched) if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled) @@ -134,3 +147,29 @@ export function sync(m) { } return changed; }; + +/** + * For the watchdog: what of each running server's interface differs from + * what sync() writes, by option name (a LuCI or uci edit of network., + * which would otherwise last until the next apply): { server id: [ names ] }, + * an empty list when it is as Dawnline set it. Only enabled servers whose + * section exists and is theirs (a missing one is the tunnel probe's); the + * markers are not compared, netifd does not read them. A dry run on a + * cursor of its own: nothing is saved. Meaningful while amneziawg-tools is + * installed (sync() leaves the interfaces alone without it). + */ +export function drift(m) { + let c = cursor(); + c.load('network'); + let out = {}; + for (let id, srv in m.servers) { + if (!srv.enabled || !length(core.tunnels(srv)) || owner(srv.ifname, c) != id || c.get('network', srv.ifname) != 'interface') + continue; + let diff = []; + for (let k, v in options(srv)) + if (uci_put(c, 'network', srv.ifname, k, v)) + push(diff, k); + out[id] = diff; + } + return out; +}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc index 435bd35..9be782d 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc @@ -10,7 +10,8 @@ import * as core from 'dawnline.core'; import * as net from 'dawnline.net'; import * as loop from 'dawnline.loop'; -const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ]; +/** Private IPv4 ranges: internet people never reach them (awg.BYPASS4 is the rest). */ +export const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ]; /** The sets whose members change at run time (update replaces them together). */ const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ]; @@ -18,8 +19,11 @@ function ip4(a) { return ip2int(a ?? '') != null; } -/** Per-person runtime membership: which tunnel addresses may reach what. */ -export function access_sets(m, usage, states) { +/** + * Per-person runtime membership: which tunnel addresses may reach what. + * `snap` is the network (net.snapshot() when not given). + */ +export function access_sets(m, usage, states, snap) { // lan_ok: home access (the router itself, the mesh); lan_all: every home // network; lan_part: device . network for people limited to some networks; // mesh_pairs: device . device within a circle (or one person's own devices); @@ -27,7 +31,7 @@ export function access_sets(m, usage, states) { let sets = {}; for (let k in SETS) sets[k] = []; - let snap = net.snapshot(); + snap ??= net.snapshot(); let homes = {}, groups = {}; for (let id, d in m.devices) { let p = m.people[d.person]; @@ -91,13 +95,23 @@ function portal_ports(m) { return ports; } -function table(m, sets) { +/** + * What the table is made from besides the model, read from the router: the + * netns's DNS address (loop.client_dns), where the Home-only resolver runs + * (loop.resolver_target), the LAN's DNS and the network snapshot. + */ +function router_ctx() { + return { dns_addr: loop.client_dns(), resolver: loop.resolver_target(), lan_dns: loop.lan_dns(), snap: net.snapshot() }; +} + +function table(m, sets, ctx) { + ctx ??= router_ctx(); let ifs = [], tun = []; - let dns_addr = loop.client_dns(); + let dns_addr = ctx.dns_addr; if (!ip4(dns_addr)) dns_addr = null; - let rt = loop.resolver_target(); - let snap = net.snapshot(); + let rt = ctx.resolver; + let snap = ctx.snap; // Each server's home networks are its own: with several servers, "all // home" on one never reaches the other's networks (set lan_). let homes = {}; @@ -194,7 +208,7 @@ function table(m, sets) { push(t, ' }'); // Devices ask the tunnel address; send each query where it belongs. let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`; - let lan_dns = loop.lan_dns(); + let lan_dns = ctx.lan_dns; if (!ip4(lan_dns)) lan_dns = null; push(t, ' chain dns {'); @@ -228,9 +242,13 @@ export function load(script) { return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`; }; -/** The table as text, for a check (`nft -c -f`) or a test; nothing is loaded. */ -export function render(m, sets) { - return table(m, sets); +/** + * The table as text, for a check (`nft -c -f`) or a test; nothing is loaded. + * `ctx` (a test's) stands for what is read from the router: { dns_addr, + * resolver, lan_dns, snap } (router_ctx). + */ +export function render(m, sets, ctx) { + return table(m, sets, ctx); }; /** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */ diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc index a75d387..a1f6178 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc @@ -47,13 +47,28 @@ export function version(name) { return found ? trim(found[2]) : null; }; +/** + * The package a control text names: { name, version }, each null when it + * does not say. Pure: an ipk's control file (ipk true), else `apk adbdump` + * of an apk, whose first name and version are the package's own (its files + * are "- name:" entries further down). + */ +export function control_info(text, ipk) { + if (ipk) + return { name: match(text, /(^|\n)Package: *([^\n]+)/)?.[2], version: match(text, /(^|\n)Version: *([^\n]+)/)?.[2] }; + return { name: match(text, /\n *name: *([^\n]+)/)?.[1], version: match(text, /\n *version: *([^\n]+)/)?.[1] }; +}; + +/** The package inside a file: { name, version }, each null when the file does not say. */ +export function file_info(path) { + if (match(path, /\.ipk$/)) + return control_info(run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out, true); + return control_info(run(`apk adbdump ${q(path)}`).out, false); +}; + /** The version inside a package file, or null. */ export function file_version(path) { - if (match(path, /\.ipk$/)) { - let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out; - return match(o, /(^|\n)Version: *([^\n]+)/)?.[2]; - } - return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1]; + return file_info(path).version; }; /** @@ -105,22 +120,54 @@ function preflight(files, need_kb, log) { log?.(' ' + sprintf(_('%d MB free on the overlay'), int(free / 1024))); } -/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */ +/** Dawnline's own package: a file of it tells whether apk really reinstalled it. */ +const SELF = 'luci-app-dawnline', SELF_MARKER = '/usr/share/ucode/dawnline/util.uc'; + +/** + * The packages an apk install did not leave at their file's version: apk + * takes a given file as it is (an older version too, a rollback) but leaves + * an installed version alone, whatever the file. Pure: want [{ name, + * version, file }] from the files (file_info()), have { name: installed + * version }. [] when every package took. + */ +export function mismatched(want, have) { + return filter(want, (w) => w.name == null || w.version == null || have?.[w.name] != w.version); +}; + +/** + * Package files (from a release): true when every one is installed. force + * also reinstalls the same version or goes back to an older one (opkg; apk + * takes a file as it is: Dawnline's own package is checked by a file of it, + * any other by its installed version). + */ export function install_files(files, force, log) { preflight(files, 0, log); let args = join(' ', map(files, q)); if (!is_apk()) return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0; - // apk leaves an installed version alone, whatever the file: a reinstall - // that changed nothing is a failure, not a silent "done". - let marker = '/usr/share/ucode/dawnline/util.uc'; - let before = force ? stat(marker)?.mtime : null; - let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0; - if (ok && force && before != null && stat(marker)?.mtime == before) { - log?.(' ' + _('apk did not reinstall the version that is already installed')); - die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router")); + let want = map(files, (f) => ({ ...file_info(f), file: f })); + let own = length(filter(want, (w) => w.name == SELF)) > 0; + // Dawnline's own reinstall that changed nothing is a failure, not a silent "done". + let before = own && force ? stat(SELF_MARKER)?.mtime : null; + if (logged(`apk add --allow-untrusted ${args}`, log).code != 0) + return false; + if (own) { + if (force && before != null && stat(SELF_MARKER)?.mtime == before) { + log?.(' ' + _('apk did not reinstall the version that is already installed')); + die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router")); + } + return true; } - return ok; + // Any other package took when it is at its file's version (the same + // version again counts: apk keeps the installed one). + let have = {}; + for (let w in want) + if (w.name != null) + have[w.name] = version(w.name); + let bad = mismatched(want, have); + for (let w in bad) + log?.(' ' + sprintf(_('apk did not install %s %s (installed: %s)'), w.name ?? w.file, w.version ?? '?', have[w.name] ?? '-')); + return !length(bad); }; /** Packages by name from the feeds. */ 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 602596f..44fea14 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 @@ -3,7 +3,7 @@ // GET / the app shell // GET //assets/ its script, styles and fonts // GET //api/state -// POST //api/devices { name, kind, public_key? } +// POST //api/devices { name, kind, public_key?, lan_bypass? } // GET //api/devices//config // POST //api/devices/ { action: rename|rotate|delete, name? } // @@ -368,7 +368,8 @@ function tz_offset() { function state(r) { let m = r.m, person = r.person; let usage = core.load_usage(); - let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage)); + // Only their server's tunnel: one `awg` process per request, however many servers there are. + let v = view.person_view(m, person, usage, live.dump(m, person.server ?? ''), view.states(m, usage)); v.state = person_state(m, person, usage); // Day by day this month, for the page's chart (the admin's views have no use for it). v.month_days = view.month_days(usage.people?.[person.id]); @@ -384,6 +385,9 @@ function state(r) { awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false, // Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets. preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy', + // The home networks a device with LAN Bypass still sends into the tunnel (home and internet access): + // its own local network on the same addresses is out of reach (Add a device says so). + home: srv && person.access == 'both' ? core.person_home(srv, person).nets : [], }, can_add: length(person.devices) < person.device_limit, locked: index(LOCKED, v.state) >= 0, @@ -419,7 +423,8 @@ function api_add(r) { if (!devices.ready()) fail(r, '503 Service Unavailable', not_ready()); rate_action(r); - let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key })); + // lan_bypass: JSON true keeps the device's own local network out of the tunnel; anything else is off. + let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key, lan_bypass: b.lan_bypass === true })); reload(r); send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) }); } diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc index f726c05..77be170 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc @@ -56,7 +56,9 @@ function person_update(a) { let s = apply.sync(); let m = core.load(); let u = core.load_usage(); - return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning }; + // One person: only their server's tunnel is read. + let p = m.people[a.id]; + return { person: view.person_view(m, p, u, live.dump(m, p.server ?? ''), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning }; } function person_pause(a) { @@ -138,20 +140,28 @@ function person_usage(a) { function device_create(a) { devices.need_awg(); - return devices.add(a.person, a.name, a.kind, { by: 'admin' }); + return devices.add(a.person, a.name, a.kind, { by: 'admin', lan_bypass: a.lan_bypass === true }); } +/** + * A device's configuration. Only `issue` (true: the admin shows its QR code, + * downloads or copies it) counts as handing it out; a look at the device + * marks nothing, so its "settings changed" stays until it really gets them. + */ function device_config(a) { let m = core.load(); let d = m.devices[a.id]; if (!d) die(_('Unknown device.')); - awg.mark_issued(m, d.id); + if (a.issue === true) + awg.mark_issued(m, d.id); return awg.client_config(m, d); } +/** Name, on/off and the link values (mtu, keepalive: strings, '' = the server's; lan_bypass: true or false). */ function device_update(a) { - return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' }); + return devices.update(a.id, { name: a.name, disabled: a.disabled, mtu: a.mtu, keepalive: a.keepalive, + lan_bypass: a.lan_bypass == null ? null : a.lan_bypass === true }, { by: 'admin' }); } export const methods = { @@ -169,9 +179,10 @@ export const methods = { person_links: { args: { id: '' }, call: wrap(person_links) }, person_delete: { args: { id: '' }, call: wrap(person_delete) }, person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) }, - device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) }, - device_config: { args: { id: '' }, call: wrap(device_config) }, - device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) }, + device_create: { args: { person: '', name: '', kind: '', lan_bypass: false }, call: wrap(device_create) }, + device_config: { args: { id: '', issue: false }, call: wrap(device_config) }, + device_update: { args: { id: '', name: '', disabled: false, mtu: '', keepalive: '', lan_bypass: false }, call: wrap(device_update) }, device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) }, - device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(a.id, { by: 'admin' })) }, + // New keys: the device is set up again, as with the portal's Reconnect. + device_rotate: { args: { id: '' }, call: wrap((a) => devices.reconnect(a.id, { by: 'admin' })) }, }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc index 027d82e..fadd2dc 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc @@ -596,6 +596,10 @@ function server_ports(a) { function server_obfuscation(a) { let preset = str(a.preset) || default_method(); let o = awg.obf_preset(check_method(preset)); + // A cheap self-check: new values pass what a restore would be held to. + let errs = awg.obf_errors(o); + if (length(errs)) + die(join(' ', errs)); let srv = store.transact((c, m) => { let srv = m.servers[a.id]; if (!srv) diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/status.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/status.uc index 2aa0098..75ec1d0 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/status.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/status.uc @@ -1,5 +1,6 @@ // Dawnline rpcd methods: the live revision, the Overview status (servers, -// people, totals, map, recent activity), the activity log and traffic history. +// people, totals, map, recent activity), the live meter, the activity log and +// traffic history. import { readfile } from 'fs'; import { _ } from 'dawnline.i18n'; @@ -13,6 +14,7 @@ import * as loop from 'dawnline.loop'; import * as awg from 'dawnline.awg'; import * as lookup from 'dawnline.lookup'; import * as health from 'dawnline.health'; +import * as meter from 'dawnline.meter'; import { wrap, str, clamp_days } from 'dawnline.rpc.common'; /** The router's public IPv4 (null when none or private). */ @@ -127,7 +129,8 @@ function server_view(m, srv, usage, dmp, rates, days) { blocked: awg.blocked_text(srv), // Home networks (interfaces) for the per-person picker. home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })), - peers, online, obf: srv.obf, + // The header protection key is a secret every device shares: whether there is one. + peers, online, obf: awg.obf_public(srv.obf), hpk: !!srv.obf.header_protection_key, // Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices). rate: rates[srv.id] ?? [], // Daily traffic of the people on this server (its Overview chart). @@ -137,7 +140,8 @@ function server_view(m, srv, usage, dmp, rates, days) { /* * Everything the pages show at once. Readable by read-only users: no personal - * codes or links here (person_links has them). + * codes or links here (person_links has them), and no keys but public ones + * (device_config has the rest). */ function status(a) { let m = core.load(); @@ -282,8 +286,21 @@ function rev() { return { rev: +(live.presence()?.rev ?? 0), version: VERSION }; } +/* + * The live meter (Overview): each call keeps the agent's watcher writing out + * the points it keeps for meter.WANT_FOR seconds more (a first call finds + * none yet: the watcher writes the last two minutes within a second) and + * returns them (dawnline.meter.read), those newer than `since` when given. Read-only users may look: server ids + * and bytes per second only, no keys or personal codes. + */ +function meter_points(a) { + meter.want(); + return meter.read(+a.since || 0); +} + export const methods = { rev: { call: wrap(rev) }, + meter: { args: { since: 0 }, call: wrap(meter_points) }, status: { args: { days: 30 }, call: wrap(status) }, events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) }, logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) }, diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc index 67ae5a9..cfcf877 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc @@ -1,6 +1,8 @@ // Dawnline updater: AmneziaWG — the builds published for this firmware by // each source, installing or switching a build (verified against GitHub's // sha256), the Russian LuCI translation, and rolling back to a kept build. +// Every install and rollback is recorded (dawnline.awg_builds), with whether +// the new kernel module runs or waits for the next boot. // ctx is the updater's job context (see usr/libexec/dawnline/updater). import { stat } from 'fs'; @@ -89,6 +91,8 @@ export function check(ctx) { current = id; let mine = current ? sources[current] : null; let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null; + // An update that waits for a reboot: Components says so after a check. + let pending = builds.waits_for_reboot(); let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest'; ctx.log(cur == null ? _('AmneziaWG is not installed') : !current ? sprintf(_('AmneziaWG %s: no source publishes this build for this firmware any more'), cur) @@ -99,13 +103,19 @@ export function check(ctx) { update: cur == null || st == 'outdated', // An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic. gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version), - note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1)) : null }; + pending, + note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1)) + : pending ? _('The AmneziaWG update is installed and starts after a reboot.') : null }; }; -/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */ -function reload_module(ctx, before, after) { - if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg']) - return; +/** + * Tunnels on a new kernel module: every AmneziaWG interface is brought down, + * the module swapped and the interfaces brought up again. False when the old + * module stays loaded: the tunnels come back on it (the tools talk to an + * older module at its own netlink version) and the installed one starts + * with the next boot, which caps() and Health then wait for. + */ +function reload_module(ctx) { let ifaces = []; let c = cursor(); c.load('network'); @@ -119,33 +129,58 @@ function reload_module(ctx, before, after) { iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i); sh(`ifdown '${i}'`); } - // Both steps must really happen: the new tools against the old module (or - // no module at all) leave every tunnel down while the job says "done". - ctx.run('rmmod amneziawg'); if (stat('/sys/module/amneziawg')) - die(_('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update')); - ctx.run('modprobe amneziawg'); - if (!stat('/sys/module/amneziawg')) - die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)")); + ctx.run('rmmod amneziawg'); + let swapped = !stat('/sys/module/amneziawg'); + if (swapped) { + ctx.run('modprobe amneziawg'); + if (!stat('/sys/module/amneziawg')) + die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)")); + } for (let i in ifaces) sh(`ifup '${i}'`); + return swapped; } -/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */ -function settle(ctx, before, after) { - if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) { +/** + * After packages changed: the module loaded, netifd knowing the protocol, + * Dawnline set up again. was: the module loaded before (builds.module_now()). + * Returns whether the module that runs is the installed one; false while the + * old one stays loaded until the next boot. + */ +function settle(ctx, before, after, was) { + let b = before['kmod-amneziawg'], a = after['kmod-amneziawg']; + let fresh = true; + // A new module package, one over a module loaded by hand, or an earlier + // update that still waits for a boot (Reinstall tries again). + if (a && (a != b || was.pending) && (b || was.core != null)) + fresh = reload_module(ctx); + else if (a && !b) { ctx.phase(_('Loading the kernel module')); if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg')) die(_("AmneziaWG is installed, but its kernel module doesn't load on this firmware")); } - else - reload_module(ctx, before, after); // netifd reads its protocol handlers when it starts. if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) { ctx.phase(_('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)')); ctx.run('/etc/init.d/network restart'); } ctx.after('apply'); + return fresh; +} + +/** + * The packages are in: settle them and record the build (source, tag) with + * the module that ran before (was). An old module that stays loaded is no + * failure: the job says so, and Health until the next boot. + */ +function finish(ctx, out, source, tag, was) { + out.after = builds.installed(); + out.reloaded = settle(ctx, out.before, out.after, was); + builds.record(source, tag, out.after, { prev_gen: was.gen, prev_core: was.core, reloaded: out.reloaded }); + if (!out.reloaded) + ctx.log(_('The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot.')); + return out; } /** The first source that publishes every package for this firmware. */ @@ -165,6 +200,7 @@ function pick(fw) { /** arg: [auto|slava|grey][:ru] | rollback */ export function install(ctx, arg) { let before = builds.installed(); + let was = builds.module_now(before['kmod-amneziawg']); let out = { from: before['amneziawg-tools'], to: null, before }; let fw = builds.firmware(); if (!fw) @@ -182,9 +218,7 @@ export function install(ctx, arg) { if (!pkg.install_files(k.files, true, ctx.log)) die(_('Package installation failed')); upd.forget('amneziawg'); - out.after = builds.installed(); - settle(ctx, before, out.after); - return out; + return finish(ctx, out, k.build, fw.tag, was); } let parts = split(arg ?? '', ':'); let id = parts[0] || 'auto'; @@ -236,8 +270,5 @@ export function install(ctx, arg) { die(_('Package installation failed')); if (!want_ru && pkg.version(builds.RU)) pkg.remove([ builds.RU ], ctx.log); - out.after = builds.installed(); - settle(ctx, before, out.after); - builds.record(id, fw.tag, out.after); - return out; + return finish(ctx, out, id, fw.tag, was); }; 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 fce329e..5805cf9 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 @@ -5,7 +5,7 @@ import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs'; import { _ } from 'dawnline.i18n'; -export const VERSION = '0.13.0'; +export const VERSION = '0.14.0'; /** GitHub repository with Dawnline releases (updates and the installer). */ export const REPO = 'tickcount/luci-app-dawnline'; export const RUN_DIR = '/var/run/dawnline'; @@ -561,6 +561,76 @@ export function name_rule() { // with one fails these checks (a regex looks only up to it). const ASCII_ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const B64 = `${ASCII_ALNUM}+/`; + +/** + * The longest name a device takes, in characters: ordinary words fill a portal card's line about as far as its + * status ("Return to save, Esc to cancel"), and fit the server list in the AmneziaVPN app. Names set before the rule stay as they are; it holds when a name is set. + */ +export const DEVICE_NAME_MAX = 20; +// What a device's name may hold of ASCII: letters, digits, spaces and - _ . It goes into configurations, file +// names and the AmneziaVPN key: nothing there to escape. +const DEVICE_NAME_CHARS = `${ASCII_ALNUM} ._-`; +// Past ASCII, letters of any language are welcome; these blocks are not: symbols, punctuation, arrows, maths, +// emoji and invisibles (code point ranges, both ends in; web/src/shared/format.ts NAME_SYMBOLS is the same list, +// and the page asks Unicode besides that a character is a letter or a digit). +const NAME_SYMBOLS = [ + [ 0x80, 0xbf ], [ 0xd7, 0xd7 ], [ 0xf7, 0xf7 ], [ 0x2000, 0x2bff ], [ 0x3000, 0x303f ], [ 0xd800, 0xf8ff ], + [ 0xfe00, 0xfe0f ], [ 0xfe30, 0xfe4f ], [ 0xfeff, 0xfeff ], [ 0xfff0, 0xffff ], [ 0x1f000, 0x1fbff ], + [ 0xe0000, 0xe007f ] +]; + +function name_symbol(cp) { + for (let r in NAME_SYMBOLS) + if (cp >= r[0] && cp <= r[1]) + return true; + return false; +} + +/** + * A device's name (trimmed by the caller): 1-DEVICE_NAME_MAX characters, not blank, each one of + * DEVICE_NAME_CHARS or past ASCII outside NAME_SYMBOLS. Read by code points: broken UTF-8, and an + * ASCII character spelled long (0xC0 0xAF for "/"), are refused. + */ +export function valid_device_name(s) { + if (type(s) != 'string' || length(trim(s)) == 0 || ulength(s) > DEVICE_NAME_MAX) + return false; + let i = 0, n = length(s); + while (i < n) { + let b = ord(s, i), cp, len; + if (b < 0x80) { + if (index(DEVICE_NAME_CHARS, substr(s, i, 1)) < 0) + return false; + i++; + continue; + } + if ((b & 0xe0) == 0xc0) { + len = 2; + cp = b & 0x1f; + } + else if ((b & 0xf0) == 0xe0) { + len = 3; + cp = b & 0x0f; + } + else if ((b & 0xf8) == 0xf0) { + len = 4; + cp = b & 0x07; + } + else + return false; + if (i + len > n) + return false; + for (let k = 1; k < len; k++) { + let c = ord(s, i + k); + if ((c & 0xc0) != 0x80) + return false; + cp = (cp << 6) | (c & 0x3f); + } + if (cp < 0xc0 || cp > 0x10ffff || name_symbol(cp)) + return false; + i += len; + } + return true; +}; // 32 bytes are 43 base64 characters: the last holds four bits of the key and two zero bits. const KEY_LAST = 'AEIMQUYcgkosw048'; @@ -568,7 +638,7 @@ const KEY_LAST = 'AEIMQUYcgkosw048'; * A (Amnezia)WireGuard key: 32 bytes in base64, 43 characters and "=", the * same as /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/ without its 1.7 ms * compile on the WR3000P: the agent's watcher checks two keys per line of - * `awg show all dump` every second. This takes about 0.03 ms. + * `awg show dump` every second. This takes about 0.03 ms. */ export function valid_key(s) { return type(s) == 'string' && length(s) == 44 && substr(s, 43) == '=' && 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 e97b87f..5e8d29c 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 @@ -58,6 +58,7 @@ export function device_view(m, d, usage, dmp) { m._reconnect ??= awg.reconnects(); let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]); let p = m.people[d.person]; + let srv = m.servers[p?.server]; // The same label /tmp/hosts carries (core.device_labels), so what is shown resolves. let label = ''; if (m.settings.hostnames && p) { @@ -65,6 +66,7 @@ export function device_view(m, d, usage, dmp) { m._labels[p.id] ??= core.device_labels(m, p); label = m._labels[p.id][d.id] ?? 'device'; } + let online = hs > 0 && live.online(dmp, d.id, peer); let v = { id: d.id, name: d.name, @@ -73,7 +75,7 @@ export function device_view(m, d, usage, dmp) { disabled: d.disabled, created: d.created, created_by: d.created_by, - online: hs > 0 && live.online(dmp, d.id, peer), + online, handshake: hs, endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '', active: !!peer, @@ -84,6 +86,21 @@ export function device_view(m, d, usage, dmp) { browser_key: d.private_key == '', // Its configuration changed since it was last shown or downloaded. config_stale: config_stale(m, d), + // How it connects: its own local network outside the tunnel, its own MTU + // and keep-alive (0 / null: the server's) and what its configuration carries. + lan_bypass: d.lan_bypass, + mtu: d.mtu, + keepalive: d.keepalive, + mtu_used: srv ? core.device_mtu(srv, d) : null, + keepalive_used: srv ? core.device_keepalive(srv, d) : null, + // Its link failing in a named way, as the agent's watcher shows it + // (dawnline.link): { state, since }, or null. + link: dmp.link?.[d.id] ?? null, + // What its link does right now, for the set-up sheet (dawnline.link + // setup_state): { state: 'trying' | 'flowing' | 'nodata', since }, or null. + // Without the agent nobody tells data from a bare handshake: a session + // that lives counts as data flowing, so the sheet still sees it arrive. + setup: dmp.setup != null ? (dmp.setup[d.id] ?? null) : online ? { state: 'flowing', since: hs } : null, }; return v; }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc index 30a160e..5c88706 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc @@ -44,7 +44,23 @@ function restart_services() { function probes(m) { let out = []; // The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface. - push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) })); + let tunnels = awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }); + push(out, ...tunnels); + // A tunnel's interface edited outside Dawnline (LuCI, uci) keeps that until + // the next apply: set up again with Dawnline's settings. Only while + // AmneziaWG itself works (its target comes first, and is fixed first). + if (filter(tunnels, (p) => p.id == 'awg')[0]?.ok) + for (let id, diff in netifd.drift(m)) { + let srv = m.servers[id]; + push(out, { + id: `cfg_${id}`, src: 'awg', name: `${srv.name} · interface settings`, who: srv.name, ok: !length(diff), + problem: sprintf(L_('interface %s was changed outside Dawnline'), srv.ifname), + back: sprintf(L_("interface %s has Dawnline's settings again"), srv.ifname), + // Option names only: their values hold the server's private key. + detail: () => sprintf(L_('Changed: %s.'), join(', ', diff)), + repair: { what: L_('setting it up again'), run: () => apply.apply() }, + }); + } if (length(m.servers)) push(out, { id: 'nft', src: 'dawnline', name: 'Access rules', who: L_('Access rules'), ok: nft.present(), @@ -184,6 +200,14 @@ function names() { }; } +/** A target's chip name in the language of the call: names(), a server's interface settings, else as stored. */ +function chip_name(m, n, id, stored) { + if (n[id]) + return n[id]; + let srv = substr(id, 0, 4) == 'cfg_' ? m.servers[substr(id, 4)] : null; + return srv ? sprintf(_('%s · interface settings'), srv.name) : stored; +} + /** * For the Health page: the watchdog's state and the newest log entries. Target * and repair names in the language of the call; the log as it was written. @@ -195,11 +219,11 @@ export function view(m) { // The agent itself: fine while it ticks (cron restarts it after 5 minutes without). let targets = [ { id: 'agent', name: n.agent, ok: beat > 0 && time() - beat < 180, tries: 0 } ]; for (let id, x in (type(st.targets) == 'object' ? st.targets : {})) - push(targets, { id, name: n[id] ?? x.name, ok: !!x.ok, tries: x.tries ?? 0 }); + push(targets, { id, name: chip_name(m, n, id, x.name), ok: !!x.ok, tries: x.tries ?? 0 }); return { watchdog: { enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(), - targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: n[r.id] ?? r.name })), + targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: chip_name(m, n, r.id, r.name) })), }, log: slog_read(200), }; diff --git a/rules/backend.md b/rules/backend.md index 18733ed..a7826e3 100644 --- a/rules/backend.md +++ b/rules/backend.md @@ -7,7 +7,7 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort - `util`, `schema` (validation) → `core` (model, allocation) → `store` (the only writer of `/etc/config/dawnline`) → domain modules (`net`, `nft`, `fw`, `netifd`, `awg`, `loop`, `resolver`, `live`, `health`, `backup`, …) → `apply` (reconciliation) → entry points (`rpc/*`, `portal`, the `dawnline` CLI, the agent, the updater). - Read models for the UI live in `view`; RPC modules translate arguments and call down, they hold no business logic. - The updater is a thin dispatcher over `upd_app` / `upd_awg` / `upd_pkgs`, with GitHub in `github`, the package manager in `pkg`, policy/locks/history in `updates`. -- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.ONLINE_WINDOW`): traffic silence is no signal, a phone asleep is silent too. +- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.online_window()`: 190 s, longer for a device with a long keep-alive): traffic silence is no signal, a phone asleep is silent too. A device's link trouble (trying, shared, dropped, unstable) is the watcher's too (`dawnline.link`, `live.LINK`). ## ucode @@ -21,9 +21,9 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort ## Cost on the router -- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action. +- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action. A person's answers read only their server's tunnel (`live.dump(m, sid)`: one `awg` process, however many servers). - **rpcd keeps the admin backend loaded:** LuCI RPC calls are cheap, so the admin UI may poll small methods often (`rev`), and the heavy ones (`status`) only on change or rarely. -- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show all dump` (about 4 ms with process start, 1 ms to parse), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition. +- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show dump` per Dawnline tunnel, never `all` (another AmneziaWG interface's peers are not Dawnline's; about 4 ms with process start, 1 ms to parse), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition. - **A regex literal is compiled every time it runs:** ucode calls regcomp for `/…/` each time the expression is evaluated, and musl's regcomp grows with the pattern. Bounded repeats are copied out (`{42}` about 1.7 ms on the WR3000P, `[A-Za-z0-9_.@-]{1,32}` 3 ms, two `{0,61}` 10 ms), alternations and classes add up (`/^(PrivateKey|Jc|Jmin|Jmax) /` 0.11 ms, `/^[0-9]+$/` 0.02 ms); matching a compiled regex takes 0.01–0.1 ms. In a loop or on a hot path, hoist the regex into a module `const` (compiled once, when the module loads — every portal request pays that too) or check with `length`/`substr`/`ltrim` (`util.valid_key`, `valid_host`, `valid_iface`). - Measure before and after on the router (a loop of 20–200 calls, `/proc/self/stat` CPU ticks, system busy from `/proc/stat`) when adding anything periodic. diff --git a/rules/i18n.md b/rules/i18n.md index b16557d..cb86188 100644 --- a/rules/i18n.md +++ b/rules/i18n.md @@ -63,6 +63,7 @@ Write like a careful Russian product (Telegram, Яндекс), not a word-for-wo | home network | домашняя сеть | | internet | интернет | | home network + internet | домашняя сеть и интернет | +| LAN Bypass (a device's option) | обход локальной сети («Обход локальной сети») | | portal, personal link, personal page | портал, личная ссылка, личная страница | | invite (card) | приглашение (карточка приглашения) | | disguise; Off / Balanced / Maximum | маскировка; Выкл. / Сбалансированная / Максимальная | diff --git a/scripts/capture-portal.mjs b/scripts/capture-portal.mjs new file mode 100755 index 0000000..4b1e761 --- /dev/null +++ b/scripts/capture-portal.mjs @@ -0,0 +1,261 @@ +#!/usr/bin/env node +// Capture the raw README screenshots of the personal portal into +// docs/screenshots/raw/ (2x PNG): the page (portal.png) and the three steps of +// adding a phone in front of it (portal-add-1..3.png: Add a device, the set-up +// sheet waiting, the phone connected), each sheet alone on a transparent page. +// The Russian ones take a -ru suffix. scripts/frame-screenshots.py then frames +// them for the README. +// +// The portal is its demo build (web/dist/demo, `npm run build:demo`, built +// first unless --no-build): the real portal over a router that lives in the +// page, so no one's real page is shown and adding a device adds none. It is +// opened as https://vpn.example.com/ and every file is answered from the +// build over the DevTools protocol (scripts/cdp.mjs), so its personal link +// reads like one. The cast is made up here: the demo's own three devices (the +// ones its router keeps, so adding one works) under other names, three more +// shown beside them, and the person's and the server's names. +// +// scripts/capture-portal.mjs [--lang en,ru] [--no-build] + +import { execFileSync } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { dirname, extname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { die, launch, sleep } from './cdp.mjs'; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const WEB = join(ROOT, 'web'); +const DEMO = join(WEB, 'dist', 'demo'); +const RAW = join(ROOT, 'docs', 'screenshots', 'raw'); +const SCALE = 2; +/** The page's width, as the README shot always had it. */ +const WIDTH = 1320; +/** Around a sheet in its capture: left, top, right, bottom (frame-screenshots.py FLOW_MARGIN). */ +const MARGIN = [56, 40, 56, 72]; +const ORIGIN = 'https://vpn.example.com'; +/** The demo's personal link (web/src/portal/demo/index.html, data-base). */ +const CODE = 'kelino-sarupa-motive'; +const NAMES = { person: 'Aemeath', server: 'Ames Gateway' }; +/** The device this page is open on (its card says "This device"). */ +const HERE = 'MacBook Air'; +/** The phone added in the steps. */ +const NEW = 'Pixel 9'; +const SLOTS = 8; + +const args = { langs: ['en', 'ru'], build: true }; +for (let i = 2; i < process.argv.length; i++) { + const a = process.argv[i]; + if (a === '--lang') args.langs = (process.argv[++i] ?? die('--lang needs a value')).split(','); + else if (a === '--no-build') args.build = false; + else die(`unknown argument ${a}`); +} + +const DAY = 86400; +const now = () => Math.floor(Date.now() / 1000); + +/** + * What the demo's router keeps (its DemoDb, in localStorage before the page loads): three devices, so one more + * fits its limit of four and the steps add it for real. + */ +function demoDb(t) { + const dev = (id, name, kind, n, gb, hs, days) => ({ + id, + name, + kind, + n, + gb, + hs, + connectAt: 0, + created: t - days * DAY, + by: 'admin', + stale: false, + }); + return { + scenario: 'normal', + devs: [ + dev('d_mac', HERE, 'computer', 2, 5.4, t - 20, 60), + dev('d_iph', 'iPhone 16', 'phone', 3, 2.3, t - 40, 58), + dev('d_gal', 'Galaxy S24', 'phone', 4, 0.66, t - 26 * 3600, 30), + ], + next: 5, + }; +} + +/** + * The page's side, before it loads: the language, the router's devices, the demo's own chrome hidden, and every + * answer of its router touched on the way to the page (the names, this device, the slots, the devices shown + * beside the ones it keeps). + */ +const prelude = (lang, db) => `(() => { + try { + localStorage.setItem('dl.lang', ${JSON.stringify(lang)}); + localStorage.setItem('dawnline-demo', ${JSON.stringify(JSON.stringify(db))}); + } catch {} + const NAMES = ${JSON.stringify(NAMES)}, HERE = ${JSON.stringify(HERE)}, SLOTS = ${SLOTS}; + const extra = (devs, t) => { + const like = (d, o) => ({ ...d, link: null, setup: null, online: false, config_stale: false, created_by: 'admin', ...o }); + const mac = devs.find((d) => d.name === HERE) ?? devs[0]; + const none = { handshake: 0, endpoint: '', month: [0, 0], total: [0, 0], spark: mac.spark.map(() => [0, 0]) }; + const scale = (p, f) => p.map((v) => Math.round(v * f)); + return [ + like(mac, { id: 'x_tv', name: 'Living room TV', kind: 'other', address: '10.8.0.6', handshake: t - 3 * 3600, + config_stale: true, month: scale(mac.month, 1.13), total: scale(mac.total, 1.4), + spark: mac.spark.map((p) => scale(p, 1.1)), created: t - 45 * 86400 }), + like(mac, { id: 'x_ipad', name: 'iPad', kind: 'tablet', address: '10.8.0.7', created: t - 2 * 86400, ...none }), + like(mac, { id: 'x_rtr', name: 'Cottage router', kind: 'router', address: '10.8.0.8', created: t - 86400, ...none }), + ]; + }; + const touch = (st) => { + if (!st?.person) return; + const own = st.person.devices; + st.person.name = NAMES.person; + if (st.server) st.server.name = NAMES.server; + st.person.devices = [...own, ...extra(own, st.now)]; + st.person.device_limit = SLOTS; + st.can_add = st.person.devices.length < SLOTS; + st.here = own.find((d) => d.name === HERE)?.id ?? null; + }; + let inner = window.fetch; + Object.defineProperty(window, 'fetch', { + configurable: true, + get: () => inner, + // The demo's router takes fetch over (demo/serve.ts): its answers pass through here. + set: (f) => { + inner = async (...a) => { + const r = await f(...a); + if (!String(a[0] instanceof Request ? a[0].url : a[0]).includes('/api/')) return r; + let j; + try { j = await r.clone().json(); } catch { return r; } + touch(j?.person ? j : j?.state); + return new Response(JSON.stringify(j), { status: r.status, headers: { 'content-type': 'application/json' } }); + }; + }, + }); + addEventListener('DOMContentLoaded', () => { + const s = document.createElement('style'); + // The demo's chip and GitHub pill go, and the path takes the row again, as on a router's page. + s.textContent = '.dm-chip, .dm-gh { display: none !important; } .cr-path { flex: 1 !important; }'; + document.head.append(s); + }); +})()`; + +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.woff2': 'font/woff2' }; + +/** Answer the page's requests from the demo build: its page for the personal link, its files by name. */ +async function serve(page) { + page.on('Fetch.requestPaused', async (e) => { + const path = new URL(e.request.url).pathname; + const file = path === `/${CODE}` || path === '/' ? 'index.html' : path.slice(1); + let body; + try { + body = readFileSync(join(DEMO, file)); + } catch { + await page.send('Fetch.fulfillRequest', { requestId: e.requestId, responseCode: 404, body: '' }).catch(() => {}); + return; + } + await page.send('Fetch.fulfillRequest', { + requestId: e.requestId, + responseCode: 200, + responseHeaders: [{ name: 'Content-Type', value: TYPES[extname(file)] ?? 'application/octet-stream' }], + body: body.toString('base64'), + }); + }); + await page.send('Fetch.enable', { patterns: [{ urlPattern: `${ORIGIN}/*`, requestStage: 'Request' }] }); +} + +async function shoot(page, file, clip) { + const { data } = await page.send('Page.captureScreenshot', { + format: 'png', + clip: { ...clip, scale: 1 }, + captureBeyondViewport: true, + }); + writeFileSync(join(RAW, file), Buffer.from(data, 'base64')); + console.log(`${file}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`); +} + +// The page's content: everything on screen but full-width or full-height wrappers, 36px around it (as the +// README shot always was; what waits off screen, as a field's measuring copy does, is no content). +const PAGE_CLIP = `(() => { + let l = innerWidth, r = 0, b = 0; + for (const e of document.querySelectorAll('#app *')) { + const x = e.getBoundingClientRect(); + if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue; + if (x.left < 0 || x.right > innerWidth) continue; + l = Math.min(l, x.left); + r = Math.max(r, x.right); + b = Math.max(b, x.bottom); + } + return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 }; +})()`; + +// The open sheet alone: the page and the scrim out of sight on a transparent page, MARGIN around the sheet. +const SHEET_CLIP = `(() => { + const r = document.querySelector('.sheet-root.open .sheet').getBoundingClientRect(); + const [l, t, rr, b] = ${JSON.stringify(MARGIN)}; + return { x: r.left - l, y: r.top - t, width: r.width + l + rr, height: r.height + t + b }; +})()`; +const ALONE = `(() => { + const s = document.createElement('style'); + s.id = 'alone'; + s.textContent = 'html, body { background: transparent !important; } #app { visibility: hidden !important; } .scrim { display: none !important; }'; + document.head.append(s); +})()`; + +async function capture(lang) { + const suffix = lang === 'en' ? '' : `-${lang}`; + const b = await launch([`--lang=${lang}`]); + const { page, evaluate, go, waitSel } = b; + try { + await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] }); + await page.send('Emulation.setDeviceMetricsOverride', { width: WIDTH, height: 1400, deviceScaleFactor: SCALE, mobile: false }); + // Where the page paints nothing (a sheet alone), the capture is transparent. + await page.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } }); + await serve(page); + await page.send('Page.addScriptToEvaluateOnNewDocument', { source: prelude(lang, demoDb(now())) }); + await go(`${ORIGIN}/${CODE}`); + await waitSel('.dev[data-id]'); + await sleep(2500); + await shoot(page, `portal${suffix}.png`, await evaluate(PAGE_CLIP)); + + // 1: Add a device, a phone, its name typed in. + await evaluate(`document.querySelector('.dev.add').click()`); + await waitSel('.sheet-root.open .kinds'); + await sleep(900); + await evaluate(`document.querySelectorAll('.sheet-root.open .kind')[1].click()`); + await sleep(500); + await evaluate(`(() => { const i = document.querySelector('.sheet-root.open .field input'); i.focus(); i.select(); })()`); + await page.send('Input.insertText', { text: NEW }); + await evaluate(`document.activeElement.blur()`); + await sleep(900); + await evaluate(ALONE); + await shoot(page, `portal-add-1${suffix}.png`, await evaluate(SHEET_CLIP)); + await evaluate(`document.getElementById('alone').remove()`); + + // 2: the set-up sheet, waiting for the phone, its link open as a code for the phone's camera (the page + // opens on the app's row, whose code a key makes too dense to read at this size). + await evaluate(`document.querySelector('.sheet-root.open .field .go').click()`); + await waitSel('.sheet-root.open .way'); + await sleep(1200); + await evaluate(`document.querySelector('.sheet-root.open .acc-row:not(.open) .acc-head').click()`); + await sleep(1500); + await evaluate(ALONE); + await shoot(page, `portal-add-2${suffix}.png`, await evaluate(SHEET_CLIP)); + await evaluate(`document.getElementById('alone').remove()`); + + // 3: connected (the demo's phone does within 6-9 s), what was under the way folded away. + await waitSel('.sheet-root.open .way.done', 15000); + await sleep(1150); + await evaluate(ALONE); + await shoot(page, `portal-add-3${suffix}.png`, await evaluate(SHEET_CLIP)); + page.close(); + } finally { + await b.close(); + } +} + +async function main() { + if (args.build) execFileSync('npm', ['run', '--silent', 'build:demo'], { cwd: WEB, stdio: 'inherit' }); + for (const lang of args.langs) await capture(lang); +} + +main().catch((e) => die(e.message)); diff --git a/scripts/capture-screenshots.mjs b/scripts/capture-screenshots.mjs index a217797..508b0c6 100755 --- a/scripts/capture-screenshots.mjs +++ b/scripts/capture-screenshots.mjs @@ -1,29 +1,33 @@ #!/usr/bin/env node -// Capture the raw README screenshots from a live router into +// Capture the raw README screenshots of the admin pages from a live router into // docs/screenshots/raw/.png (2x PNG); scripts/frame-screenshots.py then -// puts them into a browser window for the README. +// frames them for the README. The portal's come from its demo instead +// (scripts/capture-portal.mjs): no one's real page, and adding a device there adds none. // // Drives a headless Chromium (BROWSER=/path/to/chrome, default: Brave or Chrome -// on macOS) over the DevTools protocol, no npm packages. Signs in to LuCI with +// on macOS) over the DevTools protocol (scripts/cdp.mjs). Signs in to LuCI with // the password from LUCI_PASSWORD or asked on the terminal; the session lives // only in a throwaway profile (LUCI_USER picks another user than root). Nothing on the router is changed. // // scripts/capture-screenshots.mjs [--router https://router.lan] [--person id] // [--mask real=shown ...] [--name real=shown ...] -// [--only overview,people] [--demo] +// [--only overview,people] [--demo] [--lang ru] // +// --lang asks LuCI for the pages in that language (its catalog, po//dawnline.po; +// the router's LuCI language left on auto) and names the captures -.png +// for that README (README_ru.md); English (the default) keeps .png. // --mask replaces text on every page before the capture (a domain, a name); // --name does the same for a person's name in any case, and for their initials. // Public IPv4 addresses are always swapped for documentation ones (203.0.113.x). // --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs): // the router's answers are rewritten in the headless browser on their way to the page. -import { execFileSync, spawn } from 'node:child_process'; -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; +import { execFileSync } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createInterface } from 'node:readline'; +import { die, launch, sleep } from './cdp.mjs'; import { demoRpc } from './screenshot-demo.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); @@ -37,6 +41,7 @@ const args = { names: [], only: [], demo: false, + lang: 'en', }; for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; @@ -47,8 +52,26 @@ for (let i = 2; i < process.argv.length; i++) { else if (a === '--name') args.names.push(v().split('=', 2)); else if (a === '--only') args.only = v().split(','); else if (a === '--demo') args.demo = true; + else if (a === '--lang') args.lang = v(); else die(`unknown argument ${a}`); } +const SUFFIX = args.lang === 'en' ? '' : `-${args.lang}`; + +/** The admin's catalog for --lang: msgid -> msgstr, the entries without a context (English: none). */ +const CATALOG = (() => { + const out = new Map(); + if (args.lang === 'en') return out; + let po; + try { + po = readFileSync(join(ROOT, 'package', 'luci-app-dawnline', 'po', args.lang, 'dawnline.po'), 'utf8'); + } catch { + die(`no admin catalog for --lang ${args.lang}`); + } + for (const m of po.matchAll(/^(msgctxt .*\n)?msgid "(.*)"\nmsgstr "(.*)"$/gm)) if (!m[1] && m[3]) out.set(m[2], m[3]); + return out; +})(); +/** A button's words as the page shows them in --lang (the pages are clicked by what they say). */ +const tr = (id) => CATALOG.get(id) ?? id; if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown'); /** As shared/format initials(): first letters of the first and last word, or the first two of one word. */ @@ -60,11 +83,6 @@ for (const [real, shown] of args.names) args.mask.push([real, shown], [real.toLowerCase(), shown.toLowerCase()], [real.toUpperCase(), shown.toUpperCase()]); const INITIALS = args.names.map(([real, shown]) => [initials(real), initials(shown)]); -function die(msg) { - console.error(msg); - process.exit(1); -} - const LUCI = `${args.router}/cgi-bin/luci/admin/network/dawnline`; const USER = process.env.LUCI_USER || 'root'; @@ -93,7 +111,7 @@ const SHOTS = [ ready: '.dl-srvov .dl-panel.flush .maplibregl-canvas', // The map shows the last 30 days, not only who is online now. prep: `(() => { - const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === '30 days'); + const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('30 days'))}); b?.click(); })()`, settle: 6000, @@ -113,7 +131,7 @@ const SHOTS = [ ready: '.dl-grid-person .dl-row', // Where they connected from, on the map. prep: `(() => { - const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === 'Show map'); + const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('Show map'))}); b?.click(); })()`, settle: 6000, @@ -131,25 +149,6 @@ const SHOTS = [ return { x: c.x, y: 0, width: c.w, height: cut }; })()`, }, - { - name: 'portal', - url: (s) => s.portal, - width: 1320, - ready: 'body', - settle: 3000, - // The content: everything but full-width or full-height wrappers, 36px around it. - clip: `(() => { - let l = innerWidth, r = 0, b = 0; - for (const e of document.body.querySelectorAll('*')) { - const x = e.getBoundingClientRect(); - if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue; - l = Math.min(l, x.left); - r = Math.max(r, x.right); - b = Math.max(b, x.bottom); - } - return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 }; - })()`, - }, ]; const MASK = `((pairs, inits) => { @@ -198,87 +197,20 @@ async function password() { } } -function findBrowser() { - const c = [ - process.env.BROWSER, - '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser', - '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', - '/usr/bin/chromium', - '/usr/bin/google-chrome', - ]; - return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome'); -} - -/** A page over the DevTools protocol: send(method, params) and waitFor(event). */ -async function connect(wsUrl) { - const ws = new WebSocket(wsUrl); - await new Promise((ok, fail) => { - ws.onopen = ok; - ws.onerror = fail; - }); - let id = 0; - const pending = new Map(); - const waiters = []; - const listeners = []; - ws.onmessage = (m) => { - const msg = JSON.parse(m.data); - if (msg.id && pending.has(msg.id)) { - const { ok, fail } = pending.get(msg.id); - pending.delete(msg.id); - msg.error ? fail(new Error(msg.error.message)) : ok(msg.result); - } else if (msg.method) { - for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params); - for (const w of waiters.filter((x) => x.method === msg.method)) { - waiters.splice(waiters.indexOf(w), 1); - w.ok(msg.params); - } - } - }; - const send = (method, params = {}) => - new Promise((ok, fail) => { - pending.set(++id, { ok, fail }); - ws.send(JSON.stringify({ id, method, params })); - }); - const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok })); - const on = (method, fn) => listeners.push({ method, fn }); - return { send, waitFor, on, close: () => ws.close() }; -} - -const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms)); - async function main() { const pass = await password(); - const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-')); - const chrome = spawn( - findBrowser(), - [ - '--headless=new', - '--remote-debugging-port=0', - `--user-data-dir=${profile}`, - // The router's certificate is usually for its public name, not router.lan. - '--ignore-certificate-errors', - '--hide-scrollbars', - '--no-first-run', - '--no-default-browser-check', - // MapLibre needs WebGL; headless gets it from SwiftShader. - '--use-angle=swiftshader', - '--enable-unsafe-swiftshader', - 'about:blank', - ], - { stdio: 'ignore' }, - ); + // The router's certificate is usually for its public name, not router.lan. + const b = await launch(['--ignore-certificate-errors', `--lang=${args.lang}`]); + const { page, evaluate, go, waitSel } = b; try { - const portFile = join(profile, 'DevToolsActivePort'); - for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100); - const port = readFileSync(portFile, 'utf8').split('\n')[0]; - const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); - const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl); - await page.send('Page.enable'); + // LuCI on auto speaks the browser's language: this one, whatever this computer's is. + await page.send('Network.enable'); + await page.send('Network.setExtraHTTPHeaders', { headers: { 'Accept-Language': args.lang } }); await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }], }); // The person shown on the Person page; known once People has loaded (or from --person). - const s = { person: args.person, portal: '' }; + const s = { person: args.person }; if (args.demo) { page.on('Fetch.requestPaused', async (e) => { try { @@ -302,27 +234,6 @@ async function main() { }); } - const evaluate = async (expression) => { - const r = await page.send('Runtime.evaluate', { - expression, - awaitPromise: true, - returnByValue: true, - }); - if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text); - return r.result.value; - }; - const go = async (url) => { - const loaded = page.waitFor('Page.loadEventFired'); - await page.send('Page.navigate', { url }); - await loaded; - }; - const waitSel = async (sel, ms = 20000) => { - for (let t = 0; t < ms; t += 250) { - if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return; - await sleep(250); - } - throw new Error(`timed out waiting for ${sel}`); - }; // A tall window: Outline scrolls #maincontent, not the page, so it must hold everything. const viewport = (width, height = 2600) => page.send('Emulation.setDeviceMetricsOverride', { @@ -350,24 +261,16 @@ async function main() { ); } - // The person to show (the first one on People unless --person) and their personal link. + // The person to show: the first one on People unless --person. await go(`${LUCI}/server?section=people`); await waitSel('.dl-srvbody a[href*="dawnline/person"]'); if (!s.person) s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`); - s.portal = await evaluate(`L.require('rpc').then((rpc) => - rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)})) - .then((r) => r.link ?? r.links?.[0] ?? '')`); for (const shot of SHOTS) { if (args.only.length && !args.only.includes(shot.name)) continue; - const url = shot.url(s); - if (!url) { - console.log(`skip ${shot.name}: no URL (the portal is off?)`); - continue; - } await viewport(shot.width); - await go(url); + await go(shot.url(s)); await waitSel(shot.ready); await sleep(2000); if (shot.prep) await evaluate(shot.prep); @@ -379,14 +282,12 @@ async function main() { clip: { ...clip, scale: 1 }, captureBeyondViewport: true, }); - writeFileSync(join(RAW, `${shot.name}.png`), Buffer.from(data, 'base64')); - console.log(`${shot.name}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`); + writeFileSync(join(RAW, `${shot.name}${SUFFIX}.png`), Buffer.from(data, 'base64')); + console.log(`${shot.name}${SUFFIX}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`); } page.close(); } finally { - chrome.kill(); - await sleep(300); - rmSync(profile, { recursive: true, force: true }); + await b.close(); } } diff --git a/scripts/cdp.mjs b/scripts/cdp.mjs new file mode 100644 index 0000000..6866cfc --- /dev/null +++ b/scripts/cdp.mjs @@ -0,0 +1,122 @@ +// A headless Chromium driven over the DevTools protocol, no npm packages: what +// the README screenshot scripts share (capture-screenshots.mjs from a router, +// capture-portal.mjs from the portal demo). BROWSER=/path/to/chrome picks the +// browser (default: Brave or Chrome on macOS); its profile is a throwaway one. + +import { spawn } from 'node:child_process'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +export const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms)); + +export function die(msg) { + console.error(msg); + process.exit(1); +} + +export function findBrowser() { + const c = [ + process.env.BROWSER, + '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser', + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/usr/bin/chromium', + '/usr/bin/google-chrome', + ]; + return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome'); +} + +/** A page over the DevTools protocol: send(method, params), waitFor(event) and on(event, fn). */ +export async function connect(wsUrl) { + const ws = new WebSocket(wsUrl); + await new Promise((ok, fail) => { + ws.onopen = ok; + ws.onerror = fail; + }); + let id = 0; + const pending = new Map(); + const waiters = []; + const listeners = []; + ws.onmessage = (m) => { + const msg = JSON.parse(m.data); + if (msg.id && pending.has(msg.id)) { + const { ok, fail } = pending.get(msg.id); + pending.delete(msg.id); + msg.error ? fail(new Error(msg.error.message)) : ok(msg.result); + } else if (msg.method) { + for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params); + for (const w of waiters.filter((x) => x.method === msg.method)) { + waiters.splice(waiters.indexOf(w), 1); + w.ok(msg.params); + } + } + }; + const send = (method, params = {}) => + new Promise((ok, fail) => { + pending.set(++id, { ok, fail }); + ws.send(JSON.stringify({ id, method, params })); + }); + const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok })); + const on = (method, fn) => listeners.push({ method, fn }); + return { send, waitFor, on, close: () => ws.close() }; +} + +/** + * Start the browser headless on a fresh profile and connect to its first page. `flags` go on its command line + * (a language, certificate errors). Returns the page, its helpers, and close() that ends the browser and removes + * the profile. + */ +export async function launch(flags = []) { + const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-')); + const chrome = spawn( + findBrowser(), + [ + '--headless=new', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + '--hide-scrollbars', + '--no-first-run', + '--no-default-browser-check', + // MapLibre needs WebGL; headless gets it from SwiftShader. + '--use-angle=swiftshader', + '--enable-unsafe-swiftshader', + ...flags, + 'about:blank', + ], + { stdio: 'ignore' }, + ); + const close = async () => { + chrome.kill(); + await sleep(300); + rmSync(profile, { recursive: true, force: true }); + }; + try { + const portFile = join(profile, 'DevToolsActivePort'); + for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100); + const port = readFileSync(portFile, 'utf8').split('\n')[0]; + const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); + const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl); + await page.send('Page.enable'); + const evaluate = async (expression) => { + const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }); + if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text); + return r.result.value; + }; + const go = async (url) => { + const loaded = page.waitFor('Page.loadEventFired'); + await page.send('Page.navigate', { url }); + await loaded; + }; + const waitSel = async (sel, ms = 20000) => { + for (let t = 0; t < ms; t += 250) { + if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return; + await sleep(250); + } + throw new Error(`timed out waiting for ${sel}`); + }; + return { page, evaluate, go, waitSel, close }; + } catch (e) { + await close(); + throw e; + } +} diff --git a/scripts/frame-screenshots.py b/scripts/frame-screenshots.py index eaeab92..a5a5341 100755 --- a/scripts/frame-screenshots.py +++ b/scripts/frame-screenshots.py @@ -2,7 +2,8 @@ """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 +per CSS pixel (scripts/capture-screenshots.mjs takes the admin's from a router, +scripts/capture-portal.mjs the portal's from its demo); the framed images are written to docs/screenshots/.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 @@ -25,11 +26,12 @@ OUT = os.path.join(ROOT, 'docs', 'screenshots') FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets', 'geist-latin-wght-normal.woff2') -SHOTS = ['overview', 'people', 'person', 'portal'] -# name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router: -# adding a device there would add one. +SHOTS = ['overview', 'people', 'person', 'portal', 'overview-ru', 'people-ru', 'person-ru', 'portal-ru'] +# name -> the steps in front of its page, in order (raw captures). The portal's come from its demo +# (scripts/capture-portal.mjs), not a router: adding a device there would add one. -ru: README_ru's. FLOWS = { 'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'], + 'portal-ru': ['portal-add-1-ru', 'portal-add-2-ru', 'portal-add-3-ru'], } PAD_X, PAD_Y, INSET = 96, 80, 16 # canvas around the panel; panel around the page FLOW_MARGIN = (56, 40, 56, 72) # around a step's sheet in its capture: left, top, right, bottom diff --git a/scripts/screenshot-demo.mjs b/scripts/screenshot-demo.mjs index 92a304e..a28183b 100644 --- a/scripts/screenshot-demo.mjs +++ b/scripts/screenshot-demo.mjs @@ -129,16 +129,31 @@ const seen = (when, now) => { }[k] ?? 0 ); }; -/** A week of daily totals that adds up to about a quarter of the month, today last (nothing before it was first seen). */ +/** + * A week of daily [rx, tx] that adds up to about a quarter of the month, today last (nothing before it was first + * seen), rx (from the device) about an eighth. + */ const week = (gb, last, now) => - [0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => (!gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7))); + [0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => { + const b = !gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7); + return [Math.round(b * 0.12), b - Math.round(b * 0.12)]; + }); +/** + * One second of the cast's traffic through a server (the k-th), [rx, tx] in bytes/s: a few devices streaming, + * their uploads small. The same for a second whichever call asks, so the live chart keeps its shape. + */ +const meterRate = (ts, k) => { + const wave = (a, b) => Math.sin(ts / a + k) * 0.45 + Math.sin(ts / b + 2 * k) * 0.25; + const noise = (((ts * 7919 + k * 104729) % 1000) / 1000 - 0.5) * 0.35; + return [Math.round(Math.max(0, 1.8e5 * (1 + wave(7, 17) + noise))), Math.round(Math.max(0, 1.6e6 * (1 + wave(9, 23) + noise)))]; +}; let ipN = 10; /** A documentation address (the capture swaps public addresses for these anyway). */ const ip = () => `203.0.113.${ipN++}`; const where = (city) => `${city} · ${CITIES[city][4]}`; -/** What the last status made of the router's ids, for the calls that come after it (events, usage). */ -const demo = { events: [], people: new Map(), days: [], now: 0 }; +/** What the last status made of the router's ids, for the calls that come after it (events, usage, the meter). */ +const demo = { events: [], people: new Map(), days: [], now: 0, servers: [] }; /** * Daily traffic over `days` (oldest first) for `gb` this month: busier some days of the week, today @@ -255,6 +270,12 @@ function demoStatus(st, first) { total: [Math.round(gb * 0.3 * GB), Math.round(gb * 2.2 * GB)], spark: week(gb, hs, now), hostname: hs ? `${slug(name)}.${slug(c.name.split(' ')[0])}.lan` : '', + // As set up: nothing failing, its own link values the server's, its data flowing while online. + link: null, + setup: online ? { state: 'flowing', since: hs } : null, + lan_bypass: false, + mtu: 0, + keepalive: null, }; }); for (const [name, ago, by] of c.added ?? []) { @@ -313,6 +334,7 @@ function demoStatus(st, first) { demo.events = events; points.sort((a, b) => b.ts - a.ts); demo.now = now; + demo.servers = (st.servers ?? []).map((x) => x.id); demo.days = (st.series ?? []).map((x) => x.day); if (!demo.days.length) for (let k = 29; k >= 0; k--) demo.days.push(date(now - k * DAY)); const all = CAST.reduce((s, c) => s + c.devices.reduce((t, d) => t + d[3], 0), 0); @@ -384,6 +406,16 @@ export function demoRpc(request, response, first) { }, ], }; + // Speed now, live: the last two minutes of the cast's traffic, not the router's. + if (method === 'meter' && Array.isArray(data.points)) { + const ids = demo.servers.length ? demo.servers : [...new Set(data.points.flatMap((p) => Object.keys(p.servers ?? {})))]; + const keep = data.keep > 1 ? data.keep : 120; + const since = +args?.since || 0; + const points = []; + for (let ts = data.now - keep + 1; ts <= data.now; ts++) + if (ts > since) points.push({ ts, servers: Object.fromEntries(ids.map((id, k) => [id, meterRate(ts, k)])) }); + return { ...r, result: [r.result[0], { ...data, ts: data.now, points }] }; + } if (method === 'events' && Array.isArray(data.events)) { const mine = demo.events.filter((e) => !args?.person || e.person === args.person); return { diff --git a/tests/ucode/access.test.uc b/tests/ucode/access.test.uc new file mode 100644 index 0000000..7cc745a --- /dev/null +++ b/tests/ucode/access.test.uc @@ -0,0 +1,67 @@ +// dawnline.access: the Check access walk for a device that keeps its own +// local network out of the tunnel (lan_bypass), and the way its internet +// leaves, on a model and a network snapshot of the test's own (nothing read +// from the container). +import * as access from 'dawnline.access'; + +const KEY_TV = 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', KEY_PHONE = 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c='; + +/** Bob (Internet only) on a server that sends everyone direct: a TV with lan_bypass and a phone without. */ +function model() { + return { + settings: { portal_enabled: false }, + servers: { + home: { id: 'home', name: 'Home', ifname: 'awghome', subnet: '10.9.0.0/29', private_key: 'k', enabled: true, lan_like: false, + auto_wan: false, wan_device: 'eth1', auto_lan: false, lan_devices: [ 'br-lan' ], mesh: 'all', device_mesh: true, dns: [] }, + }, + people: { bob: { id: 'bob', name: 'Bob', server: 'home', access: 'internet', services: [], devices: [ 'tv', 'phone' ] } }, + devices: { + tv: { id: 'tv', person: 'bob', name: 'TV', address: '10.9.0.2', public_key: KEY_TV, lan_bypass: true }, + phone: { id: 'phone', person: 'bob', name: 'Phone', address: '10.9.0.3', public_key: KEY_PHONE, lan_bypass: false }, + }, + services: {}, + circles: {}, + }; +} + +const CTX = { + states: { bob: 'active' }, + dmp: { peers: {}, windows: {} }, + snap: { + devices: { + 'br-lan': { nets: [ '192.168.1.0/24' ], zone: 'lan', addrs: [ '192.168.1.1/24' ] }, + eth1: { nets: [ '203.0.113.0/24' ], zone: 'wan', addrs: [ '203.0.113.7/24' ] }, + awghome: { nets: [ '10.9.0.0/29' ], addrs: [ '10.9.0.1/29' ] }, + }, + lan: 'br-lan', + wan: 'eth1', + }, +}; + +function last(r) { + return r.steps[length(r.steps) - 1]; +} + +test('check: a device with its local network outside the tunnel', () => { + let m = model(); + let r = access.check(m, 'tv', '192.168.1.20', CTX); + eq([ r.ok, last(r).ok, last(r).title ], [ false, false, "Its configuration doesn't send it to the router" ], + 'a home address: on its own network, not blocked in the tunnel'); + ok(index(last(r).detail, "the device's own network handles it") >= 0, 'says where it goes'); + r = access.check(m, 'tv', '192.168.1.1:80', CTX); + eq(last(r).title, "Its configuration doesn't send it to the router", 'the router\'s LAN address is on its own network too'); + r = access.check(m, 'tv', '10.9.0.1:53', CTX); + eq([ r.ok, r.steps[1].title ], [ true, '10.9.0.1 is this router: DNS is open to everyone' ], 'its DNS stays in the tunnel'); + r = access.check(m, 'tv', '8.8.8.8', CTX); + eq([ r.ok, last(r).title, last(r).detail ], [ true, '8.8.8.8 is on the internet', 'It leaves through eth1.' ], 'the internet through the tunnel'); + + r = access.check(m, 'phone', '192.168.1.20', CTX); + eq([ r.ok, last(r).title ], [ false, '192.168.1.20 is at home (br-lan)' ], 'without it: into the tunnel, and blocked there'); +}); + +test('check: the way out is the server\'s', () => { + let m = model(); + eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves through eth1.', 'direct'); + m.servers.home.lan_like = true; + eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves like a home device would.', 'like a home device'); +}); diff --git a/tests/ucode/awg.test.uc b/tests/ucode/awg.test.uc index 07d8f1a..9dafa53 100644 --- a/tests/ucode/awg.test.uc +++ b/tests/ucode/awg.test.uc @@ -1,10 +1,18 @@ -// dawnline.awg: disguise presets against their own validation, the parser -// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1 -// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), -// Reconnect, and a device's configuration from the fixture model. +// dawnline.awg: disguise presets against their own validation, the values +// AmneziaWG refuses (obf_unsafe, one case per rule), the parser of `awg show +// dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1 and how +// each tunnel's read went (the stand-in awg in fixtures/bin prints the +// fixture put at AWG_DUMP), the devices a tunnel should hold, Reconnect, a +// device's configuration from the fixture model, what the server's interface +// and the read-only status get of it. import { readfile, writefile, unlink } from 'fs'; +import { cursor } from 'uci'; +import { valid_key, cidr_any } from 'dawnline.util'; import * as awg from 'dawnline.awg'; import * as core from 'dawnline.core'; +import * as backup from 'dawnline.backup'; +import * as rpc_status from 'dawnline.rpc.status'; +import * as nft from 'dawnline.nft'; const AWG_DUMP = '/tmp/dawnline-tests/awg-dump'; let fixtures = sourcepath(0, true) + '/fixtures'; @@ -34,7 +42,8 @@ test('obf_preset balanced', () => { test('obf_preset max', () => { let o = awg.obf_preset('max'); - eq(o.header_protection_key, 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=', 'key from awg genkey'); + ok(valid_key(o.header_protection_key), 'a header protection key'); + ok(o.header_protection_key != awg.obf_preset('max').header_protection_key, 'made for each server, without awg genkey'); ok(+o.jc >= 4 && +o.jc <= 6, 'jc'); ok(substr(o.i1, 0, 3) == ' { shapes[awg.obf_preset('max').i1] = true; ok(length(keys(shapes)) > 1, 'signature packets differ between servers'); // The preset passes the server's own validation (jmin/jmax may be small: 0.5.2). - eq(awg.obf_errors(o), [], 'max is valid'); + for (let i = 0; i < 25; i++) + eq(awg.obf_errors(awg.obf_preset('max')), [], 'max is valid'); }); -test('obf_errors', () => { +test('obf_errors: Dawnline\'s own bounds on top of obf_unsafe', () => { eq(awg.obf_errors({}), [], 'nothing set'); - eq(awg.obf_errors({ jc: '11' }), [ 'jc=11 (0-10)' ], 'jc range'); + eq(awg.obf_errors(null), [], 'no values'); + eq(awg.obf_errors({ jc: '11' }), [ 'Jc must be from 0 to 10.' ], 'jc range'); eq(awg.obf_errors({ jmin: '0', jmax: '0' }), [], 'zero junk sizes are allowed'); - eq(awg.obf_errors({ jmin: '2000' }), [ 'jmin=2000 (0-1024)' ], 'jmin range'); - eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'jmin > jmax' ], 'order'); - eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 's1 + 56 = s2' ], 'the handshake size clash'); - eq(awg.obf_errors({ s4: '33' }), [ 's4=33 (0-32)' ], 's4 range'); - eq(awg.obf_errors({ jc: 'x' }), [ 'jc=x (0-10)' ], 'not a number'); - eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'h1-h4 must be distinct' ], 'duplicate headers'); - eq(awg.obf_errors({ h1: '7-9', h2: 'abc' }), [ 'h2 must be a number or range' ], 'header ranges'); + eq(awg.obf_errors({ jmin: '2000', jmax: '3000' }), [ 'Jmin must be from 0 to 1024.', 'Jmax must be from 0 to 1024.' ], 'junk sizes'); + eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 'S2 must not be S1 + 56: the handshake initiation and response would have the same size.' ], + 'the handshake size clash'); + eq(awg.obf_errors({ s4: '33' }), [ 'S4 must be from 0 to 32.' ], 's4 range'); + // What AmneziaWG refuses comes first, said once. + eq(awg.obf_errors({ jc: 'x' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'not a number'); + eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'Jmin must not be larger than Jmax.' ], 'order'); + eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'duplicate headers'); eq(awg.obf_neutral({ jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }), true, 'off is neutral'); eq(awg.obf_neutral({ jc: '4', jmin: '64', jmax: '128' }), false, 'junk is not neutral'); }); +// One case per rule of obf_unsafe: what an import, a restore or a hand edit must never hand to the kernel. +const HPK = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='; +const MAX = { s1: '12', s2: '12', s3: '12', s4: '12', header_protection_key: HPK }; + +test('obf_unsafe: what the presets and older servers hold passes', () => { + eq(awg.obf_unsafe(null), [], 'no values'); + eq(awg.obf_unsafe(awg.obf_preset('off')), [], 'off'); + for (let i = 0; i < 25; i++) { + eq(awg.obf_unsafe(awg.obf_preset('balanced')), [], 'balanced'); + eq(awg.obf_unsafe(awg.obf_preset('max')), [], 'max'); + } + // Values from before 0.8 and hand-tuned ones the kernel takes: none of Dawnline's own bounds here. + let old = { jc: '12', jmin: '50', jmax: '1400', s1: '100', s2: '156', h1: '1234567', h2: '2345678', h3: '3456789', h4: '4567890' }; + eq(awg.obf_unsafe(old), [], 'older and hand-tuned values'); + ok(length(awg.obf_errors(old)) > 0, 'which a new server would not get'); +}); + +test('obf_unsafe: 16-bit numbers', () => { + eq(awg.obf_unsafe({ jc: '65535', s4: '0' }), [], 'the ends'); + eq(awg.obf_unsafe({ jc: '65536' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'too large'); + eq(awg.obf_unsafe({ s3: '-1' }), [ 'S3 must be a whole number from 0 to 65535.' ], 'negative'); + eq(awg.obf_unsafe({ jmax: '1e3' }), [ 'Jmax must be a whole number from 0 to 65535.' ], 'not digits'); +}); + +test('obf_unsafe: Jmin not above Jmax', () => { + eq(awg.obf_unsafe({ jmin: '50', jmax: '50' }), [], 'equal'); + eq(awg.obf_unsafe({ jmin: '51', jmax: '50' }), [ 'Jmin must not be larger than Jmax.' ], 'the kernel would write past its junk buffer'); + eq(awg.obf_unsafe({ jmin: '51' }), [], 'Jmax not given'); +}); + +test('obf_unsafe: header values are numbers or ranges', () => { + eq(awg.obf_unsafe({ h1: '100-200', h2: '300', h3: '4294967295', h4: '0' }), [], 'numbers and ranges'); + eq(awg.obf_unsafe({ h1: '200-100' }), [ 'H1 must be a number or a range like 100-200, up to 4294967295.' ], 'reversed'); + eq(awg.obf_unsafe({ h2: '4294967296' }), [ 'H2 must be a number or a range like 100-200, up to 4294967295.' ], 'past 32 bits'); + eq(awg.obf_unsafe({ h3: '5-6-7' }), [ 'H3 must be a number or a range like 100-200, up to 4294967295.' ], 'two dashes'); + eq(awg.obf_unsafe({ h4: 'abc' }), [ 'H4 must be a number or a range like 100-200, up to 4294967295.' ], 'not a number'); +}); + +test('obf_unsafe: header values do not overlap', () => { + eq(awg.obf_unsafe({ h1: '10-20', h2: '20-30', h3: '40', h4: '50' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'a shared end'); + eq(awg.obf_unsafe({ h1: '10-20', h2: '30', h3: '15', h4: '50' }), [ 'H1 and H3 overlap: each packet type needs values of its own.' ], 'one inside a range'); + // One not given keeps WireGuard's type: 1-4. + eq(awg.obf_unsafe({ h1: '1-10' }), [ 'H1 and H2 overlap: each packet type needs values of its own.', 'H1 and H3 overlap: each packet type needs values of its own.', + 'H1 and H4 overlap: each packet type needs values of its own.' ], 'over the default types'); + eq(awg.obf_unsafe({ h1: '5-10' }), [], 'clear of them'); +}); + +test('obf_unsafe: header protection needs a key and 12-byte padding', () => { + eq(awg.obf_unsafe(MAX), [], 'the 3.1 values'); + eq(awg.obf_unsafe({ ...MAX, header_protection_key: 'abc' }), [ 'The header protection key is not a key.' ], 'not a key'); + eq(awg.obf_unsafe({ ...MAX, s3: '11' }), [ 'S3 must be at least 12 with header protection.' ], 'too little padding'); + eq(awg.obf_unsafe({ ...MAX, s4: null }), [ 'S4 must be at least 12 with header protection.' ], 'no padding'); + eq(awg.obf_unsafe({ s1: '0', s2: '0' }), [], 'none needed without the key'); +}); + +test('obf_unsafe: 3.1 timers and counts', () => { + eq(awg.obf_unsafe({ rekey_after_time: '100-120', rekey_timeout: '3', keepalive_timeout: '0', max_handshake_attempts: '0-0' }), [], + 'numbers, ranges and 0 (the default)'); + eq(awg.obf_unsafe({ rekey_timeout: '0-7' }), [ 'RekeyTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'a 0 in a range'); + eq(awg.obf_unsafe({ keepalive_timeout: '15-5' }), [ 'KeepaliveTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'reversed'); + eq(awg.obf_unsafe({ max_handshake_attempts: '70000' }), [ 'MaxHandshakeAttempts must be a number or a range like 5-15, from 1 to 65535.' ], 'past 16 bits'); + eq(awg.obf_unsafe({ content_padding_addition: '0-100' }), [], 'padding may start at 0'); + eq(awg.obf_unsafe({ content_padding_addition: '10-x' }), [ 'ContentPaddingAddition must be a number or a range like 10-100, up to 65535.' ], 'padding'); +}); + +test('obf_unsafe: RejectAfterTime up to 180 seconds', () => { + eq(awg.obf_unsafe({ reject_after_time: '150-180' }), [], 'the preset'); + eq(awg.obf_unsafe({ reject_after_time: '150-181' }), [ 'RejectAfterTime must be at most 180 seconds.' ], 'the kernel drops keys after 180 seconds'); +}); + +test('obf_unsafe: switches', () => { + eq(awg.obf_unsafe({ random_trailers: 'on', disable_cookies: '0' }), [], 'on, off, 1, 0'); + eq(awg.obf_unsafe({ random_trailers: 'yes' }), [ 'RandomTrailers must be on or off.' ], 'what the .conf parser refuses'); + eq(awg.obf_unsafe({ disable_cookies: 'true' }), [ 'DisableCookies must be on or off.' ], 'the same for cookies'); +}); + +test('obf_unsafe: signature packet tags', () => { + let bad = (name, tag) => `${name}: <${tag}> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or .`; + eq(awg.obf_unsafe({ i1: '', i2: 'text between tags is skipped' }), [], 'every tag both parsers know'); + eq(awg.obf_unsafe({ i1: '' }), [ bad('I1', 'b 0xabc') ], 'an odd number of hex digits'); + eq(awg.obf_unsafe({ i1: '' }), [ bad('I1', 'b 0x') ], 'no bytes'); + eq(awg.obf_unsafe({ i1: '' }), [ bad('I1', 'b ff00') ], 'no 0x (the kernel needs it)'); + eq(awg.obf_unsafe({ i1: '' }), [ bad('I1', 'b 0xzz') ], 'not hex'); + eq(awg.obf_unsafe({ i2: '' }), [ bad('I2', 'r -5') ], 'a negative length writes past the packet'); + eq(awg.obf_unsafe({ i2: '' }), [ bad('I2', 'rc 0') ], 'no length'); + eq(awg.obf_unsafe({ i2: '' }), [ bad('I2', 'rd 1001') ], 'too long'); + eq(awg.obf_unsafe({ i3: '' }), [ bad('I3', 'r 5') ], 'two spaces'); + eq(awg.obf_unsafe({ i3: '' }), [ bad('I3', 't ') ], 'a space after t'); + eq(awg.obf_unsafe({ i4: '' }), [ bad('I4', 'c') ], 'the kernel\'s counter, which amneziawg-go refuses'); + for (let t in [ 'd', 'ds', 'dz' ]) + eq(awg.obf_unsafe({ i4: `<${t}>` }), [ bad('I4', t) ], `amneziawg-go's <${t}>, which the kernel refuses`); + eq(awg.obf_unsafe({ i5: '<>' }), [ bad('I5', '') ], 'an empty tag'); + eq(awg.obf_unsafe({ i5: '' }), [ bad('I5', 'r <5') ], 'a tag inside a tag'); + eq(awg.obf_unsafe({ i5: '' }), [], 'long tags are fine'); + eq(awg.obf_unsafe({ i5: '' }), [ bad('I5', 'x 0x0102030405060708090a…') ], 'shown cut short'); + eq(awg.obf_unsafe({ i1: '.' ], 'not closed'); + eq(awg.obf_unsafe({ i1: ' # note' }), [ 'I1 may not contain # or a line break.' ], 'a comment in a .conf'); + eq(awg.obf_unsafe({ i1: '\n' }), [ 'I1 may not contain # or a line break.' ], 'a line break'); +}); + +test('obf_unsafe: I1-I5 fit one configuration', () => { + // A tag of 100 characters. + let tag = ' { + let out = ''; + for (let k = 0; k < n; k++) + out += tag; + return out; + }; + let four = many(4); + eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: four }), [], '2000 characters'); + eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: many(5) }), [ 'I1-I5 together must be at most 2000 characters, not 2100.' ], 'over 2000'); +}); + +test('obf_unsafe: an import or restore with such values is refused', () => { + let dir = '/tmp/dawnline-tests/import'; + let errs = (text) => { + system(`rm -rf ${dir}; mkdir -p ${dir}/.delta`); + writefile(`${dir}/dawnline`, text); + let c = cursor(dir, `${dir}/.delta`); + c.load('dawnline'); + let out = backup.config_errors(c); + system(`rm -rf ${dir}`); + return out; + }; + let fixture = readfile('/etc/config/dawnline'); + let bad = errs(replace(fixture, "option jmax '128'", "option jmax '32'")); + ok(index(bad, 'Server Main: Jmin must not be larger than Jmax.') >= 0, `refused: ${join(' ', bad)}`); + eq(filter(errs(fixture), (e) => index(e, 'Jmin') >= 0), [], 'the fixture as it is'); +}); + +// The stand-in's call log and failures (fixtures/bin/awg). +const AWG_CALLS = '/tmp/dawnline-tests/awg-calls'; +const AWG_FAIL = '/tmp/dawnline-tests/awg-fail-'; +const SERVER_KEY = 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='; +const PEER_ON = 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=', PEER_NEW = 'TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0='; + +// A fixture's lines as another interface's (`show all` prints the ifname first). +function lines_as(name, ifname) { + let out = ''; + for (let l in split(readfile(`${fixtures}/awg-dump-${name}.txt`), '\n')) + if (l != '') + out += `${ifname}${substr(l, length('awgmain'))}\n`; + return out; +} + +// lo is in every container's /sys/class/net (index 1), and is no AmneziaWG +// interface: the stand-in prints the fixture's lines for it, as for a tunnel. function dump_of(name) { - writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-${name}.txt`)); - return awg.dump(); + writefile(AWG_DUMP, lines_as(name, 'lo')); + return awg.dump([ 'lo' ]); } test('dump: AmneziaWG 1.0 (14 interface fields)', () => { let d = dump_of('1.0'); eq(d.ok, true, 'ok'); - eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface'); - eq(d.peers['HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw='], - { ifname: 'awgmain', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 }, 'peer with a session'); - eq(d.peers['TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0='], - { ifname: 'awgmain', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected'); + eq(d.reads, { lo: 'read' }, 'read'); + eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface; its index is the epoch of its counters'); + eq(d.peers[PEER_ON], { ifname: 'lo', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 }, + 'peer with a session, with the ifname the lines leave out'); + eq(d.peers[PEER_NEW], { ifname: 'lo', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected'); }); test('dump: AmneziaWG 2.0 (33 interface fields)', () => { let d = dump_of('2.0'); - eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface'); - eq(keys(d.peers), [ 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=' ], 'one peer'); + eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface'); + eq(keys(d.peers), [ PEER_ON ], 'one peer'); }); test('dump: AmneziaWG 3.1 (33 interface fields, protection on)', () => { let d = dump_of('3.1'); - eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface'); + eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface'); eq(length(d.peers), 2, 'two peers'); }); -test('dump: the tool fails', () => { +// awgmain is not in the container's /sys/class/net, as a tunnel netifd could not bring up. +test('dump: a tunnel that is not there is down, without a process', () => { + writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`)); + unlink(AWG_CALLS); + eq(awg.dump([ 'awgmain' ]), { ok: true, reads: { awgmain: 'down' }, ifaces: {}, peers: {} }, 'its counters are gone'); + eq(readfile(AWG_CALLS), null, 'awg is not asked about a link the kernel does not have'); + eq(awg.dump([]), { ok: true, reads: {}, ifaces: {}, peers: {} }, 'no tunnel runs'); +}); + +test('dump: each tunnel on its own', () => { + writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`) + lines_as('2.0', 'lo')); + let d = awg.dump([ 'awgmain', 'lo' ]); + eq([ d.ok, d.reads ], [ true, { awgmain: 'down', lo: 'read' } ], 'one down, one read'); + eq(keys(d.ifaces), [ 'lo' ], 'only what was read'); + eq(filter(values(d.peers), (p) => p.ifname != 'lo'), [], 'no peers of the one that is down'); +}); + +// The tool says "Operation not supported" for lo on a real system. +test('dump: a tunnel that exists but cannot be read', () => { + writefile(AWG_DUMP, lines_as('2.0', 'lo')); + writefile(`${AWG_FAIL}lo`, 'Unable to access interface: Operation not supported\n'); + let d = awg.dump([ 'awgmain', 'lo' ]); + unlink(`${AWG_FAIL}lo`); + eq(d.ok, false, 'not every tunnel was read'); + eq(d.reads, { awgmain: 'down', lo: 'error' }, 'each on its own'); + eq([ d.ifaces, d.peers ], [ {}, {} ], 'nothing of the failed one'); +}); + +// The agent's watcher reads every second: with one server, one process. +test('dump: only the tunnels asked for, one process each', () => { + writefile(AWG_DUMP, lines_as('1.0', 'lo') + lines_as('2.0', 'wgclient')); + unlink(AWG_CALLS); + let d = awg.dump([ 'lo' ]); + // The tests after these find no tunnel, as on a router without AmneziaWG running. unlink(AWG_DUMP); - let d = awg.dump(); - eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known'); + eq(readfile(AWG_CALLS), 'show lo dump\n', 'one call, never `all`'); + eq(keys(d.ifaces), [ 'lo' ], 'the other tunnel is not read'); + eq(d.peers[PEER_ON].ifname, 'lo', 'its peers stand in for none of ours'); +}); + +test('tunnel_devices: what sync_peers loads', () => { + let m = { + servers: { s: { public_key: SERVER_KEY } }, + people: { a: { id: 'a', server: 's' }, b: { id: 'b', server: 's' }, c: { id: 'c', server: 'other' } }, + devices: { + on: { person: 'a', public_key: PEER_ON, address: '10.9.0.2' }, + own: { person: 'a', public_key: SERVER_KEY, address: '10.9.0.8' }, + off: { person: 'a', public_key: PEER_NEW, address: '10.9.0.3', disabled: true }, + paused: { person: 'b', public_key: SERVER_KEY, address: '10.9.0.4' }, + elsewhere: { person: 'c', public_key: PEER_NEW, address: '10.9.0.5' }, + badkey: { person: 'a', public_key: 'not a key', address: '10.9.0.6' }, + badaddr: { person: 'a', public_key: PEER_NEW, address: '' }, + nobody: { person: 'gone', public_key: PEER_NEW, address: '10.9.0.7' }, + }, + }; + let st = { a: 'quota', b: 'paused', c: 'active' }; + eq(map(awg.tunnel_devices(m, 's', st), (d) => d.address), [ '10.9.0.2' ], + 'over the limit stays; off, paused, other servers, lines syncconf would refuse and the server\'s own key (ignored by the kernel) do not'); + eq(map(awg.tunnel_devices(m, 'other', st), (d) => d.address), [ '10.9.0.5' ], 'the other server'); + eq(awg.tunnel_devices(m, 'none', st), [], 'none'); +}); + +test('peer_diff: by key, per tunnel', () => { + let dmp = { peers: {} }; + dmp.peers[PEER_ON] = { ifname: 'awgmain' }; + dmp.peers[SERVER_KEY] = { ifname: 'awgmain' }; + dmp.peers[PEER_NEW] = { ifname: 'awgother' }; + let devs = (...ks) => map(ks, (k) => ({ public_key: k })); + eq(awg.peer_diff(devs(PEER_ON, SERVER_KEY), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 0 }, 'the same'); + eq(awg.peer_diff(devs(PEER_ON, PEER_NEW), dmp, 'awgmain'), { loaded: 2, missing: 1, extra: 1 }, + 'a stale peer standing in for a missing one'); + eq(awg.peer_diff(devs(PEER_ON), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 1 }, 'one too many'); + eq(awg.peer_diff(devs(PEER_NEW), dmp, 'awgdown'), { loaded: 0, missing: 1, extra: 0 }, 'a tunnel with no peers read'); + eq(awg.peer_diff([], { peers: {} }, 'awgmain'), { loaded: 0, missing: 0, extra: 0 }, 'nothing either way'); }); test('handshake_since: Reconnect hides older handshakes', () => { @@ -116,6 +349,60 @@ test('blocked reasons', () => { // Files of older versions hold the English fragment after the name. eq(awg.blocked_text(srv('has an invalid interface name "x"')), 'Home has an invalid interface name "x".', 'old fragment'); eq(awg.blocked_note({ code: 'ifname', ifname: 'x' }), 'has an invalid interface name "x"', 'the log keeps the fragment'); + // Values AmneziaWG refuses: which ones, from the server's own when read. + let bad = { name: 'Home', obf: { jmin: '60', jmax: '50' }, blocked: { code: 'disguise_invalid' } }; + eq(awg.blocked_text(bad), 'Home is kept down: its disguise has values AmneziaWG cannot take. Jmin must not be larger than Jmax.', 'invalid values'); + eq(awg.blocked_text({ ...bad, obf: {} }), 'Home is kept down: its disguise has values AmneziaWG cannot take.', 'fixed since'); + eq(awg.blocked_note(bad.blocked), 'is kept down: its disguise has values AmneziaWG cannot take', 'the log'); + eq(awg.blocked_fix(bad.blocked), 'Choose a disguise on the Server page: it replaces the values set by hand.', 'what to do about it'); + eq(awg.blocked_fix({ code: 'taken', ifname: 'wg0' }), 'Choose another interface name in the server settings.', 'what to do about a name'); +}); + +test('netifd_options: the server keeps its defence against handshake floods', () => { + let m = core.load(); + let srv = m.servers.main; + srv.obf = awg.obf_preset('max'); + let o = awg.netifd_options(srv); + ok('awg_disable_cookies' in o, 'named, so netifd.sync takes it off an interface that had it'); + eq(o.awg_disable_cookies, null, 'no DisableCookies on the server'); + eq([ o.awg_header_protection_key, o.awg_jc, o.awg_i1, o.awg_random_trailers ], [ srv.obf.header_protection_key, srv.obf.jc, srv.obf.i1, 'on' ], + 'the rest of the disguise stays'); + ok(index(split(awg.client_config(m, m.devices.alice_phone).conf, '\n'), 'DisableCookies = on') >= 0, 'devices keep it'); +}); + +test('client_config: one keep-alive for the .conf and the AmneziaVPN key', () => { + let m = core.load(); + let srv = m.servers.main, dev = m.devices.alice_phone; + let ka = () => { + let c = awg.client_config(m, dev); + return [ match(c.conf, /\nPersistentKeepalive = ([^\n]*)\n/)?.[1], c.amnezia.persistent_keep_alive ]; + }; + eq(ka(), [ '25', '25' ], 'a number without header protection'); + srv.obf = awg.obf_preset('max'); + eq(ka(), [ '25-35', '25-35' ], 'jittered with 3.1'); + srv.keepalive = 0; + eq(ka(), [ null, '0' ], 'off'); +}); + +test('status: the header protection key stays out of what read-only users get', () => { + eq(awg.obf_public({ jc: '4', header_protection_key: HPK }), { jc: '4' }, 'obf_public'); + eq(awg.obf_public(null), {}, 'no values'); + // Server main on Maximum, as a uci change not committed (the fixture file stays as it is). + let c = cursor(); + c.load('dawnline'); + let o = awg.obf_preset('max'); + for (let k, v in o) + c.set('dawnline', 'main', k, v); + c.save('dawnline'); + let out = rpc_status.methods.status.call({ args: { days: 30 } }); + c.revert('dawnline'); + eq(out.error, null, 'status answers'); + let srv = filter(out.servers ?? [], (x) => x.id == 'main')[0]; + eq([ srv?.hpk, srv?.obf?.header_protection_key, srv?.obf?.disable_cookies ], [ true, null, 'on' ], 'whether there is a key, not which'); + let text = sprintf('%J', out); + ok(index(text, o.header_protection_key) < 0, 'the key is nowhere in the answer'); + let found = uniq(map(match(text, /[A-Za-z0-9+\/]{43}=/g) ?? [], (x) => x[0])); + eq(found, [ srv.public_key ], 'no key but the server\'s public one'); }); test('client_config: an IPv6 endpoint in brackets, without a regex', () => { @@ -153,3 +440,117 @@ test('config_fingerprint leaves out the private key and the junk', () => { ok(awg.config_fingerprint(m, dev) != f, 'another port'); eq(awg.config_fingerprint(m, null), null, 'no device'); }); + +/* ---------- a device's local network, MTU and keep-alive ---------- */ + +// Exactly the complement: aligned prefixes, none overlapping another or a +// private range, and all of them together the whole address space. +test('BYPASS4: every IPv4 address outside the private ranges, once', () => { + let nets = [ ...map(awg.BYPASS4, (n) => [ n, false ]), ...map(nft.PRIVATE4, (n) => [ n, true ]) ]; + let total = 0; + for (let i = 0; i < length(nets); i++) { + let a = cidr_any(nets[i][0]); + ok(a && a.ip == a.net, `${nets[i][0]}: a prefix`); + total += a.size; + for (let j = i + 1; j < length(nets); j++) { + let b = cidr_any(nets[j][0]); + ok(a.net + a.size <= b.net || b.net + b.size <= a.net, `${nets[i][0]} and ${nets[j][0]} apart`); + } + } + eq(total, 4294967296, 'together: every address'); +}); + +test('BYPASS6: every IPv6 address outside fc00::/7, fe80::/10 and ff00::/8, once', () => { + // Each of them is /16 or wider: the first 16 bits decide. + let span = (n) => { + let p = split(n, '/'), len = +p[1]; + ok(len >= 1 && len <= 16 && substr(p[0], -2) == '::', `${n}: a prefix of the first 16 bits`); + let g = substr(p[0], 0, length(p[0]) - 2); + let start = g == '' ? 0 : hex(g), size = 1 << (16 - len); + ok(start % size == 0, `${n}: aligned`); + return [ start, size ]; + }; + let nets = map([ ...awg.BYPASS6, 'fc00::/7', 'fe80::/10', 'ff00::/8' ], span); + let total = 0; + for (let i = 0; i < length(nets); i++) { + total += nets[i][1]; + for (let j = i + 1; j < length(nets); j++) + ok(nets[i][0] + nets[i][1] <= nets[j][0] || nets[j][0] + nets[j][1] <= nets[i][0], `${i} and ${j} apart`); + } + eq(total, 65536, 'together: every address'); +}); + +test('allowed_ips: the local network outside the tunnel', () => { + let m = core.load(); + let srv = m.servers.main; + // No home network from the container's own interfaces. + srv.auto_lan = false; + srv.lan_devices = []; + let alice = m.people.alice, bob = m.people.bob; + eq(awg.allowed_ips(m, srv, bob), [ '0.0.0.0/0', '::/0' ], 'no device: everything'); + eq(awg.allowed_ips(m, srv, bob, { lan_bypass: false }), [ '0.0.0.0/0', '::/0' ], 'as before'); + let dns = (list) => [ ...slice(list, 0, 2), '10.9.0.1/32', ...slice(list, 2) ]; + eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'internet: the rest, and its DNS'); + eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...slice(awg.BYPASS4, 0, 2), '10.9.0.0/29', ...slice(awg.BYPASS4, 2), ...awg.BYPASS6 ], + 'home too: the tunnel network with the other devices (the DNS is in it)'); + srv.mesh = 'off'; + srv.device_mesh = false; + eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'no mesh: the router'); + srv.dns = [ '192.168.1.1', '192.168.1.53', 'fd00::53', '2001:4860:4860::8888', 'fe80::1' ]; + let all = awg.allowed_ips(m, srv, bob, { lan_bypass: true }); + ok(index(all, '192.168.1.1/32') >= 0 && index(all, '192.168.1.53/32') >= 0, 'every private IPv4 DNS server stays in the tunnel, not only the first'); + eq(slice(all, length(all) - length(awg.BYPASS6) - 2), [ ...awg.BYPASS6, 'fd00::53/128', 'fe80::1/128' ], + 'a private IPv6 one too; a public IPv6 one is in the rest already'); + eq(length(all), length(awg.BYPASS4) + 2 + length(awg.BYPASS6) + 2, 'nothing else'); + srv.dns = [ '1.1.1.1' ]; + eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'a public DNS is in the rest already'); + alice.access = 'lan'; + alice.dns_mode = 'home'; + let lan = awg.allowed_ips(m, srv, alice, { lan_bypass: true }); + eq(lan, awg.allowed_ips(m, srv, alice), 'Home only: the same either way'); + let c = awg.client_config(m, { ...m.devices.alice_phone, person: 'bob', lan_bypass: true }); + eq(c.amnezia.allowed_ips, [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'in the AmneziaVPN key'); + ok(index(c.conf, `AllowedIPs = ${join(', ', [ ...awg.BYPASS4, ...awg.BYPASS6 ])}\n`) >= 0, 'in the .conf'); +}); + +test('keepalive_range and idle_handshake', () => { + let srv = { keepalive: 25, obf: {} }; + eq(awg.keepalive_range(srv, {}), [ 25, 25 ], 'the server\'s, no range'); + eq(awg.keepalive_range(srv, { keepalive: 120 }), [ 120, 120 ], 'the device\'s own'); + eq(awg.keepalive_range(srv, { keepalive: 0 }), null, 'off for the device'); + eq(awg.keepalive_range({ keepalive: 0, obf: {} }, {}), null, 'off on the server'); + let max = { keepalive: 25, obf: awg.obf_preset('max') }; + eq(awg.keepalive_range(max, {}), [ 25, 35 ], 'jittered with 3.1'); + eq(awg.keepalive_range(max, { keepalive: 60 }), [ 60, 70 ], 'the device\'s own, jittered'); + // The first keep-alive after the rekey time (120 s; RekeyAfterTime's upper end) starts a handshake. + eq(awg.idle_handshake(srv, {}), 145, 'within the rekey time: up to one keep-alive past it'); + eq(awg.idle_handshake(max, {}), 155, 'Maximum: RekeyAfterTime 100-120, keep-alive up to 35'); + eq(awg.idle_handshake(srv, { keepalive: 100 }), 220, 'every second keep-alive'); + eq(awg.idle_handshake(srv, { keepalive: 300 }), 300, 'every keep-alive once they are further apart'); + eq(awg.idle_handshake({ keepalive: 25, obf: { rekey_after_time: '200-400' } }, {}), 205, 'past 180 s the key is refused anyway'); + eq(awg.idle_handshake(srv, { keepalive: 0 }), null, 'no keep-alive: none'); +}); + +test('client_config: the device\'s own MTU and keep-alive', () => { + let m = core.load(); + let dev = m.devices.alice_phone; + let line = (c, k) => match(c.conf, regexp(`\n${k} = ([^\n]*)\n`))?.[1]; + let c = awg.client_config(m, dev); + eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu ], [ '1280', '25', '1280' ], 'the server\'s (a phone)'); + let fp = awg.config_fingerprint(m, dev); + let old = { ...dev }; + delete old.mtu; + delete old.keepalive; + delete old.lan_bypass; + eq(awg.config_fingerprint(m, old), fp, 'a device without values of its own keeps its fingerprint (as before the options)'); + dev.mtu = 1420; + dev.keepalive = 0; + c = awg.client_config(m, dev); + eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu, c.amnezia.persistent_keep_alive ], [ '1420', null, '1420', '0' ], + 'its own; keep-alive off'); + ok(awg.config_fingerprint(m, dev) != fp, 'a change asks it to import again'); + m.servers.main.obf = awg.obf_preset('max'); + dev.keepalive = 120; + c = awg.client_config(m, dev); + eq([ line(c, 'PersistentKeepalive'), c.amnezia.persistent_keep_alive ], [ '120-130', '120-130' ], 'jittered with 3.1'); +}); diff --git a/tests/ucode/awg_builds.test.uc b/tests/ucode/awg_builds.test.uc new file mode 100644 index 0000000..4da2e5d --- /dev/null +++ b/tests/ucode/awg_builds.test.uc @@ -0,0 +1,59 @@ +// dawnline.awg_builds: the AmneziaWG generation of package and kernel module +// versions, whether an installed update waits for a reboot (its old module +// stayed loaded) and the generation that really runs meanwhile, which is +// what caps() reports. +import * as builds from 'dawnline.awg_builds'; +import * as awg from 'dawnline.awg'; + +// The live router's module (3.1) after an update from a 2.0 one that could not be swapped. +const KMOD_31 = '6.12.94.3.1.20260906-r1'; +const WAITING = { reloaded: false, boot: 'boot-1', prev_gen: '2.0', prev_core: 98304 }; + +test('gen of package versions', () => { + eq(builds.gen(null), null, 'not installed'); + eq(builds.gen('3.1.20260812-r1'), '3.1', 'amneziawg-tools 3.1'); + eq(builds.gen('3.1.0-r1'), '3.1', 'luci-proto-amneziawg 3.1'); + eq(builds.gen('1.0.20250722-r1'), '2.0', 'July 2025 on: 2.0'); + eq(builds.gen('1.0.20250901'), '2.0', 'no release suffix'); + eq(builds.gen('1.0.20250610-r1'), '1.0', 'before July 2025'); + eq(builds.gen('1.0.20241112-r2'), '1.0', '2024'); +}); + +test('gen of kernel module versions', () => { + eq(builds.gen(KMOD_31), '3.1', 'kernel release in front'); + eq(builds.gen('6.12.94.3.1.20260906'), '3.1', 'no release suffix'); + eq(builds.gen('6.6.73.1.0.20250722-r1'), '2.0', '2.0 module'); + eq(builds.gen('6.6.73.1.0.20250612-r1'), '1.0', 'first generation module'); + eq(builds.gen('5.15.150.1.0.20240711-r3'), '1.0', '2024 module on an older kernel'); + eq(builds.gen('3.1.20260812'), '3.1', 'the version.h string of a 3.1 module'); +}); + +test('pending: an update waits for a reboot', () => { + ok(builds.pending(WAITING, 'boot-1', 98304), 'the old module still loaded, same boot'); + ok(!builds.pending(WAITING, 'boot-2', 98304), 'rebooted'); + ok(!builds.pending(WAITING, 'boot-1', null), 'no module loaded: the next one is the new one'); + ok(!builds.pending(WAITING, 'boot-1', 110592), 'another module loaded (reloaded by hand)'); + ok(!builds.pending({ ...WAITING, reloaded: true }, 'boot-1', 98304), 'the install swapped it'); + ok(!builds.pending({ ...WAITING, reloaded: null }, 'boot-1', 98304), 'a record of a module Dawnline did not install'); + ok(!builds.pending({ osrelease: '6.12.94', source: 'slava', tag: 'v25.12.5', installed: 1 }, 'boot-1', 98304), + 'a record from before boots were kept'); + ok(!builds.pending({ ...WAITING, boot: null }, null, 98304), 'the kernel gave no boot id'); + ok(!builds.pending(null, 'boot-1', 98304), 'no record'); +}); + +test('caps: the generation that runs while a reboot is pending', () => { + eq(builds.running_gen(WAITING, 'boot-1', 98304, KMOD_31), '2.0', 'the 2.0 module runs, not the 3.1 package'); + eq(builds.running_gen(WAITING, 'boot-2', 98304, KMOD_31), '3.1', 'after the reboot: the package'); + eq(builds.running_gen(WAITING, 'boot-1', null, KMOD_31), '3.1', 'nothing loaded: the package loads'); + eq(builds.running_gen(null, 'boot-1', 98304, KMOD_31), '3.1', 'no record: the package'); + eq(builds.running_gen({ ...WAITING, prev_gen: null }, 'boot-1', 98304, KMOD_31), null, + 'a module installed by hand before: unknown, the tools are believed'); + eq(builds.running_gen(null, null, null, null), null, 'nothing installed'); +}); + +test('caps in a container without AmneziaWG', () => { + let c = awg.caps(); + eq(c.kmod, null, 'no module package'); + eq(c.pending, false, 'nothing waits for a reboot'); + eq(builds.module_core(), null, 'no module loaded'); +}); diff --git a/tests/ucode/core.test.uc b/tests/ucode/core.test.uc index 754f651..ae66ae0 100644 --- a/tests/ucode/core.test.uc +++ b/tests/ucode/core.test.uc @@ -1,6 +1,7 @@ // dawnline.core: the model read from the fixture config (real libuci), access // hours, quotas and the derived person state at an explicit time, address -// allocation, the automatic MTU, and other packages' port forwards. +// allocation, the automatic MTU, a device's own MTU, keep-alive and local +// network, and other packages' port forwards. import { readfile, writefile, unlink } from 'fs'; import * as core from 'dawnline.core'; @@ -28,6 +29,8 @@ test('load reads the fixture', () => { eq(m.settings.updates.interval, '7d', 'update policy from the same section'); eq(m.settings.updates.targets, [ 'app' ], 'update targets list'); eq(m.settings.retention.log_connections, '0', 'raw retention values'); + let d = m.devices.alice_phone; + eq([ d.mtu, d.keepalive, d.lan_bypass ], [ 0, null, false ], 'a device without link values of its own'); }); test('parse_hours', () => { @@ -129,6 +132,82 @@ test('tunnel_mtu / device_mtu', () => { eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone' }), 1280, 'phone'); eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer' }), 1380, 'computer'); eq(core.device_mtu({ mtu: 1200 }, { kind: 'tablet' }), 1200, 'a smaller tunnel MTU stays'); + eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone', mtu: 1420 }), 1420, 'the device\'s own, also above 1280 on a phone'); + eq(core.device_mtu({ mtu: 1420 }, { kind: 'computer', mtu: 1280 }), 1280, 'the device\'s own below the tunnel\'s'); + eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer', mtu: 9000 }), 1380, 'out of range (a hand edit): the automatic one'); + eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone', mtu: 0 }), 1280, '0: as before'); +}); + +test('device_keepalive', () => { + let srv = { keepalive: 25 }; + eq(core.device_keepalive(srv, { keepalive: null }), 25, 'the server\'s'); + eq(core.device_keepalive(srv, {}), 25, 'none read'); + eq(core.device_keepalive(srv, { keepalive: 0 }), 0, 'off for this device'); + eq(core.device_keepalive(srv, { keepalive: 120 }), 120, 'its own'); + eq(core.device_keepalive(srv, { keepalive: 700 }), 25, 'out of range: the server\'s'); + eq(core.device_keepalive({ keepalive: 0 }, { keepalive: 15 }), 15, 'its own on a server without keep-alive'); +}); + +/** A uci cursor that records what is written: { 'section.option': value or null (deleted) }. */ +function recorder() { + let w = {}; + return { w, c: { set: (cfg, s, k, v) => { w[`${s}.${k}`] = v; }, delete: (cfg, s, k) => { w[`${s}.${k}`] = null; } } }; +} + +test('set_device_link', () => { + let mm = { devices: { d: { id: 'd', mtu: 0, keepalive: null, lan_bypass: false } } }; + let r = recorder(); + eq(core.set_device_link(r.c, mm, 'd', { mtu: '1400', keepalive: '0', lan_bypass: true }), [ 'mtu', 'keepalive', 'lan_bypass' ], 'what changed'); + eq(r.w, { 'd.mtu': '1400', 'd.keepalive': '0', 'd.lan_bypass': '1' }, 'written'); + r = recorder(); + mm.devices.d = { id: 'd', mtu: 1400, keepalive: 0, lan_bypass: true }; + eq(core.set_device_link(r.c, mm, 'd', { mtu: '', keepalive: '', lan_bypass: false }), [ 'mtu', 'keepalive', 'lan_bypass' ], 'back'); + eq(r.w, { 'd.mtu': null, 'd.keepalive': null, 'd.lan_bypass': null }, 'removed: the server\'s again'); + r = recorder(); + eq(core.set_device_link(r.c, mm, 'd', { mtu: '1400', keepalive: ' 0 ' }), [], 'the same values change nothing'); + eq(r.w, {}, 'nothing written'); + eq(core.set_device_link(r.c, mm, 'd', {}), [], 'nothing asked'); + throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1279' }), /^MTU must be 1280-1500\.$/, 'MTU too small'); + throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1501' }), /^MTU must be 1280-1500\.$/, 'MTU too large'); + throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1400.5' }), /^MTU/, 'not a whole number'); + throws(() => core.set_device_link(r.c, mm, 'd', { keepalive: '601' }), /^Keep-alive must be 0-600 seconds\.$/, 'keep-alive too long'); + throws(() => core.set_device_link(r.c, mm, 'd', { keepalive: '-1' }), /^Keep-alive/, 'negative'); + throws(() => core.set_device_link(r.c, mm, 'x', { mtu: '' }), /^Unknown device\.$/, 'unknown device'); +}); + +test('create_device: the local network outside the tunnel', () => { + let mm = core.load(); + let r = recorder(); + let keys = { public_key: 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', preshared_key: '' }; + let id = core.create_device(r.c, mm, 'bob', 'Laptop', 'computer', { keys, lan_bypass: true }); + eq([ r.w[`${id}.lan_bypass`], mm.devices[id].lan_bypass, mm.devices[id].mtu, mm.devices[id].keepalive ], [ '1', true, 0, null ], 'set'); + r = recorder(); + id = core.create_device(r.c, mm, 'bob', 'Tablet', 'tablet', { keys: { ...keys, public_key: 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=' } }); + ok(!(`${id}.lan_bypass` in r.w) && !mm.devices[id].lan_bypass, 'off unless asked'); +}); + +test('create_device: not with the server\'s own key', () => { + let mm = core.load(); + let keys = { public_key: mm.servers.main.public_key, preshared_key: '' }; + throws(() => core.create_device(recorder().c, mm, 'bob', 'Laptop', 'computer', { keys }), /^This key is already in use\.$/, + 'it is in every configuration of the server'); + mm.devices.alice_phone.public_key = mm.servers.main.public_key; + eq(core.model_errors(mm), [ "Device Phone of Alice: the public key is the server's own." ], 'one set by hand is named'); +}); + +test('model_errors: a device\'s own MTU and keep-alive', () => { + let mm = core.load(); + eq(core.model_errors(mm), [], 'the fixture is consistent'); + let d = mm.devices.alice_phone; + d.mtu = 1400; + d.keepalive = 0; + eq(core.model_errors(mm), [], 'values of its own in range'); + d.mtu = 9000; + d.keepalive = 601; + eq(core.model_errors(mm), [ + 'Device Phone of Alice: MTU 9000 is not between 1280 and 1500.', + 'Device Phone of Alice: keep-alive 601 is not between 0 and 600 seconds.', + ], 'named'); }); test('names and codes', () => { diff --git a/tests/ucode/devices.test.uc b/tests/ucode/devices.test.uc new file mode 100644 index 0000000..a32315a --- /dev/null +++ b/tests/ucode/devices.test.uc @@ -0,0 +1,67 @@ +// The admin's device methods (dawnline.rpc.people over dawnline.devices): what +// counts as handing a configuration out, and New keys as setting the device up +// again. The real calls on the fixture: the stand-in awg makes the keys, the +// sync's nft and awg steps fail harmlessly in the container. /etc/config/dawnline +// and the issued and reconnect marks are put back after. +import { readfile, writefile, unlink } from 'fs'; +import { DATA_DIR, ensure_dir } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as awg from 'dawnline.awg'; +import * as people from 'dawnline.rpc.people'; + +const CONFIG = '/etc/config/dawnline'; +const ISSUED = `${DATA_DIR}/issued.json`; +const RECONNECT = `${DATA_DIR}/reconnect.json`; + +// fn(), then the files as they were, whatever fn did. +function kept(paths, fn) { + let had = map(paths, (p) => readfile(p)); + let err = null; + try { + fn(); + } + catch (e) { + err = e; + } + for (let i = 0; i < length(paths); i++) + had[i] == null ? unlink(paths[i]) : writefile(paths[i], had[i]); + if (err) + die(err.message ?? `${err}`); +} + +function call(name, args) { + return people.methods[name].call({ args }); +} + +test('device_config: a look marks nothing, a delivery does', () => { + ensure_dir(DATA_DIR, 0o700); + kept([ ISSUED ], () => { + let old = sprintf('%J', { alice_phone: '00000000' }); + writefile(ISSUED, old); + ok(index(call('device_config', { id: 'alice_phone' }).conf ?? '', '[Peer]') >= 0, 'the configuration comes back'); + eq(readfile(ISSUED), old, 'without issue: issued.json left alone'); + call('device_config', { id: 'alice_phone', issue: false }); + eq(readfile(ISSUED), old, 'issue false: the same'); + call('device_config', { id: 'alice_phone', issue: true }); + let m = core.load(); + eq(awg.issued().alice_phone, awg.config_fingerprint(m, m.devices.alice_phone), 'issue: what it holds now counts as handed out'); + eq(call('device_config', { id: 'nobody', issue: true }).error, 'Unknown device.', 'an unknown device'); + }); +}); + +test('device_rotate: New keys set the device up again', () => { + kept([ CONFIG, ISSUED, RECONNECT ], () => { + unlink(RECONNECT); + let before = core.load().devices.alice_phone; + let t0 = time(); + let c = call('device_rotate', { id: 'alice_phone' }); + ok(c.error == null && index(c.conf ?? '', '[Peer]') >= 0, `the new configuration comes back (${c.error})`); + let m = core.load(); + ok(m.devices.alice_phone.preshared_key != before.preshared_key, 'new keys'); + let at = awg.reconnects().alice_phone; + ok(at >= t0 && at <= time(), `a reconnect mark at the rotation (${at})`); + eq(awg.handshake_since(t0 - 30, at), 0, "the old keys' last handshake no longer counts: Not set up yet, with Connect"); + eq(awg.issued().alice_phone, awg.config_fingerprint(m, m.devices.alice_phone), 'its new configuration is the one handed out'); + }); + eq(core.load().devices.alice_phone.private_key, '', 'the fixture is back'); +}); diff --git a/tests/ucode/fixtures/bin/awg b/tests/ucode/fixtures/bin/awg index e550469..559fdee 100755 --- a/tests/ucode/fixtures/bin/awg +++ b/tests/ucode/fixtures/bin/awg @@ -1,10 +1,29 @@ #!/bin/sh # Stand-in for amneziawg-tools in the ucode tests (no kernel module in a -# container): `genkey` prints one fixed key, `show all dump` prints the fixture -# a test has put at /tmp/dawnline-tests/awg-dump (or fails, as the tool does -# when no interface is up). Anything else fails. +# container): `genkey` prints one fixed key, `pubkey` (a key on stdin) the +# fixture server's public key, its pair; `show dump` prints that +# interface's lines of the fixture a test has put at /tmp/dawnline-tests/awg-dump +# (written as `awg show all dump` prints them: the ifname first, left out here, +# as the tool does), fails as the tool does for an interface that is not there, +# and fails with the text of /tmp/dawnline-tests/awg-fail- when a test +# put one. Every call is appended to /tmp/dawnline-tests/awg-calls. Anything +# else fails. +T=/tmp/dawnline-tests +echo "$*" >> "$T/awg-calls" case "$1 ${2:-} ${3:-}" in 'genkey ') echo 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=' ;; - 'show all dump') cat /tmp/dawnline-tests/awg-dump ;; + 'pubkey ') cat >/dev/null; echo 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=' ;; + 'show '*' dump') + if [ -e "$T/awg-fail-$2" ]; then + cat "$T/awg-fail-$2" >&2 + exit 1 + fi + out="$(awk -F '\t' -v i="$2" '$1 == i { sub(/^[^\t]*\t/, ""); print }' "$T/awg-dump" 2>/dev/null)" + if [ -z "$out" ]; then + echo 'Unable to access interface: No such device' >&2 + exit 1 + fi + printf '%s\n' "$out" + ;; *) echo "awg stand-in: unsupported arguments: $*" >&2; exit 1 ;; esac diff --git a/tests/ucode/fixtures/config/dawnline b/tests/ucode/fixtures/config/dawnline index 2e1b2de..634a8da 100644 --- a/tests/ucode/fixtures/config/dawnline +++ b/tests/ucode/fixtures/config/dawnline @@ -41,4 +41,4 @@ config device 'alice_phone' option name 'Phone' option kind 'phone' option address '10.9.0.2' - option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=' + option public_key 'AuTb2wZ8C1032Ksn76nFgXzOJgT86OgEVbEE7ClpNy8=' diff --git a/tests/ucode/fixtures/nft-table.txt b/tests/ucode/fixtures/nft-table.txt new file mode 100644 index 0000000..aa81b09 --- /dev/null +++ b/tests/ucode/fixtures/nft-table.txt @@ -0,0 +1,57 @@ +table inet dawnline { + set home_home { type ipv4_addr; flags interval; auto-merge; elements = { 192.168.1.0/24 } } + set home_work { type ipv4_addr; flags interval; auto-merge; elements = { 192.168.1.0/24 } } + set tun_nets { type ipv4_addr; flags interval; auto-merge; elements = { 10.9.0.0/29, 10.9.1.0/29 } } + set lan_ok { type ipv4_addr; elements = { 10.9.0.2, 10.9.0.3, 10.9.1.3 } } + set lan_all { type ipv4_addr; elements = { 10.9.0.2, 10.9.0.3, 10.9.1.3 } } + set lan_part { type ipv4_addr . ipv4_addr; flags interval; } + set mesh_pairs { type ipv4_addr . ipv4_addr; } + set inet_ok { type ipv4_addr; elements = { 10.9.0.2, 10.9.1.2, 10.9.0.4, 10.9.0.5, 10.9.1.3 } } + set svc_ok { type ipv4_addr . ipv4_addr . inet_service; } + set svc_host { type ipv4_addr . ipv4_addr; } + set dns_real { type ipv4_addr; elements = { 10.9.0.3 } } + chain pre { + type filter hook prerouting priority -160; policy accept; + iifname { "awghome", "awgwork" } jump guard + } + chain guard { + meta nfproto ipv6 drop + ct state related accept + ct status dnat accept + icmp type { echo-request, echo-reply } fib daddr type local accept + fib daddr type local meta l4proto { tcp, udp } th dport 53 accept + fib daddr type local tcp dport { 8443 } accept + fib daddr type local ip saddr @lan_all accept + fib daddr type local ip saddr . ip daddr @lan_part accept + fib daddr type local counter drop + ip daddr 192.168.1.250 meta l4proto { tcp, udp } th dport 53 accept + iifname "awghome" ip daddr @home_home ip daddr != @tun_nets ip saddr @lan_all accept + iifname "awgwork" ip daddr @home_work ip daddr != @tun_nets ip saddr @lan_all accept + ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept + iifname "awghome" ip saddr @lan_ok ip daddr @lan_ok accept + iifname "awgwork" ip saddr . ip daddr @mesh_pairs accept + meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept + ip saddr . ip daddr @svc_host accept + ip daddr { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, 169.254.0.0/16, 224.0.0.0/3 } counter drop + ip saddr @inet_ok accept + counter drop + } + chain inbound { + type filter hook forward priority filter - 5; policy accept; + oifname { "awghome", "awgwork" } iifname != { "awghome", "awgwork" } ct state new jump to_device + } + chain to_device { + meta nfproto ipv6 drop + ct status dnat accept + oifname "awghome" ip saddr @home_home ip saddr != @tun_nets ip daddr @lan_all accept + oifname "awgwork" ip saddr @home_work ip saddr != @tun_nets ip daddr @lan_all accept + ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept + counter reject with icmpx admin-prohibited + } + chain dns { + type nat hook prerouting priority dstnat - 5; policy accept; + iifname { "awghome", "awgwork" } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 dnat ip to 169.254.77.2:53 + iifname "awghome" ip daddr 10.9.0.1 meta l4proto { tcp, udp } th dport 53 dnat ip to 192.168.1.250:53 + iifname "awgwork" ip daddr 10.9.1.1 meta l4proto { tcp, udp } th dport 53 dnat ip to 192.168.1.1:53 + } +} diff --git a/tests/ucode/health.test.uc b/tests/ucode/health.test.uc new file mode 100644 index 0000000..0ef38e4 --- /dev/null +++ b/tests/ucode/health.test.uc @@ -0,0 +1,109 @@ +// dawnline.health: where a public address points, in words. The name's AAAA +// records are checked against the router's public IPv6 addresses as well as +// its A records against the WAN. The facts take a test's reads instead of +// DNS, the WAN and `ip`. +import * as health from 'dawnline.health'; + +const HOST = 'vpn.example.com'; +const WAN = '203.0.113.7'; +// The WAN's own address and the LAN's from the delegated prefix: both reach the router. +const ROUTER6 = [ '2001:db8:1::1', '2001:db8:2::1' ]; + +function facts(ips, router6, wan) { + return health.endpoint_facts(null, HOST, { ips, wan, router6 }); +} + +function words(ips, router6, wan) { + return health.endpoint_words(facts(ips, router6, wan), 'UDP 51820'); +} + +test('own_ipv6: public addresses on any interface', () => { + let links = [ + { ifname: 'wan', addr_info: [ { family: 'inet6', local: '2001:db8:1::1', prefixlen: 128, scope: 'global' } ] }, + { ifname: 'br-lan', addr_info: [ + { family: 'inet6', local: '2001:db8:2::1', prefixlen: 64, scope: 'global' }, + { family: 'inet6', local: 'fd12:3456:789a::1', prefixlen: 60, scope: 'global' }, + { family: 'inet6', local: '2001:db8:2::99', prefixlen: 64, scope: 'global', dadfailed: true }, + ] }, + { ifname: 'lan2', addr_info: [ { family: 'inet6', local: 'FC00::1', prefixlen: 64, scope: 'global' } ] }, + { ifname: 'lo' }, + ]; + eq(health.own_ipv6(links), ROUTER6, 'the WAN and the LAN prefix; no ULA, no failed duplicate'); + eq(health.own_ipv6([ links[1] ]), [ '2001:db8:2::1' ], 'only the LAN has one'); + eq(health.own_ipv6([ { ifname: 'br-lan', addr_info: [ links[1].addr_info[1] ] } ]), [], 'only a ULA: none'); + eq(health.own_ipv6(null), [], 'nothing read'); +}); + +test('endpoint_facts: AAAA records against the router', () => { + let f = facts([ WAN, '2001:db8:2::1' ], ROUTER6, WAN); + eq([ f.here, f.here6, f.foreign6 ], [ true, true, [] ], 'both records are the router'); + eq(facts([ WAN, '2001:DB8:2:0:0::1' ], ROUTER6, WAN).here6, true, 'another spelling of the same address'); + f = facts([ WAN, '2001:db8:2::1', '2001:db8:9::5' ], ROUTER6, WAN); + eq([ f.here6, f.foreign6 ], [ false, [ '2001:db8:9::5' ] ], 'one of two is not'); + f = facts([ WAN, '2001:db8:9::5' ], [], WAN); + eq([ f.here6, f.foreign6, f.router6 ], [ false, [ '2001:db8:9::5' ], [] ], 'the router has no IPv6: none is'); + f = facts([ WAN, '2001:db8:9::5' ], null, WAN); + eq([ f.here6, f.foreign6, f.router6 ], [ false, null, null ], 'unknown: no verdict'); + eq(facts([ WAN ], ROUTER6, WAN).here6, false, 'no AAAA'); +}); + +test('endpoint_words: IPv4 and IPv6 both at the router', () => { + eq(words([ WAN, '2001:db8:2::1' ], ROUTER6, WAN), + { status: 'ok', text: 'vpn.example.com points at this router (203.0.113.7, 2001:db8:2::1).' }, 'A and AAAA'); + eq(words([ WAN ], null, WAN), { status: 'ok', text: 'vpn.example.com points at this router (203.0.113.7).' }, 'A only, as before'); + eq(words([ WAN, '2001:db8:9::5' ], null, WAN).status, 'ok', 'the router\'s IPv6 unknown: the AAAA gets no verdict'); +}); + +test('endpoint_words: an AAAA record that is not the router', () => { + eq(words([ WAN, '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn', + text: 'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.' }, + 'a stale prefix'); + eq(words([ WAN, '2001:db8:9::5', '2001:db8:9::6' ], ROUTER6, WAN).text, + 'vpn.example.com AAAA → 2001:db8:9::5, 2001:db8:9::6 are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.', + 'two of them'); + eq(words([ WAN, '2001:db8:2::1', 'fd12:3456:789a::1' ], ROUTER6, WAN).text, + 'vpn.example.com AAAA → fd12:3456:789a::1 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.', + 'a ULA beside the right one'); + eq(words([ WAN, '2001:db8:9::5' ], [], WAN), { status: 'warn', + text: 'vpn.example.com AAAA → 2001:db8:9::5, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.' }, + 'the router has no IPv6'); + eq(words([ '198.51.100.4', '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn', + text: 'vpn.example.com points at 198.51.100.4, not this router (WAN 203.0.113.7). Check your DNS / DDNS. ' + + 'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.' }, + 'both wrong: two sentences, IPv4 first'); + eq(words([ '198.51.100.4', '2001:db8:2::1' ], ROUTER6, WAN).text, + 'vpn.example.com points at 198.51.100.4, not this router (WAN 203.0.113.7). Check your DNS / DDNS.', 'only the A record wrong: as before'); + eq(words([ '198.51.100.4', '2001:db8:9::5' ], ROUTER6, null).text, + 'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.', + 'no WAN address: the AAAA alone'); +}); + +test('endpoint_words: IPv6 only', () => { + eq(words([ '2001:db8:2::1' ], ROUTER6, WAN), { status: 'warn', + text: "vpn.example.com → 2001:db8:2::1: IPv6 only, so only devices with IPv6 connect (the router's IPv4 203.0.113.7 has no name)." }, + 'the v6_only wording stays'); + eq(words([ '2001:db8:2::1' ], ROUTER6, '100.64.1.2'), + { status: 'ok', text: 'vpn.example.com → 2001:db8:2::1: IPv6 only, so only devices with IPv6 connect.' }, 'behind CGNAT, as before'); + eq(words([ '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn', + text: 'vpn.example.com → 2001:db8:9::5: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.' }, + 'not the router'); + eq(words([ '2001:db8:9::5', '2001:db8:9::6' ], ROUTER6, WAN).text, + 'vpn.example.com → 2001:db8:9::5, 2001:db8:9::6: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.', + 'two, neither the router'); + eq(words([ '2001:db8:9::5' ], [], '100.64.1.2'), { status: 'warn', + text: 'vpn.example.com → 2001:db8:9::5: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.' }, + 'the router has no IPv6'); + eq(words([ '2001:db8:2::1', '2001:db8:9::5' ], ROUTER6, WAN).text, + 'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.', + 'one right, one wrong'); + eq(words([ '2001:db8:9::5' ], null, WAN).text, + "vpn.example.com → 2001:db8:9::5: IPv6 only, so only devices with IPv6 connect (the router's IPv4 203.0.113.7 has no name).", + 'the router\'s IPv6 unknown: as before'); +}); + +test('common home subnets', () => { + eq(health.common_home([ '192.168.1.0/24', '10.0.1.0/24' ]), [ '192.168.1.0/24' ], 'the out-of-the-box /24 only'); + eq(health.common_home([ '192.168.0.0/16' ]), [ '192.168.0.0/16' ], 'a wider network that holds one'); + eq(health.common_home([ '10.37.12.0/24', '172.20.0.0/24' ]), [], 'rare ones'); + eq(health.common_home(null), [], 'none'); +}); diff --git a/tests/ucode/link.test.uc b/tests/ucode/link.test.uc new file mode 100644 index 0000000..85e207b --- /dev/null +++ b/tests/ucode/link.test.uc @@ -0,0 +1,332 @@ +// dawnline.link: what a device's counters say about its link, on synthetic +// sequences of one read a second, run the way the agent's watcher runs them +// (observe, the set-up state at once, then classify and settle when +// something happened or CHECK_EVERY passed); and the pieces on their own. +import * as link from 'dawnline.link'; + +const T0 = 1800000000; +const A = '203.0.113.7:41821', B = '198.51.100.4:50123'; + +/* + * `seconds` reads from T0. `at(s)` gives what happened in second s: { drx, + * dtx (bytes in, out), hs (a handshake completed), ep (the endpoint now), + * gone (the peer is not in the tunnel) }. Returns the history, the changes + * of what is shown: [ { s, from, to, since (seconds from T0), ev } ], those of + * the set-up state: [ { s, state } ], and the seconds where the set-up state + * kept by setup() was not what setup_state() gives then (it should never be). + */ +function run(seconds, at, opts) { + opts ??= {}; + let ka = opts.ka ?? link.KEEPALIVE, window = opts.window ?? 190; + let h = link.fresh(T0); + let peer = { endpoint: opts.ep ?? A, handshake: opts.hs0 ?? 0, rx: 1000, tx: 1000 }; + let changes = [], raws = {}, setups = [], lag = []; + for (let s = 0; s < seconds; s++) { + let t = T0 + s, x = at(s) ?? {}; + peer.rx += x.drx ?? 0; + peer.tx += x.dtx ?? 0; + if (x.hs) + peer.handshake = t; + if (x.ep) + peer.endpoint = x.ep; + let on = peer.handshake > 0 && t - peer.handshake < window; + let moved = false; + if (x.gone) + link.gone(h); + else + moved = link.observe(h, peer, t, ka); + if (link.setup(h, t, on, moved)) + push(setups, { s, state: h.setup?.state ?? null }); + if (link.setup_state(h, t, on).state != (h.setup?.state ?? null)) + push(lag, s); + if (!moved && t - h.checked < link.CHECK_EVERY) + continue; + h.checked = t; + link.prune(h, t); + h.raw = link.classify(h, t, on); + if (h.raw) + raws[h.raw] ??= s; + let ch = link.settle(h, h.raw, t, on); + if (ch) + push(changes, { s, from: ch.from, to: ch.to, since: h.since ? h.since - T0 : 0, + ev: link.event_for(ch, { id: 'd_1', person: 'p_1' }, on)?.type ?? null }); + } + return { h, changes, raws, setups, lag }; +} + +// A phone in use: keep-alive 25 s, new keys every ~125 s (the initiation in +// one second, the packet that confirms it in the next), something sent or +// received now and then. +function phone(s, busy) { + let x = {}; + if (s % 125 == 3) + x = { drx: 148, dtx: 92 }; + else if (s % 125 == 4) + x = { hs: true, drx: 32 }; + else if (s % 25 == 0) + x = { drx: 32 }; + if (busy && s % 30 < 4) + x = { ...x, drx: (x.drx ?? 0) + 1400, dtx: (x.dtx ?? 0) + 9000 }; + return x; +} + +test('no state for a phone in use', () => { + let r = run(1800, (s) => phone(s, true)); + eq(r.changes, [], 'half an hour of normal use'); + eq(r.raws, {}, 'not even for a moment'); +}); + +test('no state for a sleeping phone', () => { + eq(run(1800, (s) => phone(s, false)).changes, [], 'keep-alives and new keys only'); + // Then it stops sending at all (deep sleep, out of range): it goes offline, nothing else. + let r = run(1200, (s) => s < 300 ? phone(s, false) : {}); + eq(r.changes, [], 'silent after five minutes'); + eq(r.raws, {}, 'silence is no failure'); + // The same with the disguise's content padding: keep-alives of 42-132 bytes. + eq(run(1800, (s) => s % 25 == 0 ? { drx: 42 + (s % 90) } : phone(s, false), { ka: 132 }).changes, [], 'padded keep-alives'); +}); + +test('no state for a phone that left with traffic still coming', () => { + // Online and busy until 100 s, then gone; the internet keeps sending to it for a while. + let at = (s) => s < 100 ? phone(s, true) : (s % 3 == 0 ? { dtx: 1400 } : {}); + eq(run(900, at).changes, [], 'the online window ends it'); + eq(run(900, at, { window: 400 }).changes, [], 'a long keep-alive window: no handshake within DROP_HS ends it'); +}); + +test('trying: knocks that never finish connecting', () => { + // Never connected: an initiation every 5 s for 90 s, then a pause, again and again. + let knocking = (s) => (s % 120 < 90 && s % 5 == 0) ? { drx: 148, dtx: 92 } : {}; + let r = run(600, knocking); + // The first read is the baseline: the knocks count from 5 s. + eq(r.raws.trying, 15, 'from the third accepted initiation'); + eq(r.changes[0], { s: 195, from: null, to: 'trying', since: 15, ev: 'device_failing' }, 'shown once it held 3 minutes'); + eq(length(r.changes), 1, 'and kept through the pauses'); + // It gets through at 400 s: working again at once. + let r2 = run(600, (s) => s < 400 ? knocking(s) : (s == 400 ? { hs: true, drx: 148 + 1400, dtx: 4000 } : phone(s, true))); + eq(r2.changes[1], { s: 400, from: 'trying', to: null, since: 0, ev: 'device_recovered' }, 'connected: recovered'); + // It gives up (the app was turned off): the state goes without a "recovered". + let r3 = run(1200, (s) => s < 300 ? knocking(s) : {}); + eq(r3.changes[1].to, null, 'cleared'); + eq(r3.changes[1].ev, null, 'nobody saw it work'); + // The last knock at 295 s: it ages out of TRY_SPAN by 415 s, and HOLD passes by 595 s. + eq(r3.changes[1].s, 595, 'only after the knocks aged out and HOLD passed'); +}); + +test('trying after a session that ran out', () => { + // Online until 200 s; then its new keys never complete (the answers are lost). + let at = (s) => s < 200 ? phone(s, true) : (s % 5 == 0 ? { drx: 148, dtx: 92 } : {}); + let r = run(900, at); + eq(r.changes[0].to, 'trying', 'after the online window'); + ok(r.changes[0].s > 129 + 190, 'not while the old session still counted'); +}); + +test('shared: one configuration on two devices', () => { + // Each takes the session from the other every 20 s; the endpoint flips with every packet. + let r = run(600, (s) => ({ hs: s % 20 == 0, drx: 2000, dtx: 6000, ep: s % 2 ? B : A })); + eq(r.raws.shared, 60, 'from the fourth handshake'); + eq(r.changes[0], { s: 240, from: null, to: 'shared', since: 60, ev: 'device_failing' }, 'shown once it held'); + eq(r.raws.unstable, null, 'never taken for a breaking connection'); + // Two devices behind one NAT: one address, two ports. + let r2 = run(600, (s) => ({ hs: s % 20 == 0, drx: 2000, dtx: 6000, ep: s % 2 ? '203.0.113.7:1111' : '203.0.113.7:2222' })); + eq(r2.changes[0]?.to, 'shared', 'told apart by port'); +}); + +test('unstable: connecting over and over from one place', () => { + let r = run(600, (s) => ({ hs: s % 20 == 0, drx: s % 20 < 5 ? 3000 : 0, dtx: s % 20 < 5 ? 9000 : 0 })); + eq(r.raws.unstable, 60, 'from the fourth quick handshake'); + eq(r.changes[0], { s: 240, from: null, to: 'unstable', since: 60, ev: 'device_failing' }, 'shown once it held'); + // Moving once (wifi to mobile) while it breaks is still the connection, not a second device. + let r2 = run(600, (s) => ({ hs: s % 20 == 0, drx: 3000, dtx: 9000, ep: s < 100 ? A : B })); + eq(r2.changes[0]?.to, 'unstable', 'one move is no alternation'); + // It settles down: working again once the quick handshakes left the span. + let r3 = run(1200, (s) => s < 300 ? { hs: s % 20 == 0, drx: 3000, dtx: 9000 } : phone(s, true)); + eq(r3.changes[1]?.to, null, 'cleared'); + eq(r3.changes[1]?.ev, 'device_recovered', 'online: recovered'); + // Normal key renewals never churn, even at RekeyAfterTime's shortest (100 s). + eq(run(1800, (s) => ({ hs: s % 100 == 0, drx: s % 25 == 0 ? 32 : 0 })).changes, [], '3.1 timers'); +}); + +/* + * An old address after renumbering: every packet it sends is dropped after + * decryption (not counted in rx), the router answers with a keepalive every + * ~10 s, the device renews its keys every ~125 s (the first packet under them + * is data, so only the initiation shows in rx). + */ +function renumbered(s) { + if (s % 125 == 3) + return { drx: 148, dtx: 92 }; + if (s % 125 == 4) + return { hs: true }; + return s % 10 == 7 ? { dtx: 32 } : {}; +} + +test('dropped: connected, but nothing it sends gets through', () => { + let r = run(900, renumbered, { hs0: T0 - 30 }); + // Classified on the router's next answer after DROP_SPAN (187 s). + eq(r.raws.dropped, 187, 'once DROP_SPAN passed without data'); + eq(r.changes[0], { s: 367, from: null, to: 'dropped', since: 187, ev: 'device_failing' }, 'shown once it held'); + // Imported again at 500 s: data flows, working at once. + let r2 = run(900, (s) => s < 500 ? renumbered(s) : (s == 500 ? { hs: true, drx: 3000, dtx: 9000 } : phone(s, true)), { hs0: T0 - 30 }); + eq(r2.changes[1], { s: 500, from: 'dropped', to: null, since: 0, ev: 'device_recovered' }, 'recovered'); + // With the disguise's padding the router's answers are bigger; still under DROP_TX. + let r3 = run(900, (s) => { let x = renumbered(s); if (x.dtx == 32) x.dtx = 32 + 1400; return x; }, { hs0: T0 - 30, ka: 132 }); + eq(r3.changes[0]?.to, 'dropped', 'padded answers'); + // Not before the history covers DROP_SPAN (the agent just started). + eq(run(170, renumbered, { hs0: T0 - 30 }).raws, {}, 'too early to tell'); +}); + +test('counters that restart are a new baseline', () => { + let h = link.fresh(T0); + let peer = { endpoint: A, handshake: T0, rx: 50000, tx: 90000 }; + link.observe(h, peer, T0, 32); + peer.rx = 148; + peer.tx = 92; + link.observe(h, peer, T0 + 1, 32); + eq([ h.rx, h.tx, length(h.knocks), h.data ], [ 148, 92, 0, 0 ], 'the peer was added again: no knock, no data'); + link.gone(h); + eq(h.rx, null, 'not in the tunnel'); + eq(link.observe(h, { ...peer, rx: 5000 }, T0 + 2, 32), false, 'back: a baseline, nothing counted'); + eq(h.data, 0, 'no data from the jump'); +}); + +test('knock and bare', () => { + eq([ link.knock(148), link.knock(296), link.knock(444) ], [ true, true, true ], 'one to three initiations'); + eq([ link.knock(592), link.knock(180), link.knock(0) ], [ false, false, false ], 'too many, with something else, nothing'); + eq([ link.bare(32, 32, false), link.bare(0, 32, false), link.bare(180, 32, true), link.bare(124, 32, true), link.bare(92, 32, true) ], + [ true, true, true, true, true ], 'keepalive, nothing; in a handshake\'s second: initiation + keepalive, response + keepalive, response'); + // Plain data is 32 + a multiple of 16: an IPv4 header alone is 64, a TCP ACK 80 or 96. + eq([ link.bare(64, 32, false), link.bare(80, 32, true), link.bare(96, 32, false), link.bare(1480, 32, true), link.bare(5000, 32, false) ], + [ false, false, false, false, false ], 'data'); + eq([ link.bare(180, 32, false), link.bare(124, 32, false), link.bare(92, 32, false) ], [ false, false, false ], + 'handshake messages only count in the second a handshake completed'); + // Padding makes it fuzzy: in a handshake's second anything up to three initiations, a response and a + // padded keepalive; in any other second one padded keepalive, never more. + eq([ link.bare(100, 132, false), link.bare(148 + 132, 132, true), link.bare(3 * 148 + 92 + 132, 132, true), link.bare(3 * 148 + 92 + 133, 132, true) ], + [ true, true, true, false ], 'padded keepalives'); + eq([ link.bare(133, 132, false), link.bare(148 + 52, 132, false), link.bare(668, 132, false) ], [ false, false, false ], + 'small packets on Maximum: data'); +}); + +test('keepalive_max', () => { + eq(link.keepalive_max(null), 32, 'no server'); + eq(link.keepalive_max({ obf: {} }), 32, 'no disguise'); + eq(link.keepalive_max({ obf: { content_padding_addition: '10-100' } }), 132, 'content padding'); + eq(link.keepalive_max({ obf: { content_padding_addition: '40' } }), 72, 'a fixed padding'); + eq(link.keepalive_max({ obf: { content_padding_addition: '10-100', random_trailers: 'on' } }), 132, 'content padding wins over trailers'); + eq(link.keepalive_max({ obf: { random_trailers: 'on' } }), 1532, 'random trailers: up to a full packet'); + let m = { servers: { s_1: { obf: { content_padding_addition: '10-100' } } }, people: { p_1: { server: 's_1' } }, + devices: { d_1: { person: 'p_1' }, d_2: { person: 'p_gone' } } }; + eq(link.keepalive_sizes(m), { d_1: 132, d_2: 32 }, 'per device'); +}); + +test('settle holds a state before it shows', () => { + let h = link.fresh(T0); + eq(link.settle(h, 'trying', T0, false), null, 'new: waits'); + eq(link.settle(h, 'trying', T0 + link.HOLD - 1, false), null, 'still waits'); + eq(link.settle(h, 'trying', T0 + link.HOLD, false), { from: null, to: 'trying' }, 'held: shown'); + eq([ h.state, h.since ], [ 'trying', T0 ], 'since it began'); + eq(link.settle(h, 'unstable', T0 + 200, true), null, 'another state waits too'); + eq(link.settle(h, 'trying', T0 + 210, true), null, 'and is forgotten when the first comes back'); + eq(h.pend, null, 'nothing pending'); + eq(link.settle(h, null, T0 + 220, true), { from: 'trying', to: null }, 'online and fine: at once'); + eq([ h.state, h.since ], [ null, 0 ], 'nothing shown'); + eq(link.shown({ d_1: h, d_2: { state: 'shared', since: 5 } }), { d_2: { state: 'shared', since: 5 } }, 'only what shows'); + eq(link.event_for({ from: 'shared', to: null }, { id: 'd_2', person: 'p_1' }, true), + { type: 'device_recovered', person: 'p_1', device: 'd_2', detail: 'shared' }, 'recovered event'); + eq(link.event_for({ from: null, to: 'dropped' }, { id: 'd_2', person: 'p_1' }, true), + { type: 'device_failing', person: 'p_1', device: 'd_2', detail: 'dropped' }, 'failing event'); + eq(link.event_for(null, { id: 'd_2' }, true), null, 'no change'); +}); + +// The agent moves the person's revision on every change settle() makes, so a +// state that clears while the device is away (no event) still leaves the page. +test('settle clears a state silently while the device is away', () => { + let h = link.fresh(T0); + link.settle(h, 'trying', T0, false); + link.settle(h, 'trying', T0 + link.HOLD, false); + eq(link.settle(h, null, T0 + 300, false), null, 'it stopped trying: waits'); + let ch = link.settle(h, null, T0 + 300 + link.HOLD, false); + eq(ch, { from: 'trying', to: null }, 'then a change: nothing shown'); + eq(link.event_for(ch, { id: 'd_1', person: 'p_1' }, false), null, 'without an activity event'); +}); + +/* + * The set-up sheet's states: at once, no HOLD. Each run also checks that the + * state setup() keeps, worked out only when something happened, is what + * setup_state() gives on every read. + */ +test('setup: knocks that never finish connecting', () => { + let knocking = (s) => (s % 120 < 90 && s % 5 == 0) ? { drx: 148, dtx: 92 } : {}; + let r = run(300, knocking); + // The first read is the baseline: the knocks count from 5 s. + eq(slice(r.setups, 0, 3), [ { s: 10, state: 'trying' }, { s: 100, state: null }, { s: 125, state: 'trying' } ], + 'with the second initiation; gone 15 s after the last one (85 s); back with the next two'); + eq(run(130, knocking).h.setup, { state: 'trying', since: T0 + 125 }, 'since it began again'); + eq(r.lag, [], 'never behind'); + // One initiation that the next second confirms is a connection, not a knock. + let ok1 = run(60, (s) => s == 10 ? { drx: 148, dtx: 92 } : s == 11 ? { hs: true, drx: 32 } : {}); + eq(ok1.setups, [], 'one knock, then the handshake: nothing to tell (idle)'); + // Knocking again while an older session still counts as online: it is trying now. + let late = run(300, (s) => s < 200 ? phone(s, true) : (s % 5 == 0 ? { drx: 148, dtx: 92 } : {})); + eq(late.setups[length(late.setups) - 1], { s: 205, state: 'trying' }, 'its new keys never complete'); + eq(late.lag, [], 'never behind'); +}); + +test('setup: a new device that connects and passes data', () => { + // It knocks at 10 s, the next second its first packets under the new keys carry data. + let at = (s) => s < 10 ? {} : s == 10 ? { drx: 148, dtx: 92 } : s == 11 ? { hs: true, drx: 32 + 1400, dtx: 4000 } : phone(s, true); + let r = run(900, at); + eq(r.setups, [ { s: 11, state: 'flowing' } ], 'flowing with the handshake, and through every new key after'); + eq(r.h.setup, { state: 'flowing', since: T0 + 11 }, 'since then'); + eq(r.lag, [], 'never behind'); + // A first keepalive only, data a few seconds later. + let r2 = run(60, (s) => s == 11 ? { hs: true, drx: 32 } : s == 14 ? { drx: 1400, dtx: 9000 } : {}); + eq(r2.setups, [ { s: 14, state: 'flowing' } ], 'with the first data'); + // Busy until 300 s, then gone: its session ends 190 s after its last handshake (254 s). + let r3 = run(600, (s) => s < 300 ? phone(s, true) : {}); + eq(r3.setups, [ { s: 30, state: 'flowing' }, { s: 444, state: null } ], 'data from 30 s (what came before the handshake does not count); away: nothing'); + eq(r3.lag, [], 'never behind'); +}); + +test('setup: idle is not "no data"', () => { + // Connected, keepalives only: the router sends nothing back, nothing to tell. + let r = run(900, (s) => phone(s, false)); + eq(r.setups, [], 'a sleeping phone'); + eq(r.lag, [], 'never behind'); + // The router sends it something now and then, and it answers: data flows. + eq(run(120, (s) => s == 4 ? { hs: true, drx: 32 } : s == 30 ? { dtx: 300, drx: 96 } : {}).setups, + [ { s: 30, state: 'flowing' } ], 'an answer is data'); +}); + +test('setup: connected, but nothing it sends comes through', () => { + // An old address: its first handshake at 4 s, the router's answers to what it drops at 7, 17, 27 s... + let r = run(400, renumbered); + eq(r.setups, [ { s: 19, state: 'nodata' } ], 'SETUP_QUIET after the handshake, with an answer in it'); + eq(r.lag, [], 'never behind, through its new keys at 128 s'); + // Imported again at 300 s: data flows at once. + let r2 = run(400, (s) => s < 300 ? renumbered(s) : s == 300 ? { hs: true, drx: 3000, dtx: 9000 } : phone(s, true)); + eq(r2.setups, [ { s: 19, state: 'nodata' }, { s: 300, state: 'flowing' } ], 'then flowing'); + // The router answers only after the quiet span: shown with the answer. + let slow = run(60, (s) => s == 4 ? { hs: true } : s == 25 ? { dtx: 32 } : {}); + eq(slow.setups, [ { s: 25, state: 'nodata' } ], 'with the first answer'); + eq(slow.lag, [], 'never behind'); +}); + +test('setup: light traffic on Maximum is data', () => { + // Content padding of 10-100: keep-alives of 42-132 bytes. A phone that only sends small packets (a DNS + // query, a SYN, ACKs: 150-600 bytes a second), and an answer now and then in a second it sent nothing. + let at = (s) => s == 3 ? { drx: 148, dtx: 92 } : s == 4 ? { hs: true, drx: 42 } : + s > 4 && s % 3 == 0 ? { drx: 150 + (s % 5) * 100, dtx: 1200 } : s % 7 == 0 ? { dtx: 600 } : {}; + let r = run(60, at, { ka: 132 }); + eq(r.setups, [ { s: 6, state: 'flowing' } ], 'flowing with its first small packets, never "no data"'); + eq(r.lag, [], 'never behind'); + // A keep-alive alone in a second is still no data: an idle phone on Maximum stays idle. + eq(run(120, (s) => s == 4 ? { hs: true, drx: 42 } : s % 25 == 0 ? { drx: 42 + (s % 90) } : {}, { ka: 132 }).setups, [], + 'padded keep-alives'); +}); + +test('setups', () => { + let h = link.fresh(T0); + eq(link.setups({ d_1: h, d_2: { setup: { state: 'trying', since: 5 } } }), { d_2: { state: 'trying', since: 5 } }, 'only devices with one'); + eq(link.setup_state(h, T0, false), { state: null, due: 0 }, 'nothing seen: nothing'); +}); diff --git a/tests/ucode/live.test.uc b/tests/ucode/live.test.uc index 5c4aa63..bc438cc 100644 --- a/tests/ucode/live.test.uc +++ b/tests/ucode/live.test.uc @@ -1,6 +1,10 @@ // dawnline.live: event categories and the retention policy, from a settings -// object and from the fixture config (real libuci). +// object and from the fixture config (real libuci); which tunnels are read, +// the counters folded from a read, how long a device counts as online, and +// what of the agent's files a read takes (RUN_DIR, put back after). import * as live from 'dawnline.live'; +import { RUN_DIR } from 'dawnline.util'; +import { readfile, writefile, unlink } from 'fs'; test('category_of', () => { eq(live.category_of('connect'), 'connections', 'connect'); @@ -66,3 +70,113 @@ test('fill_places', () => { ok(!live.fill_places(ev, { '7.7.7.7': 'X' }, 0), 'nothing to fill: unchanged'); ok(!live.fill_places([], { '1.1.1.1': 'X' }, 0), 'empty log'); }); + +test('tunnel_ifnames: the servers that run, on interfaces of their own', () => { + let srv = (ifname, more) => ({ enabled: true, private_key: 'k', ifname, subnet: '10.9.0.0/29', ...(more ?? {}) }); + let m = { servers: { + a: srv('awga'), off: srv('awgoff', { enabled: false }), keyless: srv('awgk', { private_key: '' }), + taken: srv('lan', { blocked: { code: 'taken', ifname: 'lan' } }), bad: srv('Bad Name'), + } }; + eq(live.tunnel_ifnames(m), [ 'awga' ], 'not turned off, without keys, kept down or misnamed'); + eq(live.tunnel_ifnames({ servers: {} }), [], 'none'); + m.servers.b = srv('awgb'); + eq(live.tunnel_ifnames(m, 'b'), [ 'awgb' ], 'one server\'s (a person\'s page)'); + eq([ live.tunnel_ifnames(m, 'off'), live.tunnel_ifnames(m, ''), live.tunnel_ifnames(m, 'gone') ], [ [], [], [] ], + 'one that does not run, no server, an unknown one: nothing'); +}); + +// What a read that failed, a tunnel that is down and a new link do to the counters. +test('collect: counters per tunnel read', () => { + let m = { + servers: { a: { ifname: 'awga' }, b: { ifname: 'awgb' } }, + people: { pa: { server: 'a' }, pb: { server: 'b' } }, + devices: { da: { person: 'pa', public_key: 'KA' }, db: { person: 'pb', public_key: 'KB' } }, + settings: { retention: {} }, + }; + let usage = { devices: { da: { raw: [ 40, 10 ], ifindex: 7 }, db: { raw: [ 500, 500 ] } }, people: {} }; + let peer = (rx, tx) => ({ KA: { ifname: 'awga', endpoint: '', handshake: 0, rx, tx } }); + live.collect(m, usage, { ok: false, reads: { awga: 'read', awgb: 'error' }, ifaces: { awga: { ifindex: 7 } }, peers: peer(100, 50) }); + eq(usage.devices.da.total, [ 60, 40 ], 'the difference since the last read'); + eq(usage.people.pa.total, [ 60, 40 ], 'their person'); + eq(usage.devices.db.raw, [ 500, 500 ], 'a tunnel that could not be read keeps its counters'); + live.collect(m, usage, { ok: true, reads: { awga: 'read', awgb: 'down' }, ifaces: { awga: { ifindex: 7 } }, peers: peer(100, 50) }); + eq(usage.devices.db.raw, [ 0, 0 ], 'a tunnel that is down starts again from zero'); + eq(usage.devices.da.total, [ 60, 40 ], 'nothing new'); + // Set up again: a new link whose counters already passed the old ones. + live.collect(m, usage, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: 8 } }, peers: peer(150, 80) }); + eq(usage.devices.da.total, [ 210, 120 ], 'a new link counts from zero'); + eq(usage.devices.da.ifindex, 8, 'the record follows its link'); + // A link whose index is unknown changes nothing about the epoch. + live.collect(m, usage, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: null } }, peers: peer(160, 90) }); + eq([ usage.devices.da.total, usage.devices.da.ifindex ], [ [ 220, 130 ], 8 ], 'counted on'); +}); + +// The window follows the keep-alive the device's configuration carries +// (awg.idle_handshake): 190 s for every default, longer only where the +// handshakes of an idle device are further apart. +test('online_window', () => { + let srv = { keepalive: 25, obf: {} }; + eq(live.online_window(srv, {}), 190, 'the default keep-alive'); + eq(live.online_window({ keepalive: 25, obf: { header_protection_key: 'k', rekey_after_time: '100-120' } }, {}), 190, 'Maximum'); + eq(live.online_window(srv, { keepalive: 0 }), 190, 'keep-alive off: the session alone'); + eq(live.online_window(srv, { keepalive: 100 }), 250, 'a handshake every second keep-alive'); + eq(live.online_window(srv, { keepalive: 300 }), 330, 'one every keep-alive'); + eq(live.online_window({ keepalive: 300, obf: {} }, {}), 330, 'the server\'s keep-alive'); + eq(live.online_window(null, {}), 190, 'no server'); + let m = { servers: { a: srv }, people: { p: { server: 'a' } }, devices: { d: { person: 'p', keepalive: 300 }, e: { person: 'x' } } }; + eq(live.online_windows(m), { d: 330, e: 190 }, 'per device'); + eq(live.online_windows(m, 'a'), { d: 330 }, 'one server\'s devices'); +}); + +test('online: without the agent, by the device\'s window', () => { + let peer = { handshake: time() - 300 }; + eq(live.online({ presence: null, windows: { d: 330 } }, 'd', peer), true, 'within its window'); + eq(live.online({ presence: null }, 'd', peer), false, 'the shortest window'); + eq(live.online({ presence: { online: { d: false } }, windows: { d: 330 } }, 'd', peer), false, 'the agent\'s word first'); +}); + +test('collect: online by the device\'s window', () => { + let m = { + servers: { a: { ifname: 'awga', keepalive: 300, obf: {} } }, + people: { pa: { server: 'a' } }, + devices: { da: { person: 'pa', public_key: 'KA' }, db: { person: 'pa', public_key: 'KB', keepalive: 25 } }, + settings: { retention: {} }, + }; + let hs = time() - 300; + let peers = { KA: { ifname: 'awga', endpoint: '', handshake: hs, rx: 0, tx: 0 }, KB: { ifname: 'awga', endpoint: '', handshake: hs, rx: 0, tx: 0 } }; + let v = live.collect(m, { devices: {}, people: {} }, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: 1 } }, peers }); + eq([ v.da.online, v.db.online ], [ true, false ], 'the server\'s keep-alive of 300 s, and a device\'s own of 25 s'); +}); + +// What the agent's watcher shows of each link (dawnline.link) reaches the +// read models through dump(), only while the agent runs. +test('dump: link and set-up states while the agent runs', () => { + let beat = `${RUN_DIR}/agent.beat`; + let had_beat = readfile(beat), had_link = readfile(live.LINK), had_setup = readfile(live.SETUP); + let shown = { d_1: { state: 'trying', since: 1800000000 } }, setups = { d_1: { state: 'trying', since: 1800000000 } }; + writefile(live.LINK, sprintf('%J', shown)); + writefile(live.SETUP, sprintf('%J', setups)); + writefile(beat, `${time()}`); + let m = { servers: {}, people: {}, devices: {} }; + eq(live.dump(m).link, shown, 'the watcher\'s states'); + eq(live.dump(m).setup, setups, 'and its set-up states'); + writefile(beat, `${time() - 600}`); + eq(live.dump(m).link, {}, 'a stopped agent\'s states are stale'); + eq(live.dump(m).setup, null, 'and nobody tells the set-up states'); + for (let f in [ [ beat, had_beat ], [ live.LINK, had_link ], [ live.SETUP, had_setup ] ]) + f[1] == null ? unlink(f[0]) : writefile(f[0], f[1]); +}); + +// A link that keeps failing is one line per device (add_event_merged), not one per device and person. +test('add_event_merged: per device', () => { + let path = `${RUN_DIR}/events.json`, had = readfile(path); + writefile(path, '[]'); + live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x1', detail: 'trying' }, 3600); + live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x1', detail: 'unstable' }, 3600); + live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x2', detail: 'shared' }, 3600); + let ev = live.load_events(); + eq(map(ev, (e) => [ e.device, e.detail ]), [ [ 'd_x1', 'trying, unstable' ], [ 'd_x2', 'shared' ] ], 'merged per device'); + eq(live.category_of('device_failing'), 'problems', 'a problem'); + eq(live.category_of('device_recovered'), 'problems', 'and so is its end'); + had == null ? unlink(path) : writefile(path, had); +}); diff --git a/tests/ucode/loop.test.uc b/tests/ucode/loop.test.uc index c7c04ef..e59f244 100644 --- a/tests/ucode/loop.test.uc +++ b/tests/ucode/loop.test.uc @@ -1,5 +1,7 @@ // dawnline.loop: the "like a home device" link's errors, stored as codes and -// put into words when read; the netns's MAC and which LAN address it may use. +// put into words when read; the netns's MAC and which LAN address it may use; +// the policy rules for the servers that send their devices this way, and the +// commands that bring the rules the kernel shows to them. import * as loop from 'dawnline.loop'; import { ip2int, parse_cidr } from 'dawnline.util'; @@ -56,3 +58,52 @@ test('ns_rules', () => { ok(index(plain, 'flowtable') < 0 && index(plain, 'flow add') < 0, 'plain: no flowtable'); eq(replace(fast, /\n\tflowtable ft \{(\n\t\t[^\n]*)*\n\t\}|\n\t\tct state established meta l4proto \{ tcp, udp \} flow add @ft/g, ''), plain, 'otherwise the same rules'); }); + +// A plan with one server sending its devices like a home device (plan() makes +// it, from the server's interface, its tunnel and its home networks). +const PLAN = { address: '192.168.1.250', table: 2077, + servers: [ { ifname: 'awghome', subnet: '10.9.0.0/29', direct: [ '10.9.0.0/29', '192.168.1.0/24' ] } ] }; + +test('rules', () => { + eq(loop.rules(PLAN), [ + { pref: 5205, iif: 'awghome', to: '192.168.1.250/32', table: '2077' }, + { pref: 5210, iif: 'awghome', to: '10.9.0.0/29', table: 'main' }, + { pref: 5210, iif: 'awghome', to: '192.168.1.0/24', table: 'main' }, + { pref: 5290, iif: 'awghome', to: null, table: '2077' }, + ], 'DNS into the netns, home and the tunnel by main, the rest into the netns'); + eq(loop.rules({ servers: [] }), [], 'no server sends anyone'); + eq(loop.rules(null), [], 'no plan'); +}); + +// What `ip -j -4 rule show` prints for the rules of PLAN: "src": "all" for a +// rule without a source, a /32 without its length (iproute2 iprule.c). +const HOME_SHOWN = [ + { priority: 5205, src: 'all', iif: 'awghome', dst: '192.168.1.250', table: '2077' }, + { priority: 5210, src: 'all', iif: 'awghome', dst: '10.9.0.0', dstlen: 29, table: 'main' }, + { priority: 5210, src: 'all', iif: 'awghome', dst: '192.168.1.0', dstlen: 24, table: 'main' }, + { priority: 5290, src: 'all', iif: 'awghome', table: '2077' }, +]; + +test('rule_cmds: the rules the kernel shows, against the plan', () => { + eq(loop.rule_cmds(PLAN, HOME_SHOWN), [], 'as wanted: nothing to do (no rule added again, none removed)'); + eq(loop.rule_cmds(PLAN, slice(HOME_SHOWN, 0, 3)), [ "ip -4 rule add priority 5290 iif 'awghome' lookup 2077" ], 'one gone: only it comes back'); + eq(loop.rule_cmds(PLAN, [ ...HOME_SHOWN, HOME_SHOWN[3] ]), [ "ip -4 rule del priority 5290 iif 'awghome' lookup 2077" ], 'one twice: one of them goes'); + eq(loop.rule_cmds(PLAN, []), [ + "ip -4 rule add priority 5205 iif 'awghome' to 192.168.1.250/32 lookup 2077", + "ip -4 rule add priority 5210 iif 'awghome' to 10.9.0.0/29 lookup main", + "ip -4 rule add priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main", + "ip -4 rule add priority 5290 iif 'awghome' lookup 2077", + ], 'none yet: all of them'); + eq(loop.rule_cmds({ servers: [] }, HOME_SHOWN), [ + "ip -4 rule del priority 5205 iif 'awghome' to 192.168.1.250 lookup 2077", + "ip -4 rule del priority 5210 iif 'awghome' to 10.9.0.0/29 lookup main", + "ip -4 rule del priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main", + "ip -4 rule del priority 5290 iif 'awghome' lookup 2077", + ], 'none wanted: each removed as shown, without "from all"'); + eq(loop.rule_cmds({ ...PLAN, servers: [ { ...PLAN.servers[0], direct: [ '10.9.0.0/29', '192.168.2.0/24' ] } ] }, HOME_SHOWN), [ + "ip -4 rule add priority 5210 iif 'awghome' to 192.168.2.0/24 lookup main", + "ip -4 rule del priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main", + ], 'another home network: the new rule first, then the old one goes'); + eq(loop.rule_cmds(PLAN, [ ...HOME_SHOWN, { priority: 5290, src: '10.9.0.2', iif: 'awghome', table: '2077' } ]), + [ "ip -4 rule del priority 5290 from 10.9.0.2 iif 'awghome' lookup 2077" ], 'a rule of ours with a source is not one of them: it goes'); +}); diff --git a/tests/ucode/meter.test.uc b/tests/ucode/meter.test.uc new file mode 100644 index 0000000..ca53911 --- /dev/null +++ b/tests/ucode/meter.test.uc @@ -0,0 +1,73 @@ +// dawnline.meter: the point between two samples (each server's bytes per +// second), the sample taken from a dump, the two minutes kept, and the file +// the watcher writes and the RPC reads (in RUN_DIR, removed after). +import * as meter from 'dawnline.meter'; +import { stat, unlink } from 'fs'; + +test('point', () => { + let a = { + t: 100.0, ts: 5000, servers: [ 's_1', 's_2' ], + dev: { d_1: [ 1000, 2000, 's_1' ], d_2: [ 500, 500, 's_1' ], d_3: [ 9000, 9000, 's_1' ], d_5: [ 0, 0, 's_2' ] }, + }; + let b = { + t: 101.0, ts: 5001, servers: [ 's_1', 's_2' ], + // d_2 sent nothing; d_3's peer was added again (counters from zero); d_4 is new; d_5 moved to s_1. + dev: { d_1: [ 3000, 12000, 's_1' ], d_2: [ 500, 500, 's_1' ], d_3: [ 100, 300, 's_1' ], d_4: [ 10, 10, 's_1' ], d_5: [ 50, 50, 's_1' ] }, + }; + eq(meter.point(a, b), { ts: 5001, servers: { s_1: [ 2000, 10000 ], s_2: [ 0, 0 ] } }, + 'bytes per second of each server\'s devices together; a server read with nothing moving is 0'); + eq(meter.point(a, { ...b, t: 102.0 }).servers.s_1, [ 1000, 5000 ], 'over two seconds'); + eq(meter.point(a, { ...b, t: 100.0 }), null, 'no time passed'); + eq(meter.point(a, { ...b, t: 110.0 }), null, 'the watcher stalled'); + eq(meter.point(a, { ...b, servers: [ 's_2' ], dev: { d_5: [ 50, 50, 's_2' ] } }).servers, { s_2: [ 50, 50 ] }, 'only servers read in the newer sample'); + eq(meter.point({ ...a, dev: {} }, b).servers, { s_1: [ 0, 0 ], s_2: [ 0, 0 ] }, 'a first look at every device: nothing yet'); +}); + +test('sample', () => { + let m = { + servers: { s_1: { ifname: 'dawn0' }, s_2: { ifname: 'dawn9' } }, + people: { p: { server: 's_1' }, q: { server: 's_2' } }, + devices: { d_1: { person: 'p', public_key: 'K1' }, d_2: { person: 'p', public_key: 'K2' }, d_3: { person: 'q', public_key: 'K3' } }, + }; + let d = { reads: { dawn0: 'read', dawn9: 'error' }, peers: { K1: { rx: 10, tx: 20 }, K3: { rx: 1, tx: 1 } } }; + let s = meter.sample(m, d, 5000); + eq([ s.ts, s.servers, s.dev ], [ 5000, [ 's_1' ], { d_1: [ 10, 20, 's_1' ] } ], + 'the servers read and their devices in the tunnel; not a tunnel that could not be read'); + ok(s.t > 0, 'monotonic time'); +}); + +test('keep', () => { + let pt = (ts) => ({ ts: ts, servers: { s_1: [ ts, 0 ] } }); + let ring = []; + for (let ts = 1000; ts < 1000 + meter.POINTS + 5; ts++) + meter.keep(ring, pt(ts)); + eq([ length(ring), ring[0][0], ring[length(ring) - 1][0] ], [ meter.POINTS, 1005, 1000 + meter.POINTS + 4 ], + 'the last POINTS seconds, newest last'); + eq(json(ring[0][1]), pt(1005), 'each point kept as its JSON'); + meter.keep(ring, pt(5000)); + eq(map(ring, (r) => r[0]), [ 5000 ], 'after a stalled watcher: nothing older than two minutes'); + meter.keep(ring, pt(5001)); + meter.keep(ring, pt(5002)); + meter.keep(ring, pt(5001)); + eq(map(ring, (r) => r[0]), [ 5000, 5001 ], 'a clock that went back: its points replace the later ones'); +}); + +test('want, save and read', () => { + let had = stat(meter.WANT) != null; + meter.want(); + ok(meter.wanted(time()), 'just asked'); + ok(!meter.wanted(time() + meter.WANT_FOR), 'stale after WANT_FOR'); + ok(!meter.wanted(time() - meter.WANT_FOR - 1), 'a clock that went back does not keep it'); + let t = time(); + meter.save([ [ t - 2, `{"ts":${t - 2},"servers":{}}` ], [ t - 1, `{"ts":${t - 1},"servers":{}}` ], [ t, `{"ts":${t},"servers":{"s_1":[1,2]}}` ] ]); + let r = meter.read(0); + eq([ r.ts, length(r.points), r.want, r.keep ], [ t, 3, meter.WANT_FOR, meter.POINTS ], 'everything'); + eq(meter.read(t - 1).points, [ { ts: t, servers: { s_1: [ 1, 2 ] } } ], 'only what is newer'); + let old = t - meter.WANT_FOR - 1; + meter.save([ [ old, `{"ts":${old},"servers":{}}` ] ]); + eq([ meter.read(0).ts, meter.read(0).points ], [ old, [] ], 'left by an agent that died while someone looked: no points'); + meter.stop(); + eq([ meter.read(0).ts, meter.read(0).points ], [ 0, [] ], 'nobody looks: nothing'); + if (!had) + unlink(meter.WANT); +}); diff --git a/tests/ucode/netifd.test.uc b/tests/ucode/netifd.test.uc new file mode 100644 index 0000000..27bb5f4 --- /dev/null +++ b/tests/ucode/netifd.test.uc @@ -0,0 +1,57 @@ +// dawnline.netifd: drift(), the watchdog's look at a server's interface +// (network. against what sync() writes, markers aside), on the +// fixture's server and a section this test puts into /etc/config/network +// the way sync() writes it, and takes out again. +import { readfile, writefile, unlink } from 'fs'; +import { cursor } from 'uci'; +import { uci_put } from 'dawnline.util'; +import * as core from 'dawnline.core'; +import * as awg from 'dawnline.awg'; +import * as netifd from 'dawnline.netifd'; + +const NETWORK = '/etc/config/network'; + +test('drift: the interface as Dawnline set it, and edited outside it', () => { + let had = readfile(NETWORK); + if (had == null) + writefile(NETWORK, ''); + let m = core.load(); + let srv = m.servers.main; + let c = cursor(); + c.load('network'); + c.set('network', 'awgmain', 'interface'); + for (let k, v in awg.netifd_options(srv)) + uci_put(c, 'network', 'awgmain', k, v); + c.set('network', 'awgmain', '_dawnline', 'main'); + c.set('network', 'awgmain', '_dawnline_name', srv.name); + c.commit('network'); + let edit = (opt, val) => { + uci_put(c, 'network', 'awgmain', opt, val); + c.commit('network'); + return netifd.drift(m); + }; + let got = { as_set: netifd.drift(m) }; + got.renamed = edit('_dawnline_name', 'Renamed in LuCI'); + got.edited = edit('mtu', '1420'); + got.more = edit('awg_jc', null); + edit('mtu', `${core.tunnel_mtu(srv)}`); + got.restored = edit('awg_jc', srv.obf.jc); + got.disabled = edit('disabled', '1'); + edit('disabled', null); + got.foreign = edit('_dawnline', 'someone'); + m.servers.main.enabled = false; + got.off = netifd.drift(m); + // Put the router back as the other tests know it. + c.delete('network', 'awgmain'); + c.commit('network'); + if (had == null) + unlink(NETWORK); + eq(got.as_set, { main: [] }, 'as sync() writes it'); + eq(got.renamed, { main: [] }, 'the markers are not compared'); + eq(got.edited, { main: [ 'mtu' ] }, 'an option changed by hand'); + eq(got.more, { main: [ 'mtu', 'awg_jc' ] }, 'and one removed, by name only'); + eq(got.restored, { main: [] }, 'put back'); + eq(got.disabled, { main: [ 'disabled' ] }, 'switched off outside Dawnline'); + eq(got.foreign, {}, "a section that isn't the server's is not looked at"); + eq(got.off, {}, 'a server turned off is not looked at'); +}); diff --git a/tests/ucode/nft.test.uc b/tests/ucode/nft.test.uc new file mode 100644 index 0000000..5e93b51 --- /dev/null +++ b/tests/ucode/nft.test.uc @@ -0,0 +1,49 @@ +// dawnline.nft: the access table rendered for a model with two servers (one +// sending everyone like a home device, one direct) and the router read as a +// fixed context: exactly what 0.13.0 renders (fixtures/nft-table.txt, made by +// that version from this model). +import { readfile } from 'fs'; +import * as nft from 'dawnline.nft'; + +const KEY = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='; +const SNAP = { devices: { 'br-lan': { nets: [ '192.168.1.0/24' ], zone: 'lan', addrs: [ '192.168.1.1/24' ] }, eth1: { nets: [], zone: 'wan' } }, + wan: 'eth1', lan: 'br-lan', zones: [ 'lan', 'wan' ] }; +// The netns is up (its DNS address, the Home-only resolver inside it) and the LAN's DNS is the router. +const CTX = { dns_addr: '192.168.1.250', resolver: { mode: 'ns', address: '169.254.77.2', port: 53 }, lan_dns: '192.168.1.1', snap: SNAP }; +const STATES = { alice: 'active', bob: 'active', carol: 'active', dave: 'active', erin: 'active' }; +let golden = readfile(sourcepath(0, true) + '/fixtures/nft-table.txt'); + +/** Server home sends everyone like a home device, work sends everyone direct. */ +function model() { + let srv = (id, ifname, subnet, lan_like, mesh) => ({ id, name: id, ifname, subnet, private_key: KEY, enabled: true, lan_like, mesh, + auto_wan: true, auto_lan: true, lan_devices: [], lan_zone: 'lan', wan_zone: 'wan', obf: {} }); + let person = (id, server, access, extra) => ({ id, name: id, server, access, dns_mode: 'device', services: [], home_nets: [], + circle: '', ...(extra ?? {}) }); + let dev = (person, address) => ({ person, address, disabled: false }); + return { + settings: { portal_enabled: true, portal_port: 8443, portal_host: 'vpn.example.com', portal_alt: [] }, + servers: { home: srv('home', 'awghome', '10.9.0.0/29', true, 'all'), work: srv('work', 'awgwork', '10.9.1.0/29', false, 'circles') }, + people: { + alice: person('alice', 'home', 'both'), bob: person('bob', 'work', 'internet'), + carol: person('carol', 'home', 'lan', { dns_mode: 'home' }), dave: person('dave', 'home', 'internet'), + erin: person('erin', 'work', 'both'), + }, + devices: { + a1: dev('alice', '10.9.0.2'), b1: dev('bob', '10.9.1.2'), c1: dev('carol', '10.9.0.3'), + d1: dev('dave', '10.9.0.4'), d2: dev('dave', '10.9.0.5'), e1: dev('erin', '10.9.1.3'), + }, + services: {}, circles: {}, + }; +} + +function render(m, states) { + return nft.render(m, nft.access_sets(m, null, states ?? STATES, SNAP), CTX); +} + +test('render: the table as it was', () => { + ok(golden != null, 'the fixture is there'); + eq(render(model()), golden, 'line for line'); + let m = model(); + m.devices.b1.lan_bypass = true; + eq(render(m), golden, 'a device that keeps its own local network out of the tunnel changes nothing here'); +}); diff --git a/tests/ucode/pkg.test.uc b/tests/ucode/pkg.test.uc new file mode 100644 index 0000000..b3c7e12 --- /dev/null +++ b/tests/ucode/pkg.test.uc @@ -0,0 +1,71 @@ +// dawnline.pkg: the package a control text or file names (ipk control, +// `apk adbdump`), and when an apk install of package files took: every +// package at its file's version, a rollback to an older one included. +import * as pkg from 'dawnline.pkg'; + +const DIR = '/tmp/dawnline-tests/pkg'; + +// AmneziaWG 3.1 as the Components tab installs it, and the 2.0 build before it. +const NEW = [ + { name: 'kmod-amneziawg', version: '6.12.94.3.1.20260906-r1', file: '/tmp/x/kmod.apk' }, + { name: 'amneziawg-tools', version: '3.1.20260812-r1', file: '/tmp/x/tools.apk' }, + { name: 'luci-proto-amneziawg', version: '3.1.0-r1', file: '/tmp/x/proto.apk' }, +]; +const OLD = { 'kmod-amneziawg': '6.12.94.1.0.20250722-r1', 'amneziawg-tools': '1.0.20250722-r1', 'luci-proto-amneziawg': '2.0.0-r1' }; + +function at(list) { + let have = {}; + for (let w in list) + have[w.name] = w.version; + return have; +} + +test('control_info of an ipk control file', () => { + eq(pkg.control_info('Package: amneziawg-tools\nVersion: 1.0.20250722-r1\nDepends: libc\nArchitecture: aarch64_cortex-a53\n', true), + { name: 'amneziawg-tools', version: '1.0.20250722-r1' }, 'fields'); + eq(pkg.control_info('Description: no package here\n', true), { name: null, version: null }, 'nothing said'); +}); + +test('control_info of apk adbdump', () => { + let dump = '#%SCHEMA: 00504B47\ninfo:\n name: kmod-amneziawg\n version: 6.12.94.3.1.20260906-r1\n' + + ' description: AmneziaWG kernel module\n arch: aarch64_cortex-a53\n depends: # 2 items\n - kernel=6.12.94\n' + + ' - kmod-udptunnel4\npaths: # 2 items\n - name: lib/modules\n - name: lib/modules/6.12.94\n files: # 1 items\n' + + ' - name: amneziawg.ko\n'; + eq(pkg.control_info(dump, false), { name: 'kmod-amneziawg', version: '6.12.94.3.1.20260906-r1' }, 'the package, not its files'); + eq(pkg.control_info('', false), { name: null, version: null }, 'adbdump failed'); + eq(pkg.control_info(null, false), { name: null, version: null }, 'no output'); +}); + +test('file_info of an ipk', () => { + system(`rm -rf ${DIR} && mkdir -p ${DIR}`); + ok(system(`cd ${DIR} && printf 'Package: luci-proto-amneziawg\\nVersion: 2.0.0-r1\\n' > control && tar -czf control.tar.gz ./control && tar -czf proto.ipk ./control.tar.gz`) == 0, + 'made the ipk'); + eq(pkg.file_info(`${DIR}/proto.ipk`), { name: 'luci-proto-amneziawg', version: '2.0.0-r1' }, 'name and version'); + eq(pkg.file_version(`${DIR}/proto.ipk`), '2.0.0-r1', 'file_version'); +}); + +test('mismatched: an update took', () => { + eq(pkg.mismatched(NEW, at(NEW)), [], 'every package at its file'); +}); + +test('mismatched: a rollback to an older build took', () => { + let back = map(keys(OLD), (n) => ({ name: n, version: OLD[n], file: `/tmp/x/${n}.apk` })); + eq(pkg.mismatched(back, OLD), [], 'older versions are what the files hold'); +}); + +test('mismatched: apk left a package alone', () => { + let have = { ...at(NEW), 'amneziawg-tools': OLD['amneziawg-tools'] }; + eq(pkg.mismatched(NEW, have), [ NEW[1] ], 'the tools kept their old version'); + eq(pkg.mismatched(NEW, OLD), NEW, 'nothing changed'); +}); + +test('mismatched: missing or unreadable', () => { + let have = at(NEW); + delete have['luci-proto-amneziawg']; + eq(pkg.mismatched(NEW, have), [ NEW[2] ], 'not installed after the install'); + let blind = [ { name: null, version: null, file: '/tmp/x/broken.apk' } ]; + eq(pkg.mismatched(blind, {}), blind, 'a file that names no package never counts as installed'); + eq(pkg.mismatched([ { name: 'amneziawg-tools', version: null, file: '/tmp/x/t.apk' } ], { 'amneziawg-tools': null }), + [ { name: 'amneziawg-tools', version: null, file: '/tmp/x/t.apk' } ], 'no version on either side'); + eq(pkg.mismatched(NEW, null), NEW, 'no installed versions'); +}); diff --git a/tests/ucode/util.test.uc b/tests/ucode/util.test.uc index 057e0c0..fcf7d21 100644 --- a/tests/ucode/util.test.uc +++ b/tests/ucode/util.test.uc @@ -18,6 +18,38 @@ test('valid_name', () => { ok(!util.valid_name('a\tb'), 'control character'); }); +test('valid_device_name', () => { + eq(util.DEVICE_NAME_MAX, 20, 'the limit'); + ok(util.valid_device_name('9999999999999999999'), '19 characters'); + ok(util.valid_device_name('99999999999999999999'), '20 characters'); + ok(!util.valid_device_name('999999999999999999999'), '21 characters'); + ok(util.valid_device_name('Kitchen iPad'), 'letters and a space'); + ok(util.valid_device_name('my-pc_2.home'), 'dash, underscore and dot'); + ok(util.valid_device_name('Мой ноутбук'), 'Cyrillic'); + ok(util.valid_device_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛ'), '20 Cyrillic letters (40 bytes) are 20 characters'); + ok(!util.valid_device_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛД'), '21 Cyrillic letters'); + ok(util.valid_device_name('Ordinateur de Zoé'), 'Latin with an accent'); + ok(util.valid_device_name('客厅电视'), 'Chinese'); + ok(util.valid_device_name('Ελένη'), 'Greek'); + ok(!util.valid_device_name('Phone 📱'), 'emoji'); + ok(!util.valid_device_name('Офис™'), 'trade mark sign'); + ok(!util.valid_device_name('«Дом»'), 'guillemets'); + ok(!util.valid_device_name('a\u200bb'), 'zero-width space'); + ok(!util.valid_device_name('a×b'), 'multiplication sign'); + // Raw bytes by chr(): a "\xd0" in a literal is the character Ð to some ucode releases. + ok(!util.valid_device_name('a' + chr(0xc0) + chr(0xaf) + 'b'), 'a slash spelled long'); + ok(!util.valid_device_name('a' + chr(0xd0)), 'a character cut short'); + ok(!util.valid_device_name("Bob's iPhone"), 'apostrophe'); + ok(!util.valid_device_name('a;rm -rf /'), 'semicolon and slash'); + ok(!util.valid_device_name('$(reboot)'), 'shell'); + ok(!util.valid_device_name('a { ok(util.valid_host('vpn.example.com'), 'name'); ok(util.valid_host('router'), 'single label'); diff --git a/tests/ucode/view.test.uc b/tests/ucode/view.test.uc index 1fe76c2..1309b1f 100644 --- a/tests/ucode/view.test.uc +++ b/tests/ucode/view.test.uc @@ -37,3 +37,23 @@ test('month_days', () => { eq(view.month_days(null)[0], [ 0, 0 ], 'a day without traffic is zero both ways'); eq(view.spark({ days }, 1), [ [ 5, 7 ] ], 'the week the same way, today last'); }); + +// What the set-up sheet reads off a device: the watcher's state, or without the agent a session that lives. +test('device_view: set-up state', () => { + let m = { + settings: { hostnames: false }, + servers: { s_1: { id: 's_1', keepalive: 25, obf: {} } }, + people: { p_1: { id: 'p_1', server: 's_1', devices: [ 'd_1' ] } }, + devices: { d_1: { id: 'd_1', person: 'p_1', kind: 'phone', public_key: 'K1', private_key: 'x', mtu: 0, keepalive: null } }, + _reconnect: {}, _issued: {}, + }; + let hs = time() - 10; + let peers = { K1: { ifname: 'awga', endpoint: '203.0.113.7:4000', handshake: hs, rx: 100, tx: 100 } }; + let usage = { devices: {}, people: {} }; + let watched = { peers, presence: { online: { d_1: true } }, windows: {}, link: {}, setup: { d_1: { state: 'nodata', since: hs + 15 } } }; + eq(view.device_view(m, m.devices.d_1, usage, watched).setup, { state: 'nodata', since: hs + 15 }, 'the watcher\'s'); + eq(view.device_view(m, m.devices.d_1, usage, { ...watched, setup: {} }).setup, null, 'the watcher sees nothing'); + let alone = { peers, presence: null, windows: {}, link: {}, setup: null }; + eq(view.device_view(m, m.devices.d_1, usage, alone).setup, { state: 'flowing', since: hs }, 'no agent: a live session'); + eq(view.device_view(m, m.devices.d_1, usage, { ...alone, peers: {} }).setup, null, 'no agent, not online: nothing'); +}); diff --git a/web/package-lock.json b/web/package-lock.json index 58960b8..57100bf 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "dawnline-web", - "version": "0.13.0", + "version": "0.14.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dawnline-web", - "version": "0.13.0", + "version": "0.14.0", "license": "MIT", "dependencies": { "qrcode-generator": "1.4.4" diff --git a/web/package.json b/web/package.json index 5f76063..f0948b6 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "dawnline-web", - "version": "0.13.0", + "version": "0.14.0", "private": true, "license": "MIT", "type": "module", diff --git a/web/src/admin/api.ts b/web/src/admin/api.ts index e126b12..eaf88dd 100644 --- a/web/src/admin/api.ts +++ b/web/src/admin/api.ts @@ -3,7 +3,19 @@ // that did not load, a server that refused its devices) as { warning }. import type { Network, PortHold } from './netcheck'; -import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types'; +import type { + AwgCaps, + AwgState, + Circle, + ClientConfig, + DayUsage, + HealthCheck, + LogEvent, + MeshMode, + Pair, + Person, + Status, +} from '../shared/types'; import { notify } from './ui/toast'; import { lang } from '../shared/i18n'; @@ -62,6 +74,44 @@ export interface EndpointProbe { v6_only: boolean; status: 'ok' | 'warn' | 'error'; text: string; + /** The router's public IPv6 addresses ([]: none; null: not read, the name has no IPv6). */ + router6?: string[] | null; + /** The name's IPv6 addresses that are not the router's (null while router6 is). */ + foreign6?: string[] | null; + /** The name has IPv6 and every address is the router's. */ + here6?: boolean; +} + +/** One second of the live meter: each server whose tunnel was read, [rx, tx] in bytes/s (rx = from devices, as Server.rate). */ +export interface MeterPoint { + ts: number; + servers: Record; +} + +/** + * The live meter (rpc meter): each call keeps the router sampling for `want` + * seconds more; the first point comes about 2 s after the first call. + */ +export interface Meter { + /** Router time. */ + now: number; + /** Seconds the router keeps sampling after a call. */ + want: number; + /** Points it keeps: one a second, the last 2 minutes. */ + keep: number; + /** The newest point's time (0: none yet); it stops moving when the agent does. */ + ts: number; + /** Oldest first; only those newer than `since` when it was given. */ + points: MeterPoint[]; +} + +/** + * A device's own link values for device_update; left out = kept. Numbers go as text: '' = the server's, keep-alive + * '0' = off. LAN Bypass stays as chosen when the device was added (the RPC takes it, the admin UI never changes it). + */ +export interface DeviceLinkPatch { + mtu?: string; + keepalive?: string; } export interface Backup { @@ -400,6 +450,11 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P const status = call('status', ['days']); +const deviceUpdateRaw = call('device_update', ['id', 'name', 'disabled', 'mtu', 'keepalive']); +/** Rename, turn off or on, or change how a device connects; what is undefined stays as it is. */ +const deviceUpdate = (id: string, name?: string, disabled?: boolean, link: DeviceLinkPatch = {}) => + deviceUpdateRaw(id, name, disabled, link.mtu, link.keepalive); + /** One line of the service log: tunnel and service starts, stops, watchdog repairs, errors. */ export interface ServiceLogEntry { ts: number; @@ -433,6 +488,8 @@ export type Health = { checks: HealthCheck[] } & ServiceLog; export const api = { rev: call<{ rev: number; version?: string }>('rev'), + /** The live meter's points newer than `since` (0: all); polled while the Overview shows it. */ + meter: call('meter', ['since']), personUpdate, settingsGet: call('settings_get'), portalInfo: call('portal_info'), @@ -501,9 +558,11 @@ export const api = { personRegen: call<{ link: string | null; removed: number }>('person_regen', ['id', 'remove']), personDelete: call('person_delete', ['id']), personUsage: call<{ person: DayUsage[]; devices: Record }>('person_usage', ['id', 'days']), - deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']), - deviceConfig: call('device_config', ['id']), - deviceUpdate: call('device_update', ['id', 'name', 'disabled']), + /** A new device; `lan_bypass` (true) keeps its own local network outside the tunnel. */ + deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind', 'lan_bypass']), + /** A device's configuration; `issue` (true) when it goes to the device as a code, a file or a key: only that clears "Update config". */ + deviceConfig: call('device_config', ['id', 'issue']), + deviceUpdate, deviceDelete: call('device_delete', ['id']), deviceRotate: call('device_rotate', ['id']), apply: call('apply'), diff --git a/web/src/admin/cores/awg.ts b/web/src/admin/cores/awg.ts index 67dc726..36209b5 100644 --- a/web/src/admin/cores/awg.ts +++ b/web/src/admin/cores/awg.ts @@ -50,14 +50,16 @@ const CONF: [string, string][] = [ /** * The applied parameters, grouped by what they do, with a plain-language - * line per group. Collapsed by default; copyable as config lines. + * line per group. Collapsed by default; copyable as config lines. The header + * protection key stays out of the status (read-only users can read it): the + * view says there is one, and each device's file has it. */ -function paramsView(o: Record): HTMLElement | null { - const has = (k: string) => o[k] != null && o[k] !== ''; +function paramsView(o: Record, hpk: boolean): HTMLElement | null { + const has = (k: string) => (k === 'header_protection_key' ? hpk : o[k] != null && o[k] !== ''); const keys = CONF.filter(([k]) => has(k)); if (!keys.length) return null; const val = (k: string, name: string) => - E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? `${o[k].slice(0, 6)}••••` : o[k])]); + E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? _('set', 'key') : o[k])]); const group = (title: string, ic: string, text: string, ks: string[]) => { const present = CONF.filter(([k]) => ks.includes(k) && has(k)); return present.length @@ -76,7 +78,10 @@ function paramsView(o: Record): HTMLElement | null { const signature = (o.i1 ?? '').includes('0x8580') ? _('A first packet shaped like a DNS answer.') : _('Extra packets sent before the handshake.'); - const conf = keys.map(([k, n]) => `${n} = ${o[k]}`).join('\n'); + const conf = keys + .filter(([k]) => k !== 'header_protection_key') + .map(([k, n]) => `${n} = ${o[k]}`) + .join('\n'); const body = E('div', { class: 'dl-pgrid' }, [ group( _('Junk packets'), @@ -126,7 +131,7 @@ function paramsView(o: Record): HTMLElement | null { class: 'dl-linkbtn', click: (ev: Event) => { ev.preventDefault(); - copyText(conf, _('Parameters copied')); + copyText(conf, hpk ? _('Parameters copied. The header protection key is in each device’s file.') : _('Parameters copied')); }, }, _('Copy as config'), @@ -379,7 +384,7 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement { ), ) : '', - paramsView(srv.obf ?? {}) ?? '', + paramsView(srv.obf ?? {}, srv.hpk) ?? '', E('div', { class: 'dl-row-end' }, [ E('span', { class: 'dl-sub' }, _('Applies at once: every AmneziaWG device imports its configuration again.')), apply, @@ -438,7 +443,7 @@ function overviewTile(srv: Server): HTMLElement { if (pad.length) chips.push(pad.slice(0, 2).join(' · ') + (pad.length > 2 ? ` +${pad.length - 2}` : '')); if (['h1', 'h2', 'h3', 'h4'].some((k) => o[k] && o[k] !== String(['h1', 'h2', 'h3', 'h4'].indexOf(k) + 1))) chips.push(_('H1–H4 random')); if (o.i1) chips.push(/0x(8580|0100)0001/.test(o.i1) ? _('DNS-like first packets') : _('Signature packets')); - if (o.header_protection_key) chips.push(_('Encrypted headers')); + if (srv.hpk) chips.push(_('Encrypted headers')); if (!chips.length) chips.push(m?.id === 'off' ? _('Plain WireGuard') : _('No values yet')); return E('div', { class: 'dl-bento-tile dl-disg' }, [ E('div', { class: 'dl-bento-head' }, [ diff --git a/web/src/admin/device-link.ts b/web/src/admin/device-link.ts new file mode 100644 index 0000000..077a6f7 --- /dev/null +++ b/web/src/admin/device-link.ts @@ -0,0 +1,147 @@ +// A device's own link in its drawer (./device): what goes wrong with its +// connection (the agent's link state, in words about the device), its MTU and +// keep-alive with a dialog each, and LAN Bypass as it was chosen when the +// device was added. The router checks the values again +// (core.set_device_link); the help lines are ./netcheck's, the state's words +// ./events/model's. + +import type { Device, DeviceLink, Person, Server } from '../shared/types'; +import { E } from './e'; +import { api, type DeviceLinkPatch } from './api'; +import { button } from './ui/button'; +import { cancelButton, closeModal, modal } from './ui/modal'; +import { attempt, notify } from './ui/toast'; +import { liveField } from './ui/layout'; +import { deviceKeepaliveHelp, deviceMtuHelp, type Help } from './netcheck'; +import { linkStateText } from './events/model'; +import { fmt } from '../shared/i18n'; +import { homeOf, netsLabel } from '../shared/format'; + +/** Status while the link fails in a named way: the state (warn) and a line on what it means; null for an unknown one. */ +export function linkStatus(link: DeviceLink): HTMLElement[] | null { + const t = linkStateText(link.state); + return t ? [E('span', { class: 'dl-dstat warn' }, t.title), E('span', { class: 'dl-sub' }, t.line)] : null; +} + +/** The MTU a device gets with none of its own: its server's for its kind (null when that is not known). */ +function autoMtu(d: Device, srv?: Server): number | null { + if (srv) return d.kind === 'phone' || d.kind === 'tablet' ? srv.mtus.phone : srv.mtus.computer; + return d.mtu ? null : (d.mtu_used ?? null); +} + +/** One value in a dialog of its own: the field with its help as it is typed, Save through device_update. */ +function linkDialog( + title: string, + label: string, + input: HTMLInputElement, + help: () => Help, + patch: () => DeviceLinkPatch, + id: string, + saved: () => unknown, +) { + const field = liveField(label, input, help); + modal( + title, + [field], + [ + cancelButton(), + ' ', + button( + _('Save'), + async () => { + const h = field.help(); + if (h.bad) { + notify(h.text, 'warning'); + return; + } + if (await attempt(() => api.deviceUpdate(id, undefined, undefined, patch()), _('Saved'))) { + closeModal(); + await saved(); + } + }, + 'positive', + ), + ], + ); + setTimeout(() => input.select(), 50); +} + +/** A number field for a link value: the device's own, or empty for what it gets without one (`placeholder`). */ +function numberInput(value: number | null | undefined, placeholder: string | null): HTMLInputElement { + return E('input', { + type: 'text', + class: 'cbi-input-text', + inputmode: 'numeric', + maxlength: 4, + value: value == null ? '' : String(value), + placeholder, + }) as HTMLInputElement; +} + +function mtuDialog(d: Device, srv: Server | undefined, saved: () => unknown) { + const auto = autoMtu(d, srv); + const input = numberInput(d.mtu || null, auto ? fmt(_('Automatic: %s'), auto) : null); + linkDialog( + fmt(_('MTU of %s'), d.name), + 'MTU', + input, + () => deviceMtuHelp(input.value), + () => ({ mtu: input.value.trim() }), + d.id, + saved, + ); +} + +function keepaliveDialog(d: Device, srv: Server | undefined, saved: () => unknown) { + const input = numberInput(d.keepalive, srv ? fmt(_('As the server: %s'), srv.keepalive) : null); + linkDialog( + fmt(_('Keep-alive of %s'), d.name), + _('Keep-alive'), + input, + () => deviceKeepaliveHelp(input.value), + () => ({ keepalive: input.value.trim() }), + d.id, + saved, + ); +} + +/** + * Details rows as [label, value]: the MTU and keep-alive its configuration + * carries, each with Change (its own dialog, then `saved`), and LAN Bypass as + * it was chosen when the device was added. + */ +export function linkRows(d: Device, p: Person, srv: Server | undefined, saved: () => unknown): [string, Node][] { + const home = homeOf(p, srv); + // Two buttons say "Change": each is named after its row for a screen reader. + const value = (v: string, from: string, name: string, change: () => void) => + E('span', { class: 'dl-kv-act' }, [ + E('span', {}, [v, from ? [' ', E('span', { class: 'dl-faint' }, from)] : '']), + E('button', { type: 'button', class: 'dl-linkbtn', 'aria-label': name, click: change }, _('Change')), + ]); + const ka = d.keepalive_used; + return [ + [ + 'MTU', + value(d.mtu_used == null ? '—' : String(d.mtu_used), d.mtu ? '' : _('automatic'), _('Change the MTU'), () => + mtuDialog(d, srv, saved), + ), + ], + [ + _('Keep-alive'), + value( + ka == null ? '—' : ka ? fmt(_('%s s'), ka) : _('Off'), + d.keepalive != null ? '' : _('as the server'), + _('Change the keep-alive'), + () => keepaliveDialog(d, srv, saved), + ), + ], + [ + _('LAN Bypass'), + E('span', {}, [ + !d.lan_bypass ? _('Off') : home.length ? fmt(_('On, except %s (home)'), netsLabel(home)) : _('On'), + ' ', + E('span', { class: 'dl-faint' }, _('set when it was added')), + ]), + ], + ]; +} diff --git a/web/src/admin/device.ts b/web/src/admin/device.ts index 184e3ff..cd27b09 100644 --- a/web/src/admin/device.ts +++ b/web/src/admin/device.ts @@ -1,8 +1,9 @@ // Device drawer: a right-hand panel with the device's status, connection // (QR / key / file, from its server's core), details and actions; the ⋯ menu -// on a device card; and the admin's Add device dialog. +// on a device card; and the admin's Add device dialog. Its own link (link +// state, MTU, keep-alive, LAN Bypass) is ./device-link. -import type { Device, Geo, Kind, LogEvent, Person } from '../shared/types'; +import type { ClientConfig, Device, Geo, Kind, LogEvent, Person, Server } from '../shared/types'; import { E } from './e'; import { api } from './api'; import { button } from './ui/button'; @@ -12,10 +13,12 @@ import { dropdown, type MenuItem } from './ui/menu'; import { drawer } from './ui/drawer'; import { attempt, notify } from './ui/toast'; import { liveField, warnNote } from './ui/layout'; +import { isOn, sw } from './ui/controls'; import { qrCode } from './ui/qr'; -import { nameHelp } from './netcheck'; +import { deviceNameHelp, type Help } from './netcheck'; import { deviceStatus } from './ui/badges'; -import { ago, bytes, isoDay, kindLabel, KINDS, todayOf } from '../shared/format'; +import { ago, bytes, defaultName, fitName, homeOf, isoDay, kindLabel, KINDS, netsLabel, todayOf } from '../shared/format'; +import { guardDeviceName } from '../shared/name-guard'; import { fill, fmt, locale, num } from '../shared/i18n'; import { icon } from '../shared/icons'; import { eventBy } from './events/model'; @@ -27,6 +30,7 @@ import { onLiveChange } from './state/live'; import { ConnectionMap, rangeControl, type Range } from './map'; import { PlacesView } from './places/render'; import { personUrl } from './urls'; +import { linkRows, linkStatus } from './device-link'; /** What the page that opens a device hands over. */ export interface DeviceOpts { @@ -38,6 +42,8 @@ export interface DeviceOpts { today?: string; /** The device's server's core (AmneziaWG when not given). */ core?: Core; + /** The device's server: what an empty MTU or keep-alive of its own gives. */ + server?: Server; /** The page's activity log, when it keeps one: the drawer reads it instead of fetching its own. */ events?: () => LogEvent[] | null; } @@ -128,11 +134,38 @@ async function reopen(personId: string, deviceId: string, o: DeviceOpts) { const p2 = st?.people.find((x) => x.id === personId); const d2 = p2?.devices.find((x) => x.id === deviceId); if (st && p2 && d2) - void openDevice(p2, d2, { ...o, geo: st.geo, now: st.now, today: todayOf(st.series), core: coreFor(st.servers, p2.server) }); + void openDevice(p2, d2, { + ...o, + geo: st.geo, + now: st.now, + today: todayOf(st.series), + core: coreFor(st.servers, p2.server), + server: st.servers.find((s) => s.id === p2.server), + }); +} + +/** + * The connection of a device that holds an older configuration, behind a button: showing the new one is what + * counts as giving it out (it clears "Update config"), never opening the drawer. `shown` runs once it is out. + */ +function newConfigGate(id: string, show: (cfg: ClientConfig) => Promise, shown: () => unknown): HTMLElement { + const box = E('div', { class: 'dl-row-actions' }); + dom.content( + box, + button([icon('qr'), ' ', _('Show the new configuration')], async () => { + const cfg = await attempt(() => api.deviceConfig(id, true)); + if (!cfg) return; + box.className = ''; + dom.content(box, await show(cfg)); + void shown(); + }), + ); + return box; } /** Device drawer. */ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { + // A look: only a delivery (a code, a file, a key handed to the device) clears "Update config". const cfg = await attempt(() => api.deviceConfig(dev.id)); if (!cfg) return; const core = o.core ?? coreOf(null); @@ -141,8 +174,20 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { let geo = o.geo; let now = o.now; let today = o.today ?? isoDay(new Date()); + let srv = o.server; // Phones and tablets are set up by scanning; computers and routers by a file. - const connect = await core.connectBlock(cfg, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file'); + const block = (c: ClientConfig) => core.connectBlock(c, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file'); + // An older configuration on the device: the new one waits for a click (the inline QR code is itself a delivery). + // `relinked`: its MTU or keep-alive was just changed here, which outdates the configuration on screen even where + // the router keeps no record of what the device got (never "stale" then, e.g. after a JSON import). + let gated = dev.config_stale; + let relinked = false; + const gate = () => + newConfigGate(dev.id, block, () => { + gated = false; + return changed(); + }); + const connect = gated ? gate() : await block(cfg); const titleEl = E('div', { class: 'dl-drawer-title' }); const stats = E('div', {}); const details = E('div', {}); @@ -184,7 +229,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { E('div', { class: 'dl-dstats' }, [ E('div', { class: 'dl-dstats-cell wide' }, [ E('span', { class: 'dl-metric-label' }, _('Status')), - deviceStatus(d, now, _('Waiting for the first connection'), p), + // Its link failing in a named way says so, with what it means; otherwise its usual status. + (d.link && !d.disabled && linkStatus(d.link)) || deviceStatus(d, now, _('Waiting for the first connection'), p), ]), E('div', { class: 'dl-dstats-cell' }, [ E('span', { class: 'dl-metric-label' }, _('This month')), @@ -202,6 +248,10 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { details, E('div', { class: 'dl-kv2' }, [ copyRow(_('Tunnel address'), d.address), + ...linkRows(d, p, srv, () => { + relinked = true; + return changed(); + }).map(([k, v]) => row(k, v)), d.hostname && p.access !== 'internet' ? copyRow(_('Local address'), d.hostname) : '', // Where it connects from is under Locations (with the place and network); from home // (not on the map) or without locations, here. @@ -287,7 +337,15 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { geo = st.geo; now = st.now; today = todayOf(st.series); + srv = st.servers.find((s) => s.id === p2.server); paint(); + // A change made here (its MTU or keep-alive) or elsewhere left the configuration on screen behind: the new one + // waits behind the button. + if ((d.config_stale || relinked) && !gated) { + gated = true; + dom.content(connectSec, connectBody(gate())); + } + relinked = false; view?.update({ geo: st.geo, now: st.now, person: p, device: d }); }; /** After a change made here: this drawer and the page. */ @@ -297,9 +355,10 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { }; const rename = () => { - const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement; + const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name }) as HTMLInputElement; + const said = nameGuard(input, () => nameRow.refresh()); const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name); - const nameRow = liveField(_('Name'), input, () => nameHelp(input.value, taken, _('Shown in the portal and in the app.'))); + const nameRow = liveField(_('Name'), input, () => said(deviceNameHelp(input.value, taken, _('Shown in the portal and in the app.')))); modal( fmt(_('Rename %s'), d.name), [nameRow], @@ -327,7 +386,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { }; const foot = E('div', { class: 'dl-drawer-actions' }); - const connectSec = E('section', { class: 'dl-dsec' }, [ + const connectBody = (c: HTMLElement) => [ // Whether it is connected (or still waiting) is in Status above. E('div', { class: 'dl-dsec-head' }, [E('h4', {}, _('Connect', 'section'))]), d.config_stale @@ -337,8 +396,9 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { ), ) : '', - connect, - ]); + c, + ]; + const connectSec = E('section', { class: 'dl-dsec' }, connectBody(connect)); const activitySec = E('section', { class: 'dl-dsec' }, [ E('div', { class: 'dl-dsec-head' }, [ E('h4', {}, _('Activity')), @@ -429,7 +489,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { /** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOpts) { const core = o.core ?? coreOf(null); - const cfg = () => attempt(() => api.deviceConfig(d.id)); + // Each of these gives the configuration out. + const cfg = () => attempt(() => api.deviceConfig(d.id, true)); const items: (MenuItem | null)[] = [ { label: _('Show QR code'), @@ -519,23 +580,49 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp dropdown(anchor, items); } +/** + * A device's name field guarded as the portal's are (shared/name-guard.ts): a refused character shakes the input, + * and the row's help says why until a change gets in or the field is left (Save never reads a stale reason). + * Returns what the row's help passes its own through. + */ +function nameGuard(input: HTMLInputElement, refresh: () => void): (help: Help) => Help { + let why: string | null = null; + guardDeviceName(input, input, (w) => { + why = w; + refresh(); + }); + input.addEventListener('blur', () => { + if (!why) return; + why = null; + refresh(); + }); + return (help) => (why ? { text: why, bad: true } : help); +} + /** Admin "Add device" dialog for a person; opens the new device's drawer. */ export function addDevice(person: Person, o: DeviceOpts) { const taken = person.devices.map((x) => x.name); // The name a type gives when none is typed: "Phone", then "Phone 2" (as the portal does). const suggest = (k: Kind) => { - const base = kindLabel(k); + const base = defaultName(k); let n = 1; - let name = base; - while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = `${base} ${++n}`; + let name = fitName(base); + while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = fitName(base, ` ${++n}`); return name; }; let kind: Kind = 'phone'; - const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: suggest(kind), maxlength: 48 }) as HTMLInputElement; + const nameInput = E('input', { + type: 'text', + class: 'cbi-input-text', + placeholder: suggest(kind), + }) as HTMLInputElement; + const said = nameGuard(nameInput, () => nameRow.refresh()); const nameRow = liveField(_('Name'), nameInput, () => - nameInput.value.trim() - ? nameHelp(nameInput.value, taken, _('Shown in the portal and in the app.')) - : { text: fmt(_('Named after its type: %s.'), suggest(kind)), bad: false }, + said( + nameInput.value.trim() + ? deviceNameHelp(nameInput.value, taken, _('Shown in the portal and in the app.')) + : { text: fmt(_('Named after its type: %s.'), suggest(kind)), bad: false }, + ), ); const kinds = E( 'div', @@ -564,6 +651,8 @@ export function addDevice(person: Person, o: DeviceOpts) { ), ), ); + // LAN Bypass: off unless chosen (the person chooses it on the portal, the admin here). + const bypass = sw(false, _('LAN Bypass')); const over = person.devices.length >= person.device_limit; modal( fmt(_('Add a device for %s'), person.name), @@ -585,6 +674,23 @@ export function addDevice(person: Person, o: DeviceOpts) { ) : '', E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Type')), kinds]), + // As the portal's Add a device: between the type and the name. + E('div', { class: 'cbi-value dl-live' }, [ + E('div', { class: 'cbi-value-title' }, [ + E('label', {}, _('LAN Bypass')), + E( + 'div', + { class: 'dl-sub' }, + homeOf(person, o.server).length + ? fmt( + _('The device’s local network stays reachable while connected, except %s: your home network.'), + netsLabel(homeOf(person, o.server)), + ) + : _('The device’s local network stays reachable while connected.'), + ), + ]), + E('div', { class: 'cbi-value-field' }, bypass), + ]), nameRow, ], [ @@ -599,7 +705,7 @@ export function addDevice(person: Person, o: DeviceOpts) { return; } const name = nameInput.value.trim() || suggest(kind); - const r = await attempt(() => api.deviceCreate(person.id, name, kind)); + const r = await attempt(() => api.deviceCreate(person.id, name, kind, isOn(bypass))); if (!r) return; closeModal(); notify(fmt(_('%s added'), name), 'success', 3000); diff --git a/web/src/admin/events/log-templates.ts b/web/src/admin/events/log-templates.ts index 4ebb166..f6c8bbf 100644 --- a/web/src/admin/events/log-templates.ts +++ b/web/src/admin/events/log-templates.ts @@ -24,6 +24,8 @@ export const LOG_TEMPLATES: string[] = [ "AmneziaWG isn't running", 'Backup', 'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.', + 'Changed: %s.', + 'Choose a disguise on the Server page: it replaces the values set by hand.', 'Choose another interface name in the server settings.', 'Components', 'Connections', @@ -31,6 +33,7 @@ export const LOG_TEMPLATES: string[] = [ "Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.", 'Firewall', 'Install it in Dawnline → Components.', + 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.', 'Internet like a home device', 'MTU is now automatic', 'Missing: %s.', @@ -71,7 +74,10 @@ export const LOG_TEMPLATES: string[] = [ 'has an invalid interface name "%s"', 'installed the %s build', 'installed the %s build · %s', + "interface %s has Dawnline's settings again", + 'interface %s was changed outside Dawnline', 'is kept down', + 'is kept down: its disguise has values AmneziaWG cannot take', 'is kept down: its disguise needs AmneziaWG %s (installed: %s)', 'is kept down: its disguise needs AmneziaWG %s (installed: none)', 'is off', diff --git a/web/src/admin/events/model.ts b/web/src/admin/events/model.ts index 519d496..99d7220 100644 --- a/web/src/admin/events/model.ts +++ b/web/src/admin/events/model.ts @@ -25,6 +25,8 @@ const CATEGORY: Record = { expiring: 'people', expired_kept: 'people', portal_blocked: 'problems', + device_failing: 'problems', + device_recovered: 'problems', }; export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems']; @@ -37,7 +39,7 @@ export function categoryHelp(c: LogCategory): string { return { 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)'), + problems: _('Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)'), }[c]; } @@ -134,6 +136,42 @@ export function changedText(detail: string): string { .join(', '); } +/** A device's settings a device_changed event lists (its link options, "mtu, keepalive"); anything else as written. */ +export function deviceChangedText(detail: string): string { + const f: Record = { mtu: 'MTU', keepalive: _('keep-alive'), lan_bypass: _('LAN Bypass') }; + return detail + .split(', ') + .map((k) => f[k] ?? k) + .join(', '); +} + +/** + * A device's link failing in a named way (dawnline.link's states), said about + * the device: its title and what it means (the device drawer's Status, the + * title also in Activity). Null for a state this page does not know. + */ +export function linkStateText(state: string): { title: string; line: string } | null { + const t: Record = { + trying: [_('Unable to complete the handshake'), _('The device’s network may be blocking the connection.')], + dropped: [_('Handshake complete, but no data'), _('This device is using an outdated configuration.')], + shared: [_('On two devices at once'), _('The same configuration connects from two places in turn. Give the other device its own.')], + unstable: [ + _('Connection keeps dropping'), + _('It connects, but the connection breaks every few minutes: the network may be cutting it.'), + ], + }; + const w = t[state]; + return w ? { title: w[0], line: w[1] } : null; +} + +/** The states a device_failing event names ("trying, unstable" when two came within an hour), by their titles. */ +export function linkStatesText(detail: string): string { + return detail + .split(', ') + .map((s) => linkStateText(s)?.title ?? s) + .join(', '); +} + /** * The admin's own change in the service log ({ msg: 'changed', kind: * 'server', who: 'Home' }), as one sentence: with %s for the name it names, diff --git a/web/src/admin/events/render.ts b/web/src/admin/events/render.ts index ced52ff..d704963 100644 --- a/web/src/admin/events/render.ts +++ b/web/src/admin/events/render.ts @@ -8,7 +8,20 @@ import { E } from '../e'; import { icon } from '../../shared/icons'; import { ago, fmtDay } from '../../shared/format'; import { fill, fmt, locale, num } from '../../shared/i18n'; -import { adminName, adminSentence, changedText, daysOf, eventBy, logText, noteText, plainDetail, reasonText, sourceName } from './model'; +import { + adminName, + adminSentence, + changedText, + daysOf, + deviceChangedText, + eventBy, + linkStatesText, + logText, + noteText, + plainDetail, + reasonText, + sourceName, +} from './model'; /** What the people and servers in the log are called now. */ export type Names = Pick; @@ -28,6 +41,8 @@ const EVENT_TONE: Record = { portal_blocked: 'bad', person_changed: '', devices_removed: 'warn', + device_failing: 'warn', + device_recovered: 'ok', }; /** The icon in an event's tile: the device's kind for device events, else what happened. */ @@ -93,7 +108,8 @@ export function eventText(st: Pick, e: LogEvent): Node[] { return [...you(_('You renamed device %s of %s'), d, b(who)), m(` · ${fmt(_('was %s'), detail.slice(13))}`)]; if (detail === 'turned off') return you(_('You turned off device %s of %s'), d, b(who)); if (detail === 'turned on') return you(_('You turned on device %s of %s'), d, b(who)); - return [...you(_('You changed device %s of %s'), d, b(who)), ...(detail ? [m(` · ${detail}`)] : [])]; + // Its own link options by name ("mtu, keepalive"), as person_changed lists a person's. + return [...you(_('You changed device %s of %s'), d, b(who)), ...(detail ? [m(` · ${deviceChangedText(detail)}`)] : [])]; } case 'device_keys': return [...you(_('You issued new keys for device %s of %s'), devName, b(who)), m(` · ${_('it needs its new configuration')}`)]; @@ -157,6 +173,10 @@ export function eventText(st: Pick, e: LogEvent): Node[] { ); case 'devices_removed': return say(_('Person %s - all devices removed, end date reached'), b(who)); + case 'device_failing': + return [...say(_('Device %s has a connection problem'), wd), ...(e.detail ? [m(` · ${linkStatesText(e.detail)}`)] : [])]; + case 'device_recovered': + return say(_('Device %s connects normally again'), wd); default: return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)]; } diff --git a/web/src/admin/netcheck.ts b/web/src/admin/netcheck.ts index 577ee72..d025267 100644 --- a/web/src/admin/netcheck.ts +++ b/web/src/admin/netcheck.ts @@ -2,6 +2,7 @@ // them (rpc/servers.uc) and said in plain words for the setup wizard. The // addresses are three numbers ("10.77.0"): the tunnel is that /24. +import { DEVICE_NAME_MAX, deviceNameFits } from '../shared/format'; import { fmt, locale, num, plural } from '../shared/i18n'; /** A network on the router, by name: an interface ("lan") or a server ("Home"). */ @@ -122,6 +123,16 @@ export function nameHelp(s: string, taken: string[] = [], good = ''): Help { return { text: good, bad: false }; } +/** + * A device's name (util.valid_device_name): up to DEVICE_NAME_MAX of letters (any language), digits, spaces and - _ . + * (an old name from before the rule says what to change in it). + */ +export function deviceNameHelp(s: string, taken: string[] = [], good = ''): Help { + if (chars(s.trim()) > DEVICE_NAME_MAX) return { text: tooLong(DEVICE_NAME_MAX, s.trim()), bad: true }; + if (!deviceNameFits(s.trim())) return { text: _('Letters, digits, spaces and - _ . only.'), bad: true }; + return nameHelp(s, taken, good); +} + /** A circle's name: like a name, up to 32 characters. */ export function circleNameHelp(s: string, taken: string[] = []): Help { if (chars(s) > 32) return { text: tooLong(32, s), bad: true }; @@ -198,6 +209,20 @@ export function keepaliveHelp(s: string): Help { return { text: fmt(_('Devices send a packet every %s s to keep NAT open (a little battery on phones).'), t), bad: false }; } +/** A device's own MTU (core.set_device_link): empty = automatic (the server's for its kind), else 1280–1500. */ +export function deviceMtuHelp(s: string): Help { + const t = s.trim(); + if (t && (!/^\d{1,4}$/.test(t) || Number(t) < 1280 || Number(t) > 1500)) return { text: _('From 1280 to 1500.'), bad: true }; + return { text: _('Empty: automatic. Lower it when big pages hang on this device.'), bad: false }; +} + +/** A device's own keep-alive (core.set_device_link): empty = the server's, else 0–600 s (0 = off). */ +export function deviceKeepaliveHelp(s: string): Help { + const t = s.trim(); + if (t && (!/^\d{1,4}$/.test(t) || Number(t) > 600)) return { text: _('From 0 to 600 seconds.'), bad: true }; + return { text: _('Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops.'), bad: false }; +} + /** Device limit (core.create_person): 1–32; `have` is how many they have now (an edit). */ export function limitHelp(s: string, have = 0): Help { const t = s.trim(); diff --git a/web/src/admin/pages/overview.ts b/web/src/admin/pages/overview.ts index 504dd31..b5e0c86 100644 --- a/web/src/admin/pages/overview.ts +++ b/web/src/admin/pages/overview.ts @@ -14,8 +14,9 @@ import { ConnectionMap, rangeControl, type Range } from '../map'; import { personUrl } from '../urls'; import { eventRow } from '../events/render'; import { scoped } from '../state/scope'; -import { repaint } from '../state/poller'; -import { daysTile, speedTile } from '../widgets/tiles'; +import { focusInside, repaint } from '../state/poller'; +import type { LiveMeter } from '../state/meter'; +import { daysTile, LiveSpeedTile } from '../widgets/tiles'; import { coreOf } from '../cores'; import { healthNotices, runFix } from '../widgets/health'; import { attempt } from '../ui/toast'; @@ -128,10 +129,13 @@ export class ServerOverview { range: Range = 'online'; parts: Record = {}; healthAt = 0; + /** Speed now, live: one tile for this Overview's life, its numbers put in place each second. */ + speed = new LiveSpeedTile(); - /** `go` switches the Servers page to another section in place. */ + /** `meter` is the Servers page's live meter (it polls it); `go` switches the page to another section in place. */ constructor( readonly srvId: string, + private meter: LiveMeter, private go?: (section: string, filter?: string) => void, ) {} @@ -249,11 +253,13 @@ export class ServerOverview { const srv = st.servers[0]; this.paintMap(); - repaint( - this.parts.bento, - E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]), - quiet, - ); + // The live speed tile moves into a new bento: one is made only when it is put on the page. + if (quiet && focusInside(this.parts.bento)) this.paintSpeed(); + else + dom.content( + this.parts.bento, + E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]), + ); const att = attention(st); repaint( @@ -446,12 +452,19 @@ export class ServerOverview { } /** - * Throughput right now (from the agent's minute samples): download and - * upload side by side, the last 15 minutes as a small chart, today's total. + * Throughput right now (the live meter, one point a second): download and + * upload side by side, the last 2 minutes as a small chart, today's total. */ speedTile(): HTMLElement { + this.paintSpeed(); + return this.speed.el; + } + + /** The speed tile from the meter as it stands (the Servers page calls this with each answer). */ + paintSpeed() { + if (!this.st) return; const srv = this.st.servers[0]; - return speedTile(srv?.rate ?? [], this.st.now, this.st.totals.today, srv ? !srv.enabled : false); + this.speed.update(this.meter.speed(this.srvId, Date.now()), this.st.totals.today, srv ? !srv.enabled : false); } /** The last 30 days, today on the right, with the peak. */ diff --git a/web/src/admin/pages/people.ts b/web/src/admin/pages/people.ts index a1972ba..bb1f0fb 100644 --- a/web/src/admin/pages/people.ts +++ b/web/src/admin/pages/people.ts @@ -154,6 +154,7 @@ export class PeoplePage { now: this.st.now, today: this.today, core: coreFor(this.st.servers, p.server), + server: this.st.servers.find((s) => s.id === p.server), }; } diff --git a/web/src/admin/pages/person/devices.ts b/web/src/admin/pages/person/devices.ts index 22ceb8e..9900cd7 100644 --- a/web/src/admin/pages/person/devices.ts +++ b/web/src/admin/pages/person/devices.ts @@ -17,13 +17,13 @@ import type { PersonPage } from './index'; /** Setting up a device: its QR code (key and file one tap away). */ async function showDeviceQr(page: PersonPage, d: Device) { - const cfg = await attempt(() => api.deviceConfig(d.id)); + const cfg = await attempt(() => api.deviceConfig(d.id, true)); if (!cfg) return; modal(fmt(_('Set up %s'), d.name), [await page.core.connectBlock(cfg, 'qr')], [cancelButton(_('Close'))]); } async function downloadConfig(page: PersonPage, d: Device) { - const cfg = await attempt(() => api.deviceConfig(d.id)); + const cfg = await attempt(() => api.deviceConfig(d.id, true)); if (!cfg) return; if (!cfg.has_private_key) { notify(_('This device made its own keys in the browser; its configuration only exists there.'), 'warning'); diff --git a/web/src/admin/pages/person/index.ts b/web/src/admin/pages/person/index.ts index 89de5dd..873efac 100644 --- a/web/src/admin/pages/person/index.ts +++ b/web/src/admin/pages/person/index.ts @@ -161,6 +161,7 @@ export class PersonPage { now: this.st.now, today: this.today, core: this.core, + server: this.st.servers.find((s) => s.id === this.p.server), events: () => this.events, }; } diff --git a/web/src/admin/pages/server.ts b/web/src/admin/pages/server.ts index a5ff699..3acf7d9 100644 --- a/web/src/admin/pages/server.ts +++ b/web/src/admin/pages/server.ts @@ -23,6 +23,7 @@ import { defaultMethod, methodPicker } from '../disguise'; import { coreOf } from '../cores'; import { installAwg } from '../pkgs'; import { createPoller, focusInside, repaint, type Poller } from '../state/poller'; +import { LiveMeter, type MeterAnswer } from '../state/meter'; import { ServerOverview } from './overview'; import { PeoplePage } from './people'; @@ -64,6 +65,9 @@ export class ServerPage { secEl = E('div', {}); bodyEl = E('div', { class: 'dl-srvbody' }); poller?: Poller; + /** The live meter's last 2 minutes, every server's (the Overviews' Speed now), and its poller. */ + meter = new LiveMeter(); + meterPoller?: Poller; async load(): Promise<[Status, SetupDefaults | null]> { const st = await api.status(31); @@ -100,6 +104,23 @@ export class ServerPage { this.ov[this.current().id]?.update(n, quiet); }, }); + // Speed now, live: one meter call a second while the Overview of a running server is on screen + // (the router keeps the last two minutes and writes them out while someone asks). A failed call is said in the tile, not in a + // second "not answering" toast beside the status poller's. + this.meterPoller?.stop(); + this.meterPoller = createPoller({ + fetch: () => + api.meter(this.meter.since(Date.now())).then( + (meter) => ({ meter }), + (e) => ({ error: errorText(e) }), + ), + every: 1, + active: () => this.section === 'overview' && this.root.isConnected && this.current().enabled, + apply: (r) => { + this.meter.take(r, Date.now()); + this.ov[this.current().id]?.paintSpeed(); + }, + }); return this.root; } @@ -229,7 +250,7 @@ export class ServerPage { const body: Record Node> = { overview: () => { const ov = this.ov[srv.id]; - if (!ov) return (this.ov[srv.id] = new ServerOverview(srv.id, (k, f) => this.go(k as Section, f))).mount(st); + if (!ov) return (this.ov[srv.id] = new ServerOverview(srv.id, this.meter, (k, f) => this.go(k as Section, f))).mount(st); ov.update(st); return ov.el; }, diff --git a/web/src/admin/state/meter.ts b/web/src/admin/state/meter.ts new file mode 100644 index 0000000..38d532a --- /dev/null +++ b/web/src/admin/state/meter.ts @@ -0,0 +1,108 @@ +// The live meter as the Servers page keeps it (rpc meter, polled once a +// second while an Overview is on screen): the answers merged into the last two +// minutes, and one server's part of them for its Speed now tile. No DOM and no +// RPC here: the poller is the page's (pages/server.ts), the tile widgets/tiles. + +import type { Meter, MeterPoint } from '../api'; + +/** [ts, rx, tx] in bytes/s, as Server.rate: rx = from the devices, tx = to them. */ +export type Rate = [number, number, number]; + +/** One call's outcome: the meter, or why there is none. */ +export type MeterAnswer = { meter: Meter } | { error: string }; + +/** Page milliseconds after the last answer when what is kept stops counting as live: the next call asks for everything again. */ +const STALE_MS = 5000; +/** Router seconds the newest point is "now": an agent that stopped leaves its last one behind. */ +const FRESH_S = 5; +/** Failed calls in a row before the tile says so (one may just be slow). */ +const LOST_AFTER = 3; +/** + * Answers with no points before the tile says it is collecting: the first call of a look finds none, and the + * router writes out the two minutes it kept within a second. + */ +const EARLY = 3; + +/** One server's live speed, ready for the tile. */ +export interface LiveSpeed { + /** Its points, oldest first. */ + pts: Rate[]; + /** Where each one sits across the chart: 1 is the newest point the meter has, 0 two minutes before it. */ + xs: number[]; + /** Bytes/s now: its newest point while that is fresh, else 0. */ + rx: number; + tx: number; + /** Why the meter could not be read, once that happened a few times in a row; null otherwise. */ + error: string | null; + /** No points yet, a moment after asking: the router is writing out what it kept (the tile waits without words). */ + early: boolean; +} + +export class LiveMeter { + private points: MeterPoint[] = []; + /** Page clock (ms) of the last answer. */ + private at = 0; + /** Router clock of the last answer. */ + private now = 0; + private keep = 120; + private failed = 0; + private error = ''; + /** Answers in a row that left nothing kept. */ + private empty = 0; + + /** Still live at page time `ms`: kept points from an answer a moment ago. */ + private live(ms: number): boolean { + return this.points.length > 0 && ms - this.at < STALE_MS; + } + + /** What to ask for: the points after the newest one kept, or all of them (0) when nothing live is kept. */ + since(ms: number): number { + return this.live(ms) ? this.points[this.points.length - 1].ts : 0; + } + + /** An answer at page time `ms`: new points appended, those over two minutes behind the newest dropped. */ + take(r: MeterAnswer, ms: number): void { + if ('error' in r) { + this.failed++; + this.error = r.error; + return; + } + const m = r.meter; + let kept = this.live(ms) ? this.points : []; + // The router's clock went back: its points are now behind what is kept, and asking for those after the newest + // kept would never bring them. Start over: the next call asks for everything. + if (kept.length && m.ts > 0 && m.ts < kept[kept.length - 1].ts) kept = []; + const last = kept.length ? kept[kept.length - 1].ts : 0; + const all = [...kept, ...m.points.filter((p) => p.ts > last)]; + this.keep = m.keep > 1 ? m.keep : 120; + const end = all.length ? all[all.length - 1].ts : 0; + this.points = all.filter((p) => p.ts > end - this.keep); + this.empty = this.points.length ? 0 : this.empty + 1; + this.at = ms; + this.now = m.now; + this.failed = 0; + this.error = ''; + } + + /** Server `id`'s points at page time `ms` (none once they are not live), placed against the meter's newest point. */ + speed(id: string, ms: number): LiveSpeed { + const error = this.failed >= LOST_AFTER ? this.error : null; + const live = this.live(ms) ? this.points : []; + // A second its tunnel was not read has no point of its own. + const pts = live.flatMap((p): Rate[] => (p.servers[id] ? [[p.ts, p.servers[id][0], p.servers[id][1]]] : [])); + const end = live.length ? live[live.length - 1].ts : 0; + const span = this.keep - 1; + const last = pts[pts.length - 1]; + // A point dated after the router's now (its clock went back) is no speed now either. + const age = last ? this.now - last[0] : -1; + const fresh = age >= 0 && age < FRESH_S; + return { + pts, + xs: pts.map((p) => 1 - (end - p[0]) / span), + rx: fresh ? last[1] : 0, + tx: fresh ? last[2] : 0, + error, + early: !live.length && this.empty < EARLY, + }; + } +} diff --git a/web/src/admin/styles/layout.css b/web/src/admin/styles/layout.css index f719d5f..4b3190f 100644 --- a/web/src/admin/styles/layout.css +++ b/web/src/admin/styles/layout.css @@ -44,5 +44,8 @@ .dl-seg button b.warn { background: var(--dl-warn-wash); color: var(--dl-warn); } .dl-seg.sm button { padding: 2px 9px; font-size: 11px; } .dl-seg.wide { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); border-radius: 12px; padding: 4px; } -.dl-seg.wide button { flex-direction: column; justify-content: center; padding: 8px 6px; border-radius: 9px; gap: 3px; } +/* Three equal columns: a label longer than its column (Russian "Дом и интернет") wraps under its icon instead of + running out of the button. */ +.dl-seg.wide button { flex-direction: column; justify-content: center; padding: 8px 6px; border-radius: 9px; gap: 3px; + white-space: normal; text-align: center; line-height: 16px; } .dl-seg.wide button.on { background: var(--dl-primary); color: var(--dl-primary-fg); } diff --git a/web/src/admin/widgets/tiles.ts b/web/src/admin/widgets/tiles.ts index 83f3e9b..183ec37 100644 --- a/web/src/admin/widgets/tiles.ts +++ b/web/src/admin/widgets/tiles.ts @@ -1,7 +1,8 @@ // Bento tiles shared by the server Overview and the person page: speed now -// and the last 30 days. +// (from the minute samples, or live on the Overview) and the last 30 days. import type { DayUsage } from '../../shared/types'; +import type { LiveSpeed, Rate } from '../state/meter'; import { E } from '../e'; import { bits, bytes, parseDay } from '../../shared/format'; import { fill, fmt, locale } from '../../shared/i18n'; @@ -10,37 +11,53 @@ import { svg } from '../ui/layout'; const dayLabel = (day: string) => parseDay(day).toLocaleDateString(locale(), { day: 'numeric', month: 'short' }); +/** The speed chart's box (its viewBox; CSS stretches it to the tile). */ +const W = 200, + H = 40; + +/** The speed chart's lines through `pts` at `xs` (0–1 across): download filled, upload over it. */ +function chartPaths(pts: Rate[], xs: number[]): { area: string; down: string; up: string } { + const max = Math.max(1, ...pts.map((p) => Math.max(p[1], p[2]))); + const line = (k: 1 | 2) => pts.map((p, i) => `${xs[i] * W},${H - 2 - (p[k] / max) * (H - 6)}`); + const dl = line(2), + ul = line(1); + return { + area: `M${dl.join(' L')} L${xs[xs.length - 1] * W},${H} L${xs[0] * W},${H}Z`, + down: `M${dl.join(' L')}`, + up: `M${ul.join(' L')}`, + }; +} + +/** One of the two speeds: its arrow and label, then the value. */ +const speedCol = (label: string, ic: string, cls: string, val: HTMLElement) => + E('div', { class: 'dl-speed-col' }, [E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]), val]); + +/** Today's traffic under the chart (`today` is [rx, tx]). */ +const todayParts = ([rx, tx]: [number, number]) => [ + E('span', {}, fill(_('Today %s'), E('b', {}, bytes(rx + tx)))), + E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]), +]; + /** * Throughput over the last 15 minutes plus today's total. `off`: the server is * turned off, so there is no speed to show (dashes, not zeros) and no chart. */ -export function speedTile(rate: [number, number, number][], now: number, today: [number, number], off = false): HTMLElement { +export function speedTile(rate: Rate[], now: number, today: [number, number], off = false): HTMLElement { const pts = rate.slice(-15); const last = pts[pts.length - 1]; const fresh = last && now - last[0] < 180; const down = fresh ? last[2] : 0, up = fresh ? last[1] : 0; - const [rx, tx] = today; - const W = 200, - H = 40; - const max = Math.max(1, ...pts.map((p) => Math.max(p[1], p[2]))); - const line = (k: 1 | 2) => pts.map((p, i) => `${pts.length > 1 ? (i / (pts.length - 1)) * W : W},${H - 2 - (p[k] / max) * (H - 6)}`); - const dl = line(2), - ul = line(1); - const chart = - pts.length > 1 && !off - ? svg( - ``, - ) - : E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, _('Collecting… 1 point a minute'))]); - const col = (label: string, ic: string, cls: string, v: number) => - E('div', { class: 'dl-speed-col' }, [ - E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]), - off ? E('span', { class: 'dl-speed-val off' }, '—') : E('span', { class: 'dl-speed-val' }, bits(v)), - ]); - if (pts.length > 1 && !off) + let chart: HTMLElement; + if (pts.length > 1 && !off) { + const d = chartPaths( + pts, + pts.map((_x, i) => i / (pts.length - 1)), + ); + chart = svg( + ``, + ); attachTip(chart, () => { const p = pts[pts.length - 1]; return [ @@ -48,20 +65,88 @@ export function speedTile(rate: [number, number, number][], now: number, today: E('div', {}, `↓ ${bits(p[2])} · ↑ ${bits(p[1])}`), ]; }); + } else chart = E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, _('Collecting… 1 point a minute'))]); + const val = (v: number) => (off ? E('span', { class: 'dl-speed-val off' }, '—') : E('span', { class: 'dl-speed-val' }, bits(v))); return E('div', { class: 'dl-bento-tile' }, [ E('div', { class: 'dl-bento-head' }, [ E('span', { class: 'dl-metric-label' }, _('Speed now')), off ? '' : E('span', { class: 'dl-sub' }, _('last 15 min')), ]), - E('div', { class: 'dl-speed-cols' }, [col(_('Download', 'speed'), '↓', 'dl-dn', down), col(_('Upload', 'speed'), '↑', 'dl-up', up)]), - chart, - E('div', { class: 'dl-speed-today' }, [ - E('span', {}, fill(_('Today %s'), E('b', {}, bytes(rx + tx)))), - E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]), + E('div', { class: 'dl-speed-cols' }, [ + speedCol(_('Download', 'speed'), '↓', 'dl-dn', val(down)), + speedCol(_('Upload', 'speed'), '↑', 'dl-up', val(up)), ]), + chart, + E('div', { class: 'dl-speed-today' }, todayParts(today)), ]); } +/** + * Speed now, live (the server Overview): speedTile's tile, its chart the last + * 2 minutes one point a second (state/meter.ts). Built once; update() puts each + * second's numbers and lines in place. No tooltip: the numbers above the chart + * are its newest point already. + */ +export class LiveSpeedTile { + private span = E('span', { class: 'dl-sub' }, _('last 2 min')); + private down = E('span', { class: 'dl-speed-val' }); + private up = E('span', { class: 'dl-speed-val' }); + private chart = svg( + ``, + ); + private wait = E('div', { class: 'dl-speed-wait' }); + /** The chart or the waiting line, whichever is in the tile. */ + private shown = this.wait; + private today = E('div', { class: 'dl-speed-today' }); + readonly el = E('div', { class: 'dl-bento-tile' }, [ + E('div', { class: 'dl-bento-head' }, [E('span', { class: 'dl-metric-label' }, _('Speed now')), this.span]), + E('div', { class: 'dl-speed-cols' }, [ + speedCol(_('Download', 'speed'), '↓', 'dl-dn', this.down), + speedCol(_('Upload', 'speed'), '↑', 'dl-up', this.up), + ]), + this.wait, + this.today, + ]); + + /** + * This second's speed and today's traffic ([rx, tx]). `off`: the server is + * turned off (dashes, no chart); a meter that cannot be read says why in + * the chart's place, with dashes for the speeds. + */ + update(s: LiveSpeed, today: [number, number], off: boolean): void { + const none = off || !!s.error; + this.span.style.display = off ? 'none' : ''; + for (const [el, v] of [ + [this.down, s.tx], + [this.up, s.rx], + ] as const) { + el.className = `dl-speed-val${none ? ' off' : ''}`; + el.textContent = none ? '—' : bits(v); + } + const lines = !none && s.pts.length > 1; + if (lines) { + const p = chartPaths(s.pts, s.xs); + const [area, down, up] = this.chart.querySelectorAll('path'); + area.setAttribute('d', p.area); + down.setAttribute('d', p.down); + up.setAttribute('d', p.up); + } else + dom.content(this.wait, [ + E('i'), + off || (s.early && !s.error) + ? '' + : E('span', {}, s.error ? fmt(_("Couldn't read the live speed: %s"), s.error) : _('Collecting… 1 point a second')), + ]); + const want = lines ? this.chart : this.wait; + if (want !== this.shown) { + this.shown.replaceWith(want); + this.shown = want; + } + dom.content(this.today, todayParts(today)); + } +} + /** Daily traffic for the last 30 days, today on the right. */ export function daysTile(series: DayUsage[], note: string): HTMLElement { const days = series.slice(-30); diff --git a/web/src/portal/demo/data.ts b/web/src/portal/demo/data.ts index 0105dc1..205e232 100644 --- a/web/src/portal/demo/data.ts +++ b/web/src/portal/demo/data.ts @@ -62,8 +62,15 @@ export interface DemoDevice { created: number; by: 'admin' | 'portal'; stale: boolean; + /** A set-up state the visitor picked in the sheet (way-pick.ts), held until they pick another; none: as it comes. */ + way?: DemoWay; + /** When it was picked: the knocks' or the handshake's time. */ + wayAt?: number; } +/** The set-up states the visitor can hold a device in (connected is a real handshake: router.ts). */ +export type DemoWay = 'waiting' | 'trying' | 'nodata'; + /** The scenario's own devices, as it starts. */ export function seedDevices(s: ScenarioId, t: number, id: () => string): DemoDevice[] { if (s === 'first') return []; @@ -135,8 +142,12 @@ export function hoursAway(t: number): string { export const handshakeOf = (d: DemoDevice, t: number) => (d.connectAt && t >= d.connectAt ? d.connectAt : d.hs); function device(d: DemoDevice, t: number, st: Person['state']): Device { - const hs = handshakeOf(d, t); + // Held waiting or knocking: no handshake; no data: one handshake when it was picked, nothing after it. + const at = d.wayAt ?? t; + const hs = d.way === 'nodata' ? at : d.way ? 0 : handshakeOf(d, t); const month = d.gb * GB; + // A stopped person's tunnels are down; the rest count as online for three minutes after a handshake. + const online = !!hs && t - hs < 180 && st !== 'paused' && st !== 'expired'; return { id: d.id, name: d.name, @@ -145,8 +156,7 @@ function device(d: DemoDevice, t: number, st: Person['state']): Device { disabled: false, created: d.created, created_by: d.by, - // A stopped person's tunnels are down; the rest count as online for three minutes after a handshake. - online: !!hs && t - hs < 180 && st !== 'paused' && st !== 'expired', + online, handshake: hs, endpoint: hs ? `203.0.113.${20 + d.n}` : '', active: true, @@ -158,6 +168,22 @@ function device(d: DemoDevice, t: number, st: Person['state']): Device { hostname: `${label(d.name)}.user.lan`, browser_key: false, config_stale: d.stale, + lan_bypass: false, + mtu: 0, + keepalive: null, + // The server's for its kind, as the router works it out (the portal never shows it). + mtu_used: d.kind === 'phone' || d.kind === 'tablet' ? 1280 : 1368, + keepalive_used: 25, + link: null, + // The demo's devices pass data whenever they are connected: the set-up sheet sees one arrive. + setup: + d.way === 'trying' + ? { state: 'trying', since: at } + : d.way === 'nodata' + ? { state: 'nodata', since: at } + : online + ? { state: 'flowing', since: hs } + : null, }; } @@ -204,6 +230,8 @@ export function pageState(s: ScenarioId, devs: DemoDevice[], t: number, secureUr device_mesh: true, awg_disguise: s !== 'plain', preset: s === 'plain' ? 'off' : 'max', + // A home network as most routers come with it: LAN Bypass then says those addresses still lead home. + home: ['192.168.1.0/24'], }, can_add: devs.length < limit, locked: locked(s), diff --git a/web/src/portal/demo/demo.css b/web/src/portal/demo/demo.css index 09a4870..0d0a2de 100644 --- a/web/src/portal/demo/demo.css +++ b/web/src/portal/demo/demo.css @@ -1,6 +1,6 @@ /* The portal demo's stylesheet: the portal's own, then the demo's pieces in its tokens — the "Demo" - chip after the breadcrumb's path, the GitHub pill beside the page's QR knob, and the scenario - rows in the drawer. */ + chip after the breadcrumb's path, the GitHub pill beside the page's QR knob, the scenario + rows in the drawer, and the set-up state switch beside the set-up sheet's ×. */ @import '../styles/index.css'; /* The path keeps its width so the chip sits right after it; the page's QR stays at the end. */ @@ -149,3 +149,154 @@ display: none; } } + +/* The set-up state switch: a pill beside ×, gliding into its place when the device arrives. */ +.dm-way { + position: absolute; + z-index: 3; + top: 22px; + display: inline-flex; + align-items: center; + gap: 7px; + height: 32px; + padding: 0 10px 0 12px; + border-radius: 999px; + background: var(--knob); + color: var(--text); + font-size: 13px; + font-weight: 500; + transition: + background-color 150ms, + transform 150ms var(--ease-out), + right var(--spring-smooth-dur) var(--spring-smooth); +} +.dm-way:hover { + background: color-mix(in srgb, var(--knob), var(--text) 6%); +} +.dm-way:active { + transform: scale(0.95); +} +.dm-way[aria-expanded='true'] { + background: color-mix(in srgb, var(--knob), var(--text) 10%); +} +.dm-way .i { + width: 14px; + height: 14px; + color: var(--text-2); + transform: rotate(90deg); + transition: transform 240ms var(--ease-out); +} +.dm-way[aria-expanded='true'] .i { + transform: rotate(-90deg); +} +.dm-way .dot, +.dm-way-pop .dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--text-3); + transition: + background-color 300ms, + opacity 150ms; +} +.dm-way .dot.warn, +.dm-way-pop .dot.warn { + background: var(--warn); +} +.dm-way .dot.ok, +.dm-way-pop .dot.ok { + background: var(--ok); +} + +/* Its popup: segments in one pill frame, a step above the sheet each (white on grey in light), a tail down + to the pill, and a dark, softly blurred halo behind that fades out around it. */ +.dm-way-pop { + --frame: color-mix(in srgb, var(--field), var(--knob) 55%); + --seg: color-mix(in srgb, var(--knob), var(--text) 2%); + --seg-hover: color-mix(in srgb, var(--knob), var(--text) 6%); + position: fixed; + z-index: 60; + display: flex; + gap: 3px; + padding: 3px; + border-radius: 999px; + background: var(--frame); + box-shadow: var(--pop-shadow); +} +.dm-way-pop::before { + content: ''; + position: absolute; + bottom: -5px; + left: var(--tail, 50%); + width: 12px; + height: 12px; + margin-left: -6px; + border-radius: 0 0 3px 0; + background: var(--frame); + transform: rotate(45deg); +} +.dm-way-pop button { + position: relative; + display: inline-flex; + align-items: center; + gap: 6px; + height: 34px; + padding: 0 10px; + border-radius: 10px; + background: var(--seg); + color: color-mix(in srgb, var(--text-2), var(--text-3) 35%); + font-size: 12.5px; + font-weight: 500; + white-space: nowrap; + transition: + color 150ms, + background-color 150ms, + transform 150ms var(--ease-out); +} +/* The ends follow the frame: half the segment's height (a larger radius would shrink every corner). */ +.dm-way-pop button:first-of-type { + border-radius: 17px 10px 10px 17px; + padding-left: 13px; +} +.dm-way-pop button:last-of-type { + border-radius: 10px 17px 17px 10px; + padding-right: 13px; +} +.dm-way-pop button:hover { + color: color-mix(in srgb, var(--text-2), var(--text) 45%); + background: var(--seg-hover); +} +.dm-way-pop button:active { + transform: scale(0.96); +} +.dm-way-pop button[aria-checked='true'] { + color: var(--text); +} +.dm-way-pop .dot { + background: currentColor; + opacity: 0.5; +} +.dm-way-pop button[aria-checked='true'] .dot, +.dm-way-pop button:hover .dot { + opacity: 1; +} +.dm-way-halo { + position: fixed; + z-index: 59; + pointer-events: none; + background: radial-gradient(closest-side, rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.35) 55%, transparent); + -webkit-backdrop-filter: blur(3px); + backdrop-filter: blur(3px); + -webkit-mask-image: radial-gradient(closest-side, #000 60%, transparent 92%); + mask-image: radial-gradient(closest-side, #000 60%, transparent 92%); +} +@media (prefers-color-scheme: light) { + .dm-way-pop { + --frame: var(--knob); + --seg: var(--raised); + --seg-hover: color-mix(in srgb, var(--raised), var(--text) 4%); + } + .dm-way-halo { + background: radial-gradient(closest-side, rgba(0, 0, 0, 0.14), rgba(0, 0, 0, 0.07) 55%, transparent); + } +} diff --git a/web/src/portal/demo/i18n/demo.pot b/web/src/portal/demo/i18n/demo.pot index b0a00c1..4302d65 100644 --- a/web/src/portal/demo/i18n/demo.pot +++ b/web/src/portal/demo/i18n/demo.pot @@ -18,6 +18,10 @@ msgstr "" msgid "Access only at certain hours of the day." msgstr "" +#: web/src/portal/demo/way-pick.ts +msgid "Auto" +msgstr "" + #: web/src/portal/demo/crumbs.ts msgid "Dawnline on GitHub" msgstr "" @@ -50,10 +54,18 @@ msgstr "" msgid "How the page looks in each case. Nothing here connects." msgstr "" +#: web/src/portal/demo/way-pick.ts +msgid "No data" +msgstr "" + #: web/src/portal/demo/data.ts msgid "No free slots" msgstr "" +#: web/src/portal/demo/way-pick.ts +msgid "Online" +msgstr "" + #: web/src/portal/demo/data.ts msgid "Opened over plain HTTP" msgstr "" @@ -78,6 +90,10 @@ msgstr "" msgid "Plain WireGuard" msgstr "" +#: web/src/portal/demo/way-pick.ts +msgid "Set-up state" +msgstr "" + #: web/src/portal/demo/data.ts msgid "Settings changed" msgstr "" @@ -122,6 +138,14 @@ msgstr "" msgid "Try a scenario" msgstr "" +#: web/src/portal/demo/way-pick.ts +msgid "Trying" +msgstr "" + +#: web/src/portal/demo/way-pick.ts +msgid "Waiting" +msgstr "" + #: web/src/portal/demo/data.ts msgid "Your page" msgstr "" diff --git a/web/src/portal/demo/i18n/ru.po b/web/src/portal/demo/i18n/ru.po index 78cc388..e977244 100644 --- a/web/src/portal/demo/i18n/ru.po +++ b/web/src/portal/demo/i18n/ru.po @@ -20,6 +20,10 @@ msgstr "Доступ закончился" msgid "Access only at certain hours of the day." msgstr "Доступ только в определённые часы." +#: web/src/portal/demo/way-pick.ts +msgid "Auto" +msgstr "Авто" + #: web/src/portal/demo/crumbs.ts msgid "Dawnline on GitHub" msgstr "Dawnline на GitHub" @@ -52,10 +56,18 @@ msgstr "Первый визит" msgid "How the page looks in each case. Nothing here connects." msgstr "Как выглядит страница в каждом случае. Ничего не подключается по-настоящему." +#: web/src/portal/demo/way-pick.ts +msgid "No data" +msgstr "Нет данных" + #: web/src/portal/demo/data.ts msgid "No free slots" msgstr "Нет свободных мест" +#: web/src/portal/demo/way-pick.ts +msgid "Online" +msgstr "В сети" + #: web/src/portal/demo/data.ts msgid "Opened over plain HTTP" msgstr "Открыто по обычному HTTP" @@ -80,6 +92,10 @@ msgstr "Доступ на паузе" msgid "Plain WireGuard" msgstr "Обычный WireGuard" +#: web/src/portal/demo/way-pick.ts +msgid "Set-up state" +msgstr "Состояние настройки" + #: web/src/portal/demo/data.ts msgid "Settings changed" msgstr "Настройки изменились" @@ -124,6 +140,14 @@ msgstr "Три устройства: одно в сети, одно ждёт н msgid "Try a scenario" msgstr "Выберите сценарий" +#: web/src/portal/demo/way-pick.ts +msgid "Trying" +msgstr "Попытки" + +#: web/src/portal/demo/way-pick.ts +msgid "Waiting" +msgstr "Ожидание" + #: web/src/portal/demo/data.ts msgid "Your page" msgstr "Ваша страница" diff --git a/web/src/portal/demo/main.ts b/web/src/portal/demo/main.ts index 0104136..54ccd48 100644 --- a/web/src/portal/demo/main.ts +++ b/web/src/portal/demo/main.ts @@ -1,7 +1,7 @@ // The portal demo (npm run build:demo → dist/demo, a static site): the real // portal over a router that lives in the page (serve.ts, router.ts, data.ts), // with a scenario picker and a GitHub link in the breadcrumb (crumbs.ts, -// picker.ts). The order of the imports is the boot order: the router owns +// picker.ts) and a set-up state switch in the set-up sheet (way-pick.ts). The order of the imports is the boot order: the router owns // fetch before the portal loads. // First: the translation globals, before anything draws. @@ -11,10 +11,12 @@ import { router } from './serve'; import '../main'; import { toast } from '../ui/feedback'; import { mountCrumbs } from './crumbs'; +import { mountWayPick } from './way-pick'; // The demo's own words (the scenarios, its chip and toasts), beside the portal's. addCatalog('ru', ru); mountCrumbs(router); +mountWayPick(router); // An AmneziaVPN key would add a server that connects nowhere to the visitor's app: the demo keeps it on the page. document.addEventListener( diff --git a/web/src/portal/demo/picker.ts b/web/src/portal/demo/picker.ts index c94d663..68265e6 100644 --- a/web/src/portal/demo/picker.ts +++ b/web/src/portal/demo/picker.ts @@ -7,7 +7,7 @@ import { h, ic } from '../dom'; import { call } from '../api'; import { repaint, setState, type State } from '../state'; -import { closeSheet, head, openSheet, sub, type View } from '../ui/sheet'; +import { closeSheet, head, onSheetEntry, openSheet, sub, type View } from '../ui/sheet'; import { glass, type Tone } from '../ui/glass'; import { toast } from '../ui/feedback'; import { EASE_OUT, play } from '../motion'; @@ -34,11 +34,16 @@ export function scenarioChip(router: DemoRouter): HTMLElement { /** Swap the page in place: it dims away and comes back drawn from the scenario, the link saying which. */ async function pick(s: ScenarioId, done?: string) { + // The link goes on the page's own history entry, once the sheet's is stepped back off: a reload keeps the scenario. + const mark = () => { + const u = new URL(location.href); + u.searchParams.set('s', s); + history.replaceState(history.state, '', u); + }; + if (onSheetEntry()) addEventListener('popstate', mark, { once: true }); + else mark(); closeSheet(); router.use(s); - const u = new URL(location.href); - u.searchParams.set('s', s); - history.replaceState(history.state, '', u); const out = play(app, [{ opacity: 1 }, { opacity: 0, filter: 'blur(4px)' }], { duration: 160, easing: EASE_OUT, fill: 'forwards' }); const st = await call('state'); await out.finished; diff --git a/web/src/portal/demo/router.ts b/web/src/portal/demo/router.ts index f583688..c29b7a2 100644 --- a/web/src/portal/demo/router.ts +++ b/web/src/portal/demo/router.ts @@ -6,7 +6,18 @@ // itself is data.ts; serve.ts puts this router behind the page's fetch. import type { AwgConfig, Kind } from '../../shared/types'; -import { ENDPOINT, deviceLimit, isScenario, pageState, seedDevices, type DemoDevice, type ScenarioId } from './data'; +import { DEVICE_NAME_MAX, validDeviceName } from '../../shared/format'; +import { + ENDPOINT, + deviceLimit, + isScenario, + pageState, + seedDevices, + type DemoDevice, + type DemoWay, + type ScenarioId, + handshakeOf, +} from './data'; /** What the router remembers for this visitor. */ export interface DemoDb { @@ -59,7 +70,6 @@ function valid(v: unknown): DemoDb | null { } const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other']; -const NAME_MAX = 32; export function createRouter(o: RouterOpts) { const clock = o.clock ?? (() => Math.floor(Date.now() / 1000)); @@ -74,6 +84,8 @@ export function createRouter(o: RouterOpts) { let db = kept && (!o.want || kept.scenario === o.want) ? kept : seed(isScenario(o.want) ? o.want : 'normal'); const state = () => pageState(db.scenario, db.devs, clock(), o.secureUrl()); + /** The device whose settings went out last: the one the set-up sheet is open for. */ + let issued = ''; function needOpen() { if (db.scenario === 'paused') refuse(403, 'Your access is paused.'); @@ -88,7 +100,7 @@ export function createRouter(o: RouterOpts) { function checkName(v: unknown, self?: DemoDevice): string { const name = String(v ?? '').trim(); if (!name) refuse(400, 'Give the device a name.'); - if (name.length > NAME_MAX) refuse(400, `A name is at most ${NAME_MAX} characters.`); + if (!validDeviceName(name)) refuse(400, `Enter a device name: up to ${DEVICE_NAME_MAX} letters, digits, spaces and - _ .`); if (db.devs.some((d) => d !== self && d.name.toLowerCase() === name.toLowerCase())) refuse(409, 'You already have a device with this name.'); return name; @@ -148,6 +160,7 @@ export function createRouter(o: RouterOpts) { stale: false, }; db.devs.push(d); + issued = d.id; return { id: d.id, config: config(d), state: state() }; } @@ -158,6 +171,7 @@ export function createRouter(o: RouterOpts) { needHttps(); d.stale = false; if (!d.hs && !d.connectAt) d.connectAt = soon(); + issued = d.id; return config(d); } @@ -172,6 +186,7 @@ export function createRouter(o: RouterOpts) { d.hs = 0; d.stale = false; d.connectAt = soon(); + issued = d.id; extra = { config: config(d) }; } else if (b.action === 'delete') db.devs = db.devs.filter((x) => x !== d); else refuse(400, 'Unknown action.'); @@ -200,6 +215,33 @@ export function createRouter(o: RouterOpts) { return { answer, scenario: () => db.scenario, + /** The device being set up (its settings went out last), if it is still there. */ + settingUp: () => (db.devs.some((d) => d.id === issued) ? issued : null), + /** The set-up state `id` is held in, 'auto' when none. */ + wayOf: (id: string): DemoWay | 'auto' => db.devs.find((d) => d.id === id)?.way ?? 'auto', + /** + * Hold `id` in a set-up state, or let it go: 'connected' is a handshake now with data after it, 'auto' the + * demo's own timing (it connects a few seconds on, unless it already has). + */ + holdWay(id: string, w: DemoWay | 'connected' | 'auto') { + const d = db.devs.find((x) => x.id === id); + if (!d) return; + const t = clock(); + delete d.way; + delete d.wayAt; + if (w === 'connected') { + d.hs = t; + d.connectAt = 0; + } else if (w === 'auto') { + if (!handshakeOf(d, t)) d.connectAt = soon(); + } else { + d.way = w; + d.wayAt = t; + d.hs = 0; + d.connectAt = 0; + } + o.keep.save(db); + }, /** Start a scenario over: its own devices, nothing added. */ use(s: ScenarioId) { db = seed(s); diff --git a/web/src/portal/demo/way-pick.ts b/web/src/portal/demo/way-pick.ts new file mode 100644 index 0000000..6666a51 --- /dev/null +++ b/web/src/portal/demo/way-pick.ts @@ -0,0 +1,200 @@ +// The demo's set-up state switch: a pill beside the set-up sheet's ×, so a visitor can see each state the way +// shows (waiting, knocks that never finish, no data, connected) without a device. Its popup is a row of segments +// in one pill frame, above the pill with a tail pointing at it and a dark halo behind. Only on the set-up view: +// another view in the same sheet (a question, a device's page) fades it out. Picking holds the device in that +// state on the demo's router and polls at once; Auto is the demo's own timing. + +import { h, ic } from '../dom'; +import { EASE_IN, EASE_OUT, POP, play } from '../motion'; +import { morphText, setText } from '../ui/morph'; +import { pollNow } from '../flows/wait'; +import type { DemoWay } from './data'; +import type { DemoRouter } from './router'; + +type Pick = DemoWay | 'connected' | 'auto'; +type Tone = 'neutral' | 'warn' | 'ok'; + +const PICKS: [Pick, () => string, Tone][] = [ + ['auto', () => _('Auto'), 'neutral'], + ['waiting', () => _('Waiting'), 'neutral'], + ['trying', () => _('Trying'), 'warn'], + ['nodata', () => _('No data'), 'warn'], + ['connected', () => _('Online'), 'ok'], +]; +const pick = (p: Pick) => PICKS.find((x) => x[0] === p)!; + +/** The gap between the pill and the popup above it, and how far the halo reaches out (up, sideways, down). */ +const GAP = 18; +const HALO = { x: 64, up: 48, down: 14 }; + +/** Gone from where it stands, so one leaving while it still comes in turns back from there. */ +function leave(el: Element, frames: Keyframe, ms: number) { + const s = getComputedStyle(el); + el.getAnimations().forEach((a) => a.cancel()); + const a = play( + el, + [ + { opacity: s.opacity, transform: s.transform, filter: s.filter }, + { opacity: 0, ...frames }, + ], + { + duration: ms, + easing: EASE_IN, + fill: 'forwards', + }, + ); + a.onfinish = () => el.remove(); +} + +export function mountWayPick(router: DemoRouter) { + /** What each device's pill says: what was picked here, else what the router holds it in. */ + const shown = new Map(); + let pop: HTMLElement | null = null; + let halo: HTMLElement | null = null; + let anchor: HTMLElement | null = null; + + function closePop() { + if (!pop) return; + leave(pop, { transform: 'scale(.96)', filter: 'blur(3px)' }, 120); + if (halo) leave(halo, {}, 160); + anchor?.setAttribute('aria-expanded', 'false'); + pop = halo = anchor = null; + } + + function openPop(pill: HTMLElement, id: string, paint: () => void) { + const now = shown.get(id) ?? router.wayOf(id); + const m = h( + 'div', + { class: 'dm-way-pop', role: 'menu' }, + ...PICKS.map(([p, label, tone]) => + h( + 'button', + { + type: 'button', + role: 'menuitemradio', + 'aria-checked': String(p === now), + onclick: () => { + closePop(); + shown.set(id, p); + router.holdWay(id, p); + paint(); + pollNow(); + }, + }, + h('span', { class: `dot ${tone}` }), + label(), + ), + ), + ); + document.body.append(m); + // Centred over the pill, inside the sheet where it fits (else the screen), the tail on the pill's middle. + const r = pill.getBoundingClientRect(); + const box = pill.closest('.sheet')?.getBoundingClientRect() ?? { left: 0, right: innerWidth }; + const w = m.offsetWidth; + const mid = r.left + r.width / 2; + const lo = Math.max(12, box.left + 10); + const hi = Math.min(innerWidth - 12, box.right - 10); + const left = Math.max(lo, Math.min(mid - w / 2, hi - w)); + const top = r.top - GAP - m.offsetHeight; + Object.assign(m.style, { left: `${left}px`, top: `${top}px`, transformOrigin: `${mid - left}px bottom` }); + m.style.setProperty('--tail', `${mid - left}px`); + // The halo reaches up and out but stops short of the pill, which stays sharp. + const sc = h('div', { class: 'dm-way-halo' }); + Object.assign(sc.style, { + left: `${left - HALO.x}px`, + top: `${top - HALO.up}px`, + width: `${w + HALO.x * 2}px`, + height: `${m.offsetHeight + HALO.up + HALO.down}px`, + }); + m.before(sc); + play(sc, [{ opacity: 0 }, { opacity: 1 }], { duration: 220, easing: EASE_OUT }); + play( + m, + [ + { opacity: 0, transform: 'scale(.9)', filter: 'blur(4px)' }, + { opacity: 1, transform: 'none', filter: 'none' }, + ], + { duration: POP.duration, easing: POP.easing }, + ); + pop = m; + halo = sc; + anchor = pill; + pill.setAttribute('aria-expanded', 'true'); + } + + function makePill(id: string): HTMLElement { + const dot = h('span', { class: 'dot' }); + const lbl = h('span', {}); + const pill = h( + 'button', + { type: 'button', class: 'dm-way', 'aria-haspopup': 'menu', 'aria-expanded': 'false', 'aria-label': _('Set-up state') }, + dot, + lbl, + ic('chevron', 'i'), + ); + const paint = (morph = true) => { + const [, label, tone] = pick(shown.get(id) ?? router.wayOf(id)); + dot.className = `dot ${tone}`; + if (morph) morphText(lbl, label()); + else setText(lbl, label()); + }; + paint(false); + pill.addEventListener('click', () => (anchor === pill ? closePop() : (closePop(), openPop(pill, id, () => paint())))); + return pill; + } + + function place() { + if (anchor && !anchor.isConnected) closePop(); + const sheet = document.querySelector('.sheet-root.open .sheet'); + const id = router.settingUp(); + const setup = !!sheet && !!id && !!sheet.querySelector('.way') && !sheet.classList.contains('asks'); + document.querySelectorAll('.dm-way:not(.gone)').forEach((el) => { + if (setup && el.parentElement === sheet && el.dataset.id === id) return; + el.classList.add('gone'); + el.parentElement?.querySelectorAll('.vhead').forEach((hd) => (hd.style.paddingRight = '')); + if (anchor === el) closePop(); + leave(el, { transform: 'scale(.9)', filter: 'blur(3px)' }, 160); + }); + if (!sheet || !setup || !id) return; + let pill = sheet.querySelector('.dm-way:not(.gone)'); + if (!pill) { + pill = makePill(id); + pill.dataset.id = id; + sheet.append(pill); + } + // Left of × and of the view's own buttons, whatever they are; into their place once the sheet hides them + // (the device arrived), gliding there as they fade. + const acts = sheet.querySelector('.sheet-acts'); + const arrived = sheet.classList.contains('arrived'); + const right = (arrived ? 22 : 58) + (!arrived && acts?.offsetWidth ? acts.offsetWidth + 6 : 0); + if (pill.style.right !== `${right}px`) pill.style.right = `${right}px`; + // The title keeps clear of the pill as it does of ×: a long device name ends in an ellipsis before it. Worked + // out from where the pill goes, not where it is gliding through. + const sr = sheet.getBoundingClientRect(); + const scale = sr.width / sheet.offsetWidth || 1; + for (const head of sheet.querySelectorAll('.vhead')) { + const inset = (sr.right - head.getBoundingClientRect().right) / scale; + const pad = `${Math.max(0, right + pill.offsetWidth + 8 - inset)}px`; + if (head.style.paddingRight !== pad) head.style.paddingRight = pad; + } + } + + new MutationObserver(place).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] }); + document.addEventListener('pointerdown', (e) => { + const t = e.target as Element; + if (pop && !pop.contains(t) && !anchor?.contains(t)) closePop(); + }); + // Escape takes the popup only, not the sheet under it. + document.addEventListener( + 'keydown', + (e) => { + if (!pop || e.key !== 'Escape') return; + e.stopPropagation(); + closePop(); + }, + true, + ); + // A wheel or a swipe closes it; the sheet's own scroll as it settles does not. + for (const ev of ['wheel', 'touchmove']) + addEventListener(ev, (e) => pop && !pop.contains(e.target as Node) && closePop(), { passive: true, capture: true }); +} diff --git a/web/src/portal/flows/add.ts b/web/src/portal/flows/add.ts index 310865c..4cc2aad 100644 --- a/web/src/portal/flows/add.ts +++ b/web/src/portal/flows/add.ts @@ -1,21 +1,27 @@ // Adding a device: what it is (four kinds; phones and tablets are one choice, -// the same apps and the same smaller packets) and its name, guessed from the -// browser when it is this device; then straight on to its set-up. Or the page -// opens on the device itself, from a code, ready to add it there. +// the same apps and the same smaller packets), whether the local network it is +// on stays reachable while connected (LAN Bypass, off unless they turn it on; +// it stays as chosen: the admin's drawer shows it, neither page changes it) +// and its name, guessed from the browser when it is this device; then straight +// on to its set-up. Or the page opens on the device itself, from a code, ready +// to add it there. import type { ClientConfig, Kind } from '../../shared/types'; -import { kindLabel } from '../../shared/format'; +import { defaultName, fitName, kindLabel, netsLabel } from '../../shared/format'; +import { guardDeviceName } from '../../shared/name-guard'; +import { shake } from '../../shared/shake'; import { fmt, num, plural } from '../../shared/i18n'; import { ApiError, call } from '../api'; import { h, ic } from '../dom'; -import { EASE_OUT, play } from '../motion'; +import { SMOOTH, play } from '../motion'; import { addLink } from '../setup'; import { pageUrl, repaint, setState, state, type State } from '../state'; +import { smoothCaret } from '../ui/caret'; import { linkRow, qrBox } from '../ui/codes'; import { once, toast } from '../ui/feedback'; +import { badLine } from '../ui/bad-line'; import { glass } from '../ui/glass'; -import { morphText } from '../ui/morph'; -import { go, head, hint, openSheet, sub, type View } from '../ui/sheet'; +import { go, head, openSheet, sub, type View } from '../ui/sheet'; import { secureFirst, showSecure } from './secure'; import { continueSetup } from './setup-view'; @@ -68,7 +74,7 @@ function guessName(kind: Kind): string { if (/Mac OS X/.test(UA)) return 'Mac'; if (/Windows/.test(UA)) return _('Windows PC'); if (/Linux/.test(UA)) return _('Linux PC'); - return kindLabel(kind); + return defaultName(kind); } /* @@ -81,6 +87,44 @@ const pickLabel = (p: Pick): string => (p === 'mobile' ? _('Mobile') : kindLabel const pickOf = (k: Kind): Pick => (k === 'phone' || k === 'tablet' ? 'mobile' : k); const kindOf = (p: Pick): Kind => (p !== 'mobile' ? p : guessKind() === 'tablet' ? 'tablet' : 'phone'); +/** + * What they chose so far, kept outside the view: Back from "Open on the device" + * builds the view again, and it comes back as they left it. `name`: what they + * typed (unset while the name is still the guess). + */ +interface Draft { + pick?: Pick; + bypass: boolean; + name?: string; +} + +/** + * A line in a block opens or folds away: height, opacity and blur on SMOOTH, as the set-up steps fold, from + * where it is on screen (flicking the switch never snaps). The block's 1 px gap goes with it. + */ +function foldLine(el: HTMLElement, open: boolean) { + const cs = getComputedStyle(el); + const from = el.hidden + ? { h: 0, o: 0, b: 4, m: -1 } + : { + h: el.getBoundingClientRect().height, + o: +cs.opacity, + b: +(cs.filter.match(/blur\(([\d.]+)px\)/)?.[1] ?? 0), + m: parseFloat(cs.marginTop) || 0, + }; + el.getAnimations().forEach((a) => a.cancel()); + el.hidden = false; + el.style.overflow = 'hidden'; + const to = open ? { h: el.scrollHeight, o: 1, b: 0, m: 0 } : { h: 0, o: 0, b: 4, m: -1 }; + const frame = (v: typeof from) => ({ height: `${v.h}px`, opacity: v.o, filter: v.b ? `blur(${v.b}px)` : 'none', marginTop: `${v.m}px` }); + const a = play(el, [frame(from), frame(to)], { duration: SMOOTH.duration, easing: SMOOTH.easing, fill: 'forwards' }); + a.onfinish = () => { + el.hidden = !open; + el.style.overflow = ''; + a.cancel(); + }; +} + export function startAdd() { const st = state(); if (!st || st.locked) return; @@ -90,22 +134,24 @@ export function startAdd() { true, ); if (secureFirst()) return; - openSheet(vAdd); + const draft: Draft = { bypass: false }; + openSheet(() => vAdd(draft)); } -function vAdd(): View { +function vAdd(draft: Draft): View { const st = state()!; const p = st.person; // The kinds this router takes, as the four choices. const picks = (['computer', 'mobile', 'router', 'other'] as Pick[]).filter((k) => st.kinds.some((x) => pickOf(x) === k)); - let pick: Pick = picks.includes(pickOf(guessKind())) ? pickOf(guessKind()) : picks[0]; - let edited = false; + const guess = picks.includes(pickOf(guessKind())) ? pickOf(guessKind()) : picks[0]; + let pick: Pick = draft.pick && picks.includes(draft.pick) ? draft.pick : guess; const taken = new Set(p.devices.map((d) => d.name.toLowerCase())); const suggest = (k: Pick) => { - const n = k === pickOf(guessKind()) ? guessName(kindOf(k)) : kindLabel(k === 'mobile' ? 'phone' : k); - if (!taken.has(n.toLowerCase())) return n; - for (let i = 2; i < 20; i++) if (!taken.has(`${n} ${i}`.toLowerCase())) return `${n} ${i}`; - return n; + const n = k === pickOf(guessKind()) ? guessName(kindOf(k)) : defaultName(k === 'mobile' ? 'phone' : k); + // Stripped of what the router refuses and cut to its limit, the number after it too ("Galaxy S24+ 2"). + if (!taken.has(fitName(n).toLowerCase())) return fitName(n); + for (let i = 2; i < 20; i++) if (!taken.has(fitName(n, ` ${i}`).toLowerCase())) return fitName(n, ` ${i}`); + return fitName(n); }; const kinds = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': _('What is it?') }); @@ -120,48 +166,78 @@ function vAdd(): View { kinds.appendChild(t); return t; }); + // With home access, the home networks still go into the tunnel: a local network on the same addresses is out + // of reach, and the row says so while LAN Bypass is on. + const home = st.server.home ?? []; + const except = home.length + ? h( + 'span', + { class: 'sw-sub sw-note', hidden: !draft.bypass }, + fmt(_('Except %s: those addresses lead to the home network.'), netsLabel(home)), + ) + : null; + // The whole row is the switch. Built as they left it, before it is on the page: nothing slides. + const lan = h( + 'button', + { + type: 'button', + class: draft.bypass ? 'swrow on' : 'swrow', + role: 'switch', + 'aria-checked': String(draft.bypass), + onclick: () => { + draft.bypass = !draft.bypass; + lan.classList.toggle('on', draft.bypass); + lan.setAttribute('aria-checked', String(draft.bypass)); + if (except) foldLine(except, draft.bypass); + }, + }, + glass('lan', 'blue'), + h( + 'span', + { class: 'sw-t' }, + h('b', {}, _('LAN Bypass')), + h('span', { class: 'sw-sub' }, _('Your local network stays reachable while connected.')), + except, + ), + h('span', { class: 'sw', 'aria-hidden': 'true' }), + ); const input = h('input', { type: 'text', - maxlength: 48, - required: true, + // Not `required`: the browser's own check would stop an empty submit before the field can shake. 'aria-label': _('Name'), autocomplete: 'off', + // Not a login: no password manager offering itself here. + 'data-1p-ignore': true, }) as HTMLInputElement; const goBtn = h('button', { class: 'go ready', type: 'submit', 'aria-label': _('Create connection') }, ic('arrow')) as HTMLButtonElement; - const err = h('p', { class: 'hint bad-t', hidden: true }); - const say = (msg: string) => { - // Already showing: its words change in place. - if (!err.hidden) return morphText(err, msg); - err.textContent = msg; - err.hidden = false; - play( - err, - [ - { opacity: 0, transform: 'translateY(-4px)' }, - { opacity: 1, transform: 'none' }, - ], - { duration: 220, easing: EASE_OUT }, - ); - }; - input.value = suggest(pick); + // The red line under the field: why a name is refused (the router's word, or the field's own as it is typed). + const { el: err, say, unsay } = badLine(); + // What the router won't take never gets in: the field shakes instead (shared/name-guard.ts). + guardDeviceName( + input, + () => form, + (w) => (w ? say(w) : unsay()), + ); + input.value = draft.name ?? suggest(pick); + goBtn.classList.toggle('ready', !!input.value.trim()); input.addEventListener('input', () => { - edited = true; + draft.name = input.value; goBtn.classList.toggle('ready', !!input.value.trim()); - err.hidden = true; + unsay(); }); // The Android model arrives a moment later: use it unless they started typing. void modelReady.then(() => { - if (!edited && pick === pickOf(guessKind())) input.value = suggest(pick); + if (draft.name === undefined && pick === pickOf(guessKind())) input.value = suggest(pick); }); // The picked tile rings itself where it stands (the ring does not travel between tiles). function choose(k: Pick) { - pick = k; + pick = draft.pick = k; tiles.forEach((t, i) => { const on = picks[i] === k; t.classList.toggle('on', on); t.setAttribute('aria-checked', String(on)); }); - if (!edited) { + if (draft.name === undefined) { input.value = suggest(k); goBtn.classList.add('ready'); } @@ -169,20 +245,30 @@ function vAdd(): View { choose(pick); const form = h('form', { class: 'field', autocomplete: 'off' }, input, goBtn); + smoothCaret(form); form.addEventListener('submit', (e) => { e.preventDefault(); const name = input.value.trim(); - if (!name) return; - if (taken.has(name.toLowerCase())) return say(_('You already have a device with this name.')); + // Nothing to name it: the field shakes (only now, not as it empties). + if (!name) return shake(form); + if (taken.has(name.toLowerCase())) { + shake(form); + return say(_('You already have a device with this name.')); + } void once(goBtn, async () => { try { - const r = await call<{ id: string; config: ClientConfig; state: State }>('devices', { name, kind: kindOf(pick) }); + const r = await call<{ id: string; config: ClientConfig; state: State }>('devices', { + name, + kind: kindOf(pick), + lan_bypass: draft.bypass, + }); setState(r.state); repaint({ pop: r.id }); const dev = r.state.person.devices.find((d) => d.id === r.id)!; await continueSetup(dev, r.config); } catch (er) { if (er instanceof ApiError && er.httpsUrl) return showSecure(er.httpsUrl); + shake(form); say((er as Error).message); } }); @@ -200,13 +286,12 @@ function vAdd(): View { head(_('Add a device')), sub(fmt(N_(p.device_limit, '%s of %s slot free', '%s of %s slots free'), num(free), num(p.device_limit))), kinds, - hint(_('Phones and tablets get a smaller packet size that suits mobile networks.')), + lan, form, err, h('div', { class: 'or' }, _('OR')), viaLink, ); - el.querySelector('.hint')!.classList.add('kinds-note'); return { el, label: _('Add a device') }; } diff --git a/web/src/portal/flows/device-actions.ts b/web/src/portal/flows/device-actions.ts index 9c343ef..7354cb9 100644 --- a/web/src/portal/flows/device-actions.ts +++ b/web/src/portal/flows/device-actions.ts @@ -1,16 +1,17 @@ -// A device's own actions from its ⋯ menu: Rename, Reconnect (new keys, then -// the set-up of the new ones) and Remove. A question comes before what cannot -// be undone; the action's button stays busy until the router answers. +// A device's own actions from its ⋯ menu: Reconnect (new keys, then the set-up +// of the new ones) and Remove (Rename edits the name on the card: rename.ts). A +// question comes before what cannot be undone; the action's button stays busy +// until the router answers. import type { ClientConfig, Device } from '../../shared/types'; import { fmt } from '../../shared/i18n'; import { call } from '../api'; -import { h, ic } from '../dom'; +import { h } from '../dom'; import { EASE_IN, play } from '../motion'; import { repaint, setState, state, type State } from '../state'; import { once, toast } from '../ui/feedback'; import { glass, type Tone } from '../ui/glass'; -import { closeSheet, head, onClosed, openSheet, type View } from '../ui/sheet'; +import { closeSheet, onClosed, openSheet, type View } from '../ui/sheet'; import { secureFirst } from './secure'; import { continueSetup } from './setup-view'; @@ -37,37 +38,6 @@ function ask(o: { icon: string; tone: Tone; title: string; text: string; action: return { el, label: o.title, asks: true }; } -export function rename(d: Device) { - openSheet(() => { - const input = h('input', { type: 'text', maxlength: 48, 'aria-label': _('Device name'), autocomplete: 'off' }) as HTMLInputElement; - input.value = d.name; - const save = h('button', { class: 'go', type: 'submit', 'aria-label': _('Save') }, ic('check')) as HTMLButtonElement; - input.addEventListener('input', () => save.classList.toggle('ready', !!input.value.trim() && input.value.trim() !== d.name)); - const form = h('form', { class: 'field', autocomplete: 'off' }, input, save); - form.addEventListener('submit', (e) => { - e.preventDefault(); - const name = input.value.trim(); - if (!name || name === d.name) return; - void once(save, async () => { - try { - const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'rename', name }); - setState(r.state); - onClosed(() => { - repaint(); - toast(_('Renamed')); - }); - closeSheet(); - } catch (er) { - toast((er as Error).message, true); - } - }); - }); - setTimeout(() => input.select(), 60); - const title = fmt(_('Rename %s'), d.name); - return { el: h('div', { class: 'view' }, head(title), form), label: title }; - }); -} - /** * Set a device up from scratch (a new phone, the app reinstalled, settings the * admin changed): new keys, so what it holds stops working; it shows "Not set diff --git a/web/src/portal/flows/rename.ts b/web/src/portal/flows/rename.ts new file mode 100644 index 0000000..43450d5 --- /dev/null +++ b/web/src/portal/flows/rename.ts @@ -0,0 +1,172 @@ +// Renaming a device where its name stands on the card: a click on the name (or Rename in its ⋯ menu) turns it +// into its own input, in the name's font and place, with nothing around it but the field's caret and selection +// (ui/caret.ts), the name selected. The status line under it says how to finish. Return saves: the words shimmer +// while the router answers (ui/shimmer.ts), settle, and the card is drawn again with the new name, its status +// morphing back from the hint. Esc or a click away puts the name it had back, whatever was typed. What the router +// won't take never gets in (shared/name-guard.ts): the words shake and the status line says why in red; the +// router's own refusals (a name taken) say so the same way. + +import type { Device } from '../../shared/types'; +import { guardDeviceName } from '../../shared/name-guard'; +import { shake } from '../../shared/shake'; +import { call } from '../api'; +import { h } from '../dom'; +import { repaint, setState, state, type State } from '../state'; +import { smoothCaret } from '../ui/caret'; +import { morphText } from '../ui/morph'; +import { shimmer } from '../ui/shimmer'; + +/** The status line's colours (page/devices.ts), and the red of a refusal. */ +const TONES = ['ok-t', 'warn-t', 'here-t', 'bad-t']; + +/** + * The status line says something else in another tone: its words morph and the colour turns from the one it + * had, as a repaint's status does. Only the tone classes change hands: a morph under way keeps its own. + */ +function say(stat: HTMLElement, text: string, tone: string, title = text) { + const color = getComputedStyle(stat).color; + for (const t of TONES) stat.classList.toggle(t, t === tone); + // The line is one line: a long reason (the router's own) reads in full on hover. + stat.title = title; + morphText(stat, text, undefined, { color }); +} + +/** + * Focus given back to the name without its ring: the browser would draw it (the last thing done was typing), but + * nobody moved there. The ring is the name's again once focus leaves it, for a Tab that does. + */ +function quietFocus(el: HTMLElement | null) { + if (!el) return; + el.classList.add('quiet'); + el.addEventListener('blur', () => el.classList.remove('quiet'), { once: true }); + el.focus({ preventScroll: true }); +} + +let editing: { id: string; cancel: () => void } | null = null; + +/** A name is being edited on its card: the page is not drawn again under it. */ +export const renaming = (): boolean => !!editing; + +/** Edit `d`'s name on its card (`card`: its `.dev`). Another one being edited lets go first. */ +export function renameOnCard(d: Device, card: HTMLElement) { + if (editing?.id === d.id) return; + editing?.cancel(); + const name = card.querySelector('.dev-name'); + const stat = card.querySelector('.dev-stat'); + if (!name || !stat) return; + const was = { text: stat.textContent ?? '', tone: TONES.find((t) => stat.classList.contains(t)) ?? '', title: stat.title }; + // How to finish, where a keyboard says it; on a touch screen its Done key saves. + const hint = matchMedia('(pointer: fine)').matches ? _('Return to save, Esc to cancel') : ''; + + const input = h('input', { + type: 'text', + 'aria-label': _('Device name'), + autocomplete: 'off', + spellcheck: 'false', + enterkeyhint: 'done', + 'data-1p-ignore': true, + }) as HTMLInputElement; + input.value = d.name; + const form = h('form', { class: 'field inline', autocomplete: 'off' }, input); + guardDeviceName(input, form, (why) => why && say(stat, why, 'bad-t'), { ring: false }); + // Typing again after a refusal: the hint is back. + input.addEventListener('input', () => { + if (stat.classList.contains('bad-t')) say(stat, hint || was.text, hint ? '' : was.tone, hint ? hint : was.title); + }); + + // Where the name stands, in its font, with nothing around it: swapping them shows nothing but the caret. + name.after(form); + name.hidden = true; + if (hint) say(stat, hint, ''); + smoothCaret(form); + // Focused in the same turn as the click or the menu's item: iOS only raises its keyboard for a focus made + // inside the tap. The whole name selected at once, and again a frame on: iOS may drop a selection made as the + // input takes focus (select() it ignores there). + input.focus(); + const all = () => input.setSelectionRange(0, input.value.length); + all(); + requestAnimationFrame(() => document.activeElement === input && input.selectionStart === input.selectionEnd && all()); + + let saving = false; + /** + * `saved`: the new name, null to let go. `back`: focus goes back to the name (Return and Esc, from a keyboard + * or the screen's Done key: a screen reader, the next Tab, carry on from it); a click or tap away leaves it + * where it went. + */ + const finish = (saved: string | null, back: boolean) => { + if (editing?.id === d.id) editing = null; + document.removeEventListener('pointerdown', away, true); + input.removeEventListener('blur', left); + if (saved) name.textContent = saved; + name.hidden = false; + form.remove(); + // Saved: the hint stays for the repaint, which morphs it into the status (words and colour) as it does any + // status that changed. Let go: it turns back here. + if (!saved) say(stat, was.text, was.tone, was.title); + if (!back) return; + // After a save the card is drawn again: the name is found anew then. + if (saved) + requestAnimationFrame(() => quietFocus(document.querySelector(`.dev-name[data-t="${CSS.escape(`${d.id}:name`)}"]`))); + else quietFocus(name); + }; + + const refuse = (msg: string) => { + say(stat, msg, 'bad-t'); + shake(form, { ring: false }); + input.focus(); + }; + + const save = async () => { + const next = input.value.trim(); + if (saving) return; + // Empty: said before asking the router. The same name: nothing to save. + if (!next) return refuse(_('Give the device a name.')); + if (next === d.name) return finish(null, true); + // Another of theirs has it: said here, shorter than the router would. + const mine = state()?.person.devices ?? []; + if (mine.some((x) => x.id !== d.id && x.name.toLowerCase() === next.toLowerCase())) return refuse(_('That name is taken.')); + saving = true; + input.readOnly = true; + const stop = shimmer(form, input); + try { + const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'rename', name: next }); + setState(r.state); + // The words settle to solid before the field gives way to the name: nothing changes as it does. + await stop(); + finish(next, true); + repaint(); + } catch (e) { + await stop(); + input.readOnly = false; + refuse((e as Error).message); + } finally { + saving = false; + } + }; + + form.addEventListener('submit', (e) => { + e.preventDefault(); + void save(); + }); + input.addEventListener('keydown', (e) => { + if (e.key !== 'Escape' || saving) return; + e.preventDefault(); + e.stopPropagation(); + finish(null, true); + }); + // A click away lets it go; while saving, the router's answer settles it. + const away = (e: Event) => { + if (saving || form.contains(e.target as Node)) return; + finish(null, false); + }; + // Focus gone elsewhere in the page (Tab, iPad's hide-keyboard key) lets it go too. Gone from the window (another + // app, another tab) it stays: coming back, they carry on. + const left = () => + setTimeout(() => { + if (editing?.id !== d.id || saving || !document.hasFocus() || form.contains(document.activeElement)) return; + finish(null, false); + }); + input.addEventListener('blur', left); + document.addEventListener('pointerdown', away, true); + editing = { id: d.id, cancel: () => finish(null, false) }; +} diff --git a/web/src/portal/flows/setup-parts.ts b/web/src/portal/flows/setup-parts.ts index e80c8b3..6bf0af0 100644 --- a/web/src/portal/flows/setup-parts.ts +++ b/web/src/portal/flows/setup-parts.ts @@ -7,7 +7,7 @@ import type { ClientConfig, Device } from '../../shared/types'; import { fill, fmt } from '../../shared/i18n'; import { h, ic, type Kid } from '../dom'; -import { EASE_OUT, POP, SMOOTH, play } from '../motion'; +import { EASE_IN, EASE_OUT, POP, SMOOTH, play } from '../motion'; import { APP_NAME, importPath, @@ -24,7 +24,7 @@ import { type Store, } from '../setup'; import { accordion } from '../ui/accordion'; -import { copy, download, sendFile, shareFile, swapIcon } from '../ui/feedback'; +import { copy, download, sendFile, shareFile } from '../ui/feedback'; import { glass } from '../ui/glass'; import { menuLine, morphText, setText } from '../ui/morph'; import { hint } from '../ui/sheet'; @@ -200,25 +200,68 @@ export function sendKids(c: SetupCtx): Kid[] { ]; } -/** One configuration line, highlighted; private and preshared keys masked unless shown. */ -function confLine(line: string, reveal: boolean): Node { +/** At rest out of sight: it keeps its place, with nothing to see, select or read out. */ +function rest(el: HTMLElement | SVGElement) { + el.style.opacity = '0'; + el.style.visibility = 'hidden'; +} + +/** + * Both looks in one place (a key and its mask, two icons): the one showing and + * the other at rest under it, so a press cross-fades them and nothing is + * rebuilt. The cell is as wide as the wider of the two. + */ +function stack(shown: HTMLElement | SVGElement, other: HTMLElement | SVGElement): HTMLElement { + const cell = h('span', {}, shown, other); + cell.style.display = 'inline-grid'; + for (const x of [shown, other]) x.style.gridArea = '1 / 1'; + rest(other); + return cell; +} + +/** + * Shown or not: it comes into focus out of a blur, or blurs away and rests out + * of sight, from where it stands now (pressed again half-way, it turns back). + */ +function turn(el: HTMLElement | SVGElement, on: boolean, off: Keyframe) { + const s = getComputedStyle(el); + const from = { opacity: s.opacity, filter: s.filter === 'none' ? 'blur(0px)' : s.filter, transform: s.transform }; + const old = el.getAnimations(); + el.style.opacity = on ? '' : '0'; + el.style.visibility = ''; + const a = on + ? play(el, [from, { opacity: 1, filter: 'blur(0px)', transform: 'none' }], { duration: 320, easing: EASE_OUT }) + : play(el, [from, off], { duration: 200, easing: EASE_IN }); + if (!on) a.onfinish = () => (el.style.visibility = 'hidden'); + old.forEach((x) => x.cancel()); +} + +/** A key masked, or a mask lifted: they blur through each other. */ +const SECRET_OFF: Keyframe = { opacity: 0, filter: 'blur(4px)', transform: 'none' }; +/** The button's icon (a key, or × to hide it again) turns the way a copy's check comes in (ui/feedback.ts). */ +const ICON_OFF: Keyframe = { opacity: 0, filter: 'blur(3px)', transform: 'scale(.6)' }; + +/** One configuration line, highlighted; private and preshared keys masked until shown. */ +function confLine(line: string): Node { if (/^\s*\[.+\]\s*$/.test(line)) return h('span', { class: 'sec' }, line); const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line); if (!m) return document.createTextNode(line); const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line); - const value = !secret ? m[2] : reveal ? h('span', { class: 'secret' }, m[2]) : h('span', { class: 'mask' }, '••••••••••••••••'); + const value = secret ? stack(h('span', { class: 'mask' }, '••••••••••••••••'), h('span', { class: 'secret' }, m[2])) : m[2]; return h('span', {}, h('span', { class: 'k' }, m[1]), ' ', value); } /** The .conf for a router: a file card to download (or share), and the configuration folded, its keys hidden. */ export function filePane(cfg: ClientConfig): HTMLElement { let reveal = false; - const pre = h('pre', { class: 'conf' }); - const paint = () => - pre.replaceChildren(...cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)]))); - paint(); + const pre = h( + 'pre', + { class: 'conf' }, + cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l)] : [confLine(l)])), + ); const share = !!shareFile(cfg.filename, cfg.conf); - let icon = ic('key'); + const key = ic('key') as SVGElement; + const hide = ic('x') as SVGElement; const label = h('span', {}, _('Show key')); const eye = h( 'button', @@ -227,23 +270,15 @@ export function filePane(cfg: ClientConfig): HTMLElement { class: 'btn soft sm', onclick: () => { reveal = !reveal; - icon = swapIcon(icon, reveal ? 'x' : 'key'); morphText(label, reveal ? _('Hide key') : _('Show key')); - paint(); - // A key shown comes into focus out of a blur; hidden again, the mask fades back. - pre.querySelectorAll('.mask, .secret').forEach((x) => - play( - x, - [ - { filter: 'blur(4px)', opacity: 0.4 }, - { filter: 'none', opacity: 1 }, - ], - { duration: 320, easing: EASE_OUT }, - ), - ); + // A key shown comes into focus out of a blur as its mask blurs away; hidden again, the other way round. + pre.querySelectorAll('.secret').forEach((x) => turn(x, reveal, SECRET_OFF)); + pre.querySelectorAll('.mask').forEach((x) => turn(x, !reveal, SECRET_OFF)); + turn(key, !reveal, ICON_OFF); + turn(hide, reveal, ICON_OFF); }, }, - icon, + stack(key, hide), label, ); const cp = h( @@ -303,7 +338,9 @@ export interface ConnPill { * Beside ×: the connection itself, to download or copy, where the sheet offers * neither (a phone or a tablet set up from elsewhere). One tooltip for both * keys, under them: the first waits a beat; once one is up the next comes at - * once and the tooltip glides across. Copied: a check, and the tooltip says so. + * once and the tooltip glides across (by Tab too, and back to a key while it + * still fades out), each move from where it stands. Copied: a check, and the + * tooltip says so. */ export function connPill(get: () => { text: string; msg: string; file: string; app: string }): ConnPill { const tt = h('span', { class: 'tt' }); @@ -324,11 +361,22 @@ export function connPill(get: () => { text: string; msg: string; file: string; a return Math.min(b.offsetLeft + b.offsetWidth / 2, el.offsetWidth + 46 - w / 2); }; const at = (x: number) => `translateX(${x}px) translateX(-50%)`; + /** Where the tooltip stands now: mid-fade and mid-glide included. */ + const now = (): Keyframe => { + const s = getComputedStyle(tip); + return { opacity: s.opacity, filter: s.filter === 'none' ? 'blur(0px)' : s.filter, transform: s.transform }; + }; + /** Its next motion takes over from where the last one stands; the last one stops once it is in place. */ + const move = (frames: Keyframe[], o: KeyframeAnimationOptions) => { + const old = tip.getAnimations(); + play(tip, frames, o); + old.forEach((a) => a.cancel()); + }; + // To another key, or back while it fades out: it glides there and comes up whole on the way. const glideTo = (x: number) => { - const from = getComputedStyle(tip).transform; - tip.getAnimations().forEach((a) => a.cancel()); + const from = now(); tip.style.transform = at(x); - play(tip, [{ transform: from }, { transform: at(x) }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); + move([from, { opacity: 1, filter: 'blur(0px)', transform: at(x) }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); }; // Another key's words, or "Copied": what the two share slides, the rest morphs; the pill glides with it. const reword = (t: string) => morphText(tt, t); @@ -336,20 +384,20 @@ export function connPill(get: () => { text: string; msg: string; file: string; a clearTimeout(tipT); if (tipFor === b && tip.classList.contains('on')) return; tipFor = b; - if (tip.classList.contains('on')) { + if (tip.classList.contains('on') || +getComputedStyle(tip).opacity > 0) { const t = words(b); + tip.classList.add('on'); glideTo(centre(b, t)); return reword(t); } + // Out of sight: it comes up under the key out of a blur. const up = () => { const t = words(b); setText(tt, t); const x = centre(b, t); - tip.getAnimations().forEach((a) => a.cancel()); tip.style.transform = at(x); tip.classList.add('on'); - play( - tip, + move( [ { opacity: 0, transform: `${at(x)} translateY(-3px) scale(.96)`, filter: 'blur(3px)' }, { opacity: 1, transform: at(x), filter: 'blur(0px)' }, @@ -368,8 +416,10 @@ export function connPill(get: () => { text: string; msg: string; file: string; a tipFor = null; if (!tip.classList.contains('on')) return; warmUntil = performance.now() + 500; + // It fades where it stands, mid-glide or still coming up. + const from = now(); tip.classList.remove('on'); - play(tip, [{ opacity: 1 }, { opacity: 0 }], { duration: 120, easing: 'ease-out' }); + move([from, { ...from, opacity: 0 }], { duration: 120, easing: 'ease-out' }); }; for (const b of [dl, cp]) { b.addEventListener('pointerenter', (e) => { @@ -378,7 +428,10 @@ export function connPill(get: () => { text: string; msg: string; file: string; a b.addEventListener('focus', () => { if (b.matches(':focus-visible')) show(b); }); - b.addEventListener('blur', hide); + // Tab from one key to the other: the focus that follows glides the tooltip across instead. + b.addEventListener('blur', (e) => { + if (!el.contains(e.relatedTarget as Node | null)) hide(); + }); } el.addEventListener('pointerleave', hide); diff --git a/web/src/portal/flows/setup-view.ts b/web/src/portal/flows/setup-view.ts index 7c1f687..95c5276 100644 --- a/web/src/portal/flows/setup-view.ts +++ b/web/src/portal/flows/setup-view.ts @@ -2,10 +2,12 @@ // on the device itself, two steps (get the app, add the connection) with a way // round folded under the wait; a router, its packages and the file; a phone or // a tablet set up from elsewhere, its link as a code or the connection as a -// code for an app it has; a computer set up from elsewhere, its link or the -// connection to send there. Which app and where it comes from follow the +// code for an app it has (the link again where the key is too long for one); a +// computer, or another device added from a phone, its link or the connection +// to send there. Which app and where it comes from follow the // server's disguise and the platform (setup.ts). The wait for the first -// connection sits on top the whole time (wait.ts). +// connection sits on top the whole time (wait.ts); on the device itself and for +// a router the steps regroup under it as it goes (can't finish, no data). import type { ClientConfig, Device } from '../../shared/types'; import { fmt } from '../../shared/i18n'; @@ -15,7 +17,7 @@ import { h, put } from '../dom'; import { SMOOTH, play } from '../motion'; import { APP_NAME, appsFor, deviceNoun, inWebview, keyFileName, sameDevice, setupLink, type AppId } from '../setup'; import { pageUrl, platform, preset, repaint } from '../state'; -import { accordion } from '../ui/accordion'; +import { accordion, regrow, type Accordion } from '../ui/accordion'; import { codeRow, linkRow, type CodeRow } from '../ui/codes'; import { once, toast } from '../ui/feedback'; import { glass } from '../ui/glass'; @@ -37,7 +39,8 @@ import { storeBlock, type SetupCtx, } from './setup-parts'; -import { arrive, waitWay, watchFirstConnection } from './wait'; +import type { WayState } from '../way'; +import { follow, waitWay, watchFirstConnection } from './wait'; async function getConfig(d: Device): Promise { try { @@ -49,14 +52,17 @@ async function getConfig(d: Device): Promise { } } -/** Set up a device from its card: the configuration first (the button waits for it), then the sheet. */ -export async function openSetup(d: Device, from?: EventTarget | null) { +/** + * Set up a device from its card: the configuration first (the button waits for it), then the sheet. `here`: the + * page came from the device's own set-up link, so it is open on that device (setup.ts sameDevice). + */ +export async function openSetup(d: Device, from?: EventTarget | null, here = false) { if (secureFirst()) return; const run = async () => { const cfg = await getConfig(d); if (!cfg) return; const key = await vpnKey(cfg, cfg.server); - openSheet(() => setupView(d, cfg, key)); + openSheet(() => setupView(d, cfg, key, here)); }; if (from instanceof HTMLButtonElement) await once(from, run); else await run(); @@ -78,42 +84,104 @@ function step(n: string, title: Node | string, kids: (Node | null)[]): HTMLEleme ); } -/** Fold a block away (height, then gone) or bring it back; `instant` without motion. */ +/** A block folded away: no height, blurred out. */ +const FOLDED: Keyframe = { height: '0px', opacity: 0, filter: 'blur(4px)' }; + +/** + * Fold a block away (height, then gone) or bring it back, from where it stands + * now: a fold turned round half-way (a double click) never jumps. What holds it + * (a row still opening) glides on to its new height with it. + * `instant` without motion. + */ function foldBlock(el: HTMLElement, fold: boolean, instant: boolean) { - const cur = el.hidden ? 0 : el.getBoundingClientRect().height; + const cs = getComputedStyle(el); + const cur: Keyframe = el.hidden + ? FOLDED + : { height: `${el.getBoundingClientRect().height}px`, opacity: cs.opacity, filter: cs.filter === 'none' ? 'blur(0px)' : cs.filter }; el.getAnimations().forEach((a) => a.cancel()); + el.hidden = fold; + regrow(el.parentElement); if (instant) { - el.hidden = fold; + el.style.overflow = ''; return; } el.style.overflow = 'hidden'; el.hidden = false; - const to = fold ? 0 : el.getBoundingClientRect().height; - const [a, b] = fold ? [1, 0] : [0, 1]; - play( - el, - [ - { height: `${cur}px`, opacity: a, filter: `blur(${4 - a * 4}px)` }, - { height: `${to}px`, opacity: b, filter: `blur(${4 - b * 4}px)` }, - ], - { - duration: SMOOTH.duration, - easing: SMOOTH.easing, - }, - ).onfinish = () => { + const to = fold ? FOLDED : { height: `${el.getBoundingClientRect().height}px`, opacity: 1, filter: 'blur(0px)' }; + play(el, [cur, to], { duration: SMOOTH.duration, easing: SMOOTH.easing }).onfinish = () => { el.style.overflow = ''; el.hidden = fold; }; } +/** The first control in `el` that can take focus now (shown, not disabled). */ +const firstControl = (el: Element | null | undefined) => + [...(el?.querySelectorAll('button:not([disabled]), a[href], input:not([disabled])') ?? [])].find( + (x) => x.getClientRects().length > 0, + ); + +/** + * The steps on the device itself or for a router, as the way goes (way.ts); the + * layouts set up from elsewhere have rows, no steps. Waiting: the steps as + * built (connected is never asked: what shows folds shut as it is, wait.ts + * follow). Can't finish: the network is the likely cause, so they fold + * into one closed row, "Set it up again". No data: only what fixes it, open in + * one row, "Add the connection again" ("Import the configuration again" for a + * router): the connection step without its number and title. A router that + * knocks has AmneziaWG on it already, so its row holds that step alone in both. + * What sits on field inside the row steps up one (accordion.css). "Not on the X + * right now?" (`round`, on the device itself) goes in both: the device is in + * hand. Focus inside what moves (a badge just used) stays in the sheet: on that + * control where it still shows, else on the first one of what holds the steps + * now. Returns whether anything changed. + */ +function regroup(body: HTMLElement, steps: HTMLElement, round: Accordion | null, router: boolean): (st: WayState) => boolean { + const [s1, s2] = [...steps.children].slice(-2) as HTMLElement[]; + const gap = steps.querySelector(':scope > .steps-gap'); + const head2 = [...s2.querySelectorAll(':scope > .step-n, :scope > .step-b > .step-t')]; + let look: 'steps' | 'again' | 'conn' = 'steps'; + let row: HTMLElement | null = null; + return (st) => { + const next = st === 'trying' ? 'again' : st === 'nodata' ? 'conn' : 'steps'; + if (next === look) return false; + look = next; + // Moving a focused control out of the page and back drops its focus (to the page under the sheet). + const had = document.activeElement; + const inside = had instanceof HTMLElement && (steps.contains(had) || !!round?.el.contains(had) || !!row?.contains(had)); + row?.remove(); + row = null; + // The steps show whole wherever they go: opened, the way round folds them away. + round?.setOpen(-1); + if (round) round.el.hidden = next !== 'steps'; + const alone = next === 'conn' || (next === 'again' && router); + for (const e of [gap, s1, ...head2]) if (e) e.hidden = alone; + if (next === 'steps') body.append(steps); + else { + const title = next === 'again' ? _('Set it up again') : router ? _('Import the configuration again') : _('Add the connection again'); + row = accordion([{ icon: glass('refresh', 'blue'), title, body: [steps] }], { inset: true, open: next === 'conn' ? 0 : -1 }).el; + body.append(row); + } + if (inside) { + const to = + had.isConnected && had.getClientRects().length + ? had + : next === 'again' + ? row?.querySelector('.acc-head') + : firstControl(alone ? s2 : steps); + to?.focus({ preventScroll: true }); + } + return true; + }; +} + type Layout = 'same' | 'router' | 'away' | 'pc-away'; -export function setupView(d: Device, cfg: ClientConfig, key: string): View { +export function setupView(d: Device, cfg: ClientConfig, key: string, here = false): View { const pf = platform(); const apps = appsFor(preset()); const handheld = d.kind === 'phone' || d.kind === 'tablet'; const router = d.kind === 'router'; - const same = sameDevice(d.kind, pf); + const same = sameDevice(d.kind, pf, here); const layout: Layout = same ? 'same' : router ? 'router' : handheld ? 'away' : 'pc-away'; const there = deviceNoun(d.kind); const thereOn = deviceNoun(d.kind, true); @@ -135,8 +203,10 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View { app = v; rememberApp(d, v); segs.forEach((x) => x.sync(v)); - // The sheet glides to its new height; inside, what changed morphs (morphInto). + // The sheet glides to its new height; inside, what changed morphs (morphInto). A row still opening + // around what changed glides on to its new height, and the sheet with it. glide(fill); + regrow(title1, getBox, addBox, codeBox, sendBox); }, ); segs.push(s); @@ -147,6 +217,22 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View { const addBox = h('div', { class: 'step-box' }); const codeBox = h('div', { class: 'step-box' }); const sendBox = h('div', { class: 'step-box' }); + // Not on the device: the link goes there (as a code for a phone's camera); the page there does the rest. + const linkThere = setupLink(pageUrl(), d.id); + // A connection too long for a camera (a key this browser cannot compress, a configuration with a long list of + // networks): the code is the link instead; the page there hands it over. The words follow the app picked. + const tooLong = { + text: linkThere, + words: () => [ + h( + 'span', + {}, + app === 'vpn' + ? fmt(_('The key is too long for a code. Scan this one to open your link on the %s instead.'), thereOn) + : fmt(_('The configuration is too long for a code. Scan this one to open your link on the %s instead.'), thereOn), + ), + ], + }; let code: CodeRow | null = null; let scan: ScanLine | null = null; let codeApp: AppId | null = null; @@ -167,26 +253,27 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View { // The router's file is the same for either app: it stays as it is (a folded configuration stays folded). if (!router) morphInto(addBox, connectKids(c)); else if (!addBox.firstChild) put(addBox, filePane(cfg)); - const text = app === 'vpn' ? vpnQrText(key) : cfg.conf; - // Another app: its words morph in place, the code changes only when it holds something else (codes.ts). - if (code && scan && code.el.isConnected) { - if (codeApp !== app) { - code.swap(text); - scan.set(app); + // The connection as a code: only a phone or a tablet set up from here shows one. + if (layout === 'away') { + const text = app === 'vpn' ? vpnQrText(key) : cfg.conf; + // Another app: its words morph in place, the code changes only when it holds something else (codes.ts). + if (code && scan && code.el.isConnected) { + if (codeApp !== app) { + code.swap(text); + scan.set(app); + } + } else { + scan = scanLine(app); + code = codeRow(text, [scan.el], tooLong); + codeBox.replaceChildren(code.el); } - } else { - scan = scanLine(app); - code = codeRow(text, [scan.el]); - codeBox.replaceChildren(code.el); + codeApp = app; } - codeApp = app; morphInto(sendBox, sendKids(c)); pill?.sync(); } fill(); - // Not on the device: the link goes there (as a code for a phone's camera); the page there does the rest. - const linkThere = setupLink(pageUrl(), d.id); const linkBody = () => [ handheld ? codeRow(linkThere, [h('span', {}, _('Point its camera at the code: the link opens there.'))]).el @@ -201,6 +288,7 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View { body.appendChild( notice('warn', 'shield', null, _('Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.')), ); + let shape: (st: WayState) => boolean = () => false; if (layout === 'same') { // Opened, the way round folds the steps away: the device is not in hand. const steps = h('div', { class: 'steps-wrap' }, h('div', { class: 'steps-gap' }), step1(), step2()); @@ -209,7 +297,12 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View { onToggle: (_i, open, instant) => foldBlock(steps, open, instant), }); body.append(round.el, steps); - } else if (layout === 'router') body.append(step1(), step2()); + shape = regroup(body, steps, round, false); + } else if (layout === 'router') { + const steps = h('div', { class: 'steps-wrap' }, step1(), step2()); + body.append(steps); + shape = regroup(body, steps, null, true); + } // A phone or a tablet set up from here: its link as a code, or the connection as a code for an app it has. else if (layout === 'away') body.appendChild( @@ -221,7 +314,8 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View { { inset: true, open: 1 }, ).el, ); - // A computer set up from somewhere else: its system is not known here, so the link goes there and the page there does both steps. + // A computer set up from somewhere else, or something else (a TV, a box, a NAS) set up from a phone: its system is + // not known here, so the link goes there and the page there does both steps. else body.appendChild( accordion( @@ -233,29 +327,20 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View { ).el, ); - const way = waitWay(d); - let finished = false; - onLeave( - watchFirstConnection( - d, - () => { - if (finished) return; - finished = true; - void arrive(way, body, d); - }, - way.gaveUp, - ), - ); - // Closed before the device connected: the page shows what the polls brought. - onClosed(() => repaint()); - - const subline = + const subline = sub( layout === 'same' ? _('Two steps, about a minute') : router ? _('The packages and the file for OpenWrt') - : fmt(_('The app goes on the %s.'), there); + : fmt(_('The app goes on the %s.'), there), + ); + const way = waitWay(d); + const wait = follow(d, way, { sub: subline, rest: body, shape }); + onLeave(watchFirstConnection(d, wait.seen, wait.gaveUp)); + // Closed before the device connected: the page shows what the polls brought. + onClosed(() => repaint()); + const title = fmt(_('Set up %s'), d.name); - const el = h('div', { class: 'view' }, head(title, { acts: !!pill }), sub(subline), way.el, body); + const el = h('div', { class: 'view' }, head(title, { acts: !!pill }), subline, way.el, body); return { el, label: title, acts: pill?.el ?? null }; } diff --git a/web/src/portal/flows/wait.ts b/web/src/portal/flows/wait.ts index 35a6aa3..22d4a71 100644 --- a/web/src/portal/flows/wait.ts +++ b/web/src/portal/flows/wait.ts @@ -1,68 +1,184 @@ // Waiting for a new device's first connection: the way from the device to the -// server (a light runs along it while the page waits), the polling behind it, -// and what happens when it comes: the way fills green and its line morphs into -// " connected", the sheet's buttons step away, the steps fold shut, -// and the sheet closes by itself onto the page. +// server and what it says in each state (waiting, can't finish, connected, no +// data: way.ts reads them off the router's answer), the polling behind it, and +// the sheet around it keeping pace. Connected, the way fills green and its line +// morphs into " connected", × and the sheet's buttons step away, +// everything under the way folds shut and the sheet closes by itself onto the +// page; any other state undoes that. What sits under the way in each state is +// the view's (setup-view.ts hands it over as `Around`). import type { Device } from '../../shared/types'; import { fmt } from '../../shared/i18n'; import { gone, call } from '../api'; import { h, ic } from '../dom'; -import { EASE_OUT, play } from '../motion'; +import { EASE_IN, EASE_OUT, calm, play } from '../motion'; import { now, repaint, setState, type State } from '../state'; import { menuOpen } from '../ui/menu'; -import { morphText } from '../ui/morph'; +import { morphText, setText, textOf } from '../ui/morph'; import { closeSheet, onClosed, scrollTop, settle, showing } from '../ui/sheet'; +import { wayState, type WayState } from '../way'; export interface Way { el: HTMLElement; - connected(): void; + /** Show this state: its look, its line morphing, the line under it gliding in or out or changing in place. */ + set(st: WayState): void; + /** Ten minutes and nothing: the light goes out, and the way says so. */ gaveUp(): void; } +/** The way's line and the one under it (empty: none) in a state. */ +function lines(st: WayState, d: Device): [string, string] { + switch (st) { + case 'trying': + return [_('Unable to complete the handshake'), _('Your network may be blocking the connection.')]; + case 'connected': + return [fmt(_('%s connected'), d.name), '']; + case 'nodata': + return [_('Handshake complete, but no data'), _('This device is using an outdated configuration.')]; + case 'waiting': + return [_('Waiting for the connection'), '']; + } +} + +/** The way's class in a state (setup.css). */ +const LOOK: Record = { waiting: '', trying: 'trying', connected: 'done', nodata: 'nodata' }; + export function waitWay(d: Device): Way { const line = h('b', {}, _('Waiting for the connection')); const more = h('span', { class: 'ws', hidden: true }); + const t = h('span', { class: 't' }, line, more); + const text = h('div', { class: 'way-text' }, t); + // The light's two loops (running, knocking) and the break at the router run all along, each showing in its own + // state (setup.css): a change of state cross-fades them where they stand instead of starting one over. + const track = h( + 'span', + { class: 'way-track' }, + h('span', { class: 'way-glow' }, h('span', { class: 'run' }, h('i')), h('span', { class: 'knock' }, h('i'))), + h('span', { class: 'way-fill' }), + h('span', { class: 'way-break' }, h('i')), + ); const el = h( 'div', { class: 'way', role: 'status', 'aria-live': 'polite' }, - h( - 'div', - { class: 'way-row' }, - h('span', { class: 'way-end' }, ic(d.kind)), - h('span', { class: 'way-track' }, h('span', { class: 'way-glow' }, h('i')), h('span', { class: 'way-fill' })), - h('span', { class: 'way-end home' }, ic('server')), - ), - h('div', { class: 'way-text' }, h('span', { class: 't' }, line, more)), + h('div', { class: 'way-row' }, h('span', { class: 'way-end' }, ic(d.kind)), track, h('span', { class: 'way-end home' }, ic('server'))), + text, ); - return { - el, - connected() { - el.classList.add('done'); - morphText(line, fmt(_('%s connected'), d.name)); - }, - gaveUp() { - el.classList.add('stopped'); - morphText(line, _('No connection yet')); - more.textContent = _('Close this and open it again to keep checking.'); + + // The lines sit centred in their block: when the second comes or goes, the block's height and the lines' place + // glide together (a FLIP of the lines), so the first never jumps to its new centre. `from` and `top`: the block's + // height and the lines' top on screen before the change. + const glide = (from: number, top: number) => { + text.getAnimations().forEach((a) => a.cancel()); + t.getAnimations().forEach((a) => a.cancel()); + const to = text.offsetHeight; + text.style.overflow = ''; + if (from !== to) { + text.style.overflow = 'hidden'; + play(text, [{ height: `${from}px` }, { height: `${to}px` }], { duration: 340, easing: EASE_OUT }).onfinish = () => { + text.style.overflow = ''; + }; + } + // Measured with the block held at its old height (its glide has just started), the sheet around it at its old + // size too: the lines start exactly where they stood, however the sheet is anchored and however they centre. + const dy = top - t.getBoundingClientRect().top; + if (Math.abs(dy) > 0.5) play(t, [{ transform: `translateY(${dy}px)` }, { transform: 'none' }], { duration: 340, easing: EASE_OUT }); + }; + /** Where the line under it shows its words on screen (mid-morph, the words it is turning into). */ + const words = () => { + const r = document.createRange(); + r.selectNodeContents(more.querySelector(':scope > .mt-new') ?? more); + return r.getBoundingClientRect(); + }; + // The line under it comes, goes and changes without the block snapping: in, it blurs in as the block opens; out, + // it blurs away first, then the block closes; another in its place, the words blur from the old into the new + // where they stand as the block glides to the new one's height. A fade under way turns round from where it is. + let says = ''; + let hiding = 0; + const second = (why: string) => { + if (why === says) return; + says = why; + clearTimeout(hiding); + const shown = !more.hidden; + const cs = getComputedStyle(more); + const cur = { opacity: cs.opacity, filter: cs.filter }; + if (!why) { + if (!shown) return; + more.getAnimations().forEach((a) => a.cancel()); + play(more, [cur, { opacity: 0, filter: 'blur(4px)' }], { duration: 180, easing: EASE_OUT, fill: 'forwards' }); + hiding = window.setTimeout(() => { + const from = text.offsetHeight; + const top = t.getBoundingClientRect().top; + more.hidden = true; + more.getAnimations().forEach((a) => a.cancel()); + glide(from, top); + }, 170); + return; + } + const from = text.offsetHeight; + const top = t.getBoundingClientRect().top; + if (!shown) { + setText(more, why); more.hidden = false; + glide(from, top); play( - line.parentElement!, + more, [ { opacity: 0, filter: 'blur(4px)' }, { opacity: 1, filter: 'none' }, ], - { duration: 280, easing: EASE_OUT }, + { duration: 300, easing: EASE_OUT, delay: 60, fill: 'backwards' }, ); + return; + } + // The old words go from where they stand now, placed against the block as the glide holds it on its first frame. + const was = textOf(more); + const at = words(); + setText(more, why); + glide(from, top); + morphText(more, why, was, { whole: true, at }); + more.getAnimations().forEach((a) => a.cancel()); + if (+cur.opacity < 1) play(more, [cur, { opacity: 1, filter: 'none' }], { duration: 300, easing: EASE_OUT }); + }; + const packets = (on: boolean) => { + // Those on their way out are not counted: back to no data while they fade, a fresh pair sets off. + const pk = track.querySelectorAll('.way-pkt:not(.out)'); + if (on) { + // Two, half a loop apart: one is always on its way. + if (!pk.length) track.append(h('span', { class: 'way-pkt' }), h('span', { class: 'way-pkt b' })); + return; + } + // Each fades where it is, falling on (a fade from script wins over its loop's own opacity), then goes. + pk.forEach((p) => { + p.classList.add('out'); + const o = getComputedStyle(p).opacity; + play(p, [{ opacity: o }, { opacity: 0 }], { duration: 200, easing: EASE_IN, fill: 'forwards' }).onfinish = () => p.remove(); + }); + }; + return { + el, + set(st) { + el.classList.remove('trying', 'nodata', 'done', 'stopped'); + if (LOOK[st]) el.classList.add(LOOK[st]); + const [a, b] = lines(st, d); + morphText(line, a); + second(b); + packets(st === 'nodata'); + }, + gaveUp() { + el.classList.remove('trying', 'nodata', 'done'); + el.classList.add('stopped'); + packets(false); + morphText(line, _('No connection yet')); + second(_('Close this and open it again to keep checking.')); }, }; } /** - * The first connection was seen (a fresh handshake) before the agent's watcher - * marked the device online, a second at most: ask again shortly, a few times, - * and repaint the page with the answer, so the card goes on to "Connected" - * instead of staying on "Last connected just now". + * The first connection was seen before the agent's watcher marked the device + * online, a second at most: ask again shortly, a few times, and repaint the + * page with the answer, so the card goes on to "Connected" instead of staying + * on "Last connected just now". */ function catchUp(id: string, tries = 4) { window.setTimeout(async () => { @@ -77,25 +193,33 @@ function catchUp(id: string, tries = 4) { }, 1500); } +/** The open set-up sheets' polls, for pollNow(). */ +const pokes = new Set<() => void>(); + +/** Run the open set-up sheet's poll now instead of at its next turn (the demo, once its state switch moved). */ +export function pollNow() { + pokes.forEach((p) => p()); +} + /** - * Poll for the first connection of a device that never connected: 5 s at - * first, then slower, for ten minutes at most (then `gaveUp`), not while the - * tab is hidden (every poll is a process on the router), and never again once - * the link stopped working. `arrived` runs once. Returns the stop function. + * Poll the device being set up while its sheet is open: 5 s at first, then + * slower, for ten minutes at most (then `gaveUp`, unless it is connected: the + * sheet is closing by itself), not while the tab is hidden (every poll is a + * process on the router), and never again once the link stopped working. + * `seen` gets each new state of the way. Returns the stop function. */ -export function watchFirstConnection(d: Device, arrived: () => void, gaveUp: () => void): () => void { - // The first connection is a handshake newer than this sheet (router clock), not `online`: - // that follows the agent's watcher, which can lag the handshake by a poll, and a device - // set up again with new keys still reports the last handshake of its old ones. +export function watchFirstConnection(d: Device, seen: (st: WayState) => void, gaveUp: () => void): () => void { + // The states count from this sheet (router clock): way.ts. const opened = now(); let timer = 0; let polls = 0; let done = false; + let last: WayState = 'waiting'; const started = Date.now(); const poll = async () => { timer = 0; if (done) return; - if (Date.now() - started > 600_000) { + if (last !== 'connected' && Date.now() - started > 600_000) { done = true; gaveUp(); return; @@ -104,12 +228,14 @@ export function watchFirstConnection(d: Device, arrived: () => void, gaveUp: () try { const st = await call('state'); setState(st); + // Left while it asked: the answer is the page's, not this sheet's any more. + if (done) return; const dev = st.person.devices.find((x) => x.id === d.id); - if (dev && dev.handshake > opened) { - done = true; - arrived(); - if (!dev.online) catchUp(d.id); - return; + const next = wayState(dev, opened); + if (next !== last) { + if (next === 'connected' && dev && !dev.online) catchUp(d.id); + last = next; + seen(next); } } catch (e) { if (gone(e)) { @@ -126,47 +252,170 @@ export function watchFirstConnection(d: Device, arrived: () => void, gaveUp: () const onVisible = () => { if (!document.hidden && !done && !timer) void poll(); }; + const poke = () => { + if (done) return; + if (timer) clearTimeout(timer); + void poll(); + }; document.addEventListener('visibilitychange', onVisible); + pokes.add(poke); schedule(); return () => { done = true; if (timer) clearTimeout(timer); document.removeEventListener('visibilitychange', onVisible); + pokes.delete(poke); }; } -const beat = (ms: number) => new Promise((r) => setTimeout(r, ms)); +/** What the sheet around the way is made of (setup-view.ts). */ +export interface Around { + /** The line under the sheet's title. */ + sub: HTMLElement; + /** Everything under the way. */ + rest: HTMLElement; + /** Give what is under the way its shape for this state, at once (the glide is here); false: nothing changed. */ + shape(st: WayState): boolean; +} + +/** Blocks folded away, held at nothing until they come back. */ +const folded = new WeakSet(); /** - * The first connection arrived. The way fills green and says so (the sheet - * goes back up to it if it was scrolled), the buttons beside × step away; then - * everything under the way, which did its job, folds shut. Two seconds to read - * it, and the sheet closes by itself onto the page, the card ringing green. + * Fold a block away (its height and margins to nothing, blurring out) or bring + * it back, from wherever it stands now: a fold turned round half-way never jumps. + * With less motion it fades out and then is gone, its space with it (or comes + * back at once and fades in): nothing travels, and nothing keeps a blank band. */ -export async function arrive(way: Way, rest: HTMLElement, d: Device) { - way.connected(); - settle(); - scrollTop(); - await beat(400); - if (!showing(way.el)) return; +function fold(el: HTMLElement, away: boolean, duration: number) { + if (folded.has(el) === away) return; + if (away) folded.add(el); + else folded.delete(el); + if (calm()) { + el.getAnimations().forEach((a) => a.cancel()); + if (!away) { + el.hidden = false; + play(el, [{ opacity: 0 }, { opacity: 1 }], { duration }); + return; + } + play(el, [{ opacity: 1 }, { opacity: 0 }], { duration, fill: 'forwards' }).onfinish = () => { + if (folded.has(el)) el.hidden = true; + }; + return; + } + el.hidden = false; + const cs = getComputedStyle(el); + const cur = { + height: `${el.getBoundingClientRect().height}px`, + marginTop: cs.marginTop, + marginBottom: cs.marginBottom, + opacity: cs.opacity, + filter: cs.filter, + }; + el.getAnimations().forEach((a) => a.cancel()); + const own = getComputedStyle(el); + const to = away + ? { height: '0px', marginTop: '0px', marginBottom: '0px', opacity: 0, filter: 'blur(4px)' } + : { + height: `${el.getBoundingClientRect().height}px`, + marginTop: own.marginTop, + marginBottom: own.marginBottom, + opacity: 1, + filter: 'none', + }; + el.style.overflow = 'hidden'; + play(el, [cur, to], { duration, easing: EASE_OUT, fill: away ? 'forwards' : 'none' }).onfinish = () => { + if (!away) el.style.overflow = ''; + }; +} + +/** The way's own gap to what is under it (18 px, setup.css) goes with it, and comes back with it. */ +function gap(way: HTMLElement, away: boolean) { + const from = getComputedStyle(way).marginBottom; + way.getAnimations().forEach((a) => a.cancel()); + const to = away ? '0px' : getComputedStyle(way).marginBottom; + play(way, [{ marginBottom: from }, { marginBottom: to }], { duration: 520, easing: EASE_OUT, fill: away ? 'forwards' : 'none' }); +} + +/** What is under the way takes another shape: it glides to its new height, and what came in blurs in. */ +function reshape(a: Around, st: WayState) { + const rest = a.rest; + // From where it stands on screen (a glide under way included) to its new height. + const h0 = rest.getBoundingClientRect().height; + if (!a.shape(st)) return; + rest.getAnimations().forEach((x) => x.cancel()); + const h1 = rest.getBoundingClientRect().height; rest.style.overflow = 'hidden'; + play(rest, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: 420, easing: EASE_OUT }).onfinish = () => { + rest.style.overflow = ''; + }; play( rest, [ - { height: `${rest.offsetHeight}px`, opacity: 1, filter: 'none' }, - { height: '0px', opacity: 0, filter: 'blur(4px)' }, + { opacity: 0.4, filter: 'blur(2px)' }, + { opacity: 1, filter: 'none' }, ], - { - duration: 520, - easing: EASE_OUT, - fill: 'forwards', - }, + { duration: 320, easing: EASE_OUT }, ); - play(way.el, [{ marginBottom: '18px' }, { marginBottom: '0px' }], { duration: 520, easing: EASE_OUT, fill: 'forwards' }); - // Reading time, not motion: the same with less motion. - await beat(2400); - // Only this sheet: not one the visitor went on to. - if (!showing(way.el)) return; - onClosed(() => repaint({ flash: d.id })); - closeSheet(); +} + +/** What the sheet does as the wait goes on (follow). */ +export interface Following { + /** A new state of the way. */ + seen(st: WayState): void; + /** Ten minutes and nothing (watchFirstConnection). */ + gaveUp(): void; +} + +/** + * The sheet keeps pace with the way. Connected: × and the buttons beside it + * step away, the sheet goes back up to the way if it was scrolled, everything + * under the way folds shut with the way's gap to it, and after two seconds to + * read it the sheet closes by itself onto the page, the card ringing green. Any + * other state undoes that (× comes back, what folded unfolds) and gives what is + * under the way its shape. The subtitle says what setting up takes, so it shows + * only while waiting: once the device is heard from, or the wait gives up, it + * folds away, the way then right under the head. + */ +export function follow(d: Device, way: Way, a: Around): Following { + let shut = false; + let timers: number[] = []; + const later = (ms: number, f: () => void) => timers.push(window.setTimeout(f, ms)); + const seen = (st: WayState) => { + timers.forEach(clearTimeout); + timers = []; + way.set(st); + fold(a.sub, st !== 'waiting', 380); + settle(st === 'connected'); + if (st === 'connected') { + scrollTop(); + later(400, () => { + if (!showing(way.el)) return; + shut = true; + fold(a.rest, true, 520); + gap(way.el, true); + // Reading time, not motion: the same with less motion. + later(2400, () => { + // Only this sheet: not one the visitor went on to. + if (!showing(way.el)) return; + onClosed(() => repaint({ flash: d.id })); + closeSheet(); + }); + }); + return; + } + if (!shut) return reshape(a, st); + // Folded while it was connected: it unfolds straight into its new shape. + shut = false; + a.shape(st); + fold(a.rest, false, 520); + gap(way.el, false); + }; + return { + seen, + gaveUp() { + fold(a.sub, true, 380); + way.gaveUp(); + }, + }; } diff --git a/web/src/portal/i18n/portal.pot b/web/src/portal/i18n/portal.pot index ff33e62..d3a9eb2 100644 --- a/web/src/portal/i18n/portal.pot +++ b/web/src/portal/i18n/portal.pot @@ -29,6 +29,10 @@ msgid_plural "%s already has %d devices. Remove one first to lower the limit to msgstr[0] "" msgstr[1] "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s and %s overlap: each packet type needs values of its own." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s can't use the network interface %s: it exists and isn't Dawnline's." msgstr "" @@ -51,6 +55,10 @@ msgstr[1] "" msgid "%s h ago" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s has a tag that is not closed with >." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s has an invalid interface name \"%s\"." msgstr "" @@ -67,6 +75,10 @@ msgstr "" msgid "%s is kept down." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)." msgstr "" @@ -79,12 +91,40 @@ msgstr "" msgid "%s left" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s may not contain # or a line break." +msgstr "" + #: web/src/shared/format.ts msgid "%s min ago" msgstr "" #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc -msgid "%s must be a number or range" +msgid "%s must be a number or a range like 10-100, up to 65535." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a number or a range like 100-200, up to 4294967295." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a number or a range like 5-15, from 1 to 65535." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a whole number from 0 to 65535." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be at least 12 with header protection." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be from %d to %d." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be on or off." msgstr "" #: web/src/portal/page/devices.ts @@ -121,6 +161,10 @@ msgstr "" msgid "%s your time" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s: <%s> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or ." +msgstr "" + #: web/src/shared/format.ts msgid "%sd %sh" msgstr "" @@ -186,6 +230,10 @@ msgstr "" msgid "Add the connection" msgstr "" +#: web/src/portal/flows/setup-view.ts +msgid "Add the connection again" +msgstr "" + #: web/src/portal/page/devices.ts msgid "Add this device" msgstr "" @@ -247,6 +295,10 @@ msgstr "" msgid "Cancel" msgstr "" +#: web/src/portal/page/devices.ts +msgid "Can’t finish connecting" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Circle %s: server %s does not exist." msgstr "" @@ -280,6 +332,10 @@ msgstr "" msgid "Connected" msgstr "" +#: web/src/portal/page/devices.ts +msgid "Connected, but no data" +msgstr "" + #: web/src/portal/page/devices.ts msgid "Connected, no data left" msgstr "" @@ -288,6 +344,10 @@ msgstr "" msgid "Connected, outside your hours" msgstr "" +#: web/src/portal/page/devices.ts +msgid "Connection keeps dropping" +msgstr "" + #: web/src/portal/flows/secure.ts msgid "Connection settings only travel encrypted" msgstr "" @@ -381,6 +441,14 @@ msgstr "" msgid "Data used" msgstr "" +#: web/src/shared/format.ts +msgid "Device" +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: MTU %d is not between 1280 and 1500." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s of %s: address %s is also used by device %s of %s." msgstr "" @@ -401,6 +469,10 @@ msgstr "" msgid "Device %s of %s: address (none) is not a plain IPv4 address." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s of %s: the preshared key is not a key." msgstr "" @@ -413,6 +485,10 @@ msgstr "" msgid "Device %s of %s: the public key is not a key." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: the public key is the server's own." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s: person %s does not exist." msgstr "" @@ -425,7 +501,7 @@ msgstr "" msgid "Device limit reached (%d)." msgstr "" -#: web/src/portal/flows/device-actions.ts +#: web/src/portal/flows/rename.ts msgid "Device name" msgstr "" @@ -503,7 +579,11 @@ msgid "Ends %s" msgstr "" #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc -msgid "Enter a device name (up to 48 characters)." +msgid "Enter a device name: up to %d letters, digits, spaces and - _ ." +msgstr "" + +#: web/src/portal/flows/add.ts +msgid "Except %s: those addresses lead to the home network." msgstr "" #: web/src/shared/format.ts @@ -542,6 +622,14 @@ msgstr "" msgid "Get it on" msgstr "" +#: web/src/portal/flows/rename.ts +msgid "Give the device a name." +msgstr "" + +#: web/src/portal/flows/wait.ts +msgid "Handshake complete, but no data" +msgstr "" + #: web/src/portal/flows/setup-parts.ts msgid "Hide key" msgstr "" @@ -567,6 +655,10 @@ msgstr "" msgid "Hours, your time" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "I1-I5 together must be at most 2000 characters, not %d." +msgstr "" + #: web/src/portal/page/devices.ts msgid "IP address copied" msgstr "" @@ -585,6 +677,10 @@ msgstr "" msgid "Import the configuration" msgstr "" +#: web/src/portal/flows/setup-view.ts +msgid "Import the configuration again" +msgstr "" + #: web/src/portal/setup.ts msgctxt "WireGuard app" msgid "Import tunnel(s) from file…" @@ -624,6 +720,10 @@ msgstr "" msgid "Invalid public key." msgstr "" +#: web/src/portal/page/devices.ts +msgid "It connects, but the connection breaks every few minutes. Another network may help." +msgstr "" + #: web/src/portal/page/access.ts msgid "It ended on %s." msgstr "" @@ -636,14 +736,26 @@ msgstr "" msgid "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." msgstr "" +#: web/src/portal/page/devices.ts +msgid "It reaches the router, but the connection never completes. The network may be blocking it." +msgstr "" + #: web/src/portal/flows/device-actions.ts msgid "Its connection stops working at once. You can add it again later." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "Jmin must not be larger than Jmax." +msgstr "" + #: web/src/shared/format.ts msgid "KB" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Keep-alive must be 0-600 seconds." +msgstr "" + #: web/src/portal/flows/setup-parts.ts #: web/src/portal/flows/setup-view.ts msgid "Key copied" @@ -662,6 +774,10 @@ msgstr "" msgid "Key generation failed." msgstr "" +#: web/src/portal/flows/add.ts +msgid "LAN Bypass" +msgstr "" + #: web/src/portal/page/frame.ts msgid "Language" msgstr "" @@ -686,6 +802,10 @@ msgstr "" msgid "MB" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "MTU must be 1280-1500." +msgstr "" + #: web/src/shared/format.ts msgid "Mbit/s" msgstr "" @@ -782,6 +902,18 @@ msgstr "" msgid "On GitHub" msgstr "" +#: web/src/portal/page/devices.ts +msgid "On two devices at once" +msgstr "" + +#: web/src/shared/name-guard.ts +msgid "Only letters, digits, - _ ." +msgstr "" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc +msgid "Only the admin can change how a device connects." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc msgid "Only the admin can turn devices off." msgstr "" @@ -893,10 +1025,6 @@ msgstr "" msgid "Phone" msgstr "" -#: web/src/portal/flows/add.ts -msgid "Phones and tablets get a smaller packet size that suits mobile networks." -msgstr "" - #: web/src/portal/flows/setup-parts.ts msgid "Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app." msgstr "" @@ -943,6 +1071,10 @@ msgstr "" msgid "Reconnect %s?" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "RejectAfterTime must be at most 180 seconds." +msgstr "" + #: web/src/portal/flows/device-actions.ts #: web/src/portal/page/devices.ts msgid "Remove" @@ -956,14 +1088,10 @@ msgstr "" msgid "Rename" msgstr "" -#: web/src/portal/flows/device-actions.ts +#: web/src/portal/page/devices.ts msgid "Rename %s" msgstr "" -#: web/src/portal/flows/device-actions.ts -msgid "Renamed" -msgstr "" - #: web/src/portal/api.ts msgid "Request failed (%s)" msgstr "" @@ -976,6 +1104,10 @@ msgstr "" msgid "Resets on the 1st." msgstr "" +#: web/src/portal/flows/rename.ts +msgid "Return to save, Esc to cancel" +msgstr "" + #: web/src/shared/format.ts msgid "Router" msgstr "" @@ -984,8 +1116,8 @@ msgstr "" msgid "Run" msgstr "" -#: web/src/portal/flows/device-actions.ts -msgid "Save" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size." msgstr "" #: web/src/portal/setup.ts @@ -1017,6 +1149,10 @@ msgstr "" msgid "Server is turned off" msgstr "" +#: web/src/portal/flows/setup-view.ts +msgid "Set it up again" +msgstr "" + #: web/src/portal/flows/setup-view.ts #: web/src/portal/page/devices.ts msgid "Set up %s" @@ -1078,6 +1214,10 @@ msgstr "" msgid "Tap “%s” and connect" msgstr "" +#: web/src/portal/flows/rename.ts +msgid "That name is taken." +msgstr "" + #: web/src/portal/setup.ts msgid "The APK is for phones without Google Play, or where the store hides the app." msgstr "" @@ -1094,6 +1234,10 @@ msgstr "" msgid "The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”)." msgstr "" +#: web/src/portal/flows/setup-view.ts +msgid "The configuration is too long for a code. Scan this one to open your link on the %s instead." +msgstr "" + #: web/src/portal/flows/setup-parts.ts msgid "The connection" msgstr "" @@ -1102,10 +1246,18 @@ msgstr "" msgid "The connection as one key" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "The header protection key is not a key." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "The id may use lowercase letters, digits and underscores." msgstr "" +#: web/src/portal/flows/setup-view.ts +msgid "The key is too long for a code. Scan this one to open your link on the %s instead." +msgstr "" + #: web/src/portal/flows/setup-view.ts msgid "The packages and the file for OpenWrt" msgstr "" @@ -1118,6 +1270,10 @@ msgstr "" msgid "The person has no server." msgstr "" +#: web/src/portal/page/devices.ts +msgid "The router can’t use what it sends: reconnect it." +msgstr "" + #: web/src/portal/flows/setup-parts.ts msgid "Then come back here and tap" msgstr "" @@ -1126,10 +1282,18 @@ msgstr "" msgid "Then import it in the app" msgstr "" +#: web/src/portal/page/devices.ts +msgid "This connection is on two devices and they push each other out. Add the other one as its own device." +msgstr "" + #: web/src/portal/page/devices.ts msgid "This device" msgstr "" +#: web/src/portal/flows/wait.ts +msgid "This device is using an outdated configuration." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "This key is already in use." msgstr "" @@ -1163,6 +1327,10 @@ msgstr "" msgid "Two steps, about a minute: get the app, then add the connection." msgstr "" +#: web/src/portal/flows/wait.ts +msgid "Unable to complete the handshake" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Unknown DNS choice." msgstr "" @@ -1196,6 +1364,10 @@ msgstr "" msgid "Unknown service %s." msgstr "" +#: web/src/shared/name-guard.ts +msgid "Up to %s characters." +msgstr "" + #: web/src/portal/ui/bars.ts msgid "Uploaded" msgstr "" @@ -1268,6 +1440,14 @@ msgstr "" msgid "Your devices can’t connect until it’s resumed." msgstr "" +#: web/src/portal/flows/add.ts +msgid "Your local network stays reachable while connected." +msgstr "" + +#: web/src/portal/flows/wait.ts +msgid "Your network may be blocking the connection." +msgstr "" + #: web/src/shared/format.ts msgid "bit/s" msgstr "" @@ -1314,10 +1494,6 @@ msgstr "" msgid "ends tomorrow" msgstr "" -#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc -msgid "h1-h4 must be distinct" -msgstr "" - #: web/src/shared/format.ts msgid "just now" msgstr "" diff --git a/web/src/portal/i18n/ru.po b/web/src/portal/i18n/ru.po index cd70648..aeaa145 100644 --- a/web/src/portal/i18n/ru.po +++ b/web/src/portal/i18n/ru.po @@ -32,6 +32,10 @@ msgstr[0] "%s: уже %d устройство. Чтобы снизить лим msgstr[1] "%s: уже %d устройства. Чтобы снизить лимит до %d, сначала удалите одно из них." msgstr[2] "%s: уже %d устройств. Чтобы снизить лимит до %d, сначала удалите одно из них." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s and %s overlap: each packet type needs values of its own." +msgstr "%s и %s пересекаются: у каждого типа пакетов должны быть свои значения." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s can't use the network interface %s: it exists and isn't Dawnline's." msgstr "Сервер %s не может использовать сетевой интерфейс %s: он уже существует и создан не Dawnline." @@ -55,6 +59,10 @@ msgstr[2] "%s дней" msgid "%s h ago" msgstr "%s ч назад" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s has a tag that is not closed with >." +msgstr "%s: тег не закрыт символом >." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s has an invalid interface name \"%s\"." msgstr "У сервера %s недопустимое имя интерфейса «%s»." @@ -71,6 +79,10 @@ msgstr "%s всего" msgid "%s is kept down." msgstr "Сервер %s остановлен." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s" +msgstr "Сервер %s остановлен: в его маскировке есть значения, которые AmneziaWG не примет. %s" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)." msgstr "Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (установлен %s)." @@ -83,13 +95,41 @@ msgstr "Сервер %s остановлен: для его маскировки msgid "%s left" msgstr "осталось %s" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s may not contain # or a line break." +msgstr "%s не может содержать # или перенос строки." + #: web/src/shared/format.ts msgid "%s min ago" msgstr "%s мин назад" #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc -msgid "%s must be a number or range" -msgstr "%s: нужно число или диапазон" +msgid "%s must be a number or a range like 10-100, up to 65535." +msgstr "%s: нужно число или диапазон вида 10-100, не больше 65535." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a number or a range like 100-200, up to 4294967295." +msgstr "%s: нужно число или диапазон вида 100-200, не больше 4294967295." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a number or a range like 5-15, from 1 to 65535." +msgstr "%s: нужно число или диапазон вида 5-15, от 1 до 65535." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be a whole number from 0 to 65535." +msgstr "%s: нужно целое число от 0 до 65535." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be at least 12 with header protection." +msgstr "%s: с защитой заголовков нужно не меньше 12." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be from %d to %d." +msgstr "%s: от %d до %d." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s must be on or off." +msgstr "%s: нужно on или off." #: web/src/portal/page/devices.ts msgid "%s of %s" @@ -126,6 +166,10 @@ msgstr "%s в этом месяце" msgid "%s your time" msgstr "%s по вашему времени" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "%s: <%s> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or ." +msgstr "%s: тег <%s> не примут приложения AmneziaWG: используйте с чётным числом шестнадцатеричных цифр, , или с N от 1 до 1000 либо ." + #: web/src/shared/format.ts msgid "%sd %sh" msgstr "%s д %s ч" @@ -191,6 +235,10 @@ msgstr "Добавить с самого устройства" msgid "Add the connection" msgstr "Добавьте подключение" +#: web/src/portal/flows/setup-view.ts +msgid "Add the connection again" +msgstr "Добавить заново" + #: web/src/portal/page/devices.ts msgid "Add this device" msgstr "Добавить это устройство" @@ -252,6 +300,10 @@ msgstr "Навигационная цепочка" msgid "Cancel" msgstr "Отмена" +#: web/src/portal/page/devices.ts +msgid "Can’t finish connecting" +msgstr "Не удаётся подключиться" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Circle %s: server %s does not exist." msgstr "Круг %s: сервера %s нет." @@ -285,6 +337,10 @@ msgstr "Подключить" msgid "Connected" msgstr "Подключено" +#: web/src/portal/page/devices.ts +msgid "Connected, but no data" +msgstr "Подключено, но данных нет" + #: web/src/portal/page/devices.ts msgid "Connected, no data left" msgstr "Подключено, трафик закончился" @@ -293,6 +349,10 @@ msgstr "Подключено, трафик закончился" msgid "Connected, outside your hours" msgstr "Подключено, вне часов доступа" +#: web/src/portal/page/devices.ts +msgid "Connection keeps dropping" +msgstr "Связь постоянно рвётся" + #: web/src/portal/flows/secure.ts msgid "Connection settings only travel encrypted" msgstr "Настройки подключения передаются только в зашифрованном виде" @@ -386,6 +446,14 @@ msgstr "Трафик за месяц" msgid "Data used" msgstr "Трафик всего" +#: web/src/shared/format.ts +msgid "Device" +msgstr "Устройство" + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: MTU %d is not between 1280 and 1500." +msgstr "Устройство %s (%s): MTU %d вне пределов от 1280 до 1500." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s of %s: address %s is also used by device %s of %s." msgstr "Устройство %s (%s): адрес %s уже занят устройством %s (%s)." @@ -406,6 +474,10 @@ msgstr "Устройство %s (%s): адрес %s принадлежит са msgid "Device %s of %s: address (none) is not a plain IPv4 address." msgstr "Устройство %s (%s): нет IPv4-адреса." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds." +msgstr "Устройство %s (%s): keep-alive %d вне пределов от 0 до 600 секунд." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s of %s: the preshared key is not a key." msgstr "Устройство %s (%s): общий ключ (PSK) некорректен." @@ -418,6 +490,10 @@ msgstr "Устройство %s (%s): приватный ключ некорре msgid "Device %s of %s: the public key is not a key." msgstr "Устройство %s (%s): публичный ключ некорректен." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Device %s of %s: the public key is the server's own." +msgstr "Устройство %s (%s): публичный ключ совпадает с ключом сервера." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Device %s: person %s does not exist." msgstr "Устройство %s: человека %s нет." @@ -430,7 +506,7 @@ msgstr "Лимит устройств: от 1 до 32." msgid "Device limit reached (%d)." msgstr "Достигнут лимит устройств (%d)." -#: web/src/portal/flows/device-actions.ts +#: web/src/portal/flows/rename.ts msgid "Device name" msgstr "Имя устройства" @@ -508,8 +584,12 @@ msgid "Ends %s" msgstr "Закончится %s" #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc -msgid "Enter a device name (up to 48 characters)." -msgstr "Введите название устройства (до 48 символов)." +msgid "Enter a device name: up to %d letters, digits, spaces and - _ ." +msgstr "Введите название устройства: до %d букв, цифр, пробелов и - _ ." + +#: web/src/portal/flows/add.ts +msgid "Except %s: those addresses lead to the home network." +msgstr "Кроме %s: эти адреса ведут в домашнюю сеть." #: web/src/shared/format.ts msgid "Expired" @@ -547,6 +627,14 @@ msgstr "Установите %s на роутер" msgid "Get it on" msgstr "Доступно в" +#: web/src/portal/flows/rename.ts +msgid "Give the device a name." +msgstr "Дайте устройству название." + +#: web/src/portal/flows/wait.ts +msgid "Handshake complete, but no data" +msgstr "Рукопожатие есть, но данных нет" + #: web/src/portal/flows/setup-parts.ts msgid "Hide key" msgstr "Скрыть ключ" @@ -572,6 +660,10 @@ msgstr "Часы доступа, время роутера" msgid "Hours, your time" msgstr "Часы доступа, ваше время" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "I1-I5 together must be at most 2000 characters, not %d." +msgstr "I1–I5 вместе: не больше 2000 символов, сейчас %d." + #: web/src/portal/page/devices.ts msgid "IP address copied" msgstr "IP-адрес скопирован" @@ -590,6 +682,10 @@ msgstr "Импорт из файла или архива" msgid "Import the configuration" msgstr "Импортируйте конфигурацию" +#: web/src/portal/flows/setup-view.ts +msgid "Import the configuration again" +msgstr "Импортировать заново" + #: web/src/portal/setup.ts msgctxt "WireGuard app" msgid "Import tunnel(s) from file…" @@ -629,6 +725,10 @@ msgstr "Некорректный JSON." msgid "Invalid public key." msgstr "Недопустимый публичный ключ." +#: web/src/portal/page/devices.ts +msgid "It connects, but the connection breaks every few minutes. Another network may help." +msgstr "Устройство подключается, но связь рвётся каждые несколько минут. Может помочь другая сеть." + #: web/src/portal/page/access.ts msgid "It ended on %s." msgstr "Доступ закончился %s." @@ -641,14 +741,26 @@ msgstr "Устройство получит новые ключи, а текущ msgid "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." msgstr "Устройство получит новые ключи. Сейчас вы подключены через его текущие настройки: через несколько секунд после подтверждения связь прервётся. Добавьте новые - они откроются следом." +#: web/src/portal/page/devices.ts +msgid "It reaches the router, but the connection never completes. The network may be blocking it." +msgstr "Устройство доходит до роутера, но подключение не завершается. Возможно, его блокирует сеть." + #: web/src/portal/flows/device-actions.ts msgid "Its connection stops working at once. You can add it again later." msgstr "Подключение сразу перестанет работать. Устройство можно будет добавить снова." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "Jmin must not be larger than Jmax." +msgstr "Jmin не может быть больше Jmax." + #: web/src/shared/format.ts msgid "KB" msgstr "КБ" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Keep-alive must be 0-600 seconds." +msgstr "Keep-alive: от 0 до 600 секунд." + #: web/src/portal/flows/setup-parts.ts #: web/src/portal/flows/setup-view.ts msgid "Key copied" @@ -667,6 +779,10 @@ msgstr "Не удалось создать ключ (нет случайных msgid "Key generation failed." msgstr "Не удалось создать ключ." +#: web/src/portal/flows/add.ts +msgid "LAN Bypass" +msgstr "Обход локальной сети" + #: web/src/portal/page/frame.ts msgid "Language" msgstr "Язык" @@ -691,6 +807,10 @@ msgstr "Компьютер с Linux" msgid "MB" msgstr "МБ" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "MTU must be 1280-1500." +msgstr "MTU: от 1280 до 1500." + #: web/src/shared/format.ts msgid "Mbit/s" msgstr "Мбит/с" @@ -787,6 +907,18 @@ msgstr "Дата окончания - %s." msgid "On GitHub" msgstr "На GitHub" +#: web/src/portal/page/devices.ts +msgid "On two devices at once" +msgstr "На двух устройствах сразу" + +#: web/src/shared/name-guard.ts +msgid "Only letters, digits, - _ ." +msgstr "Только буквы, цифры, - _ ." + +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc +msgid "Only the admin can change how a device connects." +msgstr "Менять настройки подключения устройства может только администратор." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc msgid "Only the admin can turn devices off." msgstr "Отключать устройства может только администратор." @@ -898,10 +1030,6 @@ msgstr "Человек %s: сервера %s нет." msgid "Phone" msgstr "Телефон" -#: web/src/portal/flows/add.ts -msgid "Phones and tablets get a smaller packet size that suits mobile networks." -msgstr "У телефонов и планшетов пакеты меньше - так лучше для мобильных сетей." - #: web/src/portal/flows/setup-parts.ts msgid "Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app." msgstr "Выберите AmneziaVPN в меню «Поделиться». Его там нет? %s и добавьте его в приложении." @@ -948,6 +1076,10 @@ msgstr "Переподключить %s" msgid "Reconnect %s?" msgstr "Переподключить «%s»?" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "RejectAfterTime must be at most 180 seconds." +msgstr "RejectAfterTime: не больше 180 секунд." + #: web/src/portal/flows/device-actions.ts #: web/src/portal/page/devices.ts msgid "Remove" @@ -961,14 +1093,10 @@ msgstr "Удалить «%s»?" msgid "Rename" msgstr "Переименовать" -#: web/src/portal/flows/device-actions.ts +#: web/src/portal/page/devices.ts msgid "Rename %s" msgstr "Переименовать «%s»" -#: web/src/portal/flows/device-actions.ts -msgid "Renamed" -msgstr "Переименовано" - #: web/src/portal/api.ts msgid "Request failed (%s)" msgstr "Не удалось выполнить запрос (%s)" @@ -981,6 +1109,10 @@ msgstr "Слишком большой запрос." msgid "Resets on the 1st." msgstr "Обнуляется 1-го числа." +#: web/src/portal/flows/rename.ts +msgid "Return to save, Esc to cancel" +msgstr "Return сохраняет, Esc отменяет" + #: web/src/shared/format.ts msgid "Router" msgstr "Роутер" @@ -989,9 +1121,9 @@ msgstr "Роутер" msgid "Run" msgstr "Выполните" -#: web/src/portal/flows/device-actions.ts -msgid "Save" -msgstr "Сохранить" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size." +msgstr "S2 не может равняться S1 + 56: начальный и ответный пакеты рукопожатия будут одного размера." #: web/src/portal/setup.ts msgctxt "WireGuard app" @@ -1022,6 +1154,10 @@ msgstr "Сервер выключен" msgid "Server is turned off" msgstr "Сервер выключен" +#: web/src/portal/flows/setup-view.ts +msgid "Set it up again" +msgstr "Настроить заново" + #: web/src/portal/flows/setup-view.ts #: web/src/portal/page/devices.ts msgid "Set up %s" @@ -1083,6 +1219,10 @@ msgstr "Планшет" msgid "Tap “%s” and connect" msgstr "Нажмите «%s» и подключитесь" +#: web/src/portal/flows/rename.ts +msgid "That name is taken." +msgstr "Это имя уже занято." + #: web/src/portal/setup.ts msgid "The APK is for phones without Google Play, or where the store hides the app." msgstr "APK - для телефонов без Google Play или если магазин скрывает приложение." @@ -1099,6 +1239,10 @@ msgstr "Приложение ставится на %s." msgid "The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”)." msgstr "Браузер может предупредить, что сертификату нельзя доверять: это собственный сертификат роутера. Продолжите переход («Дополнительные» → «Перейти на сайт»)." +#: web/src/portal/flows/setup-view.ts +msgid "The configuration is too long for a code. Scan this one to open your link on the %s instead." +msgstr "Конфигурация слишком длинная для QR-кода. Отсканируйте этот код, чтобы открыть свою ссылку на %s." + #: web/src/portal/flows/setup-parts.ts msgid "The connection" msgstr "Подключение" @@ -1107,10 +1251,18 @@ msgstr "Подключение" msgid "The connection as one key" msgstr "Подключение одним ключом" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +msgid "The header protection key is not a key." +msgstr "Ключ защиты заголовков некорректен." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "The id may use lowercase letters, digits and underscores." msgstr "В идентификаторе можно использовать строчные латинские буквы, цифры и подчёркивания." +#: web/src/portal/flows/setup-view.ts +msgid "The key is too long for a code. Scan this one to open your link on the %s instead." +msgstr "Ключ слишком длинный для QR-кода. Отсканируйте этот код, чтобы открыть свою ссылку на %s." + #: web/src/portal/flows/setup-view.ts msgid "The packages and the file for OpenWrt" msgstr "Пакеты и файл для OpenWrt" @@ -1123,6 +1275,10 @@ msgstr "Не удалось загрузить страницу" msgid "The person has no server." msgstr "У человека нет сервера." +#: web/src/portal/page/devices.ts +msgid "The router can’t use what it sends: reconnect it." +msgstr "Роутер не принимает то, что отправляет устройство: переподключите его." + #: web/src/portal/flows/setup-parts.ts msgid "Then come back here and tap" msgstr "Затем вернитесь сюда и нажмите" @@ -1131,10 +1287,18 @@ msgstr "Затем вернитесь сюда и нажмите" msgid "Then import it in the app" msgstr "Затем импортируйте его в приложении" +#: web/src/portal/page/devices.ts +msgid "This connection is on two devices and they push each other out. Add the other one as its own device." +msgstr "Это подключение стоит на двух устройствах, и они вытесняют друг друга. Добавьте второе как отдельное устройство." + #: web/src/portal/page/devices.ts msgid "This device" msgstr "Это устройство" +#: web/src/portal/flows/wait.ts +msgid "This device is using an outdated configuration." +msgstr "На этом устройстве устаревшая конфигурация." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "This key is already in use." msgstr "Этот ключ уже используется." @@ -1168,6 +1332,10 @@ msgstr "Два шага, около минуты" msgid "Two steps, about a minute: get the app, then add the connection." msgstr "Два шага, около минуты: установите приложение, затем добавьте подключение." +#: web/src/portal/flows/wait.ts +msgid "Unable to complete the handshake" +msgstr "Не удаётся завершить рукопожатие" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Unknown DNS choice." msgstr "Неизвестный вариант DNS." @@ -1201,6 +1369,10 @@ msgstr "Неизвестный сервер." msgid "Unknown service %s." msgstr "Неизвестный сервис %s." +#: web/src/shared/name-guard.ts +msgid "Up to %s characters." +msgstr "Не больше %s символов." + #: web/src/portal/ui/bars.ts msgid "Uploaded" msgstr "Отправлено" @@ -1275,6 +1447,14 @@ msgstr "Ваши устройства не подключатся, пока до msgid "Your devices can’t connect until it’s resumed." msgstr "Ваши устройства не подключатся, пока доступ не возобновят." +#: web/src/portal/flows/add.ts +msgid "Your local network stays reachable while connected." +msgstr "Ваша локальная сеть остаётся доступной при подключении." + +#: web/src/portal/flows/wait.ts +msgid "Your network may be blocking the connection." +msgstr "Возможно, ваша сеть блокирует подключение." + #: web/src/shared/format.ts msgid "bit/s" msgstr "бит/с" @@ -1323,10 +1503,6 @@ msgstr "закончится сегодня" msgid "ends tomorrow" msgstr "закончится завтра" -#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc -msgid "h1-h4 must be distinct" -msgstr "h1-h4 должны быть разными" - #: web/src/shared/format.ts msgid "just now" msgstr "только что" diff --git a/web/src/portal/main.ts b/web/src/portal/main.ts index 7b4b3f7..3c0ec52 100644 --- a/web/src/portal/main.ts +++ b/web/src/portal/main.ts @@ -14,12 +14,13 @@ import { gone, call } from './api'; import { base, code, onRepaint, placeName, setState, state, type RepaintOpts, type State } from './state'; import { setupFromHash, wantsAdd } from './setup'; import { frame, crumbs, single } from './page/frame'; -import { pageNotice, stateNotice } from './page/notices'; -import { devicesSection, fillDevices } from './page/devices'; +import { fillNotice, stateNotice } from './page/notices'; +import { devicesNow, devicesSection, fillDevices } from './page/devices'; import { accessSection, fillAccess } from './page/access'; import { glass, type Tone } from './ui/glass'; import { closeMenu, menuOpen } from './ui/menu'; import { closeSheet, sheetOpen } from './ui/sheet'; +import { renaming } from './flows/rename'; import { startAdd } from './flows/add'; import { openSetup } from './flows/setup-view'; @@ -34,10 +35,12 @@ let redraw: () => void = () => {}; /** The first paint comes in: the blocks rise one after the other, the sun rises behind its line. */ function intro() { // In the order they stand on screen, top to bottom and then left to right: on a phone "Your access" comes before the devices. - const els = [...app.querySelectorAll('.crumbs, .notice, .sec-head, .dgrid > *, .note-s:not([hidden]), .acc-slot .acc-row, .gone')] + const blocks = [...app.querySelectorAll('.crumbs, .notice, .sec-head, .dgrid > *, .note-s:not([hidden]), .acc-slot .acc-row, .gone')] .map((el) => ({ el, at: el.getBoundingClientRect() })) - .sort((a, b) => Math.round(a.at.top) - Math.round(b.at.top) || a.at.left - b.at.left) - .map((x) => x.el); + .sort((a, b) => Math.round(a.at.top) - Math.round(b.at.top) || a.at.left - b.at.left); + const els = blocks.map((x) => x.el); + // The wave starts at the first block on screen (a reload goes back deep into the page): those above it rise with it. + const above = blocks.filter((x) => x.at.bottom <= 0).length; // Each block rises to its own opacity: a card the admin disabled is dimmed all the way, not at the end. const own = els.map((el) => getComputedStyle(el).opacity); els.forEach((el, i) => @@ -49,7 +52,7 @@ function intro() { ], { duration: 520, - delay: 60 + i * 40, + delay: 60 + Math.max(0, i - above) * 40, easing: EASE_OUT, fill: 'backwards', }, @@ -84,18 +87,63 @@ function render(o: RepaintOpts = {}) { single(false); crumbs(); document.title = placeName(); + // Safari lays the page out once with the new cards still empty (each is a size container, devices.css) and + // pulls the scroll up to fit that shorter page; a language change empties it all. The content keeps its height + // while it is refilled, and lets go once everything in it has its styles. + slot.style.minHeight = `${slot.offsetHeight}px`; + const fresh = !parts; if (!parts) { parts = { notice: h('div', { class: 'notice-slot' }), devices: devicesSection(), access: accessSection() }; put(slot, parts.notice, h('div', { class: 'cols' }, parts.devices, parts.access)); } + // Where the cards stand before anything above them changes: the notice and, on a phone, "Your access" move them too. + const devices = devicesNow(parts.devices); // What stops the devices comes first. - put(parts.notice, pageNotice(st.person)); - fillDevices(parts.devices, st, o); + fillNotice(parts.notice, st.person, !fresh); fillAccess(parts.access, st); - if (!booted) intro(); + fillDevices(parts.devices, st, o, devices); + slot.getBoundingClientRect(); + slot.style.minHeight = ''; + if (!booted) { + const y = keptPlace(); + if (y) scrollTo(0, y); + intro(); + } } onRepaint(render); +/* + * A phone drops a tab while the visitor is in another app (the VPN app, the App Store) and loads it again on + * return; a pull to refresh loads it again too. The browser puts the page back where it was as it loads, before + * the router has answered: the page is one empty screen then, so it stays at the top. The tab keeps the page's + * place itself, and the first paint of a reload (or of a step back onto the page) goes back there; a fresh visit + * to the link still opens at the top. Each link keeps its own (several people's links opened in one tab share the + * origin), and only the page drawn in its place has one: hidden before the router answered, or showing a card in + * place of the page, the tab keeps the place it had. + */ +const PLACE = `dl.y:${location.pathname}`; +function keepPlace() { + if (!parts) return; + try { + sessionStorage.setItem(PLACE, String(Math.round(scrollY))); + } catch { + // No storage (a private window that refuses it): a reload opens at the top. + } +} +function keptPlace(): number { + const how = (performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined)?.type; + if (how !== 'reload' && how !== 'back_forward') return 0; + try { + return Number(sessionStorage.getItem(PLACE)) || 0; + } catch { + return 0; + } +} +addEventListener('pagehide', keepPlace); +document.addEventListener('visibilitychange', () => { + if (document.hidden) keepPlace(); +}); + /** A card in place of the page: the link stopped working, nothing could load, or the access is paused. */ function only(icon: string, title: string, text: string, gone = false, tone: Tone = 'grey') { parts = null; @@ -134,14 +182,16 @@ function openFromLink() { history.replaceState(null, '', location.pathname + location.search); if (add) return startAdd(); const d = st.person.devices.find((x) => x.id === id); - if (d && !d.handshake && !d.disabled && !st.locked) void openSetup(d); + // Its own link: the page is open on that device. + if (d && !d.handshake && !d.disabled && !st.locked) void openSetup(d, null, true); } addEventListener('hashchange', openFromLink); async function refresh() { try { setState(await call('state')); - if (!sheetOpen() && !menuOpen()) render(); + // Not under an open sheet or menu, nor a name being edited on its card. + if (!sheetOpen() && !menuOpen() && !renaming()) render(); openFromLink(); } catch (e) { if (gone(e)) linkGone(); diff --git a/web/src/portal/motion.ts b/web/src/portal/motion.ts index 5d4459d..ad34254 100644 --- a/web/src/portal/motion.ts +++ b/web/src/portal/motion.ts @@ -93,6 +93,11 @@ export function rubber(dist: number, dim: number): number { return dist <= 0 || dim <= 0 ? 0 : (1 - 1 / ((dist * 0.55) / dim + 1)) * dim; } +/** How far a pull goes for an edge to stand `d` past it: rubber() undone (a sheet taken while it settles back). */ +export function unrubber(d: number, dim: number): number { + return d <= 0 || dim <= 0 ? 0 : (d * dim) / (0.55 * Math.max(1, dim - d)); +} + /** * Does a pulled sheet go away? A flick down (px/ms, as Vaul) or a pull past a * third of its height does; a flick back up keeps it, however far it went. diff --git a/web/src/portal/page/access.ts b/web/src/portal/page/access.ts index fbe024e..fe8bda1 100644 --- a/web/src/portal/page/access.ts +++ b/web/src/portal/page/access.ts @@ -2,20 +2,23 @@ // access reaches (home and internet as two tiles, and the names devices at // home reach this person's devices by); the data, as a ring in the head and // the month day by day inside; and until when, as the days left over a -// calendar of the weeks, with the admin's hours as a bar of the day. +// calendar of the weeks, with the admin's hours as a bar of the day. A repaint +// keeps the rows on the page and changes what they hold in place. import type { Pair, Person } from '../../shared/types'; import { accessLabel, byDeviceState, bytes, date, daysLeft, endsSoon, parseDay } from '../../shared/format'; import { fill, fmt, locale, num, plural } from '../../shared/i18n'; import { h, ic, markup } from '../dom'; import { calendar, clockOf, hoursFor, minuteAt, monthOf, stretches } from '../days'; +import { SMOOTH, play } from '../motion'; import { now, today, type State } from '../state'; -import { accordion, type Accordion } from '../ui/accordion'; +import { accordion, regrow, type Accordion } from '../ui/accordion'; import { bars, upDown } from '../ui/bars'; import { copy } from '../ui/feedback'; import { glass } from '../ui/glass'; -import { morphChanged, setText, textsOf } from '../ui/morph'; +import { morphChanged, morphInto, setText, textOf, textsOf } from '../ui/morph'; import { reachableFromHome } from './devices'; +import { holdFoot } from './frame'; const desc = (text: string) => h('p', { class: 'desc' }, text); /** A share of a length, as a CSS percentage. */ @@ -266,7 +269,7 @@ export function accessAccordion(st: State, open = 1): Accordion { // No end date and no hours: nothing to open, the row just says so. { icon: glass('calendar'), title: _('Access until'), val: untilVal, valHide: !!p.expires && (left ?? 0) >= 0, body: untilBody }, ], - { open }, + { open, hold: holdFoot }, ); } @@ -280,13 +283,115 @@ export function accessSection(): HTMLElement { ); } +/** + * Markup to compare: each keyed value as the words it says (one still morphing, those it turns into), less the ids + * each glass icon makes up (the same icon twice is the same). + */ +function plain(el: Element, inner = false): string { + const c = el.cloneNode(true) as Element; + const keyed = el.querySelectorAll('[data-t]'); + c.querySelectorAll('[data-t]').forEach((k, i) => { + k.textContent = textOf(keyed[i]); + k.classList.remove('mt', 'mt-ib'); + }); + return (inner ? c.innerHTML : c.outerHTML).replace(/\bgl\d+/g, 'gl'); +} + +/** + * The rows on the page take the new rows' content in place, so what moves in + * them goes on (a row opening or folding, the calendar's days coming in, a + * value still morphing into the same words): keyed values in a head take their + * new words (they morph afterwards, morphChanged), a head swaps only the parts + * that changed (its click stays the row's own), and a body takes its new + * content (`refillBody`). Rows of another shape (an end date set or taken + * away) can't: null. Returns what came in whole. + */ +function refill(acc: HTMLElement, next: HTMLElement): Element[] | null { + const rows = [...acc.children] as HTMLElement[]; + const news = [...next.children] as HTMLElement[]; + if (rows.length !== news.length || rows.some((r, i) => r.classList.contains('still') !== news[i].classList.contains('still'))) + return null; + const fresh: Element[] = []; + rows.forEach((r, i) => { + const [head, body] = [...r.children] as HTMLElement[]; + const [nh, nb] = [...news[i].children] as HTMLElement[]; + for (const el of head.querySelectorAll('[data-t]')) { + const n = nh.querySelector(`[data-t="${el.dataset.t}"]`); + if (n && textOf(el) !== n.textContent) setText(el, n.textContent ?? ''); + } + if (head.children.length !== nh.children.length) head.replaceChildren(...nh.childNodes); + else + [...nh.children].forEach((y, k) => { + const x = head.children[k]; + if (plain(x) === plain(y)) return; + // The same box (the value that hides while the row is open) keeps its own fade and takes the new content. + if (x.tagName === y.tagName && x.className === y.className) x.replaceChildren(...y.childNodes); + else x.replaceWith(y); + }); + fresh.push(...refillBody(r, body, nb)); + }); + return fresh; +} + +/** Open bodies whose days are still coming in, with what each shows once they are in. */ +const waiting = new WeakMap(); + +/** + * A row's body takes the new one's content: shut, at once; open or still + * closing, where it stands (morphInto: a crossing piece keeps its old words as + * it fades) while the row glides to its new height. The calendar's days still + * coming in finish their cascade first: the body changes once they are in, to + * what the last repaint brought. Returns what came in whole. + */ +function refillBody(r: HTMLElement, body: HTMLElement, nb: HTMLElement): Element[] { + if (waiting.has(body)) { + waiting.set(body, nb); + return []; + } + if (plain(body, true) === plain(nb, true)) return []; + if (!r.classList.contains('open') && !r.classList.contains('closing')) { + body.replaceChildren(...nb.childNodes); + return []; + } + const days = [...body.querySelectorAll('.cal-g i')].flatMap((c) => c.getAnimations()); + if (days.length) { + waiting.set(body, nb); + void Promise.all(days.map((a) => a.finished.catch(() => undefined))).then(() => { + const n = waiting.get(body)!; + waiting.delete(body); + if (!r.isConnected) return; + const said = textsOf(body); + morphChanged(body, said, refillBody(r, body, n)); + }); + return []; + } + // Its days came in when it opened: what comes now is the change alone. + r.classList.remove('opened'); + const h0 = r.getBoundingClientRect().height; + const moving = r.getAnimations().length > 0; + const came = morphInto(body, [...nb.childNodes]); + // Opening or folding still: that glide heads for the new height instead. + if (moving) regrow(body); + else { + const h1 = r.getBoundingClientRect().height; + if (Math.abs(h1 - h0) > 0.5) + play(r, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); + } + return came; +} + let shown: Accordion | null = null; -/** The accordion for this state, the same row open as before. */ +/** The accordion for this state, the same row open as before: the rows on the page stay when they can (`refill`). */ export function fillAccess(section: HTMLElement, st: State) { + const slot = section.querySelector('.acc-slot') as HTMLElement; const acc = accessAccordion(st, shown ? shown.openIndex() : 1); // The values it showed: what changed morphs from it. const said = textsOf(section); - section.querySelector('.acc-slot')!.replaceChildren(acc.el); - if (shown) morphChanged(section, said); - shown = acc; + const had = !!shown; + const fresh = shown && slot.contains(shown.el) ? refill(shown.el, acc.el) : null; + if (!fresh) { + slot.replaceChildren(acc.el); + shown = acc; + } + if (had) morphChanged(section, said, fresh ?? []); } diff --git a/web/src/portal/page/devices.ts b/web/src/portal/page/devices.ts index 3229f91..95be24f 100644 --- a/web/src/portal/page/devices.ts +++ b/web/src/portal/page/devices.ts @@ -1,29 +1,54 @@ // "Your devices": a card per device (the one this page is open on first, then // by state), the card to add one, and the count. A repaint keeps the grid: -// cards that stay glide to their new places, a new one pops in, one that just +// cards that stay glide to their new places and heights (Connect turned into +// the week crosses where it stands), a new one pops in, one that just // connected rings green for a moment. What a card's buttons start lives in // flows/. -import type { Device, Person } from '../../shared/types'; +import type { Device, LinkState, Person } from '../../shared/types'; import { addDays, ago, byDeviceState, parseDay } from '../../shared/format'; import { fmt, locale, num, plural } from '../../shared/i18n'; import { h, ic } from '../dom'; -import { BOUNCY, EASE_IN, EASE_OUT, SMOOTH, play } from '../motion'; +import { BOUNCY, EASE_IN, EASE_OUT, SMOOTH, calm, play } from '../motion'; import { now, today, type RepaintOpts, type State } from '../state'; import { bars, sumDays, upDown } from '../ui/bars'; import { copy } from '../ui/feedback'; import { glass } from '../ui/glass'; import { openMenu, type MenuItem } from '../ui/menu'; -import { morphChanged, morphText, setText, textsOf } from '../ui/morph'; +import { appear, fadeAway, look, morphChanged, morphText, setText, textsOf, type Look } from '../ui/morph'; import { startAdd } from '../flows/add'; -import { reconnect, removeDevice, rename } from '../flows/device-actions'; +import { reconnect, removeDevice } from '../flows/device-actions'; +import { renameOnCard } from '../flows/rename'; import { openSetup } from '../flows/setup-view'; /** The home network can open connections to it: home access, active, and the device on. */ export const reachableFromHome = (p: Person, d: Device) => p.access !== 'internet' && p.state === 'active' && !d.disabled; -/** The status line: its class and words (short, on one line; the full wording shows on hover). */ -function statusOf(d: Device, p: Person): [string, string] { +/** A link failing in a named way (the router's watcher held it 3 minutes): the card's line, and why. */ +function linkWords(s: LinkState): [string, string] { + switch (s) { + case 'trying': + return [ + _('Can’t finish connecting'), + _('It reaches the router, but the connection never completes. The network may be blocking it.'), + ]; + case 'dropped': + return [_('Connected, but no data'), _('The router can’t use what it sends: reconnect it.')]; + case 'shared': + return [ + _('On two devices at once'), + _('This connection is on two devices and they push each other out. Add the other one as its own device.'), + ]; + case 'unstable': + return [_('Connection keeps dropping'), _('It connects, but the connection breaks every few minutes. Another network may help.')]; + } +} + +/** + * The status line: its class and words (short, on one line; the full wording shows on hover), and for a link + * failing in a named way, why (its hover). + */ +function statusOf(d: Device, p: Person): [string, string, string?] { if (d.disabled) return ['', _('Disabled')]; // The Reconnect button under it says what to do. if (d.config_stale && d.handshake) return ['warn-t', _('Settings changed')]; @@ -31,11 +56,38 @@ function statusOf(d: Device, p: Person): [string, string] { // "connected", so say here why nothing works. if (d.online && p.state === 'quota') return ['warn-t', _('Connected, no data left')]; if (d.online && p.state === 'hours') return ['warn-t', _('Connected, outside your hours')]; + if (d.link) return ['warn-t', ...linkWords(d.link.state)]; if (d.online) return ['ok-t', _('Connected')]; if (!d.handshake) return ['warn-t', _('Not set up yet')]; return ['', fmt(_('Last connected %s'), ago(d.handshake, now()))]; } +/** + * The card's name. One the person may change is a button too: a click, Return or Space edits it in place + * (flows/rename.ts), as Rename in the ⋯ menu does. + */ +function nameOf(d: Device, editable: boolean): HTMLElement { + const el = h('span', { class: 'dev-name', 'data-t': `${d.id}:name` }, d.name); + if (!editable) return el; + el.classList.add('can-edit'); + el.setAttribute('role', 'button'); + el.tabIndex = 0; + el.setAttribute('aria-label', fmt(_('Rename %s'), d.name)); + el.addEventListener('click', () => renameHere(d)); + el.addEventListener('keydown', (e) => { + if (e.key !== 'Enter' && e.key !== ' ') return; + e.preventDefault(); + renameHere(d); + }); + return el; +} + +/** Edit `d`'s name on its card, wherever the card is now (ui: flows/rename.ts). */ +function renameHere(d: Device) { + const card = document.querySelector(`.dev[data-id="${CSS.escape(d.id)}"]`); + if (card) renameOnCard(d, card); +} + function menuItems(d: Device, st: State): (MenuItem | null)[] { return [ // How devices at home reach it: only where the router actually lets them through. @@ -50,7 +102,7 @@ function menuItems(d: Device, st: State): (MenuItem | null)[] { ...(d.disabled ? [] : [ - { label: _('Rename'), icon: 'edit', run: () => rename(d) }, + { label: _('Rename'), icon: 'edit', run: () => renameHere(d) }, { label: _('Reconnect'), icon: 'refresh', tone: 'warn' as const, run: () => reconnect(d) }, { label: _('Remove'), icon: 'trash', tone: 'bad' as const, run: () => removeDevice(d) }, ]), @@ -91,16 +143,19 @@ function card(d: Device, st: State): HTMLElement { const locked = !!st.locked; // The device this page was opened from (through the tunnel): it is connected, so say which one it is instead. const here = st.here === d.id; - const [cls, words] = here ? ['here-t', _('This device')] : statusOf(d, p); + const [cls, words, why] = here ? ['here-t', _('This device')] : statusOf(d, p); const setUp = !d.handshake && !d.disabled; const stale = d.config_stale && !setUp && !locked && !d.disabled; - // On one line; the exact time, or the whole wording, on hover. + // Connected, but nothing it sends gets through (an old configuration): new keys fix it, as changed settings. + const renew = (d.config_stale || d.link?.state === 'dropped') && !setUp && !locked && !d.disabled; + // On one line; why, the exact time, or the whole wording, on hover. const title = - !here && d.handshake && !d.online && !d.disabled && !d.config_stale + why ?? + (!here && d.handshake && !d.online && !d.disabled && !d.config_stale ? new Date(d.handshake * 1000).toLocaleString(locale()) : stale ? _('Settings changed, update needed') - : words; + : words); const items = menuItems(d, st); const more = locked || !items.length @@ -127,13 +182,17 @@ function card(d: Device, st: State): HTMLElement { h( 'div', { class: 'dev-id' }, - h('span', { class: 'dev-name', 'data-t': `${d.id}:name` }, d.name), + nameOf(d, !d.disabled && !locked), h('span', { class: `dev-stat ${cls}`, title, 'data-t': `${d.id}:stat` }, words), + // Why a link fails: a pointer reads it on hover, a screen reader right after the status (a touch screen + // has neither; the card keeps its one line). + why ? h('span', { class: 'offscreen' }, why) : null, ), more, ), - // Stopped by the admin: a device never set up has nothing to show. Its settings changed: Reconnect in - // place of its week (new keys, then set it up again), as a device not set up yet shows Connect. + // Stopped by the admin: a device never set up has nothing to show. Its settings changed, or no data gets + // through: Reconnect in place of its week (new keys, then set it up again), as a device not set up yet shows + // Connect. setUp && locked ? null : setUp @@ -148,7 +207,7 @@ function card(d: Device, st: State): HTMLElement { ic('qr'), h('span', {}, _('Connect')), ) - : stale + : renew ? h( 'button', { @@ -214,13 +273,77 @@ function snapOnJump(grid: HTMLElement) { }).observe(grid); } -/** The cards for this state, moving from where they were. */ -export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}) { +/** The green ring of a device that just connected (its animation's id, to find it again on a repaint). */ +const RING = 'ring'; + +/** What a card ends in (Connect, Reconnect or its week), and which of them (a button by its words). */ +const footOf = (c: Element) => c.querySelector(':scope > .dev-use, :scope > .setup-btn'); +const footKind = (f: HTMLElement | null) => (!f ? '' : f.classList.contains('dev-use') ? 'use' : (f.textContent ?? '')); + +/** A card as it stood before a repaint. */ +interface CardWas { + el: HTMLElement; + at: DOMRect; + shows: Look; + /** What it ended in, which kind, where it stood and how it showed: one of another kind crosses. */ + foot: { el: HTMLElement; kind: string; at: DOMRect; shows: Look } | null; + /** How far its green ring had faded (ms), while it still shows. */ + ring: number | null; +} + +/** "Your devices" as it stands: each card, and where the note under them stood (if it showed). */ +export interface DevicesWas { + cards: Map; + note: DOMRect | null; +} + +/** "Your devices" as it stands: read before anything above it changes (the notice; on a phone, "Your access"). */ +export function devicesNow(section: HTMLElement): DevicesWas { + const note = section.querySelector('.limit') as HTMLElement; + // Not a card still fading out where it stood (laid over the grid, hidden from screen readers). + const cards = [...section.querySelectorAll('.dgrid > [data-id]:not([aria-hidden])')].map((c): [string, CardWas] => { + const f = footOf(c); + const ring = c.getAnimations().find((a) => a.id === RING); + return [ + c.dataset.id!, + { + el: c, + at: c.getBoundingClientRect(), + shows: look(c), + foot: f && { el: f, kind: footKind(f), at: f.getBoundingClientRect(), shows: look(f) }, + ring: ring ? Number(ring.currentTime) : null, + }, + ]; + }); + return { cards: new Map(cards), note: note.hidden ? null : note.getBoundingClientRect() }; +} + +/** + * The green ring of a device that just connected fades into the card's own (this device's blue one, or none); + * `from`: a ring already fading on the card a repaint rebuilt goes on from there. + */ +function ring(c: HTMLElement, from: number) { + const own = getComputedStyle(c).boxShadow; + c.animate([{ boxShadow: 'inset 0 0 0 1.5px var(--ok)' }, { boxShadow: own === 'none' ? 'inset 0 0 0 1.5px transparent' : own }], { + duration: 1800, + easing: 'ease-out', + id: RING, + }).currentTime = from; +} + +/** + * The cards for this state, moving from where they were (`was`: read before + * what stands above them changed). A card that changes height (another foot, a + * row that no longer stretches it) glides to it; a foot of another kind + * crosses, the old one fading where it stood as the new one blurs in; a card + * no longer there (Add device once the last slot is taken) fades where it + * stood. + */ +export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}, was = devicesNow(section)) { const p = st.person; const grid = section.querySelector('.dgrid') as HTMLElement; // A repaint (not the first paint, which brings everything in): what newly shows comes in too. const repainting = grid.childElementCount > 0; - const first = new Map([...grid.querySelectorAll('[data-id]')].map((c) => [c.dataset.id, c.getBoundingClientRect()])); // What each card said (a name, its status, its week): what changed morphs from it once the cards are in place. const said = textsOf(grid); // The device this page was opened from comes first. @@ -233,8 +356,27 @@ export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {} else if (st.can_add && !st.locked) cards.push(addCard()); grid.classList.toggle('empty', !p.devices.length); grid.replaceChildren(...cards); + const heights = cards.map((c) => c.getBoundingClientRect().height); + cards.forEach((c, i) => { + const w = was.cards.get(c.dataset.id!); + if (!w || c.dataset.id === o.pop) return; + const foot = footOf(c); + if ((w.foot?.kind ?? '') !== footKind(foot)) { + if (w.foot) fadeAway(w.foot.el, w.foot.at, c, w.at, w.foot.shows); + if (foot) appear(foot); + } + // What it holds is clipped to it on the way (a taller foot would hang out of it). + if (Math.abs(w.at.height - heights[i]) > 0.5) { + c.style.overflow = 'clip'; + play(c, [{ height: `${w.at.height}px` }, { height: `${heights[i]}px` }], { + duration: SMOOTH.duration, + easing: SMOOTH.easing, + }).onfinish = () => (c.style.overflow = ''); + } + }); + // Places once the heights set off: a card under one that grows rides along with it. for (const c of cards) { - const f = first.get(c.dataset.id); + const f = was.cards.get(c.dataset.id!)?.at; const l = c.getBoundingClientRect(); if (c.dataset.id === o.pop) play( @@ -268,12 +410,16 @@ export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {} fill: 'backwards', }, ); - if (c.dataset.id === o.flash) - c.animate([{ boxShadow: 'inset 0 0 0 1.5px var(--ok)' }, { boxShadow: 'inset 0 0 0 1.5px transparent' }], { - duration: 1800, - easing: 'ease-out', - }); + const r = c.dataset.id === o.flash ? 0 : was.cards.get(c.dataset.id!)?.ring; + if (r != null) ring(c, r); } + const ids = new Set(cards.map((c) => c.dataset.id)); + const g = grid.getBoundingClientRect(); + for (const [id, w] of was.cards) + if (!ids.has(id)) { + w.el.style.height = `${w.at.height}px`; + fadeAway(w.el, w.at, grid, g, w.shows); + } if (repainting) morphChanged(grid, said); const count = section.querySelector('.sec-head .aside') as HTMLElement; const n = fmt(_('%s of %s'), num(p.devices.length), num(p.device_limit)); @@ -282,38 +428,89 @@ export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {} // The admin may add devices past the limit. count.classList.toggle('warn-t', p.devices.length > p.device_limit); const limit = section.querySelector('.limit') as HTMLElement; - const was = limit.hidden; - const hide = st.can_add || !!st.locked; limit.textContent = plural( p.device_limit, 'You have reached your limit of %s device. Remove one to add another.', 'You have reached your limit of %s devices. Remove one to add another.', ); - limit.getAnimations().forEach((a) => a.cancel()); - // A slot freed: the note fades the way it came, then leaves the layout. - if (repainting && !was && hide) { - const a = play( + limitNote(limit, st.can_add || !!st.locked, repainting, was.note); +} + +/** + * The note that the limit is reached. It rises in under the cards when the + * last slot is taken; when one frees up it fades the way it came while its + * space folds away (on a phone it ends the page: a page scrolled to its foot + * then moves down with it instead of dropping), then leaves the layout. Each + * from where it stands, one turned back half-way included. + */ +function limitNote(limit: HTMLElement, hide: boolean, repainting: boolean, at: DOMRect | null) { + const cs = getComputedStyle(limit); + const stood = { + opacity: cs.opacity, + filter: cs.filter, + transform: cs.transform, + height: `${limit.offsetHeight}px`, + marginTop: cs.marginTop, + }; + const prior = limit.getAnimations(); + const shown = !limit.hidden; + if (repainting && hide && shown) { + const fade = play( limit, [ - { opacity: 1, filter: 'none' }, - { opacity: 0, filter: 'blur(4px)' }, + { opacity: stood.opacity, filter: stood.filter, transform: stood.transform }, + { opacity: 0, filter: 'blur(4px)', transform: stood.transform }, ], - { duration: 200, easing: EASE_IN, fill: 'forwards' }, + { duration: 200 * +stood.opacity, easing: EASE_IN, fill: 'forwards' }, ); - a.onfinish = () => { + // With less motion nothing folds: it fades, then is gone with its space. + const fold = calm() + ? null + : play( + limit, + [ + { height: stood.height, marginTop: stood.marginTop }, + { height: '0px', marginTop: '0px' }, + ], + { duration: SMOOTH.duration, easing: SMOOTH.easing, fill: 'forwards' }, + ); + prior.forEach((a) => a.cancel()); + (fold ?? fade).onfinish = () => { limit.hidden = true; - a.cancel(); + fade.cancel(); + fold?.cancel(); }; } else { + prior.forEach((a) => a.cancel()); limit.hidden = hide; - if (repainting && was && !hide) - play( - limit, - [ - { opacity: 0, transform: 'translateY(6px)', filter: 'blur(4px)' }, - { opacity: 1, transform: 'none', filter: 'none' }, - ], - { duration: 420, easing: EASE_OUT }, - ); } + if (!repainting || hide) return glideFrom(limit, at); + if (!shown) + play( + limit, + [ + { opacity: 0, transform: 'translateY(6px)', filter: 'blur(4px)' }, + { opacity: 1, transform: 'none', filter: 'none' }, + ], + { duration: 420, easing: EASE_OUT }, + ); + // Folding away when it was needed again: it opens back from where it stood. + else if (prior.length) + play( + limit, + [ + stood, + { opacity: 1, filter: 'none', transform: 'none', height: `${limit.offsetHeight}px`, marginTop: getComputedStyle(limit).marginTop }, + ], + { duration: SMOOTH.duration, easing: SMOOTH.easing }, + ); + glideFrom(limit, at); +} + +/** The note, shown before and still in the page, glides from where it stood as the cards do (one came in above it). */ +function glideFrom(limit: HTMLElement, at: DOMRect | null) { + if (!at || limit.hidden) return; + const dy = at.top - limit.getBoundingClientRect().top; + if (Math.abs(dy) > 0.5) + play(limit, [{ translate: `0 ${dy}px` }, { translate: '0 0' }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); } diff --git a/web/src/portal/page/frame.ts b/web/src/portal/page/frame.ts index 26f7b59..50d9205 100644 --- a/web/src/portal/page/frame.ts +++ b/web/src/portal/page/frame.ts @@ -2,9 +2,11 @@ // bottom edges (the top fade only once it scrolls, so the breadcrumb at rest // stays crisp), and opens with a breadcrumb: the Dawnline mark, the place (the // server's name) and the person, then the language and this page's code. The -// content goes in `body`. +// content goes in `body`, which holds its height while a fold near the page's +// foot takes the scroll down with it (`holdFoot`). import { h, ic, markup } from '../dom'; +import { EASE_OUT, SOFT, play } from '../motion'; import { placeName, state } from '../state'; import { showPageCode } from '../flows/page-code'; import { openMenu } from '../ui/menu'; @@ -35,6 +37,34 @@ export function frame(app: HTMLElement): HTMLElement { return bodyEl; } +/** + * The page keeps its height while something in it takes a shorter shape (an + * access row folding): with no scroll anchoring (base.css), a page scrolled + * near its foot would drop to its new end on the frame that shape is measured. + * Held at what the scroll needs, it lets go once the new shape is known (what + * this returns), on an ease that never overshoots, so the scroll follows the + * fold down frame by frame and stops at the new foot. Still tall enough, it + * lets go at once. + */ +export function holdFoot(): () => void { + const body = bodyEl; + if (!body) return () => {}; + // Read as it stands (a hold still letting go included), then taken over. + const r = body.getBoundingClientRect(); + // Tall enough for the page's foot to stay at the bottom of the screen: the scroll and the screen, less what is + // above the body and under it. + const need = innerHeight - r.top - (document.documentElement.scrollHeight - scrollY - r.bottom); + body.getAnimations().forEach((a) => a.cancel()); + body.style.minHeight = `${need}px`; + return () => { + const last = body.lastElementChild; + const end = last ? last.getBoundingClientRect().bottom - body.getBoundingClientRect().top : 0; + body.style.minHeight = ''; + if (end < need - 0.5) + play(body, [{ minHeight: `${need}px` }, { minHeight: `${end}px` }], { duration: SOFT.duration, easing: EASE_OUT }); + }; +} + /** One card in place of the page (the link gone, nothing loaded, access paused): it and the breadcrumb sit in the middle of the screen. */ export function single(on: boolean) { pageEl?.classList.toggle('single', on); diff --git a/web/src/portal/page/notices.ts b/web/src/portal/page/notices.ts index d304c5f..32ec370 100644 --- a/web/src/portal/page/notices.ts +++ b/web/src/portal/page/notices.ts @@ -1,14 +1,18 @@ // What stops the person's devices, said once at the top of the page: paused, // ended, out of data, outside the hours, the server off or missing, or access -// ending soon. A notice wears its tone (orange or red) in its tint. +// ending soon. A notice wears its tone (orange or red) in its tint. On a +// repaint it comes, goes or changes in place while its slot glides to its new +// height, so the page under it moves instead of jumping. import type { Person } from '../../shared/types'; import { daysLeft, date, endsIn, endsSoon } from '../../shared/format'; import { fmt } from '../../shared/i18n'; -import { h } from '../dom'; +import { h, put } from '../dom'; +import { SMOOTH, play } from '../motion'; import { clockOf, hoursFor } from '../days'; import { state, today } from '../state'; import { glass } from '../ui/glass'; +import { appear, morphInto } from '../ui/morph'; export type Tone = 'warn' | 'bad'; @@ -55,3 +59,23 @@ export function pageNotice(p: Person): HTMLElement | null { ? notice('warn', 'calendar', fmt(_('Access %s'), endsIn(left as number)), fmt(_('On %s.'), date(p.expires))) : null; } + +/** + * The page's notice in its slot. On a repaint one that comes blurs in, one that + * goes fades where it stood, one that changes morphs in place (ui/morph.ts), + * and the slot glides from its height on screen to the new one (the slot holds + * the notice's margin and clips it on the way: page.css). + */ +export function fillNotice(slot: HTMLElement, p: Person, repainting: boolean) { + const n = pageNotice(p); + if (!repainting) return put(slot, n); + const h0 = slot.getBoundingClientRect().height; + // A notice that was there (one fading out lies over the slot, hidden from screen readers). + const had = !!slot.querySelector(':scope > .notice:not([aria-hidden])'); + slot.getAnimations().forEach((a) => a.cancel()); + morphInto(slot, n); + if (n && !had) appear(n); + const h1 = slot.getBoundingClientRect().height; + if (Math.abs(h1 - h0) > 0.5) + play(slot, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); +} diff --git a/web/src/portal/setup.ts b/web/src/portal/setup.ts index 70c82e5..78f3728 100644 --- a/web/src/portal/setup.ts +++ b/web/src/portal/setup.ts @@ -26,12 +26,18 @@ export function platformOf(ua: string, touchPoints = 0): Platform { /** A browser inside another app (Telegram, Instagram…): vpn:// and the share sheet do not work there. */ export const inWebview = (ua: string): boolean => /Telegram|FBAN|FBAV|Instagram|VKClient|Line\//i.test(ua); -/** Is the page open on the device being set up? A router never is; an unknown platform never counts. */ -export function sameDevice(kind: Kind, platform: Platform): boolean { +/** + * Is the page open on the device being set up? A router never is; an unknown + * platform never counts. Something else (a TV, a box, a NAS) counts when the + * page came from its own set-up link (`here`: it is open there, an Android TV + * included) or on a computer's system: added from a phone, it is not the + * phone in hand. + */ +export function sameDevice(kind: Kind, platform: Platform, here = false): boolean { if (kind === 'router' || platform === 'unknown') return false; if (kind === 'phone' || kind === 'tablet') return platform === 'ios' || platform === 'android'; if (kind === 'computer') return platform === 'windows' || platform === 'mac' || platform === 'linux'; - return true; + return here || platform === 'windows' || platform === 'mac' || platform === 'linux'; } export interface AppChoice { diff --git a/web/src/portal/state.ts b/web/src/portal/state.ts index 326f81c..eb99dfd 100644 --- a/web/src/portal/state.ts +++ b/web/src/portal/state.ts @@ -11,7 +11,8 @@ export interface State { person: Person; /** device_mesh: devices with home access reach each other through the tunnel. */ /** awg_disguise: false = plain WireGuard, any WireGuard app connects. */ - server: { name?: string; endpoint: string; device_mesh?: boolean; awg_disguise?: boolean; preset?: Preset }; + /** home: the home networks a device with LAN Bypass still sends into the tunnel (home and internet access). */ + server: { name?: string; endpoint: string; device_mesh?: boolean; awg_disguise?: boolean; preset?: Preset; home?: string[] }; /** The device this page was opened from (through the tunnel), if any. */ here?: string | null; can_add: boolean; diff --git a/web/src/portal/styles/accordion.css b/web/src/portal/styles/accordion.css index f554d64..958ad39 100644 --- a/web/src/portal/styles/accordion.css +++ b/web/src/portal/styles/accordion.css @@ -84,7 +84,7 @@ align-items: center; gap: 8px; } -.acc-row.open .acc-val.hide-open { +.acc-row.open > .acc-head > .acc-val.hide-open { opacity: 0; filter: blur(4px); transform: translateX(8px); @@ -97,15 +97,17 @@ transform: rotate(90deg); transition: transform var(--spring-soft-dur, 470ms) var(--spring-soft, ease); } -.acc-row.open .acc-chev { +/* Only the row's own head and body: a row inside an open row keeps its own state (the router's + "Configuration" inside "Set it up again"). */ +.acc-row.open > .acc-head > .acc-chev { transform: rotate(-90deg); } .acc-body { display: none; padding: 0 8px 16px 40px; } -.acc-row.open .acc-body, -.acc-row.closing .acc-body { +.acc-row.open > .acc-body, +.acc-row.closing > .acc-body { display: flex; flex-direction: column; gap: 12px; @@ -128,6 +130,33 @@ .acc.inset .seg { background: color-mix(in srgb, var(--knob) 65%, var(--field)); } +/* Steps inside an inset row ("Set it up again") sit on field: their badges step up as the picker + does, and one step more on hover. */ +.acc.inset .badge { + background: color-mix(in srgb, var(--knob) 65%, var(--field)); +} +.acc.inset .badge:hover { + background: var(--knob); +} +/* The router's file step inside an inset row: its card, its inset "Configuration" row and what + that row opens step up one the same way; its buttons one more, and one more again on hover. */ +.acc.inset .filecard, +.acc.inset .acc.inset .acc-row { + background: color-mix(in srgb, var(--knob) 65%, var(--field)); +} +.acc.inset .acc.inset .acc-row:not(.open):not(.still):hover { + background: var(--knob); +} +.acc.inset .filecard-ic, +.acc.inset .acc.inset .btn.soft { + background: color-mix(in srgb, var(--knob), var(--text) 6%); +} +.acc.inset .acc.inset .btn.soft:hover { + background: color-mix(in srgb, var(--knob), var(--text) 12%); +} +.acc.inset .acc.inset .conf { + background: var(--knob); +} @media (prefers-reduced-motion: reduce) { .acc-chev { diff --git a/web/src/portal/styles/base.css b/web/src/portal/styles/base.css index c2270a0..d742847 100644 --- a/web/src/portal/styles/base.css +++ b/web/src/portal/styles/base.css @@ -8,6 +8,10 @@ html { -webkit-text-size-adjust: 100%; /* The page keeps its width when a sheet locks the scroll: no sideways jump behind the scrim. */ scrollbar-gutter: stable; + /* No scroll anchoring: on a phone "Your access" shows above the devices but comes after them in the page + (main.ts), so the browser would hold "Your devices" still while an access row opens or folds, and pull a page + scrolled less than the fold to the very top. A row grows and folds in place; a repaint glides what moves. */ + overflow-anchor: none; } body { margin: 0; diff --git a/web/src/portal/styles/controls.css b/web/src/portal/styles/controls.css index 678312f..a42559f 100644 --- a/web/src/portal/styles/controls.css +++ b/web/src/portal/styles/controls.css @@ -1,6 +1,7 @@ /* The controls every part uses: round knobs, buttons (and their busy orb), the field with its - go button, the icon picker, the kinds with their ring, badges, hints and menu paths, the link row, - QR codes and the row that puts a code beside its words. */ + go button and its own caret and selection, the icon picker, the kinds with their ring, the option + row with its switch, badges, hints and menu paths, the link row, QR codes and the row that puts a + code beside its words. */ .knob { width: 32px; @@ -199,7 +200,7 @@ gap: 12px; padding: 0 4px 0 16px; overflow: hidden; - transition: box-shadow 200ms var(--ease-out); + transition: box-shadow var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease); } .field:focus-within { box-shadow: inset 0 0 0 1.5px color-mix(in srgb, var(--text) 16%, transparent); @@ -228,8 +229,8 @@ place-items: center; flex: none; transition: - background-color 200ms var(--ease-out), - color 200ms var(--ease-out), + background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease), + color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease), transform 200ms var(--ease-out); } .go .i { @@ -247,6 +248,142 @@ cursor: not-allowed; } +/* The field's own caret (ui/caret.ts): the input's is hidden, ours glides to where the next letter + goes. As macOS draws it (Sonoma, NSTextInsertionIndicator): the accent, a 2 px capsule the line's + height, on for 0.6 s and off for 0.6 s with a soft fade either way; solid while typing, blinking + again 0.5 s after the last key. */ +.field.own-caret { + position: relative; +} +.field.own-caret input { + caret-color: transparent; +} +.caret { + position: absolute; + left: 0; + top: 50%; + width: 2px; + height: 20px; + margin-top: -10px; + border-radius: 1px; + background: var(--accent); + pointer-events: none; + opacity: 0; + transition: opacity 100ms linear; + will-change: transform; +} +.caret.on { + opacity: 1; +} +.caret.on.blink { + animation: caret-blink 1.2s ease-in-out infinite; +} +@keyframes caret-blink { + 0%, + 38% { + opacity: 1; + } + 50%, + 88% { + opacity: 0; + } + 100% { + opacity: 1; + } +} +/* Where the caret measures the text: the input's font, out of sight. */ +.caret-mirror { + position: absolute; + left: -9999px; + top: 0; + visibility: hidden; + white-space: pre; +} +/* With a mouse or trackpad, an iOS-style selection: the native one is see-through (the text keeps + its colour) and ours is drawn under the text, an accent wash a little taller than the line with a + handle at each end (2 px, the knob on top at the start and under it at the end). They fade in as + a selection starts and out as it collapses. */ +.field.own-sel input { + position: relative; + z-index: 1; +} +.field.own-sel input::selection { + background: transparent; + color: var(--text); +} +.caret-sel { + position: absolute; + left: 0; + top: 50%; + height: 22px; + margin-top: -11px; + border-radius: 4px; + background: color-mix(in srgb, var(--accent) 26%, transparent); + pointer-events: none; + opacity: 0; + transition: opacity 140ms linear; +} +.caret-hd { + position: absolute; + z-index: 2; + left: 0; + top: 50%; + width: 2px; + height: 22px; + margin-top: -11px; + border-radius: 1px; + background: var(--accent); + pointer-events: none; + opacity: 0; + transition: opacity 140ms linear; +} +.caret-hd::after { + content: ''; + position: absolute; + left: 50%; + width: 9px; + height: 9px; + margin-left: -4.5px; + border-radius: 50%; + background: var(--accent); +} +.caret-hd.s::after { + top: -7px; +} +.caret-hd.e::after { + bottom: -7px; +} +.field.selecting .caret-sel, +.field.selecting .caret-hd { + opacity: 1; +} + +/* Words on their way to the router (ui/shimmer.ts): the input's own are hidden under a copy that dims and lets a + light band sweep across it, the band the words' colour over a muted base; the caret steps aside meanwhile. */ +.field.saving input { + color: transparent; +} +.field.saving .caret { + opacity: 0 !important; + animation: none !important; +} +.shim-clip { + position: absolute; + z-index: 2; + overflow: hidden; + pointer-events: none; +} +.shim { + --shim-high: var(--text); + --shim-base: color-mix(in oklab, var(--text) 38%, var(--raised)); + position: absolute; + top: 0; + white-space: pre; + -webkit-background-clip: text; + background-clip: text; + color: transparent; +} + /* The icon picker (skiper21's tabs): icons only, the picked one widens and shows its name. */ .seg { position: relative; @@ -398,6 +535,98 @@ font-size: 11.5px; } } + +/* An option with a switch (Add a device's LAN Bypass): a field-coloured block on the raised sheet, + its glass icon grey while off, the whole row the switch. Hover tints it; it does not shrink. */ +.swrow { + width: 100%; + display: flex; + align-items: center; + gap: 12px; + padding: 12px 12px 12px 14px; + border-radius: 16px; + background: var(--field); + color: var(--text); + text-align: left; + user-select: none; + -webkit-user-select: none; + transition: background-color 200ms; +} +.swrow:hover { + background: color-mix(in srgb, var(--field), var(--knob) 50%); +} +.kinds + .swrow { + margin: 16px 0 12px; +} +.swrow .gi { + width: 28px; + height: 28px; + flex: none; + transition: + filter var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease), + opacity var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease); +} +.swrow:not(.on) .gi { + filter: grayscale(1); + opacity: 0.55; +} +.sw-t { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 1px; +} +.sw-t b { + font-size: 15px; + line-height: 22px; + font-weight: 500; + letter-spacing: -0.015em; +} +.sw-sub { + font-size: 13px; + line-height: 18px; + color: var(--text-2); +} +/* The switch: a knob-coloured track on the field, the accent when on. Held down, the knob reaches + halfway toward where it goes (as iOS switches do: off it stretches to the right, on to the left); + let go and it finishes the move. */ +.sw { + position: relative; + flex: none; + width: 44px; + height: 26px; + border-radius: 999px; + background: var(--knob); + transition: background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease); +} +.sw::after { + content: ''; + position: absolute; + top: 3px; + left: 3px; + width: 20px; + height: 20px; + border-radius: 10px; + background: var(--text-2); + transition: + transform var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease), + width var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease), + background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease); +} +.swrow.on .sw { + background: var(--accent); +} +.swrow.on .sw::after { + transform: translateX(18px); + background: var(--accent-ink); +} +.swrow:active .sw::after { + width: 27px; +} +.swrow.on:active .sw::after { + transform: translateX(11px); +} .or { display: flex; align-items: center; @@ -499,6 +728,11 @@ line-height: 18px; color: var(--text-2); } +/* A hint that says what is wrong (under a name field): red, over the hint's own grey (this file comes after + base.css's .bad-t). */ +.hint.bad-t { + color: var(--bad); +} .hint a, .hint button { color: var(--accent); @@ -595,7 +829,8 @@ width: 100%; height: 100%; } -/* A code swapping for another: the old one lies over the new one while it fades. */ +/* A code swapping for another: the old one lies over the new one while it fades, and one turned back to while it + fades up again where it lies. */ .qrbox > svg.old { position: absolute; inset: 0; @@ -657,4 +892,8 @@ opacity: 1; filter: none; } + /* The caret stands still: a blink is motion the visitor asked to be spared. */ + .caret.on.blink { + animation: none; + } } diff --git a/web/src/portal/styles/devices.css b/web/src/portal/styles/devices.css index 1ebf71c..d8f4603 100644 --- a/web/src/portal/styles/devices.css +++ b/web/src/portal/styles/devices.css @@ -72,6 +72,46 @@ .dev-stat.here-t { color: var(--accent); } +/* Why a name it was given won't do (flows/rename.ts). */ +.dev-stat.bad-t { + color: var(--bad); +} + +/* A name the person may change (flows/rename.ts): it hugs its words, a faint wash under the pointer says it can + be clicked; editing, it gives way to its own input in the same font and place, with nothing around it but the + field's caret and selection. */ +.dev-name.can-edit { + align-self: flex-start; + max-width: calc(100% + 12px); + margin: 0 -6px; + padding: 0 6px; + border-radius: 8px; + cursor: text; + outline: none; + transition: background-color 150ms var(--ease-out); +} +.dev-name.can-edit:hover { + background: color-mix(in srgb, var(--raised), var(--text) 6%); +} +/* Not when an edit gave focus back to it (flows/rename.ts): only reached with Tab. */ +.dev-name.can-edit:focus-visible:not(.quiet) { + box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 60%, transparent); +} +.field.inline, +.field.inline:focus-within { + height: 30px; + margin: -4px -6px; + padding: 0 6px; + gap: 0; + border-radius: 8px; + background: none; + box-shadow: none; + overflow: visible; +} +.field.inline input { + font: 500 16px/22px var(--font); + letter-spacing: -0.02em; +} .dev-use { margin-top: auto; background: var(--field); diff --git a/web/src/portal/styles/page.css b/web/src/portal/styles/page.css index a895b00..7d2be87 100644 --- a/web/src/portal/styles/page.css +++ b/web/src/portal/styles/page.css @@ -176,6 +176,12 @@ body.scrolled .edge-fade.top { line-height: 18px; } +/* The notice's slot holds its margin (flow-root) and clips it while its height glides, so a notice that comes or + goes is uncovered or folded away instead of hanging over what follows (page/notices.ts). */ +.notice-slot { + display: flow-root; + overflow-y: clip; +} /* A notice wears its tone: the fill tinted, the rim a little stronger. */ .notice { display: flex; diff --git a/web/src/portal/styles/setup.css b/web/src/portal/styles/setup.css index 79166a0..639cba9 100644 --- a/web/src/portal/styles/setup.css +++ b/web/src/portal/styles/setup.css @@ -1,6 +1,7 @@ /* The set-up sheet: the numbered steps, the way from the device to the server while the page waits - (and its line morphing into " connected"), the .conf for a router, and the scan line that - speaks for both phone systems. */ + (its line morphing into " connected", and how it looks when the device can't finish + connecting or connects with no data), the .conf for a router, and the scan line that speaks for + both phone systems. */ .setup { display: flex; @@ -21,6 +22,10 @@ .step + .step { margin-top: 20px; } +/* No data: the connection step alone in its row (flows/setup-view.ts regroup). */ +.step[hidden] + .step { + margin-top: 0; +} .step-n { width: 24px; height: 24px; @@ -108,8 +113,22 @@ } .way-glow { overflow: hidden; +} +/* Running and knocking are two loops that never stop: a state fades its own in and the other out where + each stands (a new animation-name would start over at 0%, off the track, in one frame). Connected, no + data and given up show neither. */ +.way-glow > span { + position: absolute; + inset: 0; transition: opacity 200ms var(--ease-out); } +.way.trying .run, +.way.done .run, +.way.nodata .run, +.way.stopped .run, +.way:not(.trying) .knock { + opacity: 0; +} .way-glow i { position: absolute; inset: 0; @@ -134,19 +153,26 @@ .way.done .way-fill { clip-path: inset(0); } -.way.done .way-glow, -.way.stopped .way-glow { - opacity: 0; -} .way.done .way-end { color: var(--ok); background: var(--ok-soft); } -.way.done .way-end.home { +.way.done .way-end.home, +.way.nodata .way-end.home { transition-delay: 600ms; } +/* The router's icon pops as the green gets there: it dips to .6 first (from rest to rest, on the way's + curve), so it starts from its own size, and springs back on BOUNCY's own curve and time from 600 ms, + with its colour. */ .way.done .way-end.home .i { - animation: way-pop 420ms var(--spring-bouncy, ease) 600ms backwards; + animation: + way-dip 120ms cubic-bezier(0.45, 0, 0.55, 1) 480ms, + way-pop var(--spring-bouncy-dur, 572ms) var(--spring-bouncy, ease) 600ms; +} +@keyframes way-dip { + to { + transform: scale(0.6); + } } @keyframes way-pop { from { @@ -191,6 +217,121 @@ color: var(--ok); } +/* Can't finish: the light runs almost to the router and falls back, a break flashes at the router, + and the router's end turns orange. */ +.way-glow .knock i { + background: linear-gradient(90deg, transparent 32%, var(--warn) 50%, transparent 68%); + animation: way-knock 1.8s cubic-bezier(0.45, 0, 0.55, 1) infinite; +} +@keyframes way-knock { + 0% { + transform: translateX(-70%); + } + 48% { + transform: translateX(34%); + } + 62% { + transform: translateX(26%); + opacity: 1; + } + 86%, + 100% { + transform: translateX(-70%); + opacity: 0; + } +} +/* The break flashes all along on the knock's beat (both start with the way) and fades in and out with + can't finish, from whatever it shows. */ +.way-break { + position: absolute; + right: -2px; + top: -5px; + width: 2px; + height: 18px; + opacity: 0; + transition: opacity 200ms var(--ease-out); +} +.way.trying .way-break { + opacity: 1; +} +.way-break i { + position: absolute; + inset: 0; + border-radius: 2px; + background: var(--warn); + transform: rotate(18deg); + animation: way-break 1.8s cubic-bezier(0.45, 0, 0.55, 1) infinite; +} +@keyframes way-break { + 0%, + 40% { + opacity: 0.25; + transform: rotate(18deg) scaleY(0.7); + } + 50% { + opacity: 1; + transform: rotate(18deg) scaleY(1.15); + } + 70%, + 100% { + opacity: 0.25; + transform: rotate(18deg) scaleY(0.7); + } +} +.way.trying .way-end.home { + color: var(--warn); + background: color-mix(in srgb, var(--warn) 14%, transparent); +} +.way.trying .way-text b, +.way.nodata .way-text b { + color: var(--warn); +} +/* No data: the way is green (it connects), but a packet falls through on its way to the router. */ +.way.nodata .way-fill { + clip-path: inset(0); +} +.way.nodata .way-end { + color: var(--ok); + background: var(--ok-soft); +} +.way-pkt { + position: absolute; + top: 50%; + left: 0; + width: 8px; + height: 8px; + margin-top: -4px; + border-radius: 50%; + background: var(--warn); + box-shadow: 0 0 10px color-mix(in srgb, var(--warn) 70%, transparent); + opacity: 0; + animation: way-drop 2.2s cubic-bezier(0.45, 0, 0.55, 1) infinite; +} +.way-pkt.b { + animation-delay: 1.1s; +} +@keyframes way-drop { + 0% { + left: 0; + opacity: 0; + transform: none; + } + 8% { + opacity: 1; + } + 46% { + left: 48%; + opacity: 1; + transform: none; + } + 66%, + 100% { + left: 54%; + opacity: 0; + transform: translateY(16px) scale(0.5); + } +} + /* The .conf for a router: a file card, and the configuration folded with its keys masked. */ .filecard { display: flex; @@ -315,4 +456,11 @@ .way.done .way-end.home .i { animation: none; } + /* Still frames: the break stands at the router, and no packet falls. */ + .way-break i { + animation: none; + } + .way-pkt { + display: none; + } } diff --git a/web/src/portal/styles/sheet.css b/web/src/portal/styles/sheet.css index a9c73a3..4b15796 100644 --- a/web/src/portal/styles/sheet.css +++ b/web/src/portal/styles/sheet.css @@ -1,5 +1,6 @@ -/* The sheet: a drawer floating at the bottom on every width, × and a view's own buttons pinned in its - corner, the views inside (head, line under it), and the question look (Remove, Reconnect). */ +/* The sheet: a drawer floating at the bottom of a phone, a dialog in the middle of a computer, × and a view's + own buttons pinned in its corner, the views inside (head, line under it), and the question look (Remove, + Reconnect). */ /* Closed, the sheet is out of the page (display, not visibility): each open computes its styles afresh. Hidden by visibility, Chromium could keep the inherited "hidden" on the views' box after a @@ -60,6 +61,8 @@ right: 22px; top: 22px; } +/* The viewport: as tall as its view, give or take the gap or overhang under the view while it glides to a new height + (ui/sheet.ts); what does not fit yet, and a view on its way out, is clipped. */ .vp { position: relative; overflow: hidden; @@ -116,9 +119,6 @@ max-width: 32ch; text-wrap: balance; } -.kinds-note { - margin: 14px 2px 16px; -} .view > .hint.bad-t { margin-top: 8px; } diff --git a/web/src/portal/ui/accordion.ts b/web/src/portal/ui/accordion.ts index a11a7f0..337b02c 100644 --- a/web/src/portal/ui/accordion.ts +++ b/web/src/portal/ui/accordion.ts @@ -3,8 +3,12 @@ // and its own corners. One row open at a time. A row with nothing to open is a // plain head: no chevron, no click. Inside the sheet it tells the sheet first, // so a code that comes into view gets its width. A row the person opens is -// `.opened` until it closes: what enters inside it (the calendar's days) keys on -// that, so a repaint that rebuilds the row open doesn't play it again. +// `.opened` until it has shut: what enters inside it (the calendar's days) keys +// on that, so a repaint that rebuilds the row open doesn't play it again, and a +// row opened again before it has shut carries on. A click mid-way (a double +// click) turns every row and body back from where it stands, and a row around +// them glides on with them (`regrow`, which the set-up sheet also uses when a +// pick changes a row still opening); the sheet follows its view by itself. import { h, ic } from '../dom'; import { EASE_IN, SOFT, play } from '../motion'; @@ -41,9 +45,79 @@ const PROPS = [ 'borderBottomRightRadius', ] as const; +/** A body not showing (display: none) stands where an opening one starts. */ +const HIDDEN: Keyframe = { opacity: 0, filter: 'blur(2px)' }; + +/** A body's new fade takes over from the one under way, which stops once the new one is in place. */ +function fade(body: HTMLElement, frames: Keyframe[], o: KeyframeAnimationOptions) { + const old = body.getAnimations(); + play(body, frames, o); + old.forEach((a) => a.cancel()); +} + +/** What a keyframe holds besides the properties it animates. */ +const META = new Set(['offset', 'computedOffset', 'easing', 'composite']); +const kebab = (p: string) => p.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`); + +/** + * Content changed under a glide still heading for a height it measured before + * (a row opening, a fold coming back): each element from `from` up whose + * height glides to what its content gives it carries on from where it stands + * to what its content gives it now, on its own curve, so it neither clips what + * grew nor jumps when the glide ends. A row closing (its height is its head's, + * not its content's) or a fold shutting keeps its end. Called with what changed + * in its end shape, before that moves. The heights are taken at the sheet's end + * width (a dense code widening it). + */ +export function regrow(...from: (Element | null | undefined)[]) { + const runs: { el: HTMLElement; a: Animation; t: CSSNumberish | null; cur: Keyframe; to: Keyframe }[] = []; + const widths: { a: Animation; t: CSSNumberish | null }[] = []; + const seen = new Set(); + for (const start of from) + for (let el: Element | null | undefined = start; el && !seen.has(el); el = el.parentElement) { + seen.add(el); + if (!(el instanceof HTMLElement) || el.classList.contains('closing')) continue; + for (const a of el.getAnimations()) { + const ks = a.playState === 'running' && a.effect instanceof KeyframeEffect ? a.effect.getKeyframes() : []; + const end = ks[ks.length - 1]; + if (end && ('width' in end || 'maxWidth' in end)) widths.push({ a, t: a.currentTime }); + if (!end?.height || end.height === '0px') continue; + const cs = getComputedStyle(el); + const cur: Keyframe = {}; + const to: Keyframe = {}; + for (const p of Object.keys(end)) + if (!META.has(p)) { + cur[p] = cs.getPropertyValue(kebab(p)); + to[p] = end[p]; + } + runs.push({ el, a, t: a.currentTime, cur, to }); + } + } + if (!runs.length) return; + // Measured with every glide lifted, the widths too; those not aimed anew go on from where they were. + [...runs, ...widths].forEach((r) => r.a.cancel()); + const ends = runs.map((r) => getComputedStyle(r.el).height); + for (const w of widths) { + w.a.play(); + w.a.currentTime = w.t; + } + runs.forEach((r, i) => { + r.a.play(); + // Its content gives it the height it was heading for: it carries on as it was. + if (Math.abs(parseFloat(ends[i]) - parseFloat(String(r.to.height))) < 0.5) r.a.currentTime = r.t; + else (r.a.effect as KeyframeEffect).setKeyframes([r.cur, { ...r.to, height: ends[i] }]); + }); +} + export function accordion( items: AccItem[], - o: { inset?: boolean; open?: number; onToggle?: (i: number, open: boolean, instant: boolean) => void } = {}, + o: { + inset?: boolean; + open?: number; + onToggle?: (i: number, open: boolean, instant: boolean) => void; + /** On the page: holds its height as a click reshapes the rows; what it returns lets go once their new shape is measured. */ + hold?: () => () => void; + } = {}, ): Accordion { const acc = h('div', { class: `acc${o.inset ? ' inset' : ''}` }); const rows = items.map((it, i) => { @@ -87,43 +161,57 @@ export function accordion( }; const aria = () => rows.forEach((x) => x.querySelector('button.acc-head')?.setAttribute('aria-expanded', String(x.classList.contains('open')))); + /** A row shows its body while open and while it closes (`.closing`). */ + const shows = (x: HTMLElement) => x.classList.contains('open') || x.classList.contains('closing'); + /** Where a body's fade stands now, mid-fade included. */ + const faded = (x: HTMLElement): Keyframe => { + if (!shows(x)) return HIDDEN; + const cs = getComputedStyle(bodyOf(x)); + return { opacity: cs.opacity, filter: cs.filter === 'none' ? 'blur(0px)' : cs.filter }; + }; function toggle(r: HTMLElement) { const before = rows.map(read); + const fades = rows.map(faded); + const release = o.hold?.(); rows.forEach((x) => x.getAnimations().forEach((a) => a.cancel())); - rows.forEach((x) => - bodyOf(x) - .getAnimations() - .forEach((a) => a.cancel()), - ); const willOpen = !r.classList.contains('open'); - const closing = rows.filter((x) => x.classList.contains('open') && (x === r || willOpen)); + // Every row showing its body shuts, still closing from a click before included, but the one that opens. + const closing = rows.filter((x) => shows(x) && !(x === r && willOpen)); rows.forEach((x) => { x.classList.remove('closing'); - if (x !== r) x.classList.remove('open', 'opened'); + if (x !== r) x.classList.remove('open'); }); r.classList.toggle('open', willOpen); - r.classList.toggle('opened', willOpen); + if (willOpen) r.classList.add('opened'); corners(); const plan = planWidth(); + const after = rows.map(read); + release?.(); + // The row this accordion sits in glides on to its new height with them (the sheet follows its view by itself). + regrow(acc.parentElement); rows.forEach((x, i) => { - const after = read(x); - if (!PROPS.some((p) => before[i][p] !== after[p])) return; + // Shut: what enters inside it plays again the next time it opens. + const shut = () => { + x.classList.remove('closing'); + if (!x.classList.contains('open')) x.classList.remove('opened'); + }; + if (!PROPS.some((p) => before[i][p] !== after[i][p])) return shut(); if (closing.includes(x)) x.classList.add('closing'); - play(x, [before[i], after], { duration: SOFT.duration, easing: SOFT.easing }).onfinish = () => x.classList.remove('closing'); + play(x, [before[i], after[i]], { duration: SOFT.duration, easing: SOFT.easing }).onfinish = shut; }); - closing.forEach((x) => - play(bodyOf(x), [{ opacity: 1 }, { opacity: 0, filter: 'blur(2px)' }], { duration: 160, easing: EASE_IN, fill: 'forwards' }), - ); - if (willOpen) - play( - bodyOf(r), - [ - { opacity: 0, filter: 'blur(2px)' }, - { opacity: 1, filter: 'blur(0px)' }, - ], - { duration: 300, easing: 'cubic-bezier(0,0,.58,1)' }, - ); + // Each body fades on from where it stands (a double click turns it back), over what is left of its way. + closing.forEach((x) => { + const f = fades[rows.indexOf(x)]; + fade(bodyOf(x), [f, { opacity: 0, filter: 'blur(2px)' }], { duration: 160 * Number(f.opacity), easing: EASE_IN, fill: 'forwards' }); + }); + if (willOpen) { + const f = fades[rows.indexOf(r)]; + fade(bodyOf(r), [f, { opacity: 1, filter: 'blur(0px)' }], { + duration: 300 * (1 - Number(f.opacity)), + easing: 'cubic-bezier(0,0,.58,1)', + }); + } startWidth(plan); aria(); o.onToggle?.(rows.indexOf(r), willOpen, false); @@ -134,7 +222,14 @@ export function accordion( el: acc, openIndex: () => rows.findIndex((x) => x.classList.contains('open')), setOpen(i) { - rows.forEach((x, k) => x.classList.toggle('open', k === i && !x.classList.contains('still'))); + rows.forEach((x, k) => { + // Without motion: whatever was under way stops where it was going. + [x, bodyOf(x)].forEach((e) => e.getAnimations().forEach((a) => a.cancel())); + const open = k === i && !x.classList.contains('still'); + x.classList.toggle('open', open); + x.classList.remove('closing'); + if (!open) x.classList.remove('opened'); + }); corners(); aria(); rows.forEach((x, k) => o.onToggle?.(k, x.classList.contains('open'), true)); diff --git a/web/src/portal/ui/bad-line.ts b/web/src/portal/ui/bad-line.ts new file mode 100644 index 0000000..e4113ae --- /dev/null +++ b/web/src/portal/ui/bad-line.ts @@ -0,0 +1,69 @@ +// The red line under a name field (Add a device, Rename): why the name is refused, the router's word or the +// field's own as it is typed (shared/name-guard.ts). It comes and goes without the sheet snapping: in, it rises in +// as the sheet glides open; out, it blurs away first, then the sheet glides shut. Either way it turns back from +// where it stands on screen. A view already swapped out (the answer came late) changes alone: the sheet's height is +// the new view's. Another reason while it shows: its words change in place. + +import { h } from '../dom'; +import { EASE_IN, EASE_OUT, play } from '../motion'; +import { morphText, setText, textOf } from './morph'; +import { glide, showing } from './sheet'; + +/** Away and shown. */ +const GONE: Keyframe = { opacity: 0, transform: 'translateY(-4px)', filter: 'blur(4px)' }; +const SHOWN: Keyframe = { opacity: 1, transform: 'none', filter: 'none' }; + +export interface BadLine { + el: HTMLElement; + say: (msg: string) => void; + unsay: () => void; +} + +export function badLine(): BadLine { + const err = h('p', { class: 'hint bad-t', hidden: true }); + const reflow = (change: () => void) => (showing(err) ? glide(change) : change()); + let fade: Animation | null = null; + let hiding = 0; + const now = (): Keyframe => { + const s = getComputedStyle(err); + return { opacity: s.opacity, transform: s.transform, filter: s.filter }; + }; + // The new fade takes over from the old one once it is in place (nothing paints between). + const fadeTo = (from: Keyframe, to: Keyframe, o: KeyframeAnimationOptions) => { + const was = fade; + fade = play(err, [from, to], o); + was?.cancel(); + }; + const say = (msg: string) => { + if (err.hidden) { + reflow(() => { + setText(err, msg); + err.hidden = false; + }); + return fadeTo(GONE, SHOWN, { duration: 220, easing: EASE_OUT }); + } + // Already showing: its words change in place. On its way out, it comes back from where it stands as they do. + const from = hiding ? now() : null; + morphText(err, msg); + if (!from) return; + clearTimeout(hiding); + hiding = 0; + fadeTo(from, SHOWN, { duration: 220, easing: EASE_OUT }); + }; + const unsay = () => { + if (err.hidden || hiding) return; + const from = now(); + // A morph under way ends where it was going: its end would cancel the fade. + setText(err, textOf(err)); + fadeTo(from, GONE, { duration: 180, easing: EASE_IN, fill: 'forwards' }); + hiding = window.setTimeout(() => { + hiding = 0; + reflow(() => { + err.hidden = true; + fade?.cancel(); + fade = null; + }); + }, 170); + }; + return { el: err, say, unsay }; +} diff --git a/web/src/portal/ui/busy.ts b/web/src/portal/ui/busy.ts index a4677dc..83a2cf7 100644 --- a/web/src/portal/ui/busy.ts +++ b/web/src/portal/ui/busy.ts @@ -39,14 +39,18 @@ function hand(btn: HTMLElement, next: Animation[]) { } export function busyOn(btn: HTMLElement) { - btn.querySelector(':scope > .orb')?.remove(); const parts = content(btn); const from = parts.map(now); - const orb = h('span', { class: 'orb', 'aria-hidden': 'true' }, h('i'), h('i')); - btn.append(orb); + // An orb still on its way out (pressed again right after an answer) turns back from where it stands, at once. + const was = btn.querySelector(':scope > .orb'); + const orb = was ?? h('span', { class: 'orb', 'aria-hidden': 'true' }, h('i'), h('i')); + if (!was) btn.append(orb); btn.classList.add('busy'); btn.setAttribute('aria-busy', 'true'); - hand(btn, [...parts.map((p, i) => play(p, [from[i], GONE], OUT)), play(orb, [ORB_GONE, SHOWN], IN)]); + hand(btn, [ + ...parts.map((p, i) => play(p, [from[i], GONE], OUT)), + play(orb, [was ? now(was) : ORB_GONE, SHOWN], was ? { ...IN, delay: 0 } : IN), + ]); } export function busyOff(btn: HTMLElement) { diff --git a/web/src/portal/ui/caret.ts b/web/src/portal/ui/caret.ts new file mode 100644 index 0000000..c7ee583 --- /dev/null +++ b/web/src/portal/ui/caret.ts @@ -0,0 +1,270 @@ +// The name fields' own caret and, with a mouse or trackpad, their own selection +// (`smoothCaret` on a `.field`). The caret glides to where the next letter goes +// and blinks as macOS draws it; a selection is an accent wash with a handle at +// each end, as iOS draws it, growing out of the caret and fading back into it. +// The input stays the browser's own (typing, IME, its native selection, made +// see-through): this only draws over it. On a touch screen the system draws its +// own selection and handles, so ours stays off and the caret steps aside while +// one shows. The look is in styles/controls.css; like the rest of the page this +// writes styles through `el.style` only (the CSP drops style attributes). +// +// Places come from a hidden mirror with the input's own font: the width of the +// text up to a position, less how far the input has scrolled. The pure parts +// (`glideStep`, `places`) are what the tests run. + +import { h } from '../dom'; +import { calm } from '../motion'; + +/** One edge that glides: where it is, how fast it moves, where it goes. */ +export interface Glide { + x: number; + v: number; + t: number; +} + +/** The frame the glide is tuned to, in ms. */ +const FRAME = 16.67; + +/** + * Move a glide on by `frames` frames (after bencho.dev's one-time code, a softer pull: per frame + * v += (t − x)·0.12, v ·= 0.62, x += v; 90% of the way in ~134 ms, about 2% over, no stretch). + * At most 2.5 frames at once; after a long gap (a hidden tab) it is simply there. False once it + * rests, then exactly on its target. + */ +export function glideStep(g: Glide, frames: number): boolean { + if (frames > 15) { + g.x = g.t; + g.v = 0; + return false; + } + const dt = Math.min(2.5, Math.max(0, frames)); + g.v += (g.t - g.x) * 0.12 * dt; + g.v *= Math.pow(0.62, dt); + g.x += g.v * dt; + if (Math.abs(g.t - g.x) < 0.05 && Math.abs(g.v) < 0.05) { + g.x = g.t; + g.v = 0; + return false; + } + return true; +} + +/** What an input shows now, as `places` reads it. */ +export interface FieldText { + value: string; + /** The selection (equal: a caret), and which end the caret is at. */ + start: number; + end: number; + backward: boolean; + /** The input's box in the field: its left edge and width, and how far its text has scrolled. */ + left: number; + width: number; + scroll: number; +} + +/** Where the caret and a selection's ends go, in px from the field's left edge. */ +export interface Places { + caret: number; + start: number; + end: number; + /** A selection, not just a caret. */ + range: boolean; +} + +/** + * The places for `f`, with `measure` the width of a text in the input's font. A selection that + * runs past the input's edges (a long name, scrolled) stops at them: the wash never covers the + * go button. + */ +export function places(f: FieldText, measure: (text: string) => number): Places { + const x = (i: number) => Math.min(f.left + f.width, Math.max(f.left, f.left + measure(f.value.slice(0, i)) - f.scroll)); + const start = x(f.start); + const end = f.end === f.start ? start : x(f.end); + return { caret: f.backward ? start : end, start, end, range: f.start !== f.end }; +} + +/** The input's font, as the mirror needs it to measure the same widths. */ +const FONT = ['fontFamily', 'fontSize', 'fontWeight', 'letterSpacing', 'fontFeatureSettings', 'fontVariationSettings'] as const; + +/** + * Give the input of `field` (a `.field`) the glide caret and, with a fine pointer, the selection. + * Call it once, as the field is built (it measures only once the field is on the page). + */ +export function smoothCaret(field: HTMLElement) { + const input = field.querySelector('input'); + if (!input) return; + const fine = matchMedia('(pointer: fine)').matches; + field.classList.add('own-caret'); + if (fine) field.classList.add('own-sel'); + const wash = h('span', { class: 'caret-sel' }); + const h0 = h('span', { class: 'caret-hd s' }); + const h1 = h('span', { class: 'caret-hd e' }); + const caret = h('span', { class: 'caret' }); + const mirror = h('span', { class: 'caret-mirror', 'aria-hidden': 'true' }); + field.append(wash, h0, h1, caret, mirror); + // In the field's own px: while the sheet scales in (the rename field selects its text then), the + // box on screen is smaller than the one the caret is drawn in. + const measure = (text: string) => { + mirror.textContent = text; + const shown = field.getBoundingClientRect().width; + return mirror.getBoundingClientRect().width * (shown ? field.offsetWidth / shown : 1); + }; + const now = (): Places => + places( + { + value: input.value, + start: input.selectionStart ?? 0, + end: input.selectionEnd ?? 0, + backward: input.selectionDirection === 'backward', + left: input.offsetLeft, + width: input.clientWidth, + scroll: input.scrollLeft, + }, + measure, + ); + + const glide = (): Glide => ({ x: 0, v: 0, t: 0 }); + const cur = glide(); + const s0 = glide(); + const s1 = glide(); + const all = [cur, s0, s1]; + const jump = (g: Glide, x: number) => { + g.x = g.t = x; + g.v = 0; + }; + let selecting = false; + const focused = () => document.activeElement === input; + + const draw = () => { + caret.style.transform = `translateX(${(cur.x - 1).toFixed(2)}px)`; + wash.style.transform = `translateX(${Math.min(s0.x, s1.x).toFixed(2)}px)`; + wash.style.width = `${Math.abs(s1.x - s0.x).toFixed(2)}px`; + h0.style.transform = `translateX(${(s0.x - 1).toFixed(2)}px)`; + h1.style.transform = `translateX(${(s1.x - 1).toFixed(2)}px)`; + }; + + // One loop for the three edges; it stops when all of them rest. + let raf = 0; + let last = 0; + const step = (t: number) => { + const frames = last ? (t - last) / FRAME : 1; + last = t; + let busy = false; + for (const g of all) if (glideStep(g, frames)) busy = true; + draw(); + raf = busy ? requestAnimationFrame(step) : 0; + if (!raf) last = 0; + }; + const follow = () => { + // Less motion: everything is where it goes at once. + if (calm()) { + all.forEach((g) => jump(g, g.t)); + return draw(); + } + if (!raf) raf = requestAnimationFrame(step); + }; + + let first = true; + let rest = 0; + let faded = 0; + let fading = false; + let pressedAt = 0; + const place = () => { + if (!focused()) { + clearTimeout(rest); + caret.classList.remove('on', 'blink'); + field.classList.remove('selecting'); + selecting = false; + return draw(); + } + if (first) { + // Measured here, not when built: a field not on the page yet has no font to copy. + const cs = getComputedStyle(input); + for (const k of FONT) mirror.style[k] = cs[k]; + } + const p = now(); + if (first) { + all.forEach((g) => jump(g, p.start)); + first = false; + } + if (p.range && fine) { + // Selecting: the wash grows out of where the caret is, and the caret steps aside. A wash still fading from + // the last selection turns back instead and glides from its old ends to the new ones. + if (!selecting) { + clearTimeout(faded); + if (!fading) { + s0.x = s1.x = cur.x; + s0.v = s1.v = 0; + } + fading = false; + } + selecting = true; + s0.t = p.start; + s1.t = p.end; + cur.t = p.caret; + field.classList.add('selecting'); + caret.classList.remove('on', 'blink'); + } else if (p.range) { + // A touch screen: the system's own selection shows. + caret.classList.remove('on', 'blink'); + return; + } else { + // Collapsed: the wash fades where it stands, and its ends join the caret once it is gone. + // A click puts the caret where it was clicked at once, as macOS does; typing and the arrows glide. + if (selecting) { + field.classList.remove('selecting'); + clearTimeout(faded); + fading = true; + faded = window.setTimeout(() => { + fading = false; + if (selecting) return; + jump(s0, cur.t); + jump(s1, cur.t); + draw(); + }, 160); + } else if (!fading) { + jump(s0, p.start); + jump(s1, p.start); + } + selecting = false; + if (performance.now() - pressedAt < 400) jump(cur, p.caret); + else cur.t = p.caret; + // Solid while it moves or they type, blinking again half a second after. + caret.classList.add('on'); + caret.classList.remove('blink'); + clearTimeout(rest); + rest = window.setTimeout(() => { + if (focused()) caret.classList.add('blink'); + }, 500); + } + follow(); + }; + // After the event: by then the browser has moved its own caret. + let queued = 0; + const soon = () => { + if (!queued) + queued = requestAnimationFrame(() => { + queued = 0; + place(); + }); + }; + + for (const ev of ['pointerdown', 'pointerup']) input.addEventListener(ev, () => (pressedAt = performance.now())); + for (const ev of ['input', 'keydown', 'keyup', 'pointerup', 'select', 'scroll']) input.addEventListener(ev, soon); + input.addEventListener('pointermove', (e) => { + if (e.buttons) soon(); + }); + // A selection made any other way (the keyboard's, a double click, the page's own select()). + const onSelect = () => { + if (focused()) soon(); + }; + input.addEventListener('focus', () => { + first = true; + document.addEventListener('selectionchange', onSelect); + soon(); + }); + input.addEventListener('blur', () => { + document.removeEventListener('selectionchange', onSelect); + soon(); + }); +} diff --git a/web/src/portal/ui/codes.ts b/web/src/portal/ui/codes.ts index ec211e9..a86e711 100644 --- a/web/src/portal/ui/codes.ts +++ b/web/src/portal/ui/codes.ts @@ -2,71 +2,165 @@ // link as text with Copy and Share. Codes follow the theme: the night look // (light dots on black) on a dark one, the same dots dark on white on a light // one, redrawn in place when the system's theme changes. A dense code (an -// AmneziaVPN key) fills its row; the sheet widens for it (ui/sheet.ts). +// AmneziaVPN key) fills its row; the sheet widens for it (ui/sheet.ts). A code +// too long for a camera gives its place to a stand-in (the device's set-up link). -import { denseQr, qrSvg } from '../../shared/qr'; -import { h, ic } from '../dom'; -import { EASE_IN, EASE_OUT, play } from '../motion'; +import { denseQr, qrSvg, scannable } from '../../shared/qr'; +import { h, ic, markup } from '../dom'; +import { EASE_IN, EASE_OUT, SMOOTH, play } from '../motion'; import { placeName } from '../state'; import { copy } from './feedback'; const LIGHT = matchMedia('(prefers-color-scheme: light)'); const look = () => (LIGHT.matches ? 'day' : 'night'); -function paint(box: HTMLElement, text: string) { - box.dataset.qr = text; - box.classList.toggle('dense', denseQr(text)); +/** The code for `text` in the theme's look, tagged with what it says. */ +function drawn(text: string): SVGSVGElement { + const svg = markup(qrSvg(text, 3, true, look())) as SVGSVGElement; + svg.dataset.qr = text; + return svg; +} + +/** The box shows `svg` (or is about to): its size, and the sheet's width, follow that code. */ +function holds(box: HTMLElement, svg: SVGSVGElement) { + box.dataset.qr = svg.dataset.qr; + box.classList.toggle('dense', denseQr(svg.dataset.qr!)); box.classList.toggle('light', LIGHT.matches); - box.innerHTML = qrSvg(text, 3, true, look()); // The modules across: how wide the sheet must be for a camera to read it. - box.dataset.mods = String((box.firstElementChild as SVGSVGElement | null)?.viewBox.baseVal.width ?? 0); + box.dataset.mods = String(svg.viewBox.baseVal.width); } export function qrBox(text: string, big = false): HTMLElement { const box = h('div', { class: `qrbox${big ? ' big' : ''}` }); - paint(box, text); + const svg = drawn(text); + box.append(svg); + holds(box, svg); return box; } +// Each code is redrawn in the other look where it stands: a cross-fade under way carries on. LIGHT.addEventListener('change', () => document.querySelectorAll('.qrbox[data-qr]').forEach((b) => { - // Mid cross-fade a box holds two codes: the old one goes, the new one is drawn again. - b.querySelector('svg.old')?.remove(); - paint(b, b.dataset.qr!); + b.querySelectorAll(':scope > svg[data-qr]').forEach((s) => s.replaceChildren(...drawn(s.dataset.qr!).childNodes)); + b.classList.toggle('light', LIGHT.matches); }), ); +/** Where an element's fade stands now, mid-fade included. */ +function now(el: Element): Keyframe { + const s = getComputedStyle(el); + return { opacity: s.opacity, filter: s.filter === 'none' ? 'blur(0px)' : s.filter }; +} + export interface CodeRow { el: HTMLElement; /** Another code in the same place: it comes in over the old one, which then goes; new words too, if given (else they stay, to change in place). */ swap(next: string, words?: Node[]): void; } -/** A code and its words: side by side, or a dense code full width with the words under it. */ -export function codeRow(text: string, words: Node[]): CodeRow { - const box = qrBox(text); - let shown = h('div', { class: 'words' }, words); +/** What a code row shows instead of a code a camera cannot read: another code, and words that say why (made each time it shows). */ +export interface StandIn { + text: string; + words: () => Node[]; +} + +/** + * A code and its words: side by side, or a dense code full width with the + * words under it. With a stand-in, a code too long to scan shows the stand-in + * and its words; the row's own words come back with a code that fits. + */ +export function codeRow(text: string, words: Node[], standIn?: StandIn): CodeRow { + const instead = (t: string) => !!standIn && !scannable(t); + let own = words; + let out = instead(text); + const box = qrBox(out ? standIn!.text : text); + let shown = h('div', { class: 'words' }, out ? standIn!.words() : own); const side = h('div', { class: 'side' }, shown); const el = h('div', { class: `coderow${box.classList.contains('dense') ? ' stacked' : ''}` }, box, side); + /** + * Another code in the box: it comes in under the one showing, which lies over + * it and goes after it, so the place is never empty. Nothing on screen changes + * its place in the stack: the codes lie in the box in the order they paint (the + * one in flow first, under the rest). A swap under way carries on from where + * each code stands; a code turned back to fades up again where it lies, what + * lies over it going, and what lies under it goes once it shows whole. A code + * of the other size (dense or not) takes the box from its size on screen to its + * own on SMOOTH, the codes in it scaling with it, while the sheet glides the + * rest (glide() in ui/sheet.ts). + */ + let sizing: Animation | null = null; + /** The codes on their way out: a later swap leaves their fade as it is. */ + const going = new WeakSet(); + const cross = (code: string) => { + const svgs = [...box.querySelectorAll(':scope > svg')]; + const op = new Map(svgs.map((s) => [s, +getComputedStyle(s).opacity])); + const cs = getComputedStyle(box); + const r0 = box.getBoundingClientRect(); + // Its corners as they look now: a resize under way scales them with the box. + const round0 = parseFloat(cs.borderTopLeftRadius) * new DOMMatrix(cs.transform).a; + const neu = svgs.find((s) => s.dataset.qr === code) ?? drawn(code); + const at = svgs.indexOf(neu); + // A new code goes under them all; one still in the box stays where it lies. + if (at < 0) box.prepend(neu); + const over = svgs.slice(at + 1).filter((s) => !going.has(s)); + const under = svgs.slice(0, Math.max(0, at)); + const fades = [neu, ...over].flatMap((s) => s.getAnimations()); + going.delete(neu); + holds(box, neu); + el.classList.toggle('stacked', box.classList.contains('dense')); + const o0 = op.get(neu) ?? 0; + play(neu, [{ opacity: o0 }, { opacity: 1 }], { duration: 200 * (1 - o0), easing: EASE_OUT }).onfinish = () => { + // Whole: what lies under it, hidden now, goes, and it takes the box's flow under what still fades over it. + under.forEach((s) => s.remove()); + neu.classList.remove('old'); + }; + // What lies over it goes from how it shows, where it lies (the code that showed, over the new one); one already going goes on. + over.forEach((s) => { + s.classList.add('old'); + going.add(s); + play(s, [{ opacity: op.get(s)! }, { opacity: 0 }], { + duration: 220 * op.get(s)!, + delay: 110, + easing: EASE_IN, + fill: 'both', + }).onfinish = () => s.remove(); + }); + fades.forEach((a) => a.cancel()); + sizing?.cancel(); + sizing = null; + const r1 = box.getBoundingClientRect(); + const sx = r0.width / r1.width; + const sy = r0.height / r1.height; + // Not on screen (a folded row): nothing to watch move. + if (r0.width && r1.width && (Math.abs(sx - 1) > 0.005 || Math.abs(sy - 1) > 0.005)) + sizing = play( + box, + [ + { transform: `scale(${sx}, ${sy})`, transformOrigin: '0 0', borderRadius: `${round0 / sx}px` }, + { transform: 'none', transformOrigin: '0 0', borderRadius: getComputedStyle(box).borderTopLeftRadius }, + ], + { duration: SMOOTH.duration, easing: SMOOTH.easing }, + ); + }; return { el, swap(next, nextWords) { + if (nextWords) own = nextWords; + const was = out; + out = instead(next); + const code = out ? standIn!.text : next; // The same code for another app (AmneziaWG and WireGuard take one file): only the words change. - const oldSvg = box.dataset.qr === next ? null : box.querySelector('svg'); - if (oldSvg) { - paint(box, next); - el.classList.toggle('stacked', box.classList.contains('dense')); - const newSvg = box.querySelector('svg')!; - oldSvg.classList.add('old'); - box.appendChild(oldSvg); - // The new code comes in first, the old one goes after it: the place is never empty. - play(newSvg, [{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: EASE_OUT }); - play(oldSvg, [{ opacity: 1 }, { opacity: 0 }], { duration: 220, delay: 110, easing: EASE_IN, fill: 'forwards' }).onfinish = () => - oldSvg.remove(); - } - if (!nextWords) return; + if (box.dataset.qr !== code) cross(code); + // The stand-in's words stay while they say the same (they may follow what it stands in for); the row's own + // come back with a code that fits. + let put = out ? standIn!.words() : (nextWords ?? (was ? own : null)); + if (out && was && put!.map((n) => n.textContent).join('') === shown.textContent) put = null; + if (!put) return; const oldWords = shown; - shown = h('div', { class: 'words' }, nextWords); + // From where they stand: words still coming in (a pick right after a pick) go from there. + const from = now(oldWords); + const fades = oldWords.getAnimations(); + shown = h('div', { class: 'words' }, put); side.appendChild(shown); oldWords.classList.add('old'); play( @@ -77,14 +171,9 @@ export function codeRow(text: string, words: Node[]): CodeRow { ], { duration: 220, easing: EASE_OUT }, ); - play( - oldWords, - [ - { opacity: 1, filter: 'blur(0px)' }, - { opacity: 0, filter: 'blur(3px)' }, - ], - { duration: 200, delay: 90, easing: EASE_IN, fill: 'forwards' }, - ).onfinish = () => oldWords.remove(); + play(oldWords, [from, { opacity: 0, filter: 'blur(3px)' }], { duration: 200, delay: 90, easing: EASE_IN, fill: 'both' }).onfinish = + () => oldWords.remove(); + fades.forEach((a) => a.cancel()); }, }; } diff --git a/web/src/portal/ui/feedback.ts b/web/src/portal/ui/feedback.ts index b38f0fb..9a6ab2a 100644 --- a/web/src/portal/ui/feedback.ts +++ b/web/src/portal/ui/feedback.ts @@ -12,13 +12,22 @@ let slot: HTMLElement | null = null; let shown: HTMLElement | null = null; let timer = 0; -const leave = (t: HTMLElement, frames: Keyframe[], ms: number) => - (play(t, frames, { duration: ms, easing: EASE_IN, fill: 'forwards' }).onfinish = () => t.remove()); +/** A toast goes from where it stands: one still rising (a new one took its place) goes from there. */ +function leave(t: HTMLElement, to: Keyframe, ms: number) { + const s = getComputedStyle(t); + const a = play(t, [{ opacity: s.opacity, transform: s.transform, filter: s.filter }, to], { + duration: ms, + easing: EASE_IN, + fill: 'forwards', + }); + t.getAnimations().forEach((x) => x !== a && x.cancel()); + a.onfinish = () => t.remove(); +} /** One toast at a time: a new one sends the last away first. */ export function toast(msg: string, bad = false) { slot ??= document.body.appendChild(h('div', { class: 'toasts' })); - if (shown) leave(shown, [{ opacity: 1 }, { opacity: 0, transform: 'scale(.96)', filter: 'blur(4px)' }], 140); + if (shown) leave(shown, { opacity: 0, transform: 'scale(.96)', filter: 'blur(4px)' }, 140); const t = h('div', { class: `toast${bad ? ' bad' : ''}`, role: 'status' }, ic(bad ? 'alert' : 'check'), h('span', {}, msg)); slot.appendChild(t); shown = t; @@ -37,13 +46,13 @@ export function toast(msg: string, bad = false) { timer = window.setTimeout(() => { if (shown !== t) return; shown = null; - leave(t, [{ opacity: 1 }, { opacity: 0, transform: 'translateY(6px) scale(.96)', filter: 'blur(4px)' }], 180); + leave(t, { opacity: 0, transform: 'translateY(6px) scale(.96)', filter: 'blur(4px)' }, 180); }, 2400); } -/** An icon that changes in place: the new one pops in where the old one stood. */ -export function swapIcon(icon: Element, name: string): Element { - const next = ic(name, icon.getAttribute('class') ?? 'i'); +/** An icon that changes in place: the new one (by name, or one to put back) pops in where the old one stood. */ +export function swapIcon(icon: Element, to: string | Element): Element { + const next = typeof to === 'string' ? ic(to, icon.getAttribute('class') ?? 'i') : to; icon.replaceWith(next); play( next, @@ -61,9 +70,9 @@ export function swapIcon(icon: Element, name: string): Element { /** * The control that copied says so for a moment: its icon turns into a check - * and its "Copy…" label (`.lbl`, a badge's main line) into "Copied". Every - * control that copies with a label says "Copy…" (in any language), so the - * label is not read for the word. + * and its "Copy…" label (`.lbl`, a badge's main line) into "Copied", then both + * turn back the way they came. Every control that copies with a label says + * "Copy…" (in any language), so the label is not read for the word. */ function copied(from: Element) { if (from.classList.contains('copied')) return; @@ -74,7 +83,7 @@ function copied(from: Element) { const check = icon ? swapIcon(icon, 'check') : null; if (label) morphText(label, _('Copied')); setTimeout(() => { - if (check && icon) check.replaceWith(icon); + if (check && icon) swapIcon(check, icon); if (label) morphText(label, was); from.classList.remove('copied'); }, 1600); diff --git a/web/src/portal/ui/glass.ts b/web/src/portal/ui/glass.ts index 6f8b571..13ceef6 100644 --- a/web/src/portal/ui/glass.ts +++ b/web/src/portal/ui/glass.ts @@ -121,6 +121,11 @@ const GL: Record = { f: '', d: '', }, + lan: { + b: '', + f: '', + d: '', + }, }; /** The AmneziaVPN mark without its own svg: drawn on the "app" pane. */ diff --git a/web/src/portal/ui/menu.ts b/web/src/portal/ui/menu.ts index 31d95d7..3d5ea89 100644 --- a/web/src/portal/ui/menu.ts +++ b/web/src/portal/ui/menu.ts @@ -34,11 +34,22 @@ export function closeMenu(now = false) { m.remove(); return; } - play(m, [{ opacity: 1 }, { opacity: 0, transform: 'scale(.96)', filter: 'blur(3px)' }], { - duration: 120, - easing: EASE_IN, - fill: 'forwards', - }).onfinish = () => m.remove(); + // From where it stands: one closed while it still pops in (a scroll, a second press) goes from there. + const s = getComputedStyle(m); + const a = play( + m, + [ + { opacity: s.opacity, transform: s.transform, filter: s.filter }, + { opacity: 0, transform: 'scale(.96)', filter: 'blur(3px)' }, + ], + { + duration: 120, + easing: EASE_IN, + fill: 'forwards', + }, + ); + m.getAnimations().forEach((x) => x !== a && x.cancel()); + a.onfinish = () => m.remove(); } /** `items`: null is a separator, kept only between items. */ @@ -68,9 +79,12 @@ export function openMenu(anchor: HTMLElement, all: (MenuItem | null)[]) { it.checked === undefined ? ic(it.icon ?? '') : ic('check', it.checked ? 'i' : 'i off'), h('span', {}, it.label), ); - // The highlight comes in where the pointer is, then glides from item to item. + // The highlight comes in where the pointer is, then glides from item to item. Whether it shows is read off the + // screen: one still fading out (the pointer left and came back) turns back and glides from where it stands; + // only one gone altogether is placed at once. b.addEventListener('pointerenter', () => { - hl.className = `menu-hl${hl.style.opacity === '1' ? ' moving' : ''} ${it.tone ?? ''}`; + const seen = +getComputedStyle(hl).opacity > 0.01; + hl.className = `menu-hl${seen ? ' moving' : ''} ${it.tone ?? ''}`; hl.style.transform = `translateY(${b.offsetTop - 6}px)`; hl.style.opacity = '1'; }); diff --git a/web/src/portal/ui/morph.ts b/web/src/portal/ui/morph.ts index 543aee0..b48e632 100644 --- a/web/src/portal/ui/morph.ts +++ b/web/src/portal/ui/morph.ts @@ -4,7 +4,9 @@ // through `morphText`: a card's name and status after a repaint, the counts and // values, a label that says "Copied", a line that says what happened (the way: // "iPad connected"), and a menu path for another app or the other phone system -// (`menuLine`: where the app scans, iOS "Create", Android "Scan"). +// (`menuLine`: where the app scans, iOS "Create", Android "Scan"). Turned again +// half-way, a morph or a refill goes on from what shows: words still coming in +// leave from as far as they came, what was leaving keeps leaving. import { fmt } from '../../shared/i18n'; import { h, ic, markup, put, type Kid } from '../dom'; @@ -23,6 +25,22 @@ const runs = new WeakMap(); /** What `el` says: while it morphs, what it is turning into. */ export const textOf = (el: HTMLElement): string => runs.get(el)?.text ?? el.textContent ?? ''; +/** How something shows: its opacity and blur, part of the way while a fade or a morph runs. */ +export interface Look { + opacity: number; + filter: string; +} +const SHOWN: Look = { opacity: 1, filter: 'blur(0px)' }; +const settled = (s: Look) => s.opacity > 0.99 && (s.filter === 'none' || s.filter === 'blur(0px)'); + +/** How `el` shows now (on the page: a detached element has no style), with the words a whole-word morph brings in. */ +export function look(el: Element): Look { + const cs = getComputedStyle(el); + const words = el.querySelector(':scope > .mt-new'); + const ws = words && getComputedStyle(words); + return { opacity: +cs.opacity * (ws ? +ws.opacity : 1), filter: cs.filter === 'none' && ws ? ws.filter : cs.filter }; +} + /** Where `el`'s words sit (their own box, not the element's). */ function wordsBox(el: HTMLElement): DOMRect { const r = document.createRange(); @@ -30,6 +48,13 @@ function wordsBox(el: HTMLElement): DOMRect { return r.getBoundingClientRect(); } +/** Where a text's glyphs stand (only as high as the font, not the line). */ +function glyphs(n: Node): DOMRect { + const r = document.createRange(); + r.selectNodeContents(n); + return r.getBoundingClientRect(); +} + /** Where each character of `el`'s plain text starts, from the first (kerning and all). */ function spacing(el: HTMLElement): number[] { const node = el.firstChild; @@ -54,10 +79,11 @@ function spacing(el: HTMLElement): number[] { function space(box: Element, at: number[]) { const kids = [...box.children] as HTMLElement[]; if (!kids.length) return; - const start = kids[0].getBoundingClientRect().left; kids.forEach((c, i) => { if (!i || at[i] === undefined) return; - const dx = start + at[i] - c.getBoundingClientRect().left; + // Against the first letter as it stands now: in a centred line every nudge moves the whole run + // by half of it, the first letter too, and a start read once would let the nudges add up. + const dx = kids[0].getBoundingClientRect().left + at[i] - c.getBoundingClientRect().left; if (Math.abs(dx) > 0.01) c.style.marginLeft = `${dx}px`; }); } @@ -105,6 +131,20 @@ export function setText(el: HTMLElement, text: string) { el.textContent = text; } +/** + * A morph under way on `el`, taken out as it shows: the words it brings in (and where they stand), and all still + * leaving (one turned again before has more than one). + */ +function lift(el: HTMLElement): { words: HTMLElement; at: DOMRect; going: HTMLElement[] } | null { + const words = el.querySelector(':scope > .mt-new'); + if (!words) return null; + const going = [...el.querySelectorAll(':scope > .mt-old')]; + const at = wordsBox(words); + words.remove(); + going.forEach((g) => g.remove()); + return { words, at, going }; +} + export interface MorphOpts { /** The words change as a whole instead: the old blur away where they stood as the new come in. */ whole?: boolean; @@ -116,6 +156,10 @@ export interface MorphOpts { * words go from there, and the width does not glide. */ at?: DOMRect; + /** How the old words show, against `el` (they were still coming in when the caller rebuilt them): they leave from there. */ + shows?: Look; + /** The old words' colour, where `el` took another with the new ones (a status turned green): they keep it, the new turn from it. */ + color?: string; } /** @@ -125,14 +169,21 @@ export interface MorphOpts { * The old letters keep to the edge * that stays put while the width changes (the start of a line, the end of a * value on the right, the middle of a centred line). Done, it holds plain text - * again: a box that ends in an ellipsis keeps it. + * again: a box that ends in an ellipsis keeps it. Turned again half-way, the + * words that were coming in leave from as far as they came (a letter both + * texts keep slides on from where it is), and those leaving go on leaving. */ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: MorphOpts = {}) { const { whole = false, at } = o; + const run = runs.get(el); + // Asked again for what it is already turning into: the morph under way goes on. + if (run && from === run.text && next === run.text) return; // Placed by the caller, the width does not glide: what follows is moved by the caller too. const glide = (o.glide ?? true) && !at; - // Interrupted mid-way: the width carries on from where it is on screen, not from where that morph was going. - const midway = runs.has(el) ? el.getBoundingClientRect().width : null; + // Interrupted mid-way: the width carries on from where it is on screen, not from where that morph was going, + // and what shows of it is taken out as it stands. + const midway = run ? el.getBoundingClientRect() : null; + const live = run && from === run.text && !calm() && el.getClientRects().length ? lift(el) : null; finish(el); // Nothing to watch move: no motion asked for, or not on screen (a folded row, a closed sheet). if (from === next || calm() || !el.getClientRects().length) { @@ -145,8 +196,8 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M const flow = whole && cs.display === 'inline'; if (cs.display === 'inline' && !whole) el.classList.add('mt-ib'); if (cs.position === 'static') el.classList.add('mt'); - let r0: DOMRect | null = null; - let t0 = at ?? null; + let r0: DOMRect | null = live ? midway : null; + let t0 = live?.at ?? at ?? null; let at0: number[] = []; if (!t0) { el.textContent = from; @@ -157,15 +208,25 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M el.textContent = next; const r1 = el.getBoundingClientRect(); const at1 = spacing(el); - const w0 = midway ?? r0?.width ?? r1.width; + const w0 = midway?.width ?? r0?.width ?? r1.width; const glides = glide && !flow && !!r0 && Math.abs(r1.width - w0) > 0.5; const edge = !glides || !r0 || Math.abs(r1.left - r0.left) < 0.5 ? 'start' : Math.abs(r1.right - r0.right) < 0.5 ? 'end' : 'middle'; const neu = h('span', { class: whole ? 'mt-new w' : 'mt-new' }, whole ? next : letters(next)); - const old = h('span', { class: whole ? 'mt-old w' : 'mt-old', 'aria-hidden': 'true' }, whole ? from : letters(from)); + // The old words: those that were coming in, as they show, or the old text built afresh. + const old = live?.words ?? h('span', { class: whole ? 'mt-old w' : 'mt-old' }, whole ? from : letters(from)); + old.classList.replace('mt-new', 'mt-old'); + old.setAttribute('aria-hidden', 'true'); // Whole words wrap as they did: the old ones keep the width they took. - if (whole) old.style.width = `${t0.width + 1}px`; + if (old.classList.contains('w')) old.style.width = `${t0.width + 1}px`; el.replaceChildren(neu, old); + // What was still leaving goes on leaving where it is. + if (live) el.append(...live.going); + if (o.color) { + old.style.color = o.color; + const c1 = getComputedStyle(el).color; + if (c1 !== o.color) play(neu, [{ color: o.color }, { color: c1 }], { duration: 280, easing: EASE_OUT }); + } // Held at the plain text's width until the letters turn back into it, so what follows never steps. if (glides) play(el, [{ width: `${w0}px` }, { width: `${r1.width}px` }], { @@ -186,18 +247,28 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M }; const x0 = edge === 'end' ? t0.right - r2.right : edge === 'middle' ? (t0.left + t0.right - r2.left - r2.right) / 2 : t0.left - r2.left; place(x0, t0.top - r2.top); - // Then onto the old words exactly: the box's top is not the text's (the line's leading sits above it). - const t2 = wordsBox(old); + // Then onto the old words exactly: the box's top is not the text's (the line's leading sits above it), nor is a + // letter's (a box of its own, a line high): built afresh, the first letter's glyphs go where the text's stood. + const first = !live && old.querySelector('i')?.firstChild; + const t2 = first ? glyphs(first) : wordsBox(old); place(x0 + t0.left - t2.left, t0.top - r2.top + t0.top - t2.top); - if (whole) { + // How the old words show: those that were coming in as far as they came. + const s0 = live ? look(old) : (o.shows ?? SHOWN); + /** The old words go as one, from how they show. */ + const leave = () => { + const prior = old.getAnimations(); play( old, [ - { opacity: 1, filter: 'blur(0px)' }, + { opacity: s0.opacity, filter: s0.filter }, { opacity: 0, filter: 'blur(4px)' }, ], - { duration: 180, easing: EASE_IN, fill: 'forwards' }, + { duration: 180 * s0.opacity, easing: EASE_IN, fill: 'forwards' }, ); + prior.forEach((a) => a.cancel()); + }; + if (whole) { + leave(); play( neu, [ @@ -211,26 +282,36 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M return; } space(neu, at1); - space(old, at0); + if (!live) space(old, at0); // The letters both texts keep slide from where they stood to where they go, on the width's spring; - // the old ones' places in the overlay stay empty. - const was = [...old.children] as HTMLElement[]; + // the old ones' places in the overlay stay empty. Old words that came whole have no letters to keep. + const was = old.classList.contains('w') ? [] : ([...old.children] as HTMLElement[]); const now = [...neu.children] as HTMLElement[]; - const pairs = kept([...from], [...next]); + const pairs = was.length ? kept([...from], [...next]) : []; const stays = new Set(pairs.map(([i]) => i)); const comes = new Set(pairs.map(([, j]) => j)); pairs.forEach(([i, j]) => { const a = was[i].getBoundingClientRect(); const b = now[j].getBoundingClientRect(); + // A letter still rising when the morph turned comes along from as far as it rose. + const s = live ? look(was[i]) : s0; was[i].style.visibility = 'hidden'; - if (Math.abs(a.left - b.left) > 0.5 || Math.abs(a.top - b.top) > 0.5) - play(now[j], [{ transform: `translate(${a.left - b.left}px, ${a.top - b.top}px)` }, { transform: 'none' }], { - duration: SMOOTH.duration, - easing: SMOOTH.easing, - }); + const moves = Math.abs(a.left - b.left) > 0.5 || Math.abs(a.top - b.top) > 0.5; + const shows = settled(s) ? null : s; + if (moves || shows) + play( + now[j], + [ + { transform: `translate(${a.left - b.left}px, ${a.top - b.top}px)`, ...shows }, + { transform: 'none', ...(shows && SHOWN) }, + ], + { duration: SMOOTH.duration, easing: SMOOTH.easing }, + ); }); - const out = was.filter((_x, i) => !stays.has(i)); + // Turned half-way, the old words leave as one: each of their letters is somewhere on its own way. + const out = live ? [] : was.filter((_x, i) => !stays.has(i)); + if (live) leave(); const inn = now.filter((_x, j) => !comes.has(j)); // A long text keeps the same overall sweep: the steps shorten instead. const so = Math.min(12, 160 / Math.max(1, out.length)); @@ -239,7 +320,7 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M play( c, [ - { opacity: 1, filter: 'blur(0px)', transform: 'none' }, + { opacity: s0.opacity, filter: s0.filter, transform: 'none' }, { opacity: 0, filter: 'blur(4px)', transform: 'translateY(-0.45em)' }, ], { duration: 220, delay: i * so, easing: EASE_IN, fill: 'forwards' }, @@ -260,17 +341,32 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M runs.set(el, { text: next, timer: window.setTimeout(() => finish(el), ends) }); } -/** The keyed texts under `root` (`data-t`), before a repaint rebuilds them. */ -export function textsOf(root: ParentNode): Map { - return new Map([...root.querySelectorAll('[data-t]')].map((el) => [el.dataset.t!, textOf(el)])); +/** What a keyed text said, and in which colour. */ +export interface Said { + text: string; + color: string; } -/** After the repaint: each keyed text that changed morphs from what it said. */ -export function morphChanged(root: ParentNode, was: Map) { +/** The keyed texts under `root` (`data-t`), before a repaint rebuilds them. */ +export function textsOf(root: ParentNode): Map { + return new Map( + [...root.querySelectorAll('[data-t]')].map((el) => [ + el.dataset.t!, + { text: textOf(el), color: getComputedStyle(el).color }, + ]), + ); +} + +/** + * After the repaint: each keyed text that changed morphs from what it said (one already turning into it goes on). + * `fresh`: what a refill brought in whole (morphInto), its words with it: the old words fade where they stood. + */ +export function morphChanged(root: ParentNode, was: Map, fresh: Element[] = []) { root.querySelectorAll('[data-t]').forEach((el) => { const before = was.get(el.dataset.t!); - const now = el.textContent ?? ''; - if (before !== undefined && before !== now) morphText(el, now, before); + const now = textOf(el); + if (!before || before.text === now || runs.has(el) || fresh.some((f) => f.contains(el))) return; + morphText(el, now, before.text, { color: before.color }); }); } @@ -283,11 +379,87 @@ interface Piece { /** Where its words stand (a morph under way: the words it is turning into). */ words: DOMRect | null; node: Node; + /** How it shows: part of the way while it still comes in. */ + shows: Look; } +/** What can fade out where it stood. */ +type Drawn = HTMLElement | SVGElement; +const isDrawn = (n: Node): n is Drawn => n instanceof HTMLElement || n instanceof SVGElement; +/** A piece as something that can fade where it stood: bare words go into a span of their own. */ +const drawn = (n: Node): Drawn => (isDrawn(n) ? n : h('span', {}, n)); /** Its tag and classes, less a morph's own (a piece still changing is the same piece). */ const kindOf = (el: Element) => `${el.tagName}.${[...el.classList].filter((c) => c !== 'mt' && c !== 'mt-ib').join(' ')}`; /** A drawing as markup, less the ids each build makes up (a glass icon's gradients): the same icon twice is the same. */ const drawing = (el: Element) => el.outerHTML.replace(/\bgl\d+/g, 'gl'); + +/** What fades out where it stood (`fadeAway`), each with the element it is laid over. */ +const fading = new Map(); +/** How many fade over each element, and those made a positioned box for them. */ +const holding = new WeakMap(); +const boxed = new WeakSet(); +/** Inside something already fading out (under `box`): it goes with it. */ +function within(el: Element, box: Element): boolean { + for (let p = el.parentElement; p && p !== box; p = p.parentElement) if (fading.has(p)) return true; + return false; +} +function hold(host: Element) { + const n = holding.get(host) ?? 0; + if (!n && getComputedStyle(host).position === 'static') { + host.classList.add('mt'); + boxed.add(host); + } + holding.set(host, n + 1); +} +/** The last to fade over `host` is gone: a box made positioned for them is static again. */ +function release(host: Element) { + const n = (holding.get(host) ?? 1) - 1; + holding.set(host, n); + if (!n && boxed.delete(host)) host.classList.remove('mt'); +} + +/** + * `e`, which stood at `at` on screen, fades out there, laid over `host` (which + * stood at `from`): a piece a refill crossed or left out (morphInto), a card's + * old foot (page/devices.ts). One already fading only moves over its new host + * and goes on; another starts from how it showed (`shows`: it may still have + * been coming in), over what is left of its way. + */ +export function fadeAway(e: Drawn, at: DOMRect, host: Element, from: DOMRect, shows: Look = SHOWN) { + const over = fading.get(e); + if (over) release(over); + hold(host); + fading.set(e, host); + e.style.position = 'absolute'; + e.style.margin = '0'; + e.style.left = `${at.left - from.left - host.clientLeft}px`; + e.style.top = `${at.top - from.top - host.clientTop}px`; + e.style.right = ''; + e.style.translate = ''; + e.style.width = `${at.width}px`; + e.style.pointerEvents = 'none'; + e.setAttribute('aria-hidden', 'true'); + host.appendChild(e); + if (over) return; + const prior = e.getAnimations(); + const a = play( + e, + [ + { opacity: shows.opacity, filter: shows.filter }, + { opacity: 0, filter: 'blur(4px)' }, + ], + { duration: 180 * shows.opacity, easing: EASE_IN, fill: 'forwards' }, + ); + prior.forEach((x) => x.cancel()); + // Gone, or stopped by whatever stops what moves around it: it was leaving either way. + a.onfinish = a.oncancel = () => { + const last = fading.get(e); + if (!last) return; + fading.delete(e); + release(last); + e.remove(); + }; +} + function pieces(box: Element): Map { const out = new Map(); const walk = (n: Node, path: string) => @@ -298,58 +470,121 @@ function pieces(box: Element): Map { const r = document.createRange(); r.selectNodeContents(c); const at = r.getBoundingClientRect(); - out.set(p, { kind: '#text', text: c.textContent, svg: '', at, words: at, node: c }); + out.set(p, { kind: '#text', text: c.textContent, svg: '', at, words: at, node: c, shows: SHOWN }); } return; } - if (!(c instanceof Element)) return; + // What is on its way out already (crossed by a refill before, words a morph lifts away) goes on by itself. + if (!(c instanceof Element) || fading.has(c) || c.classList.contains('mt-old')) return; const svg = c instanceof SVGElement ? drawing(c) : ''; const words = c instanceof HTMLElement && !svg ? wordsBox(c.querySelector(':scope > .mt-new') ?? c) : null; - out.set(p, { kind: kindOf(c), text: c instanceof HTMLElement ? textOf(c) : '', svg, at: c.getBoundingClientRect(), words, node: c }); + out.set(p, { + kind: kindOf(c), + text: c instanceof HTMLElement ? textOf(c) : '', + svg, + at: c.getBoundingClientRect(), + words, + node: c, + shows: look(c), + }); if (!svg) walk(c, p); }); walk(box, ''); return out; } -/** Something with nothing to change from comes in through a blur. */ -const appear = (el: Element) => +/** + * `el` glides back to its place from `(dx, dy)` away, on SMOOTH. A transform + * does nothing to words in a line (an inline box): those move by a relative + * offset instead, theirs only for the glide. + */ +function shift(el: Element, dx: number, dy: number) { + const o = { duration: SMOOTH.duration, easing: SMOOTH.easing }; + if (!(el instanceof HTMLElement) || getComputedStyle(el).display !== 'inline') + return play(el, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], o); + const own = el.style.position; + if (getComputedStyle(el).position === 'static') el.style.position = 'relative'; + const a = play( + el, + [ + { left: `${dx}px`, top: `${dy}px` }, + { left: '0px', top: '0px' }, + ], + o, + ); + a.onfinish = a.oncancel = () => (el.style.position = own); + return a; +} + +/** + * Something with nothing to change from comes in through a blur, to its own + * opacity (a part the stylesheet dims stays dimmed); `shows`: it was on its way + * in already, and goes on from as far as it came. + */ +export function appear(el: Element, shows?: Look) { + const own = +getComputedStyle(el).opacity; + const o0 = shows?.opacity ?? 0; play( el, [ - { opacity: 0, filter: 'blur(4px)' }, - { opacity: 1, filter: 'blur(0px)' }, + { opacity: o0, filter: shows?.filter ?? 'blur(4px)' }, + { opacity: own, filter: 'blur(0px)' }, ], - { duration: 280, delay: 60, easing: EASE_OUT, fill: 'backwards' }, + { duration: 280 * Math.min(1, Math.max(0, own - o0) / (own || 1)), delay: shows ? 0 : 60, easing: EASE_OUT, fill: 'backwards' }, ); +} /** * `box` refilled with `kids` and nothing blinks: what is the same stays still; * a piece in the same place with other words blurs from the old words into the - * new where it stands; a drawing that changed comes in through a blur; a piece - * that changed its kind or its height (another block, a list that wraps over - * more lines) crosses whole, the old one blurring out exactly where it stood as - * the new one blurs in, and so does what is gone. A piece that kept its kind - * and size but moved glides from where it stood. Places are taken against the - * box, which its sheet moves as a whole; an old piece fades inside its own - * parent's new self (the same kind, in the same place), so it keeps its look. + * new where it stands (a keyed text, `data-t`, is left to morphChanged, which + * letter-morphs it from what it said); a piece that changed its kind, its + * height (another block, a list that wraps over more lines) or its drawing + * crosses whole, the old one blurring out exactly where it stood as the new one + * blurs in, and so does what is gone. A piece that kept its kind and size but + * moved glides from where it stood. Places are taken against the box, which its + * sheet moves as a whole; an old piece fades inside its own parent's new self + * (the same kind, in the same place), so it keeps its look. Refilled again + * half-way, what was fading goes on fading where it is, and what was still + * coming in goes on from as far as it came. Returns what came in whole. */ -export function morphInto(box: HTMLElement, kids: Kid) { +export function morphInto(box: HTMLElement, kids: Kid): Element[] { const was = pieces(box); const box0 = box.getBoundingClientRect(); + // What is on its way out already, with what it sat in: it goes on over that one's new self. + const going = [...fading.keys(), ...box.querySelectorAll('.mt-old')] + .filter((g): g is Drawn => box.contains(g) && !within(g, box) && isDrawn(g)) + .map((g) => ({ g, at: g.getBoundingClientRect(), over: g.parentElement, shows: fading.has(g) ? undefined : look(g) })); + const pathOf = new Map([...was].map(([p, w]) => [w.node, p])); put(box, kids); - if (!was.size || calm()) return; + /** The new element at each place. */ + const placed = new Map(); + const carry = () => + going.forEach(({ g, at, over, shows }) => { + const p = over && pathOf.get(over); + const host = p && placed.get(p); + const w = p && was.get(p); + if (host && w && w.at && w.kind === kindOf(host)) fadeAway(g, at, host, w.at, shows); + else fadeAway(g, at, box, box0, shows); + }); + if (!was.size || calm()) { + carry(); + return []; + } const box1 = box.getBoundingClientRect(); /** Where something that stood at `r` in the box's old place stands now, the pieces having glided back there. */ const here = (r: DOMRect | null) => r && new DOMRect(r.left - box0.left + box1.left, r.top - box0.top + box1.top, r.width, r.height); const morphs: (() => void)[] = []; - /** An old piece, where it stood, the new parent it fades in and where that parent stood. */ - const ghosts: [Element, DOMRect, Element, DOMRect][] = []; + /** An old piece, where it stood, the new parent it fades in, where that parent stood, and how the piece showed. */ + const ghosts: [Drawn, DOMRect, Element, DOMRect, Look][] = []; const seen = new Set(); + /** What comes in whole. */ + const came: Element[] = []; const cross = (el: Element, w: Piece | undefined, path: string) => { const host = el.parentElement; const from = path ? was.get(path)?.at : box0; - if (w?.at && w.node instanceof Element) ghosts.push(host && from ? [w.node, w.at, host, from] : [w.node, w.at, box, box0]); + if (w?.at) ghosts.push(host && from ? [drawn(w.node), w.at, host, from, w.shows] : [drawn(w.node), w.at, box, box0, w.shows]); + came.push(el); morphs.push(() => appear(el)); }; /** Moves `el` from where it stood (`at`, in the box's old place) to where it is, less what its parent already carries. */ @@ -359,8 +594,7 @@ export function morphInto(box: HTMLElement, kids: Kid) { const dy = at.top - box0.top - (r.top - box1.top); const ox = dx - carried[0]; const oy = dy - carried[1]; - if (Math.abs(ox) > 0.5 || Math.abs(oy) > 0.5) - play(el, [{ transform: `translate(${ox}px, ${oy}px)` }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); + if (Math.abs(ox) > 0.5 || Math.abs(oy) > 0.5) shift(el, ox, oy); return [dx, dy]; }; const walk = (n: Node, path: string, carried: [number, number]) => @@ -370,75 +604,58 @@ export function morphInto(box: HTMLElement, kids: Kid) { const w = was.get(p); if (c.nodeType === Node.TEXT_NODE) { const t = c.textContent ?? ''; - if (!t.trim() || (w?.kind === '#text' && w.text === t)) return; + if (!t.trim()) return; + // Words: a bare word before, or one the last refill put in a span of its own (it is still that word). + const said = w && (w.kind === '#text' || (w.node instanceof HTMLElement && !w.node.children.length)) ? w.text : null; + const coming = w && w.shows.opacity < 0.99 ? w.shows : null; + if (said === t && !coming) return; // A bare word among elements goes into a span of its own, so it can change (and glide from where its words were). const s = h('span', {}, t); c.replaceWith(s); + if (said === null || Math.max(t.length, said.length) > 40) return cross(s, w, path); if (w?.at) glideFrom(s, w.at, carried); morphs.push(() => - w?.kind === '#text' && t.length <= 40 && w.text.length <= 40 - ? morphText(s, t, w.text, { whole: true, at: here(w.words) ?? undefined }) - : appear(s), + said === t ? appear(s, coming!) : morphText(s, t, said, { whole: true, at: here(w!.words) ?? undefined, shows: w!.shows }), ); return; } if (!(c instanceof Element)) return; + placed.set(p, c); const r = c.getBoundingClientRect(); - if (!w || w.kind !== kindOf(c) || (w.at && Math.abs(w.at.height - r.height) > 1 && !(c instanceof SVGElement))) + const svg = c instanceof SVGElement; + if (!w || w.kind !== kindOf(c) || (svg ? w.svg !== drawing(c) : !!w.at && Math.abs(w.at.height - r.height) > 1)) return cross(c, w, path); // The same piece somewhere else in the box: it glides there (what it holds rides along, plus its own move). const own = w.at ? glideFrom(c, w.at, carried) : carried; - if (c instanceof SVGElement) { - if (w.svg !== drawing(c)) morphs.push(() => appear(c)); + // Still coming in when the box was refilled: it goes on from as far as it came. + const rest = +getComputedStyle(c).opacity; + const coming = Math.abs(w.shows.opacity - rest) > 0.01 ? w.shows : null; + if (svg) { + if (coming) morphs.push(() => appear(c, coming)); return; } if (!c.children.length && c instanceof HTMLElement) { const t = c.textContent ?? ''; - if (t !== w.text) - morphs.push(() => - t.length <= 40 && w.text.length <= 40 - ? morphText(c, t, w.text, { whole: true, at: here(w.words) ?? undefined }) - : cross(c, w, path), - ); + if (t === w.text || c.dataset.t) { + if (coming) morphs.push(() => appear(c, coming)); + } else if (t.length <= 40 && w.text.length <= 40) { + // The old words leave from how they showed, against the element that holds them now. + const shows = { opacity: Math.min(1, w.shows.opacity / (rest || 1)), filter: w.shows.filter }; + morphs.push(() => morphText(c, t, w.text, { whole: true, at: here(w.words) ?? undefined, shows })); + } else cross(c, w, path); return; } + if (coming) morphs.push(() => appear(c, coming)); walk(c, p, own); }); walk(box, '', [0, 0]); // What the new box no longer has goes the same way. - for (const [p, w] of was) - if (!seen.has(p) && p.lastIndexOf('/') === 0 && w.at && w.node instanceof Element) ghosts.push([w.node, w.at, box, box0]); + for (const [p, w] of was) if (!seen.has(p) && p.lastIndexOf('/') === 0 && w.at) ghosts.push([drawn(w.node), w.at, box, box0, w.shows]); morphs.forEach((m) => m()); // The old pieces that cross go from exactly where they stood in their parent (which glides from where it stood). - const hosts = new Map(); - for (const [, , host] of ghosts) { - if (!hosts.has(host) && getComputedStyle(host).position === 'static') host.classList.add('mt'); - hosts.set(host, (hosts.get(host) ?? 0) + 1); - } - for (const [g, at, host, from] of ghosts) { - const e = g as HTMLElement; - e.style.position = 'absolute'; - e.style.margin = '0'; - e.style.left = `${at.left - from.left - host.clientLeft}px`; - e.style.top = `${at.top - from.top - host.clientTop}px`; - e.style.width = `${at.width}px`; - e.style.pointerEvents = 'none'; - e.setAttribute('aria-hidden', 'true'); - host.appendChild(e); - play( - e, - [ - { opacity: 1, filter: 'blur(0px)' }, - { opacity: 0, filter: 'blur(4px)' }, - ], - { duration: 180, easing: EASE_IN, fill: 'forwards' }, - ).onfinish = () => { - e.remove(); - const n = hosts.get(host)! - 1; - hosts.set(host, n); - if (!n) host.classList.remove('mt'); - }; - } + for (const [g, at, host, from, shows] of ghosts) fadeAway(g, at, host, from, shows); + carry(); + return came; } /** The Android robot's head; its eyes take the colour of what it sits on. */ @@ -502,15 +719,21 @@ export function menuLine(ios: string, android: string): MenuLine { }; const MARK = { width: '1.05em', marginRight: '0.25em' }; - const markOut = (m: HTMLElement) => - (play( + /** The mark shrinks away from where it stands (one still growing in turns back), over what is left of its width. */ + const markOut = (m: HTMLElement) => { + const cs = getComputedStyle(m); + const left = Math.min(1, parseFloat(cs.width) / (1.05 * parseFloat(cs.fontSize)) || 0); + const prior = m.getAnimations(); + play( m, [ - { opacity: 1, filter: 'blur(0px)', ...MARK }, + { opacity: cs.opacity, filter: cs.filter, width: cs.width, marginRight: cs.marginRight }, { opacity: 0, filter: 'blur(3px)', width: '0px', marginRight: '0px' }, ], - { duration: 220, easing: EASE_IN, fill: 'forwards' }, - ).onfinish = () => m.remove()); + { duration: 220 * left, easing: EASE_IN, fill: 'forwards' }, + ).onfinish = () => m.remove(); + prior.forEach((a) => a.cancel()); + }; const markIn = (m: HTMLElement) => play( m, diff --git a/web/src/portal/ui/seg.ts b/web/src/portal/ui/seg.ts index 3d817c3..5a6869e 100644 --- a/web/src/portal/ui/seg.ts +++ b/web/src/portal/ui/seg.ts @@ -19,6 +19,26 @@ export interface IconSeg { sync(v: T): void; } +/** Where a name stands on screen: its width of `full` (its words' whole width), and its opacity. */ +export interface LabelAt { + width: number; + full: number; + opacity: number; +} + +/** + * How a name fades on a pick, from where it stands (ms): the picked one blurs + * in (280, a beat after the pill sets off), the others fold (220); a fade + * turned back half-way runs only the share of its way it has left, and a name + * already folded has nothing to do (0). + */ +export function labelFade(at: LabelAt, picked: boolean): { duration: number; delay: number } { + const opacity = Math.min(1, Math.max(0, at.opacity)); + if (picked) return { duration: 280 * (1 - opacity), delay: 70 * (1 - opacity) }; + const left = Math.max(opacity, at.full > 0 ? Math.min(1, at.width / at.full) : 0); + return { duration: left > 0.01 ? 220 * left : 0, delay: 0 }; +} + export function iconSeg(items: SegItem[], value: T, onPick: (v: T) => void): IconSeg { const pill = h('span', { class: 'seg-pill' }); const el = h('div', { class: 'seg appseg', role: 'tablist' }, pill); @@ -59,32 +79,68 @@ export function iconSeg(items: SegItem[], value: T, onPick: const cs = getComputedStyle(pill); const l0 = parseFloat(cs.left) || 0; const r0 = parseFloat(cs.right) || 0; + // Each item's share as it stands, and its basis (a narrow picker gives a picked item more: controls.css). const g0 = btns.map((b) => parseFloat(getComputedStyle(b).flexGrow) || 0); - const oldL = labelOf(btns[from]); - const oldW = oldL.getBoundingClientRect().width; - [...btns, ...btns.map(labelOf)].forEach((x) => x.getAnimations().forEach((a) => a.cancel())); + const f0 = btns.map((b) => getComputedStyle(b).flexBasis); + // Every name from where it stands too: a pick turned back half-way (or an item still folding from the one + // before) goes on from there, so neither a name nor the icon beside it jumps. + const labels = btns.map(labelOf); + const now = labels.map((l) => { + const s = getComputedStyle(l); + return { width: l.getBoundingClientRect().width, opacity: +s.opacity, filter: s.filter, marginLeft: s.marginLeft }; + }); + [...btns, ...labels].forEach((x) => x.getAnimations().forEach((a) => a.cancel())); value = v; mark(); + // The picked name's whole width, as it will stand once its item has its share. + const w1 = labels[to].getBoundingClientRect().width; btns.forEach((b, i) => { const g1 = i === to ? 1 : 0; - if (g0[i] !== g1) play(b, [{ flexGrow: g0[i] }, { flexGrow: g1 }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); + const f1 = getComputedStyle(b).flexBasis; + if (g0[i] !== g1 || f0[i] !== f1) + play( + b, + [ + { flexGrow: g0[i], flexBasis: f0[i] }, + { flexGrow: g1, flexBasis: f1 }, + ], + { duration: SMOOTH.duration, easing: SMOOTH.easing }, + ); + }); + labels.forEach((l, i) => { + const n = now[i]; + const fade = labelFade({ ...n, full: l.scrollWidth }, i === to); + if (i !== to) { + // It folds (its blur, if it was still coming in, stays while it fades). + if (fade.duration) + play( + l, + [ + { opacity: n.opacity, maxWidth: `${n.width}px`, marginLeft: n.marginLeft, filter: n.filter }, + { opacity: 0, maxWidth: '0px', marginLeft: '-8px', filter: n.filter }, + ], + { duration: fade.duration, easing: 'ease-out' }, + ); + return; + } + // The picked name opens with its item's share, inside the pill, and blurs in. + play( + l, + [ + { maxWidth: `${n.width}px`, marginLeft: n.marginLeft }, + { maxWidth: `${w1}px`, marginLeft: '0px' }, + ], + { duration: SMOOTH.duration, easing: SMOOTH.easing }, + ); + play( + l, + [ + { opacity: n.opacity, filter: n.opacity ? n.filter : 'blur(4px)' }, + { opacity: 1, filter: 'none' }, + ], + { ...fade, easing: EASE_OUT, fill: 'backwards' }, + ); }); - play( - oldL, - [ - { opacity: 1, maxWidth: `${oldW}px`, marginLeft: '0px' }, - { opacity: 0, maxWidth: '0px', marginLeft: '-8px' }, - ], - { duration: 220, easing: 'ease-out' }, - ); - play( - labelOf(btns[to]), - [ - { opacity: 0, filter: 'blur(4px)' }, - { opacity: 1, filter: 'none' }, - ], - { duration: 280, delay: 70, easing: EASE_OUT, fill: 'backwards' }, - ); // The stretch: the leading edge follows the quick spring, the trailing edge the smooth one. const right = to > from; const lead = calm() ? SMOOTH : LEAD; diff --git a/web/src/portal/ui/sheet.ts b/web/src/portal/ui/sheet.ts index 4f89bc5..26cc902 100644 --- a/web/src/portal/ui/sheet.ts +++ b/web/src/portal/ui/sheet.ts @@ -1,12 +1,13 @@ -// The sheet: one drawer floating at the bottom of the screen, on phones and -// desktops alike. It holds a stack of views (go/back), glides to each view's -// height, widens on a desktop for a dense QR code until the code gets its -// pixels, pins a view's own buttons beside ×, and closes by ×, the scrim, a +// The sheet: a drawer at the bottom of a phone's screen, a dialog in the +// middle of a computer's. It holds a stack of views (go/back), glides to each +// view's height, widens on a desktop for a dense QR code until the code gets +// its pixels, pins a view's own buttons beside ×, and closes by ×, the scrim, a // pull down on its header, Escape, or the phone's back button (it is a history -// entry). Views are built by the flows; this module only moves them. +// entry). A flow that comes while it is on its way out opens once it is gone. +// Views are built by the flows; this module only moves them. import { h, ic } from '../dom'; -import { BOUNCY, DRAWER, EASE_IN, EASE_OUT, SMOOTH, SOFT, dismisses, play, rubber } from '../motion'; +import { BOUNCY, DRAWER, EASE_IN, EASE_OUT, SMOOTH, SOFT, dismisses, play, rubber, unrubber } from '../motion'; import { closeMenu } from './menu'; /** A view: its root, and what the sheet reads from it. */ @@ -32,11 +33,19 @@ let vp: HTMLElement; let stack: ViewFactory[] = []; let closed: (() => void) | null = null; let left: (() => void) | null = null; +/** A flow that came while the sheet was on its way out (an answer after Cancel): it opens once the sheet is gone. */ +let next: ViewFactory | null = null; let ownsHistory = false; let returnFocus: HTMLElement | null = null; +/** Until then clicks in a sheet just opened are the second half of the double click that opened it. */ +let quietUntil = 0; export const sheetOpen = () => !!root?.classList.contains('open'); +/** What runs on `el` and moves one of `props`: stopped or waited for without touching the rest. */ +const running = (el: Element, ...props: string[]) => + el.getAnimations().filter((a) => (a.effect as KeyframeEffect | null)?.getKeyframes().some((k) => props.some((p) => p in k))); + /* ---------- width: a dense code scans from a screen at about 3 px a module ---------- */ const SHEET_W = 400; @@ -56,8 +65,9 @@ export interface WidthPlan { /** * The width the sheet needs now, set at once so whatever measures the new - * layout (an accordion, the height glide) measures it at the final width; the - * plan then animates there on the same spring (`startWidth`), so nothing snaps. + * layout (an accordion) measures it at the final width; the plan then animates + * there on the same spring (`startWidth`), so nothing snaps. The sheet's own + * height follows its view through the glide (`glideHeight`). */ export function planWidth(): WidthPlan | null { if (!root || !sheetOpen()) return null; @@ -81,10 +91,7 @@ export function planWidth(): WidthPlan | null { if (Math.abs(want - sheetW) < 8) return reveal ? { from: want, want, reveal } : null; const from = parseFloat(getComputedStyle(sheetEl).maxWidth) || sheetW; sheetW = want; - sheetEl - .getAnimations() - .filter((a) => (a.effect as KeyframeEffect | null)?.getKeyframes().some((k) => 'maxWidth' in k)) - .forEach((a) => a.cancel()); + running(sheetEl, 'maxWidth').forEach((a) => a.cancel()); sheetEl.style.maxWidth = `${want}px`; return { from, want, reveal }; } @@ -115,6 +122,17 @@ function build() { sheetEl = h('div', { class: 'sheet', role: 'dialog', 'aria-modal': 'true' }, closeBtn, actsEl, scroller); scrim = h('div', { class: 'scrim', onclick: () => closeSheet() }); root = h('div', { class: 'sheet-root', 'aria-hidden': 'true' }, scrim, sheetEl); + // The second click of a double click lands on what the first one opened: the scrim would close the sheet again, + // a question's button would answer it. + root.addEventListener( + 'click', + (e) => { + if (performance.now() >= quietUntil) return; + e.preventDefault(); + e.stopPropagation(); + }, + true, + ); document.body.appendChild(root); new ResizeObserver(() => startWidth(planWidth())).observe(vp); pullToClose(); @@ -148,6 +166,11 @@ export function onClosed(fn: () => void) { export function openSheet(factory: ViewFactory) { if (!root) build(); closeMenu(true); + if (root.dataset.closing) { + // Still on its way out: the new flow opens once it is gone, as it would have a moment later. + next = factory; + return; + } leave(); if (sheetOpen()) { // Already open: the new flow takes the place of the old one, history and all. @@ -156,6 +179,7 @@ export function openSheet(factory: ViewFactory) { return; } returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; + quietUntil = performance.now() + 320; stack = [factory]; closed = null; sheetW = SHEET_W; @@ -194,6 +218,9 @@ export function openSheet(factory: ViewFactory) { if (!ownsHistory) { try { history.pushState({ sheet: true }, ''); + // The sheet's own entry never moves the page: left behind once the sheet closes, a step forward onto it (Safari's + // swipe in from the right edge) would put the page back where it stood when the sheet opened. + history.scrollRestoration = 'manual'; ownsHistory = true; } catch { /* no history */ @@ -203,63 +230,91 @@ export function openSheet(factory: ViewFactory) { /** `now`: gone at once (Escape: what the keyboard does never animates). */ export function closeSheet(now = false) { - if (!sheetOpen() || root.dataset.closing) return; + if (!sheetOpen()) return; + if (root.dataset.closing) { + // Escape while it goes, or the link stopped working: gone at once, and nothing opens after it. + if (now) { + next = null; + gone(); + } + return; + } leave(); if (ownsHistory) { ownsHistory = false; history.back(); } document.body.classList.remove('locked'); - const done = () => { - root.classList.remove('open'); - root.setAttribute('aria-hidden', 'true'); - delete root.dataset.closing; - sheetEl.style.transform = ''; - scrim.style.opacity = ''; - sheetEl.getAnimations().forEach((a) => a.cancel()); - scrim.getAnimations().forEach((a) => a.cancel()); - vp.getAnimations().forEach((a) => a.cancel()); - vp.replaceChildren(); - actsEl.replaceChildren(); - sheetEl.classList.remove('arrived'); - sheetEl.style.maxWidth = ''; - sheetW = SHEET_W; - stack = []; - if (returnFocus?.isConnected) returnFocus.focus({ preventScroll: true }); - returnFocus = null; - const f = closed; - closed = null; - f?.(); - }; - if (now) return done(); + if (now) return gone(); root.dataset.closing = '1'; - const from = getComputedStyle(sheetEl).transform; - sheetEl.getAnimations().forEach((a) => a.cancel()); + // From where it stands: a dialog still coming up leaves from its present fade, blur and scale. + const cs = getComputedStyle(sheetEl); + const at = cs.transform; + const op = cs.opacity; + const blur = cs.filter === 'none' ? 'blur(0px)' : cs.filter; + const dim = getComputedStyle(scrim).opacity; + running(sheetEl, 'transform', 'opacity').forEach((a) => a.cancel()); + scrim.getAnimations().forEach((a) => a.cancel()); play( scrim, - [{ opacity: getComputedStyle(scrim).opacity }, { opacity: 0 }], + [{ opacity: dim }, { opacity: 0 }], wide() ? { duration: 120, easing: EASE_IN, fill: 'forwards' } : { duration: 320, easing: 'ease-out', fill: 'forwards' }, ); - const at = from === 'none' ? 'none' : from; // A dialog goes the way a ⋯ menu does, quick and soft into its centre; the drawer goes down past the edge. play( sheetEl, wide() ? [ - { opacity: 1, transform: at, filter: 'blur(0px)' }, + { opacity: op, transform: at, filter: blur }, { opacity: 0, transform: `${at === 'none' ? '' : at} scale(.96)`.trim(), filter: 'blur(3px)' }, ] : [{ transform: at }, { transform: 'translateY(calc(100% + 40px))' }], wide() ? { duration: 120, easing: EASE_IN, fill: 'forwards' } : { duration: 420, easing: DRAWER, fill: 'forwards' }, - ).onfinish = done; + ).onfinish = gone; } -// The phone's back button closes the sheet instead of leaving the page. +/** The sheet is out of the page: emptied, focus back on what opened it, then whatever waited for it. */ +function gone() { + // Nothing a view holds (a poll) outlives the sheet. + leave(); + root.classList.remove('open'); + root.setAttribute('aria-hidden', 'true'); + delete root.dataset.closing; + sheetEl.style.transform = ''; + scrim.style.opacity = ''; + sheetEl.getAnimations().forEach((a) => a.cancel()); + scrim.getAnimations().forEach((a) => a.cancel()); + vp.replaceChildren(); + actsEl.replaceChildren(); + sheetEl.classList.remove('arrived'); + sheetEl.style.maxWidth = ''; + sheetW = SHEET_W; + stack = []; + if (returnFocus?.isConnected) returnFocus.focus({ preventScroll: true }); + returnFocus = null; + const f = closed; + closed = null; + f?.(); + const n = next; + next = null; + if (n) openSheet(n); +} + +/** On the history entry a sheet pushed (openSheet): closing it steps back to the page's own. */ +export const onSheetEntry = () => !!(history.state as { sheet?: boolean } | null)?.sheet; + +// The phone's back button closes the sheet instead of leaving the page. A sheet's entry is current only while its +// sheet is open: one left behind (a reload with a sheet open, a step forward onto it) is stepped back off at once, so +// Back from there leaves the page instead of putting it back where it stood when that sheet opened. addEventListener('popstate', () => { - if (!sheetOpen()) return; + if (!sheetOpen()) { + if (onSheetEntry()) history.back(); + return; + } ownsHistory = false; closeSheet(); }); +if (onSheetEntry()) history.back(); /** A view's own buttons beside ×: pinned with it while the sheet scrolls, they come and go with the view. */ function setActs(v: View, anim = true) { @@ -301,17 +356,38 @@ function setActs(v: View, anim = true) { } } +/** + * The viewport glides from `h0`, its height on screen, to its view's: as a gap under the view that closes, or an + * overhang the viewport clips, so what changes inside meanwhile (a row opening, a fold, a poll) carries the sheet's + * edge along instead of landing when the glide ends. + */ +function glideHeight(view: Element | null, h0: number, o: KeyframeAnimationOptions) { + if (!view) return; + running(view, 'marginBottom').forEach((a) => a.cancel()); + const d = h0 - vp.getBoundingClientRect().height; + if (Math.abs(d) > 1) play(view, [{ marginBottom: `${d}px` }, { marginBottom: '0px' }], o); +} + /** Another view in the open sheet: the old one fades out over the new one, the sheet glides to its height. */ function swapView(v: View) { label(v); setActs(v); sheetEl.classList.remove('arrived'); - const old = [...vp.children] as HTMLElement[]; const h0 = vp.getBoundingClientRect().height; - vp.getAnimations().forEach((a) => a.cancel()); - old.forEach((o) => { + // What goes stays where it stands on screen while the scroll goes back to the top under it (the viewport clips it); + // a view already on its way out keeps its own fade. + const st = scroller.scrollTop; + const views = [...vp.children] as HTMLElement[]; + const tops = views.map((o) => (o.classList.contains('leaving') ? parseFloat(o.style.top) || 0 : 0) - st); + const old = views.filter((o) => !o.classList.contains('leaving')); + // It fades from how it shows: one still coming in (Back right after a step) goes from as far as it came. + const shown = old.map((o) => { + const cs = getComputedStyle(o); + return { opacity: cs.opacity, transform: cs.transform, filter: cs.filter }; + }); + views.forEach((o, i) => { o.classList.add('leaving'); - Object.assign(o.style, { position: 'absolute', left: '0', right: '0', top: '0', pointerEvents: 'none' }); + Object.assign(o.style, { position: 'absolute', left: '0', right: '0', top: `${tops[i]}px`, pointerEvents: 'none' }); o.inert = true; }); vp.appendChild(v.el); @@ -319,25 +395,17 @@ function swapView(v: View) { v.el.style.pointerEvents = 'none'; setTimeout(() => (v.el.style.pointerEvents = ''), 320); scroller.scrollTop = 0; - const plan = planWidth(); - const h1 = v.el.getBoundingClientRect().height; - play(vp, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: 360, easing: 'cubic-bezier(.25,1,.5,1)' }); - startWidth(plan); - old.forEach( - (o) => - (play( - o, - [ - { 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 = () => o.remove()), - ); + startWidth(planWidth()); + glideHeight(v.el, h0, { duration: 360, easing: 'cubic-bezier(.25,1,.5,1)' }); + old.forEach((o, i) => { + const prior = o.getAnimations(); + play(o, [shown[i], { opacity: 0, transform: 'scale(.96)', filter: 'blur(2px)' }], { + duration: 200 * +shown[i].opacity, + easing: 'cubic-bezier(.2,0,0,1)', + fill: 'forwards', + }).onfinish = () => o.remove(); + prior.forEach((a) => a.cancel()); + }); play( v.el, [ @@ -355,14 +423,14 @@ function swapView(v: View) { /** Further into a flow (Add → Open on the device). */ export function go(factory: ViewFactory) { - if (!sheetOpen()) return openSheet(factory); + if (!sheetOpen() || root.dataset.closing) return openSheet(factory); leave(); stack.push(factory); swapView(factory()); } export function back() { - if (stack.length < 2) return; + if (stack.length < 2 || root.dataset.closing) return; leave(); stack.pop(); swapView(stack[stack.length - 1]()); @@ -375,19 +443,17 @@ export function back() { */ export function glide(change: () => void, focus: (Element | null | undefined)[] = []) { if (!sheetOpen()) return change(); - const h0 = vp.getBoundingClientRect().height; - vp.getAnimations().forEach((a) => a.cancel()); const view = vp.lastElementChild; + // As it all stands on screen, the sheet's own glides under way included. const was = new Map(); view?.querySelectorAll('*').forEach((e) => { if (!(e instanceof SVGElement) || e instanceof SVGSVGElement) was.set(e, e.getBoundingClientRect()); }); + const h0 = vp.getBoundingClientRect().height; change(); - const plan = planWidth(); - const h1 = vp.getBoundingClientRect().height; - if (Math.abs(h1 - h0) > 1) play(vp, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); - startWidth(plan); - // Measured with the sheet back at its old size (its glides have just started): only what moved inside it moves. + startWidth(planWidth()); + glideHeight(view, h0, { duration: SMOOTH.duration, easing: SMOOTH.easing }); + // Measured with the sheet back at its size on screen (its glides have just started): only what moved inside it moves. const moved = new Set(); for (const [e, r] of was) { if (!e.isConnected || !r.width || !r.height) continue; @@ -401,7 +467,13 @@ export function glide(change: () => void, focus: (Element | null | undefined)[] let p = e.parentElement; while (p && p !== view && !moved.has(p)) p = p.parentElement; if (p && p !== view) continue; - play(e, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); + // Added to a glide still under way (a quick second pick), which runs on to its end underneath: both rects held + // its offset, so this is only the new move, and nothing it had left to go is dropped. + play(e, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { + duration: SMOOTH.duration, + easing: SMOOTH.easing, + composite: 'add', + }); } for (const el of focus) if (el) @@ -415,9 +487,12 @@ export function glide(change: () => void, focus: (Element | null | undefined)[] ); } -/** The view's job is done (a device connected): ×, and the view's own buttons, step away. */ -export function settle() { - sheetEl?.classList.add('arrived'); +/** + * The view's job is done (a device connected): ×, and the view's own buttons, step away. `false`: it turned out + * not to be (the device left that state): they come back. + */ +export function settle(done = true) { + sheetEl?.classList.toggle('arrived', done); } /** The sheet scrolls back to the top (a device connected under a scrolled sheet). */ @@ -428,12 +503,27 @@ export const showing = (el: Element) => sheetOpen() && vp.contains(el) && !el.cl /* ---------- pull down by the header to close ---------- */ +/** The dim a pull alone leaves: it fades as the sheet goes down. */ +const dimAt = (dy: number) => Math.max(0, 1 - Math.max(0, dy) / 420); + function pullToClose() { - let drag: { y: number; t: number; dy: number; v: number } | null = null; + // `y`: where the finger would stand with the sheet at rest; `y0`: where the sheet was taken; `off`: how far the dim + // was then from what the pull alone gives (a sheet taken while it still opens). + let drag: { y: number; t: number; dy: number; v: number; y0: number; off: number } | null = null; sheetEl.addEventListener('pointerdown', (e) => { const t = e.target as Element; if (!t.closest('.vhead') || t.closest('button, a, input')) return; - drag = { y: e.clientY, t: performance.now(), dy: 0, v: 0 }; + // Not while it leaves, nor while a dialog pops up: its fade and blur ride the same animation as its scale. + if (root.dataset.closing || running(sheetEl, 'opacity').length) return; + // Taken where it stands (still rising, or settling back from the last pull), and the dim with it. + const y0 = new DOMMatrixReadOnly(getComputedStyle(sheetEl).transform).m42; + const o = +getComputedStyle(scrim).opacity; + running(sheetEl, 'transform').forEach((a) => a.cancel()); + scrim.getAnimations().forEach((a) => a.cancel()); + if (y0) sheetEl.style.transform = `translateY(${y0}px)`; + if (o !== 1) scrim.style.opacity = String(o); + const raw = y0 < 0 ? -unrubber(-y0, sheetEl.offsetHeight) : y0; + drag = { y: e.clientY - raw, t: performance.now(), dy: y0, v: 0, y0, off: o - dimAt(y0) }; sheetEl.setPointerCapture(e.pointerId); }); sheetEl.addEventListener('pointermove', (e) => { @@ -446,17 +536,22 @@ function pullToClose() { drag.dy = dy; drag.t = t; sheetEl.style.transform = `translateY(${dy}px)`; - scrim.style.opacity = String(Math.max(0, 1 - Math.max(0, dy) / 420)); + scrim.style.opacity = String(Math.min(1, Math.max(0, dimAt(dy) + drag.off))); }); const end = () => { if (!drag) return; - const { dy, v } = drag; + const { dy, v, y0 } = drag; drag = null; - if (dismisses(dy, v, sheetEl.offsetHeight)) return closeSheet(); + // A touch that never moved (on a sheet still rising) only lets it settle. + if (dy !== y0 && dismisses(dy, v, sheetEl.offsetHeight)) return closeSheet(); + // Back to rest from where the pull left it, the dim with it on the same spring. const from = sheetEl.style.transform; + const dim = getComputedStyle(scrim).opacity; sheetEl.style.transform = ''; scrim.style.opacity = ''; - if (dy !== 0) play(sheetEl, [{ transform: from }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing }); + const o = { duration: SMOOTH.duration, easing: SMOOTH.easing }; + if (dy !== 0) play(sheetEl, [{ transform: from }, { transform: 'none' }], o); + if (+dim !== 1) play(scrim, [{ opacity: dim }, { opacity: 1 }], o); }; sheetEl.addEventListener('pointerup', end); sheetEl.addEventListener('pointercancel', end); diff --git a/web/src/portal/ui/shimmer.ts b/web/src/portal/ui/shimmer.ts new file mode 100644 index 0000000..10e2f4b --- /dev/null +++ b/web/src/portal/ui/shimmer.ts @@ -0,0 +1,151 @@ +// A light sweeping across a field's words while they are on their way to the router (a device's name being +// saved), as an assistant's "thinking" line does: a copy of the words laid exactly over the input's dims, and a +// band with a bell-shaped falloff crosses it again and again with a rest between. Stopping holds the band where it +// is and fades the words back to their colour around it; only then does the copy go, so the input's own words +// (or what takes their place) show with nothing changing. The band is the words' own colour over a muted base +// (styles/controls.css, `.shim`). With less motion asked for it only dims and comes back. + +import { h } from '../dom'; +import { calm } from '../motion'; + +/** A cubic-bezier easing as a function of progress (0..1). */ +function bezier(x1: number, y1: number, x2: number, y2: number): (x: number) => number { + const at = (a: number, b: number, t: number) => 3 * a * t * (1 - t) ** 2 + 3 * b * t * t * (1 - t) + t ** 3; + return (x) => { + let lo = 0; + let hi = 1; + for (let i = 0; i < 24; i++) { + const mid = (lo + hi) / 2; + if (at(x1, x2, mid) < x) lo = mid; + else hi = mid; + } + return at(y1, y2, (lo + hi) / 2); + }; +} +const STANDARD = bezier(0.2, 0, 0, 1); +const linear = (x: number) => x; + +/** One value that moves; a new move of it stops the old one first. */ +class Value { + v: number; + private stop: (() => void) | null = null; + constructor( + v: number, + private paint: () => void, + ) { + this.v = v; + } + /** To `to` over `ms` (after `delay`), from where it is: true once there, false if stopped first. */ + to(to: number, ms: number, ease: (x: number) => number, delay = 0): Promise { + this.halt(); + return new Promise((done) => { + let t0 = 0; + let from = this.v; + const step = (now: number) => { + if (!t0) { + t0 = now + delay; + from = this.v; + } + const k = ms <= 0 ? 1 : Math.min(1, Math.max(0, (now - t0) / ms)); + if (now >= t0) { + this.v = from + (to - from) * ease(k); + this.paint(); + } + if (k < 1) raf = requestAnimationFrame(step); + else { + this.stop = null; + done(true); + } + }; + let raf = requestAnimationFrame(step); + this.stop = () => { + cancelAnimationFrame(raf); + this.stop = null; + done(false); + }; + }); + } + halt() { + this.stop?.(); + } +} + +/** Half the band's width in em, and its falloff as [offset, strength]. */ +const BAND = 2.2; +const FALLOFF = [ + [-1, 0], + [-0.5, 0.5], + [-0.2, 0.9], + [0, 1], + [0.2, 0.9], + [0.5, 0.5], + [1, 0], +] as const; +const pct = (x: number) => `${(x * 100).toFixed(1)}%`; + +/** The band at sweep `t` (0: left of the words, 1: right of them) over a base `settle` of the way to solid. */ +function image(t: number, settle: number): string { + const base = `color-mix(in oklab, var(--shim-high) ${pct(settle)}, var(--shim-base))`; + const stops = FALLOFF.map( + ([o, k]) => + `color-mix(in oklab, var(--shim-high) ${pct(k)}, ${base}) calc(${(t * 100).toFixed(2)}% + ${((2 * t - 1 + o) * BAND).toFixed(3)}em)`, + ); + return `linear-gradient(90deg, ${base}, ${stops.join(', ')}, ${base})`; +} + +/** The input's font, for a copy of its words that has to sit exactly on them. */ +const FONT = ['fontFamily', 'fontSize', 'fontWeight', 'letterSpacing', 'fontFeatureSettings', 'fontVariationSettings'] as const; + +/** Seconds for one sweep across the words, and the rest between sweeps (a share of it). */ +const SWEEP = 1.8; +const REST = 0.32; +/** How long the words take to fade back to their colour once the answer is in, in ms. */ +const SETTLE = 480; + +/** + * Start the shimmer over `input` (inside `field`, which it marks `.saving`). Returns the stop, which resolves + * once the words are solid again and the copy is gone. + */ +export function shimmer(field: HTMLElement, input: HTMLInputElement): () => Promise { + const cs = getComputedStyle(input); + // The copy sits in a box the input's size and is clipped to it, scrolled as the input is: a name longer than + // the field shows the same part, never more. + const copy = h('span', { class: 'shim' }, input.value); + const clip = h('span', { class: 'shim-clip', 'aria-hidden': 'true' }, copy); + for (const k of FONT) copy.style[k] = cs[k]; + Object.assign(clip.style, { + left: `${input.offsetLeft}px`, + top: `${input.offsetTop}px`, + width: `${input.clientWidth}px`, + height: `${input.offsetHeight}px`, + }); + Object.assign(copy.style, { left: `${-input.scrollLeft}px`, lineHeight: `${input.offsetHeight}px` }); + const still = calm(); + const paint = () => (copy.style.backgroundImage = image(sweep.v, settle.v)); + // Solid at first, exactly the input's words: the swap shows nothing, then it dims. + const sweep = new Value(0, paint); + const settle = new Value(1, paint); + paint(); + field.append(clip); + field.classList.add('saving'); + field.setAttribute('aria-busy', 'true'); + + let running = !still; + const pass = async (delay: number) => { + if (!running) return; + if (sweep.v >= 1) sweep.v = 0; + if (await sweep.to(1, SWEEP * 1000 * (1 - sweep.v), linear, delay * 1000)) void pass(SWEEP * REST); + }; + void pass(0.12); + void settle.to(0, still ? 0 : 240, STANDARD); + + return async () => { + // The band stops where it is and the words fade back to their colour around it: nothing races off. + running = false; + sweep.halt(); + await settle.to(1, still ? 0 : SETTLE, STANDARD); + field.classList.remove('saving'); + field.removeAttribute('aria-busy'); + clip.remove(); + }; +} diff --git a/web/src/portal/way.ts b/web/src/portal/way.ts new file mode 100644 index 0000000..682b5a3 --- /dev/null +++ b/web/src/portal/way.ts @@ -0,0 +1,25 @@ +// What the set-up sheet's way shows, read off the device in the router's last +// answer (`setup` on every device view: the agent's watcher's; without the +// agent the router counts a session that lives as data flowing): waiting, +// can't finish (its knocks reach the router, no handshake follows), connected +// (a handshake since the sheet opened, and data coming through), no data (a +// handshake since then, but nothing in except handshakes and keep-alives: an +// outdated configuration). Pure: flows/wait.ts polls for it and draws it. + +import type { Device } from '../shared/types'; + +export type WayState = 'waiting' | 'trying' | 'connected' | 'nodata'; + +/** + * The way's state for `d` (undefined: no longer in the answer), `opened` being when the sheet opened (router + * clock). Arrival is data flowing, not the first handshake, so no data shows instead of the sheet closing; a + * handshake from before the sheet is not this set-up's. Knocks that never finish show whenever they come. Anything + * else (the device gone offline, quiet, or removed) is plain waiting. + */ +export function wayState(d: Device | undefined, opened: number): WayState { + if (!d) return 'waiting'; + if (d.setup?.state === 'trying') return 'trying'; + if (d.handshake <= opened) return 'waiting'; + if (d.setup?.state === 'flowing') return 'connected'; + return d.setup?.state === 'nodata' ? 'nodata' : 'waiting'; +} diff --git a/web/src/shared/format.ts b/web/src/shared/format.ts index 9e1de50..86ad808 100644 --- a/web/src/shared/format.ts +++ b/web/src/shared/format.ts @@ -1,7 +1,7 @@ // Formatting helpers shared by the admin UI and the portal, in the page's // language (shared/i18n.ts): units, relative times, dates, labels. -import type { Access, Kind, PersonState } from './types'; +import type { Access, Kind, Person, PersonState, Server } from './types'; import { fmt, locale, num, plural } from './i18n'; /** A size with its unit: one decimal from 1 KB up to 100 of a unit ("1.5 GB", "120 MB"). */ @@ -155,6 +155,73 @@ export function accessLabel(a: Access): string { return { lan: _('Home network'), internet: _('Internet'), both: _('Home network + Internet') }[a]; } +/** The longest name a device takes, in characters (the router's DEVICE_NAME_MAX, util.uc). */ +export const DEVICE_NAME_MAX = 20; + +/** + * Past ASCII, the blocks a device's name doesn't take: symbols, punctuation, arrows, maths, emoji and invisibles + * (the router refuses the same, util.uc NAME_SYMBOLS). Code point ranges, both ends in. + */ +const NAME_SYMBOLS: [number, number][] = [ + [0x80, 0xbf], + [0xd7, 0xd7], + [0xf7, 0xf7], + [0x2000, 0x2bff], + [0x3000, 0x303f], + [0xd800, 0xf8ff], + [0xfe00, 0xfe0f], + [0xfe30, 0xfe4f], + [0xfeff, 0xfeff], + [0xfff0, 0xffff], + [0x1f000, 0x1fbff], + [0xe0000, 0xe007f], +]; +const ASCII_NAME = /^[A-Za-z0-9 ._-]$/; +const LETTER = /^[\p{L}\p{M}\p{N}]$/u; + +/** + * One character a device's name may hold: a letter of any language (with its marks) or a digit, a space, - _ or + * . (the router checks the ASCII ones and refuses the symbol blocks past it; this also asks Unicode it is a letter). + */ +export function deviceNameChar(ch: string): boolean { + const cp = ch.codePointAt(0) ?? 0; + if (cp < 0x80) return ASCII_NAME.test(ch); + return !NAME_SYMBOLS.some(([a, b]) => cp >= a && cp <= b) && LETTER.test(ch); +} + +/** `s` could still become a device's name as it is typed: only those characters, no more than DEVICE_NAME_MAX. */ +export function deviceNameFits(s: string): boolean { + const chars = [...s]; + return chars.length <= DEVICE_NAME_MAX && chars.every(deviceNameChar); +} + +/** A device's name the router takes: not blank, and it fits (spaces around are trimmed). */ +export const validDeviceName = (s: string): boolean => !!s.trim() && deviceNameFits(s.trim()); + +/** + * A name made up for a device (its kind, the phone's model), as the router takes it: what it refuses stripped + * ("Galaxy S24+" → "Galaxy S24"), cut to fit with `suffix` after it ("Phone 2"), not left ending in a space. + * Nothing left: the kind-less "Device". + */ +export function fitName(base: string, suffix = ''): string { + const clean = + [...base] + .map((c) => (deviceNameChar(c) ? c : ' ')) + .join('') + .replace(/\s+/g, ' ') + .trim() || _('Device'); + const cut = [...clean] + .slice(0, Math.max(1, DEVICE_NAME_MAX - [...suffix].length)) + .join('') + .trimEnd(); + return cut + suffix; +} + +/** The name a device of kind `k` gets when nobody gives it one, in the page's language: "Phone", "Device". */ +export function defaultName(k: Kind): string { + return k === 'other' ? _('Device') : kindLabel(k); +} + /** In picker order. */ export const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other']; @@ -207,3 +274,18 @@ export function byDeviceState rank(a[0]) - rank(b[0]) || a[1] - b[1]) .map(([d]) => d); } + +/** Networks as people read them: a /24 as its first three numbers and x ("10.0.1.x"), others as they are. */ +export function netsLabel(nets: string[]): string { + return nets.map((n) => (n.endsWith('.0/24') ? `${n.slice(0, -5)}.x` : n)).join(', '); +} + +/** + * The home networks a device of `p` with LAN Bypass still sends into the tunnel: with home and internet access, + * the server's home networks they reach (all of them, or the ones picked for them). None otherwise. + */ +export function homeOf(p: Person, srv: Server | undefined): string[] { + if (p.access !== 'both' || !srv) return []; + const pick = p.home_nets ?? []; + return srv.home.filter((h) => !pick.length || pick.includes(h.dev)).flatMap((h) => h.nets); +} diff --git a/web/src/shared/name-guard.ts b/web/src/shared/name-guard.ts new file mode 100644 index 0000000..f393634 --- /dev/null +++ b/web/src/shared/name-guard.ts @@ -0,0 +1,59 @@ +// A device's name as it is typed, in the portal and the admin: what the router would refuse never gets in. A +// character it doesn't take (letters of any language, digits, spaces and - _ . only) or one past DEVICE_NAME_MAX is turned +// away as it is typed, pasted or dropped, `field` shakes and `tell` gets a short reason for the field's red line, +// then null once a change gets in. Nothing is asked of the router for it. Emptying the field is fine as it +// happens: a submit says so. The router checks the same on its own (util.uc): this only spares the round trip. + +import { DEVICE_NAME_MAX, deviceNameChar, deviceNameFits } from './format'; +import { fmt, num } from './i18n'; +import { shake } from './shake'; + +/** Why `next` doesn't fit, short enough for a card's status line: a character it doesn't take, else its length. */ +function why(next: string): string { + return [...next].every(deviceNameChar) ? fmt(_('Up to %s characters.'), num(DEVICE_NAME_MAX)) : _('Only letters, digits, - _ .'); +} + +/** + * Call it as the input is built, before its own `input` listeners: a refused change is undone before they see it. + * `field`: what shakes (a getter, for a field built after its input); the input itself by default. `look`: as + * shake() takes it (no red ring for a field drawn without one). + */ +export function guardDeviceName( + input: HTMLInputElement, + field: HTMLElement | (() => HTMLElement) = input, + tell: (why: string | null) => void = () => {}, + look: { ring?: boolean } = {}, +) { + const box = () => (typeof field === 'function' ? field() : field); + let last = input.value; + input.addEventListener('beforeinput', (e) => { + last = input.value; + // Deleting is always fine; typing through an IME is checked once it lands (it can't be refused mid-way). + if (e.inputType.startsWith('delete') || e.isComposing || e.inputType === 'insertCompositionText') return; + const text = e.data ?? e.dataTransfer?.getData('text/plain') ?? ''; + const s = input.selectionStart ?? input.value.length; + const end = input.selectionEnd ?? s; + const next = input.value.slice(0, s) + text + input.value.slice(end); + if (deviceNameFits(next)) return; + e.preventDefault(); + shake(box(), look); + tell(why(next)); + }); + // What got in anyway (an IME's letters, autofill): back to what it was, caret where it stood. Deleting stays + // (an old name the rules came after is shortened a letter at a time). + input.addEventListener('input', (e) => { + const deleting = e instanceof InputEvent && e.inputType.startsWith('delete'); + if (deleting || deviceNameFits(input.value)) { + last = input.value; + tell(null); + return; + } + const next = input.value; + const at = Math.min(input.selectionStart ?? last.length, last.length); + input.value = last; + input.setSelectionRange(at, at); + e.stopImmediatePropagation(); + shake(box(), look); + tell(why(next)); + }); +} diff --git a/web/src/shared/qr.ts b/web/src/shared/qr.ts index ab458b7..c97d3a4 100644 --- a/web/src/shared/qr.ts +++ b/web/src/shared/qr.ts @@ -27,6 +27,39 @@ const ROUND: Record<'night' | 'day', [bg: string, fg: string]> = { night: [NIGHT /** Long content: fewer modules matter more than the mark. */ export const denseQr = (text: string): boolean => text.length > 300; +/** The last code made: qrSvg right after qrFits on the same text does not make it again. */ +let made: { text: string; qr: ReturnType } | null = null; + +/** The code for a text, at the level qrSvg draws it with; throws when no version holds the text. */ +function make(text: string) { + if (made?.text === text) return made.qr; + const qr = qrcode(0, denseQr(text) ? 'L' : 'H'); + qr.addData(text, 'Byte'); + qr.make(); + made = { text, qr }; + return qr; +} + +/** Does the text fit in a code at all? Version 40 holds 2953 bytes at level L; past that the library throws. */ +export function qrFits(text: string): boolean { + try { + make(text); + return true; + } catch { + return false; + } +} + +/** + * Past about 1.6 KB (version 29-L, 133 modules) a code on a phone's screen is + * too fine for another phone's camera, even before it stops fitting at all + * (an AmneziaVPN key on Maximum without compression is about 3.3 KB). + */ +const SCAN_MAX = 1600; + +/** Can a camera read this text from a code on a screen? */ +export const scannable = (text: string): boolean => text.length <= SCAN_MAX && qrFits(text); + const n2 = (v: number) => +v.toFixed(2); /** A rounded rectangle as a sub-path. */ function rrect(x: number, y: number, w: number, h: number, r: number): string { @@ -41,9 +74,7 @@ export function qrSvg(text: string, margin = 3, logo = true, look: QrLook = 'pla // The night and day looks draw the same round dots and eyes; only their colours differ. const round = look !== 'plain'; const [bg, fg] = round ? ROUND[look] : ['#fff', '#000']; - const qr = qrcode(0, dense ? 'L' : 'H'); - qr.addData(text, 'Byte'); - qr.make(); + const qr = make(text); const n = qr.getModuleCount(); const size = n + margin * 2; // A centred, module-aligned hole for the mark (same parity as n). diff --git a/web/src/shared/shake.ts b/web/src/shared/shake.ts new file mode 100644 index 0000000..3df162f --- /dev/null +++ b/web/src/shared/shake.ts @@ -0,0 +1,52 @@ +// The field shake for a name it won't take (iOS's wrong passcode): a damped swing sideways, about four times in +// half a second, from wherever a shake under way has it, so another one starts over without a jump; and its +// outline goes red at once and fades back to what it is. Only their own animations are touched (the field's +// transitions go on). With less motion asked for it doesn't move; the outline still says it. Used by the portal +// and the admin both (shared/name-guard.ts). + +const FRAMES = 30; +const SWING = Array.from({ length: FRAMES + 1 }, (_, i) => { + const t = i / FRAMES; + return 14 * Math.exp(-4.2 * t) * Math.sin(t * Math.PI * 2 * 3.6); +}); + +/** How long the outline stays red, then how long it takes to fade back, in ms. */ +const RED_HOLD = 700; +const RED_FADE = 800; + +/** + * The outline red at once (a 1.5 px ring: inside the portal's field, as its focus ring is; around the admin's + * input), then back to whatever the field shows now, focused or not. Another one starts red again. + */ +function redden(el: HTMLElement) { + el.getAnimations() + .filter((a) => a.id === 'redden') + .forEach((a) => a.cancel()); + const cs = getComputedStyle(el); + const inset = el.classList.contains('field') ? 'inset ' : ''; + const red = `${inset}0 0 0 1.5px ${cs.getPropertyValue('--bad').trim() || '#e5484d'}`; + const all = RED_HOLD + RED_FADE; + // No last frame: it fades into the field's own ring as it is then, a focus ring still coming in included. + el.animate( + [ + { boxShadow: red, offset: 0 }, + { boxShadow: red, offset: RED_HOLD / all, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' }, + ], + { duration: all, id: 'redden' }, + ); +} + +/** `ring: false` for a field drawn without one (a name edited in place on its card): it only moves. */ +export function shake(el: HTMLElement, o: { ring?: boolean } = {}) { + if (o.ring !== false) redden(el); + if (typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches) return; + const tr = getComputedStyle(el).transform; + const from = tr && tr !== 'none' ? new DOMMatrix(tr).m41 : 0; + el.getAnimations() + .filter((a) => a.id === 'shake') + .forEach((a) => a.cancel()); + el.animate( + SWING.map((x, i) => ({ transform: `translateX(${(i === 0 ? from : x).toFixed(2)}px)` })), + { duration: 520, easing: 'linear', id: 'shake' }, + ); +} diff --git a/web/src/shared/types.ts b/web/src/shared/types.ts index 86c43f4..a92ae6a 100644 --- a/web/src/shared/types.ts +++ b/web/src/shared/types.ts @@ -5,6 +5,35 @@ export type Kind = 'computer' | 'phone' | 'tablet' | 'router' | 'other'; export type PersonState = 'active' | 'paused' | 'expired' | 'quota' | 'hours' | 'no_server' | 'server_off'; export type Pair = [number, number]; // [rx, tx] from the router's point of view +/** + * A device's link failing in a named way (the agent's watcher), shown once it + * held 3 minutes: trying (it knocks, never finishes connecting), shared (one + * configuration on two devices), dropped (connected, but the router drops + * what it sends), unstable (the connection keeps breaking). + */ +export type LinkState = 'trying' | 'shared' | 'dropped' | 'unstable'; + +export interface DeviceLink { + state: LinkState; + /** When it began (router clock). */ + since: number; +} + +/** + * What a device's link does right now, without that hold, for the set-up + * sheet: trying (its initiations reach the router, no handshake follows), + * flowing (online, data came in during this session), nodata (online for + * 15 s with nothing but handshakes and keepalives in, and the router + * answering what it dropped: an old address in its configuration). + */ +export type SetupState = 'trying' | 'flowing' | 'nodata'; + +export interface DeviceSetup { + state: SetupState; + /** When the watcher first saw it (router clock). */ + since: number; +} + export interface Device { id: string; name: string; @@ -25,6 +54,23 @@ export interface Device { browser_key: boolean; /** Its configuration changed (networks, DNS, keys...) since it was last shown or downloaded. */ config_stale: boolean; + // How it connects (set by the admin, LAN Bypass also by the person when adding it). + /** LAN Bypass: its own local network stays outside the tunnel (chosen when it was added). */ + lan_bypass: boolean; + /** Its own MTU; 0 = the server's (automatic by kind and disguise). */ + mtu: number; + /** Its own keep-alive in seconds (0 = off); null = the server's. */ + keepalive: number | null; + /** The MTU and keep-alive its configuration carries now; null without a server. */ + mtu_used: number | null; + keepalive_used: number | null; + /** Its link failing in a named way; null when it is not. */ + link: DeviceLink | null; + /** + * What its link does right now (the set-up sheet); null for none of these. Without the router's agent a session + * that lives counts as flowing (nobody tells data from a bare handshake then). + */ + setup: DeviceSetup | null; } export interface Person { @@ -122,7 +168,10 @@ export interface Server { /** The newest handshake from a public address that is not the router's own (0: never). */ reached?: number; online: number; + /** The disguise parameters, without the header protection key: only device configurations carry it. */ obf: Record; + /** The disguise has a header protection key (AmneziaWG 3.1). */ + hpk: boolean; } export interface DayUsage { @@ -182,6 +231,8 @@ export interface AwgCaps { kmod?: string | null; /** The two differ: a feature counts only when both have it. */ mismatch?: boolean; + /** An installed kernel module waits for a reboot (kmod is the one that runs until then). */ + pending?: boolean; } /** Whether AmneziaWG can run here: tools and kernel module installed, the module loaded, netifd's proto handler present. */ diff --git a/web/src/shared/vpnkey.ts b/web/src/shared/vpnkey.ts index 79015a4..dc7d4af 100644 --- a/web/src/shared/vpnkey.ts +++ b/web/src/shared/vpnkey.ts @@ -4,14 +4,19 @@ import type { ClientConfig } from './types'; +/** + * What a parameter the server does not set reads as. S3 and S4 stay empty: the + * app names a key "AmneziaWG (version 2)" when either is there (awgVersionOf in + * amnezia-client), and every platform skips an empty one. + */ const DEFAULTS: Record = { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', - s3: '0', - s4: '0', + s3: '', + s4: '', h1: '1', h2: '2', h3: '3', @@ -94,8 +99,11 @@ export function amneziaJson(cfg: ClientConfig, description: string): Record { + const g: Glide = { x, v: 0, t }; + const out: number[] = []; + for (let i = 0; i < 200 && glideStep(g, frames); i++) out.push(g.x); + out.push(g.x); + return out; +}; + +describe('caret glide', () => { + it('is 90% of the way in about 134 ms (8–9 frames), a touch over, then rests exactly on its target', () => { + const xs = run(0, 100); + expect(xs[7]).toBeLessThan(90); + expect(xs[8]).toBeGreaterThanOrEqual(90); + const peak = Math.max(...xs); + expect(peak).toBeGreaterThan(101); + expect(peak).toBeLessThan(103); + expect(xs.at(-1)).toBe(100); + expect(xs.length).toBeLessThan(40); + }); + + it('goes the same way to the left', () => { + const xs = run(100, 0); + expect(xs[8]).toBeLessThanOrEqual(10); + expect(Math.min(...xs)).toBeGreaterThan(-3); + expect(xs.at(-1)).toBe(0); + }); + + it('takes a late frame as up to 2.5 frames, and is simply there after a long gap', () => { + const one: Glide = { x: 0, v: 0, t: 100 }; + glideStep(one, 2.5); + const late: Glide = { x: 0, v: 0, t: 100 }; + glideStep(late, 6); + expect(late.x).toBeCloseTo(one.x, 9); + const gone: Glide = { x: 0, v: 3, t: 100 }; + expect(glideStep(gone, 60)).toBe(false); + expect(gone).toEqual({ x: 100, v: 0, t: 100 }); + }); + + it('rests at once where it already is', () => { + const g: Glide = { x: 42, v: 0, t: 42 }; + expect(glideStep(g, 1)).toBe(false); + expect(g.x).toBe(42); + }); +}); + +/** A font of 10 px a letter, in an input 16 px from the field's edge and 200 px wide. */ +const mono = (s: string) => s.length * 10; +const field = (o: Partial): FieldText => ({ + value: 'Pixel 9', + start: 0, + end: 0, + backward: false, + left: 16, + width: 200, + scroll: 0, + ...o, +}); + +describe('caret places', () => { + it('puts a caret after the text before it', () => { + expect(places(field({ start: 0, end: 0 }), mono)).toEqual({ caret: 16, start: 16, end: 16, range: false }); + expect(places(field({ start: 5, end: 5 }), mono)).toEqual({ caret: 66, start: 66, end: 66, range: false }); + expect(places(field({ start: 7, end: 7 }), mono).caret).toBe(86); + }); + + it('gives a selection both ends, the caret at the end it was made toward', () => { + expect(places(field({ start: 1, end: 5 }), mono)).toEqual({ caret: 66, start: 26, end: 66, range: true }); + expect(places(field({ start: 1, end: 5, backward: true }), mono)).toEqual({ caret: 26, start: 26, end: 66, range: true }); + }); + + it('follows the text as the input scrolls it', () => { + const long = 'Living room television'; + // 220 px of text in 200 px: scrolled to its end, the caret stands on the input's right edge. + expect(places(field({ value: long, start: 22, end: 22, scroll: 20 }), mono).caret).toBe(216); + expect(places(field({ value: long, start: 12, end: 12, scroll: 20 }), mono).caret).toBe(116); + }); + + it('stops a selection at the input edges, so the wash never runs under the go button', () => { + const long = 'Living room television'; + expect(places(field({ value: long, start: 0, end: 22 }), mono)).toEqual({ caret: 216, start: 16, end: 216, range: true }); + expect(places(field({ value: long, start: 0, end: 22, scroll: 20 }), mono)).toEqual({ caret: 216, start: 16, end: 216, range: true }); + }); + + it('measures only the text before each end', () => { + const seen: string[] = []; + places(field({ value: 'iPad', start: 1, end: 3 }), (s) => { + seen.push(s); + return mono(s); + }); + expect(seen).toEqual(['i', 'iPa']); + }); +}); diff --git a/web/tests/demo.test.ts b/web/tests/demo.test.ts index 8592132..5097c4b 100644 --- a/web/tests/demo.test.ts +++ b/web/tests/demo.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { createRouter, type DemoDb, type Keep } from '../src/portal/demo/router'; import { SCENARIOS, hoursAway, monthDays } from '../src/portal/demo/data'; +import { wayState } from '../src/portal/way'; import type { State } from '../src/portal/state'; import type { AwgConfig } from '../src/shared/types'; @@ -105,6 +106,35 @@ describe('demo data', () => { expect(Math.abs(days.reduce((a, [rx, tx]) => a + rx + tx, 0) - 1000)).toBeLessThanOrEqual(19); }); + it('holds the device being set up in the state the visitor picks', () => { + const { r, state, later } = demo('normal'); + const { id } = r.answer('POST', 'devices', { name: 'Laptop', kind: 'computer' }).body as { id: string }; + expect(r.settingUp()).toBe(id); + const opened = (state() as State & { now: number }).now; + later(1); + const way = () => + wayState( + state().person.devices.find((d) => d.id === id), + opened, + ); + r.holdWay(id, 'trying'); + later(60); + expect(way()).toBe('trying'); + expect(r.wayOf(id)).toBe('trying'); + r.holdWay(id, 'nodata'); + later(1); + expect(way()).toBe('nodata'); + r.holdWay(id, 'waiting'); + later(60); + expect(way()).toBe('waiting'); + r.holdWay(id, 'connected'); + expect(way()).toBe('connected'); + expect(r.wayOf(id)).toBe('auto'); + // Removed: nothing is being set up. + r.answer('POST', `devices/${id}`, { action: 'delete' }); + expect(r.settingUp()).toBe(null); + }); + it('keeps the hours scenario outside its window', () => { expect(hoursAway(new Date(2026, 9, 19, 22, 30).getTime() / 1000)).toBe('00:00-08:00'); expect(hoursAway(new Date(2026, 9, 19, 9).getTime() / 1000)).toBe('11:00-19:00'); diff --git a/web/tests/events.test.ts b/web/tests/events.test.ts index 294b2c9..37912f4 100644 --- a/web/tests/events.test.ts +++ b/web/tests/events.test.ts @@ -7,8 +7,11 @@ import { categoryOf, changedText, daysOf, + deviceChangedText, eventBy, isProblem, + linkStatesText, + linkStateText, logText, noteText, reasonText, @@ -74,6 +77,39 @@ describe('events', () => { }); }); +describe('a device’s link', () => { + const people = [{ id: 'p1', name: 'Myata', devices: [{ id: 'd1', name: 'Phone' }] }] as unknown as Person[]; + const ev = (e: Partial) => ({ ts: 1, person: 'p1', device: 'd1', ...e }) as LogEvent; + it('says what its state means', () => { + expect(linkStateText('trying')).toEqual({ + title: 'Unable to complete the handshake', + line: 'The device’s network may be blocking the connection.', + }); + expect(linkStateText('dropped')?.title).toBe('Handshake complete, but no data'); + expect(linkStateText('shared')?.title).toBe('On two devices at once'); + expect(linkStateText('unstable')?.title).toBe('Connection keeps dropping'); + expect(linkStateText('flowing')).toBeNull(); + expect(linkStatesText('trying, unstable')).toBe('Unable to complete the handshake, Connection keeps dropping'); + expect(linkStatesText('later')).toBe('later'); + }); + it('puts its failing and recovering into Activity', () => { + expect(categoryOf('device_failing')).toBe('problems'); + expect(categoryOf('device_recovered')).toBe('problems'); + const st = { people }; + expect(text(eventText(st, ev({ type: 'device_failing', detail: 'trying, shared' })))).toBe( + 'Device Myata · Phone has a connection problem · Unable to complete the handshake, On two devices at once', + ); + expect(text(eventText(st, ev({ type: 'device_recovered', detail: 'unstable' })))).toBe('Device Myata · Phone connects normally again'); + }); + it('names the link options the admin changed', () => { + expect(deviceChangedText('mtu, keepalive, lan_bypass')).toBe('MTU, keep-alive, LAN Bypass'); + expect(deviceChangedText('something new')).toBe('something new'); + expect(text(eventText({ people }, ev({ type: 'device_changed', by: 'admin', detail: 'mtu' })))).toBe( + 'You changed device Phone of Myata · MTU', + ); + }); +}); + describe('the router’s words', () => { it('puts the admin’s own changes into sentences', () => { expect(adminSentence('changed', 'server', 'Home')).toEqual({ text: 'You changed server %s', named: true }); diff --git a/web/tests/format.test.ts b/web/tests/format.test.ts index 24b4e02..a44b023 100644 --- a/web/tests/format.test.ts +++ b/web/tests/format.test.ts @@ -1,5 +1,22 @@ import { describe, expect, it } from 'vitest'; -import { addDays, addMonthsClamped, date, dayDiff, daysLeft, endsIn, endsSoon, fmtDay, kb, shiftDay, todayOf } from '../src/shared/format'; +import { + addDays, + addMonthsClamped, + date, + dayDiff, + daysLeft, + defaultName, + DEVICE_NAME_MAX, + deviceNameFits, + endsIn, + endsSoon, + fitName, + fmtDay, + kb, + shiftDay, + todayOf, + validDeviceName, +} from '../src/shared/format'; import { plural } from '../src/shared/i18n'; describe('months', () => { @@ -64,3 +81,48 @@ describe('numbers', () => { expect(kb(3 * 1048576)).toBe('3.0 MB'); }); }); + +describe('device names', () => { + it('take letters of any language, digits, spaces and - _ . up to the limit', () => { + expect(DEVICE_NAME_MAX).toBe(20); + expect(validDeviceName('Kitchen iPad')).toBe(true); + expect(validDeviceName('my-pc_2.home')).toBe(true); + expect(validDeviceName('Мой ноутбук')).toBe(true); + expect(validDeviceName('Ordinateur de Zoé')).toBe(true); + expect(validDeviceName('客厅电视')).toBe(true); + expect(validDeviceName('99999999999999999999')).toBe(true); + expect(validDeviceName('999999999999999999999')).toBe(false); + expect(validDeviceName('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛ')).toBe(true); + expect(validDeviceName('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛД')).toBe(false); + expect(validDeviceName(' Kitchen iPad ')).toBe(true); + expect(validDeviceName("Bob's iPhone")).toBe(false); + expect(validDeviceName('$(reboot)')).toBe(false); + expect(validDeviceName('Phone 📱')).toBe(false); + expect(validDeviceName('Офис™')).toBe(false); + expect(validDeviceName('«Дом»')).toBe(false); + expect(validDeviceName('a\u200bb')).toBe(false); + expect(validDeviceName('')).toBe(false); + expect(validDeviceName(' ')).toBe(false); + // As it is typed: empty is fine (a submit says so), a space at the end too. + expect(deviceNameFits('')).toBe(true); + expect(deviceNameFits('Kitchen ')).toBe(true); + expect(deviceNameFits('Kitchen!')).toBe(false); + }); + + it('strips a made-up name of what the router refuses and cuts it to fit, the number too', () => { + expect(fitName('Phone')).toBe('Phone'); + expect(fitName('Phone', ' 2')).toBe('Phone 2'); + expect(fitName('Galaxy S24+')).toBe('Galaxy S24'); + expect(fitName('Samsung Galaxy S24 Ultra')).toBe('Samsung Galaxy S24 U'); + expect(fitName('Pixel 9 Pro (XL)', ' 2')).toBe('Pixel 9 Pro XL 2'); + expect(fitName('Компьютер с Windows', ' 2')).toBe('Компьютер с Window 2'); + // Not left ending in a space before the number. + expect(fitName('Living room TV ab xy', ' 2')).toBe('Living room TV ab 2'); + expect(validDeviceName(fitName('Redmi Note 13 Pro+ 5G', ' 12'))).toBe(true); + }); + + it('names a device after its kind', () => { + expect(defaultName('phone')).toBe('Phone'); + expect(defaultName('other')).toBe('Device'); + }); +}); diff --git a/web/tests/home-nets.test.ts b/web/tests/home-nets.test.ts new file mode 100644 index 0000000..1bbbd35 --- /dev/null +++ b/web/tests/home-nets.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest'; + +import { homeOf, netsLabel } from '../src/shared/format'; +import type { Person, Server } from '../src/shared/types'; + +describe('home networks a LAN Bypass device still sends home', () => { + it('reads a /24 as its first three numbers', () => { + expect(netsLabel(['10.0.1.0/24'])).toBe('10.0.1.x'); + expect(netsLabel(['192.168.1.0/24', '10.8.0.0/16'])).toBe('192.168.1.x, 10.8.0.0/16'); + expect(netsLabel([])).toBe(''); + }); + + it('takes the server home networks a person with home and internet access reaches', () => { + const srv = { + home: [ + { dev: 'br-lan', nets: ['10.0.1.0/24'] }, + { dev: 'br-iot', nets: ['10.0.9.0/24'] }, + ], + } as Server; + const p = (o: Partial) => ({ access: 'both', ...o }) as Person; + expect(homeOf(p({}), srv)).toEqual(['10.0.1.0/24', '10.0.9.0/24']); + expect(homeOf(p({ home_nets: ['br-iot'] }), srv)).toEqual(['10.0.9.0/24']); + expect(homeOf(p({ access: 'internet' }), srv)).toEqual([]); + expect(homeOf(p({ access: 'lan' }), srv)).toEqual([]); + expect(homeOf(p({}), undefined)).toEqual([]); + }); +}); diff --git a/web/tests/meter.test.ts b/web/tests/meter.test.ts new file mode 100644 index 0000000..1fb146d --- /dev/null +++ b/web/tests/meter.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from 'vitest'; +import { LiveMeter } from '../src/admin/state/meter'; +import type { Meter, MeterPoint } from '../src/admin/api'; + +/** Points at ts from..to, one a second; server `a` at [ts, 2·ts], `b` only on even seconds. */ +const points = (from: number, to: number): MeterPoint[] => + Array.from({ length: to - from + 1 }, (_x, i): MeterPoint => { + const ts = from + i; + return { ts, servers: ts % 2 ? { a: [ts, 2 * ts] } : { a: [ts, 2 * ts], b: [1, 1] } }; + }); +const meter = (pts: MeterPoint[], now = pts.length ? pts[pts.length - 1].ts + 1 : 0): Meter => ({ + now, + want: 10, + keep: 120, + ts: pts.length ? pts[pts.length - 1].ts : 0, + points: pts, +}); + +describe('live meter', () => { + it('asks for everything first, then for what it lacks', () => { + const m = new LiveMeter(); + expect(m.since(0)).toBe(0); + m.take({ meter: meter(points(1001, 1010)) }, 10_000); + expect(m.since(11_000)).toBe(1010); + // An answer that repeats what is kept adds nothing twice. + m.take({ meter: meter(points(1005, 1012)) }, 11_000); + const s = m.speed('a', 11_500); + expect(s.pts.map((p) => p[0])).toEqual(Array.from({ length: 12 }, (_x, i) => 1001 + i)); + expect(s.pts[0]).toEqual([1001, 1001, 2002]); + }); + + it('keeps two minutes, the newest point on the right edge', () => { + const m = new LiveMeter(); + m.take({ meter: meter(points(1001, 1200)) }, 0); + const s = m.speed('a', 0); + expect(s.pts).toHaveLength(120); + expect(s.pts[0][0]).toBe(1081); + expect(s.xs[0]).toBe(0); + expect(s.xs[119]).toBe(1); + expect(s.xs[60]).toBeCloseTo(60 / 119); + }); + + it('gives a server only its own seconds, placed against the newest point of all', () => { + const m = new LiveMeter(); + m.take({ meter: meter(points(1001, 1011)) }, 0); + const s = m.speed('b', 0); + expect(s.pts.map((p) => p[0])).toEqual([1002, 1004, 1006, 1008, 1010]); + expect(s.xs[s.xs.length - 1]).toBeCloseTo(1 - 1 / 119); + expect(m.speed('nope', 0).pts).toEqual([]); + }); + + it('reads the speed now from a fresh point only', () => { + const m = new LiveMeter(); + m.take({ meter: meter(points(1001, 1010), 1011) }, 0); + expect(m.speed('a', 0)).toMatchObject({ rx: 1010, tx: 2020, error: null }); + // The agent stopped: its last point stays behind the router's clock. + m.take({ meter: meter([], 1030) }, 1000); + expect(m.speed('a', 1000)).toMatchObject({ rx: 0, tx: 0 }); + expect(m.speed('a', 1000).pts).toHaveLength(10); + }); + + it('starts over when what it kept is no longer live', () => { + const m = new LiveMeter(); + m.take({ meter: meter(points(1001, 1010)) }, 0); + expect(m.speed('a', 6000).pts).toEqual([]); + expect(m.since(6000)).toBe(0); + // The watcher freed its ring meanwhile: the next look starts from what it has now. + m.take({ meter: meter(points(1100, 1102)) }, 6000); + expect(m.speed('a', 6000).pts.map((p) => p[0])).toEqual([1100, 1101, 1102]); + }); + + it('starts over when the router clock goes back', () => { + const m = new LiveMeter(); + m.take({ meter: meter(points(1001, 1010)) }, 0); + // Stepped back 600 s: the router kept only its newer points, all before what the page has. + m.take({ meter: { ...meter([], 411), ts: 410 } }, 1000); + expect(m.since(1000)).toBe(0); + expect(m.speed('a', 1000)).toMatchObject({ pts: [], rx: 0, tx: 0 }); + m.take({ meter: meter(points(405, 410), 411) }, 2000); + expect(m.speed('a', 2000)).toMatchObject({ rx: 410, tx: 820 }); + }); + + it('never takes a point dated after the router clock for the speed now', () => { + const m = new LiveMeter(); + m.take({ meter: meter(points(1001, 1010), 900) }, 0); + expect(m.speed('a', 0)).toMatchObject({ rx: 0, tx: 0 }); + }); + + it('waits without words a moment before saying it is collecting', () => { + const m = new LiveMeter(); + expect(m.speed('a', 0).early).toBe(true); + // The first call of a look finds nothing written out yet. + m.take({ meter: meter([], 1000) }, 0); + m.take({ meter: meter([], 1001) }, 1000); + expect(m.speed('a', 1000).early).toBe(true); + m.take({ meter: meter([], 1002) }, 2000); + expect(m.speed('a', 2000).early).toBe(false); + m.take({ meter: meter(points(1001, 1003)) }, 3000); + expect(m.speed('a', 3000).early).toBe(false); + // A server with no seconds of its own while others have some: collecting, not early. + expect(m.speed('nope', 3000)).toMatchObject({ pts: [], early: false }); + }); + + it('says it cannot read the meter only after a few failures in a row', () => { + const m = new LiveMeter(); + m.take({ meter: meter(points(1001, 1010)) }, 0); + m.take({ error: 'Access denied' }, 1000); + m.take({ error: 'Access denied' }, 2000); + expect(m.speed('a', 2000)).toMatchObject({ error: null }); + expect(m.speed('a', 2000).pts).toHaveLength(10); + m.take({ error: 'Access denied' }, 3000); + expect(m.speed('a', 3000).error).toBe('Access denied'); + m.take({ meter: meter(points(1011, 1013)) }, 4000); + expect(m.speed('a', 4000).error).toBeNull(); + }); +}); diff --git a/web/tests/motion.test.ts b/web/tests/motion.test.ts index 7837b84..6c6c22b 100644 --- a/web/tests/motion.test.ts +++ b/web/tests/motion.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { BOUNCY, SMOOTH, dismisses, rubber, spring } from '../src/portal/motion'; +import { BOUNCY, SMOOTH, dismisses, rubber, spring, unrubber } from '../src/portal/motion'; describe('motion', () => { it('pulls past an edge with growing resistance, never further than the box', () => { @@ -12,6 +12,12 @@ describe('motion', () => { expect(rubber(100_000, 400)).toBeLessThan(400); }); + it('undoes the rubber: the pull that puts an edge where it stands', () => { + for (const d of [1, 40, 200, 1000]) expect(unrubber(rubber(d, 400), 400)).toBeCloseTo(d, 6); + expect(unrubber(0, 400)).toBe(0); + expect(unrubber(-5, 400)).toBe(0); + }); + it('dismisses a sheet on a flick down or a pull past a third, not on a flick back up', () => { expect(dismisses(12, 0.6, 500)).toBe(true); expect(dismisses(200, 0, 500)).toBe(true); diff --git a/web/tests/netcheck.test.ts b/web/tests/netcheck.test.ts index cf55d6b..31a7d85 100644 --- a/web/tests/netcheck.test.ts +++ b/web/tests/netcheck.test.ts @@ -66,6 +66,8 @@ describe('netcheck', () => { import { chars, circleNameHelp, + deviceKeepaliveHelp, + deviceMtuHelp, dnsHelp, domainHelp, expiresHelp, @@ -112,6 +114,18 @@ describe('field helps', () => { expect(keepaliveHelp('601').bad).toBe(true); expect(keepaliveHelp('0').bad).toBe(false); }); + it('checks a device’s own MTU and keep-alive like the router', () => { + expect(deviceMtuHelp('')).toEqual({ text: 'Empty: automatic. Lower it when big pages hang on this device.', bad: false }); + expect(deviceMtuHelp(' 1400 ').bad).toBe(false); + expect(deviceMtuHelp('1279')).toEqual({ text: 'From 1280 to 1500.', bad: true }); + expect(deviceMtuHelp('1501').bad).toBe(true); + expect(deviceMtuHelp('14OO').bad).toBe(true); + expect(deviceKeepaliveHelp('').bad).toBe(false); + expect(deviceKeepaliveHelp('0').bad).toBe(false); + expect(deviceKeepaliveHelp('600').bad).toBe(false); + expect(deviceKeepaliveHelp('601')).toEqual({ text: 'From 0 to 600 seconds.', bad: true }); + expect(deviceKeepaliveHelp('-1').bad).toBe(true); + }); it('checks limits, quota and dates', () => { expect(limitHelp('0').bad).toBe(true); expect(limitHelp('33').bad).toBe(true); diff --git a/web/tests/qr.test.ts b/web/tests/qr.test.ts index 2a0b479..9dd7a9c 100644 --- a/web/tests/qr.test.ts +++ b/web/tests/qr.test.ts @@ -1,8 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { denseQr, qrSvg } from '../src/shared/qr'; +import { denseQr, qrFits, qrSvg, scannable } from '../src/shared/qr'; const LINK = 'https://engage.example.eu:4500/abcdef-ghijkl-mnopqr'; const KEY = `vpn://${'A1b2C3d4'.repeat(180)}`; +/** An AmneziaVPN key on Maximum where the browser cannot compress it: past what version 40-L holds. */ +const HUGE = 'A1b2C3d4'.repeat(425); describe('qr', () => { it('draws the plain look as black squares on white in one path', () => { @@ -37,4 +39,26 @@ describe('qr', () => { expect(qrSvg(LINK, 3, true, 'night')).toContain('a0.42 0.42'); expect(qrSvg(KEY, 3, true, 'night')).toContain('a0.48 0.48'); }); + + it('says a 3.4 KB text does not fit instead of throwing, and keeps it from the camera', () => { + expect(HUGE.length).toBe(3400); + expect(() => qrFits(HUGE)).not.toThrow(); + expect(qrFits(HUGE)).toBe(false); + expect(scannable(HUGE)).toBe(false); + // It still fits a code, but too fine to read off a screen. + expect(qrFits(HUGE.slice(0, 2000))).toBe(true); + expect(scannable(HUGE.slice(0, 2000))).toBe(false); + expect(scannable(KEY)).toBe(true); + expect(scannable(LINK)).toBe(true); + }); + + it('draws the same code after checking it fits, and the next text as itself', () => { + const fresh = qrSvg(KEY, 3, true, 'night'); + qrFits(LINK); + const link = qrSvg(LINK, 3, true, 'night'); + expect(qrFits(KEY)).toBe(true); + expect(qrSvg(KEY, 3, true, 'night')).toBe(fresh); + expect(qrSvg(LINK, 3, true, 'night')).toBe(link); + expect(link).not.toBe(fresh); + }); }); diff --git a/web/tests/seg.test.ts b/web/tests/seg.test.ts new file mode 100644 index 0000000..b63d9f8 --- /dev/null +++ b/web/tests/seg.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; +import { labelFade } from '../src/portal/ui/seg'; + +describe('picker names on a pick', () => { + it('blurs the picked name in a beat after the pill, and folds a shown one whole', () => { + expect(labelFade({ width: 0, full: 90, opacity: 0 }, true)).toEqual({ duration: 280, delay: 70 }); + expect(labelFade({ width: 90, full: 90, opacity: 1 }, false)).toEqual({ duration: 220, delay: 0 }); + }); + + it('runs only what is left of a fade turned back half-way', () => { + // Picked again while it was folding away: it comes back from 40% at once. + const back = labelFade({ width: 36, full: 90, opacity: 0.4 }, true); + expect(back.duration).toBeCloseTo(168); + expect(back.delay).toBeCloseTo(42); + // Left while it was still coming in: it folds from the wider of its width and its opacity. + expect(labelFade({ width: 45, full: 90, opacity: 0.2 }, false).duration).toBeCloseTo(110); + expect(labelFade({ width: 9, full: 90, opacity: 0.7 }, false).duration).toBeCloseTo(154); + }); + + it('leaves a folded name alone and a shown one picked again as it is', () => { + expect(labelFade({ width: 0, full: 90, opacity: 0 }, false).duration).toBe(0); + expect(labelFade({ width: 0.4, full: 90, opacity: 0.001 }, false).duration).toBe(0); + expect(labelFade({ width: 90, full: 90, opacity: 1 }, true)).toEqual({ duration: 0, delay: 0 }); + }); + + it('keeps to its bounds when the readings are off (no width to measure, opacity past 1)', () => { + expect(labelFade({ width: 30, full: 0, opacity: 0 }, false).duration).toBe(0); + expect(labelFade({ width: 200, full: 90, opacity: 0 }, false).duration).toBe(220); + expect(labelFade({ width: 0, full: 90, opacity: 1.2 }, true).duration).toBe(0); + }); +}); diff --git a/web/tests/setup.test.ts b/web/tests/setup.test.ts index e0e6221..2d2f7a6 100644 --- a/web/tests/setup.test.ts +++ b/web/tests/setup.test.ts @@ -68,6 +68,25 @@ describe('setup', () => { expect(sameDevice('phone', 'unknown')).toBe(false); }); + it('sets something else (a TV, a NAS) up from a phone as a device elsewhere, and on a computer’s system as itself', () => { + expect(sameDevice('other', 'ios')).toBe(false); + expect(sameDevice('other', 'android')).toBe(false); + expect(sameDevice('other', 'windows')).toBe(true); + expect(sameDevice('other', 'mac')).toBe(true); + expect(sameDevice('other', 'linux')).toBe(true); + expect(sameDevice('other', 'unknown')).toBe(false); + }); + + it('sets something else up as itself when the page came from its own set-up link (an Android TV)', () => { + expect(sameDevice('other', 'android', true)).toBe(true); + expect(sameDevice('other', 'ios', true)).toBe(true); + expect(sameDevice('other', 'unknown', true)).toBe(false); + // A phone's, a computer's or a router's link opened elsewhere: the platform still decides. + expect(sameDevice('phone', 'mac', true)).toBe(false); + expect(sameDevice('computer', 'android', true)).toBe(false); + expect(sameDevice('router', 'linux', true)).toBe(false); + }); + it('lists the apps a disguise allows, AmneziaVPN first', () => { expect(appsFor('max').map((a) => a.id)).toEqual(['vpn', 'awg']); expect(appsFor('off').map((a) => a.id)).toEqual(['vpn', 'awg', 'wg']); diff --git a/web/tests/shared.test.ts b/web/tests/shared.test.ts index abf2dab..cc43fe1 100644 --- a/web/tests/shared.test.ts +++ b/web/tests/shared.test.ts @@ -64,12 +64,50 @@ describe('vpn:// keys', () => { expect(j.dns1).toBe('10.0.1.1'); const last = JSON.parse(j.containers[0].awg.last_config); expect(last.Jc).toBe('4'); - expect(last.S3).toBe('0'); expect(last.H1).toBe('11'); expect(last.port).toBe(51830); expect(last.config).toContain('\r\n'); }); + it('leaves S3 and S4 empty when the server sets none, so the app does not call the key version 2', () => { + const last = (c: ClientConfig) => JSON.parse((amneziaJson(c, 'x') as any).containers[0].awg.last_config); + expect(last(cfg).S3).toBe(''); + expect(last(cfg).S4).toBe(''); + expect(last(cfg).S1).toBe('20'); + const off = { + ...cfg, + amnezia: { ...cfg.amnezia, obfuscation: { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' } }, + }; + expect(last(off).S3).toBe(''); + expect(last(off).Jc).toBe('0'); + expect(last(off).I1).toBe(''); + const bal = { ...cfg, amnezia: { ...cfg.amnezia, obfuscation: { ...cfg.amnezia.obfuscation, s3: '24', s4: '8' } } }; + expect(last(bal).S3).toBe('24'); + expect(last(bal).S4).toBe('8'); + }); + + it('gives the one DNS server as both, so the app adds none of its own', () => { + const json = (dns: string[]) => amneziaJson({ ...cfg, amnezia: { ...cfg.amnezia, dns } }, 'x') as any; + expect(json(['10.0.1.1'])).toMatchObject({ dns1: '10.0.1.1', dns2: '10.0.1.1' }); + expect(json(['10.0.1.1', '1.1.1.1'])).toMatchObject({ dns1: '10.0.1.1', dns2: '1.1.1.1' }); + // Home network only, without the home DNS: nothing to give. + expect(json([]).dns1).toBeUndefined(); + expect(json([]).dns2).toBeUndefined(); + }); + + it('passes the keep-alive through as the router sends it: a range on 3.1, a number before', () => { + const awg = (persistent_keep_alive: string, obfuscation: Record) => + (amneziaJson({ ...cfg, amnezia: { ...cfg.amnezia, persistent_keep_alive, obfuscation } }, 'x') as any).containers[0].awg; + const max = awg('25-35', { ...cfg.amnezia.obfuscation, header_protection_key: 'HPK=' }); + expect(JSON.parse(max.last_config).persistent_keep_alive).toBe('25-35'); + expect(JSON.parse(max.last_config).HeaderProtectionKey).toBe('HPK='); + expect(max.protocol_version).toBe('3.1'); + const bal = awg('25', cfg.amnezia.obfuscation); + expect(JSON.parse(bal.last_config).persistent_keep_alive).toBe('25'); + expect(bal.protocol_version).toBe('2'); + expect(JSON.parse(awg('0', {}).last_config).persistent_keep_alive).toBe('0'); + }); + it('produces a qCompress payload AmneziaVPN can read', async () => { const key = await vpnKey(cfg, 'x'); expect(key.startsWith('vpn://')).toBe(true); diff --git a/web/tests/way.test.ts b/web/tests/way.test.ts new file mode 100644 index 0000000..6f5ce9f --- /dev/null +++ b/web/tests/way.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest'; +import { wayState, type WayState } from '../src/portal/way'; +import type { Device, SetupState } from '../src/shared/types'; + +/** When the sheet opened (router clock). */ +const OPENED = 1_792_400_000; + +/** A device as the router sends it while it is being set up: never connected, nothing on its link. */ +function dev(o: Partial = {}): Device { + return { + id: 'd_1', + name: 'Pixel 9', + kind: 'phone', + address: '10.8.0.5', + disabled: false, + created: OPENED - 30, + created_by: 'portal', + online: false, + handshake: 0, + endpoint: '', + active: true, + month: [0, 0], + total: [0, 0], + spark: [], + hostname: 'pixel-9.user.lan', + browser_key: false, + config_stale: false, + lan_bypass: false, + mtu: 0, + keepalive: null, + mtu_used: 1280, + keepalive_used: 25, + link: null, + setup: null, + ...o, + }; +} + +const setup = (state: SetupState, since = OPENED + 5) => ({ state, since }); + +describe('the set-up sheet’s way', () => { + it('waits while the device is not heard from', () => { + expect(wayState(dev(), OPENED)).toBe('waiting'); + // Online with an old handshake, quiet: not this set-up's connection. + expect(wayState(dev({ online: true, handshake: OPENED - 40 }), OPENED)).toBe('waiting'); + }); + + it('shows knocks that never finish whenever they come, before the sheet or after', () => { + expect(wayState(dev({ setup: setup('trying') }), OPENED)).toBe('trying'); + expect(wayState(dev({ setup: setup('trying', OPENED - 60) }), OPENED)).toBe('trying'); + // An older session still counts online while its rekeys fail: still trying. + expect(wayState(dev({ online: true, handshake: OPENED + 2, setup: setup('trying') }), OPENED)).toBe('trying'); + }); + + it('arrives when data flows after a handshake newer than the sheet', () => { + expect(wayState(dev({ online: true, handshake: OPENED + 9, setup: setup('flowing') }), OPENED)).toBe('connected'); + // The router's watcher may lag the handshake by a second: data flowing is what counts, not `online`. + expect(wayState(dev({ online: false, handshake: OPENED + 9, setup: setup('flowing') }), OPENED)).toBe('connected'); + }); + + it('does not arrive on a handshake alone', () => { + expect(wayState(dev({ online: true, handshake: OPENED + 9 }), OPENED)).toBe('waiting'); + expect(wayState(dev({ online: true, handshake: OPENED + 9, setup: setup('nodata') }), OPENED)).toBe('nodata'); + }); + + it('keeps what began before the sheet for the sheet before', () => { + // Already flowing, or already without data, on a handshake older than the sheet: not this set-up's. + expect(wayState(dev({ online: true, handshake: OPENED, setup: setup('flowing', OPENED - 90) }), OPENED)).toBe('waiting'); + expect(wayState(dev({ online: true, handshake: OPENED - 20, setup: setup('nodata', OPENED - 5) }), OPENED)).toBe('waiting'); + }); + + it('goes back to plain waiting when the device goes quiet, offline or away', () => { + expect(wayState(dev({ online: false, handshake: OPENED + 9, setup: null }), OPENED)).toBe('waiting'); + expect(wayState(undefined, OPENED)).toBe('waiting'); + }); + + it('follows a whole set-up: knocks, no data, imported again, connected', () => { + const seen: WayState[] = []; + const answers: Partial[] = [ + {}, + { setup: setup('trying') }, + { setup: setup('trying') }, + // The network let it through, but the phone holds an old configuration. + { online: true, handshake: OPENED + 40 }, + { online: true, handshake: OPENED + 40, setup: setup('nodata', OPENED + 52) }, + // Gone offline: plain waiting, no line of its own. + { online: false, handshake: OPENED + 40 }, + { online: true, handshake: OPENED + 300, setup: setup('flowing', OPENED + 300) }, + ]; + for (const a of answers) { + const st = wayState(dev(a), OPENED); + if (st !== seen[seen.length - 1]) seen.push(st); + } + expect(seen).toEqual(['waiting', 'trying', 'waiting', 'nodata', 'waiting', 'connected']); + }); +});