Dawnline 0.14.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions

- A device is renamed where its name stands on its card: a click on the
  name, Return or Space on it, or Rename in the ⋯ menu turns it into a
  field with the name selected. Return saves, and the words shimmer until
  the router answers. Esc or a click elsewhere puts the old name back. The
  rename window is gone, and the page no longer redraws under a name being
  edited
- Device names take up to 20 characters: letters of any language, digits,
  spaces and - _ . The router refuses anything else when a device is added
  or renamed, so a name can't carry symbols into configurations, file
  names or the AmneziaVPN key. The portal and the admin turn a character
  like that away as it is typed: the field shakes, its outline goes red
  and a short line says why. Suggested names (a phone's model, "Phone 2")
  are stripped of such characters and cut to fit. Names set before this
  stay as they are
- LAN Bypass: Add a device, in the portal and in the admin, has a switch
  that keeps the device's own local network (printer, TV, NAS) reachable
  while it is connected. It is off by default and stays as chosen; the
  admin's device drawer shows it. With home and internet access the switch
  says which addresses still lead to the home network
- Health warns when a server's home network is on one of the subnets home
  routers come with (192.168.0.x, 192.168.1.x and others). People with
  home access who connect from a network on the same addresses reach your
  home instead of their own, LAN Bypass or not
- The router tells when a device can't connect properly. After the problem
  lasts three minutes, the portal card and the admin drawer name it:
  can't finish connecting (the network may block it), connected but no
  data (an outdated configuration, and the card offers Reconnect), on two
  devices at once, or a connection that keeps dropping. Activity lists
  these under Problems, one line per device per hour, and says when the
  device connects normally again
- The set-up sheet's connection line follows what the device does:
  waiting, can't finish, connected, or connected but no data. The sheet
  closes by itself only once data comes through. On the device itself and
  for a router, the steps regroup to what fixes the problem: "Set it up
  again" when the handshake never finishes, "Add the connection again"
  ("Import the configuration again" for a router) when no data comes
- Set-up in the portal: a QR code too long for a camera to read gives its
  place to a code that opens the set-up link (a LAN Bypass configuration
  or a long AmneziaVPN key can be that long). A TV, box or NAS added from
  a phone gets the steps for setting up from another device. Back from
  "Open on the device" keeps the kind, LAN Bypass and the name typed. The
  packet-size note under the kinds is gone
- The portal on phones keeps its place: nothing jumps when an access row
  opens or folds, a notice comes or goes, or Safari redraws the cards. A
  reload, or coming back from the VPN app, opens where the page was. Cards
  glide to their new height, and an animation interrupted half-way goes on
  from where it is instead of snapping. A double click no longer closes
  the sheet it just opened
- In the admin, a device's drawer has its own MTU and keep-alive (empty
  means the server's), each with a Change dialog. A change touches only
  that device's configuration and restarts nothing on the router. Opening
  the drawer no longer counts as handing out the configuration: "Update
  config" stays until the new configuration is shown as a QR code,
  downloaded or copied ("Show the new configuration"). New keys set the
  device up again, as the portal's Reconnect does
- "Speed now" on a server's Overview is live: one point a second over the
  last two minutes, all there as soon as the Overview opens. The agent
  keeps those two minutes in memory and writes them out only while someone
  is looking
- Disguise values that AmneziaWG refuses or crashes on are stopped before
  they reach the kernel. That covers overlapping H1-H4, Jmin above Jmax,
  broken I1-I5 tags, padding under 12 with header protection, and more.
  Import and restore refuse them. After a hand edit in uci, the server's
  tunnel stays down and Health and the service log say why and what to do.
  Errors are full sentences in the reader's language
- The header protection key no longer shows in the status that read-only
  users can see: the Server page says only that the key is set, and each
  device's configuration still has it. The server no longer turns off
  WireGuard's protection against handshake floods (devices keep
  DisableCookies). A device can't be added with a server's own key
- An AmneziaWG update whose kernel module can't be swapped (another
  AmneziaWG interface holds the old one) no longer fails. It is installed,
  the tunnels come back on the old module, and Health and Components say
  the update starts after a reboot. On apk firmware, an install that apk
  left at the old version counts as failed. A module installed by hand is
  recorded, so after a firmware upgrade Health can tell that it is gone
- Dawnline reads only its own tunnels, each one separately. Another
  AmneziaWG interface on the router no longer slows the agent's
  once-a-second check, has its keys read or breaks Dawnline's reads. A
  portal request reads only that person's server: one process however many
  servers there are
- Fewer false disconnects: a tunnel that netifd sets up again no longer
  logs everyone as leaving and coming back, and a device with a long
  keep-alive stays online between handshakes. One configuration on two
  devices isn't logged as roaming every few seconds, and new keys end the
  old session at once. A tunnel that is missing devices is synced within a
  minute, and traffic across a tunnel restart is no longer undercounted
- Renaming a server no longer restarts its tunnel. If a tunnel's interface
  is edited outside Dawnline (LuCI, uci), the watchdog sets it up again
  with Dawnline's settings and names only the changed options. The routing
  rules for "Internet like a home device" change one at a time, new ones
  first, so traffic never falls between them. Health and the Server page
  warn when the address's AAAA record isn't this router's, or the router
  has no public IPv6: devices that prefer IPv6 fail to connect
- The README screenshots come in English and Russian; the portal's are
  taken from its demo. The demo has a switch beside × in the set-up sheet
  to show each state of the connection line. In Russian, long labels in
  the admin's wide option buttons wrap under their icon. DESIGN.md
  describes the switch, renaming on the card, the shimmer, the shake and
  how the portal scrolls. New tests cover link states, the meter, access,
  Health, firewall rules, network settings and packages
This commit is contained in:
Aemeath committed 2026-10-22 00:11:50 +03:00
1 parent 58492be021
commit dc0f159447
155 files changed
+11062 -1461

No files matched your search

+63 -4
View File
@@ -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<string, Pair>;
}
/**
* 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>('status', ['days']);
const deviceUpdateRaw = call<unknown>('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>('meter', ['since']),
personUpdate,
settingsGet: call<SettingsData>('settings_get'),
portalInfo: call<PortalInfo>('portal_info'),
@@ -501,9 +558,11 @@ export const api = {
personRegen: call<{ link: string | null; removed: number }>('person_regen', ['id', 'remove']),
personDelete: call<unknown>('person_delete', ['id']),
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
deviceConfig: call<ClientConfig>('device_config', ['id']),
deviceUpdate: call<unknown>('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<ClientConfig>('device_config', ['id', 'issue']),
deviceUpdate,
deviceDelete: call<unknown>('device_delete', ['id']),
deviceRotate: call<ClientConfig>('device_rotate', ['id']),
apply: call<unknown>('apply'),
+13 -8
View File
@@ -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<string, string>): HTMLElement | null {
const has = (k: string) => o[k] != null && o[k] !== '';
function paramsView(o: Record<string, string>, 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<string, string>): 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<string, string>): 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' }, [
+147
View File
@@ -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')),
]),
],
];
}
+127 -21
View File
@@ -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<HTMLElement>, 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);
+6
View File
@@ -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',
+39 -1
View File
@@ -25,6 +25,8 @@ const CATEGORY: Record<string, LogCategory> = {
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<string, string> = { 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<string, [string, string]> = {
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,
+22 -2
View File
@@ -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<Status, 'people' | 'servers'>;
@@ -28,6 +41,8 @@ const EVENT_TONE: Record<string, string> = {
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<Status, 'people'>, 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<Status, 'people'>, 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}` : ''}`)];
}
+25
View File
@@ -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();
+24 -11
View File
@@ -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<string, HTMLElement> = {};
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. */
+1
View File
@@ -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),
};
}
+2 -2
View File
@@ -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');
+1
View File
@@ -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,
};
}
+22 -1
View File
@@ -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<Status>;
/** The live meter's last 2 minutes, every server's (the Overviews' Speed now), and its poller. */
meter = new LiveMeter();
meterPoller?: Poller<MeterAnswer>;
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<MeterAnswer>({
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<Section, () => 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;
},
+108
View File
@@ -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,
};
}
}
+4 -1
View File
@@ -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); }
+113 -28
View File
@@ -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(
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
`<path d="M${dl.join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${dl.join(' L')}" class="line"/>` +
`<path d="M${ul.join(' L')}" class="line up"/></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(
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
`<path d="${d.area}" class="area"/><path d="${d.down}" class="line"/><path d="${d.up}" class="line up"/></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(
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
`<path class="area"/><path class="line"/><path class="line up"/></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);