Dawnline 0.4.0
Build packages / Version (push) Waiting to run

- Components tab replaces Updates: Dawnline, the AmneziaWG build for this
  firmware (Slava-Shchipunov 2.0 or 2Grey 3.1, Russian translation) and
  the system packages Dawnline adds, each checked, installed, reinstalled
  or rolled back in place, with What's new, versions and an activity log
- Automatic updates: daily check, install at a set time or right away,
  per component; AmneziaWG is left out by default and an automatic run
  never switches its build or generation
- Downloads verified against GitHub's sha256; mirrors are used only when
  GitHub is unreachable and the hash is known
- New installer: checks firmware, clock, space and DNS, lets you pick a
  release, shows the plan and asks first; --dry-run
- New uninstaller removes everything Dawnline added (cron, nft, firewall,
  routing, interfaces, packages it installed); --dry-run
- Works without AmneziaWG on the router: Overview, the setup wizard,
  Health and Components say what is missing and offer to install it
- Overview shows failed health checks as notices with their fix
- People list no longer reads the config from the browser: private keys
  stay on the router; personal links are fetched on demand
- Config changes are serialized under one lock, the nft table loads
  atomically and fails closed, and Dawnline never touches network
  sections it did not create
- The portal never opens system ports, keeps disabled devices disabled,
  rate-limits per address and counts days by the router's clock
- Settings and Diagnostics load their heavy parts in the background
- Release notes are written from the commits since the previous release
- Backend and admin UI split into small single-purpose modules
This commit is contained in:
Aemeath committed 2026-10-16 02:14:15 +03:00
1 parent 70a932b8ea
commit 34293fb8e5
158 files changed
+17418 -10022

No files matched your search

+1
View File
@@ -2,3 +2,4 @@ node_modules/
coverage/
package-lock.json
src/portal/fonts/
src/admin/styles/*.css
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dawnline-web",
"version": "0.3.1",
"version": "0.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dawnline-web",
"version": "0.3.1",
"version": "0.4.0",
"license": "MIT",
"dependencies": {
"qrcode-generator": "1.4.4"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dawnline-web",
"version": "0.3.1",
"version": "0.4.0",
"private": true,
"license": "MIT",
"type": "module",
+127 -75
View File
@@ -4,8 +4,10 @@
import type { Circle, Person, Server, Status } from '../shared/types';
import { E } from './e';
import { api, type HomeHost } from './api';
import { attempt, button, closeModal, confirmDialog, modal } from './ui';
import { input } from './kit';
import { button } from './ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
import { attempt } from './ui/toast';
import { chipToggle, input } from './ui/controls';
import { icon } from '../shared/icons';
type Service = Status['services'][number];
@@ -21,7 +23,7 @@ export const homeAccess = (p: Person) => p.access === 'both' || (p.access === 'l
/* ---------- Home services ---------- */
export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onSaved: () => void) {
export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onSaved: () => unknown) {
const name = input(sv?.name ?? prefill.name ?? '', { placeholder: 'NAS' });
const addr = input(sv?.address ?? prefill.address ?? '', { placeholder: '192.168.1.10', class: 'cbi-input-text dl-mono' });
const ports = input((sv?.ports ?? prefill.ports ?? []).join(', '), {
@@ -34,7 +36,7 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
sv ? `Edit ${sv.name}` : 'Add service',
[field('Name', name), field('Address', addr), field('Ports', ports)],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Save',
@@ -88,59 +90,91 @@ function portGroups(h: HomeHost): [string, string[]][] {
return by.size ? [...by].map(([l, p]) => [l, [...p].sort((a, b) => +a - +b)]) : DEFAULT_PORTS;
}
/** Services shared by all servers, and the devices at home to add them from. */
export function homeServices(st: Status, serverId: string, reload: () => void): HTMLElement {
const services = st.services;
/** Home services as a live part of Server → Access: `update` repaints it from a new status. */
export interface HomeServices {
el: HTMLElement;
update(st: Status): void;
}
/**
* Services shared by all servers, and the devices at home to add them from.
* The devices are read once; `reload` refreshes the status after a change
* (the rest of the Access section, and what is typed there, stays).
*/
export function homeServices(initial: Status, serverId: string, reload: () => Promise<unknown>): HomeServices {
let st = initial;
let hosts: { hosts: HomeHost[]; mdns: boolean } | null = null;
let failed = false;
/** The "Add from devices at home" fold, once opened or closed by hand. */
let open: boolean | null = null;
/** Devices with a change on its way: a second click would add the service twice. */
const busy = new Set<string>();
const list = E('div', { class: 'dl-list' });
const picker = E('div', { class: 'dl-stack gap8' }, E('span', { class: 'dl-sub' }, 'Looking for devices at home…'));
const rows = services.length
? services.map((sv) =>
E('div', { class: 'dl-row' }, [
icon('home'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, sv.name),
E(
'span',
{ class: 'dl-mono dl-faint' },
`${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`,
),
]),
button('Edit', () => serviceDialog(sv, {}, reload)),
button(
[icon('trash')],
async () => {
if (
(await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) &&
(await attempt(() => api.serviceDelete(sv.id), 'Removed'))
)
reload();
},
'neutral',
{ title: 'Remove', 'aria-label': `Remove ${sv.name}` },
),
]),
)
: [E('div', { class: 'dl-row dl-muted' }, 'No services yet: pick ports of a device below.')];
const paintRows = () => {
const services = st.services;
dom.content(
list,
services.length
? services.map((sv) =>
E('div', { class: 'dl-row' }, [
icon('home'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, sv.name),
E(
'span',
{ class: 'dl-mono dl-faint' },
`${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`,
),
]),
button('Edit', () => serviceDialog(sv, {}, reload)),
button(
[icon('trash')],
async () => {
if (
(await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) &&
(await attempt(() => api.serviceDelete(sv.id), 'Removed'))
)
await reload();
},
'neutral',
{ title: 'Remove', 'aria-label': `Remove ${sv.name}` },
),
]),
)
: [E('div', { class: 'dl-row dl-muted' }, 'No services yet: pick ports of a device below.')],
);
};
/** Ports chosen for a device: add, change or remove its service at once. */
async function choose(h: HomeHost, ports: string[] | null) {
const sv = services.find((s) => s.address === h.address);
const ok =
ports === null
? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`))
: await attempt(
() => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports),
sv ? `${sv.name} updated` : `${h.name || h.address} added`,
);
if (ok) reload();
if (busy.has(h.address)) return;
busy.add(h.address);
paintPicker();
try {
const sv = st.services.find((s) => s.address === h.address);
const ok =
ports === null
? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`))
: await attempt(
() => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports),
sv ? `${sv.name} updated` : `${h.name || h.address} added`,
);
if (ok) await reload();
} finally {
busy.delete(h.address);
paintPicker();
}
}
function hostRow(h: HomeHost): HTMLElement {
const sv = services.find((s) => s.address === h.address);
const sv = st.services.find((s) => s.address === h.address);
const all = !!sv && !sv.ports.length;
const chosen = new Set(sv?.ports ?? []);
const wait = busy.has(h.address);
const chip = (label: string, on: boolean, click: () => void) =>
E('button', { type: 'button', class: `dl-chipbtn${on ? ' on' : ''}`, 'aria-pressed': on ? 'true' : 'false', click }, label);
chipToggle(label, on, click, { disabled: wait ? 'disabled' : null, 'aria-busy': wait ? 'true' : null });
return E('div', { class: 'dl-row' }, [
icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, h.name || h.address), E('span', { class: 'dl-mono dl-faint' }, h.address)]),
@@ -161,36 +195,46 @@ export function homeServices(st: Status, serverId: string, reload: () => void):
]);
}
function paintPicker() {
if (failed) return dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home."));
if (!hosts) return;
const r = hosts;
if (!r.hosts.length) return dom.content(picker, E('span', { class: 'dl-sub' }, 'No devices found in the home network right now.'));
// Open while there are no services yet (that is where they come from), then as left.
const fold = E('details', { class: 'dl-params', open: (open ?? !st.services.length) ? '' : null }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Add from devices at home'),
E('span', { class: 'dl-pcount' }, String(r.hosts.length)),
]),
E('div', { class: 'dl-params-body' }, [
E(
'span',
{ class: 'dl-sub' },
r.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.',
),
E('div', { class: 'dl-list' }, r.hosts.map(hostRow)),
]),
]);
fold.addEventListener('toggle', () => (open = (fold as HTMLDetailsElement).open));
dom.content(picker, fold);
}
api
.homeHosts(serverId)
.then((r) => {
const open = r.hosts.some((h) => services.some((s) => s.address === h.address)) && !services.length;
dom.content(
picker,
r.hosts.length
? E('details', { class: 'dl-params', open: open ? '' : null }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Add from devices at home'),
E('span', { class: 'dl-pcount' }, String(r.hosts.length)),
]),
E('div', { class: 'dl-params-body' }, [
E(
'span',
{ class: 'dl-sub' },
r.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.',
),
E('div', { class: 'dl-list' }, r.hosts.map(hostRow)),
]),
])
: E('span', { class: 'dl-sub' }, 'No devices found in the home network right now.'),
);
hosts = r;
paintPicker();
})
.catch(() => dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home.")));
.catch(() => {
failed = true;
paintPicker();
});
paintRows();
return E('div', { class: 'dl-stack gap8' }, [
const el = E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-iflead' }, [
E('div', { class: 'dl-iflead-row' }, [
E('b', {}, 'Home services'),
@@ -202,14 +246,22 @@ export function homeServices(st: Status, serverId: string, reload: () => void):
'Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.',
),
]),
E('div', { class: 'dl-list' }, rows),
list,
picker,
]);
return {
el,
update(n: Status) {
st = n;
paintRows();
paintPicker();
},
};
}
/* ---------- Circles ---------- */
export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => void) {
export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => unknown) {
const used = new Set(st.circles.filter((c) => c.server === serverId).map((c) => c.color));
let color = ci?.color ?? CIRCLE_COLORS.findIndex((_, i) => !used.has(i));
if (color < 0) color = 0;
@@ -287,7 +339,7 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
)
: '',
E('span', { class: 'dl-spacer' }),
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Save',
@@ -305,7 +357,7 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
}
/** The server's circles as chips (click to edit) and a round "+" to add one. */
export function circleChips(st: Status, serverId: string, onDone: () => void): HTMLElement {
export function circleChips(st: Status, serverId: string, onDone: () => unknown): HTMLElement {
const list = st.circles.filter((c) => c.server === serverId);
return E('div', { class: 'dl-chips-row dl-circles' }, [
...list.map((c) => {
+93 -25
View File
@@ -1,6 +1,6 @@
// luci.dawnline RPC bindings. The backend reports failures as { error }.
import type { AwgCaps, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
function call<T>(method: string, params: string[] = []) {
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params });
@@ -25,6 +25,7 @@ export interface SetupDefaults {
portal_port: number;
taken: string[];
awg: AwgCaps;
awg_state?: AwgState;
}
export interface Backup {
@@ -40,6 +41,12 @@ export interface UpdateComponent {
installed?: string | null;
latest?: string | null;
update?: boolean;
/** latest | outdated | dev (installed is newer than the release) | '' (unknown). */
status?: 'latest' | 'outdated' | 'dev' | '';
/** When this component was last checked. */
time?: number;
url?: string | null;
published?: string | null;
note?: string;
error?: string;
repo?: string;
@@ -78,23 +85,89 @@ export interface UpdatesStatus {
home?: boolean;
needs?: Needs;
check: { time: number; components: Record<string, UpdateComponent> } | null;
job: {
action: string;
component: string | null;
state: 'running' | 'done' | 'failed';
started: number;
finished: number | null;
phase: string;
log: string[];
error: string | null;
} | null;
job: UpdateJob | null;
/** Router time, for the job timer. */
now: number;
repo: string;
policy: UpdatePolicy;
/** Automatic runs: the last check and the last scheduled install day. */
auto: { check?: number; install_day?: string };
/** The version kept for Roll back, per component. */
kept: Record<'app' | 'amneziawg', { version: string; build: AwgSource | null; saved: number | null } | null>;
/** Components → Activity, newest first. */
history: UpdateEvent[];
/** AmneziaWG interfaces (their Dawnline names): switching builds restarts them. */
tunnels: string[];
}
/** Missing packages by feature: the portal's HTTPS, ACME certificates, the home-like link. */
export interface UpdateEvent {
ts: number;
/** found: a check found updates; install: an update ran; error: a check or an update failed. */
kind: 'found' | 'install' | 'error';
auto?: boolean;
items?: string[];
component?: string | null;
from?: string | null;
to?: string | null;
state?: 'done' | 'failed';
error?: string | null;
took?: number;
}
export interface UpdateJob {
id: string;
action: string;
component: string | null;
state: 'running' | 'done' | 'failed';
started: number;
finished: number | null;
/** Started by Settings → Updates, not by a click. */
auto?: boolean;
phase: string;
from: string | null;
to: string | null;
log: string[];
error: string | null;
result: Record<string, any> | null;
}
/** Settings → Updates. */
export interface UpdatePolicy {
check: boolean;
interval: '6h' | '12h' | '1d' | '7d';
auto: boolean;
mode: 'immediate' | 'scheduled';
time: string;
targets: ('app' | 'amneziawg' | 'packages')[];
keep: boolean;
mirrors: boolean;
}
export interface Release {
tag: string;
name: string;
published: string | null;
prerelease: boolean;
url: string | null;
body: string | null;
assets: string[];
}
/** Missing packages by feature: the portal's HTTPS, ACME certificates, the home-like link, AmneziaWG itself. */
export interface Needs {
https: string[];
acme: string[];
home: string[];
/** amneziawg-tools and/or kmod-amneziawg (older backends leave it out). */
awg?: string[];
}
/** The slow part of the portal settings, loaded after the page shows. */
export interface PortalInfo {
/** Addresses the portal could use, found on the router. */
candidates: { host: string; kind: 'name' | 'ip'; ips: string[]; here: boolean; cloudflare: boolean; cert: boolean }[];
/** The portal's checks from Health. */
checks: HealthCheck[];
}
export interface SettingsData {
@@ -106,10 +179,6 @@ export interface SettingsData {
port_owners: string[];
wan443_taken?: boolean;
portal_public_port?: number;
/** Addresses the portal could use, found on the router. */
portal_candidates?: { host: string; kind: 'name' | 'ip'; ips: string[]; here: boolean; cloudflare: boolean; cert: boolean }[];
/** The portal's checks from Health. */
portal_checks?: HealthCheck[];
geo_cached: number;
logs: LogsInfo;
}
@@ -290,14 +359,7 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
return r;
}
const statusRaw = call<Status>('status', ['days']);
export let lastStatusAt = 0;
async function status(days?: number): Promise<Status> {
const st = await statusRaw(days);
lastStatusAt = Date.now();
return st;
}
const status = call<Status>('status', ['days']);
/** One line of the service log: tunnel and service starts, stops, watchdog repairs, errors. */
export interface ServiceLogEntry {
@@ -333,6 +395,7 @@ export type Health = { checks: HealthCheck[] } & ServiceLog;
export const api = {
personUpdate,
settingsGet: call<SettingsData>('settings_get'),
portalInfo: call<PortalInfo>('portal_info'),
settingsUpdate: call<SettingsData>('settings_update', ['values']),
serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']),
serviceDelete: call<unknown>('service_delete', ['id']),
@@ -376,6 +439,8 @@ export const api = {
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
serverUpdate: call<unknown>('server_update', ['id', 'values']),
serverDelete: call<unknown>('server_delete', ['id']),
/** The personal link, its code and every address it works on (main first); not part of the status. */
personLinks: call<{ code: string; link: string | null; links: string[] }>('person_links', ['id']),
personCreate: call<{ id: string; link: string | null }>('person_create', [
'name',
'slug',
@@ -410,5 +475,8 @@ export const api = {
exportJson: call<Record<string, unknown>>('export'),
importJson: call<unknown>('import', ['data']),
updatesStatus: call<UpdatesStatus>('updates_status'),
updatesRun: call<{ started: boolean }>('updates_run', ['what']),
updatesRun: call<{ started: boolean; job: UpdateJob | null }>('updates_run', ['what']),
updatesReleases: call<{ releases: Release[]; page: number }>('updates_releases', ['page']),
updatesNotes: call<Release & { repo: string }>('updates_notes', ['component', 'tag', 'build']),
updatesChanges: call<{ items: string[] }>('updates_changes', ['from', 'to']),
};
-96
View File
@@ -1,96 +0,0 @@
// DOM bar charts with a hover tooltip (traffic per day, sparklines).
import type { DayUsage } from '../shared/types';
import { E } from './e';
import { bytes } from '../shared/format';
function dayLabel(day: string): string {
const [y, m, d] = day.split('-').map(Number);
return new Date(y, m - 1, d).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
}
/**
* Daily traffic bars (download stacked over upload, from the person's point
* of view: router tx = download). `top(day)` may name the busiest device.
*/
export function trafficBars(series: DayUsage[], height = 180, top?: (day: string) => string | null): HTMLElement {
const max = Math.max(1, ...series.map((d) => d.rx + d.tx));
const tip = E('div', { class: 'dl-tip' });
tip.style.display = 'none';
const bars = E('div', { class: 'dl-bars' });
bars.style.height = `${height}px`;
series.forEach((d) => {
const total = d.rx + d.tx;
const col = E('div', { class: 'dl-bar' }, [E('i', { class: 'down' }), E('i', { class: 'up' })]);
(col.children[0] as HTMLElement).style.height = `${(d.tx / max) * 100}%`;
(col.children[1] as HTMLElement).style.height = `${(d.rx / max) * 100}%`;
if (!total) col.classList.add('empty');
col.addEventListener('mouseenter', () => {
const t = top?.(d.day);
tip.replaceChildren(
E('div', { class: 'dl-tip-title' }, dayLabel(d.day)),
E('div', { class: 'dl-muted' }, `↓ ${bytes(d.tx)} · ↑ ${bytes(d.rx)}`),
t ? E('div', { class: 'dl-faint' }, `Top: ${t}`) : '',
);
tip.style.display = '';
const r = col.getBoundingClientRect();
const host = bars.getBoundingClientRect();
const x = r.left - host.left + r.width / 2;
tip.style.left = `${Math.min(Math.max(x, 70), host.width - 70)}px`;
});
bars.appendChild(col);
});
bars.addEventListener('mouseleave', () => (tip.style.display = 'none'));
const first = series[0]?.day;
return E('div', { class: 'dl-chartbox' }, [
bars,
tip,
E('div', { class: 'dl-axis' }, [E('span', {}, first ? dayLabel(first) : ''), E('span', {}, 'Today')]),
]);
}
let floating: HTMLElement | null = null;
/** Floating tooltip that follows the pointer (for small charts and meters). */
export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
const show = (ev: MouseEvent) => {
floating ??= document.body.appendChild(E('div', { class: 'dl-tip dl-tip-float dl-root' }));
floating.replaceChildren(...content().map((c) => (typeof c === 'string' ? document.createTextNode(c) : c)));
floating.style.display = '';
floating.style.left = `${ev.clientX}px`;
floating.style.top = `${ev.clientY - 10}px`;
};
el.addEventListener('mouseenter', show);
el.addEventListener('mousemove', show);
el.addEventListener('mouseleave', () => floating && (floating.style.display = 'none'));
}
/** Tiny daily sparkline (oldest first, the last bar is today) with per-day tooltips. */
export function spark(values: number[], width = 120, height = 26): HTMLElement {
const max = Math.max(1, ...values);
const el = E('div', { class: 'dl-spark' });
el.style.width = `${width}px`;
el.style.height = `${height}px`;
const now = Date.now();
values.forEach((v, i) => {
const b = E('i');
b.style.height = `${Math.max(6, (v / max) * 100)}%`;
if (!v) b.classList.add('zero');
const back = values.length - 1 - i;
const d = new Date(now - back * 86400000);
attachTip(b, () => [
E(
'div',
{ class: 'dl-tip-title' },
back === 0
? 'Today'
: back === 1
? 'Yesterday'
: d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }),
),
E('div', { class: 'dl-muted' }, bytes(v)),
]);
el.appendChild(b);
});
return el;
}
+389
View File
@@ -0,0 +1,389 @@
// The AmneziaWG core in the admin: how a device connects (.conf, AmneziaVPN
// key, QR), the disguise and its parameters, and the core's own settings on
// Server → AmneziaWG. Plain WireGuard is AmneziaWG with the disguise off.
import type { AwgConfig, Server, Status } from '../../shared/types';
import { E } from '../e';
import { api } from '../api';
import { button } from '../ui/button';
import { confirmDialog } from '../ui/modal';
import { copyText, downloadFile } from '../ui/files';
import { attempt, notify } from '../ui/toast';
import { input } from '../ui/controls';
import { callout, card, group, row, svg } from '../ui/layout';
import { qrSvg } from '../../shared/qr';
import { vpnKey } from '../../shared/vpnkey';
import { icon } from '../../shared/icons';
import { methodInfo, methodPicker, type Method } from '../disguise';
import { coreHead, type Core, type CoreCtx } from './common';
/** `.conf` names of the disguise parameters, in file order. */
const CONF: [string, string][] = [
['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'],
];
/**
* The applied parameters, grouped by what they do, with a plain-language
* line per group. Collapsed by default; copyable as config lines.
*/
function paramsView(o: Record<string, string>): HTMLElement | null {
const has = (k: string) => 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])]);
const group = (title: string, ic: string, text: string, ks: string[]) => {
const present = CONF.filter(([k]) => ks.includes(k) && has(k));
return present.length
? E('div', { class: 'dl-pgroup' }, [
E('div', { class: 'dl-pgroup-head' }, [icon(ic), E('b', {}, title)]),
E('p', {}, text),
E(
'div',
{ class: 'dl-pvals' },
present.map(([k, n]) => val(k, n)),
),
])
: '';
};
const jc = Number(o.jc || 0);
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 body = E('div', { class: 'dl-pgrid' }, [
group(
'Junk packets',
'zap',
jc ? `${jc} random packet${jc === 1 ? '' : 's'} of ${o.jmin}–${o.jmax} bytes before each handshake.` : 'No junk packets.',
['jc', 'jmin', 'jmax'],
),
group('Padding', 'archive', 'Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.', [
's1',
's2',
's3',
's4',
]),
group('Packet types', 'key', 'The values that replace WireGuard’s recognisable message types.', ['h1', 'h2', 'h3', 'h4']),
group('Signatures', 'globe', signature, ['i1', 'i2', 'i3', 'i4', 'i5']),
group('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',
]),
group('Timing', 'clock', 'Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.', [
'rekey_after_time',
'rekey_timeout',
'reject_after_time',
'keepalive_timeout',
'max_handshake_attempts',
]),
]);
return E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Current parameters'),
E('span', { class: 'dl-pcount' }, String(keys.length)),
E('span', { class: 'dl-spacer' }),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(conf, 'Parameters copied');
},
},
'Copy as config',
),
]),
body,
]);
}
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
function confLine(line: string, reveal: boolean): Node {
if (/^\s*\[.+\]\s*$/.test(line)) return E('span', { class: 'dl-conf-sec' }, line);
const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line);
if (!m) return document.createTextNode(line);
const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line);
return E('span', {}, [
E('span', { class: 'dl-conf-k' }, m[1]),
' ',
secret && !reveal ? E('span', { class: 'dl-conf-mask' }, '••••••••••••••••') : m[2],
]);
}
/** The .conf as a file card (download) and a folded, highlighted view with copy and a hidden key. */
function fileCard(cfg: AwgConfig): HTMLElement {
let reveal = false;
const pre = E('pre', { class: 'dl-conf' });
const paint = () =>
dom.content(
pre,
cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)])),
);
const eye = E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
reveal = !reveal;
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? 'Hide key' : 'Show key']);
paint();
},
},
[icon('key'), 'Show key'],
);
paint();
const size = new Blob([cfg.conf]).size;
return E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-filecard' }, [
E('span', { class: 'dl-filecard-ic' }, '.conf'),
E('span', { class: 'dl-stack' }, [
E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename),
E('span', { class: 'dl-sub' }, `AmneziaWG · ${size} bytes · import it in the app`),
]),
button([icon('download'), ' Download'], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
]),
E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Configuration'),
E('span', { class: 'dl-spacer' }),
eye,
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(cfg.conf, 'Configuration copied');
},
},
[icon('copy'), 'Copy'],
),
]),
pre,
]),
]);
}
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
if (!cfg.has_private_key)
return E(
'div',
{ class: 'dl-hint' },
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
);
const key = await vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`);
const panes: Record<string, () => Node> = {
qr: () =>
E('div', { class: 'dl-qr-pane' }, [
svg(qrSvg(cfg.conf), 'dl-qr'),
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
]),
key: () =>
E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-linkbox' }, [E('span', { class: 'dl-mono' }, key), button('Copy', () => copyText(key, 'Key copied'))]),
E('span', { class: 'dl-sub' }, 'AmneziaVPN → Add server → Insert key. Keep it private.'),
]),
file: () => fileCard(cfg),
};
const body = E('div', { class: 'dl-connect-body' });
const seg = E('div', { class: 'dl-seg' });
const show = (id: string) => {
seg.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.id === id));
dom.content(body, panes[id]());
};
for (const [id, label] of [
['file', 'File'],
['key', 'Key'],
['qr', 'QR code'],
])
seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
show(initial);
return E('div', { class: 'dl-stack gap12' }, [seg, body]);
}
/** Switch the disguise (every device imports its configuration again). */
async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean) {
const info = methodInfo(m)!;
const people = ctx.st.people.filter((p) => p.server === srv.id);
const devices = people.reduce((n, p) => n + p.devices.length, 0);
const ok = await confirmDialog(
same ? 'Generate new disguise values?' : `Switch to ${info.title}?`,
`${devices} AmneziaWG device${devices === 1 ? '' : 's'} stop connecting until they import their configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : ''}`,
same ? 'Generate and apply' : 'Switch and apply',
true,
);
if (!ok) return;
if (await attempt(() => api.serverObfuscation(srv.id, m), same ? 'New values applied' : `${info.title} applied`)) {
notify('Devices are marked “Update config” until they import again.', 'info', 6000);
await ctx.refresh();
}
}
/** Server → AmneziaWG: listening port, what goes into every configuration, disguise, tunnel. */
export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
const st: Status = ctx.st;
const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const mtu = input(String(srv.mtu ?? ''), { placeholder: '1380', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
let selected: Method = current ?? 'standard';
const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral');
const label = () =>
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
label();
const devs = st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0);
const tools = st.awg_state?.tools !== false;
return card(
'',
[
coreHead(
'AmneziaWG',
srv.up ? 'ok' : 'bad',
srv.up ? 'Running' : 'Not running',
`${srv.ifname} · ${devs} device${devs === 1 ? '' : 's'}`,
),
group('globe', 'Listening', 'Where devices reach this core from the internet', [
row('UDP port', port, 'Opened on the WAN firewall automatically.'),
]),
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
row('MTU', mtu, 'Lower it if some sites hang on mobile networks.'),
row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'),
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
methodPicker(
st.awg,
selected,
(m) => {
selected = m;
label();
},
current,
tools,
),
// Only about an installed AmneziaWG: without one the server page says what to install.
tools && !st.awg.v3
? callout('info', [
'This router runs an older AmneziaWG. ',
E('b', {}, 'Maximum'),
' becomes available with kmod-amneziawg and amneziawg-tools 3.1.',
])
: '',
paramsView(srv.obf ?? {}) ?? '',
E('div', { class: 'dl-row-end' }, [
E('span', { class: 'dl-sub' }, 'Applies at once: every AmneziaWG device imports its configuration again.'),
apply,
]),
]),
E('details', { class: 'dl-params' }, [
E('summary', {}, [icon('chevron'), E('span', {}, 'Tunnel'), E('span', { class: 'dl-pcount' }, '3')]),
E('div', { class: 'dl-params-body' }, [
row('Interface', E('span', { class: 'dl-mono' }, `${srv.ifname} · router ${srv.address}`)),
row('Tunnel subnet', E('span', { class: 'dl-mono' }, srv.subnet), 'Device addresses come from it.'),
row(
'Server public key',
E('span', { class: 'dl-keyrow' }, [
E('code', { class: 'dl-mono' }, srv.public_key),
button([icon('copy')], () => copyText(srv.public_key, 'Public key copied'), 'neutral', {
title: 'Copy',
class: 'cbi-button cbi-button-neutral dl-icon-only sm',
}),
]),
),
]),
]),
],
[
E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'),
button('Save', () => ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved'), 'positive'),
],
);
}
/** Overview: the disguise in use, its stealth and speed, and the values devices carry in words. */
function overviewTile(srv: Server): HTMLElement {
const m = methodInfo(srv.preset);
const o = srv.obf ?? {};
const segs = (n: number, cls: string) =>
E(
'span',
{ class: `dl-segs ${cls}` },
[0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })),
);
const chips: string[] = [];
if (+o.jc) chips.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);
const pad = ['s1', 's2', 's3', 's4'].filter((k) => +o[k]).map((k) => `${k.toUpperCase()} ${o[k]}`);
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(o.i1.includes('0x8580') ? 'DNS-like first packet' : 'Signature packets');
if (o.header_protection_key) 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' }, [
E('span', { class: 'dl-metric-label' }, 'Disguise'),
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}&section=awg` }, 'Change'),
]),
E('div', { class: 'dl-disg-id' }, [
E('span', { class: 'dl-disg-ic' }, icon(m?.ic ?? 'shield')),
E('span', { class: 'dl-stack' }, [E('b', {}, m ? m.title : 'Custom'), E('span', { class: 'dl-sub' }, m ? m.short : 'Set by hand')]),
]),
m
? E('div', { class: 'dl-disg-meters' }, [
E('span', {}, 'Stealth'),
segs(m.stealth, 'acc'),
E('span', {}, 'Speed'),
segs(m.speed, 'ok'),
])
: '',
E(
'div',
{ class: 'dl-disg-chips' },
chips.map((c) => E('span', {}, c)),
),
]);
}
export const awg: Core = {
id: 'awg',
label: 'AmneziaWG',
settingsCard,
overviewTile,
connectBlock,
qrText: (cfg) => cfg.conf,
appKey: { label: 'Copy AmneziaVPN key', make: (cfg) => vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`) },
file: { label: 'Download .conf', make: (cfg) => ({ name: cfg.filename, text: cfg.conf }) },
};
+41
View File
@@ -0,0 +1,41 @@
// What every tunnel core gives the admin (cores/index.ts holds the registry),
// what a core's settings card gets from the Server page, and that card's head.
import type { ClientConfig, Server, Status } from '../../shared/types';
import { E } from '../e';
/** What the Server page hands a core's settings card. */
export interface CoreCtx {
st: Status;
/** server_update with these values, then refresh. */
save: (values: Record<string, unknown>, ok?: string) => Promise<void>;
refresh: () => Promise<void>;
}
/** A tunnel core (AmneziaWG today): its name and the pieces of the admin that differ per core. */
export interface Core {
id: string;
/** "AmneziaWG": the server section, the address bar, the settings card. */
label: string;
/** Server → <label>: the core's own settings. */
settingsCard(ctx: CoreCtx, srv: Server): HTMLElement;
/** Overview: how the tunnel looks on the wire (the disguise tile). */
overviewTile(srv: Server): HTMLElement;
/** How a device connects: file / key / QR. */
connectBlock(cfg: ClientConfig, initial?: 'file' | 'key' | 'qr'): Promise<HTMLElement>;
/** What a QR code for the device carries. */
qrText(cfg: ClientConfig): string;
/** The key the device's app imports (⋯ → Copy key), with the menu label. */
appKey?: { label: string; make(cfg: ClientConfig): Promise<string> };
/** The config file the device imports, with the menu label. */
file: { label: string; make(cfg: ClientConfig): { name: string; text: string } };
}
/** Name, state pill and a short line: the head of a core's settings card. */
export function coreHead(title: string, tone: 'ok' | 'bad' | 'off' | '', state: string, sub: string): HTMLElement {
return E('div', { class: 'dl-corehead' }, [
E('h3', {}, title),
E('span', { class: `dl-pill ${tone}` }, state),
sub ? E('span', { class: 'dl-sub' }, sub) : '',
]);
}
+21
View File
@@ -0,0 +1,21 @@
// Tunnel cores by id. A server names its core (`core`, AmneziaWG when absent);
// the Server, device and person pages ask the registry instead of importing a
// core directly, so another core (VLESS/Xray) plugs in here.
import type { Server } from '../../shared/types';
import type { Core } from './common';
import { awg } from './awg';
export type { Core, CoreCtx } from './common';
const CORES: Record<string, Core> = { awg };
/** The core of a server (or of the server a person is on). */
export function coreOf(srv?: Pick<Server, 'core'> | null): Core {
return CORES[srv?.core || 'awg'] ?? awg;
}
/** The core of a person's server. */
export function coreFor(servers: Server[], serverId: string): Core {
return coreOf(servers.find((s) => s.id === serverId));
}
+5
View File
@@ -0,0 +1,5 @@
// Stylesheets are imported as text (tsup: loader '.css' → 'text').
declare module '*.css' {
const css: string;
export default css;
}
+177 -198
View File
@@ -1,21 +1,41 @@
// Device drawer: a right-hand panel with the device's status, connection
// (QR / key / file), details and actions. Replaces the old tabbed modal.
// (QR / key / file, from its server's core), details and actions; the ⋯ menu
// on a device card; and the admin's Add device dialog.
import type { ClientConfig, Device, Geo, Kind, LogEvent, Person } from '../shared/types';
import type { Device, Geo, Kind, LogEvent, Person } from '../shared/types';
import { E } from './e';
import { api } from './api';
import { attempt, button, closeModal, confirmDialog, copyText, downloadFile, modal, notify, svg } from './ui';
import { button } from './ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
import { copyText, downloadFile } from './ui/files';
import { dropdown, type MenuItem } from './ui/menu';
import { drawer } from './ui/drawer';
import { attempt, notify } from './ui/toast';
import { svg } from './ui/layout';
import { deviceStatus } from './ui/badges';
import { qrSvg } from '../shared/qr';
import { vpnKey } from '../shared/vpnkey';
import { ago, bytes, KIND_LABEL, KINDS } from '../shared/format';
import { ago, bytes, isoDay, KIND_LABEL, KINDS, todayOf } from '../shared/format';
import { icon } from '../shared/icons';
import { eventBy } from './pages/overview';
import { spark } from './charts';
import { eventBy } from './events/model';
import { spark } from './widgets/spark';
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
import { coreFor, coreOf, type Core } from './cores';
let current: { close: () => void } | null = null;
/** What the page that opens a device hands over. */
export interface DeviceOpts {
/** Reload the page after a change made here. */
refresh: () => unknown;
geo?: Geo;
/** The router's clock (seconds) and day, for "5 min ago" and the chart labels. */
now?: number;
today?: string;
/** The device's server's core (AmneziaWG when not given). */
core?: Core;
/** The page's activity log, when it keeps one: the drawer reads it instead of fetching its own. */
events?: () => LogEvent[] | null;
}
function iso(ts: number): string {
function when(ts: number): string {
return ts
? new Date(ts * 1000).toLocaleString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
: '—';
@@ -36,154 +56,6 @@ function row(label: string, value: Node | string): HTMLElement {
return E('div', { class: 'dl-kvrow' }, [E('span', { class: 'dl-kvrow-k' }, label), E('span', { class: 'dl-kvrow-v' }, value)]);
}
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
function confLine(line: string, reveal: boolean): Node {
if (/^\s*\[.+\]\s*$/.test(line)) return E('span', { class: 'dl-conf-sec' }, line);
const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line);
if (!m) return document.createTextNode(line);
const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line);
return E('span', {}, [
E('span', { class: 'dl-conf-k' }, m[1]),
' ',
secret && !reveal ? E('span', { class: 'dl-conf-mask' }, '••••••••••••••••') : m[2],
]);
}
/** The .conf as a file card (download) and a folded, highlighted view with copy and a hidden key. */
function fileCard(cfg: ClientConfig): HTMLElement {
let reveal = false;
const pre = E('pre', { class: 'dl-conf' });
const paint = () =>
dom.content(
pre,
cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)])),
);
const eye = E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
reveal = !reveal;
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? 'Hide key' : 'Show key']);
paint();
},
},
[icon('key'), 'Show key'],
);
paint();
const size = new Blob([cfg.conf]).size;
return E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-filecard' }, [
E('span', { class: 'dl-filecard-ic' }, '.conf'),
E('span', { class: 'dl-stack' }, [
E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename),
E('span', { class: 'dl-sub' }, `AmneziaWG · ${size} bytes · import it in the app`),
]),
button([icon('download'), ' Download'], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
]),
E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Configuration'),
E('span', { class: 'dl-spacer' }),
eye,
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(cfg.conf, 'Configuration copied');
},
},
[icon('copy'), 'Copy'],
),
]),
pre,
]),
]);
}
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
export async function connectBlock(cfg: ClientConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
if (!cfg.has_private_key)
return E(
'div',
{ class: 'dl-hint' },
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
);
const key = await vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`);
const panes: Record<string, () => Node> = {
qr: () =>
E('div', { class: 'dl-qr-pane' }, [
svg(qrSvg(cfg.conf), 'dl-qr'),
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
]),
key: () =>
E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-linkbox' }, [E('span', { class: 'dl-mono' }, key), button('Copy', () => copyText(key, 'Key copied'))]),
E('span', { class: 'dl-sub' }, 'AmneziaVPN → Add server → Insert key. Keep it private.'),
]),
file: () => fileCard(cfg),
};
const body = E('div', { class: 'dl-connect-body' });
const seg = E('div', { class: 'dl-seg' });
const show = (id: string) => {
seg.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.id === id));
dom.content(body, panes[id]());
};
for (const [id, label] of [
['file', 'File'],
['key', 'Key'],
['qr', 'QR code'],
])
seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
show(initial);
return E('div', { class: 'dl-stack gap12' }, [seg, body]);
}
function drawer(title: Node, body: Node, foot: Node | null, onClose: () => void): { close: () => void; panel: HTMLElement } {
current?.close();
const panel = E('aside', { class: 'dl-drawer', role: 'dialog', 'aria-modal': 'true' }, [
E('div', { class: 'dl-drawer-head' }, [
title,
E('button', { type: 'button', class: 'dl-drawer-x', 'aria-label': 'Close', click: () => close() }, icon('x')),
]),
E('div', { class: 'dl-drawer-body' }, body),
foot ? E('div', { class: 'dl-drawer-foot' }, foot) : '',
]);
const overlay = E(
'div',
{
class: 'dl-drawer-overlay dl-root',
click: (ev: Event) => {
if (ev.target === overlay) close();
},
},
panel,
);
const onKey = (ev: KeyboardEvent) => {
// LuCI keeps an empty .modal in the page; the body class says whether one is open.
if (ev.key === 'Escape' && !document.body.classList.contains('modal-overlay-active')) close();
};
function close() {
document.removeEventListener('keydown', onKey);
overlay.classList.remove('open');
setTimeout(() => overlay.remove(), 220);
if (current === handle) current = null;
onClose();
}
const handle = { close, panel };
document.addEventListener('keydown', onKey);
document.body.appendChild(overlay);
requestAnimationFrame(() => overlay.classList.add('open'));
current = handle;
return handle;
}
const DEV_EVENT: Record<string, [string, string, string]> = {
connect: ['ok', 'Connected', 'plug'],
disconnect: ['', 'Went offline', 'plug'],
@@ -194,7 +66,7 @@ const DEV_EVENT: Record<string, [string, string, string]> = {
};
/** Activity of one device, newest first. */
function deviceEvents(events: LogEvent[], id: string): HTMLElement {
function deviceEvents(events: LogEvent[], id: string, now?: number): HTMLElement {
const mine = events
.filter((e) => e.device === id && DEV_EVENT[e.type])
.reverse()
@@ -223,37 +95,47 @@ function deviceEvents(events: LogEvent[], id: string): HTMLElement {
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
E('span', { class: 'dl-row-main' }, [E('span', {}, label), ...extra]),
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts)),
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts, now)),
]);
}),
);
}
function statusLine(d: Device): HTMLElement {
// Status as coloured text, no dots (only avatars carry one).
if (d.disabled) return E('span', { class: 'dl-dstat' }, 'Disabled');
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
if (!d.handshake) return E('span', { class: 'dl-dstat warn' }, 'Waiting for the first connection');
return E('span', { class: 'dl-dstat' }, `Last seen ${ago(d.handshake)}`);
/** Open the drawer of a device that was just made or changed, with fresh status. */
async function reopen(personId: string, deviceId: string, o: DeviceOpts) {
const st = await api.status(1).catch(() => null);
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) });
}
/** Device drawer; `refresh` reloads the page after changes. */
export async function openDevice(person: Person, dev: Device, refresh: () => unknown, geo?: Geo) {
/** Device drawer. */
export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const cfg = await attempt(() => api.deviceConfig(dev.id));
if (!cfg) return;
const core = o.core ?? coreOf(null);
let d = dev;
let p = person;
const connect = await connectBlock(cfg);
let geo = o.geo;
let now = o.now;
let today = o.today ?? isoDay(new Date());
const connect = await core.connectBlock(cfg);
const titleEl = E('div', { class: 'dl-drawer-title' });
const stats = E('div', {});
const details = E('div', {});
const log = E('div', {}, E('div', { class: 'dl-sub' }, 'Loading…'));
let logEvents: LogEvent[] = [];
const loadLog = async () => {
const showLog = (events: LogEvent[]) => {
logEvents = events.filter((e) => e.device === d.id);
dom.content(log, deviceEvents(events, d.id, now));
};
/** The page's events when it has them; otherwise a fetch (`force` after clearing). */
const loadLog = async (force = false) => {
const own = o.events?.();
if (own && !force) return showLog(own);
const ev = await api.events(5000).catch(() => null);
if (!ev) return;
logEvents = ev.events.filter((e) => e.device === d.id);
dom.content(log, deviceEvents(ev.events, d.id));
if (ev) showLog(ev.events);
};
const paint = () => {
@@ -265,14 +147,17 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
E('h3', {}, d.name),
button([icon('edit')], () => rename(), 'neutral', { title: 'Rename', class: 'cbi-button cbi-button-neutral dl-icon-only sm' }),
]),
E('span', { class: 'dl-sub' }, [`${p.name} · ${KIND_LABEL[d.kind]}`]),
E('span', { class: 'dl-sub' }, `${p.name} · ${KIND_LABEL[d.kind]}`),
]),
]);
const week = d.spark.reduce((a, b) => a + b, 0);
dom.content(
stats,
E('div', { class: 'dl-dstats' }, [
E('div', { class: 'dl-dstats-cell wide' }, [E('span', { class: 'dl-metric-label' }, 'Status'), statusLine(d)]),
E('div', { class: 'dl-dstats-cell wide' }, [
E('span', { class: 'dl-metric-label' }, 'Status'),
deviceStatus(d, now, 'Waiting for the first connection'),
]),
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, 'This month'),
E('b', {}, bytes(d.month[0] + d.month[1])),
@@ -281,7 +166,7 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, 'Last 7 days'),
E('b', {}, bytes(week)),
spark(d.spark, 120, 22),
spark(d.spark, 120, 22, today),
]),
]),
);
@@ -308,13 +193,13 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(reload, 300)),
click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(changed, 300)),
},
'Reset',
),
]),
),
row('Added', `${iso(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`),
row('Added', `${when(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`),
row(
'Public key',
E('span', { class: 'dl-mono dl-faint' }, cfg.amnezia.client_pub_key ? `${cfg.amnezia.client_pub_key.slice(0, 16)}…` : '—'),
@@ -326,7 +211,7 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
[icon(d.disabled ? 'play' : 'pause'), d.disabled ? ' Enable' : ' Disable'],
async () => {
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? 'Device enabled' : 'Device disabled'))
await reload();
await changed();
},
'neutral',
d.disabled ? {} : { class: 'cbi-button cbi-button-neutral dl-btn-warn' },
@@ -343,12 +228,9 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
return;
const c = await attempt(() => api.deviceRotate(d.id), 'New keys generated');
if (c) {
refresh();
o.refresh();
handle.close();
const st = await api.status(1);
const p2 = st.people.find((x) => x.id === p.id);
const d2 = p2?.devices.find((x) => x.id === d.id);
if (p2 && d2) openDevice(p2, d2, refresh, st.geo);
await reopen(p.id, d.id, o);
}
}),
E('span', { class: 'dl-spacer' }),
@@ -366,7 +248,7 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
return;
if (await attempt(() => api.deviceDelete(d.id), 'Device removed')) {
handle.close();
refresh();
o.refresh();
}
},
'negative',
@@ -374,6 +256,7 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
]);
};
/** The device's own state, fresh from the router; the page underneath is left alone. */
const reload = async () => {
const st = await api.status(1).catch(() => null);
const p2 = st?.people.find((x) => x.id === p.id);
@@ -382,8 +265,14 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
p = p2;
d = d2;
geo = st.geo;
now = st.now;
today = todayOf(st.series);
paint();
refresh();
};
/** After a change made here: this drawer and the page. */
const changed = async () => {
await reload();
o.refresh();
};
const rename = () => {
@@ -392,14 +281,14 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
`Rename ${d.name}`,
[E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, input)])],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Save',
async () => {
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) {
closeModal();
await reload();
await changed();
}
},
'positive',
@@ -435,7 +324,11 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, loadLog),
click: () =>
clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, () => {
void loadLog(true);
o.refresh();
}),
},
'Clear',
),
@@ -453,17 +346,106 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
{ class: 'dl-stack gap16' },
setUp ? [stats, connectSec, detailsSec, activitySec] : [stats, detailsSec, activitySec, connectSec],
);
loadLog();
void loadLog();
// Live status every 8 s. The log follows the page's events, or is fetched every 32 s on its own.
let ticks = 0;
const watch = window.setInterval(() => {
reload();
loadLog();
void reload();
if (o.events || ++ticks % 4 === 0) void loadLog();
}, 8000);
const handle = drawer(titleEl, body, foot, () => clearInterval(watch));
paint();
}
/** ⋯ 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));
const items: (MenuItem | null)[] = [
{
label: 'Show QR code',
icon: icon('qr'),
run: async () => {
const c = await cfg();
if (!c) return;
modal(
`${d.name} · QR code`,
E('div', { class: 'dl-qr-pane' }, [
svg(qrSvg(core.qrText(c)), 'dl-qr'),
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
]),
cancelButton('Close'),
);
},
},
{
label: core.file.label,
icon: icon('download'),
run: async () => {
const c = await cfg();
if (!c) return;
const f = core.file.make(c);
downloadFile(f.name, f.text, 'application/octet-stream');
},
},
core.appKey
? {
label: core.appKey.label,
icon: icon('copy'),
run: async () => {
const c = await cfg();
if (c) copyText(await core.appKey!.make(c), 'Key copied');
},
}
: null,
null,
{ label: 'Rename', icon: icon('edit'), run: () => openDevice(p, d, o) },
{
label: 'New keys',
icon: icon('key'),
run: async () => {
if (
await confirmDialog(
'Generate new keys?',
'The current configuration on this device stops working until it is imported again.',
'Generate',
true,
)
)
if (await attempt(() => api.deviceRotate(d.id), 'New keys generated')) o.refresh();
},
},
{
label: d.disabled ? 'Enable' : 'Disable',
icon: icon(d.disabled ? 'play' : 'pause'),
warn: !d.disabled,
run: async () => {
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? 'Device enabled' : 'Device disabled'))
o.refresh();
},
},
{
label: 'Delete',
icon: icon('trash'),
danger: true,
run: async () => {
if (
await confirmDialog(
`Remove ${d.name}?`,
'The device is disconnected immediately and its configuration stops working.',
'Remove',
true,
)
)
if (await attempt(() => api.deviceDelete(d.id), 'Device removed')) o.refresh();
},
},
];
dropdown(anchor, items);
}
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
export function addDevice(person: Person, refresh: () => unknown) {
export function addDevice(person: Person, o: DeviceOpts) {
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: KIND_LABEL.phone, maxlength: 48 }) as HTMLInputElement;
let kind: Kind = 'phone';
const kinds = E(
@@ -507,7 +489,7 @@ export function addDevice(person: Person, refresh: () => unknown) {
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Name'), nameInput]),
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Add device',
@@ -517,11 +499,8 @@ export function addDevice(person: Person, refresh: () => unknown) {
if (!r) return;
closeModal();
notify(`${name} added`, 'success', 3000);
refresh();
const st = await api.status(1);
const p2 = st.people.find((x) => x.id === person.id);
const d2 = p2?.devices.find((x) => x.id === r.id);
if (p2 && d2) openDevice(p2, d2, refresh, st.geo);
o.refresh();
await reopen(person.id, r.id, o);
},
'positive',
),
+15 -2
View File
@@ -73,6 +73,12 @@ const NEEDS: Record<keyof AwgCaps, string> = {
v3: 'Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).',
};
/** The same while no AmneziaWG is installed at all ("newer" would be misleading). */
const NEEDS_NONE: Record<keyof AwgCaps, string> = {
v2: 'Needs AmneziaWG on the router.',
v3: 'Needs AmneziaWG 3.1 on the router: install it first.',
};
function dots(n: number, label: string): HTMLElement {
return E('span', { class: 'dl-dots', title: `${label}: ${n} of 4` }, [
E('span', { class: 'dl-dots-label' }, label),
@@ -87,8 +93,15 @@ function dots(n: number, label: string): HTMLElement {
/**
* Method cards. `current` gets a badge; unavailable methods stay visible but
* disabled with the reason, so it is clear what an upgrade would bring.
* `installed` is false while the router has no AmneziaWG tools at all.
*/
export function methodPicker(caps: AwgCaps, selected: Method, onSelect: (m: Method) => void, current?: string): HTMLElement {
export function methodPicker(
caps: AwgCaps,
selected: Method,
onSelect: (m: Method) => void,
current?: string,
installed = true,
): HTMLElement {
const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': 'Disguise method' });
const paint = () =>
dom.content(
@@ -122,7 +135,7 @@ export function methodPicker(caps: AwgCaps, selected: Method, onSelect: (m: Meth
E(
'div',
{ class: 'dl-method-foot' },
ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, NEEDS[m.needs!])],
ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
),
],
);
+12
View File
@@ -0,0 +1,12 @@
// CSV for the log export. Cells a spreadsheet would run as a formula (= + - @,
// tab, CR) get a leading apostrophe; quotes, commas and line breaks are quoted.
export function csvCell(v: unknown): string {
let s = v == null ? '' : String(v);
if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`;
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
export function toCsv<K extends string>(cols: readonly K[], rows: Record<K, unknown>[]): string {
return [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
}
+74
View File
@@ -0,0 +1,74 @@
// The activity log's vocabulary: categories, who did what, problems, retention.
// No DOM and no RPC here (see ./render for rows).
import type { LogEvent } from '../../shared/types';
import type { LogCategory, LogsInfo, ServiceLogEntry } from '../api';
/** Mirrors CATEGORY in dawnline.live. */
const CATEGORY: Record<string, LogCategory> = {
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',
paused_all: 'people',
resumed_all: 'people',
portal_blocked: 'problems',
};
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
export const CATEGORY_LABEL: Record<LogCategory, string> = {
connections: 'Connections',
people: 'People',
problems: 'Problems',
};
export const CATEGORY_HELP: Record<LogCategory, string> = {
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)',
};
export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems';
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed', 'paused_all', 'resumed_all'];
/** Who did it. Older events have no `by`: LuCI and the portal marked it in the detail. */
export function eventBy(e: LogEvent): 'admin' | 'portal' | null {
if (e.by) return e.by;
if (ADMIN_TYPES.includes(e.type) || e.detail === 'by admin' || e.detail?.endsWith(' (admin)')) return 'admin';
if (e.detail?.endsWith(' (portal)')) return 'portal';
return null;
}
/** The detail without the old "(admin)" / "(portal)" / "by admin" marks. */
export function plainDetail(e: LogEvent): string {
return (e.detail ?? '').replace(/ \((admin|portal)\)$/, '').replace(/^by admin$/, '');
}
/** One line of the Log: an activity event or a service log entry. */
export type LogItem = { ts: number; ev?: LogEvent; sys?: ServiceLogEntry };
export const isProblem = (x: LogItem) =>
x.sys ? ['error', 'repair', 'down'].includes(x.sys.level) : categoryOf(x.ev!.type) === 'problems';
export function retentionText(p: LogsInfo['policy']): string {
const age = p.keep_days > 0 ? `${p.keep_days} day${p.keep_days === 1 ? '' : 's'}` : 'no age limit';
const where =
p.persist === 'off'
? 'kept in memory only (lost on reboot)'
: `saved to flash ${p.persist === '10min' ? 'every 10 minutes' : 'hourly'}`;
return `Kept for ${age}, up to ${p.max.toLocaleString('en-GB')} events, ${where}.`;
}
+256
View File
@@ -0,0 +1,256 @@
// Log rows: an activity event as a sentence ("You added device Phone for
// Myata"), its tile and time, and a service log line.
import type { LogEvent, Status } from '../../shared/types';
import type { ServiceLogEntry } from '../api';
import { E } from '../e';
import { icon } from '../../shared/icons';
import { ago } from '../../shared/format';
import { SYSTEM_SOURCE, eventBy, plainDetail } from './model';
/** What the people and servers in the log are called now. */
export type Names = Pick<Status, 'people' | 'servers'>;
const EVENT_TONE: Record<string, string> = {
connect: 'ok',
disconnect: '',
roam: '',
device_added: 'ok',
device_removed: '',
person_added: '',
person_removed: '',
paused: 'warn',
resumed: 'ok',
paused_all: 'warn',
resumed_all: 'ok',
portal_blocked: 'bad',
person_changed: '',
devices_removed: 'warn',
};
/** The icon in an event's tile: the device's kind for device events, else what happened. */
const EVENT_ICON: Record<string, string> = {
devices_removed: 'trash',
link_changed: 'link',
person_added: 'plus',
person_removed: 'trash',
person_changed: 'edit',
paused: 'pause',
resumed: 'play',
paused_all: 'pause',
resumed_all: 'play',
};
function eventIcon(st: Names, e: LogEvent): string {
if (e.device) {
const d = st.people.flatMap((p) => p.devices).find((x) => x.id === e.device);
return d?.kind ?? e.dkind ?? 'other';
}
return EVENT_ICON[e.type] ?? 'activity';
}
export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
const person = st.people.find((p) => p.id === e.person);
const who = person?.name ?? e.pname ?? e.person ?? '';
const dev = person?.devices.find((d) => d.id === e.device)?.name ?? e.dname ?? '';
const b = (t: string) => E('b', {}, t);
const m = (t: string) => E('span', { class: 'dl-muted' }, t);
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
/** An address; at home, the name of the device that has it, with the address in brackets. */
const addr = (ip: string) =>
e.hosts?.[ip]
? [E('span', { class: 'dl-ev-host' }, [E('b', {}, e.hosts[ip]), E('span', { class: 'dl-faint' }, ` (${ip})`)])]
: [mono(ip)];
// What the bold name is (a person, a device), said before it in grey.
const kind = (t: string) => E('span', { class: 'dl-ev-kind' }, `${t} `);
const wd = dev ? `${who} · ${dev}` : who;
const detail = plainDetail(e);
const devName = detail || dev || 'a device';
// The admin's own actions start with an accent "You".
const you = (verb: string) => [E('span', { class: 'dl-you' }, 'You'), m(` ${verb} `)];
if (eventBy(e) === 'admin')
switch (e.type) {
case 'device_added':
return [...you('added'), kind('device'), b(devName), m(' for '), b(who)];
case 'device_removed':
return [...you('removed'), kind('device'), b(devName), m(' from '), b(who)];
case 'paused':
return [...you('paused'), kind('person'), b(who)];
case 'resumed':
return [...you('resumed'), kind('person'), b(who)];
case 'device_changed': {
const renamed = detail.startsWith('renamed from ');
return [
...you(renamed ? 'renamed' : detail),
kind('device'),
b(dev || 'a device'),
m(' of '),
b(who),
...(renamed ? [m(` · was ${detail.slice(13)}`)] : []),
];
}
case 'device_keys':
return [...you('issued new keys for'), kind('device'), b(devName), m(' of '), b(who), m(' · it needs its new configuration')];
case 'link_changed':
return [...you('issued a new link for'), kind('person'), b(who), m(' · the old link stopped working')];
case 'paused_all':
return [E('span', { class: 'dl-you' }, 'You'), m(' paused everyone')];
case 'resumed_all':
return [E('span', { class: 'dl-you' }, 'You'), m(' resumed everyone')];
}
switch (e.type) {
case 'connect':
return [
kind('Device'),
b(wd),
m(' connected'),
...(e.detail ? [m(' from '), ...addr(e.detail)] : []),
...(e.where ? [m(` · ${e.where}`)] : []),
];
case 'disconnect':
return [kind('Device'), b(wd), m(' went offline')];
case 'roam':
return [
kind('Device'),
b(wd),
m(' changed network '),
...(e.detail ?? '').split(' → ').flatMap((ip, i) => (i ? [m(' → '), ...addr(ip)] : addr(ip))),
];
case 'device_added':
return [
kind('Person'),
b(who),
m(' added '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
case 'device_removed':
return [
kind('Person'),
b(who),
m(' removed '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
case 'device_keys':
return [kind('Person'), b(who), m(' issued new keys for '), kind('device'), b(devName), m(' on their portal')];
case 'person_added':
return [...you('added'), kind('person'), b(e.detail ?? who)];
case 'person_removed':
return [...you('removed'), kind('person'), b(e.detail ?? who)];
case 'person_changed':
// The detail lists changed fields by their option names (device_limit, expire_action).
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
case 'paused':
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
case 'resumed':
return [kind('Person'), b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])];
case 'paused_all':
return [m('Everyone paused')];
case 'resumed_all':
return [m('Everyone resumed')];
case 'portal_blocked':
return [
E('b', { class: 'dl-sys-src' }, 'Personal portal'),
m(' blocked '),
mono(e.detail ?? ''),
m(' for 15 min after too many wrong codes'),
];
case 'devices_removed':
return [kind('Person'), b(who), m(' — all devices removed, end date reached')];
default:
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
}
}
/** Events about the router rather than people look like service log lines: icon tile, colour by outcome. */
const SYSTEM_EVENT: Record<string, [string, string]> = {
portal_blocked: ['globe', 'bad'],
};
/** With several servers, which one a person's event happened on (left out where that is clear). */
function serverPill(st: Names, e: LogEvent): HTMLElement | '' {
if (st.servers.length < 2 || !e.person) return '';
const p = st.people.find((x) => x.id === e.person);
const srv = p && st.servers.find((s) => s.id === p.server);
return srv ? E('span', { class: 'dl-ev-srv', title: 'Server' }, srv.name) : '';
}
/** An activity event as a row; `time` replaces the "5 min ago" (`now` is the router's clock). */
export function eventRow(st: Names & { now?: number }, e: LogEvent, opts: { server?: boolean; time?: string } = {}): HTMLElement {
const sys = SYSTEM_EVENT[e.type];
const by = eventBy(e);
return E('div', { class: `dl-row${by === 'admin' ? ' dl-ev-by-admin' : sys ? ` dl-ev-by-system ${sys[1]}` : ''}` }, [
by === 'admin'
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: sys
? E('span', { class: 'dl-ev-tile sys' }, icon(sys[0]))
: E('span', { class: `dl-ev-tile ev ${EVENT_TONE[e.type] ?? ''}` }, icon(eventIcon(st, e))),
E('span', { class: 'dl-row-main' }, eventText(st, e)),
opts.server === false ? '' : serverPill(st, e),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, opts.time ?? ago(e.ts, st.now)),
]);
}
/** Colour per service log level (tile, source and row): neutral unless something came up, was repaired or failed. */
// "down" is a tunnel that stopped without Dawnline asking (its own stops are "info").
const SYS_TONE: Record<ServiceLogEntry['level'], string> = { info: '', up: 'ok', down: 'warn', repair: 'warn', error: 'bad' };
const SYS_ICON: Record<ServiceLogEntry['src'], string> = { awg: 'tunnel', dawnline: 'sunrise', portal: 'globe' };
/** A service log line: source, message, folded details; click to unfold. */
export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void, time: string): HTMLElement {
const admin = e.by === 'admin';
const row = E(
'div',
{
class: `dl-row dl-slog-row ${admin ? 'dl-ev-by-admin' : `dl-ev-by-system ${SYS_TONE[e.level] ?? ''}`}${e.detail ? ' has-detail' : ''}`,
},
[
admin
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: E('span', { class: 'dl-ev-tile sys', title: e.level }, icon(SYS_ICON[e.src] ?? 'zap')),
E(
'span',
{ class: 'dl-row-main' },
admin
? [
E('span', { class: 'dl-you' }, 'You'),
E('span', { class: 'dl-muted' }, ` ${e.msg} `),
e.kind ? E('span', { class: 'dl-ev-kind' }, `${e.kind} `) : '',
e.who ? E('b', {}, e.who) : '',
e.note ? E('span', { class: 'dl-muted' }, ` · ${e.note}`) : '',
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
]
: [
// Servers have names people chose: say it is a server. Services name themselves.
e.src === 'awg' && e.who && e.who !== 'AmneziaWG' ? E('span', { class: 'dl-ev-kind' }, 'Server ') : '',
E('b', { class: 'dl-sys-src', title: SYSTEM_SOURCE[e.src] ?? e.src }, e.who ?? SYSTEM_SOURCE[e.src] ?? e.src),
' ',
E('span', { class: 'dl-muted' }, e.msg),
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
],
),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, time),
],
);
if (e.detail)
row.addEventListener('click', (ev) => {
if (!(ev.target as HTMLElement).closest('pre')) toggle();
});
return row;
}
/** "Today", "Yesterday" or "Monday 12 October". */
export function dayTitle(ts: number): string {
const d = new Date(ts * 1000);
const today = new Date();
const y = new Date();
y.setDate(today.getDate() - 1);
if (d.toDateString() === today.toDateString()) return 'Today';
if (d.toDateString() === y.toDateString()) return 'Yesterday';
return d.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' });
}
+45 -53
View File
@@ -5,9 +5,11 @@ import type { MeshMode, Server, Status } from '../shared/types';
import { E } from './e';
import { api, type IfaceCategory, type InterfacesData, type NetDevice } from './api';
import { circleChips, homeServices } from './access';
import { attempt, button, notify } from './ui';
import { button } from './ui/button';
import { attempt, notify } from './ui/toast';
import { seg, sw } from './ui/controls';
import { attachTip } from './ui/tooltip';
import { installMissing } from './pkgs';
import { attachTip } from './charts';
import { icon } from '../shared/icons';
const GROUPS: [IfaceCategory, string][] = [
@@ -27,34 +29,22 @@ const ICON: Record<NetDevice['kind'], string> = {
other: 'link',
};
function sw(on: boolean, label: string, onChange: (v: boolean) => void): HTMLButtonElement {
const b = E(
'button',
{
type: 'button',
role: 'switch',
class: `dl-switch${on ? ' on' : ''}`,
'aria-checked': on ? 'true' : 'false',
'aria-label': label,
click: () => {
const v = !b.classList.contains('on');
b.classList.toggle('on', v);
b.setAttribute('aria-checked', v ? 'true' : 'false');
onChange(v);
},
},
E('i'),
) as HTMLButtonElement;
return b;
/** Server → Access cards; `update` takes a new status without touching the draft. */
export interface AccessCards {
el: HTMLElement;
update(st: Status): void;
}
/**
* Server → Access: how internet traffic leaves (Internet) and what home access
* reaches (Home network: networks, devices reaching each other, services).
* Both cards share one draft; either Save stores it.
* Both cards share one draft; either Save stores it. Changes that apply at
* once (devices reaching each other, services, circles) call `refresh`, which
* brings a new status here through `update`: the draft stays as it is.
*/
export function accessCards(srv: Server, st: Status, reload: () => void): HTMLElement {
export function accessCards(srv: Server, first: Status, refresh: () => Promise<unknown>): AccessCards {
const serverId = srv.id;
let st = first;
const root = E(
'div',
{ class: 'dl-stack gap16' },
@@ -69,7 +59,7 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
// "Other interfaces" stays open or folded across repaints.
let otherOpen = false;
// Built once: it reads the devices at home, which should not happen on every repaint.
const services = homeServices(st, serverId, reload);
const services = homeServices(st, serverId, refresh);
let lans = new Set<string>();
let initial = '';
@@ -322,32 +312,27 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
]),
]);
const meshSeg = E(
'div',
{ class: 'dl-seg sm', role: 'radiogroup', 'aria-label': 'Devices reach each other' },
(
[
['off', 'Off'],
['all', 'Everyone'],
['circles', 'Circles'],
] as const
).map(([v, t]) =>
E(
'button',
{
type: 'button',
role: 'radio',
class: mesh === v ? 'on' : '',
'aria-checked': mesh === v ? 'true' : 'false',
// Applies at once, like the choices on a person's page.
click: async () => {
if (mesh === v) return;
if (await attempt(() => api.serverUpdate(serverId, { mesh: v }), `Devices reach each other: ${t}`)) reload();
},
},
t,
),
),
const meshSeg = seg(
[
['off', 'Off'],
['all', 'Everyone'],
['circles', 'Circles'],
] as [MeshMode, string][],
mesh,
{
label: 'Devices reach each other',
cls: 'sm',
optimistic: false,
// Applies at once, like the choices on a person's page.
onChange: async (v) => {
const t = { off: 'Off', all: 'Everyone', circles: 'Circles' }[v];
if (!(await attempt(() => api.serverUpdate(serverId, { mesh: v }), `Devices reach each other: ${t}`))) return;
mesh = v;
d.config.mesh = v;
paint();
await refresh();
},
},
);
const homeCard = E('section', { class: 'dl-setsec dl-ifcard' }, [
@@ -372,9 +357,9 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
MESH_TEXT[mesh],
meshSeg,
'',
mesh === 'circles' ? circleChips(st, serverId, reload) : undefined,
mesh === 'circles' ? circleChips(st, serverId, refresh) : undefined,
),
services,
services.el,
]),
E('div', { class: 'dl-setsec-foot' }, [
E(
@@ -448,5 +433,12 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
}
load(true);
return root;
return {
el: root,
update(n: Status) {
st = n;
services.update(n);
if (d) paint();
},
};
}
+41 -11
View File
@@ -3,7 +3,11 @@
import type { Person } from '../shared/types';
import { E } from './e';
import { attempt, button, closeModal, copyText, downloadFile, modal, notify } from './ui';
import { api } from './api';
import { button } from './ui/button';
import { closeModal, modal } from './ui/modal';
import { copyText, downloadFile } from './ui/files';
import { attempt, notify } from './ui/toast';
import { icon } from '../shared/icons';
import { qrSvg } from '../shared/qr';
@@ -16,7 +20,7 @@ const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
function cardSvg(p: Person, server: string, link: string): string {
function cardSvg(p: Pick<Person, 'name'>, server: string, link: string): string {
const url = new URL(link);
const word = url.pathname.slice(1);
// Long names shrink to stay on one line (roughly 0.58 em per character).
@@ -60,19 +64,45 @@ async function toPng(svg: string): Promise<Blob> {
);
}
type Invitee = Pick<Person, 'id' | 'name' | 'link'> & { links?: string[] };
/** Who to invite; without `link` the card asks the router for the person's links (they are not in the status). */
type Invitee = Pick<Person, 'id' | 'name'> & { link?: string | null; links?: string[] };
/** The personal link and its other addresses (person_links); null while the portal is off. */
export async function personLinks(id: string): Promise<{ link: string; links: string[] } | null> {
const r = await attempt(() => api.personLinks(id));
if (!r) return null;
if (!r.link) {
notify('The personal portal is off. Turn it on in Settings.', 'warning');
return null;
}
return { link: r.link, links: r.links ?? [] };
}
/** Copy a person's personal link. */
export async function copyPersonLink(id: string) {
const r = await personLinks(id);
if (r) await copyText(r.link, 'Personal link copied');
}
/**
* The card with Copy link and Share / Download. Also the "is ready" step
* after adding someone.
*/
export async function inviteCard(p: Invitee, server: string, opts: { title?: string; lead?: string } = {}) {
if (!p.link) {
let link = p.link;
let links = p.links;
if (link === undefined) {
const r = await personLinks(p.id);
if (!r) return;
link = r.link;
links = r.links;
}
if (!link) {
notify('The personal portal is off. Turn it on in Settings.', 'warning');
return;
}
const link = p.link;
const png = await attempt(() => toPng(cardSvg(p as Person, server, link)));
const href = link;
const png = await attempt(() => toPng(cardSvg(p, server, href)));
if (!png) return;
const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' });
const url = URL.createObjectURL(png);
@@ -105,12 +135,12 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
{ class: 'dl-muted' },
opts.lead ?? `Send ${p.name} the card or the link. They open it, add their devices and connect — no account needed.`,
),
E('button', { type: 'button', class: 'dl-invite-link', title: 'Copy link', click: () => copyText(link, 'Personal link copied') }, [
E('span', {}, link.replace(/^https:\/\//, '')),
E('button', { type: 'button', class: 'dl-invite-link', title: 'Copy link', click: () => copyText(href, 'Personal link copied') }, [
E('span', {}, href.replace(/^https:\/\//, '')),
icon('copy'),
]),
...(p.links ?? [])
.filter((l) => l !== link)
...(links ?? [])
.filter((l) => l !== href)
.map((l) =>
E('button', { type: 'button', class: 'dl-invite-link alt', title: 'Copy this link', click: () => copyText(l, 'Link copied') }, [
E('span', {}, l.replace(/^https?:\/\//, '')),
@@ -125,7 +155,7 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
]),
E('div', { class: 'dl-invite-actions' }, [
share,
button([icon('copy'), ' Copy link'], () => copyText(link, 'Personal link copied')),
button([icon('copy'), ' Copy link'], () => copyText(href, 'Personal link copied')),
]),
]),
]),
+39 -61
View File
@@ -1,48 +1,15 @@
// Activity log helpers shared by Activity, Settings, the person page and the
// device drawer: categories, export, and the clear / reset dialogs.
// Activity log actions shared by Diagnostics, Settings, the person page and
// the device drawer: export, and the clear / reset dialogs.
import type { LogEvent, Status } from '../shared/types';
import { E } from './e';
import { api, type LogCategory, type LogFilter, type ServiceLogEntry } from './api';
import { attempt, button, closeModal, downloadFile, modal, notify } from './ui';
import { eventBy } from './pages/overview';
/** Mirrors CATEGORY in dawnline.live. */
const CATEGORY: Record<string, LogCategory> = {
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',
paused_all: 'people',
resumed_all: 'people',
portal_blocked: 'problems',
};
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
export const CATEGORY_LABEL: Record<LogCategory, string> = {
connections: 'Connections',
people: 'People',
problems: 'Problems',
};
export const CATEGORY_HELP: Record<LogCategory, string> = {
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)',
};
export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems';
import { button } from './ui/button';
import { cancelButton, closeModal, modal } from './ui/modal';
import { downloadFile } from './ui/files';
import { attempt, errorText, notify } from './ui/toast';
import { CATEGORIES, CATEGORY_LABEL, SYSTEM_SOURCE, categoryOf, eventBy } from './events/model';
import { toCsv } from './events/csv';
function names(st: Pick<Status, 'people'>) {
const people = new Map(st.people.map((p) => [p.id, p.name]));
@@ -50,13 +17,6 @@ function names(st: Pick<Status, 'people'>) {
return { people, devices };
}
function csvCell(v: unknown): string {
const s = v == null ? '' : String(v);
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
/** Download events (and service log entries, category "system") as CSV or JSON, names resolved, oldest first. */
export function exportEvents(
st: Pick<Status, 'people'>,
@@ -97,8 +57,7 @@ export function exportEvents(
return;
}
const cols = ['time', 'category', 'type', 'person', 'device', 'detail', 'where', 'by'] as const;
const csv = [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
downloadFile(name, csv, 'text/csv');
downloadFile(name, toCsv(cols, rows), 'text/csv');
}
const AGES: [string, string][] = [
@@ -108,6 +67,8 @@ const AGES: [string, string][] = [
['90', 'Older than 90 days'],
];
const removed = (n: number) => (n ? `${n} event${n === 1 ? '' : 's'} removed` : 'Nothing matched');
/**
* Ask what to clear and do it. `base` pins person/device; the dialog lets you
* pick a category (unless `category` is given) and an age.
@@ -138,21 +99,38 @@ export function clearLogDialog(
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Which events'), age]),
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Clear',
async () => {
// System is the service log; "All categories" clears it too where it is shown.
const r = await attempt(async () => {
const sys = withSystem && (cat.value === 'system' || cat.value === '') ? await api.serviceLogClear(age.value) : { removed: 0 };
const ev =
cat.value === 'system' ? { removed: 0 } : await api.logsClear({ ...base, category: cat.value, older_days: age.value });
return { removed: sys.removed + ev.removed };
});
if (!r) return;
// The activity log first, then the service log ("System"; "All categories"
// clears it too where it is shown). Each result is reported on its own.
let n = 0;
if (cat.value !== 'system') {
try {
n += (await api.logsClear({ ...base, category: cat.value, older_days: age.value })).removed;
} catch (e) {
notify(errorText(e), 'error', 10000);
return;
}
}
if (withSystem && (cat.value === 'system' || cat.value === '')) {
try {
n += (await api.serviceLogClear(age.value)).removed;
} catch (e) {
closeModal();
notify(
`${cat.value === 'system' ? '' : `Activity: ${removed(n).toLowerCase()}. `}The service log was not cleared: ${errorText(e)}`,
'error',
10000,
);
done();
return;
}
}
closeModal();
notify(r.removed ? `${r.removed} event${r.removed === 1 ? '' : 's'} removed` : 'Nothing matched', 'success', 3000);
notify(removed(n), 'success', 3000);
done();
},
'negative',
@@ -173,7 +151,7 @@ export function resetUsageDialog(scope: 'all' | 'person' | 'device', id: string,
scope === 'all' ? 'Reset all traffic history?' : `Reset traffic history for ${label}?`,
[E('p', { class: 'dl-muted' }, body)],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Reset',
-5
View File
@@ -121,11 +121,6 @@ declare global {
const poll: LuciPoll;
const dom: LuciDom;
const baseclass: { extend<T>(props: T): T };
// LuCI form/network/firewall/uci classes are used dynamically.
const form: any;
const network: any;
const firewall: any;
const uci: any;
}
export type { Child, LuciWidget, WidgetOptions };
+12 -13
View File
@@ -4,7 +4,7 @@
import { PeoplePage } from './pages/people';
import { ServerPage } from './pages/server';
import { SettingsPage } from './pages/settings';
import { UpdatesPage } from './pages/maintenance';
import { ComponentsPage } from './pages/components';
import { PersonPage } from './pages/person';
import { DiagnosticsPage } from './pages/diagnostics';
import { styleNode } from './styles';
@@ -12,11 +12,11 @@ import { styleNode } from './styles';
interface Page {
load(): Promise<any>;
render(data: any): Node | Promise<Node>;
/** Set by a form page when it rendered something without a form. */
/** No footer at all (otherwise LuCI's, without its form buttons). */
noFooter?: boolean;
}
function factory<P extends Page>(Cls: new () => P, formBased: boolean) {
function factory<P extends Page>(Cls: new () => P) {
return () => {
const page = new Cls();
const v: Record<string, unknown> = {
@@ -32,20 +32,19 @@ function factory<P extends Page>(Cls: new () => P, formBased: boolean) {
return page.noFooter ? document.createElement('div') : this.super('addFooter', []);
},
};
// Pages without a form.Map have nothing to save: hide the footer buttons.
if (!formBased) Object.assign(v, { handleSave: null, handleSaveApply: null, handleReset: null });
return v;
// No page is a LuCI form (changes go through RPC): nothing to Save & Apply.
return Object.assign(v, { handleSave: null, handleSaveApply: null, handleReset: null });
};
}
// The old Overview address opens the Servers page (it holds each server's overview now).
const overview = factory(ServerPage, false);
const people = factory(PeoplePage, true);
const server = factory(ServerPage, false);
const settings = factory(SettingsPage, false);
const person = factory(PersonPage, false);
const diagnostics = factory(DiagnosticsPage, false);
const updates = factory(UpdatesPage, false);
const overview = factory(ServerPage);
const people = factory(PeoplePage);
const server = factory(ServerPage);
const settings = factory(SettingsPage);
const person = factory(PersonPage);
const diagnostics = factory(DiagnosticsPage);
const updates = factory(ComponentsPage);
/** Health and Activity became Diagnostics tabs: old addresses and bookmarks go there. */
function moved(tab: '' | 'log') {
@@ -0,0 +1,50 @@
// Components → Activity: the latest updates, and checks that found something.
import type { UpdateEvent } from '../../api';
import { E } from '../../e';
import { icon } from '../../../shared/icons';
import { ago, duration } from '../../../shared/format';
import { jobComponent } from '../../updater/jobs';
import type { ComponentsPage } from './index';
const NAMES: Record<string, string> = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', all: 'Components' };
export function activity(page: ComponentsPage): HTMLElement {
const st = page.st;
const row = (e: UpdateEvent) => {
const comp = jobComponent(e.component ?? 'app');
const who = NAMES[comp] ?? 'Components';
const how = e.auto ? 'automatically' : 'by you';
let tone = 'ok',
ic = 'check',
text: (Node | string)[];
if (e.kind === 'found') {
tone = 'accent';
ic = 'download';
text = [E('b', {}, (e.items ?? []).join(', ')), ` found by ${e.auto ? 'the automatic check' : 'a check'}`];
} else if (e.state === 'failed') {
tone = 'bad';
ic = 'x';
text = [E('b', {}, who), ` ${e.kind === 'install' ? 'update' : 'check'} failed${e.error ? ` · ${e.error}` : ''}`];
} else {
const ver = e.from && e.to && e.from !== e.to ? ` ${e.from} → ${e.to}` : e.to ? ` ${e.to}` : '';
text = [E('b', {}, who), `${ver} ${ver ? '' : 'updated '}${how}${e.took ? ` · ${duration(e.took)}` : ''}`.replace(/\s+/g, ' ')];
}
return E('div', { class: 'dl-row' }, [
E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
E('span', { class: 'dl-row-main' }, text),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, ago(e.ts, st.now)),
]);
};
const h = st.history ?? [];
return E('section', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Activity'),
E('span', { class: 'dl-spacer' }),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'All in Log →'),
]),
h.length
? E('div', {}, h.slice(0, 8).map(row))
: E('p', { class: 'dl-sub dl-comp-empty' }, 'Updates, and checks that found something, show up here.'),
]);
}
+172
View File
@@ -0,0 +1,172 @@
// Components → AmneziaWG: the installed build, its update, and the builds for
// this firmware with the Russian translation (Build and translation).
import type { AwgSource, UpdateComponent } from '../../api';
import { E } from '../../e';
import { button } from '../../ui/button';
import { confirmDialog } from '../../ui/modal';
import { sw } from '../../ui/controls';
import { pill } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { whatsNew } from '../../updater/notes';
import type { ComponentsPage, MenuEntry } from './index';
export function awgRows(page: ComponentsPage, w: UpdateComponent | undefined): Node[] {
const st = page.st;
const kept = st.kept?.amneziawg;
const srcs = w?.sources ?? {};
const ids = Object.keys(srcs) as AwgSource[];
const cur = w?.current ?? null;
const curSrc = cur ? srcs[cur] : undefined;
const ru = !!w?.ru;
// What the router says is missing right now wins over the last check (which may predate a removal).
const missing = st.needs?.awg ?? [];
const installed = missing.length ? null : (w?.installed ?? null);
const actions: MenuEntry[] = [];
if (cur && installed)
actions.push({
label: 'Reinstall this build',
warn: true,
ic: 'reset',
run: () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, 'Reinstalling AmneziaWG', installed),
});
if (kept)
actions.push({
label: `Roll back to ${kept.version}`,
ic: 'archive',
warn: true,
run: async () => {
if (
await confirmDialog(
`Roll back AmneziaWG to ${kept.version}?`,
'The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.',
'Roll back',
)
)
void page.op('amneziawg:rollback', 'Rolling back AmneziaWG', installed ?? undefined);
},
});
const menu: (MenuEntry | null)[] = [
w?.release
? {
label: 'What’s new',
ic: 'file',
run: () => whatsNew('amneziawg', w.release!, `What’s new in the ${curSrc?.label ?? 'AmneziaWG'} build`, cur ?? 'slava'),
}
: null,
{
label: 'Open on GitHub',
ic: 'globe',
run: () => window.open(`https://github.com/${curSrc?.repo ?? 'Slava-Shchipunov/awg-openwrt'}`, '_blank', 'noopener'),
},
...(actions.length ? [null, ...actions] : []),
].filter((x, k, a) => x !== null || (k > 0 && a[k - 1] !== null));
const tun = st.tunnels ?? [];
const restarts = tun.length
? `Switching restarts ${tun.length === 1 ? 'the tunnel' : `${tun.length} tunnels`} for a few seconds: ${tun.join(', ')}. Devices keep their configurations.`
: 'Switching takes a few seconds. Devices keep their configurations.';
// The notice under the builds: "Switching restarts Home and Family for a few seconds."
const names = tun.length > 1 ? `${tun.slice(0, -1).join(', ')} and ${tun[tun.length - 1]}` : tun[0];
const notice = tun.length ? `Switching restarts ${names} for a few seconds.` : 'Switching takes a few seconds.';
const switchTo = async (id: AwgSource) => {
const x = srcs[id]!;
const ok = await confirmDialog(
installed ? `Switch to AmneziaWG ${x.gen}?` : `Install AmneziaWG ${x.gen}?`,
`The ${x.label} build, ${x.version}. ${restarts}${x.gen === '3.1' ? ' Devices need AmneziaVPN 3.1 or newer.' : ''}`,
installed ? 'Switch' : 'Install',
);
if (ok)
void page.op(
`amneziawg:${id}${ru ? ':ru' : ''}`,
installed ? `Switching to AmneziaWG ${x.gen}` : 'Installing AmneziaWG',
installed ?? undefined,
);
};
const build = (id: AwgSource) => {
const x = srcs[id]!;
const on = cur === id && !!installed;
return E('div', { class: 'dl-row' }, [
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, x.gen ? `AmneziaWG ${x.gen}` : 'AmneziaWG'),
E('span', { class: 'dl-sub' }, `${x.label} · ${x.gen === '3.1' ? 'AmneziaVPN 3.1+' : 'every app'}`),
]),
E('span', { class: 'dl-mono dl-faint dl-comp-bver' }, x.version ?? 'none yet'),
E(
'span',
{ class: 'dl-comp-bact' },
on
? pill('ok', 'Active')
: x.version
? button(installed ? 'Switch' : 'Install', () => switchTo(id), installed ? 'neutral' : 'positive', { disabled: page.busy })
: pill('', 'No build'),
),
]);
};
const newer = ids
.map((id) =>
srcs[id]?.newer ? `${srcs[id]!.label} moves to ${srcs[id]!.newer!.gen} with OpenWrt ${srcs[id]!.newer!.tag.replace(/^v/, '')}.` : '',
)
.filter(Boolean);
const ruSw = sw(ru, 'Russian translation', (v) => {
if (!cur) return;
void page.op(
`amneziawg:${cur}${v ? ':ru' : ''}`,
v ? 'Adding the Russian translation' : 'Removing the Russian translation',
installed ?? undefined,
);
});
ruSw.disabled = !cur || !installed || page.busy;
const open = page.awgOpen ?? !installed;
const fold = E('details', { class: 'dl-params dl-comp-fold', open: open ? 'open' : null }, [
E('summary', {}, [icon('chevron'), E('span', {}, 'Build and translation')]),
E('div', { class: 'dl-params-body' }, [
// The builds and the translation in one list.
E('div', { class: 'dl-list' }, [
...(ids.length
? ids.map(build)
: [E('div', { class: 'dl-row' }, E('span', { class: 'dl-sub' }, 'Check for updates to see the builds for this router.'))]),
E('div', { class: 'dl-row' }, [
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, 'Russian translation'),
E('span', { class: 'dl-sub' }, 'LuCI pages for AmneziaWG'),
]),
E('span', { class: 'dl-comp-bact' }, ruSw),
]),
]),
// One notice: what switching does, and what the builds will bring.
(installed && ids.length) || newer.length
? E('div', { class: `dl-comp-status ${installed && ids.length ? 'warn' : 'acc'}` }, [
icon(installed && ids.length ? 'alert' : 'download'),
E('span', {}, [installed && ids.length ? E('b', {}, notice) : '', ...newer.map((t) => ` ${t}`)]),
])
: '',
]),
]);
fold.addEventListener('toggle', () => (page.awgOpen = (fold as HTMLDetailsElement).open));
const right: Node[] = [];
if (w?.update && installed && cur)
right.push(
button(`Update to ${w.latest}`, () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, 'Updating AmneziaWG', installed), 'neutral', {
disabled: page.busy,
}),
);
else right.push((w || missing.length) && !installed ? pill('warn', 'Not installed') : page.state('amneziawg', w, w?.latest ?? ''));
right.push(page.round(() => page.op('check:amneziawg', 'Checking AmneziaWG', installed ?? undefined), menu));
return [
page.row(
'shield',
'AmneziaWG',
[
installed
? `${installed}${w?.release ? ` · ${w.release} build` : ''}`
: missing.length
? `missing ${missing.join(', ')}`
: w
? 'not installed'
: 'version not checked',
],
right,
),
E('div', { class: 'dl-comp-foldwrap' }, fold),
];
}
+294
View File
@@ -0,0 +1,294 @@
// Components → the Dawnline block: version, what the update brings, its
// settings at a glance, and every release to install (Versions).
import { E } from '../../e';
import { api, type UpdateComponent } from '../../api';
import { button, iconButton } from '../../ui/button';
import { confirmDialog } from '../../ui/modal';
import { errorText, notify } from '../../ui/toast';
import { input } from '../../ui/controls';
import { pill } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { ago, duration, fmtDay } from '../../../shared/format';
import { whatsNew } from '../../updater/notes';
import type { ComponentsPage, MenuEntry } from './index';
const EVERY: Record<string, string> = { '6h': 'every 6 h', '12h': 'every 12 h', '1d': 'daily', '7d': 'weekly' };
/** A release date (GitHub gives a timestamp). */
const released = (d: string | null | undefined) => (d ? fmtDay(d) : '');
/**
* One change as a short line: the part before "; " or ": " when that says
* enough, else the first 90 characters at a word boundary.
*/
function short(p: string): string {
const head = /^(.{20,}?)(?:;\s|:\s)/.exec(p)?.[1];
if (head) return head;
if (p.length <= 90) return p;
return `${p.slice(0, 90).replace(/[\s,;:]+\S*$/, '')}…`;
}
export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTMLElement {
const st = page.st;
const pol = st.policy;
const kept = st.kept?.app;
const tag = a?.update && a.tag ? a.tag : st.version;
const notesOf = (t: string) => () => whatsNew('app', t, `What’s new in Dawnline ${t.replace(/^v/, '')}`);
// What the offered release brings, or what the installed one brought when it is the latest.
const items = a?.tag && (a.update || a.status === 'latest') ? bullets(page, a.tag, a.update ? st.version : '') : null;
const ptag = a?.tag ?? tag;
const nextCheck =
pol.check && st.auto?.check ? st.auto.check + ({ '6h': 6, '12h': 12, '1d': 24, '7d': 168 }[pol.interval] ?? 24) * 3600 : 0;
const side = (label: string, value: (Node | string)[]) =>
E('div', { class: 'dl-stack gap4' }, [E('span', { class: 'dl-metric-label' }, label), E('span', { class: 'dl-comp-side-v' }, value)]);
const menu: (MenuEntry | null)[] = [
{ label: 'What’s new', ic: 'file', run: notesOf(tag) },
{ label: 'Open on GitHub', ic: 'globe', run: () => window.open(`https://github.com/${st.repo}`, '_blank', 'noopener') },
null,
{
label: `Reinstall ${st.version}`,
ic: 'reset',
warn: true,
run: () => page.op('app:reinstall', 'Reinstalling Dawnline', st.version),
},
kept
? {
label: `Roll back to ${kept.version}`,
ic: 'archive',
warn: true,
run: async () => {
if (
await confirmDialog(
`Roll back to Dawnline ${kept.version}?`,
`The copy kept on the router replaces ${st.version}. A backup of the settings is made first.`,
'Roll back',
)
)
void page.op('app:rollback', 'Rolling back Dawnline', st.version);
},
}
: null,
];
return E('section', { class: 'dl-panel flush dl-comp-hero' }, [
E('div', { class: 'dl-comp-hero-main' }, [
E('div', { class: 'dl-comp-hero-head' }, [
E('span', { class: 'dl-group-ic' }, icon('sunrise')),
E('b', { class: 'dl-comp-name' }, 'Dawnline'),
page.state('app', a, a?.latest ?? ''),
E('span', { class: 'dl-spacer' }),
page.round(() => page.op('check:app', 'Checking Dawnline', st.version), menu, true),
]),
// Version, what it is, and the update: one line.
E('div', { class: 'dl-comp-verrow' }, [
E('div', { class: 'dl-stack' }, [
E('div', { class: 'dl-comp-big' }, [
st.version,
a?.update
? E('small', {}, `→ ${a.latest}`)
: a?.status === 'dev' && a.latest
? E('small', { class: 'dl-faint' }, `release ${a.latest}`)
: '',
]),
E(
'span',
{ class: 'dl-faint dl-comp-meta' },
a?.error
? ''
: a?.update
? a.published
? `released ${released(a.published)}`
: ''
: a?.status === 'dev'
? 'ahead of the latest release'
: a
? `latest release${a.published ? ` · released ${released(a.published)}` : ''}`
: 'not checked yet',
),
]),
]),
// Three points at most; the rest is one click away.
items?.items.length
? E('div', { class: 'dl-stack gap4' }, [
E(
'ul',
{ class: 'dl-comp-bullets' },
items.items.map((b) => E('li', {}, b)),
),
items.total > items.items.length
? E(
'button',
{ type: 'button', class: 'dl-linkbtn dl-comp-more', click: notesOf(ptag) },
`+${items.total - items.items.length} more in What’s new`,
)
: '',
])
: '',
a?.error ? E('p', { class: 'dl-sub dl-comp-lead dl-upd-bad' }, a.error) : '',
// The update and its notes; without an update What's new stays in ⋯.
a?.update
? E('div', { class: 'dl-comp-btns' }, [
button('Update now', () => page.op('app', 'Updating Dawnline', st.version), 'positive', { disabled: page.busy }),
button('What’s new', notesOf(tag)),
])
: '',
versions(page),
]),
E('div', { class: 'dl-comp-hero-side' }, [
side('Source', [icon('globe'), E('a', { href: `https://github.com/${st.repo}`, target: '_blank', rel: 'noopener' }, st.repo)]),
side('Auto-update', [
pol.auto ? pill('ok', 'On') : pill('', 'Off'),
E(
'span',
{ class: 'dl-muted' },
pol.auto
? pol.mode === 'immediate'
? 'as soon as found'
: `${EVERY[pol.interval] === 'weekly' ? 'weekly' : 'daily'} at ${pol.time}`
: pol.check
? `checks ${EVERY[pol.interval]}`
: 'checks off',
),
]),
side(
'Last check',
st.check
? [
ago(st.check.time, st.now),
nextCheck > st.now ? E('span', { class: 'dl-faint' }, `· next in ${duration(nextCheck - st.now)}`) : '',
]
: ['Never'],
),
side(
'Rollback',
kept
? [E('span', { class: 'dl-mono' }, kept.version), E('span', { class: 'dl-faint' }, 'kept on flash')]
: [E('span', { class: 'dl-muted' }, pol.keep ? 'Kept after the next update' : 'Off')],
),
]),
]);
}
/**
* The first points of what a release brings (fetched once per tag): the
* release notes' list, else the commits since `from` (or the release's own commit).
*/
function bullets(page: ComponentsPage, tag: string, from: string): { items: string[]; total: number } | null {
if (page.notes.has(tag)) return page.notes.get(tag) ?? null;
page.notes.set(tag, null);
const clean = (x: string) => x.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g, (_m, t) => t ?? '').trim();
void (async () => {
const body = (await api.updatesNotes('app', tag, '').catch(() => null))?.body ?? '';
let pts = body
.split('\n')
.map((l) => /^\s*[-*+]\s+(.*)$/.exec(l)?.[1])
.filter((x): x is string => !!x);
if (!pts.length) pts = (await api.updatesChanges(from, tag).catch(() => null))?.items ?? [];
const out = { items: pts.slice(0, 3).map((x) => short(clean(x))), total: pts.length };
page.notes.set(tag, out);
if (out.items.length && page.root.isConnected) page.paint();
})();
return null;
}
function versions(page: ComponentsPage): HTMLElement {
const body = E('div', { class: 'dl-params-body' });
const fold = E('details', { class: 'dl-params dl-comp-vers', open: page.versOpen ? 'open' : null }, [
E('summary', {}, [icon('chevron'), E('span', {}, 'Versions'), E('span', { class: 'dl-sub' }, 'install any release')]),
body,
]);
fold.addEventListener('toggle', () => {
page.versOpen = (fold as HTMLDetailsElement).open;
if (page.versOpen) void paintVersions(page, body);
});
if (page.versOpen) void paintVersions(page, body);
return fold;
}
async function paintVersions(page: ComponentsPage, body: HTMLElement) {
const tag = input('', { placeholder: 'Tag, e.g. 0.3.1', class: 'cbi-input-text dl-mono', 'aria-label': 'Release tag' });
const installTag = (t: string) => {
t = t.trim();
if (!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(t)) return notify('Enter a release tag like 0.3.1', 'warning');
void install(page, t);
};
tag.addEventListener('keydown', (ev: KeyboardEvent) => {
if (ev.key === 'Enter') {
ev.preventDefault();
installTag(tag.value);
}
});
const head = E('div', { class: 'dl-comp-tag' }, [
tag,
button('Install', () => installTag(tag.value), 'neutral', { disabled: page.busy }),
]);
const pageNo = page.versPage;
const turn = (d: number) => {
page.versPage = Math.max(1, page.versPage + d);
void paintVersions(page, body);
};
const pager = (more: boolean) =>
E('div', { class: 'dl-comp-pager' }, [
E('button', { type: 'button', class: 'dl-linkbtn', disabled: pageNo <= 1 ? 'disabled' : null, click: () => turn(-1) }, '← Newer'),
E('span', { class: 'dl-faint' }, `Page ${pageNo}`),
E('button', { type: 'button', class: 'dl-linkbtn', disabled: more ? null : 'disabled', click: () => turn(1) }, 'Older →'),
]);
let rows = page.versCache.get(pageNo);
if (!rows) {
dom.content(body, [head, E('p', { class: 'dl-muted dl-loading' }, 'Loading versions…')]);
try {
rows = (await api.updatesReleases(pageNo)).releases;
} catch (e) {
// Not kept: opening the list again, or Try again, asks once more.
if (pageNo !== page.versPage || !body.isConnected) return;
dom.content(body, [
head,
E('div', { class: 'dl-row-actions' }, [
E('span', { class: 'dl-muted' }, `Failed to load versions: ${errorText(e)}`),
button('Try again', () => paintVersions(page, body)),
]),
pager(false),
]);
return;
}
page.versCache.set(pageNo, rows);
if (pageNo !== page.versPage || !body.isConnected) return;
}
if (!rows.length)
return dom.content(body, [head, E('p', { class: 'dl-muted' }, pageNo > 1 ? 'No more versions.' : 'No versions found.'), pager(false)]);
const cur = page.st.version;
dom.content(body, [
head,
...rows.map((r) => {
const v = r.tag.replace(/^v/, '');
return E('div', { class: 'dl-comp-ver' }, [
E('span', { class: 'dl-mono' }, v),
E('span', { class: 'dl-sub' }, released(r.published)),
r.prerelease ? pill('warn', 'Pre-release') : '',
E(
'span',
{ class: 'dl-comp-ic' },
iconButton('file', 'What’s new', () => whatsNew('app', r.tag, `What’s new in Dawnline ${v}`)),
),
v === cur ? pill('ok', 'Installed') : button('Install', () => install(page, r.tag), 'neutral', { disabled: page.busy }),
]);
}),
pager(rows.length >= 5),
]);
}
/** A release by tag; going back asks first (settings written by a newer version may not carry over). */
async function install(page: ComponentsPage, tag: string) {
const v = tag.replace(/^v/, '');
const older = v.localeCompare(page.st.version, undefined, { numeric: true }) < 0;
if (
older &&
!(await confirmDialog(
`Install Dawnline ${v}?`,
`It is older than ${page.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,
'Install',
))
)
return;
void page.op(`app@${tag}`, `Installing Dawnline ${v}`, page.st.version);
}
+254
View File
@@ -0,0 +1,254 @@
// Components: Dawnline, AmneziaWG and the OpenWrt packages Dawnline adds, each
// with its version, a check, updates, other versions and roll back. Every
// operation runs in the updater and is followed in one modal with its log
// (see ../../updater/operation). Settings → Updates holds the automatic checks
// and updates. The blocks live in ./hero, ./awg, ./packages and ./activity.
import { E } from '../../e';
import { api, type Release, type UpdateComponent, type UpdateJob, type UpdatesStatus } from '../../api';
import { button, iconButton } from '../../ui/button';
import { dropdown } from '../../ui/menu';
import { notify } from '../../ui/toast';
import { attachTip } from '../../ui/tooltip';
import { pill } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { ago } from '../../../shared/format';
import { runOperation } from '../../updater/operation';
import { jobComponent, runningComponent } from '../../updater/jobs';
import { hero } from './hero';
import { awgRows } from './awg';
import { packageRows } from './packages';
import { activity } from './activity';
/** A ⋯ menu entry; null in a list is a separator. */
export interface MenuEntry {
label: string;
ic: string;
warn?: boolean;
run: () => unknown;
}
export class ComponentsPage {
st!: UpdatesStatus;
root = E('div', { class: 'dl-upd' });
/**
* The job the modal follows, so the poll does not open a second one:
* 'starting' from the click until the operation knows its job.
*/
following: string | null = null;
/** Versions list: open state and the loaded pages (failed loads are not kept). */
versOpen = false;
versPage = 1;
versCache = new Map<number, Release[]>();
/** Release notes of the version on offer, for the bullets in the Dawnline block. */
notes = new Map<string, { items: string[]; total: number } | null>();
/** The AmneziaWG "Build and translation" fold, once opened or closed by hand. */
awgOpen: boolean | null = null;
load() {
return api.updatesStatus();
}
render(st: UpdatesStatus) {
this.st = st;
this.paint();
// A job started elsewhere (another tab, the schedule) or before a reload: follow it.
if (st.job?.state === 'running') void this.follow(st.job);
poll.add(async () => {
if (!this.root.isConnected) return;
const n = await api.updatesStatus().catch(() => null);
if (!n) return;
const was = this.st;
this.st = n;
// While a click is starting its job, that job is the click's to follow.
if (n.job?.state === 'running' && this.following !== 'starting' && n.job.id !== this.following) void this.follow(n.job);
if (
n.job?.id !== was.job?.id ||
n.job?.state !== was.job?.state ||
n.job?.phase !== was.job?.phase ||
n.check?.time !== was.check?.time
)
this.paint();
}, 5);
return this.root;
}
get busy() {
return this.st.job?.state === 'running';
}
async refresh(st?: UpdatesStatus | null) {
this.st = st ?? (await api.updatesStatus().catch(() => null)) ?? this.st;
this.paint();
}
/** Run `what` in the operation modal; the cards refresh when it ends. */
async op(what: string, title: string, version?: string) {
if (this.busy || this.following === 'starting') {
notify('Another component action is already running', 'warning');
return;
}
this.following = 'starting';
this.paint();
const comp = jobComponent(what);
const job = await runOperation(what, {
title,
version,
onJob: (j) => (this.following = j.id),
onDone: (s) => this.refresh(s),
onUpdate: (s) => {
const c = s.check?.components ?? {};
if (comp === 'amneziawg' && c.amneziawg?.current)
void this.op(
`amneziawg:${c.amneziawg.current}${c.amneziawg.ru ? ':ru' : ''}`,
'Updating AmneziaWG',
c.amneziawg.installed ?? undefined,
);
else void this.op('app', 'Updating Dawnline', this.st.version);
},
});
if (this.following === 'starting') this.following = job?.id ?? null;
void this.refresh();
}
async follow(job: UpdateJob) {
this.following = job.id;
const comp = runningComponent(job);
const what =
({ app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'system packages', all: 'components' } as Record<string, string>)[comp] ??
'components';
await runOperation(
null,
{
title: `${job.action === 'check' ? 'Checking' : job.auto ? 'Automatic update:' : 'Updating'} ${what}`,
onDone: (s) => this.refresh(s),
},
job,
);
}
paint() {
const st = this.st;
const c = st.check?.components ?? {};
const fw = st.firmware;
const pk = packageRows(this, c.packages);
// AmneziaWG missing from the router is not "up to date", whatever the last check said.
const awgMissing = (st.needs?.awg ?? []).length > 0;
const awgUpdate = !awgMissing && c.amneziawg?.update && c.amneziawg.installed ? 1 : 0;
const n = awgUpdate + pk.updates;
dom.content(this.root, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [
E('h2', { class: 'dl-h1' }, 'Components'),
E(
'span',
{ class: 'dl-faint' },
[
fw?.version ? `OpenWrt ${fw.version} · ${fw.target}` : '',
st.check ? `checked ${ago(st.check.time, st.now)}` : 'not checked yet',
]
.filter(Boolean)
.join(' · '),
),
]),
E('div', { class: 'dl-row-actions' }, [
E(
'a',
{ class: 'cbi-button cbi-button-neutral dl-icon-btn', href: `${L.url('admin/network/dawnline/settings')}?section=updates` },
[icon('edit'), ' Settings'],
),
button([icon('refresh'), ' Check all'], () => this.op('check', 'Checking all components'), 'neutral', { disabled: this.busy }),
]),
]),
hero(this, c.app),
E('div', { class: 'dl-comp-cols' }, [
E('section', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Components'),
E('span', { class: 'dl-spacer' }),
E(
'span',
{ class: 'dl-faint dl-comp-count' },
awgMissing
? n
? `AmneziaWG not installed · ${n} update${n === 1 ? '' : 's'}`
: 'AmneziaWG not installed'
: !c.amneziawg && !c.packages
? ''
: n
? `${n} of ${1 + pk.total} need${n === 1 ? 's' : ''} an update`
: 'Everything is up to date',
),
]),
E('div', {}, [...awgRows(this, c.amneziawg), ...pk.rows]),
]),
activity(this),
]),
]);
}
/** The state pill of a component; a running job wins. */
state(comp: string, x: UpdateComponent | undefined, latest: string): Node {
const j = this.st.job;
if (j?.state === 'running') {
const norm = (v: string) => (v === 'packages' ? 'pkgs' : v);
const comps = j.action === 'check' ? [norm(j.component || 'all')] : (j.component ?? '').split(' ').map((v) => norm(jobComponent(v)));
if (comps.includes(comp) || comps.includes('all'))
return E('button', { type: 'button', class: 'dl-pill info dl-comp-run', title: 'Show progress', click: () => this.follow(j) }, [
j.action === 'check' ? 'Checking' : 'Updating',
'…',
]);
}
if (!x) return pill('', 'Not checked');
if (x.error) return pill('warn', 'Check failed', x.error);
if (x.update) return pill('info', 'Update available');
if (x.status === 'dev') return pill('info', 'Newer than release', `The latest release is ${latest}`);
return pill('ok', 'Up to date');
}
/** ⋯ menu; null is a separator. Actions refuse to start while a job runs (see op). */
more(items: (MenuEntry | null)[]) {
const b: HTMLButtonElement = button(
[icon('more')],
() =>
dropdown(
b,
items
// A separator only between items: none first, last or twice in a row.
.filter((x, i, a) => x !== null || (i > 0 && i < a.length - 1 && a[i - 1] !== null && a.slice(i + 1).some(Boolean)))
.map((x) => (x ? { label: x.label, icon: icon(x.ic), warn: x.warn, run: x.run } : null)),
),
'neutral',
{ title: 'More', 'aria-label': 'More' },
);
return b;
}
/** Check and ⋯; `label` adds the word (the Dawnline block), the list keeps round icons with a tooltip. */
round(check: () => void, menu: (MenuEntry | null)[], label = false) {
const busy = this.busy ? ' is-busy' : '';
let btn: HTMLButtonElement;
if (label)
btn = button([icon('refresh'), ' Check'], check, 'neutral', {
class: `cbi-button cbi-button-neutral dl-comp-check${busy}`,
'aria-label': 'Check for updates',
});
else {
btn = iconButton('refresh', 'Check for updates', check, 'neutral', busy.trim());
// Dawnline's own tooltip (the browser's title tip is slow and plain).
btn.removeAttribute('title');
btn.setAttribute('aria-label', 'Check for updates');
attachTip(btn, () => ['Check for updates']);
}
return E('span', { class: 'dl-comp-ic' }, [btn, this.more(menu)]);
}
/** A row of the list: icon tile, name and a mono line, then its controls. */
row(ic: string, name: string, sub: (Node | string)[], right: (Node | string)[]) {
return E('div', { class: 'dl-row' }, [
E('span', { class: 'dl-group-ic' }, icon(ic)),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, name), E('span', { class: 'dl-mono dl-faint dl-comp-sub' }, sub)]),
...right,
]);
}
}
@@ -0,0 +1,93 @@
// Components → system packages: one row per feature in use (the home-like
// link; HTTPS and certificates while the portal is on).
import type { UpdateComponent } from '../../api';
import { button } from '../../ui/button';
import { confirmDialog } from '../../ui/modal';
import { E } from '../../e';
import type { ComponentsPage, MenuEntry } from './index';
const SYS_ITEMS: { title: string; sub: string; pkgs: string[]; feature: 'home' | 'https' | 'acme'; optional?: boolean }[] = [
{ 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: true,
},
];
const ICONS: Record<string, string> = { home: 'network', https: 'lock', acme: 'file' };
export function packageRows(page: ComponentsPage, p: UpdateComponent | undefined): { rows: Node[]; updates: number; total: number } {
const st = page.st;
const pkgs = p?.pkgs ?? {};
const items = SYS_ITEMS.filter((it) => (it.feature === 'home' ? st.home : st.portal));
const runPkgs = async (names: string[], what: string, shown = names) => {
const ok = await confirmDialog(
`Update ${what}?`,
`${shown.join(', ')} from the OpenWrt feeds. Services that use them restart for a moment.`,
'Update',
);
if (ok) void page.op(`pkgs:${names.join(',')}`, `Updating ${what}`);
};
const menu: (MenuEntry | null)[] = [
{ label: 'Check system packages', ic: 'refresh', run: () => page.op('check:packages', 'Checking system packages') },
{
label: 'Open the OpenWrt package list',
ic: 'globe',
run: () => window.open('https://openwrt.org/packages/start', '_blank', 'noopener'),
},
];
let updates = 0;
const rows = items.map((it) => {
const present = it.pkgs.filter((x) => pkgs[x]?.installed);
const upd = [...new Set(present.flatMap((x) => [...(pkgs[x]?.latest ? [x] : []), ...(pkgs[x]?.with ?? [])]))];
const lacks = st.needs?.[it.feature] ?? it.pkgs.filter((x) => !pkgs[x]?.installed);
const main = present.find((x) => pkgs[x]?.latest);
const vers = present.map((x) => `${x} ${pkgs[x]?.installed ?? ''}`).join(', ');
if (lacks.length)
return page.row(
ICONS[it.feature],
it.title,
[`${it.optional ? 'not installed' : `missing ${lacks.join(', ')}`}`],
[
button('Install', () => page.op(`pkgs:${lacks.join(',')}`, `Installing ${it.title}`), it.optional ? 'neutral' : 'positive', {
disabled: page.busy,
}),
E('span', { class: 'dl-comp-ic' }, page.more(menu)),
],
);
if (p && upd.length) {
updates++;
return page.row(
ICONS[it.feature],
it.title,
main ? [`${pkgs[main]!.installed} → ${pkgs[main]!.latest}`, upd.length > 1 ? ` · +${upd.length - 1}` : ''] : [upd.join(', ')],
[
button(
'Update',
() =>
runPkgs(
present.filter((x) => pkgs[x]?.latest || pkgs[x]?.with?.length),
it.title,
upd,
),
'neutral',
{ disabled: page.busy },
),
E('span', { class: 'dl-comp-ic' }, page.more(menu)),
],
);
}
return page.row(
ICONS[it.feature],
it.title,
[vers || it.sub],
[page.state('pkgs', p, ''), E('span', { class: 'dl-comp-ic' }, page.more(menu))],
);
});
return { rows, updates, total: items.length };
}
-94
View File
@@ -1,94 +0,0 @@
// Diagnostics: Health (watchdog, checks, recent problems) and Log (activity
// and the service log in one list) as two tabs. ?tab=log opens the Log; the
// old Health and Activity addresses come here.
import type { Status } from '../../shared/types';
import { E } from '../e';
import { api, type Health, type ServiceLog } from '../api';
import { HealthTab } from './maintenance';
import { LogTab } from './activity';
type Tab = 'health' | 'log';
type Loaded = [Status, Awaited<ReturnType<typeof api.events>>, ServiceLog, Health | null];
const TABS: [Tab, string][] = [
['health', 'Health'],
['log', 'Log'],
];
export class DiagnosticsPage {
tab: Tab = new URLSearchParams(location.search).get('tab') === 'log' ? 'log' : 'health';
health!: HealthTab;
log!: LogTab;
segEl = E('div', { class: 'dl-seg dl-srvsections dl-diag-tabs', role: 'tablist', 'aria-label': 'Diagnostics' });
subEl = E('span', { class: 'dl-muted' });
actionsEl = E('div', { class: 'dl-row-actions' });
bodyEl = E('div', {});
load(): Promise<Loaded> {
// The checks take a moment: only wait for them when Health opens first.
return Promise.all([
api.status(1),
api.events(20000),
api.serviceLog(),
this.tab === 'health' ? api.health().catch(() => null) : Promise.resolve(null),
]);
}
render([st, ev, sl, h]: Loaded): HTMLElement {
this.log = new LogTab(st, ev, sl.log);
this.health = new HealthTab(st, sl, ev.events, () => {
this.show('log');
this.log.show('problems');
});
if (h) this.health.take(h);
this.show(this.tab);
poll.add(async () => {
if (!this.bodyEl.isConnected) return;
const [n, e] = await Promise.all([api.serviceLog().catch(() => null), api.events(20000).catch(() => null)]);
if (e) this.log.take(e);
if (n) this.log.system = n.log;
if (n) this.health.paintLive(n, e?.events ?? this.health.events);
if (this.tab === 'log' && (n || e)) this.log.paint();
}, 10);
return E('div', {}, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Diagnostics'), this.subEl]),
this.actionsEl,
]),
this.segEl,
this.bodyEl,
]);
}
show(tab: Tab) {
this.tab = tab;
const url = new URL(location.href);
if (tab === 'log') url.searchParams.set('tab', 'log');
else url.searchParams.delete('tab');
history.replaceState(null, '', url);
dom.content(
this.segEl,
TABS.map(([k, t]) =>
E(
'button',
{
type: 'button',
role: 'tab',
class: k === tab ? 'on' : '',
'aria-selected': k === tab ? 'true' : 'false',
click: () => k !== this.tab && this.show(k),
},
t,
),
),
);
// Both tabs stay alive; only the visible one is in the page.
this.bodyEl.replaceChildren(tab === 'log' ? this.log.el : this.health.el);
this.subEl.textContent =
tab === 'log' ? this.log.sub : 'Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own.';
dom.content(this.actionsEl, tab === 'log' ? this.log.actions() : '');
if (tab === 'log') this.log.paint();
else if (!this.health.checks) void this.health.run();
}
}
+211
View File
@@ -0,0 +1,211 @@
// Diagnostics → Health: the watchdog, the checks and the latest problems.
import type { HealthCheck, LogEvent, Status } from '../../../shared/types';
import { E } from '../../e';
import { api, type Health, type ServiceLog } from '../../api';
import { button } from '../../ui/button';
import { attempt } from '../../ui/toast';
import { sw, setSwitch } from '../../ui/controls';
import { callout } from '../../ui/layout';
import { icon } from '../../../shared/icons';
import { ago, clock } from '../../../shared/format';
import { isProblem, type LogItem } from '../../events/model';
import { eventRow, systemRow } from '../../events/render';
import { fixAction, runFix } from '../../widgets/health';
const ICON: Record<HealthCheck['status'], string> = { ok: 'check', warn: 'alert', error: 'x', skip: 'pause' };
/** Diagnostics → Health: the watchdog, the checks and the latest problems from the log. */
export class HealthTab {
st: Status;
el = E('div', {});
wdEl = E('div', {});
checksEl = E('div', { class: 'dl-panel' });
recentEl = E('div', { class: 'dl-panel flush dl-recent' });
sl: ServiceLog;
events: LogEvent[];
checks: HealthCheck[] | null = null;
/** Shows the Log tab on its Problems filter. */
toLog: () => void;
summary = E('div', {});
constructor(st: Status, sl: ServiceLog, events: LogEvent[], toLog: () => void) {
this.st = st;
this.sl = sl;
this.events = events;
this.toLog = toLog;
dom.content(this.el, [this.summary, this.wdEl, E('div', { class: 'dl-health-cols' }, [this.checksEl, this.recentEl])]);
this.paintChecks();
this.paintLive(sl, events);
}
/** Run the checks (they take a moment: DNS, ports, certificates). */
async run(fix?: string) {
const r = fix ? await runFix(fix) : await api.health().catch(() => null);
if (!r) return;
this.take(r);
// The network restarts a second after the answer: look again once it is back.
if (fix === 'netrestart') setTimeout(() => this.el.isConnected && void this.run(), 5000);
}
take(r: Health) {
this.checks = r.checks;
this.paintChecks();
this.paintLive(r, this.events);
}
paintChecks() {
const checks = this.checks;
if (!checks) {
dom.content(this.summary, '');
dom.content(this.checksEl, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Checks')]),
E('p', { class: 'dl-muted dl-loading' }, 'Running checks…'),
]);
return;
}
const bad = checks.filter((c) => c.status === 'error').length;
const warn = checks.filter((c) => c.status === 'warn').length;
dom.content(
this.summary,
bad
? callout('error', `${bad} problem${bad > 1 ? 's' : ''} need attention.`)
: warn
? callout('warn', `${warn} warning${warn > 1 ? 's' : ''}.`)
: callout('ok', 'All checks passed.'),
);
const repaired = new Map<string, number>();
for (const x of this.sl.watchdog.repairs) repaired.set(x.id, Math.max(repaired.get(x.id) ?? 0, x.ts));
const refresh = () => this.run();
dom.content(this.checksEl, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Checks'), E('span', { class: 'dl-spacer' }), button('Run again', refresh)]),
E(
'ul',
{ class: 'dl-checks' },
checks.map((c) =>
E('li', {}, [
E('span', { class: `dl-check-icon ${c.status}` }, icon(ICON[c.status])),
E('div', { class: 'dl-check-body' }, [
E('div', { class: 'dl-check-title' }, c.title),
E('div', { class: 'dl-check-detail' }, c.detail),
repaired.has(c.id)
? E('div', { class: 'dl-check-repaired' }, `Repaired by the watchdog at ${clock(repaired.get(c.id)!)}`)
: '',
]),
fixAction(c, (fix) => void this.run(fix), refresh),
]),
),
),
]);
}
/** The watchdog card and recent problems; refreshed by the page poll without running the checks again. */
paintLive(sl: ServiceLog, events: LogEvent[]) {
this.sl = sl;
this.events = events;
const wd = sl.watchdog;
const stale = wd.beat != null && wd.now - wd.beat > 180;
const today = wd.repairs.filter((x) => wd.now - x.ts < 86400);
const lastRep = today[today.length - 1];
const toggle = sw(wd.enabled, 'Watchdog repairs', async (v) => {
const ok = await attempt(() => api.settingsUpdate({ watchdog: v ? '1' : '0' }), v ? 'Watchdog on' : 'Watchdog off');
if (!ok) setSwitch(toggle, !v);
const n = await api.serviceLog().catch(() => null);
if (n) this.paintLive(n, this.events);
});
dom.content(
this.wdEl,
E('div', { class: 'dl-panel dl-wd' }, [
E('div', { class: 'dl-wd-head' }, [
E('span', { class: `dl-wd-tile${wd.enabled ? '' : ' off'}` }, icon('shield')),
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-wd-title' }, 'Watchdog'),
E(
'span',
{ class: 'dl-sub' },
wd.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.',
),
]),
E('span', { class: 'dl-spacer' }),
toggle,
]),
E('div', { class: 'dl-wd-foot' }, [
E(
'div',
{ class: 'dl-wd-chips' },
wd.targets.map((t) =>
E(
'span',
{
class: `dl-check-chip${t.ok ? '' : ' error'}`,
title: t.ok ? 'OK' : `Not working${t.tries ? ` · ${t.tries} repair${t.tries > 1 ? 's' : ''}` : ''}`,
},
[icon(t.ok ? 'check' : 'x'), t.name],
),
),
),
E(
'span',
{ class: `dl-sub${stale ? ' dl-warn-text' : ''}` },
stale
? `The agent has not checked in for ${Math.round((wd.now - wd.beat!) / 60)} min; cron restarts it after 5.`
: [
wd.last ? `Looked ${ago(wd.last, wd.now)}` : 'Starts within a minute',
' · ',
today.length
? `${today.length} repair${today.length > 1 ? 's' : ''} today, last ${lastRep.name} at ${clock(lastRep.ts)}`
: 'no repairs today',
],
),
]),
]),
);
this.paintRecent();
}
/** Problems from the last 7 days, both kinds, newest first. */
paintRecent() {
const since = (this.sl.watchdog.now || Date.now() / 1000) - 7 * 86400;
const items: LogItem[] = [...this.events.map((ev) => ({ ts: ev.ts, ev })), ...this.sl.log.map((sys) => ({ ts: sys.ts, sys }))]
.filter((x) => x.ts >= since && isProblem(x))
.sort((a, b) => b.ts - a.ts);
const head = E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Recent problems'),
E('span', { class: 'dl-spacer' }),
items.length ? E('a', { href: '#', click: (e: Event) => (e.preventDefault(), this.toLog()) }, 'All in Log →') : '',
]);
if (!items.length) {
dom.content(this.recentEl, [
head,
E('div', { class: 'dl-recent-empty' }, [
E('span', { class: 'dl-check-icon ok' }, icon('check')),
'No problems in the last 7 days.',
]),
]);
return;
}
dom.content(this.recentEl, [
head,
...items.slice(0, 8).map((x) => {
if (x.sys) {
const e = x.sys;
const key = `${e.ts}|${e.msg}`;
return systemRow(
e,
this.open.has(key),
() => {
if (!this.open.delete(key)) this.open.add(key);
this.paintRecent();
},
clock(e.ts),
);
}
return eventRow(this.st, x.ev!, { time: clock(x.ts) });
}),
]);
}
open = new Set<string>();
}
+119
View File
@@ -0,0 +1,119 @@
// Diagnostics: Health (watchdog, checks, recent problems) and Log (activity
// and the service log in one list) as two tabs. ?tab=log opens the Log; the
// old Health and Activity addresses come here.
import type { Status } from '../../../shared/types';
import { E } from '../../e';
import { api, type ServiceLog } from '../../api';
import { createPoller } from '../../state/poller';
import { HealthTab } from './health';
import { LogTab } from './log';
type Tab = 'health' | 'log';
type Events = Awaited<ReturnType<typeof api.events>>;
type Loaded = [Status, Events, ServiceLog];
const TABS: [Tab, string][] = [
['health', 'Health'],
['log', 'Log'],
];
/** The whole log is large (up to 20,000 events): fetched only for the Log tab. A "since" cursor on the router would make it cheap. */
const LOG_LIMIT = 20000;
export class DiagnosticsPage {
tab: Tab = new URLSearchParams(location.search).get('tab') === 'log' ? 'log' : 'health';
health!: HealthTab;
log!: LogTab;
segEl = E('div', { class: 'dl-seg dl-srvsections dl-diag-tabs', role: 'tablist', 'aria-label': 'Diagnostics' });
subEl = E('span', { class: 'dl-muted' });
actionsEl = E('div', { class: 'dl-row-actions' });
bodyEl = E('div', {});
/** When the events were last fetched (ms); switching to the Log refreshes stale ones. */
eventsAt = 0;
load(): Promise<Loaded> {
// The checks take a moment: Health shows first and runs them in the background (see show()).
this.eventsAt = Date.now();
return Promise.all([api.status(1), api.events(LOG_LIMIT), api.serviceLog()]);
}
render([st, ev, sl]: Loaded): HTMLElement {
this.log = new LogTab(st, ev, sl.log);
this.health = new HealthTab(st, sl, ev.events, () => {
this.show('log');
this.log.show('problems');
});
this.show(this.tab);
// The service log every 10 s; the activity log only while the Log tab shows it.
createPoller({
fetch: async () => {
const withEvents = this.tab === 'log';
const [n, e] = await Promise.all([
api.serviceLog().catch(() => null),
withEvents ? api.events(LOG_LIMIT).catch(() => null) : Promise.resolve(null),
]);
return n || e ? { n, e } : null;
},
every: 10,
active: () => this.bodyEl.isConnected,
apply: ({ n, e }) => this.take(n, e),
});
return E('div', {}, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Diagnostics'), this.subEl]),
this.actionsEl,
]),
this.segEl,
this.bodyEl,
]);
}
take(n: ServiceLog | null, e: Events | null) {
if (e) {
this.log.take(e);
this.eventsAt = Date.now();
}
if (n) this.log.system = n.log;
if (n) this.health.paintLive(n, e?.events ?? this.health.events);
if (this.tab === 'log') this.log.paint();
}
/**
* Show a tab. The address stays as it is: changing it (even with
* history.replaceState) makes Outline's router load the whole page again.
*/
show(tab: Tab) {
this.tab = tab;
dom.content(
this.segEl,
TABS.map(([k, t]) =>
E(
'button',
{
type: 'button',
role: 'tab',
class: k === tab ? 'on' : '',
'aria-selected': k === tab ? 'true' : 'false',
click: () => k !== this.tab && this.show(k),
},
t,
),
),
);
// Both tabs stay alive; only the visible one is in the page.
this.bodyEl.replaceChildren(tab === 'log' ? this.log.el : this.health.el);
this.subEl.textContent =
tab === 'log' ? this.log.sub : 'Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own.';
dom.content(this.actionsEl, tab === 'log' ? this.log.actions() : '');
if (tab === 'log') {
this.log.paint();
// Health doesn't poll the activity log: catch up when the Log opens.
if (Date.now() - this.eventsAt > 10_000)
void api
.events(LOG_LIMIT)
.then((e) => this.take(null, e))
.catch(() => null);
} else if (!this.health.checks) void this.health.run();
}
}
@@ -2,93 +2,22 @@
// service starts, stops, watchdog repairs, errors) in one list, grouped by
// day, with filters, export and clearing.
import type { LogEvent, Status } from '../../shared/types';
import { E } from '../e';
import { api, type LogCategory, type LogsInfo, type ServiceLogEntry } from '../api';
import { button, dropdown } from '../ui';
import { icon } from '../../shared/icons';
import { CATEGORIES, CATEGORY_LABEL, SYSTEM_SOURCE, categoryOf, clearLogDialog, exportEvents } from '../logs';
import { eventRow } from './overview';
import type { LogEvent, Status } from '../../../shared/types';
import { E } from '../../e';
import { api, type LogCategory, type LogsInfo, type ServiceLogEntry } from '../../api';
import { button } from '../../ui/button';
import { dropdown } from '../../ui/menu';
import { icon } from '../../../shared/icons';
import { CATEGORIES, CATEGORY_LABEL, categoryOf, isProblem, retentionText, type LogItem } from '../../events/model';
import { dayTitle, eventRow, systemRow } from '../../events/render';
import { clearLogDialog, exportEvents } from '../../logs';
export type LogKind = 'all' | LogCategory | 'system';
type Events = Awaited<ReturnType<typeof api.events>>;
/** One line of the list: an activity event or a service log entry. */
export type LogItem = { ts: number; ev?: LogEvent; sys?: ServiceLogEntry };
/** Rows painted at a time; "Show more" adds another page. */
const PAGE = 300;
const KINDS: LogKind[] = ['all', 'connections', 'people', 'system', 'problems'];
/** Colour per service log level (tile, source and row): neutral unless something came up, was repaired or failed. */
// "down" is a tunnel that stopped without Dawnline asking (its own stops are "info").
const SYS_TONE: Record<ServiceLogEntry['level'], string> = { info: '', up: 'ok', down: 'warn', repair: 'warn', error: 'bad' };
const SYS_ICON: Record<ServiceLogEntry['src'], string> = { awg: 'tunnel', dawnline: 'sunrise', portal: 'globe' };
export function dayTitle(ts: number): string {
const d = new Date(ts * 1000);
const today = new Date();
const y = new Date();
y.setDate(today.getDate() - 1);
if (d.toDateString() === today.toDateString()) return 'Today';
if (d.toDateString() === y.toDateString()) return 'Yesterday';
return d.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' });
}
export function retentionText(p: LogsInfo['policy']): string {
const age = p.keep_days > 0 ? `${p.keep_days} day${p.keep_days === 1 ? '' : 's'}` : 'no age limit';
const where =
p.persist === 'off'
? 'kept in memory only (lost on reboot)'
: `saved to flash ${p.persist === '10min' ? 'every 10 minutes' : 'hourly'}`;
return `Kept for ${age}, up to ${p.max.toLocaleString('en-GB')} events, ${where}.`;
}
export const isProblem = (x: LogItem) =>
x.sys ? ['error', 'repair', 'down'].includes(x.sys.level) : categoryOf(x.ev!.type) === 'problems';
/** A service log line: source, message, folded details; click to unfold. */
export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void, time: string): HTMLElement {
const admin = e.by === 'admin';
const row = E(
'div',
{
class: `dl-row dl-slog-row ${admin ? 'dl-ev-by-admin' : `dl-ev-by-system ${SYS_TONE[e.level] ?? ''}`}${e.detail ? ' has-detail' : ''}`,
},
[
admin
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: E('span', { class: 'dl-ev-tile sys', title: e.level }, icon(SYS_ICON[e.src] ?? 'zap')),
E(
'span',
{ class: 'dl-row-main' },
admin
? [
E('span', { class: 'dl-you' }, 'You'),
E('span', { class: 'dl-muted' }, ` ${e.msg} `),
e.kind ? E('span', { class: 'dl-ev-kind' }, `${e.kind} `) : '',
e.who ? E('b', {}, e.who) : '',
e.note ? E('span', { class: 'dl-muted' }, ` · ${e.note}`) : '',
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
]
: [
// Servers have names people chose: say it is a server. Services name themselves.
e.src === 'awg' && e.who && e.who !== 'AmneziaWG' ? E('span', { class: 'dl-ev-kind' }, 'Server ') : '',
E('b', { class: 'dl-sys-src', title: SYSTEM_SOURCE[e.src] ?? e.src }, e.who ?? SYSTEM_SOURCE[e.src] ?? e.src),
' ',
E('span', { class: 'dl-muted' }, e.msg),
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
],
),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, time),
],
);
if (e.detail)
row.addEventListener('click', (ev) => {
if (!(ev.target as HTMLElement).closest('pre')) toggle();
});
return row;
}
export class LogTab {
st: Status;
@@ -239,9 +168,7 @@ export class LogTab {
),
);
} else {
const row = eventRow(this.st, x.ev!);
row.lastElementChild!.textContent = time;
panel!.appendChild(row);
panel!.appendChild(eventRow(this.st, x.ev!, { time }));
}
}
if (items.length > this.shown)
-484
View File
@@ -1,484 +0,0 @@
// Diagnostics → Health, and the Updates page.
import type { HealthCheck, LogEvent, Status } from '../../shared/types';
import { eventRow } from './overview';
import { isProblem, systemRow, type LogItem } from './activity';
import { E } from '../e';
import { api, type AwgSource, type Health, type Needs, type ServiceLog, type UpdatesStatus } from '../api';
import { installFeature } from '../pkgs';
import { attempt, button, callout, confirmDialog } from '../ui';
import { icon } from '../../shared/icons';
import { ago, clock } from '../../shared/format';
import { sw } from '../kit';
const ICON: Record<HealthCheck['status'], string> = { ok: 'check', warn: 'alert', error: 'x', skip: 'pause' };
const FIX_LABEL: Record<string, string> = { apply: 'Repair', sync: 'Reload devices', restart: 'Restart service', updates: 'Open updates' };
/** Diagnostics → Health: the watchdog, the checks and the latest problems from the log. */
export class HealthTab {
st: Status;
el = E('div', {});
wdEl = E('div', {});
checksEl = E('div', { class: 'dl-panel' });
recentEl = E('div', { class: 'dl-panel flush dl-recent' });
sl: ServiceLog;
events: LogEvent[];
checks: HealthCheck[] | null = null;
/** Shows the Log tab on its Problems filter. */
toLog: () => void;
summary = E('div', {});
constructor(st: Status, sl: ServiceLog, events: LogEvent[], toLog: () => void) {
this.st = st;
this.sl = sl;
this.events = events;
this.toLog = toLog;
dom.content(this.el, [this.summary, this.wdEl, E('div', { class: 'dl-health-cols' }, [this.checksEl, this.recentEl])]);
this.paintChecks();
this.paintLive(sl, events);
}
/** Run the checks (they take a moment: DNS, ports, certificates). */
async run(fix?: string) {
const r = fix ? await attempt(() => api.healthFix(fix), 'Done') : await api.health().catch(() => null);
if (!r) return;
this.take(r);
}
take(r: Health) {
this.checks = r.checks;
this.paintChecks();
this.paintLive(r, this.events);
}
paintChecks() {
const checks = this.checks;
if (!checks) {
dom.content(this.summary, '');
dom.content(this.checksEl, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Checks')]),
E('p', { class: 'dl-muted dl-loading' }, 'Running checks…'),
]);
return;
}
const bad = checks.filter((c) => c.status === 'error').length;
const warn = checks.filter((c) => c.status === 'warn').length;
dom.content(
this.summary,
bad
? callout('error', `${bad} problem${bad > 1 ? 's' : ''} need attention.`)
: warn
? callout('warn', `${warn} warning${warn > 1 ? 's' : ''}.`)
: callout('ok', 'All checks passed.'),
);
const repaired = new Map<string, number>();
for (const x of this.sl.watchdog.repairs) repaired.set(x.id, Math.max(repaired.get(x.id) ?? 0, x.ts));
const refresh = () => this.run();
dom.content(this.checksEl, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Checks'), E('span', { class: 'dl-spacer' }), button('Run again', refresh)]),
E(
'ul',
{ class: 'dl-checks' },
checks.map((c) =>
E('li', {}, [
E('span', { class: `dl-check-icon ${c.status}` }, icon(ICON[c.status])),
E('div', { class: 'dl-check-body' }, [
E('div', { class: 'dl-check-title' }, c.title),
E('div', { class: 'dl-check-detail' }, c.detail),
repaired.has(c.id)
? E('div', { class: 'dl-check-repaired' }, `Repaired by the watchdog at ${clock(repaired.get(c.id)!)}`)
: '',
]),
c.fix
? c.fix.startsWith('install:')
? button('Install', () => installFeature(c.fix!.slice(8) as keyof Needs, refresh), 'action')
: c.fix === 'updates'
? E('a', { class: 'cbi-button cbi-button-action', href: L.url('admin/network/dawnline/updates') }, FIX_LABEL.updates)
: button(FIX_LABEL[c.fix] ?? 'Fix', () => this.run(c.fix!), 'action')
: '',
]),
),
),
]);
}
/** The watchdog card and recent problems; refreshed by the page poll without running the checks again. */
paintLive(sl: ServiceLog, events: LogEvent[]) {
this.sl = sl;
this.events = events;
const wd = sl.watchdog;
const stale = wd.beat != null && wd.now - wd.beat > 180;
const today = wd.repairs.filter((x) => wd.now - x.ts < 86400);
const lastRep = today[today.length - 1];
const toggle = sw(wd.enabled, 'Watchdog repairs', async (v) => {
const ok = await attempt(() => api.settingsUpdate({ watchdog: v ? '1' : '0' }), v ? 'Watchdog on' : 'Watchdog off');
if (!ok) toggle.classList.toggle('on', !v);
const n = await api.serviceLog().catch(() => null);
if (n) this.paintLive(n, this.events);
});
dom.content(
this.wdEl,
E('div', { class: 'dl-panel dl-wd' }, [
E('div', { class: 'dl-wd-head' }, [
E('span', { class: `dl-wd-tile${wd.enabled ? '' : ' off'}` }, icon('shield')),
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-wd-title' }, 'Watchdog'),
E(
'span',
{ class: 'dl-sub' },
wd.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.',
),
]),
E('span', { class: 'dl-spacer' }),
toggle,
]),
E('div', { class: 'dl-wd-foot' }, [
E(
'div',
{ class: 'dl-wd-chips' },
wd.targets.map((t) =>
E(
'span',
{
class: `dl-check-chip${t.ok ? '' : ' error'}`,
title: t.ok ? 'OK' : `Not working${t.tries ? ` · ${t.tries} repair${t.tries > 1 ? 's' : ''}` : ''}`,
},
[icon(t.ok ? 'check' : 'x'), t.name],
),
),
),
E(
'span',
{ class: `dl-sub${stale ? ' dl-warn-text' : ''}` },
stale
? `The agent has not checked in for ${Math.round((wd.now - wd.beat!) / 60)} min; cron restarts it after 5.`
: [
wd.last ? `Looked ${ago(wd.last, wd.now)}` : 'Starts within a minute',
' · ',
today.length
? `${today.length} repair${today.length > 1 ? 's' : ''} today, last ${lastRep.name} at ${clock(lastRep.ts)}`
: 'no repairs today',
],
),
]),
]),
);
this.paintRecent();
}
/** Problems from the last 7 days, both kinds, newest first. */
paintRecent() {
const since = Date.now() / 1000 - 7 * 86400;
const items: LogItem[] = [...this.events.map((ev) => ({ ts: ev.ts, ev })), ...this.sl.log.map((sys) => ({ ts: sys.ts, sys }))]
.filter((x) => x.ts >= since && isProblem(x))
.sort((a, b) => b.ts - a.ts);
const head = E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Recent problems'),
E('span', { class: 'dl-spacer' }),
items.length ? E('a', { href: '#', click: (e: Event) => (e.preventDefault(), this.toLog()) }, 'All in Log →') : '',
]);
if (!items.length) {
dom.content(this.recentEl, [
head,
E('div', { class: 'dl-recent-empty' }, [
E('span', { class: 'dl-check-icon ok' }, icon('check')),
'No problems in the last 7 days.',
]),
]);
return;
}
dom.content(this.recentEl, [
head,
...items.slice(0, 8).map((x) => {
if (x.sys) {
const e = x.sys;
const key = `${e.ts}|${e.msg}`;
return systemRow(
e,
this.open.has(key),
() => {
if (!this.open.delete(key)) this.open.add(key);
this.paintRecent();
},
clock(e.ts),
);
}
const row = eventRow(this.st, x.ev!);
row.lastElementChild!.textContent = clock(x.ts);
return row;
}),
]);
}
open = new Set<string>();
}
/** What Dawnline adds to OpenWrt; the portal's HTTPS and certificates only matter while it is on. */
const SYS_ITEMS: { title: string; sub: string; pkgs: string[]; feature: keyof Needs; optional?: boolean }[] = [
{ title: 'ip-full · veth', sub: 'Policy routing and the home-like link', pkgs: ['ip-full', 'kmod-veth'], feature: 'home' },
{ title: 'OpenSSL', sub: 'HTTPS for the personal portal', pkgs: ['libustream-openssl', 'openssl-util'], feature: 'https' },
{ title: 'ACME', sub: 'Let’s Encrypt certificate for the portal', pkgs: ['acme', 'acme-acmesh-dnsapi'], feature: 'acme', optional: true },
];
export class UpdatesPage {
root!: HTMLElement;
running = false;
load() {
return api.updatesStatus();
}
render(st: UpdatesStatus) {
this.root = E('div', { class: 'dl-root dl-upd' });
this.paint(st);
poll.add(async () => {
const n = await api.updatesStatus().catch(() => null);
if (n && n.job?.state === 'running') this.paint(n);
else if (n && this.running) {
this.running = false;
this.paint(n);
// A new Dawnline is installed: load its pages instead of running the old bundle.
if (n.job?.component === 'app' && n.job.state === 'done') {
ui.menu?.flushCache();
setTimeout(() => location.reload(), 1500);
}
}
}, 3);
return this.root;
}
paint(st: UpdatesStatus) {
const job = st.job;
this.running = job?.state === 'running';
const c = st.check?.components ?? {};
const fw = st.firmware;
const app = c.app,
awg = c.amneziawg,
pk = c.packages;
const busy = { disabled: this.running };
const pill = (tone: '' | 'ok' | 'accent' | 'warn' | 'bad', text: string) => E('span', { class: `dl-pill ${tone}` }, text);
const row = (title: Node | string | (Node | string)[], sub: Node | string | (Node | string)[], right: Node | string) =>
E('div', { class: 'dl-upd-row' }, [
E('span', { class: 'dl-stack' }, [E('span', { class: 'dl-upd-name' }, title), E('span', { class: 'dl-sub' }, sub)]),
right,
]);
const sec = (ic: string, title: string, sub: string, right: Node | string, rows: Node[] = []) =>
E('section', { class: 'dl-setsec dl-upd-sec' }, [
E('div', { class: 'dl-upd-head' }, [
E('span', { class: 'dl-group-ic' }, icon(ic)),
E('span', { class: 'dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, sub)]),
right,
]),
...rows,
]);
const date = (d: string | null) =>
d ? new Date(d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : '';
// Dawnline
const appSec = sec(
'sunrise',
'Dawnline',
app?.repo ? `${st.version} · ${app.repo}` : st.version,
!app
? pill('', 'Not checked')
: app.update
? button(`Update to ${app.latest}`, () => this.run('app'), 'positive', busy)
: app.latest
? pill('ok', 'Up to date')
: pill('', 'No releases yet'),
);
// AmneziaWG: one row per build source, then the translation
const srcs = awg?.sources ?? {};
const ids = Object.keys(srcs) as AwgSource[];
const awgRows = ids.map((id) => {
const x = srcs[id]!;
const mine = awg?.current === id;
const sub: (Node | string)[] = [
x.version
? `${x.tag} build${x.date ? ` · ${date(x.date)}` : ''} · ${x.gen === '3.1' ? 'devices need AmneziaVPN with 3.1' : 'works with every AmneziaWG app'}`
: `No build for OpenWrt ${fw?.version ?? ''}`,
];
const right = !x.version
? pill('', 'No build')
: mine
? awg?.update
? button('Update', () => this.runAwg(id, !!awg.ru, x.gen), 'positive', busy)
: pill('ok', 'Installed')
: button('Switch', () => this.runAwg(id, !!awg?.ru, x.gen), 'neutral', busy);
return row([x.gen ? `AmneziaWG ${x.gen}` : 'AmneziaWG', E('span', { class: 'dl-faint' }, ` · ${x.label}`)], sub, right);
});
if (awg?.current && srcs[awg.current]?.version)
awgRows.push(
row(
'Russian translation',
'LuCI pages for AmneziaWG in Russian',
button(awg.ru ? 'Remove' : 'Add', () => this.runAwg(awg.current!, !awg.ru, awg.gen), 'neutral', busy),
),
);
const awgSec = sec(
'shield',
'AmneziaWG',
awg?.installed ? `${awg.gen ? `${awg.gen} · ` : ''}${awg.installed} · changing it restarts every tunnel` : 'Not installed',
!awg ? pill('', 'Not checked') : '',
awgRows.length ? awgRows : [row('Builds for this router', 'Check for updates to see them.', '')],
);
// System packages: one row per thing Dawnline adds
const pkgs = pk?.pkgs ?? {};
const rows: Node[] = [];
// Only what the features in use need: the home-like link, and HTTPS and certificates while the portal is on.
const items = SYS_ITEMS.filter((it) => (it.feature === 'home' ? st.home : st.portal));
for (const it of items) {
const present = it.pkgs.filter((p) => pkgs[p]?.installed);
// The package itself and what is released with it (the rest of LuCI, libopenssl, rpcd)
const upd = [...new Set(present.flatMap((p) => [...(pkgs[p]?.latest ? [p] : []), ...(pkgs[p]?.with ?? [])]))];
// What the router lacks for this feature (any TLS module counts for HTTPS, not only OpenSSL's).
const lacks = st.needs?.[it.feature] ?? it.pkgs.filter((p) => !pkgs[p]?.installed);
if (lacks.length) {
rows.push(
row(
it.title,
it.optional ? `Not installed · ${it.sub}` : E('span', { class: 'dl-upd-bad' }, `Missing ${lacks.join(', ')} · ${it.sub}`),
button('Install', () => this.runPkgs(lacks, it.title), 'neutral', busy),
),
);
} else if (upd.length) {
const main = present.find((p) => pkgs[p]?.latest);
const v: (Node | string)[] = main
? [E('span', { class: 'dl-mono' }, [`${pkgs[main]!.installed} → `, E('b', {}, pkgs[main]!.latest!)])]
: [];
const rel = upd.filter((p) => p !== main);
if (rel.length)
v.push(
`${main ? ' · ' : ''}${rel.length <= 2 ? `${main ? 'with ' : ''}${rel.join(', ')}` : `${main ? '+' : ''}${rel.length} related packages`}`,
);
rows.push(
row(
it.title,
v,
button(
'Update',
() =>
this.runPkgs(
present.filter((p) => pkgs[p]?.latest || pkgs[p]?.with?.length),
it.title,
upd,
),
'neutral',
busy,
),
),
);
} else rows.push(row(it.title, it.sub, pill('ok', 'Up to date')));
}
const shown = items.flatMap((it) => it.pkgs).filter((k) => pkgs[k]?.installed);
const allUpd = [...new Set(shown.flatMap((k) => [...(pkgs[k].latest ? [k] : []), ...(pkgs[k].with ?? [])]))];
const pkgSec = sec(
'package',
'System packages',
!pk
? 'What Dawnline adds to OpenWrt'
: allUpd.length
? `${allUpd.length} update${allUpd.length === 1 ? '' : 's'} from the OpenWrt ${fw?.version?.replace(/\.\d+$/, '') ?? ''} feeds`
: 'What Dawnline adds to OpenWrt is current',
!pk
? pill('', 'Not checked')
: allUpd.length
? button(
'Update all',
() =>
this.runPkgs(
shown.filter((k) => pkgs[k].latest || pkgs[k].with?.length),
'all packages',
allUpd,
),
'positive',
busy,
)
: '',
pk ? rows : [],
);
// The last job, folded
const jobCard = job
? E('details', { class: 'dl-params dl-upd-job', open: this.running ? 'open' : null }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Last job'),
pill(
job.state === 'done' ? 'ok' : job.state === 'failed' ? 'bad' : 'warn',
job.state === 'running' ? job.phase || 'Running' : job.state === 'done' ? 'Finished' : 'Failed',
),
E(
'span',
{ class: 'dl-sub' },
`${job.action === 'check' ? 'check' : (job.component ?? '')} · ${clock(job.started)}${job.finished ? ` · ${job.finished - job.started} s` : ''}`,
),
]),
job.error ? callout('error', job.error) : '',
E('pre', { class: 'dl-log' }, job.log.join('\n')),
])
: '';
const total = allUpd.length + (app?.update ? 1 : 0) + (awg?.update ? 1 : 0);
const facts = [
fw?.version ? `OpenWrt ${fw.version} · ${fw.target}` : '',
st.check ? (total ? `${total} update${total === 1 ? '' : 's'} ready` : 'everything is current') : 'not checked yet',
st.check ? `checked ${clock(st.check.time)}` : '',
]
.filter(Boolean)
.join(' · ');
dom.content(this.root, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Updates'), E('span', { class: 'dl-faint' }, facts)]),
button([icon('refresh'), ' Check now'], () => this.run('check'), 'neutral', busy),
]),
appSec,
awgSec,
pkgSec,
jobCard,
]);
}
async runAwg(id: AwgSource, ru: boolean, gen: string | null | undefined) {
const ok = await confirmDialog(
gen ? `Install AmneziaWG ${gen}?` : 'Install AmneziaWG?',
'Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.',
'Install',
);
if (ok) this.start(`amneziawg:${id}${ru ? ':ru' : ''}`);
}
/** names: Dawnline's own packages (the updater adds their family); shown: everything that will change. */
async runPkgs(names: string[], what: string, shown = names) {
const ok = await confirmDialog(
`Update ${what}?`,
`${shown.join(', ')} from the OpenWrt feeds. Services that use them restart for a moment.`,
'Update',
);
if (ok) this.start(`pkgs:${names.join(',')}`);
}
async run(what: string) {
if (what !== 'check') {
const ok = await confirmDialog(
`Update ${what === 'app' ? 'Dawnline' : what}?`,
'A backup is made first. The page reloads when it finishes.',
'Update',
);
if (!ok) return;
}
this.start(what);
}
async start(what: string) {
if (await attempt(() => api.updatesRun(what))) {
this.running = true;
const n = await api.updatesStatus().catch(() => null);
if (n) this.paint(n);
}
}
}
+55 -401
View File
@@ -2,220 +2,41 @@
// online, traffic, disguise, the connection map, activity and what needs
// attention — all limited to the people on that server.
import type { DayUsage, Device, LogEvent, Person, Status } from '../../shared/types';
import type { Device, Person, Status } from '../../shared/types';
import { E } from '../e';
import { api } from '../api';
import { svg } from '../ui';
import { svg } from '../ui/layout';
import { attachTip } from '../ui/tooltip';
import { icon } from '../../shared/icons';
import { ago, bits, bytes, daysLeft, initials } from '../../shared/format';
import { ago, bits, bytes, daysLeft, initials, todayOf } from '../../shared/format';
import { ConnectionMap, rangeControl, type Range } from '../map';
import { attachTip } from '../charts';
import { methodInfo } from '../disguise';
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 { coreOf } from '../cores';
import { healthNotices, runFix } from '../widgets/health';
const EVENT_TONE: Record<string, string> = {
connect: 'ok',
disconnect: '',
roam: '',
device_added: 'ok',
device_removed: '',
person_added: '',
person_removed: '',
paused: 'warn',
resumed: 'ok',
paused_all: 'warn',
resumed_all: 'ok',
portal_blocked: 'bad',
person_changed: '',
devices_removed: 'warn',
};
/** The icon in an event's tile: the device's kind for device events, else what happened. */
const EVENT_ICON: Record<string, string> = {
devices_removed: 'trash',
link_changed: 'link',
person_added: 'plus',
person_removed: 'trash',
person_changed: 'edit',
paused: 'pause',
resumed: 'play',
paused_all: 'pause',
resumed_all: 'play',
};
function eventIcon(st: Status, e: LogEvent): string {
if (e.device) {
const d = st.people.flatMap((p) => p.devices).find((x) => x.id === e.device);
return d?.kind ?? e.dkind ?? 'other';
}
return EVENT_ICON[e.type] ?? 'activity';
}
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed', 'paused_all', 'resumed_all'];
/** Who did it. Older events have no `by`: LuCI and the portal marked it in the detail. */
export function eventBy(e: LogEvent): 'admin' | 'portal' | null {
if (e.by) return e.by;
if (ADMIN_TYPES.includes(e.type) || e.detail === 'by admin' || e.detail?.endsWith(' (admin)')) return 'admin';
if (e.detail?.endsWith(' (portal)')) return 'portal';
return null;
}
/** The detail without the old "(admin)" / "(portal)" / "by admin" marks. */
function plainDetail(e: LogEvent): string {
return (e.detail ?? '').replace(/ \((admin|portal)\)$/, '').replace(/^by admin$/, '');
}
export function eventText(st: Status, e: LogEvent): Node[] {
const person = st.people.find((p) => p.id === e.person);
const who = person?.name ?? e.pname ?? e.person ?? '';
const dev = person?.devices.find((d) => d.id === e.device)?.name ?? e.dname ?? '';
const b = (t: string) => E('b', {}, t);
const m = (t: string) => E('span', { class: 'dl-muted' }, t);
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
/** An address; at home, the name of the device that has it, with the address in brackets. */
const addr = (ip: string) =>
e.hosts?.[ip]
? [E('span', { class: 'dl-ev-host' }, [E('b', {}, e.hosts[ip]), E('span', { class: 'dl-faint' }, ` (${ip})`)])]
: [mono(ip)];
// What the bold name is (a person, a device), said before it in grey.
const kind = (t: string) => E('span', { class: 'dl-ev-kind' }, `${t} `);
const wd = dev ? `${who} · ${dev}` : who;
const detail = plainDetail(e);
const devName = detail || dev || 'a device';
// The admin's own actions start with an accent "You".
const you = (verb: string) => [E('span', { class: 'dl-you' }, 'You'), m(` ${verb} `)];
if (eventBy(e) === 'admin')
switch (e.type) {
case 'device_added':
return [...you('added'), kind('device'), b(devName), m(' for '), b(who)];
case 'device_removed':
return [...you('removed'), kind('device'), b(devName), m(' from '), b(who)];
case 'paused':
return [...you('paused'), kind('person'), b(who)];
case 'resumed':
return [...you('resumed'), kind('person'), b(who)];
case 'device_changed': {
const renamed = detail.startsWith('renamed from ');
return [
...you(renamed ? 'renamed' : detail),
kind('device'),
b(dev || 'a device'),
m(' of '),
b(who),
...(renamed ? [m(` · was ${detail.slice(13)}`)] : []),
];
}
case 'device_keys':
return [...you('issued new keys for'), kind('device'), b(devName), m(' of '), b(who), m(' · it needs its new configuration')];
case 'link_changed':
return [...you('issued a new link for'), kind('person'), b(who), m(' · the old link stopped working')];
case 'paused_all':
return [E('span', { class: 'dl-you' }, 'You'), m(' paused everyone')];
case 'resumed_all':
return [E('span', { class: 'dl-you' }, 'You'), m(' resumed everyone')];
}
switch (e.type) {
case 'connect':
return [
kind('Device'),
b(wd),
m(' connected'),
...(e.detail ? [m(' from '), ...addr(e.detail)] : []),
...(e.where ? [m(` · ${e.where}`)] : []),
];
case 'disconnect':
return [kind('Device'), b(wd), m(' went offline')];
case 'roam':
return [
kind('Device'),
b(wd),
m(' changed network '),
...(e.detail ?? '').split(' → ').flatMap((ip, i) => (i ? [m(' → '), ...addr(ip)] : addr(ip))),
];
case 'device_added':
return [
kind('Person'),
b(who),
m(' added '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
case 'device_removed':
return [
kind('Person'),
b(who),
m(' removed '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
case 'device_keys':
return [kind('Person'), b(who), m(' issued new keys for '), kind('device'), b(devName), m(' on their portal')];
case 'person_added':
return [...you('added'), kind('person'), b(e.detail ?? who)];
case 'person_removed':
return [...you('removed'), kind('person'), b(e.detail ?? who)];
case 'person_changed':
// The detail lists changed fields by their option names (device_limit, expire_action).
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
case 'paused':
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
case 'resumed':
return [kind('Person'), b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])];
case 'paused_all':
return [m('Everyone paused')];
case 'resumed_all':
return [m('Everyone resumed')];
case 'portal_blocked':
return [
E('b', { class: 'dl-sys-src' }, 'Personal portal'),
m(' blocked '),
mono(e.detail ?? ''),
m(' for 15 min after too many wrong codes'),
];
case 'devices_removed':
return [kind('Person'), b(who), m(' — all devices removed, end date reached')];
default:
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
}
}
/** Events about the router rather than people look like service log lines: icon tile, colour by outcome. */
const SYSTEM_EVENT: Record<string, [string, string]> = {
portal_blocked: ['globe', 'bad'],
};
/** With several servers, which one a person's event happened on (left out where that is clear). */
function serverPill(st: Status, e: LogEvent): HTMLElement | '' {
if (st.servers.length < 2 || !e.person) return '';
const p = st.people.find((x) => x.id === e.person);
const srv = p && st.servers.find((s) => s.id === p.server);
return srv ? E('span', { class: 'dl-ev-srv', title: 'Server' }, srv.name) : '';
}
export function eventRow(st: Status, e: LogEvent, opts: { server?: boolean } = {}): HTMLElement {
const sys = SYSTEM_EVENT[e.type];
const by = eventBy(e);
return E('div', { class: `dl-row${by === 'admin' ? ' dl-ev-by-admin' : sys ? ` dl-ev-by-system ${sys[1]}` : ''}` }, [
by === 'admin'
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: sys
? E('span', { class: 'dl-ev-tile sys' }, icon(sys[0]))
: E('span', { class: `dl-ev-tile ev ${EVENT_TONE[e.type] ?? ''}` }, icon(eventIcon(st, e))),
E('span', { class: 'dl-row-main' }, eventText(st, e)),
opts.server === false ? '' : serverPill(st, e),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, ago(e.ts, st.now)),
]);
interface Attention {
tone: string;
text: (Node | string)[];
/** A button or link that deals with it. */
action?: Node;
}
/** Things worth the admin's attention, most important first. */
function attention(st: Status): { tone: string; text: (Node | string)[] }[] {
const out: { tone: string; text: (Node | string)[] }[] = [];
function attention(st: Status): Attention[] {
const out: Attention[] = [];
const link = (href: string, t: string) => E('a', { href }, t);
const today = todayOf(st.series);
// AmneziaWG itself can't run: the health notice says so once, not "Tunnel down" for every server.
const awg = !!st.awg_state && !st.awg_state.ok;
for (const s of st.servers)
if (s.enabled && !s.up)
if (s.enabled && s.blocked)
// The reason, not just "down": its interface name is taken by a network section Dawnline didn't make.
out.push({ tone: 'bad', text: [`${s.name} ${s.blocked}. `, link(L.url('admin/network/dawnline/diagnostics'), 'Open Diagnostics')] });
else if (s.enabled && !s.up && !awg)
out.push({
tone: 'bad',
text: [`Tunnel ${s.ifname} is down. `, link(L.url('admin/network/dawnline/diagnostics'), 'Open Diagnostics')],
@@ -225,7 +46,7 @@ function attention(st: Status): { tone: string; text: (Node | string)[] }[] {
if (p.state === 'quota') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), ' reached the data limit.'] });
else if (p.state === 'expired') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), '’s access has ended.'] });
else {
const left = daysLeft(p.expires);
const left = daysLeft(p.expires, today);
if (left != null && left >= 0 && left <= Math.max(p.expire_warn, 3))
out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s access ends in ${left} day${left === 1 ? '' : 's'}.`] });
if (p.quota_limit && p.quota_used >= p.quota_limit * 0.9)
@@ -254,42 +75,6 @@ function attention(st: Status): { tone: string; text: (Node | string)[] }[] {
return out;
}
/**
* The status as seen from one server: its people, their devices, traffic,
* map points and events (plus router-wide events without a person).
*/
export function scoped(st: Status, srvId: string): Status {
const srv = st.servers.find((s) => s.id === srvId) ?? st.servers[0];
const people = st.people.filter((p) => p.server === srv.id);
const ids = new Set(people.map((p) => p.id));
const devices = people.flatMap((p) => p.devices);
const sum = (f: (p: Person) => [number, number]) =>
people.reduce<[number, number]>(
(a, p) => {
const v = f(p);
return [a[0] + v[0], a[1] + v[1]];
},
[0, 0],
);
const today = srv.series?.[srv.series.length - 1];
return {
...st,
servers: [srv],
people,
series: srv.series ?? st.series,
events: st.events.filter((e) => (e.person ? ids.has(e.person) : true)),
geo: { ...st.geo, points: st.geo.points.filter((g) => ids.has(g.person)) },
totals: {
people: people.length,
devices: devices.length,
online: devices.filter((d) => d.online).length,
active: people.filter((p) => p.state === 'active').length,
today: today ? [today.rx, today.tx] : [0, 0],
month: sum((p) => p.month),
},
};
}
export class ServerOverview {
st!: Status;
el = E('div', { class: 'dl-srvov' });
@@ -319,42 +104,31 @@ export class ServerOverview {
return this.el;
}
update(st: Status) {
/** New status; a `quiet` (periodic) update leaves alone a part that has the keyboard focus. */
update(st: Status, quiet = false) {
this.st = scoped(st, this.srvId);
this.paint();
this.paint(quiet);
this.map?.update(this.mapData());
// Health checks cost more than a status call: once a minute is plenty.
if (Date.now() - this.healthAt > 60_000) void this.loadHealth();
}
/** A strip above the bento, only while Health has warnings or errors. */
/** Notices above the bento for the checks that failed (with their fix), only while Health has any. */
async loadHealth() {
this.healthAt = Date.now();
const r = await api.health().catch(() => null);
if (!r) return;
const bad = r.checks.filter((c) => c.status === 'warn' || c.status === 'error');
if (!bad.length) {
dom.content(this.parts.health, '');
return;
}
const errors = bad.filter((c) => c.status === 'error').length;
const label = `${bad.length} ${errors ? (bad.length === 1 ? 'problem' : 'problems') : bad.length === 1 ? 'warning' : 'warnings'}`;
dom.content(
const again = () => void this.loadHealth();
const run = async (fix: string) => {
if (!(await runFix(fix))) return;
again();
// The network restarts a second after the answer: look again once it is back.
if (fix === 'netrestart') setTimeout(again, 5000);
};
repaint(
this.parts.health,
E('div', { class: `dl-healthstrip ${errors ? 'bad' : 'warn'}` }, [
E('span', { class: 'dl-healthstrip-title' }, [icon('alert'), label]),
...bad.slice(0, 3).map((c) => {
const it = E('span', { class: 'dl-healthstrip-item' }, c.title);
attachTip(it, () => [E('div', { class: 'dl-tip-title' }, c.title), E('div', { class: 'dl-muted' }, c.detail)]);
return it;
}),
bad.length > 3 ? E('span', { class: 'dl-sub' }, `+${bad.length - 3} more`) : '',
E(
'a',
{ href: L.url('admin/network/dawnline/diagnostics') },
bad.some((c) => c.fix) ? 'Fix in Diagnostics →' : 'Open Diagnostics →',
),
]),
healthNotices(r.checks, (fix) => void run(fix), again),
true,
);
}
@@ -401,19 +175,19 @@ export class ServerOverview {
return E('div', { class: 'dl-panel flush' }, [head, wrap]);
}
paint() {
paint(quiet = false) {
const st = this.st;
const srv = st.servers[0];
const slots = st.people.reduce((a, p) => a + Math.max(0, p.device_limit - p.devices.length), 0);
const online = st.people.flatMap((p) => p.devices.filter((d) => d.online));
dom.content(
repaint(
this.parts.bento,
E('div', { class: 'dl-bento' }, [this.onlineTile(online), this.speedTile(), this.disguiseTile(srv), this.monthTile(slots)]),
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile(slots)]),
quiet,
);
const att = attention(st);
dom.content(
repaint(
this.parts.side,
E('div', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
@@ -424,13 +198,20 @@ export class ServerOverview {
att.length
? att
.slice(0, 8)
.map((a) => E('div', { class: 'dl-attn-item dl-row' }, [E('span', { class: `dl-ev-dot ${a.tone}` }), E('span', {}, a.text)]))
.map((a) =>
E('div', { class: 'dl-attn-item dl-row' }, [
E('span', { class: `dl-ev-dot ${a.tone}` }),
E('span', {}, a.text),
a.action ?? '',
]),
)
: E('div', { class: 'dl-row dl-muted' }, [icon('check'), 'All good. Nothing needs you right now.']),
]),
quiet,
);
const events = [...st.events].reverse().slice(0, 8);
dom.content(
repaint(
this.parts.activity,
E('div', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
@@ -442,6 +223,7 @@ export class ServerOverview {
? events.map((e) => eventRow(st, e))
: E('div', { class: 'dl-row dl-muted' }, 'Nothing yet. Connections, new devices and pauses appear here.'),
]),
quiet,
);
}
@@ -451,7 +233,7 @@ export class ServerOverview {
* then +N). The device badge is the main device, or a count. Hover: a live
* card with speed, devices and today's traffic. Nobody: when someone was last seen.
*/
onlineTile(_online: Device[]): HTMLElement {
onlineTile(): HTMLElement {
const st = this.st;
const CAP = 12;
const today = (d: Device) => d.spark[d.spark.length - 1] ?? 0;
@@ -596,49 +378,6 @@ export class ServerOverview {
return speedTile(this.st.servers[0]?.rate ?? [], this.st.now, this.st.totals.today);
}
disguiseTile(srv: Status['servers'][number]): HTMLElement {
const m = methodInfo(srv.preset);
const o = srv.obf ?? {};
const segs = (n: number, cls: string) =>
E(
'span',
{ class: `dl-segs ${cls}` },
[0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })),
);
// The values devices carry, in words.
const chips: string[] = [];
if (+o.jc) chips.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);
const pad = ['s1', 's2', 's3', 's4'].filter((k) => +o[k]).map((k) => `${k.toUpperCase()} ${o[k]}`);
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(o.i1.includes('0x8580') ? 'DNS-like first packet' : 'Signature packets');
if (o.header_protection_key) 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' }, [
E('span', { class: 'dl-metric-label' }, 'Disguise'),
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}&section=disguise` }, 'Change'),
]),
E('div', { class: 'dl-disg-id' }, [
E('span', { class: 'dl-disg-ic' }, icon(m?.ic ?? 'shield')),
E('span', { class: 'dl-stack' }, [E('b', {}, m ? m.title : 'Custom'), E('span', { class: 'dl-sub' }, m ? m.short : 'Set by hand')]),
]),
m
? E('div', { class: 'dl-disg-meters' }, [
E('span', {}, 'Stealth'),
segs(m.stealth, 'acc'),
E('span', {}, 'Speed'),
segs(m.speed, 'ok'),
])
: '',
E(
'div',
{ class: 'dl-disg-chips' },
chips.map((c) => E('span', {}, c)),
),
]);
}
/** The last 30 days, today on the right, with the peak; plus the people summary. */
monthTile(slots: number): HTMLElement {
const t = this.st.totals;
@@ -649,88 +388,3 @@ export class ServerOverview {
);
}
}
/** Throughput over the last 15 minutes plus today's total. */
export function speedTile(rate: [number, number, number][], now: number, today: [number, number]): 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
? 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'), 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}`]),
E('span', { class: 'dl-speed-val' }, bits(v)),
]);
if (pts.length > 1)
attachTip(chart as HTMLElement, () => {
const p = pts[pts.length - 1];
return [
E('div', { class: 'dl-tip-title' }, new Date(p[0] * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })),
E('div', {}, `↓ ${bits(p[2])} · ↑ ${bits(p[1])}`),
];
});
return E('div', { class: 'dl-bento-tile' }, [
E('div', { class: 'dl-bento-head' }, [
E('span', { class: 'dl-metric-label' }, 'Speed now'),
E('span', { class: 'dl-sub' }, 'last 15 min'),
]),
E('div', { class: 'dl-speed-cols' }, [col('Download', '↓', 'dl-dn', down), col('Upload', '↑', 'dl-up', up)]),
chart,
E('div', { class: 'dl-speed-today' }, [
E('span', {}, ['Today ', E('b', {}, bytes(rx + tx))]),
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]),
]),
]);
}
/** Daily traffic for the last 30 days, today on the right. */
export function daysTile(series: DayUsage[], note: string): HTMLElement {
const days = series.slice(-30);
const vals = days.map((d) => d.rx + d.tx);
const max = Math.max(1, ...vals);
const total = vals.reduce((a, v) => a + v, 0);
const peakI = vals.reduce((a, v, i) => (v > vals[a] ? i : a), 0);
const label = (day: string) => new Date(`${day}T12:00:00`).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
const bars = E(
'div',
{ class: 'dl-bento-bars' },
days.map((d, i) => {
const v = vals[i];
const bar = E('i', { class: i === days.length - 1 ? 'hi' : '', style: `height:${Math.max(4, (v / max) * 100)}%` });
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `Today · ${label(d.day)}` : label(d.day)),
E('div', {}, bytes(v)),
E('div', { class: 'dl-muted dl-mono' }, `↓ ${bytes(d.tx)} ↑ ${bytes(d.rx)}`),
]);
return bar;
}),
);
return E('div', { class: 'dl-bento-tile month' }, [
E('div', { class: 'dl-bento-head' }, [
E('span', {}, [E('span', { class: 'dl-metric-label' }, 'Last 30 days'), E('b', { class: 'dl-bento-total' }, bytes(total))]),
vals[peakI] > 0 ? E('span', { class: 'dl-sub' }, `peak ${bytes(vals[peakI])} · ${label(days[peakI].day)}`) : '',
]),
days.length ? bars : E('p', { class: 'dl-muted' }, 'No traffic yet.'),
E('div', { class: 'dl-bento-head' }, [
E('span', { class: 'dl-sub' }, days.length ? label(days[0].day) : ''),
E('span', { class: 'dl-sub' }, note),
E('span', { class: 'dl-sub' }, 'today'),
]),
]);
}
+195 -244
View File
@@ -1,39 +1,41 @@
// People: a native GridSection over `person` sections rendered as cards.
// Edits in the modal are staged (Save & Apply with rollback); creating,
// pausing and device actions take effect immediately through RPC.
// People: one card per person, built from the status (the config itself,
// with keys, is never read by the browser). Creating, editing, pausing and
// device actions take effect immediately through RPC.
import type { Person, Status } from '../../shared/types';
import { E } from '../e';
import { api } from '../api';
import { attempt, button, closeModal, confirmDialog, copyText, dropdown, iconButton, modal, notify, type MenuItem } from '../ui';
import { addDevice, openDevice } from '../device';
import { inviteCard } from '../invite';
import { button, iconButton } from '../ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from '../ui/modal';
import { copyText } from '../ui/files';
import { dropdown, type MenuItem } from '../ui/menu';
import { attempt, notify } from '../ui/toast';
import { attachTip } from '../ui/tooltip';
import { accessBadge, stateBadge } from '../ui/badges';
import { addDevice, openDevice, type DeviceOpts } from '../device';
import { copyPersonLink, inviteCard } from '../invite';
import { personUrl } from '../urls';
import { scoped } from './overview';
import { attachTip } from '../charts';
import { scoped } from '../state/scope';
import { createPoller, focusInside, type Poller } from '../state/poller';
import { accessPicker } from '../widgets/access-picker';
import { coreFor } from '../cores';
import { icon } from '../../shared/icons';
import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, bits, byDeviceState, bytes, date, daysLeft, initials } from '../../shared/format';
import {
KIND_LABEL,
addMonthsClamped,
ago,
bits,
byDeviceState,
bytes,
date,
dayDiff,
daysLeft,
initials,
todayOf,
} from '../../shared/format';
type Sid = string;
const STATE_ICON: Record<Person['state'], string> = {
active: '',
paused: 'pause',
paused_all: 'pause',
expired: 'calendar',
quota: 'chart',
hours: 'clock',
no_server: 'alert',
};
/** Nothing while active; otherwise a small icon with the state as tooltip. */
export function stateBadge(p: Person): HTMLElement | '' {
if (p.state === 'active') return '';
const el = E('span', { class: `dl-ibadge ${stateTone(p)}`, 'aria-label': STATE_LABEL[p.state] }, icon(STATE_ICON[p.state] || 'alert'));
attachTip(el, () => [E('div', { class: 'dl-tip-title' }, STATE_LABEL[p.state])]);
return el;
}
/** Device slots as a row of segments (one per allowed device, used ones lit) and "2 of 10". */
function slotBar(p: Person): HTMLElement {
const used = p.devices.length;
@@ -51,69 +53,11 @@ function slotBar(p: Person): HTMLElement {
]);
}
/** What the person can reach, as icons: home network, internet, or both. */
export function accessBadge(p: Person): HTMLElement {
const kinds = p.access === 'both' ? ['lan', 'inet'] : p.access === 'lan' ? ['lan'] : ['inet'];
const el = E(
'span',
{ class: 'dl-access', 'aria-label': ACCESS_LABEL[p.access] },
kinds.map((k) => E('span', { class: `dl-ibadge ${k}` }, icon(k === 'lan' ? 'home' : 'globe'))),
);
attachTip(el, () => [
E('div', { class: 'dl-tip-title' }, ACCESS_LABEL[p.access]),
p.access === 'lan' && p.services?.length
? E('div', { class: 'dl-muted' }, `${p.services.length} home service${p.services.length === 1 ? '' : 's'} only`)
: '',
]);
return el;
}
export function stateTone(p: Person): string {
if (p.state === 'active') return 'ok';
if (p.state === 'quota' || p.state === 'expired') return 'bad';
return 'warn';
}
/** Access choice cards; returns the element and a getter. */
export function accessPicker(initial: Person['access'], onChange?: (v: Person['access']) => void) {
let value = initial;
const opts: { v: Person['access']; ic: string; text: string }[] = [
{ 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.' },
];
const el = E(
'div',
{ class: 'dl-choices' },
opts.map((o) =>
E(
'button',
{
type: 'button',
class: `dl-choice${o.v === value ? ' selected' : ''}`,
'data-v': o.v,
click: () => {
value = o.v;
el.querySelectorAll('.dl-choice').forEach((c) => c.classList.toggle('selected', (c as HTMLElement).dataset.v === o.v));
onChange?.(o.v);
},
},
[E('span', { class: 'dl-choice-title' }, [icon(o.ic), ACCESS_LABEL[o.v]]), E('span', { class: 'dl-choice-text' }, o.text)],
),
),
);
return { el, get: () => value };
}
function isoDate(d: Date): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
type Filter = 'all' | 'online' | 'attention' | 'paused';
type SortBy = 'seen' | 'name' | 'usage';
function needsAttention(p: Person): boolean {
const left = daysLeft(p.expires);
function needsAttention(p: Person, today: string): boolean {
const left = daysLeft(p.expires, today);
return (
p.state === 'quota' ||
p.state === 'expired' ||
@@ -122,18 +66,23 @@ function needsAttention(p: Person): boolean {
);
}
function addMonth(iso: string): string {
const d = iso ? new Date(`${iso}T12:00:00`) : new Date();
const from = d.getTime() < Date.now() ? new Date() : d;
from.setMonth(from.getMonth() + 1);
return `${from.getFullYear()}-${String(from.getMonth() + 1).padStart(2, '0')}-${String(from.getDate()).padStart(2, '0')}`;
/** A month more, from the end date or from today once it has passed. */
function addMonth(end: string, today: string): string {
return addMonthsClamped(end && dayDiff(end, today) >= 0 ? end : today, 1);
}
const ids = (st: Status) =>
st.people
.map((p) => p.id)
.sort()
.join(' ');
let addOpened = false;
export class PeoplePage {
st!: Status;
map: any;
/** The cards, one per person, in the current sort order. */
private list: HTMLElement = E('div', { class: 'dl-plist', role: 'list' });
// `?filter=online` (from Overview) preselects a tab.
filter: Filter =
(['all', 'online', 'attention', 'paused'] as Filter[]).find((f) => f === new URLSearchParams(location.search).get('filter')) ?? 'all';
@@ -141,8 +90,8 @@ export class PeoplePage {
noFooter = true;
/** Set when shown as a server's People section: only that server's people. */
serverId: string | null = null;
polling = false;
el: HTMLElement | null = null;
poller?: Poller<Status>;
async load(): Promise<Status> {
return api.status(30);
@@ -163,127 +112,144 @@ export class PeoplePage {
return this.st.people.find((p) => p.id === sid);
}
/**
* Status for this page, newest request wins: a poll that started before an
* edit must not paint its older answer over the refresh that follows it.
*/
private statusSeq = 0;
private statusShown = 0;
async latestStatus(): Promise<Status | null> {
const seq = ++this.statusSeq;
const st = await api.status(30).catch(() => null);
if (!st || seq < this.statusShown) return null;
this.statusShown = seq;
return st;
get today(): string {
return todayOf(this.st.series);
}
/** What a device drawer opened from here gets. */
deviceOpts(p: Person): DeviceOpts {
return {
refresh: () => this.refresh(),
geo: this.st.geo,
now: this.st.now,
today: this.today,
core: coreFor(this.st.servers, p.server),
};
}
/**
* A new status (newest answer wins, see the poller). People added or removed
* elsewhere re-render the list; otherwise the cards repaint in place.
*/
take(stAll: Status, quiet: boolean) {
const st = this.scope(stAll);
const changed = ids(st) !== ids(this.st);
this.st = st;
if (changed) this.rebuild();
else {
this.paintCards(quiet);
this.decorate(quiet);
}
}
/** Repaint the cards from a fresh status (after a change made here). */
async update() {
await this.poller?.refresh();
}
/** Everything again, the form's sections too (after adding or removing someone). */
async refresh() {
const st = await this.latestStatus();
this.poller?.claim();
const st = await api.status(30).catch(() => null);
if (!st) return;
this.st = this.scope(st);
uci.unload('dawnline');
await this.map.load();
await this.map.reset();
// The map keeps cards it already drew: paint them from the new status, like poll().
this.paintCards();
this.rebuild();
}
/** One card per person (cards already shown are kept and repainted), or the empty state. */
rebuild() {
const old = new Map<string, HTMLElement>();
for (const el of Array.from(this.list.children) as HTMLElement[]) if (el.dataset.sid) old.set(el.dataset.sid, el);
const cards = this.st.people.map((p) => {
const card = old.get(p.id) ?? E('div', { class: 'dl-card', role: 'listitem', 'data-sid': p.id });
return this.renderCard(card, p.id);
});
dom.content(
this.list,
cards.length
? cards
: E(
'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() {
/** `quiet` (a periodic repaint) leaves alone a card that has the keyboard focus. */
paintCards(quiet = false) {
for (const p of this.st.people) {
const card = document.getElementById(`dl-card-${p.id}`);
if (card) this.renderCard(card, p.id);
const card = this.card(p.id);
if (card && !(quiet && focusInside(card))) this.renderCard(card, p.id);
}
}
/** This page's card for a person (a server's People section has its own list). */
card(sid: Sid): HTMLElement | null {
return this.list.querySelector<HTMLElement>(`[data-sid="${CSS.escape(sid)}"]`);
}
render(stAll: Status): Promise<Node> {
const st = this.scope(stAll);
this.st = st;
const page = this;
let o: any;
const m = new form.Map('dawnline');
this.map = m;
const s = m.section(form.GridSection, 'person');
s.anonymous = true;
s.addremove = true;
s.addbtntitle = 'Add person';
s.nodescriptions = true;
s.renderSectionPlaceholder = () =>
E(
'em',
{},
st.servers.length ? 'No people yet. Add someone and send them their personal link.' : 'Set up the server first, then add people.',
);
// As a server section: only rows of people on that server.
if (page.serverId) s.filter = (sid: Sid) => page.st.people.some((p) => p.id === sid);
s.handleAdd = () => page.openCreate();
s.handleRemove = (sid: Sid) => page.remove(sid);
// Actions live inside the card (title row).
s.renderRowActions = () => E('div', { class: 'dl-none' });
o = s.option(form.DummyValue, '_card');
o.modalonly = false;
o.textvalue = (sid: Sid) => page.renderCard(E('div', { class: 'dl-card', id: `dl-card-${sid}` }), sid);
return m.render().then((node: HTMLElement) => {
node.classList.add('dl-map', 'dl-root');
const sort = E(
'select',
{
class: 'dl-select',
'aria-label': 'Sort',
change: (ev: Event) => {
page.sort = (ev.target as HTMLSelectElement).value as SortBy;
page.decorate();
},
const sort = E(
'select',
{
class: 'dl-select',
'aria-label': 'Sort',
change: (ev: Event) => {
page.sort = (ev.target as HTMLSelectElement).value as SortBy;
page.decorate();
},
[E('option', { value: 'seen' }, 'Last seen'), E('option', { value: 'name' }, 'Name'), E('option', { value: 'usage' }, 'Usage')],
);
const wrap = E('div', { class: 'dl-root' }, [
page.serverId
? ''
: E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [
E('h2', { class: 'dl-h1' }, 'People'),
E('span', { class: 'dl-muted', id: 'dl-people-count' }, this.countText()),
]),
st.servers.length ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
},
[E('option', { value: 'seen' }, 'Last seen'), E('option', { value: 'name' }, 'Name'), E('option', { value: 'usage' }, 'Usage')],
);
const wrap = E('div', { class: 'dl-root' }, [
page.serverId
? ''
: E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [
E('h2', { class: 'dl-h1' }, 'People'),
E('span', { class: 'dl-muted dl-people-count' }, this.countText()),
]),
st.servers.length
? ''
: E('div', { class: 'alert-message warning' }, [
'No server yet. ',
E('a', { href: L.url('admin/network/dawnline/server') }, 'Run the setup wizard'),
' before adding people.',
]),
E('div', { class: 'dl-toolbar' }, [
E('div', { class: 'dl-seg', id: 'dl-people-tabs', role: 'tablist' }),
// Sort and add stay together on the right, wrapping as one group.
E('div', { class: 'dl-toolbar-end' }, [
sort,
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
st.servers.length ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
]),
st.servers.length
? ''
: E('div', { class: 'alert-message warning' }, [
'No server yet. ',
E('a', { href: L.url('admin/network/dawnline/server') }, 'Run the setup wizard'),
' before adding people.',
]),
E('div', { class: 'dl-toolbar' }, [
E('div', { class: 'dl-seg dl-people-tabs', role: 'tablist' }),
// Sort and add stay together on the right, wrapping as one group.
E('div', { class: 'dl-toolbar-end' }, [
sort,
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
]),
node,
]);
this.el = wrap;
requestAnimationFrame(() => this.decorate());
if (!this.polling) {
this.polling = true;
// Only while visible (a server section may be swapped out).
poll.add(() => (page.el?.isConnected ? page.poll() : Promise.resolve()), 10);
}
// ?add=1 opens Add person once, not again on every server's People tab.
if (!addOpened && new URLSearchParams(location.search).get('add')) {
addOpened = true;
setTimeout(() => page.openCreate(), 100);
}
return wrap;
]),
this.list,
]);
this.el = wrap;
this.rebuild();
// Only while visible (a server section may be swapped out).
this.poller ??= createPoller({
fetch: () => api.status(30),
every: 10,
active: () => !!page.el?.isConnected,
apply: (st, quiet) => page.take(st, quiet),
});
// ?add=1 opens Add person once, not again on every server's People tab.
if (!addOpened && new URLSearchParams(location.search).get('add')) {
addOpened = true;
setTimeout(() => page.openCreate(), 100);
}
return Promise.resolve(wrap);
}
countText(): string {
@@ -291,19 +257,21 @@ export class PeoplePage {
return `${t.people} ${t.people === 1 ? 'person' : 'people'} · ${t.devices} device${t.devices === 1 ? '' : 's'} · ${t.online} online`;
}
/** Row classes, counters, filter tabs and sort order. */
decorate() {
const c = document.getElementById('dl-people-count');
/** Row classes, counters, filter tabs and sort order; a `quiet` repaint keeps focused tabs. */
decorate(quiet = false) {
const c = this.el?.querySelector('.dl-people-count');
if (c) c.textContent = this.countText();
const people = this.st.people;
const today = this.today;
const attn = (p: Person) => needsAttention(p, today);
const counts: Record<Filter, number> = {
all: people.length,
online: people.filter((p) => p.online > 0).length,
attention: people.filter(needsAttention).length,
attention: people.filter(attn).length,
paused: people.filter((p) => p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired').length,
};
const tabs = document.getElementById('dl-people-tabs');
if (tabs) {
const tabs = this.el?.querySelector<HTMLElement>('.dl-people-tabs');
if (tabs && !(quiet && focusInside(tabs))) {
const label: Record<Filter, string> = { all: 'All', online: 'Online', attention: 'Needs attention', paused: 'Paused' };
dom.content(
tabs,
@@ -326,7 +294,7 @@ export class PeoplePage {
}
const match = (p: Person) => {
if (this.filter === 'online' && !p.online) return false;
if (this.filter === 'attention' && !needsAttention(p)) return false;
if (this.filter === 'attention' && !attn(p)) return false;
if (this.filter === 'paused' && !(p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired')) return false;
return true;
};
@@ -337,52 +305,40 @@ export class PeoplePage {
? b.month[0] + b.month[1] - (a.month[0] + a.month[1])
: b.online - a.online || b.last_seen - a.last_seen,
);
let tbody: Element | null = null;
let shown = 0;
for (const p of order) {
const card = document.getElementById(`dl-card-${p.id}`);
const row = card?.closest('.cbi-section-table-row') as HTMLElement | null;
if (!row) continue;
tbody ??= row.parentElement;
tbody?.appendChild(row);
row.classList.toggle('dl-off', p.state !== 'active');
row.classList.toggle('dl-attn-row', p.state === 'quota' || p.state === 'expired');
// A class, not an inline style: the card layout sets display with !important.
const card = this.card(p.id);
if (!card) continue;
this.list.appendChild(card);
card.classList.toggle('dl-off', p.state !== 'active');
card.classList.toggle('dl-attn-row', p.state === 'quota' || p.state === 'expired');
const hit = match(p);
row.classList.toggle('dl-filtered', !hit);
card.classList.toggle('dl-filtered', !hit);
if (hit) shown++;
}
// Say so when the filter leaves nobody.
const table = tbody?.closest('.cbi-section-table') ?? tbody;
let none = document.getElementById('dl-people-none');
if (table && people.length && !shown) {
none ??= E('div', { id: 'dl-people-none', class: 'dl-empty' });
dom.content(none, E('p', {}, 'No one here right now.'));
if (none.parentElement !== table.parentElement) table.after(none);
let none = this.el?.querySelector<HTMLElement>('.dl-people-none') ?? null;
if (people.length && !shown) {
none ??= E('div', { class: 'dl-empty dl-people-none' }, E('p', {}, 'No one here right now.'));
if (none.previousElementSibling !== this.list) this.list.after(none);
} else none?.remove();
}
async poll() {
const stAll = await this.latestStatus();
if (!stAll) return;
const st = this.scope(stAll);
this.st = st;
this.paintCards();
this.decorate();
}
async quick(p: Person, patch: Parameters<typeof api.personUpdate>[1], ok: string) {
if (await attempt(() => api.personUpdate(p.id, patch), ok)) await this.poll();
if (await attempt(() => api.personUpdate(p.id, patch), ok)) await this.update();
}
renderCard(node: HTMLElement, sid: Sid): HTMLElement {
const p = this.person(sid);
if (!p) {
dom.content(node, E('em', {}, 'Not saved yet — use “Save & Apply”.'));
dom.content(node, E('em', {}, 'This person was just removed.'));
return node;
}
const left = daysLeft(p.expires);
const today = this.today;
const left = daysLeft(p.expires, today);
const free = Math.max(0, p.device_limit - p.devices.length);
// The link itself is not in the status (person_links asks for it).
const portal = p.has_link ?? this.st.settings.portal_enabled;
// Term and hours sit by the name; online/last seen lives in the strip below.
const pills: Node[] = [];
@@ -407,7 +363,7 @@ export class PeoplePage {
title: `${KIND_LABEL[d.kind]} · ${d.address}${d.online ? ` · online from ${d.endpoint}` : d.handshake ? ` · seen ${ago(d.handshake, this.st.now)}` : ''}`,
click: (ev: Event) => {
ev.preventDefault();
openDevice(p, d, () => this.refresh(), this.st.geo);
void openDevice(p, d, this.deviceOpts(p));
},
},
[
@@ -430,7 +386,7 @@ export class PeoplePage {
title: free > 0 ? 'Add device' : 'Add device · over the limit, admins can still add',
click: (ev: Event) => {
ev.preventDefault();
addDevice(p, () => this.refresh());
addDevice(p, this.deviceOpts(p));
},
},
icon('plus'),
@@ -454,7 +410,7 @@ export class PeoplePage {
fixes.push(
E(
'button',
{ type: 'button', class: 'dl-fix', click: () => this.quick(p, { expires: addMonth(p.expires) }, 'Extended by 1 month') },
{ type: 'button', class: 'dl-fix', click: () => this.quick(p, { expires: addMonth(p.expires, today) }, 'Extended by 1 month') },
'Extend 1 month',
),
);
@@ -473,14 +429,14 @@ export class PeoplePage {
location.href = personUrl(p.id);
},
},
p.link
portal
? {
label: 'Invite card',
icon: icon('qr'),
run: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? 'Home'),
}
: null,
free > 0 ? { label: 'Add device', icon: icon('plus'), run: () => addDevice(p, () => this.refresh()) } : null,
free > 0 ? { label: 'Add device', icon: icon('plus'), run: () => addDevice(p, this.deviceOpts(p)) } : null,
null,
{
label: p.paused ? 'Resume' : 'Pause',
@@ -495,7 +451,7 @@ export class PeoplePage {
'dl-icon-only',
);
const actions = E('div', { class: 'dl-pcard-actions' }, [
p.link ? iconButton('link', 'Copy link', () => copyText(p.link!, 'Personal link copied'), 'neutral', 'dl-icon-only') : '',
portal ? iconButton('link', 'Copy link', () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
more,
]);
@@ -642,12 +598,7 @@ export class PeoplePage {
type: 'button',
class: 'cbi-button cbi-button-neutral',
click: () => {
if (!months) expires.value = '';
else {
const d = new Date();
d.setMonth(d.getMonth() + months);
expires.value = isoDate(d);
}
expires.value = months ? addMonthsClamped(todayOf(st.series), months) : '';
},
},
label,
@@ -686,7 +637,7 @@ export class PeoplePage {
row('Monthly data (GB)', quota, 'Optional. They are paused when it runs out and resumed next month.'),
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Create and copy link',
@@ -697,9 +648,9 @@ export class PeoplePage {
'',
server?.value ?? srv.id,
access.get(),
Number(limit.value) || st.settings.default_device_limit,
String(Number(limit.value) || st.settings.default_device_limit),
expires.value,
Number(quota.value) || 0,
quota.value.trim(),
'month',
),
);
File diff suppressed because it is too large. Load diff
+151
View File
@@ -0,0 +1,151 @@
// Person page: where they connected from (one line, the map on request) and their activity.
import { E } from '../../e';
import { button } from '../../ui/button';
import { dropdown } from '../../ui/menu';
import { icon } from '../../../shared/icons';
import { ConnectionMap, rangeControl } from '../../map';
import { eventRow, eventText } from '../../events/render';
import { clearLogDialog, exportEvents } from '../../logs';
import { openDevice } from '../../device';
import type { PersonPage } from './index';
function mapCard(page: PersonPage): HTMLElement {
const st = page.st;
const head = E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Locations'),
E('span', { class: 'dl-spacer' }),
st.geo.enabled ? rangeControl('30d', (r) => page.map?.setRange(r), false) : '',
button(
'Hide',
() => {
page.mapOpen = false;
page.map?.destroy();
page.map = null;
page.paintPlaces();
},
'neutral',
),
]);
if (!st.geo.enabled)
return E('div', { class: 'dl-panel flush' }, [
head,
E('div', { class: 'dl-map-off' }, [
'Locations are off. ',
E('a', { href: L.url('admin/network/dawnline/settings') }, 'Turn them on in Settings'),
'.',
]),
]);
const map = new ConnectionMap(
{
openPerson: () => undefined,
openDevice: (_pid, did) => {
const d = page.p.devices.find((x) => x.id === did);
if (d) void openDevice(page.p, d, page.deviceOpts());
},
},
'30d',
280,
);
page.map = map;
requestAnimationFrame(() => map.mount(page.mapData()));
return E('div', { class: 'dl-panel flush' }, [head, map.el]);
}
/** Where they connected from: one line, the map on request; null while the open map is already there. */
export function placesPart(page: PersonPage): HTMLElement | null {
const st = page.st;
if (!st.geo.enabled)
return E('div', { class: 'dl-places' }, [
icon('pin'),
E('div', { class: 'dl-stack' }, [
E('span', {}, 'Locations are off'),
E('span', { class: 'dl-sub' }, 'City-level, from the client IP'),
]),
E('span', { class: 'dl-spacer' }),
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/settings') }, 'Turn on'),
]);
if (page.mapOpen) return page.map && page.parts.places.contains(page.map.el) ? null : mapCard(page);
const since = st.now - 30 * 86400;
const pts = st.geo.points.filter((g) => g.person === page.p.id && g.ts >= since).sort((a, b) => b.ts - a.ts);
const places = [...new Set(pts.map((g) => g.city || g.country).filter(Boolean))];
const last = pts[0];
return E('div', { class: 'dl-places' }, [
icon('pin'),
E('div', { class: 'dl-stack' }, [
E('span', {}, last ? last.city || last.country : 'No locations yet'),
E(
'span',
{ class: 'dl-sub' },
last
? `${places.length} place${places.length === 1 ? '' : 's'} in 30 days${last.org ? ` · ${last.org}` : ''}`
: 'Shown after a device connects',
),
]),
E('span', { class: 'dl-spacer' }),
pts.length
? button(
'Show map',
() => {
page.mapOpen = true;
page.paintPlaces();
},
'neutral',
)
: '',
]);
}
/** The latest 10 events about them; back-and-forth network changes (Wi-Fi ⇄ mobile) fold into one row. */
export function activityPart(page: PersonPage): HTMLElement {
const p = page.p;
const st = page.st;
const all = page.events.filter((e) => e.person === p.id);
const rows: HTMLElement[] = [];
const latest = [...all].reverse();
for (let i = 0; i < latest.length && rows.length < 10; i++) {
const e = latest[i];
let n = 1;
while (e.type === 'roam' && latest[i + n]?.type === 'roam' && latest[i + n].device === e.device) n++;
const row = eventRow(st, e, { server: false });
if (n > 1) {
const main = row.querySelector('.dl-row-main') as HTMLElement;
dom.content(main, [...eventText(st, e).slice(0, 3), E('span', { class: 'dl-muted' }, `${n} times`)]);
main.title = latest
.slice(i, i + n)
.map((x) => x.detail ?? '')
.join('\n');
}
rows.push(row);
i += n - 1;
}
const more = button(
[icon('more')],
() =>
dropdown(more, [
{ label: 'Export CSV', icon: icon('download'), run: () => exportEvents(st, all, 'csv', p.id) },
{ label: 'Export JSON', icon: icon('download'), run: () => exportEvents(st, all, 'json', p.id) },
null,
{
label: `Clear ${p.name}'s activity`,
icon: icon('trash'),
danger: true,
run: () =>
clearLogDialog(`Clear ${p.name}'s activity`, `Removes events about ${p.name} and their devices.`, { person: p.id }, () =>
page.refresh(),
),
},
]),
'neutral',
{ title: 'Export or clear', class: 'cbi-button cbi-button-neutral dl-icon-only' },
);
return E('div', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Activity'),
E('span', { class: 'dl-sub' }, all.length > 10 ? `latest 10 of ${all.length}` : ''),
E('span', { class: 'dl-spacer' }),
more,
]),
rows.length ? rows : E('div', { class: 'dl-row dl-muted' }, 'Nothing yet.'),
]);
}
+97
View File
@@ -0,0 +1,97 @@
// Person page: the device cards (click one for its drawer) and the Add device slot.
import type { Device } from '../../../shared/types';
import { E } from '../../e';
import { api } from '../../api';
import { button } from '../../ui/button';
import { cancelButton, modal } from '../../ui/modal';
import { downloadFile } from '../../ui/files';
import { attempt, notify } from '../../ui/toast';
import { deviceStatus } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { KIND_LABEL, ago, byDeviceState, bytes } from '../../../shared/format';
import { addDevice, openDevice, quickMenu } from '../../device';
import { dayBars } from '../../widgets/tiles';
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));
if (!cfg) return;
modal(`Set up ${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));
if (!cfg) return;
if (!cfg.has_private_key) {
notify('This device made its own keys in the browser; its configuration only exists there.', 'warning');
return;
}
const f = page.core.file.make(cfg);
downloadFile(f.name, f.text, 'application/octet-stream');
}
export function devicesPart(page: PersonPage): HTMLElement {
const p = page.p;
const now = page.st.now;
const open = (d: Device) => openDevice(p, d, page.deviceOpts());
// The card opens the device's panel; its buttons (⋯, setup chips) do their own thing.
const clickCard = (d: Device) => (ev: Event) => {
if (!(ev.target as HTMLElement).closest('button:not(.dl-dcard-title), a')) void open(d);
};
const more = (d: Device) =>
button([icon('more')], (ev: MouseEvent) => quickMenu(ev.currentTarget as HTMLElement, p, d, page.deviceOpts()), 'neutral', {
title: 'QR, file, key, rename, new keys, remove',
class: 'cbi-button cbi-button-neutral dl-icon-only',
});
const cards = byDeviceState(p.devices).map((d) => {
const head = E('div', { class: 'dl-dcard-head' }, [
E('span', { class: 'dl-dcard-ic' }, icon(d.kind)),
E('button', { type: 'button', class: 'dl-dcard-title', click: () => open(d) }, [
E('b', {}, d.name),
deviceStatus(d, now),
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, 'Update config') : '',
]),
more(d),
]);
const trend = E('div', { class: 'dl-dcard-trend' }, [
E('div', { class: 'dl-stack' }, [E('b', {}, bytes(d.month[0] + d.month[1])), E('span', { class: 'dl-sub' }, 'this month')]),
dayBars(page.devSeries[d.id] ?? []),
]);
return E('article', { class: `dl-dcard clickable${d.online ? ' online' : ''}${d.disabled ? ' off' : ''}`, click: clickCard(d) }, [
head,
d.handshake
? trend
: d.disabled
? E(
'div',
{ class: 'dl-sub' },
`${KIND_LABEL[d.kind]} · created ${ago(d.created, now)} ${d.created_by === 'portal' ? 'in the portal' : 'by you'}.`,
)
: E('div', { class: 'dl-chips-row' }, [
E('button', { type: 'button', class: 'dl-chipbtn', click: () => showDeviceQr(page, d) }, [icon('qr'), 'Show QR']),
E('button', { type: 'button', class: 'dl-chipbtn', click: () => downloadConfig(page, d) }, [icon('download'), 'Config']),
]),
]);
});
// Always the last card: admins may add over the person's limit, it says so.
const over = p.devices.length >= p.device_limit;
cards.push(
E('button', { type: 'button', class: 'dl-dslot add', click: () => addDevice(p, page.deviceOpts()) }, [
E('span', { class: 'dl-dslot-ic' }, icon('plus')),
E('span', { class: 'dl-stack' }, [
E('b', {}, 'Add device'),
E(
'span',
{ class: 'dl-sub' },
over ? `Over the limit · ${p.devices.length} of ${p.device_limit}` : `${p.devices.length} of ${p.device_limit}`,
),
]),
]),
);
return E('section', { class: 'dl-devsec' }, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Devices'), E('span', { class: 'dl-sub' }, `${p.online} online`)]),
E('div', { class: 'dl-dgrid' }, cards),
]);
}
+128
View File
@@ -0,0 +1,128 @@
// Person page dialogs: rename, note, when access ends, new link, invite, delete.
import { E } from '../../e';
import { api } from '../../api';
import { button } from '../../ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from '../../ui/modal';
import { copyText } from '../../ui/files';
import { attempt } from '../../ui/toast';
import { inviteCard } from '../../invite';
import { peopleUrl } from '../../urls';
import type { PersonPage } from './index';
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
export function invite(page: PersonPage) {
const server = page.st.servers.find((s) => s.id === page.p.server)?.name ?? 'Home';
void inviteCard(page.p, server);
}
export async function newLink(page: PersonPage) {
const p = page.p;
if (!(await confirmDialog('Create a new link?', 'The old link stops working right away.', 'Create new link', true))) return;
const r = await attempt(() => api.personRegen(p.id), 'New link created');
if (r?.link) await copyText(r.link, 'New link copied');
}
export function editNote(page: PersonPage) {
const input = E(
'textarea',
{ class: 'cbi-input-textarea dl-note-input', rows: 3, maxlength: 500, placeholder: 'Only you see this' },
page.p.note ?? '',
) as HTMLTextAreaElement;
modal(
'Note',
[input],
[
cancelButton(),
' ',
button(
'Save',
async () => {
closeModal();
await page.patch({ note: input.value.trim() }, input.value.trim() ? 'Note saved' : 'Note removed');
},
'positive',
),
],
);
setTimeout(() => input.focus(), 50);
}
export function endSettings(page: PersonPage) {
const p = page.p;
const act = E('select', { class: 'cbi-input-select' }, [
E('option', { value: 'pause', selected: p.expire_action === 'pause' ? 'selected' : null }, 'Pause access'),
E('option', { value: 'notify', selected: p.expire_action === 'notify' ? 'selected' : null }, 'Keep access'),
E('option', { value: 'remove', selected: p.expire_action === 'remove' ? 'selected' : null }, 'Remove their devices'),
]) as HTMLSelectElement;
const warn = E(
'select',
{ class: 'cbi-input-select' },
[0, 1, 3, 7, 14].map((n) =>
E(
'option',
{ value: n, selected: p.expire_warn === n ? 'selected' : null },
n ? `${n} day${n === 1 ? '' : 's'} before` : 'Don’t warn',
),
),
) as HTMLSelectElement;
modal(
'When access ends',
[
field('Then', act),
E('div', { class: 'cbi-value' }, [
E('label', { class: 'cbi-value-title' }, 'Warn'),
E('div', { class: 'cbi-value-field' }, [
warn,
E('div', { class: 'cbi-value-description' }, 'Shown in their portal and on the Overview.'),
]),
]),
],
[
cancelButton(),
' ',
button(
'Save',
async () => {
closeModal();
await page.patch({ expire_action: act.value, expire_warn: warn.value }, 'Saved');
},
'positive',
),
],
);
}
export function rename(page: PersonPage) {
const input = E('input', { type: 'text', class: 'cbi-input-text', value: page.p.name, maxlength: 48 }) as HTMLInputElement;
modal(
'Rename',
[field('Name', input)],
[
cancelButton(),
' ',
button(
'Save',
async () => {
closeModal();
await page.patch({ name: input.value }, 'Renamed');
},
'positive',
),
],
);
setTimeout(() => input.select(), 50);
}
export async function remove(page: PersonPage) {
const p = page.p;
const ok = await confirmDialog(
`Delete ${p.name}?`,
`All ${p.devices.length} devices are disconnected immediately and the personal link stops working.`,
'Delete',
true,
);
if (ok && (await attempt(() => api.personDelete(p.id), 'Deleted'))) location.href = peopleUrl(p.server);
}
+73
View File
@@ -0,0 +1,73 @@
// Person page: the name block with its actions, and the traffic tiles.
import { E } from '../../e';
import { iconButton } from '../../ui/button';
import { dropdown, type MenuItem } from '../../ui/menu';
import { stateBadge } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { ago, bytes, date, initials, isoDay } from '../../../shared/format';
import { copyPersonLink } from '../../invite';
import { daysTile, speedTile } from '../../widgets/tiles';
import { editNote, invite, newLink, remove, rename } from './dialogs';
import type { PersonPage } from './index';
export function headPart(page: PersonPage): HTMLElement {
const p = page.p;
const st = page.st;
const lastSeen = p.online ? 'online now' : p.last_seen ? `last seen ${ago(p.last_seen, st.now)}` : 'never connected';
const added = p.created ? `Added ${date(isoDay(new Date(p.created * 1000)))}` : '';
// The personal link is not in the status: its actions ask for it while there is one.
const portal = p.has_link ?? st.settings.portal_enabled;
const menu: (MenuItem | null)[] = [
{ label: 'Rename', icon: icon('edit'), run: () => rename(page) },
{ label: p.note ? 'Edit note' : 'Add note', icon: icon('file'), run: () => editNote(page) },
...(portal
? [
null,
{ label: 'Invite card', icon: icon('qr'), run: () => invite(page) },
{ label: 'New link', icon: icon('key'), run: () => newLink(page) },
]
: []),
null,
{
label: p.paused ? 'Resume' : 'Pause',
icon: icon(p.paused ? 'play' : 'pause'),
warn: !p.paused,
run: () => page.patch({ paused: !p.paused }, p.paused ? 'Resumed' : 'Paused'),
},
{ label: 'Delete', icon: icon('trash'), danger: true, run: () => remove(page) },
];
return E('div', { class: 'dl-person-head' }, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-person-id' }, [
E('span', { class: `dl-avatar lg${p.online ? ' online' : ''}` }, initials(p.name)),
E('div', { class: 'dl-stack' }, [
E('div', { class: 'dl-title-row' }, [E('h2', { class: 'dl-h1' }, p.name), stateBadge(p)]),
E('span', { class: 'dl-faint', title: added }, `${p.devices.length} of ${p.device_limit} devices · ${lastSeen}`),
]),
]),
E('div', { class: 'dl-pcard-actions' }, [
portal ? iconButton('link', 'Copy link', () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
iconButton('more', 'More', (ev: MouseEvent) => dropdown(ev.currentTarget as HTMLElement, menu), 'neutral', 'dl-icon-only'),
]),
]),
// Under the name block, not inside it, so the avatar centres on name + status; indented to the name.
p.note
? E('button', { type: 'button', class: 'dl-pnote', title: 'Edit note', click: () => editNote(page) }, [
icon('file'),
E('span', {}, p.note),
])
: '',
]);
}
/** Speed now and the last 30 days, the same tiles as the server Overview; speed only while a device is online. */
export function trafficPart(page: PersonPage): HTMLElement {
const p = page.p;
// Today on the router: the last day of the series.
const todayUse = page.series[page.series.length - 1];
return E('div', { class: `dl-person-live${p.online ? '' : ' solo'}` }, [
p.online ? speedTile(p.rate ?? [], page.st.now, todayUse ? [todayUse.rx, todayUse.tx] : [0, 0]) : '',
daysTile(page.series, `${bytes(p.month[0] + p.month[1])} this month`),
]);
}
+189
View File
@@ -0,0 +1,189 @@
// Person page (admin/network/dawnline/person?id=…): devices as cards,
// locations, activity, and access & limits that apply immediately.
// The parts live in ./header, ./devices, ./limits, ./pickers, ./activity and
// ./dialogs; this class holds the state, the poller and the edits.
import type { DayUsage, LogEvent, Person, Status } from '../../../shared/types';
import { E } from '../../e';
import { api, type PersonPatch } from '../../api';
import { attempt } from '../../ui/toast';
import { todayOf } from '../../../shared/format';
import { ConnectionMap } from '../../map';
import { peopleUrl } from '../../urls';
import { addDevice, openDevice, type DeviceOpts } from '../../device';
import { coreFor, type Core } from '../../cores';
import { createPoller, repaint, type Poller } from '../../state/poller';
import { headPart, trafficPart } from './header';
import { devicesPart } from './devices';
import { limitsPart } from './limits';
import { activityPart, placesPart } from './activity';
type Part = 'head' | 'devices' | 'traffic' | 'places' | 'activity' | 'limits';
interface Loaded {
st: Status;
ev: LogEvent[] | null;
use: { person: DayUsage[]; devices: Record<string, DayUsage[]> } | null;
}
export class PersonPage {
st!: Status;
id = '';
p!: Person;
events: LogEvent[] = [];
/** The map stays folded into one line until asked for. */
mapOpen = false;
map: ConnectionMap | null = null;
parts = {} as Record<Part, HTMLElement>;
/** Daily traffic for the last 30 days. */
series: DayUsage[] = [];
/** The same per device. */
devSeries: Record<string, DayUsage[]> = {};
poller?: Poller<Loaded>;
/** Status every 15 s; the log and the traffic history every fourth time (and after a change). */
private ticks = 0;
private fullNext = false;
/** Status, and (`full`) the activity log and traffic history. */
async fetch(full: boolean): Promise<Loaded> {
const [st, ev, use] = await Promise.all([
api.status(30),
full ? api.events(5000).catch(() => null) : Promise.resolve(null),
full ? api.personUsage(this.id, 30).catch(() => null) : Promise.resolve(null),
]);
return { st, ev: ev?.events ?? null, use };
}
async load(): Promise<Loaded> {
this.id = new URLSearchParams(location.search).get('id') ?? '';
return this.fetch(true);
}
render(d: Loaded): HTMLElement {
this.take(d);
const p = this.st.people.find((x) => x.id === this.id);
if (!p)
return E('div', { class: 'dl-empty' }, [
E('h3', {}, 'Person not found'),
E('p', {}, 'They may have been removed.'),
E('a', { class: 'cbi-button', href: L.url('admin/network/dawnline/server') }, 'Back to Servers'),
]);
this.p = p;
for (const k of ['head', 'devices', 'traffic', 'places', 'activity', 'limits'] as Part[]) this.parts[k] = E('div', {});
this.parts.devices.className = 'dl-person-devices';
const root = E('div', {}, [
E('nav', { class: 'dl-crumbs', 'aria-label': 'Breadcrumb' }, [
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? 'Servers'),
E('span', {}, '/'),
E('a', { href: peopleUrl(p.server) }, 'People'),
E('span', {}, '/'),
E('span', {}, p.name),
]),
this.parts.head,
E('div', { class: 'dl-grid-person' }, [
E('div', { class: 'dl-col' }, [this.parts.devices, this.parts.traffic, this.parts.places, this.parts.activity]),
E('div', { class: 'dl-col' }, [this.parts.limits]),
]),
]);
this.paint();
const q = new URLSearchParams(location.search);
const dev = q.get('device') && p.devices.find((x) => x.id === q.get('device'));
if (dev) setTimeout(() => openDevice(this.p, dev, this.deviceOpts()), 50);
else if (q.get('add')) setTimeout(() => addDevice(this.p, this.deviceOpts()), 50);
this.poller = createPoller({
fetch: () => {
const full = this.fullNext || ++this.ticks % 4 === 0;
this.fullNext = false;
return this.fetch(full);
},
every: 15,
active: () => root.isConnected,
apply: (data, quiet) => this.apply(data, quiet),
});
return root;
}
private take(d: Loaded) {
this.st = d.st;
if (d.ev) this.events = d.ev;
if (d.use) {
this.series = d.use.person;
this.devSeries = d.use.devices;
}
}
private apply(d: Loaded, quiet: boolean) {
this.take(d);
const p = this.st.people.find((x) => x.id === this.id);
if (!p) {
if (!quiet) location.href = peopleUrl(this.p?.server);
return;
}
this.p = p;
this.paint(quiet);
this.map?.update(this.mapData());
}
/** Everything again, the log and traffic too (after a change). Newest answer wins. */
async refresh() {
this.fullNext = true;
await this.poller?.refresh();
}
/**
* Apply a change now and repaint from the router's answer. Answers of
* refreshes already on their way are dropped, so they can't paint the old state over it.
*/
async patch(patch: PersonPatch, ok?: string) {
this.poller?.claim();
const r = await attempt(() => api.personUpdate(this.p.id, patch), ok);
if (!r) return;
this.poller?.claim();
const i = this.st.people.findIndex((x) => x.id === this.p.id);
r.person.rate ??= this.p.rate;
if (i >= 0) this.st.people[i] = r.person;
this.p = r.person;
this.paint();
}
/** Today on the router (the last day of its traffic series). */
get today(): string {
return todayOf(this.series.length ? this.series : this.st.series);
}
get core(): Core {
return coreFor(this.st.servers, this.p.server);
}
/** What a device drawer opened from here gets: this page's log, clock and core. */
deviceOpts(): 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 };
}
/** Every part; a `quiet` (periodic) repaint leaves alone the parts that have the keyboard focus. */
paint(quiet = false) {
repaint(this.parts.head, headPart(this), quiet);
repaint(this.parts.traffic, trafficPart(this), quiet);
repaint(this.parts.devices, devicesPart(this), quiet);
repaint(this.parts.limits, limitsPart(this), quiet);
this.paintPlaces(quiet);
repaint(this.parts.activity, activityPart(this), quiet);
}
paintPlaces(quiet = false) {
const el = placesPart(this);
// A new map card always goes in (the map instance is made with it).
if (el) repaint(this.parts.places, el, quiet && !this.mapOpen);
}
}
+293
View File
@@ -0,0 +1,293 @@
// Person page: Access & limits — what they reach, then the tiles (devices,
// circle, end date, data, hours). Every choice applies at once.
import type { Person } from '../../../shared/types';
import { E } from '../../e';
import { notify } from '../../ui/toast';
import { seg } from '../../ui/controls';
import { attachTip } from '../../ui/tooltip';
import { icon } from '../../../shared/icons';
import { ACCESS_LABEL, bytes, date, daysLeft, shiftDay } from '../../../shared/format';
import { resetUsageDialog } from '../../logs';
import { homeAccess } from '../../access';
import { endSettings } from './dialogs';
import { circleTile, devTile, dnsPicker, netsPicker, servicesPicker } from './pickers';
import type { PersonPage } from './index';
const ACCESS_TEXT: Record<Person['access'], string> = {
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.',
};
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
function endTile(page: PersonPage): HTMLElement {
const p = page.p;
const today = page.today;
const left = daysLeft(p.expires, today);
const dateInput = E('input', {
type: 'date',
class: 'dl-date-hidden',
value: p.expires,
tabindex: '-1',
'aria-hidden': 'true',
}) as HTMLInputElement;
dateInput.addEventListener(
'change',
() => dateInput.value && page.patch({ expires: dateInput.value }, `Access until ${date(dateInput.value)}`),
);
// Extend from the current end, or from today when there is none or it has passed.
const extend = (step: 'week' | 'month' | 'year', n: number) => {
const next = shiftDay(p.expires && (left ?? -1) >= 0 ? p.expires : '', step, n, today);
void page.patch({ expires: next }, `Access until ${date(next)}`);
};
const ext = (
[
['week', 1, '+1 week'],
['month', 1, '+1 month'],
['month', 3, '+3 months'],
['year', 1, '+1 year'],
] as const
).map(([step, n, label]) => E('button', { type: 'button', class: 'dl-chipbtn', click: () => extend(step, n) }, label));
// The native date input stays hidden behind the chip and only opens its picker. It takes the
// focus first, so the page's background refresh leaves this tile (and the open picker) alone.
const pick = E('span', { class: 'dl-datechip' }, [
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: () => {
dateInput.focus({ preventScroll: true });
try {
dateInput.showPicker();
} catch {
/* focused is the best this browser offers */
}
},
},
[icon('calendar'), p.expires ? date(p.expires) : 'Date'],
),
dateInput,
]);
const action = { pause: 'pause access', notify: 'keep access', remove: 'remove their devices' }[p.expire_action];
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, [
E('span', {}, 'Access ends'),
p.expires
? E(
'span',
{ class: left != null && left < 0 ? 'dl-bad' : left != null && left <= p.expire_warn ? 'dl-warn' : 'dl-ok' },
left != null && left < 0 ? 'ended' : `${left} day${left === 1 ? '' : 's'} left`,
)
: E('span', { class: 'dl-faint' }, 'no end date'),
]),
E('div', { class: 'dl-chips-row' }, [
...ext,
pick,
p.expires
? E('button', { type: 'button', class: 'dl-chipbtn', click: () => page.patch({ expires: '' }, 'No end date') }, 'No end')
: '',
]),
E('div', { class: 'dl-tile2-foot' }, [
E(
'span',
{ class: 'dl-muted' },
`When it ends: ${action}${p.expire_warn ? `, warn ${p.expire_warn} day${p.expire_warn === 1 ? '' : 's'} before` : ''}`,
),
E(
'a',
{
href: '#',
click: (ev: Event) => {
ev.preventDefault();
endSettings(page);
},
},
'Change',
),
]),
]);
}
function dataTile(page: PersonPage): HTMLElement {
const p = page.p;
const used = p.quota_used || p.month[0] + p.month[1];
const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0;
const bar = E('div', { class: `dl-meter${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` }, [
E('i'),
p.quota_limit ? E('span', { class: 'mark', title: 'Alert at 90%' }) : '',
]);
(bar.firstChild as HTMLElement).style.width = `${pct}%`;
if (p.quota_limit)
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, `${pct.toFixed(1)}% used`),
E(
'div',
{ class: 'dl-muted' },
`${bytes(p.quota_used)} of ${bytes(p.quota_limit)} · ${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`,
),
E('div', { class: 'dl-faint' }, 'Alert at 90%'),
]);
const period = seg(
[
['month', 'Monthly'],
['total', 'Total'],
],
p.quota_period,
{ label: 'Data limit period', cls: 'sm', optimistic: false, onChange: (v) => page.patch({ quota_period: v }) },
);
const presets = [10, 50, 100].map((gb) =>
E(
'button',
{
type: 'button',
class: `dl-chipbtn${p.quota_gb === gb ? ' on' : ''}`,
click: () => page.patch({ quota_gb: String(gb) }, `Data limit ${gb} GB`),
},
`${gb} GB`,
),
);
presets.push(
E(
'button',
{ type: 'button', class: `dl-chipbtn${!p.quota_gb ? ' on' : ''}`, click: () => page.patch({ quota_gb: '' }, 'No data limit') },
'Unlimited',
),
);
presets.push(
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: () => {
const v = prompt('Data limit in GB', p.quota_gb ? String(p.quota_gb) : '');
if (v != null && v.trim() !== '' && Number(v) > 0) void page.patch({ quota_gb: v.trim() }, `Data limit ${v.trim()} GB`);
},
},
'Custom',
),
);
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, [E('span', {}, 'Data'), period]),
E('div', { class: 'dl-tile2-row' }, [
E('span', { class: 'dl-tile2-value' }, [
bytes(used),
p.quota_limit ? E('span', { class: 'dl-faint' }, ` of ${bytes(p.quota_limit)}`) : E('span', { class: 'dl-faint' }, ' · no limit'),
]),
p.quota_period === 'month' ? E('span', { class: 'dl-sub' }, 'resets on the 1st') : '',
]),
p.quota_limit ? bar : '',
E('div', { class: 'dl-chips-row' }, presets),
p.quota_gb && p.quota_period === 'month'
? E('div', { class: 'dl-tile2-foot' }, [
E('span', { class: 'dl-muted' }, p.bonus_gb ? `Includes +${p.bonus_gb} GB extra this month` : 'Need a little more this month?'),
E(
'a',
{
href: '#',
click: (ev: Event) => {
ev.preventDefault();
void page.patch({ bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month');
},
},
'+10 GB this month',
),
])
: '',
E('div', { class: 'dl-tile2-foot' }, [
E('span', { class: 'dl-muted' }, `${bytes(p.total[0] + p.total[1])} in total`),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => resetUsageDialog('person', p.id, p.name, () => setTimeout(() => page.refresh(), 300)),
},
'Reset usage',
),
]),
]);
}
/**
* Allowed hours. The times save when the focus leaves them (or on Enter), not
* on every change: a half-typed time would otherwise be saved and the tile
* repainted under the cursor. Both are checked first.
*/
function hoursTile(page: PersonPage): HTMLElement {
const p = page.p;
const hoursOn = !!p.hours;
const [h1, h2] = (p.hours || '07:00-23:00').split('-');
const from = E('input', { type: 'time', class: 'cbi-input-text', value: h1, 'aria-label': 'From' }) as HTMLInputElement;
const to = E('input', { type: 'time', class: 'cbi-input-text', value: h2, 'aria-label': 'To' }) as HTMLInputElement;
const times = E('div', { class: 'dl-tile2-row' }, [from, E('span', { class: 'dl-faint' }, 'to'), to]);
const commit = () => {
const v = `${from.value}-${to.value}`;
if (v === p.hours) return;
if (!TIME.test(from.value) || !TIME.test(to.value)) return notify('Enter both times, like 07:00 and 23:00.', 'warning');
if (from.value === to.value) return notify('The start and the end must differ.', 'warning');
void page.patch({ hours: v }, `Allowed ${from.value}–${to.value}`);
};
times.addEventListener('focusout', (ev: FocusEvent) => {
if (!times.contains(ev.relatedTarget as Node | null)) commit();
});
for (const t of [from, to])
t.addEventListener('keydown', (ev: KeyboardEvent) => {
if (ev.key === 'Enter') {
ev.preventDefault();
commit();
}
});
const sw = E(
'button',
{
type: 'button',
role: 'switch',
'aria-checked': hoursOn ? 'true' : 'false',
class: `dl-switch${hoursOn ? ' on' : ''}`,
'aria-label': 'Limit hours',
click: () => page.patch({ hours: hoursOn ? '' : '07:00-23:00' }, hoursOn ? 'Any time' : 'Allowed 07:00–23:00'),
},
E('i'),
);
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-row' }, [
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-tile2-label' }, 'Allowed hours'),
E('span', {}, hoursOn ? `${h1} – ${h2} (router time)` : 'Any time'),
]),
sw,
]),
hoursOn ? times : '',
]);
}
export function limitsPart(page: PersonPage): HTMLElement {
const p = page.p;
const access = seg(
(['internet', 'lan', 'both'] as const).map((a) => [
a,
[icon(a === 'internet' ? 'globe' : a === 'lan' ? 'home' : 'shield'), a === 'internet' ? 'Internet' : a === 'lan' ? 'Home' : 'Both'],
]),
p.access,
{ label: 'Access', cls: 'wide', optimistic: false, onChange: (a) => page.patch({ access: a }, `Access: ${ACCESS_LABEL[a]}`) },
);
// Heading above the card, like "Devices", so both columns line up (as on the portal).
return E('section', { class: 'dl-devsec', 'aria-label': 'Access and limits' }, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Access & limits')]),
E('div', { class: 'dl-panel' }, [
E('div', { class: 'dl-stack gap8' }, [
E('span', { class: 'dl-tile2-label' }, 'Can reach'),
access,
E('span', { class: 'dl-sub' }, ACCESS_TEXT[p.access]),
p.access === 'lan' && page.st.services.length ? servicesPicker(page) : '',
homeAccess(p) ? netsPicker(page) : '',
p.access === 'lan' ? dnsPicker(page) : '',
]),
E('div', { class: 'dl-tiles2' }, [devTile(page), circleTile(page), endTile(page), dataTile(page), hoursTile(page)]),
]),
]);
}
+228
View File
@@ -0,0 +1,228 @@
// Person page: the finer access choices (home services, home networks, DNS)
// and the Devices and circle tiles.
import { E } from '../../e';
import { notify } from '../../ui/toast';
import { chipToggle, seg } from '../../ui/controls';
import { dropdown } from '../../ui/menu';
import { attachTip } from '../../ui/tooltip';
import { icon } from '../../../shared/icons';
import { ago, initials } from '../../../shared/format';
import { circleDialog, circleDot, homeAccess } from '../../access';
import type { PersonPage } from './index';
/**
* DNS for Home-only access. The internet does not go through the tunnel, so
* by default the device keeps its own DNS; home names are opt-in.
*/
export function dnsPicker(page: PersonPage): HTMLElement {
const p = page.p;
const choice = seg(
[
['device', 'Device’s own DNS'],
['home', 'Home names'],
],
p.dns_mode,
{
label: 'DNS',
cls: 'sm',
optimistic: false,
onChange: (v) =>
page.patch(
{ dns_mode: v },
v === 'home' ? 'Home names on — devices need their configuration again' : 'Device DNS — devices need their configuration again',
),
},
);
const fb = page.st.settings.home_dns_fallback;
return E('div', { class: 'dl-stack gap4 dl-dnspick' }, [
E('div', { class: 'dl-row-actions' }, [E('span', { class: 'dl-sub' }, 'DNS'), choice]),
E(
'span',
{ class: 'dl-sub' },
p.dns_mode === 'home'
? [
'Names like ',
E('span', { class: 'dl-mono' }, `nas.${page.st.settings.domain}`),
' work. Internet names are resolved at home, so they depend on the tunnel',
fb
? [' (', E('span', { class: 'dl-mono' }, fb), ' takes over when it is down).']
: ' — with no fallback set, they stop when it is down.',
]
: 'Internet keeps working exactly as without the VPN. Reach home devices by IP address.',
),
]);
}
/** Home networks this person reaches, when the server has more than one. */
export function netsPicker(page: PersonPage): HTMLElement | '' {
const p = page.p;
const srv = page.st.servers.find((x) => x.id === p.server);
const all = srv?.home ?? [];
if (all.length < 2) return '';
const picked = new Set(p.home_nets?.length ? p.home_nets : all.map((h) => h.dev));
return E('div', { class: 'dl-stack gap4' }, [
E(
'div',
{ class: 'dl-chips-row' },
all.map((h) =>
chipToggle(
h.dev,
picked.has(h.dev),
() => {
const next = new Set(picked);
if (!next.delete(h.dev)) next.add(h.dev);
if (!next.size) return notify('Keep at least one network, or choose Internet only.', 'warning', 5000);
const list = next.size === all.length ? [] : [...next];
void page.patch(
{ home_nets: list },
list.length ? `${p.name} reaches ${list.join(', ')}` : `${p.name} reaches every home network`,
);
},
{ title: h.nets.join(', ') },
),
),
),
E(
'span',
{ class: 'dl-sub' },
p.home_nets?.length
? `Home networks ${p.name} reaches. Networks added to the server later stay out.`
: `Home networks ${p.name} reaches: all of them. Untick one to keep ${p.name} out of it.`,
),
]);
}
/** Optional narrowing of home-network access to selected services; the request gets a copy of the choice. */
export function servicesPicker(page: PersonPage): HTMLElement {
const chosen = new Set(page.p.services ?? []);
return E('div', { class: 'dl-stack gap4' }, [
E(
'div',
{ class: 'dl-chips-row' },
page.st.services.map((sv) =>
chipToggle(
sv.name,
chosen.has(sv.id),
() => {
// A copy: the chips show the saved choice until the router has it (a failed save changes nothing).
const next = new Set(chosen);
if (!next.delete(sv.id)) next.add(sv.id);
void page.patch({ services: [...next] }, next.size ? 'Home services updated' : 'Whole home network');
},
{ title: `${sv.address}${sv.ports.length ? ` · ${sv.ports.join(', ')}` : ''}` },
),
),
),
E(
'span',
{ class: 'dl-sub' },
chosen.size ? 'Only the selected services at home.' : 'Whole home network. Pick services to narrow it down.',
),
]);
}
/** The circle this person's devices share (servers where devices reach each other in circles). */
export function circleTile(page: PersonPage): HTMLElement | '' {
const p = page.p;
const st = page.st;
const srv = st.servers.find((x) => x.id === p.server);
if (srv?.mesh !== 'circles' || !homeAccess(p)) return '';
const circles = st.circles.filter((c) => c.server === p.server);
const ci = circles.find((c) => c.id === p.circle);
const mates = ci ? st.people.filter((x) => x.id !== p.id && x.circle === ci.id && homeAccess(x)).map((x) => x.name) : [];
const change: HTMLElement = E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: () =>
dropdown(change, [
...circles.map((c) => ({
label: c.name,
icon: circleDot(c),
run: () => c.id !== p.circle && page.patch({ circle: c.id }, `${p.name} is in ${c.name}`),
})),
p.circle ? { label: 'No circle', icon: icon('x'), run: () => page.patch({ circle: '' }, `${p.name} is in no circle`) } : null,
{ label: 'New circle', icon: icon('plus'), run: () => circleDialog(st, p.server, null, () => page.refresh()) },
]),
},
'Change',
);
// As the other tiles: the name is the value; who is in it as avatars.
const people = ci ? st.people.filter((x) => x.circle === ci.id && homeAccess(x)) : [p];
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, [E('span', {}, 'Devices see each other'), change]),
E('div', { class: 'dl-tile2-row' }, [
E('span', { class: 'dl-tile2-value' }, ci ? ci.name : 'No circle'),
E(
'span',
{ class: 'dl-avstack', title: people.map((x) => x.name).join(', ') },
people.slice(0, 5).map((x) => E('span', { class: 'dl-avatar sm' }, initials(x.name))),
),
]),
E(
'span',
{ class: 'dl-sub' },
!ci ? `Only ${p.name}'s own devices` : mates.length ? [p.name, ...mates].join(', ') : `Nobody else in ${ci.name} yet`,
),
]);
}
/** Device limit with a slot per device; never below the devices in use. */
export function devTile(page: PersonPage): HTMLElement {
const p = page.p;
const now = page.st.now;
const slots = E('div', { class: 'dl-slots' });
// Devices added over the limit get their own soft orange slots after the allowed ones.
for (let i = 0; i < Math.max(p.device_limit, p.devices.length); i++) {
const d = p.devices[i];
const over = i >= p.device_limit;
const slot = E('i', { class: over ? 'over' : d ? 'used' : '' });
attachTip(slot, () => [
E('div', { class: 'dl-tip-title' }, d ? `${d.name}${over ? ' · over the limit' : ''}` : 'Free slot'),
E(
'div',
{ class: 'dl-muted' },
d ? (d.online ? 'Connected' : d.handshake ? `Last seen ${ago(d.handshake, now)}` : 'Not set up yet') : 'They can add a device here',
),
]);
slots.appendChild(slot);
}
const floor = Math.max(1, p.devices.length);
const minus = E(
'button',
{
type: 'button',
'aria-label': 'Allow fewer devices',
disabled: p.device_limit <= floor ? 'disabled' : null,
click: () => page.patch({ device_limit: String(p.device_limit - 1) }),
},
'−',
);
if (p.device_limit <= floor && p.devices.length > 1)
attachTip(minus, () => [
E('div', { class: 'dl-tip-title' }, `${p.devices.length} devices in use`),
E('div', { class: 'dl-muted' }, 'Remove a device first to lower the limit'),
]);
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, 'Devices'),
E('div', { class: 'dl-tile2-row' }, [
E('span', { class: 'dl-tile2-value' }, [String(p.devices.length), E('span', { class: 'dl-faint' }, ` / ${p.device_limit}`)]),
E('div', { class: 'dl-stepper' }, [
minus,
E(
'button',
{
type: 'button',
'aria-label': 'Allow more devices',
disabled: p.device_limit >= 32 ? 'disabled' : null,
click: () => page.patch({ device_limit: String(p.device_limit + 1) }),
},
'+',
),
]),
]),
slots,
]);
}
+208 -319
View File
@@ -1,142 +1,48 @@
// Servers: a setup wizard when nothing is configured; otherwise one tab per
// server. Each opens on its Overview (who is online, traffic, map, activity)
// followed by its settings (General, Interfaces, Network, Disguise,
// Advanced); every settings section saves on its own and applies at once.
// followed by People, Connection, Access and AmneziaWG (its own settings come
// from ../cores/awg). Every settings section saves on its own and applies at
// once.
import type { Server, Status } from '../../shared/types';
import { E } from '../e';
import { api, type SetupDefaults } from '../api';
import { attempt, button, callout, closeModal, confirmDialog, copyText, modal, notify } from '../ui';
import { button } from '../ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from '../ui/modal';
import { copyText } from '../ui/files';
import { attempt, errorText, notify } from '../ui/toast';
import { input, seg, sw } from '../ui/controls';
import { card, group, needRow, row } from '../ui/layout';
import { icon } from '../../shared/icons';
import { duration } from '../../shared/format';
import { accessCards } from '../interfaces';
import { checkAccess, whoReaches } from '../access';
import { card, group, input, row, sw } from '../kit';
import { methodInfo, methodPicker, type Method } from '../disguise';
import { methodPicker, type Method } from '../disguise';
import { coreOf } from '../cores';
import { installAwg } from '../pkgs';
import { createPoller, focusInside, repaint, type Poller } from '../state/poller';
import { ServerOverview } from './overview';
import { PeoplePage } from './people';
type Section = 'overview' | 'people' | 'connection' | 'access' | 'disguise' | 'tunnel';
/** `awg` is the server's core section (named after its core; the key stays for old links). */
type Section = 'overview' | 'people' | 'connection' | 'access' | 'awg';
const SECTIONS: [Section, string][] = [
['overview', 'Overview'],
['people', 'People'],
['connection', 'Connection'],
['access', 'Access'],
['disguise', 'Disguise'],
['tunnel', 'Tunnel'],
['awg', ''],
];
/** Section names from before the regrouping, for old links. */
const OLD_SECTIONS: Record<string, Section> = { general: 'connection', network: 'connection', interfaces: 'access', advanced: 'tunnel' };
/** `.conf` names of the disguise parameters, in file order. */
const CONF: [string, string][] = [
['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'],
];
/**
* The applied parameters, grouped by what they do, with a plain-language
* line per group. Collapsed by default; copyable as config lines.
*/
function paramsView(o: Record<string, string>): HTMLElement | null {
const has = (k: string) => 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])]);
const group = (title: string, ic: string, text: string, ks: string[]) => {
const present = CONF.filter(([k]) => ks.includes(k) && has(k));
return present.length
? E('div', { class: 'dl-pgroup' }, [
E('div', { class: 'dl-pgroup-head' }, [icon(ic), E('b', {}, title)]),
E('p', {}, text),
E(
'div',
{ class: 'dl-pvals' },
present.map(([k, n]) => val(k, n)),
),
])
: '';
};
const jc = Number(o.jc || 0);
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 body = E('div', { class: 'dl-pgrid' }, [
group(
'Junk packets',
'zap',
jc ? `${jc} random packet${jc === 1 ? '' : 's'} of ${o.jmin}–${o.jmax} bytes before each handshake.` : 'No junk packets.',
['jc', 'jmin', 'jmax'],
),
group('Padding', 'archive', 'Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.', [
's1',
's2',
's3',
's4',
]),
group('Packet types', 'key', 'The values that replace WireGuard’s recognisable message types.', ['h1', 'h2', 'h3', 'h4']),
group('Signatures', 'globe', signature, ['i1', 'i2', 'i3', 'i4', 'i5']),
group('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',
]),
group('Timing', 'clock', 'Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.', [
'rekey_after_time',
'rekey_timeout',
'reject_after_time',
'keepalive_timeout',
'max_handshake_attempts',
]),
]);
return E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Current parameters'),
E('span', { class: 'dl-pcount' }, String(keys.length)),
E('span', { class: 'dl-spacer' }),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(conf, 'Parameters copied');
},
},
'Copy as config',
),
]),
body,
]);
}
const OLD_SECTIONS: Record<string, Section> = {
general: 'connection',
network: 'connection',
interfaces: 'access',
advanced: 'awg',
disguise: 'awg',
tunnel: 'awg',
core: 'awg',
};
const url = (server?: string, section?: string) => {
const q = new URLSearchParams();
if (server) q.set('server', server);
@@ -158,6 +64,7 @@ export class ServerPage {
headEl = E('div', {});
secEl = E('div', {});
bodyEl = E('div', { class: 'dl-srvbody' });
poller?: Poller<Status>;
async load(): Promise<[Status, SetupDefaults | null]> {
const st = await api.status(31);
@@ -178,20 +85,37 @@ export class ServerPage {
this.srvId = (st.servers.find((x) => x.id === q.get('server')) ?? st.servers[0]).id;
dom.content(this.root, [this.tabsEl, this.headEl, this.secEl, this.bodyEl]);
this.paint();
// Live numbers on the Overview; settings forms are left alone while open.
poll.add(async () => {
if (this.section !== 'overview') return;
const n = await api.status(31).catch(() => null);
if (!n || !n.servers.length) return;
this.st = n;
const srv = this.current();
dom.content(this.headEl, this.head(srv));
this.paintTabs();
this.ov[srv.id]?.update(n);
}, 10);
// Live numbers on the Overview; settings forms are left alone while open,
// and so is anything that has the keyboard focus.
this.poller = createPoller({
fetch: () => api.status(31),
every: 10,
active: () => this.section === 'overview' && this.root.isConnected,
apply: (n, quiet) => {
if (!n.servers.length) return;
this.st = n;
this.paintHead(quiet);
this.ov[this.current().id]?.update(n, quiet);
},
});
return this.root;
}
/** Server tabs and the head from the current status. */
paintHead(quiet = false) {
repaint(this.headEl, this.head(this.current()), quiet);
if (!quiet || !focusInside(this.tabsEl)) this.paintTabs();
}
/** New status for the head and tabs, without rebuilding the section (forms keep what was typed). */
async refreshStatus(): Promise<Status | null> {
const st = await api.status(31).catch(() => null);
if (!st?.servers.length) return null;
this.st = st;
this.paintHead();
return st;
}
current(): Server {
return this.st.servers.find((x) => x.id === this.srvId) ?? this.st.servers[0];
}
@@ -233,7 +157,7 @@ export class ServerPage {
this.paint();
},
},
[E('i', { class: `dot ${x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name), E('span', { class: 'dl-mono dl-faint' }, `:${x.port}`)],
[E('i', { class: `dot ${x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name)],
),
),
E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), 'Add server']),
@@ -242,6 +166,7 @@ export class ServerPage {
}
paintSections() {
const core = coreOf(this.current());
dom.content(
this.secEl,
E(
@@ -258,7 +183,7 @@ export class ServerPage {
'aria-selected': k === this.section ? 'true' : 'false',
click: () => this.showSection(k),
},
t,
k === 'awg' ? core.label : t,
),
),
),
@@ -309,21 +234,27 @@ export class ServerPage {
people: () => {
const pp = this.pp[srv.id];
if (pp?.el) {
void pp.poll();
void pp.update();
return pp.el;
}
const holder = E('div', {}, E('p', { class: 'dl-muted' }, 'Loading people…'));
const page = (this.pp[srv.id] ??= new PeoplePage());
page.embed(st, srv.id).then((node) => {
if (holder.isConnected) dom.content(holder, node);
else holder.replaceChildren(node);
});
page
.embed(st, srv.id)
.then((node) => {
if (holder.isConnected) dom.content(holder, node);
else holder.replaceChildren(node);
})
.catch((e) => {
// Try again on the next visit instead of keeping a broken page.
delete this.pp[srv.id];
dom.content(holder, E('p', { class: 'dl-muted' }, `Couldn't show people: ${errorText(e)}`));
});
return holder;
},
connection: () => this.connection(srv),
access: () => this.access(srv),
disguise: () => this.disguise(srv),
tunnel: () => this.tunnel(srv),
awg: () => this.awg(srv),
};
const node = body[k]();
this.detachKept();
@@ -333,9 +264,9 @@ export class ServerPage {
/** Name and state, the address bar, and the page actions. */
head(srv: Server): HTMLElement {
const st = this.st;
const seg = (ic: string, body: (Node | string)[]) => E('span', { class: 'dl-addrbar-seg' }, [icon(ic), ...body]);
const addr = `${srv.endpoint || '—'}:${srv.port}`;
// "Turn on" while the server is off (turning off lives in Tunnel; the same
const part = (ic: string, body: (Node | string)[]) => E('span', { class: 'dl-addrbar-seg' }, [icon(ic), ...body]);
const addr = srv.endpoint || '—';
// "Turn on" while the server is off (turning off lives in Connection; the same
// button also lifts an old router-wide pause).
const off = !srv.enabled || st.settings.paused_all;
const actions = E('div', { class: 'dl-actions' }, [
@@ -358,7 +289,7 @@ export class ServerPage {
E(
'span',
{ class: `dl-pill ${!srv.enabled ? 'off' : srv.up ? 'ok' : 'bad'}` },
!srv.enabled ? 'Turned off' : srv.up ? 'Running' : 'Not running',
!srv.enabled ? 'Turned off' : srv.up ? 'Running' : srv.blocked ? 'Can’t start' : 'Not running',
),
st.settings.paused_all && srv.enabled ? E('span', { class: 'dl-pill warn' }, 'Off') : '',
E('span', { class: 'dl-spacer' }),
@@ -367,13 +298,14 @@ export class ServerPage {
E('div', { class: 'dl-addrbar' }, [
E(
'button',
{ type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address and port', click: () => copyText(addr, 'Address copied') },
{ type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address', click: () => copyText(addr, 'Address copied') },
[icon('globe'), E('span', { class: 'dl-mono' }, addr), icon('copy')],
),
seg('tunnel', [E('span', { class: 'dl-mono' }, srv.ifname)]),
seg('network', [E('span', { class: 'dl-mono' }, srv.subnet)]),
srv.up ? seg('clock', [`up ${duration(srv.uptime)}`]) : '',
part('tunnel', [E('span', { class: 'dl-mono' }, `${coreOf(srv).label} :${srv.port}`)]),
srv.up ? part('clock', [`up ${duration(srv.uptime)}`]) : '',
]),
// The reason the tunnel can't run at all ("can't use the network interface awg0: it exists and isn't Dawnline's").
srv.blocked ? E('div', { class: 'dl-note warn' }, [icon('alert'), E('span', {}, `${srv.name} ${srv.blocked}.`)]) : '',
]);
}
@@ -381,119 +313,11 @@ export class ServerPage {
if (await attempt(() => api.serverUpdate(srv.id, values), ok)) await this.refresh();
}
/** How devices find the server and what goes into their configuration. */
/** The name, where devices find the router, DNS; then the danger zone. */
connection(srv: Server): HTMLElement {
const name = input(srv.name, { placeholder: 'Home' });
const endpoint = input(srv.endpoint, { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' });
const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const dns = input(srv.dns.join(', '), { placeholder: 'This router (recommended)', class: 'cbi-input-text dl-mono' });
const mtu = input(String(srv.mtu ?? ''), { placeholder: '1380', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
return card(
'Connection',
[
E('p', { class: 'dl-muted' }, 'How devices find this server, and what goes into their configuration.'),
group('router', 'Server', 'What people see', [row('Name', name, 'Shown to people in their portal.')]),
group('globe', 'Devices connect to', 'Where the tunnel answers from the internet', [
row(
'Public address',
endpoint,
'Hostname or IP of the router on the internet. A DDNS name keeps links working when your IP changes.',
),
row('UDP port', port, 'Opened on the WAN firewall automatically.'),
]),
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
row('DNS for devices', dns, 'Empty = this router, which sends each query where your home network would.'),
row('MTU', mtu, 'Lower it if some sites hang on mobile networks.'),
row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'),
]),
],
[
E('span'),
button(
'Save',
() =>
this.save(srv, {
name: name.value,
endpoint: endpoint.value,
port: port.value,
dns: dns.value,
mtu: mtu.value,
keepalive: ka.value,
}),
'positive',
),
],
);
}
/** Where devices may go and how their traffic leaves: internet path, home network, services, circles. */
access(srv: Server): HTMLElement {
const reload = () => this.refresh();
return E('div', { class: 'dl-stack gap16' }, [
accessCards(srv, this.st, reload),
E('div', { class: 'dl-health-cols' }, [whoReaches(this.st, srv), checkAccess(this.st, srv)]),
]);
}
disguise(srv: Server): HTMLElement {
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
let selected: Method = current ?? 'standard';
const action = button('', () => this.applyDisguise(srv, selected, selected === current), 'positive');
const label = () => {
dom.content(action, selected === current ? [icon('reset'), ' Generate new values'] : `Switch to ${methodInfo(selected)!.title}`);
};
label();
const params = paramsView(srv.obf ?? {});
return card(
'Disguise',
[
E(
'p',
{ class: 'dl-muted' },
'AmneziaWG reshapes the tunnel so networks that block VPNs do not recognise it. Every device gets these settings in its configuration.',
),
methodPicker(
this.st.awg,
selected,
(m) => {
selected = m;
label();
},
current,
),
!this.st.awg.v3
? callout('info', [
'This router runs an older AmneziaWG. ',
E('b', {}, 'Maximum'),
' becomes available with kmod-amneziawg and amneziawg-tools 3.1.',
])
: '',
params ?? '',
],
[E('span', { class: 'dl-sub' }, 'Applies at once. Every device on this server must import its configuration again.'), action],
);
}
async applyDisguise(srv: Server, m: Method, same: boolean) {
const info = methodInfo(m)!;
const people = this.st.people.filter((p) => p.server === srv.id);
const devices = people.reduce((n, p) => n + p.devices.length, 0);
const ok = await confirmDialog(
same ? 'Generate new disguise values?' : `Switch to ${info.title}?`,
`${devices} device${devices === 1 ? '' : 's'} stop connecting until they import their configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : ''}`,
same ? 'Generate and apply' : 'Switch and apply',
true,
);
if (!ok) return;
if (await attempt(() => api.serverObfuscation(srv.id, m), same ? 'New values applied' : `${info.title} applied`)) {
notify('Devices are marked “Update config” until they import again.', 'info', 6000);
await this.refresh();
}
}
/** Technical details that rarely change, then the danger zone. */
tunnel(srv: Server): HTMLElement {
const people = this.st.people.filter((p) => p.server === srv.id).length;
const toggle = button(
srv.enabled ? 'Turn off' : 'Turn on',
@@ -514,23 +338,22 @@ export class ServerPage {
);
return E('div', { class: 'dl-stack gap16' }, [
card(
'Tunnel',
'Connection',
[
E('p', { class: 'dl-muted' }, 'Technical details. They are set when the server is created and rarely change.'),
row('Interface', E('span', { class: 'dl-mono' }, `${srv.ifname} · router ${srv.address}`)),
row('Tunnel subnet', E('span', { class: 'dl-mono' }, srv.subnet), 'Device addresses come from it.'),
row(
'Server public key',
E('span', { class: 'dl-keyrow' }, [
E('code', { class: 'dl-mono' }, srv.public_key),
button([icon('copy')], () => copyText(srv.public_key, 'Public key copied'), 'neutral', {
title: 'Copy',
class: 'cbi-button cbi-button-neutral dl-icon-only sm',
}),
]),
),
E('p', { class: 'dl-muted' }, 'The name people see, where devices find the router, and DNS. The port is on AmneziaWG.'),
group('router', 'Server', 'What people see', [row('Name', name, 'Shown to people in their portal and apps.')]),
group('globe', 'Devices connect to', 'Where the router answers from the internet', [
row(
'Public address',
endpoint,
'Hostname or IP of the router on the internet. A DDNS name keeps links working when your IP changes. It must not go through Cloudflare: use a DNS-only name or an IP.',
),
]),
group('file', 'For every device', 'Changing it marks devices “Update config” until they import again', [
row('DNS for devices', dns, 'Empty = this router, which sends each query where your home network would.'),
]),
],
[],
[E('span'), button('Save', () => this.save(srv, { name: name.value, endpoint: endpoint.value, dns: dns.value }), 'positive')],
),
card(
'Danger zone',
@@ -570,6 +393,35 @@ export class ServerPage {
]);
}
/**
* Where devices may go and how their traffic leaves: internet path, home
* network, services, circles. Changes that apply at once refresh the status
* in place, so an unsaved interface choice survives them.
*/
access(srv: Server): HTMLElement {
let who = whoReaches(this.st, srv);
const cards = accessCards(srv, this.st, async () => {
const st = await this.refreshStatus();
if (!st) return;
const s2 = st.servers.find((x) => x.id === srv.id) ?? srv;
cards.update(st);
const n = whoReaches(st, s2);
who.replaceWith(n);
who = n;
});
return E('div', { class: 'dl-stack gap16' }, [cards.el, E('div', { class: 'dl-health-cols' }, [who, checkAccess(this.st, srv)])]);
}
/** The server's core: for AmneziaWG the listening port, MTU, keep-alive, disguise and tunnel. */
awg(srv: Server): HTMLElement {
const ctx = {
st: this.st,
save: (values: Record<string, unknown>, ok?: string) => this.save(srv, values, ok),
refresh: () => this.refresh(),
};
return E('div', { class: 'dl-stack gap16' }, [coreOf(srv).settingsCard(ctx, srv)]);
}
/* ---------------- add / remove ---------------- */
async addServer() {
@@ -596,7 +448,7 @@ export class ServerPage {
),
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Remove',
@@ -644,22 +496,34 @@ export class ServerPage {
return el;
};
const steps = extra ? ['Connection', 'Disguise'] : ['Connection', 'Disguise', 'Portal'];
const pages: (() => Node)[] = [
() =>
type Page = { id: string; title: string; render: () => Node; check?: () => string | null };
const serverPage: Page = {
id: 'server',
title: 'Server',
render: () =>
E('div', { class: 'dl-wizard-groups' }, [
E(
'p',
{ class: 'dl-muted' },
'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
),
group('router', 'Server', 'What people see', [row('Name', field('name'), 'Shown to people in their portal.')]),
group('globe', 'Devices connect to', 'Where the tunnel answers from the internet', [
group('router', 'Server', 'What people see', [row('Name', field('name'), 'Shown to people in their portal and apps.')]),
group('globe', 'Devices connect to', 'Where the router answers from the internet', [
row(
'Public address',
field('endpoint', { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' }),
'Hostname or IP address of your router on the internet.',
'Hostname or IP address of your router on the internet. Not through Cloudflare: use a DNS-only name or an IP.',
),
]),
]),
check: () => (!state.endpoint ? 'Fill in the public address.' : null),
};
const awgPage: Page = {
id: 'awg',
title: 'AmneziaWG',
render: () =>
E('div', { class: 'dl-wizard-groups' }, [
group('globe', 'Listening', 'Where devices reach AmneziaWG from the internet', [
row(
'UDP port',
field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }),
@@ -673,45 +537,33 @@ export class ServerPage {
`Must not overlap your networks (${d.taken.join(', ') || 'none found'}).`,
),
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
methodPicker(d.awg, state.preset, (m) => (state.preset = m), undefined, d.awg_state?.tools !== false),
]),
]),
() =>
E('div', {}, [
E(
'p',
{},
'AmneziaWG reshapes the tunnel so networks that block VPNs do not recognise it. Every device gets these settings automatically; you can change the method later.',
),
methodPicker(d.awg, state.preset, (m) => (state.preset = m)),
]),
() => {
check: () => (!state.port || !state.subnet ? 'Fill in the UDP port and subnet.' : null),
};
const portalPage: Page = {
id: 'portal',
title: 'Portal',
render: () => {
const portalPort = field('portal_port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const portRow = row('Listening port', portalPort, 'TCP port on WAN for the portal; the whole port belongs to it.');
portRow.hidden = !state.portal;
// Off | On, Off first: the same segmented control as in Settings.
const onOff = E(
'div',
{ class: 'dl-seg', role: 'radiogroup', 'aria-label': 'Personal portal' },
(['off', 'on'] as const).map((v) =>
E(
'button',
{
type: 'button',
role: 'radio',
class: (v === 'on') === state.portal ? 'on' : '',
'aria-checked': (v === 'on') === state.portal ? 'true' : 'false',
click: (ev: Event) => {
state.portal = v === 'on';
portRow.hidden = !state.portal;
onOff.querySelectorAll('button').forEach((x) => {
const sel = x === ev.currentTarget;
x.classList.toggle('on', sel);
x.setAttribute('aria-checked', sel ? 'true' : 'false');
});
},
},
v === 'on' ? 'On' : 'Off',
),
),
const onOff = seg(
[
['off', 'Off'],
['on', 'On'],
],
state.portal ? 'on' : 'off',
{
label: 'Personal portal',
onChange: (v) => {
state.portal = v === 'on';
portRow.hidden = !state.portal;
},
},
);
return E('div', { class: 'dl-wizard-groups' }, [
group('home', 'Internet like a home device', 'How devices reach the internet', [
@@ -727,22 +579,50 @@ export class ServerPage {
]),
]);
},
];
};
const pages = (): Page[] => [serverPage, awgPage, extra ? null : portalPage].filter((x): x is Page => x != null);
const aw = d.awg_state;
const missing = aw?.missing ?? [];
// Without AmneziaWG the server would only show "Tunnel down": say so first and offer to install it.
const awgNotice = missing.length
? E('div', { class: 'dl-list dl-notices' }, [
needRow(
'shield',
'bad',
'AmneziaWG isn’t installed',
`The tunnel needs ${missing.join(' and ')}. Install the build made for this firmware, then create the server.`,
button('Install', () => installAwg(() => location.reload()), 'positive'),
),
])
: aw && !aw.loaded
? E('div', { class: 'dl-list dl-notices' }, [
needRow(
'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.',
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/updates') }, 'Open Components'),
),
])
: '';
const paint = () => {
const ps = pages();
if (step >= ps.length) step = ps.length - 1;
dom.content(root, [
E('h2', {}, extra ? 'Add a server' : 'Set up Dawnline'),
awgNotice,
E(
'div',
{ class: 'dl-steps' },
steps.map((s, i) =>
ps.map((s, i) =>
E('span', { class: `dl-step${i === step ? ' current' : i < step ? ' done' : ''}` }, [
E('b', {}, i < step ? '✓' : String(i + 1)),
s,
s.title,
]),
),
),
E('div', { class: 'dl-panel' }, pages[step]()),
E('div', { class: 'dl-panel' }, ps[step].render()),
E('div', { class: 'dl-actions' }, [
step > 0
? button('Back', () => {
@@ -753,12 +633,13 @@ export class ServerPage {
? button('Cancel', onCancel)
: '',
E('span', { class: 'dl-spacer' }),
step < steps.length - 1
step < ps.length - 1
? button(
'Next',
() => {
if (step === 0 && (!state.endpoint || !state.port || !state.subnet)) {
notify('Fill in the public address, port and subnet.', 'warning');
const err = ps[step].check?.();
if (err) {
notify(err, 'warning');
return;
}
step++;
@@ -769,6 +650,13 @@ export class ServerPage {
: button(
'Create server',
async () => {
for (const pg of ps) {
const err = pg.check?.();
if (err) {
notify(err, 'warning');
return;
}
}
// An extra server leaves the portal settings alone (undefined is not sent).
const r = await attempt(
() =>
@@ -795,6 +683,7 @@ export class ServerPage {
}, 1500);
},
'positive',
{ disabled: missing.length > 0, title: missing.length ? 'Install AmneziaWG first' : null },
),
]),
]);
-765
View File
@@ -1,765 +0,0 @@
// Settings: section cards, each with its own Save (applied immediately).
import { E } from '../e';
import { api, type Backup, type SettingsData } from '../api';
import { attempt, button, closeModal, modal } from '../ui';
import { icon } from '../../shared/icons';
import { group, input, isOn, row, sw } from '../kit';
import { CATEGORIES, CATEGORY_HELP, CATEGORY_LABEL, clearLogDialog, exportEvents, resetUsageDialog } from '../logs';
import { retentionText } from './activity';
import { backupsSection } from '../backups';
import { installMissing } from '../pkgs';
type Values = Record<string, string | string[]>;
/** Single-choice pill row; read the choice with `.dataset.value`. */
function seg(options: [string, string][], value: string, label: string): HTMLElement {
if (!options.some(([v]) => v === value)) options = [...options, [value, value]];
const el = E('div', { class: 'dl-seg sm', role: 'radiogroup', 'aria-label': label, 'data-value': value });
const paint = () =>
dom.content(
el,
options.map(([v, t]) =>
E(
'button',
{
type: 'button',
role: 'radio',
class: v === el.dataset.value ? 'on' : '',
'aria-checked': v === el.dataset.value ? 'true' : 'false',
click: () => {
el.dataset.value = v;
paint();
},
},
t,
),
),
);
paint();
return el;
}
function plural(n: number, one: string, many = `${one}s`): string {
return `${n.toLocaleString('en-GB')} ${n === 1 ? one : many}`;
}
function kb(n: number): string {
return n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB` : `${(n / 1048576).toFixed(1)} MB`;
}
export class SettingsPage {
d!: SettingsData;
root = E('div', { class: 'dl-settings-main' });
backups: Backup[] = [];
load() {
return api.settingsGet();
}
render(d: SettingsData): HTMLElement {
this.d = d;
this.paint();
this.loadBackups().then(() => {
if (new URLSearchParams(location.search).get('section') === 'backups')
document.getElementById('dl-set-backups')?.scrollIntoView({ block: 'start' });
});
return E('div', {}, [E('div', { class: 'dl-pagehead' }, [E('h2', { class: 'dl-h1' }, 'Settings')]), this.root]);
}
async save(values: Values, ok = 'Saved') {
const r = await attempt(() => api.settingsUpdate(values), ok);
if (r) {
this.d = r;
this.paint();
}
}
section(id: string, title: string, body: (Node | string)[], foot: Node[], extra = '', head: (Node | string)[] = []): HTMLElement {
return E('section', { class: `dl-setsec ${extra}`, id: `dl-set-${id}` }, [
E('div', { class: 'dl-setsec-body' }, [
head.length
? E('div', { class: 'dl-setsec-head' }, [E('h3', {}, title), E('span', { class: 'dl-spacer' }), ...head])
: E('h3', {}, title),
...body,
]),
foot.length ? E('div', { class: 'dl-setsec-foot' }, foot) : '',
]);
}
/** Personal portal: the address in links (picked from what the router found), a preview, readiness, and the rest folded away. */
portalSection(): HTMLElement {
const s = this.d.settings;
const eff = this.d.effective as Record<string, any>;
const c = this.d.cert;
const cands = this.d.portal_candidates ?? [];
const checks = this.d.portal_checks ?? [];
const pOn = sw(eff.portal_enabled, 'Enable portal');
const port = input(s.portal_port, { placeholder: '8443', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' });
const on443 = sw(eff.portal_443, 'Standard ports', () => paintLinks());
const title = input(s.portal_title, { placeholder: 'Dawnline' });
const redirect = input(s.portal_redirect, { placeholder: 'Show “Not found”', class: 'cbi-input-text dl-mono' });
const other = input('', { placeholder: 'vpn.example.com or an IP', 'aria-label': 'Other address' });
const isIp = (h: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(h);
// Chosen addresses, the main one first; custom ones join the list of options.
let picked: string[] = [eff.portal_host, ...(eff.portal_alt ?? [])].filter(
(h: string, i: number, a: string[]) => h && a.indexOf(h) === i,
);
if (!picked.length && cands[0]) picked = [cands[0].host];
const rows = [...cands];
const addRow = (h: string) => {
if (h && !rows.some((x) => x.host === h))
rows.push({ host: h, kind: isIp(h) ? 'ip' : 'name', ips: [], here: false, cloudflare: false, cert: false });
};
picked.forEach(addRow);
const note = (x: (typeof cands)[number]): Node =>
x.kind === 'ip'
? E('span', { class: 'dl-addr-warn' }, [icon('alert'), 'Plain HTTP: the link and VPN keys travel unencrypted'])
: E(
'span',
{ class: 'dl-sub' },
x.cloudflare
? 'Behind Cloudflare · often stalls in Russia'
: !x.ips.length
? 'Your address'
: x.here
? `Points at this router${x.cert ? ' · Let’s Encrypt certificate' : ' · no certificate yet'}`
: `Points at ${x.ips.join(', ')}, not this router`,
);
const opts = E('div', { class: 'dl-addr-opts', role: 'group', 'aria-label': 'Portal addresses' });
const toggle = (h: string) => {
if (picked.includes(h)) {
if (picked.length > 1) picked = picked.filter((x) => x !== h);
} else picked = [...picked, h];
paintOpts();
paintLinks();
};
const paintOpts = () =>
dom.content(opts, [
...rows.map((x) => {
const on = picked.includes(x.host),
main = picked[0] === x.host;
return E(
'div',
{
class: `dl-addr-opt${on ? ' on' : ''}`,
role: 'checkbox',
'aria-checked': on ? 'true' : 'false',
tabindex: '0',
click: () => toggle(x.host),
keydown: (ev: KeyboardEvent) => {
if (ev.key === ' ' || ev.key === 'Enter') {
ev.preventDefault();
toggle(x.host);
}
},
},
[
E('i', { class: 'dl-addr-check' }, on ? icon('check') : ''),
E('span', { class: 'dl-stack' }, [E('span', { class: 'dl-mono' }, x.host), note(x)]),
main
? E('span', { class: 'dl-pill info' }, 'Main')
: on
? E(
'button',
{
type: 'button',
class: 'dl-linkbtn',
click: (ev: Event) => {
ev.stopPropagation();
picked = [x.host, ...picked.filter((h) => h !== x.host)];
paintOpts();
paintLinks();
},
},
'Make main',
)
: x.cloudflare
? E('span', { class: 'dl-pill warn' }, 'Cloudflare')
: x.kind === 'ip'
? E('span', { class: 'dl-pill' }, 'IP')
: x.here && x.cert
? E('span', { class: 'dl-pill ok' }, 'Recommended')
: '',
],
);
}),
E('div', { class: 'dl-addr-opt other' }, [
E('i', { class: 'dl-addr-check' }, icon('plus')),
other,
button('Add', () => {
const h = other.value.trim().toLowerCase();
if (!h) return;
addRow(h);
if (!picked.includes(h)) picked = [...picked, h];
other.value = '';
paintOpts();
paintLinks();
}),
]),
]);
other.addEventListener('keydown', (ev: KeyboardEvent) => {
if (ev.key === 'Enter') {
ev.preventDefault();
(other.nextElementSibling as HTMLElement)?.click();
}
});
// One row per link, as people will see it (example code).
const links = E('div', { class: 'dl-links' });
const paintLinks = () => {
const std = isOn(on443);
const lport = Number(port.value) || eff.portal_port;
dom.content(
links,
picked.map((h, i) => {
const ip = isIp(h);
const p = ip ? (std ? 80 : lport + 1) : std && !this.d.wan443_taken ? 443 : lport;
const base = `${ip ? 'http' : 'https'}://${h}${p === (ip ? 80 : 443) ? '' : `:${p}`}/`;
return E('div', { class: 'dl-link-row' }, [
E('span', { class: `dl-link-ic ${ip ? 'warn' : 'ok'}` }, icon(ip ? 'alert' : 'lock')),
E('span', { class: 'dl-mono dl-link-url' }, [base, E('b', {}, 'kamiro-telosu-bavine')]),
i === 0 ? E('span', { class: 'dl-pill info' }, 'Main') : ip ? E('span', { class: 'dl-pill warn' }, 'HTTP') : '',
]);
}),
);
};
paintOpts();
paintLinks();
port.addEventListener('input', () => paintLinks());
// Readiness: one summary line, the checks as chips, details on demand.
const SHORT: Record<string, string> = {
portal: 'Portal running',
portal_dns: 'Points here',
portal_reply: 'Answers reach visitors',
portal_443: 'Port 443',
portal_lan: 'Works at home',
portal_http: 'Plain HTTP',
cert: 'Certificate',
};
const shown = checks.filter((x) => x.status !== 'skip');
const bad = shown.filter((x) => x.status === 'error' || x.status === 'warn');
const worst = shown.some((x) => x.status === 'error') ? 'error' : bad.length ? 'warn' : 'ok';
const details = E(
'div',
{ class: 'dl-ready-details', hidden: true },
shown.map((x) =>
E('div', { class: `dl-ready-item ${x.status}` }, [
icon(x.status === 'ok' ? 'check' : 'alert'),
E('span', { class: 'dl-stack' }, [E('span', {}, x.title), E('span', { class: 'dl-sub' }, x.detail)]),
]),
),
);
const ready = E('div', { class: 'dl-stack gap8' }, [
E('div', { class: `dl-ready-sum ${worst}` }, [
icon(worst === 'ok' ? 'check' : 'alert'),
E('span', { class: 'dl-stack' }, [
E(
'b',
{},
worst === 'ok' ? `All ${shown.length} checks passed` : `${shown.length - bad.length} of ${shown.length} checks passed`,
),
bad.length
? E('span', { class: 'dl-sub' }, bad.map((x) => x.detail).join(' '))
: E('span', { class: 'dl-sub' }, 'Links will open for the people you send them to.'),
]),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn',
click: (ev: Event) => {
details.hidden = !details.hidden;
(ev.currentTarget as HTMLElement).textContent = details.hidden ? 'Details' : 'Hide';
},
},
'Details',
),
]),
E(
'div',
{ class: 'dl-chips-row' },
shown.map((x) =>
E('span', { class: `dl-check-chip ${x.status}`, title: x.detail }, [
icon(x.status === 'ok' ? 'check' : 'alert'),
SHORT[x.id] ?? x.title,
]),
),
),
details,
]);
const until =
c && !c.self_signed && c.expires
? new Date(c.expires).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })
: '';
const portsRow = row(
'Standard ports',
on443,
this.d.wan443_taken
? 'Port 443 is already forwarded to another device, so HTTPS links keep the listening port.'
: 'Links without a port: 443 for names, 80 for IP addresses. Mobile networks often drop other ports. From the internet these reach only the portal; LuCI stays closed.',
);
const listenRow = row(
'Listening port',
port,
this.d.port_owners.length
? `Port ${eff.portal_port} is used by ${this.d.port_owners.join(', ')}.`
: `Where the portal runs on the router: HTTPS here, plain HTTP for IP addresses on ${eff.portal_port + 1}.`,
);
const custom = !!(s.portal_cert && s.portal_key);
const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt';
const certFiles = () => {
const fc = input(s.portal_cert, { placeholder: '/etc/ssl/…/fullchain.crt' });
const fk = input(s.portal_key, { placeholder: '/etc/ssl/…/key' });
modal(
'Use your own certificate',
[
E('p', { class: 'dl-muted' }, 'Paths on the router. Leave both empty to pick a certificate automatically.'),
row('Certificate file', fc),
row('Key file', fk),
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
' ',
button(
'Save',
() => {
closeModal();
this.save({ portal_cert: fc.value.trim(), portal_key: fk.value.trim() }, 'Certificate saved');
},
'positive',
),
],
);
};
const need = this.d.needs ?? { https: [], acme: [], home: [] };
const needRow = (ic: string, tone: string, title: string, sub: string, feature: 'https' | 'acme', label: string) =>
E('div', { class: `dl-row dl-need-row ${tone}` }, [
tone ? E('span', { class: 'dl-need-ic' }, icon(ic)) : icon(ic),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, sub)]),
button(label, () => installMissing(feature, need[feature], () => this.reload()), 'positive'),
]);
const httpsRow = need.https.length
? needRow(
'lock',
'bad',
'HTTPS isn’t available on this router',
`The portal needs ${need.https.join(' and ')}. It can’t start without them.`,
'https',
'Install',
)
: '';
const acmeRow =
need.acme.length && (!c || c.self_signed)
? needRow(
'lock',
'',
'Free certificate from Let’s Encrypt',
`ACME isn’t installed. With it the router gets a certificate${s.portal_host ? ` for ${s.portal_host}` : ''} and browsers stop warning.`,
'acme',
'Install ACME',
)
: '';
const certRows = [
E('div', { class: 'dl-row' }, [
icon('lock'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, [kind, until ? E('span', { class: 'dl-faint' }, ` · until ${until}`) : '']),
E(
'span',
{ class: 'dl-sub dl-ellipsis', title: c?.path ?? '' },
!c
? 'Turn the portal on to see its certificate.'
: c.self_signed
? 'Made by the router: browsers warn until a certificate covers the address.'
: `${custom ? 'Your files' : 'Found automatically'} · ${c.path}`,
),
]),
]),
E('div', { class: 'dl-row' }, [
icon('file'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, 'Your own files'),
E(
'span',
{ class: 'dl-sub' },
custom ? `${s.portal_cert} · ${s.portal_key}` : 'Not set: the certificate is picked automatically.',
),
]),
custom ? button('Reset', () => this.save({ portal_cert: '', portal_key: '' }, 'Automatic certificate'), 'negative') : '',
button(custom ? 'Change' : 'Use files', certFiles),
]),
acmeRow,
];
return this.section(
'portal',
'Personal portal',
[
E('span', { class: 'dl-muted' }, 'A page where each person adds and manages their devices with their personal link.'),
httpsRow ? E('div', { class: 'dl-list' }, [httpsRow]) : '',
group('network', 'Ports', 'How the portal listens', [portsRow, listenRow]),
group('edit', 'Appearance', 'What people see', [
row('Title', title, 'Shown at the top of the portal.'),
row('Unknown links', redirect, 'Where a wrong or old link goes, for example your website. Empty shows a plain “Not found”.'),
]),
group('link', 'Addresses', 'Pick one or more; the first is the main link', [
opts,
E('div', { class: 'dl-stack gap8' }, [
links,
E('span', { class: 'dl-sub' }, 'Example code; each person gets their own three words.'),
]),
]),
group('lock', 'Certificate', 'Used for HTTPS links', certRows),
eff.portal_enabled && shown.length ? group('check', 'Ready to share', 'The portal’s checks from Health', [ready]) : '',
],
[
E('span'),
button(
'Save',
() =>
this.save({
portal_enabled: isOn(pOn) ? '1' : '0',
portal_443: isOn(on443) ? '1' : '0',
portal_host: picked[0] ?? '',
portal_alt: picked.slice(1),
portal_port: port.value,
portal_title: title.value,
portal_redirect: redirect.value.trim(),
}),
'positive',
),
],
'',
[
eff.portal_enabled
? need.https.length
? E('span', { class: 'dl-pill bad' }, 'Can’t start')
: E(
'span',
{ class: `dl-pill ${worst === 'ok' ? 'ok' : worst === 'error' ? 'bad' : 'warn'}` },
worst === 'error' ? 'Needs attention' : 'Ready',
)
: '',
pOn,
],
);
}
paint() {
const s = this.d.settings;
const eff = this.d.effective as Record<string, any>;
// Personal portal
const portal = this.portalSection();
// Defaults
const limit = input(s.default_device_limit, { placeholder: '3', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' });
const hn = sw(eff.hostnames, 'Device hostnames');
const domain = input(s.domain, { placeholder: 'lan', class: 'cbi-input-text dl-w-port' });
const fallback = input(s.home_dns_fallback === 'none' ? '' : s.home_dns_fallback || eff.home_dns_fallback || '', {
placeholder: 'None',
inputmode: 'decimal',
class: 'cbi-input-text dl-w-ip dl-mono',
});
const defaults = this.section(
'defaults',
'Defaults',
[
row('Devices per person', limit, 'Pre-filled when you add someone.'),
row(
'Device hostnames',
E('div', { class: 'dl-hostport' }, [hn, E('span', { class: 'dl-faint dl-mono' }, 'phone.myata.'), domain]),
'Name devices in your home DNS.',
),
row(
'Fallback DNS',
fallback,
'For Home-only devices using home names: the second DNS server, used by the device when the tunnel is down. Empty = none.',
),
],
[
E('span'),
button(
'Save',
() =>
this.save({
default_device_limit: limit.value,
hostnames: isOn(hn) ? '1' : '0',
domain: domain.value,
home_dns_fallback: fallback.value,
}),
'positive',
),
],
);
// Map
const gOn = sw(eff.geo_enabled, 'Locations');
const prov = E('select', { class: 'cbi-input-select' }, [
E('option', { value: 'ipwho.is', selected: eff.geo_provider !== 'ipapi.co' ? 'selected' : null }, 'ipwho.is (fallback: ipapi.co)'),
E('option', { value: 'ipapi.co', selected: eff.geo_provider === 'ipapi.co' ? 'selected' : null }, 'ipapi.co (fallback: ipwho.is)'),
]) as HTMLSelectElement;
const map = this.section(
'map',
'Map & locations',
[
E('div', { class: 'dl-setrow head' }, [
E('span', { class: 'dl-muted' }, 'Show where people connect from on the Overview and person pages, at city level.'),
gOn,
]),
row('Provider', prov),
],
[
E(
'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.',
),
button('Save', () => this.save({ geo_enabled: isOn(gOn) ? '1' : '0', geo_provider: prov.value }), 'positive'),
],
);
const logs = this.logsSection();
const danger = this.section(
'danger',
'Remove Dawnline from this router',
[
E(
'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.',
),
],
[E('span'), button('Remove', () => this.uninstall(), 'negative')],
'danger',
);
const backups = backupsSection(this.backups, () => {
this.reload();
this.loadBackups();
});
dom.content(this.root, [portal, defaults, map, logs, backups, danger]);
}
logsSection(): HTMLElement {
const L = this.d.logs;
const p = L.policy;
const keep = seg(
[
['7', '7 days'],
['30', '30 days'],
['90', '90 days'],
['365', '1 year'],
['0', 'No limit'],
],
String(p.keep_days),
'Keep activity',
);
const size = seg(
[
['500', '500'],
['2000', '2,000'],
['5000', '5,000'],
['20000', '20,000'],
],
String(p.max),
'Maximum events',
);
const persist = seg(
[
['10min', 'Every 10 min'],
['hourly', 'Hourly'],
['off', 'Memory only'],
],
p.persist,
'Save to flash',
);
const days = seg(
[
['31', '1 month'],
['62', '2 months'],
['180', '6 months'],
['365', '1 year'],
['730', '2 years'],
],
String(p.usage_days),
'Daily traffic',
);
const months = seg(
[
['12', '1 year'],
['24', '2 years'],
['60', '5 years'],
['120', '10 years'],
],
String(p.usage_months),
'Monthly traffic',
);
const chosen = new Set(p.categories);
const cats = E(
'div',
{ class: 'dl-chips-row' },
CATEGORIES.map((c) => {
const b = E(
'button',
{
type: 'button',
class: `dl-chipbtn${chosen.has(c) ? ' on' : ''}`,
title: CATEGORY_HELP[c],
click: () => {
if (chosen.has(c)) chosen.delete(c);
else chosen.add(c);
b.classList.toggle('on', chosen.has(c));
},
},
[CATEGORY_LABEL[c], E('b', {}, String(L.by_category[c] ?? 0))],
);
return b;
}),
);
const fmtDay = (d: Date | string) => new Date(d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
const since = L.oldest ? fmtDay(new Date(L.oldest * 1000)) : '';
const stored = (ic: string, title: string, detail: string, actions: Node[]) =>
E('div', { class: 'dl-row' }, [
icon(ic),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, detail)]),
...actions,
]);
const exportBtn = (fmt: 'csv' | 'json') =>
button(
fmt.toUpperCase(),
async () => {
const [st, ev] = await Promise.all([api.status(1), api.events(20000)]);
exportEvents(st, ev.events, fmt);
},
'neutral',
{ title: `Download the log as ${fmt.toUpperCase()}` },
);
return this.section(
'logs',
'Logs & history',
[
E('p', { class: 'dl-muted' }, retentionText(p)),
row('Keep activity', keep, 'Older events are removed automatically.'),
row('Maximum size', size, 'Newest events are kept when the log is full.'),
row('Record', cats, 'Switched-off categories are not logged from now on.'),
row(
'Save to flash',
persist,
'The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot.',
),
row('Daily traffic', days, 'Per-day history behind the charts.'),
row('Monthly traffic', months, 'Per-month totals; data limits use the current month.'),
E('h4', { class: 'dl-setsub' }, 'Stored data'),
E('div', { class: 'dl-list' }, [
stored(
'activity',
'Activity log',
L.events
? `${plural(L.events, 'event')} since ${since} · ${kb(L.log_ram)} in memory${p.persist === 'off' ? '' : `, ${kb(L.log_flash)} on flash`}`
: 'Empty',
[
exportBtn('csv'),
exportBtn('json'),
button(
'Clear',
() => clearLogDialog('Clear activity', 'Removes events from the log on the router.', {}, () => this.reload()),
'negative',
),
],
),
stored(
'chart',
'Traffic history',
L.usage_days ? `${plural(L.usage_days, 'day')} since ${fmtDay(L.usage_since)} · ${kb(L.usage_flash)} on flash` : 'Empty',
[button('Reset', () => resetUsageDialog('all', '', '', () => setTimeout(() => this.reload(), 300)), 'negative')],
),
stored('pin', 'Location cache', `${plural(this.d.geo_cached, 'address', 'addresses')} · ${kb(L.geo_flash)} on flash`, [
button(
'Clear',
async () => {
if (await attempt(() => api.geoClear(), 'Location cache cleared')) this.reload();
},
'negative',
),
]),
]),
],
[
E('span', { class: 'dl-sub' }, 'Clear one person or device from their own page.'),
button(
'Save',
() =>
this.save({
log_keep_days: keep.dataset.value!,
log_max: size.dataset.value!,
log_persist: persist.dataset.value!,
usage_keep_days: days.dataset.value!,
usage_keep_months: months.dataset.value!,
log_category: [...chosen],
}),
'positive',
),
],
);
}
async loadBackups() {
const r = await api.backupList().catch(() => null);
if (r) {
this.backups = r.backups;
const old = document.getElementById('dl-set-backups');
if (old)
old.replaceWith(
backupsSection(this.backups, () => {
this.reload();
this.loadBackups();
}),
);
}
}
async reload() {
const d = await api.settingsGet().catch(() => null);
if (d) {
this.d = d;
this.paint();
}
}
uninstall() {
const confirmInput = input('', { placeholder: 'remove' });
modal(
'Remove Dawnline?',
[
E(
'p',
{},
'Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “remove” to confirm.',
),
confirmInput,
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
' ',
button(
'Remove Dawnline',
async () => {
if (await attempt(() => api.uninstall(confirmInput.value.trim()), 'Dawnline removed')) {
closeModal();
setTimeout(() => location.reload(), 800);
}
},
'negative',
),
],
);
}
}
@@ -1,11 +1,18 @@
// Backups: a section of the Settings page. The three newest are rows, the
// rest fold away; moving to another router lives in the footer.
// Settings → Backups. The three newest are rows, the rest fold away; moving
// to another router lives in the footer.
import { E } from './e';
import { api, type Backup } from './api';
import { attempt, button, confirmDialog, downloadFile, dropdown, iconButton, notify, pickFile } from './ui';
import { icon } from '../shared/icons';
import { bytes } from '../shared/format';
import { E } from '../../e';
import { api, type Backup } from '../../api';
import { button, iconButton } from '../../ui/button';
import { confirmDialog } from '../../ui/modal';
import { downloadFile, pickFile } from '../../ui/files';
import { dropdown } from '../../ui/menu';
import { attempt, notify } from '../../ui/toast';
import { icon } from '../../../shared/icons';
import { bytes } from '../../../shared/format';
/** After a change: `true` when everything changed (restore, import), else only the list. */
type Done = (all?: boolean) => void;
const REASON: Record<string, string> = {
manual: 'Manual',
@@ -35,7 +42,7 @@ async function download(b: Backup) {
downloadFile(b.name, new g.Blob([arr], { type: 'application/gzip' }));
}
function backupRow(b: Backup, done: () => void): HTMLElement {
function backupRow(b: Backup, done: Done): HTMLElement {
return E('div', { class: 'dl-row dl-bk-row' }, [
E('span', { class: 'dl-group-ic' }, icon('archive')),
E('span', { class: 'dl-row-main dl-stack' }, [
@@ -59,7 +66,7 @@ function backupRow(b: Backup, done: () => void): HTMLElement {
'Restore',
true,
);
if (ok && (await attempt(() => api.backupRestore(b.name), 'Restored'))) done();
if (ok && (await attempt(() => api.backupRestore(b.name), 'Restored'))) done(true);
},
},
{
@@ -88,7 +95,7 @@ function backupRow(b: Backup, done: () => void): HTMLElement {
}
/** The Backups section; `done` reloads the list (and the page data after a restore). */
export function backupsSection(list: Backup[], done: () => void): HTMLElement {
export function backupsSection(list: Backup[], done: Done): HTMLElement {
const rows = list.slice(0, SHOWN).map((b) => backupRow(b, done));
const older = list.slice(SHOWN);
const body = list.length
@@ -112,7 +119,7 @@ export function backupsSection(list: Backup[], done: () => void): HTMLElement {
'Restore',
true,
);
if (ok && (await attempt(() => api.backupUpload(f.data), 'Restored'))) done();
if (ok && (await attempt(() => api.backupUpload(f.data), 'Restored'))) done(true);
});
const exportJson = button('Export JSON', async () => {
const r = await attempt(() => api.exportJson());
@@ -134,7 +141,7 @@ export function backupsSection(list: Backup[], done: () => void): HTMLElement {
'Import',
true,
);
if (ok && (await attempt(() => api.importJson(data), 'Imported'))) done();
if (ok && (await attempt(() => api.importJson(data), 'Imported'))) done(true);
});
return E('section', { class: 'dl-setsec', id: 'dl-set-backups' }, [
+61
View File
@@ -0,0 +1,61 @@
// Settings: what every card shares — the card frame, a card that can be
// rebuilt on its own, and the page interface the cards use.
import type { PortalInfo, SettingsData } from '../../api';
import { E } from '../../e';
export type CardId = 'portal' | 'defaults' | 'map' | 'updates' | 'logs' | 'backups' | 'danger';
/** What a card gets from the Settings page. */
export interface SettingsHost {
/** The settings as last loaded or saved. */
readonly d: SettingsData;
/** Portal addresses and checks (slow: they arrive after the page shows). */
readonly portal: PortalInfo | null;
/** Fills the portal card on screen with fresh `portal` without touching what was typed. */
portalFill?: (p: PortalInfo) => void;
/** Save `values`; afterwards only `card` is rebuilt (the others keep what was typed). */
save(values: Record<string, string | string[]>, ok: string, card: CardId): Promise<void>;
/** Load the settings again and rebuild `card` (every card when not given). */
reload(card?: CardId): Promise<void>;
/** The backups list again (and, after a restore, everything). */
loadBackups(all?: boolean): Promise<void>;
}
/** A card that can be rebuilt in place from the current settings. */
export interface Card {
el: HTMLElement;
refresh(): void;
}
export function mountCard(build: () => HTMLElement): Card {
const c: Card = {
el: build(),
refresh() {
const n = build();
c.el.replaceWith(n);
c.el = n;
},
};
return c;
}
/** A dl-setsec card with its id (for ?section=…), title, body and footer; `head` goes next to the title. */
export function section(
id: string,
title: string,
body: (Node | string)[],
foot: Node[],
extra = '',
head: (Node | string)[] = [],
): HTMLElement {
return E('section', { class: `dl-setsec ${extra}`, id: `dl-set-${id}` }, [
E('div', { class: 'dl-setsec-body' }, [
head.length
? E('div', { class: 'dl-setsec-head' }, [E('h3', {}, title), E('span', { class: 'dl-spacer' }), ...head])
: E('h3', {}, title),
...body,
]),
foot.length ? E('div', { class: 'dl-setsec-foot' }, foot) : '',
]);
}
+54
View File
@@ -0,0 +1,54 @@
// Settings → Remove Dawnline from this router.
import { E } from '../../e';
import { api } from '../../api';
import { button } from '../../ui/button';
import { cancelButton, closeModal, modal } from '../../ui/modal';
import { attempt } from '../../ui/toast';
import { input } from '../../ui/controls';
import { section } from './common';
function uninstall() {
const confirmInput = input('', { placeholder: 'remove' });
modal(
'Remove Dawnline?',
[
E(
'p',
{},
'Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “remove” to confirm.',
),
confirmInput,
],
[
cancelButton(),
' ',
button(
'Remove Dawnline',
async () => {
if (await attempt(() => api.uninstall(confirmInput.value.trim()), 'Dawnline removed')) {
closeModal();
setTimeout(() => location.reload(), 800);
}
},
'negative',
),
],
);
}
export function dangerCard(): HTMLElement {
return section(
'danger',
'Remove Dawnline from this router',
[
E(
'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.',
),
],
[E('span'), button('Remove', () => uninstall(), 'negative')],
'danger',
);
}
+55
View File
@@ -0,0 +1,55 @@
// Settings → Defaults: devices per person, device hostnames, fallback DNS.
import { E } from '../../e';
import { button } from '../../ui/button';
import { input, isOn, sw } from '../../ui/controls';
import { row } from '../../ui/layout';
import { section, type SettingsHost } from './common';
export function defaultsCard(host: SettingsHost): HTMLElement {
const s = host.d.settings;
const eff = host.d.effective as Record<string, any>;
const limit = input(s.default_device_limit, { placeholder: '3', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' });
const hn = sw(eff.hostnames, 'Device hostnames');
const domain = input(s.domain, { placeholder: 'lan', class: 'cbi-input-text dl-w-port' });
const fallback = input(s.home_dns_fallback === 'none' ? '' : s.home_dns_fallback || eff.home_dns_fallback || '', {
placeholder: 'None',
inputmode: 'decimal',
class: 'cbi-input-text dl-w-ip dl-mono',
});
return section(
'defaults',
'Defaults',
[
row('Devices per person', limit, 'Pre-filled when you add someone.'),
row(
'Device hostnames',
E('div', { class: 'dl-hostport' }, [hn, E('span', { class: 'dl-faint dl-mono' }, 'phone.myata.'), domain]),
'Name devices in your home DNS.',
),
row(
'Fallback DNS',
fallback,
'For Home-only devices using home names: the second DNS server, used by the device when the tunnel is down. Empty = none.',
),
],
[
E('span'),
button(
'Save',
() =>
host.save(
{
default_device_limit: limit.value,
hostnames: isOn(hn) ? '1' : '0',
domain: domain.value,
home_dns_fallback: fallback.value,
},
'Saved',
'defaults',
),
'positive',
),
],
);
}
+90
View File
@@ -0,0 +1,90 @@
// Settings: section cards, each with its own Save (applied immediately). A
// save rebuilds only its own card, so what is typed in the others stays.
import type { Backup, PortalInfo, SettingsData } from '../../api';
import { E } from '../../e';
import { api } from '../../api';
import { attempt } from '../../ui/toast';
import { mountCard, type Card, type CardId, type SettingsHost } from './common';
import { portalCard } from './portal';
import { defaultsCard } from './defaults';
import { mapCard } from './map';
import { updatesCard } from './updates';
import { logsCard } from './logs';
import { backupsSection } from './backups';
import { dangerCard } from './danger';
export class SettingsPage implements SettingsHost {
d!: SettingsData;
root = E('div', { class: 'dl-settings-main' });
backups: Backup[] = [];
portal: PortalInfo | null = null;
portalFill?: (p: PortalInfo) => void;
portalSeq = 0;
cards = {} as Record<CardId, Card>;
load() {
return api.settingsGet();
}
render(d: SettingsData): HTMLElement {
this.d = d;
this.cards = {
portal: mountCard(() => portalCard(this)),
defaults: mountCard(() => defaultsCard(this)),
map: mountCard(() => mapCard(this)),
updates: mountCard(() => updatesCard(this)),
logs: mountCard(() => logsCard(this)),
backups: mountCard(() => backupsSection(this.backups, (all) => this.loadBackups(all))),
danger: mountCard(() => dangerCard()),
};
const order: CardId[] = ['portal', 'defaults', 'map', 'updates', 'logs', 'backups', 'danger'];
dom.content(
this.root,
order.map((k) => this.cards[k].el),
);
this.loadBackups().then(() => {
if (new URLSearchParams(location.search).get('section') === 'backups')
document.getElementById('dl-set-backups')?.scrollIntoView({ block: 'start' });
});
void this.loadPortal();
// ?section=updates (from Components) and the like: open at that card.
const sec = new URLSearchParams(location.search).get('section');
if (sec && sec !== 'backups') requestAnimationFrame(() => document.getElementById(`dl-set-${sec}`)?.scrollIntoView({ block: 'start' }));
return E('div', {}, [E('div', { class: 'dl-pagehead' }, [E('h2', { class: 'dl-h1' }, 'Settings')]), this.root]);
}
async save(values: Record<string, string | string[]>, ok: string, card: CardId) {
const r = await attempt(() => api.settingsUpdate(values), ok);
if (!r) return;
this.d = r;
this.cards[card].refresh();
if (card === 'portal') void this.loadPortal();
}
/** Fetch the portal's addresses and checks; the newest answer wins. */
async loadPortal() {
const seq = ++this.portalSeq;
const p = await api.portalInfo().catch(() => null);
if (seq !== this.portalSeq) return;
this.portal = p ?? this.portal ?? { candidates: [], checks: [] };
this.portalFill?.(this.portal);
}
async loadBackups(all = false) {
if (all) await this.reload();
const r = await api.backupList().catch(() => null);
if (!r) return;
this.backups = r.backups;
this.cards.backups?.refresh();
}
async reload(card?: CardId) {
const d = await api.settingsGet().catch(() => null);
if (!d) return;
this.d = d;
if (card) this.cards[card].refresh();
else for (const c of Object.values(this.cards)) c.refresh();
if (!card || card === 'portal') void this.loadPortal();
}
}
+177
View File
@@ -0,0 +1,177 @@
// Settings → Logs & history: retention, what is recorded, and the stored data.
import { E } from '../../e';
import { api } from '../../api';
import { button } from '../../ui/button';
import { attempt } from '../../ui/toast';
import { chipToggle, seg, setChip } from '../../ui/controls';
import { row } from '../../ui/layout';
import { icon } from '../../../shared/icons';
import { fmtDay, kb, plural } from '../../../shared/format';
import { CATEGORIES, CATEGORY_HELP, CATEGORY_LABEL, retentionText } from '../../events/model';
import { clearLogDialog, exportEvents, resetUsageDialog } from '../../logs';
import { section, type SettingsHost } from './common';
export function logsCard(host: SettingsHost): HTMLElement {
const L = host.d.logs;
const p = L.policy;
const keep = seg(
[
['7', '7 days'],
['30', '30 days'],
['90', '90 days'],
['365', '1 year'],
['0', 'No limit'],
],
String(p.keep_days),
{ label: 'Keep activity', cls: 'sm' },
);
const size = seg(
[
['500', '500'],
['2000', '2,000'],
['5000', '5,000'],
['20000', '20,000'],
],
String(p.max),
{ label: 'Maximum events', cls: 'sm' },
);
const persist = seg(
[
['10min', 'Every 10 min'],
['hourly', 'Hourly'],
['off', 'Memory only'],
],
p.persist,
{ label: 'Save to flash', cls: 'sm' },
);
const days = seg(
[
['31', '1 month'],
['62', '2 months'],
['180', '6 months'],
['365', '1 year'],
['730', '2 years'],
],
String(p.usage_days),
{ label: 'Daily traffic', cls: 'sm' },
);
const months = seg(
[
['12', '1 year'],
['24', '2 years'],
['60', '5 years'],
['120', '10 years'],
],
String(p.usage_months),
{ label: 'Monthly traffic', cls: 'sm' },
);
const chosen = new Set(p.categories);
const cats = E(
'div',
{ class: 'dl-chips-row' },
CATEGORIES.map((c) => {
const b = chipToggle(
[CATEGORY_LABEL[c], E('b', {}, String(L.by_category[c] ?? 0))],
chosen.has(c),
() => {
if (!chosen.delete(c)) chosen.add(c);
setChip(b, chosen.has(c));
},
{ title: CATEGORY_HELP[c] },
);
return b;
}),
);
const since = L.oldest ? fmtDay(new Date(L.oldest * 1000)) : '';
const stored = (ic: string, title: string, detail: string, actions: Node[]) =>
E('div', { class: 'dl-row' }, [
icon(ic),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, detail)]),
...actions,
]);
const exportBtn = (fmt: 'csv' | 'json') =>
button(
fmt.toUpperCase(),
async () => {
const [st, ev] = await Promise.all([api.status(1), api.events(20000)]);
exportEvents(st, ev.events, fmt);
},
'neutral',
{ title: `Download the log as ${fmt.toUpperCase()}` },
);
return section(
'logs',
'Logs & history',
[
E('p', { class: 'dl-muted' }, retentionText(p)),
row('Keep activity', keep, 'Older events are removed automatically.'),
row('Maximum size', size, 'Newest events are kept when the log is full.'),
row('Record', cats, 'Switched-off categories are not logged from now on.'),
row(
'Save to flash',
persist,
'The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot.',
),
row('Daily traffic', days, 'Per-day history behind the charts.'),
row('Monthly traffic', months, 'Per-month totals; data limits use the current month.'),
E('h4', { class: 'dl-setsub' }, 'Stored data'),
E('div', { class: 'dl-list' }, [
stored(
'activity',
'Activity log',
L.events
? `${plural(L.events, 'event')} since ${since} · ${kb(L.log_ram)} in memory${p.persist === 'off' ? '' : `, ${kb(L.log_flash)} on flash`}`
: 'Empty',
[
exportBtn('csv'),
exportBtn('json'),
button(
'Clear',
() => clearLogDialog('Clear activity', 'Removes events from the log on the router.', {}, () => host.reload('logs')),
'negative',
),
],
),
stored(
'chart',
'Traffic history',
// usage_since is a router day (YYYY-MM-DD): shown as that day in any time zone.
L.usage_days ? `${plural(L.usage_days, 'day')} since ${fmtDay(L.usage_since)} · ${kb(L.usage_flash)} on flash` : 'Empty',
[button('Reset', () => resetUsageDialog('all', '', '', () => setTimeout(() => host.reload('logs'), 300)), 'negative')],
),
stored('pin', 'Location cache', `${plural(host.d.geo_cached, 'address', 'addresses')} · ${kb(L.geo_flash)} on flash`, [
button(
'Clear',
async () => {
if (await attempt(() => api.geoClear(), 'Location cache cleared')) await host.reload('logs');
},
'negative',
),
]),
]),
],
[
E('span', { class: 'dl-sub' }, 'Clear one person or device from their own page.'),
button(
'Save',
() =>
host.save(
{
log_keep_days: keep.dataset.value!,
log_max: size.dataset.value!,
log_persist: persist.dataset.value!,
usage_keep_days: days.dataset.value!,
usage_keep_months: months.dataset.value!,
log_category: [...chosen],
},
'Saved',
'logs',
),
'positive',
),
],
);
}
+35
View File
@@ -0,0 +1,35 @@
// Settings → Map & locations.
import { E } from '../../e';
import { button } from '../../ui/button';
import { isOn, sw } from '../../ui/controls';
import { row } from '../../ui/layout';
import { section, type SettingsHost } from './common';
export function mapCard(host: SettingsHost): HTMLElement {
const eff = host.d.effective as Record<string, any>;
const gOn = sw(eff.geo_enabled, 'Locations');
const prov = E('select', { class: 'cbi-input-select' }, [
E('option', { value: 'ipwho.is', selected: eff.geo_provider !== 'ipapi.co' ? 'selected' : null }, 'ipwho.is (fallback: ipapi.co)'),
E('option', { value: 'ipapi.co', selected: eff.geo_provider === 'ipapi.co' ? 'selected' : null }, 'ipapi.co (fallback: ipwho.is)'),
]) as HTMLSelectElement;
return section(
'map',
'Map & locations',
[
E('div', { class: 'dl-setrow head' }, [
E('span', { class: 'dl-muted' }, 'Show where people connect from on the Overview and person pages, at city level.'),
gOn,
]),
row('Provider', prov),
],
[
E(
'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.',
),
button('Save', () => host.save({ geo_enabled: isOn(gOn) ? '1' : '0', geo_provider: prov.value }, 'Saved', 'map'), 'positive'),
],
);
}
+400
View File
@@ -0,0 +1,400 @@
// Settings → Personal portal: the address in links (picked from what the
// router found), a preview, readiness, and the rest folded away.
import type { PortalInfo } from '../../api';
import { E } from '../../e';
import { button } from '../../ui/button';
import { cancelButton, closeModal, modal } from '../../ui/modal';
import { input, isOn, sw } from '../../ui/controls';
import { group, needRow, row } from '../../ui/layout';
import { icon } from '../../../shared/icons';
import { fmtDay } from '../../../shared/format';
import { installMissing } from '../../pkgs';
import { section, type SettingsHost } from './common';
/** Summary of the portal checks: those that failed or warn, and the worst state. */
function verdict(checks: PortalInfo['checks']) {
const shown = checks.filter((x) => x.status !== 'skip');
const bad = shown.filter((x) => x.status === 'error' || x.status === 'warn');
const worst = shown.some((x) => x.status === 'error') ? 'error' : bad.length ? 'warn' : 'ok';
return { bad, worst };
}
/** Personal portal: the address in links (picked from what the router found), a preview, readiness, and the rest folded away. */
export function portalCard(host: SettingsHost): HTMLElement {
const s = host.d.settings;
const eff = host.d.effective as Record<string, any>;
const c = host.d.cert;
const pOn = sw(eff.portal_enabled, 'Enable portal');
const port = input(s.portal_port, { placeholder: '8443', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' });
const title = input(s.portal_title, { placeholder: 'Dawnline' });
const redirect = input(s.portal_redirect, { placeholder: 'Show “Not found”', class: 'cbi-input-text dl-mono' });
const other = input('', { placeholder: 'vpn.example.com or an IP', 'aria-label': 'Other address' });
const isIp = (h: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(h);
// Chosen addresses, the main one first; custom ones join the list of options.
let picked: string[] = [eff.portal_host, ...(eff.portal_alt ?? [])].filter(
(h: string, i: number, a: string[]) => h && a.indexOf(h) === i,
);
// Until the router has looked the addresses up, only the chosen ones are listed.
let found = !!host.portal;
let rows: PortalInfo['candidates'] = [];
const addRow = (h: string) => {
if (h && !rows.some((x) => x.host === h))
rows.push({ host: h, kind: isIp(h) ? 'ip' : 'name', ips: [], here: false, cloudflare: false, cert: false });
};
const takeCands = (cands: PortalInfo['candidates']) => {
// Found addresses first (best first), then the chosen and added ones the router doesn't know.
rows = [...cands, ...rows.filter((x) => !cands.some((y) => y.host === x.host))];
if (!picked.length && cands[0]) picked = [cands[0].host];
};
if (host.portal) takeCands(host.portal.candidates);
picked.forEach(addRow);
const note = (x: PortalInfo['candidates'][number]): Node =>
x.kind === 'ip'
? E('span', { class: 'dl-addr-warn' }, [icon('alert'), 'Plain HTTP: the link and VPN keys travel unencrypted'])
: E(
'span',
{ class: 'dl-sub' },
x.cloudflare
? 'Behind Cloudflare · often stalls in Russia'
: !x.ips.length
? found
? 'Your address'
: 'Checking where it points…'
: x.here
? `Points at this router${x.cert ? ' · Let’s Encrypt certificate' : ' · no certificate yet'}`
: `Points at ${x.ips.join(', ')}, not this router`,
);
const opts = E('div', { class: 'dl-addr-opts', role: 'group', 'aria-label': 'Portal addresses' });
const toggle = (h: string) => {
if (picked.includes(h)) {
if (picked.length > 1) picked = picked.filter((x) => x !== h);
} else picked = [...picked, h];
paintOpts();
paintLinks();
};
const paintOpts = () =>
dom.content(opts, [
...rows.map((x) => {
const on = picked.includes(x.host),
main = picked[0] === x.host;
return E(
'div',
{
class: `dl-addr-opt${on ? ' on' : ''}`,
role: 'checkbox',
'aria-checked': on ? 'true' : 'false',
tabindex: '0',
click: () => toggle(x.host),
keydown: (ev: KeyboardEvent) => {
if (ev.key === ' ' || ev.key === 'Enter') {
ev.preventDefault();
toggle(x.host);
}
},
},
[
E('i', { class: 'dl-addr-check' }, on ? icon('check') : ''),
E('span', { class: 'dl-stack' }, [E('span', { class: 'dl-mono' }, x.host), note(x)]),
main
? E('span', { class: 'dl-pill info' }, 'Main')
: on
? E(
'button',
{
type: 'button',
class: 'dl-linkbtn',
click: (ev: Event) => {
ev.stopPropagation();
picked = [x.host, ...picked.filter((h) => h !== x.host)];
paintOpts();
paintLinks();
},
},
'Make main',
)
: x.cloudflare
? E('span', { class: 'dl-pill warn' }, 'Cloudflare')
: x.kind === 'ip'
? E('span', { class: 'dl-pill' }, 'IP')
: x.here && x.cert
? E('span', { class: 'dl-pill ok' }, 'Recommended')
: '',
],
);
}),
E('div', { class: 'dl-addr-opt other' }, [
E('i', { class: 'dl-addr-check' }, icon('plus')),
other,
button('Add', () => {
const h = other.value.trim().toLowerCase();
if (!h) return;
addRow(h);
if (!picked.includes(h)) picked = [...picked, h];
other.value = '';
paintOpts();
paintLinks();
}),
]),
]);
other.addEventListener('keydown', (ev: KeyboardEvent) => {
if (ev.key === 'Enter') {
ev.preventDefault();
(other.nextElementSibling as HTMLElement)?.click();
}
});
// One row per link, as people will see it (example code).
const links = E('div', { class: 'dl-links' });
const paintLinks = () => {
const lport = Number(port.value) || eff.portal_port;
dom.content(
links,
picked.map((h, i) => {
const ip = isIp(h);
// The portal keeps its own port (80 and 443 stay free for others).
const p = ip ? lport + 1 : lport;
const base = `${ip ? 'http' : 'https'}://${h}${p === (ip ? 80 : 443) ? '' : `:${p}`}/`;
return E('div', { class: 'dl-link-row' }, [
E('span', { class: `dl-link-ic ${ip ? 'warn' : 'ok'}` }, icon(ip ? 'alert' : 'lock')),
E('span', { class: 'dl-mono dl-link-url' }, [base, E('b', {}, 'kamiro-telosu-bavine')]),
i === 0 ? E('span', { class: 'dl-pill info' }, 'Main') : ip ? E('span', { class: 'dl-pill warn' }, 'HTTP') : '',
]);
}),
);
};
paintOpts();
paintLinks();
port.addEventListener('input', () => paintLinks());
// Readiness: one summary line, the checks as chips, details on demand.
const SHORT: Record<string, string> = {
portal: 'Portal running',
portal_dns: 'Points here',
portal_reply: 'Answers reach visitors',
portal_http: 'Plain HTTP',
cert: 'Certificate',
};
const need = host.d.needs ?? { https: [], acme: [], home: [] };
const readyGroup = (checks: PortalInfo['checks'] | null): HTMLElement => {
if (!eff.portal_enabled) return E('div', { hidden: true });
if (!checks)
return group('check', 'Ready to share', 'The portal’s checks from Health', [
E('p', { class: 'dl-muted dl-loading' }, 'Running checks…'),
]);
const shown = checks.filter((x) => x.status !== 'skip');
if (!shown.length) return E('div', { hidden: true });
const { bad, worst } = verdict(checks);
const details = E(
'div',
{ class: 'dl-ready-details', hidden: true },
shown.map((x) =>
E('div', { class: `dl-ready-item ${x.status}` }, [
icon(x.status === 'ok' ? 'check' : 'alert'),
E('span', { class: 'dl-stack' }, [E('span', {}, x.title), E('span', { class: 'dl-sub' }, x.detail)]),
]),
),
);
const ready = E('div', { class: 'dl-stack gap8' }, [
E('div', { class: `dl-ready-sum ${worst}` }, [
icon(worst === 'ok' ? 'check' : 'alert'),
E('span', { class: 'dl-stack' }, [
E(
'b',
{},
worst === 'ok' ? `All ${shown.length} checks passed` : `${shown.length - bad.length} of ${shown.length} checks passed`,
),
bad.length
? E('span', { class: 'dl-sub' }, bad.map((x) => x.detail).join(' '))
: E('span', { class: 'dl-sub' }, 'Links will open for the people you send them to.'),
]),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn',
click: (ev: Event) => {
details.hidden = !details.hidden;
(ev.currentTarget as HTMLElement).textContent = details.hidden ? 'Details' : 'Hide';
},
},
'Details',
),
]),
E(
'div',
{ class: 'dl-chips-row' },
shown.map((x) =>
E('span', { class: `dl-check-chip ${x.status}`, title: x.detail }, [
icon(x.status === 'ok' ? 'check' : 'alert'),
SHORT[x.id] ?? x.title,
]),
),
),
details,
]);
return group('check', 'Ready to share', 'The portal’s checks from Health', [ready]);
};
// The state pill next to the switch: none until the checks are in.
const readyPill = (checks: PortalInfo['checks'] | null): HTMLElement => {
if (!eff.portal_enabled || (!checks && !need.https.length)) return E('span', { hidden: true });
if (need.https.length) return E('span', { class: 'dl-pill bad' }, 'Can’t start');
const { worst } = verdict(checks!);
return E(
'span',
{ class: `dl-pill ${worst === 'ok' ? 'ok' : worst === 'error' ? 'bad' : 'warn'}` },
worst === 'error' ? 'Needs attention' : 'Ready',
);
};
let readyEl = readyGroup(host.portal?.checks ?? null);
let pillEl = readyPill(host.portal?.checks ?? null);
host.portalFill = (p) => {
found = true;
takeCands(p.candidates);
paintOpts();
paintLinks();
const g = readyGroup(p.checks);
readyEl.replaceWith(g);
readyEl = g;
const pl = readyPill(p.checks);
pillEl.replaceWith(pl);
pillEl = pl;
};
const until = c && !c.self_signed && c.expires ? fmtDay(c.expires) : '';
const listenRow = row(
'Listening port',
port,
host.d.port_owners.length
? `Port ${eff.portal_port} is used by ${host.d.port_owners.join(', ')}.`
: `Where the portal runs on the router: HTTPS here, plain HTTP for IP addresses on ${eff.portal_port + 1}.`,
);
const custom = !!(s.portal_cert && s.portal_key);
const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt';
const certFiles = () => {
const fc = input(s.portal_cert, { placeholder: '/etc/ssl/…/fullchain.crt' });
const fk = input(s.portal_key, { placeholder: '/etc/ssl/…/key' });
modal(
'Use your own certificate',
[
E('p', { class: 'dl-muted' }, 'Paths on the router. Leave both empty to pick a certificate automatically.'),
row('Certificate file', fc),
row('Key file', fk),
],
[
cancelButton(),
' ',
button(
'Save',
() => {
closeModal();
void host.save({ portal_cert: fc.value.trim(), portal_key: fk.value.trim() }, 'Certificate saved', 'portal');
},
'positive',
),
],
);
};
const missingRow = (ic: string, tone: '' | 'bad', title: string, sub: string, feature: 'https' | 'acme', label: string) =>
needRow(
ic,
tone,
title,
sub,
button(label, () => installMissing(feature, need[feature], () => host.reload('portal')), 'positive'),
);
const httpsRow = need.https.length
? missingRow(
'lock',
'bad',
'HTTPS isn’t available on this router',
`The portal needs ${need.https.join(' and ')}. It can’t start without them.`,
'https',
'Install',
)
: '';
const acmeRow =
need.acme.length && (!c || c.self_signed)
? missingRow(
'lock',
'',
'Free certificate from Let’s Encrypt',
`ACME isn’t installed. With it the router gets a certificate${s.portal_host ? ` for ${s.portal_host}` : ''} and browsers stop warning.`,
'acme',
'Install ACME',
)
: '';
const certRows = [
E('div', { class: 'dl-row' }, [
icon('lock'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, [kind, until ? E('span', { class: 'dl-faint' }, ` · until ${until}`) : '']),
E(
'span',
{ class: 'dl-sub dl-ellipsis', title: c?.path ?? '' },
!c
? 'Turn the portal on to see its certificate.'
: c.self_signed
? 'Made by the router: browsers warn until a certificate covers the address.'
: `${custom ? 'Your files' : 'Found automatically'} · ${c.path}`,
),
]),
]),
E('div', { class: 'dl-row' }, [
icon('file'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, 'Your own files'),
E('span', { class: 'dl-sub' }, custom ? `${s.portal_cert} · ${s.portal_key}` : 'Not set: the certificate is picked automatically.'),
]),
custom ? button('Reset', () => host.save({ portal_cert: '', portal_key: '' }, 'Automatic certificate', 'portal'), 'negative') : '',
button(custom ? 'Change' : 'Use files', certFiles),
]),
acmeRow,
];
return section(
'portal',
'Personal portal',
[
E('span', { class: 'dl-muted' }, 'A page where each person adds and manages their devices with their personal link.'),
httpsRow ? E('div', { class: 'dl-list' }, [httpsRow]) : '',
group('network', 'Port', 'How the portal listens (80 and 443 stay free)', [listenRow]),
group('edit', 'Appearance', 'What people see', [
row('Title', title, 'Shown at the top of the portal.'),
row('Unknown links', redirect, 'Where a wrong or old link goes, for example your website. Empty shows a plain “Not found”.'),
]),
group('link', 'Addresses', 'Pick one or more; the first is the main link', [
opts,
E('div', { class: 'dl-stack gap8' }, [
links,
E('span', { class: 'dl-sub' }, 'Example code; each person gets their own three words.'),
]),
]),
group('lock', 'Certificate', 'Used for HTTPS links', certRows),
readyEl,
],
[
E('span'),
button(
'Save',
() =>
host.save(
{
portal_enabled: isOn(pOn) ? '1' : '0',
portal_host: picked[0] ?? '',
portal_alt: picked.slice(1),
portal_port: port.value,
portal_title: title.value,
portal_redirect: redirect.value.trim(),
},
'Saved',
'portal',
),
'positive',
),
],
'',
[pillEl, pOn],
);
}
+121
View File
@@ -0,0 +1,121 @@
// Settings → Updates: automatic checks and updates of the components (the
// Components tab runs them by hand).
import type { UpdatePolicy } from '../../api';
import { E } from '../../e';
import { button } from '../../ui/button';
import { chipToggle, input, isOn, seg, setChip, sw } from '../../ui/controls';
import { row } from '../../ui/layout';
import { section, type SettingsHost } from './common';
const TARGET: [string, string][] = [
['app', 'Dawnline'],
['amneziawg', 'AmneziaWG'],
['packages', 'System packages'],
];
export function updatesCard(host: SettingsHost): HTMLElement {
const u = (host.d.effective as Record<string, any>).updates as UpdatePolicy;
const check = sw(u.check, 'Check automatically', (v) => show(v, isOn(auto)));
const every = seg(
[
['6h', 'Every 6 h'],
['12h', 'Every 12 h'],
['1d', 'Daily'],
['7d', 'Weekly'],
],
u.interval,
{ label: 'How often', cls: 'sm' },
);
const auto = sw(u.auto, 'Install automatically', (v) => show(isOn(check), v));
const at = input(u.time, {
placeholder: '04:00',
inputmode: 'numeric',
class: 'cbi-input-text dl-w-port dl-mono',
'aria-label': 'Time',
});
const mode = seg(
[
['scheduled', 'At a set time'],
['immediate', 'As soon as found'],
],
u.mode,
{ label: 'When', cls: 'sm', onChange: (v) => (at.hidden = v !== 'scheduled') },
);
at.hidden = u.mode !== 'scheduled';
const chosen = new Set<string>(u.targets);
const targets = E(
'div',
{ class: 'dl-chips-row' },
TARGET.map(([k, t]) => {
const b = chipToggle(t, chosen.has(k), () => {
if (!chosen.delete(k)) chosen.add(k);
setChip(b, chosen.has(k));
});
return b;
}),
);
const keep = sw(u.keep, 'Keep the previous version');
const mirrors = sw(u.mirrors, 'GitHub mirrors');
const everyRow = row('How often', every);
const autoRows = [
row(
'When',
E('div', { class: 'dl-hostport' }, [mode, at]),
'A set time keeps tunnel restarts out of the evening; the run happens within an hour of it.',
),
row('Components', targets, 'AmneziaWG is off by default: a new kernel module restarts every tunnel.'),
];
const show = (c: boolean, a: boolean) => {
everyRow.hidden = !c;
for (const r of autoRows) r.hidden = !a;
};
show(u.check, u.auto);
return section(
'updates',
'Updates',
[
E(
'span',
{ class: 'dl-muted' },
'How Dawnline keeps its components current. Every Dawnline update makes a backup of the settings first.',
),
row(
'Check automatically',
check,
'Looks for new versions in the background; Components shows what it found and the service log names it.',
),
everyRow,
row('Install automatically', auto, 'Downloads and installs new versions of the components below.'),
...autoRows,
row(
'Keep the previous version',
keep,
'Saves the replaced Dawnline or AmneziaWG package on flash, so Roll back works without internet. Under 1 MB.',
),
row('GitHub mirrors', mirrors, 'When GitHub is unreachable, download through mirrors. Checksums are still verified.'),
],
[
E('span', { class: 'dl-sub' }, 'Run a check or an update by hand in Components.'),
button(
'Save',
() =>
host.save(
{
update_check: isOn(check) ? '1' : '0',
update_interval: every.dataset.value!,
update_auto: isOn(auto) ? '1' : '0',
update_mode: mode.dataset.value!,
update_time: at.value.trim(),
update_targets: [...chosen],
update_keep: isOn(keep) ? '1' : '0',
update_mirrors: isOn(mirrors) ? '1' : '0',
},
'Saved',
'updates',
),
'positive',
),
],
);
}
+36 -29
View File
@@ -1,50 +1,57 @@
// Installing a missing package from wherever a feature is turned on: runs the
// updater job and follows it with toasts.
// updater job in the operation modal (see ./updater/operation).
import { api, type Needs } from './api';
import { attempt, confirmDialog, notify } from './ui';
import { attempt } from './ui/toast';
import { confirmDialog } from './ui/modal';
import { runOperation } from './updater/operation';
const WHAT: Record<keyof Needs, string> = {
https: 'HTTPS for the portal',
acme: 'ACME certificates',
home: 'the home-like link',
awg: 'AmneziaWG',
};
const WAIT_MS = 5 * 60 * 1000;
/** Install `names` for `feature`; resolves true when the job finished, then calls `done`. */
/** Ask, then wait for the job; after it `done` runs once the service had a moment to pick the packages up. */
async function install(what: string, label: string, body: string, done?: () => void): Promise<boolean> {
if (!(await confirmDialog(`Install ${label}?`, body, 'Install'))) return false;
const job = await runOperation(what, { title: `Installing ${label}` });
if (job?.state !== 'done') return false;
// The service restarts to pick them up; give it a moment before reloading.
setTimeout(() => done?.(), 4000);
return true;
}
/**
* AmneziaWG itself: the first build that exists for this firmware (feeds have
* none). The router loads the module afterwards and, when netifd has to learn
* the new protocol, restarts the network.
*/
export function installAwg(done?: () => void): Promise<boolean> {
return install(
'amneziawg:auto',
'AmneziaWG',
'Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.',
done,
);
}
/** Install `names` for `feature` in the operation modal; resolves true when it finished, then calls `done`. */
export async function installMissing(feature: keyof Needs, names: string[], done?: () => void): Promise<boolean> {
if (feature === 'awg') return installAwg(done);
if (!names.length) return true;
const ok = await confirmDialog(
`Install ${WHAT[feature]}?`,
return install(
`pkgs:${names.join(',')}`,
WHAT[feature],
`${names.join(', ')} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,
'Install',
done,
);
if (!ok) return false;
// The previous job stays in the status until the updater starts: wait for a new one.
const before = (await api.updatesStatus().catch(() => null))?.job?.started ?? 0;
if (!(await attempt(() => api.updatesRun(`pkgs:${names.join(',')}`)))) return false;
notify(`Installing ${names.join(', ')}…`, 'info', 4000);
const until = Date.now() + WAIT_MS;
while (Date.now() < until) {
await new Promise((r) => setTimeout(r, 2000));
const st = await api.updatesStatus().catch(() => null);
const job = st?.job;
if (!job || job.started === before || job.state === 'running') continue;
if (job.state === 'done') {
notify(`${names.join(', ')} installed`, 'success');
// The service restarts to pick them up; give it a moment before reloading.
setTimeout(() => done?.(), 4000);
return true;
}
notify(job.error ?? 'Installation failed', 'error');
return false;
}
notify('Still installing: see Updates for the log.', 'warning');
return false;
}
/** Install what a feature is missing, asking the router what that is now. */
export async function installFeature(feature: keyof Needs, done?: () => void) {
if (feature === 'awg') return installAwg(done);
const st = await attempt(() => api.updatesStatus());
if (st) return installMissing(feature, st.needs?.[feature] ?? [], done);
return false;
+73
View File
@@ -0,0 +1,73 @@
// Live pages: a poller with "newest answer wins", and repaints that leave a
// region alone while the keyboard focus is inside it (typing, a picker, a
// focused button), so a background refresh never takes it away.
/**
* Request tickets: an answer is shown only if nothing newer was shown before
* it. `claim()` invalidates everything in flight (an edit's own answer wins).
*/
export class Sequence {
private n = 0;
private shown = 0;
next(): number {
return ++this.n;
}
/** True (and marks `t` shown) unless a newer answer was shown already. */
take(t: number): boolean {
if (t < this.shown) return false;
this.shown = t;
return true;
}
claim(): void {
this.shown = ++this.n;
}
}
export interface PollerOptions<T> {
/** One request; rejections and null count as "no answer". */
fetch: () => Promise<T | null>;
/** Paint an answer; `quiet` for the periodic ones. */
apply: (data: T, quiet: boolean) => void;
/** Seconds between ticks. */
every: number;
/** Ticks are skipped while this is false (e.g. the page is not on screen). */
active?: () => boolean;
}
export interface Poller<T> {
/** Fetch and apply now (unless a newer answer arrives first); resolves with what was applied. */
refresh(quiet?: boolean): Promise<T | null>;
/** An edit is about to repaint: answers already on their way are dropped. */
claim(): void;
stop(): void;
}
export function createPoller<T>(o: PollerOptions<T>): Poller<T> {
const seq = new Sequence();
const refresh = async (quiet = false): Promise<T | null> => {
const t = seq.next();
const d = await o.fetch().catch(() => null);
if (d == null || !seq.take(t)) return null;
o.apply(d, quiet);
return d;
};
const tick = () => ((o.active?.() ?? true) ? refresh(true) : Promise.resolve(null));
poll.add(tick, o.every);
return { refresh, claim: () => seq.claim(), stop: () => poll.remove(tick) };
}
/** The keyboard focus (or an open native picker's input) is inside `el`. */
export function focusInside(el: Element | null | undefined): boolean {
const a = document.activeElement;
return !!el && !!a && a !== document.body && el.contains(a);
}
/**
* Replace a region's content, unless this is a quiet repaint and the focus is
* inside it; then it keeps what is on screen until the next one.
*/
export function repaint(el: HTMLElement, content: Parameters<typeof dom.content>[1], quiet = false): boolean {
if (quiet && focusInside(el)) return false;
dom.content(el, content);
return true;
}
+39
View File
@@ -0,0 +1,39 @@
// The status as seen from one server.
import type { Person, Status } from '../../shared/types';
/**
* The status as seen from one server: its people, their devices, traffic,
* map points and events (plus router-wide events without a person).
*/
export function scoped(st: Status, srvId: string): Status {
const srv = st.servers.find((s) => s.id === srvId) ?? st.servers[0];
const people = st.people.filter((p) => p.server === srv.id);
const ids = new Set(people.map((p) => p.id));
const devices = people.flatMap((p) => p.devices);
const sum = (f: (p: Person) => [number, number]) =>
people.reduce<[number, number]>(
(a, p) => {
const v = f(p);
return [a[0] + v[0], a[1] + v[1]];
},
[0, 0],
);
const today = srv.series?.[srv.series.length - 1];
return {
...st,
servers: [srv],
people,
series: srv.series ?? st.series,
events: st.events.filter((e) => (e.person ? ids.has(e.person) : true)),
geo: { ...st.geo, points: st.geo.points.filter((g) => ids.has(g.person)) },
totals: {
people: people.length,
devices: devices.length,
online: devices.filter((d) => d.online).length,
active: people.filter((p) => p.state === 'active').length,
today: today ? [today.rx, today.tx] : [0, 0],
month: sum((p) => p.month),
},
};
}
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
/* Server → Access, and a core's settings head. */
/* Server → Access: networks as chips, circles, services from home, who reaches what, check access. */
.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 { margin-top: 8px; }
.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-ports { justify-content: flex-end; }
@media (max-width: 760px) { .dl-host-ports { justify-content: flex-start; } }
.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); }
/* A core's settings head; device cards open their panel. */
.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); }
+115
View File
@@ -0,0 +1,115 @@
/* Tokens (Outline first, LuCI Bootstrap next, a fallback that works anywhere), pills, cards, activity rows. */
:root {
/* Outline's tokens first, then LuCI Bootstrap's, then something that works anywhere. */
--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-soft: var(--muted, color-mix(in srgb, currentColor 5%, transparent));
--dl-soft-hover: var(--soft-hover, color-mix(in srgb, currentColor 10%, transparent));
--dl-fg: var(--foreground, var(--text-color-highest, inherit));
--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-ok-wash: var(--success-a15, color-mix(in srgb, #00a240 15%, transparent));
--dl-warn-wash: var(--warning-a15, color-mix(in srgb, #e25507 15%, transparent));
--dl-bad-wash: var(--destructive-a15, color-mix(in srgb, #e02e2a 15%, transparent));
--dl-info-wash: var(--info-a15, color-mix(in srgb, #3a83f7 15%, transparent));
--dl-info: var(--info, #2c67c5);
--dl-track: var(--foreground-a10, color-mix(in srgb, currentColor 10%, transparent));
--dl-chart-1: var(--chart-blue, #3a83f7);
--dl-chart-2: var(--chart-green, #00a240);
--dl-ring: var(--ring, #3a83f7);
--dl-primary: var(--primary, #0d0d0d);
--dl-primary-fg: var(--primary-foreground, #fff);
--dl-mono: var(--font-mono, ui-monospace, Menlo, Consolas, monospace);
--dl-shadow: var(--shadow-sm, none);
--dl-radius: 16px;
}
.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 { color: var(--dl-fg-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; }
/* pills: Outline's .label */
.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; }
/* cards (Outline .cbi-section-node look) */
.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); } }
/* chart */
.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); }
/* activity */
.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); }
/* The admin's own actions: an icon in the dot's place, taking the same room. */
.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; }
/* Service log lines: tile, source name and row tint share one colour, set by the level (--sys). */
.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; }
/* server summary */
.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; }
+87
View File
@@ -0,0 +1,87 @@
/* Components page, status lines, versions, the operation modal and What's new. */
/* ===== Components ===== */
.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; } }
/* Status lines (the operation modal) */
.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; }
/* Versions */
.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; }
/* The operation modal and What's new */
.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); }
+119
View File
@@ -0,0 +1,119 @@
/* Choice cards, stacking of modals, drawer and menus, quiet inline actions, round icon buttons, status dots. */
/* choice cards */
/* LuCI's modal above the device drawer (900); menus above both. */
#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; }
/* Small inline actions (View all, Change, Export, Clear…): quiet buttons, not underlined links. */
.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; }
.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); }
/* The one status dot left: a server that is running pulses. */
@keyframes dl-srv-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--dl-ok) 55%, transparent); } 70%, 100% { 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; }
+47
View File
@@ -0,0 +1,47 @@
/* Setup wizard steps and dialogs. */
/* wizard steps */
.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); }
/* Each step's content: intro, fields and choices with even spacing. */
.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; }
/* dialogs */
.dl-modal .cbi-tabmenu { margin-bottom: 16px; }
.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: translateX(-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 rgba(0, 0, 0, .3);
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; }
+33
View File
@@ -0,0 +1,33 @@
/* Disguise method cards. */
/* Disguise methods */
.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); }
+52
View File
@@ -0,0 +1,52 @@
/* Toasts and the device drawer. */
/* live toasts */
.dl-toast strong { display: block; font-weight: 500; }
.dl-toast div { opacity: .8; font-size: 13px; }
/* device drawer */
.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: translateX(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; }
/* Values wrap (an IPv6 endpoint, traffic totals); only copyable keys are cut, see .copy */
.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; }
+55
View File
@@ -0,0 +1,55 @@
/* Diagnostics → Health: watchdog, checks, service log; tables inside panels. */
/* health */
.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); }
/* Health: watchdog card, then checks and the service log side by side. */
.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; }
/* tables inside panels */
.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); }
+53
View File
@@ -0,0 +1,53 @@
// Dawnline admin styles, built on the Outline theme's design tokens
// (luci-theme-outline: --panel-bg, --border, --muted, --accent, --success-a15,
// …). Every token has a fallback so other themes still get a sane look.
// Outline switches dark mode with html[data-darkmode], and its tokens follow
// it automatically, so nothing here needs a dark variant.
//
// One file per feature, imported as text (tsup minifies them, see
// tsup.config.ts) and joined in cascade order: later files override earlier ones.
//
// The <style> element is rendered inside each view (not <head>): Outline's
// same-document router treats unknown head styles as a reason to reload.
import base from './base.css';
import people from './people.css';
import controls from './controls.css';
import disguise from './disguise.css';
import overview from './overview.css';
import dialogs from './dialogs.css';
import portalSettings from './portal-settings.css';
import health from './health.css';
import layout from './layout.css';
import map from './map.css';
import person from './person.css';
import drawer from './drawer.css';
import settings from './settings.css';
import components from './components.css';
import access from './access.css';
export const CSS = [
base,
people,
controls,
disguise,
overview,
dialogs,
portalSettings,
health,
layout,
map,
person,
drawer,
settings,
components,
access,
].join('\n');
/** A <style> element for the view root (see the note at the top). */
export function styleNode(): HTMLStyleElement {
const el = document.createElement('style');
el.dataset.dawnline = '1';
el.textContent = CSS;
return el;
}
+48
View File
@@ -0,0 +1,48 @@
/* Page structure, metrics strip, segmented controls, server sections. */
/* ===== page structure ===== */
.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); }
/* Icon-only buttons are circles: width follows the theme's button height. */
.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); }
/* metrics strip */
.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); } }
/* segmented control */
.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); }
/* Server sections: one row that scrolls sideways on narrow screens */
.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); }
+65
View File
@@ -0,0 +1,65 @@
/* Connection map and charts. */
/* map */
.dl-geomap { position: relative; border-top: 1px solid var(--dl-line); background: var(--dl-soft); }
.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.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--dl-fg-faint); }
.dl-map-legend i.dot.ok { background: var(--dl-ok); }
.dl-map-legend i.line { width: 14px; height: 2px; border-radius: 2px; background: var(--dl-ok); }
.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; width: 18px; height: 18px; display: inline-flex; align-items: center; justify-content: center; position: relative; }
.dl-mk-dot { width: 12px; height: 12px; border-radius: 50%; background: #8f8f8f; box-shadow: 0 0 0 3px rgba(0,0,0,.55); }
.dl-mk.online .dl-mk-dot { width: 14px; height: 14px; background: #40c977; }
.dl-mk.online::before { content: ''; position: absolute; inset: -9px; border-radius: 50%; background: rgba(64, 201, 119, .28); animation: dl-pulse 2s ease-out infinite; }
@keyframes dl-pulse { 0% { transform: scale(.5); opacity: 1; } 100% { transform: scale(1.4); opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .dl-mk.online::before { animation: none; } }
.dl-mk-home { width: 22px; height: 22px; border-radius: 7px; background: #ededed; display: flex; align-items: center; justify-content: center;
box-shadow: 0 0 0 4px rgba(237, 237, 237, .18), 0 2px 6px rgba(0,0,0,.5); color: #131313; }
.dl-mk-home-ic { width: 13px; height: 13px; }
.dl-popup { z-index: 4; }
.dl-popup .maplibregl-popup-content { background: var(--dl-elevated); color: var(--dl-fg); border: 1px solid var(--dl-line); border-radius: 12px; padding: 12px;
box-shadow: var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4)); font: inherit; }
.dl-popup .maplibregl-popup-tip { border-top-color: var(--dl-elevated) !important; border-bottom-color: var(--dl-elevated) !important; }
.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-mk.multi { width: 26px; height: 26px; }
.dl-mk-count { min-width: 22px; height: 22px; padding: 0 6px; border-radius: 999px; background: #8f8f8f; color: #0a0a0a; font: 600 11px/22px var(--dl-mono);
text-align: center; box-shadow: 0 0 0 3px rgba(0,0,0,.55); box-sizing: border-box; }
.dl-mk.online .dl-mk-count { background: #40c977; }
.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 -4px 0; }
.dl-pop-row { all: unset; cursor: pointer; display: flex; align-items: center; gap: 8px; padding: 5px 4px; border-radius: 6px; }
.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; }
.maplibregl-ctrl-attrib { font-size: 10px; }
/* charts */
.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-spark i:hover { opacity: 1; filter: brightness(1.25); }
.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; gap: 2px; flex: 0 0 auto; }
.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; }
+187
View File
@@ -0,0 +1,187 @@
/* Server Overview: address bar, bento tiles, who is online, hover card, disguise tile, health strip. */
/* Overview: address bar */
.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; }
/* Overview: bento */
.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; 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 i:hover { 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; }
/* Online: only live connections, as avatars */
.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: -5px; bottom: -5px; width: 20px; height: 20px; border-radius: 7px; background: var(--dl-card); box-shadow: 0 0 0 1.5px 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.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; }
/* Hover card for a person online */
.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; }
/* Disguise tile */
.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-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 { justify-content: space-between; }
.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; gap: 3px; height: 54px; }
.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 i:hover { 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%; } }
/* Notices (failed health checks, AmneziaWG missing in the wizard): dl-list of need rows. */
.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-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; }
+46
View File
@@ -0,0 +1,46 @@
/* People: one card per person (.dl-plist > .dl-card). */
.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 .dl-card-name, .dl-plist > .dl-card.dl-off .dl-avatar { opacity: .6; }
.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; box-shadow: inset 0 0 0 1px var(--dl-line); color: var(--dl-fg-muted); aspect-ratio: 1; padding: 0; justify-content: center; }
.dl-chip.add:hover { background: var(--dl-soft); 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; }
}
/* full-width rows (label above) */
.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; }
+145
View File
@@ -0,0 +1,145 @@
/* Rows, the person page, people cards (extra), live chips. */
/* rows */
.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; }
/* person page */
.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; }
/* Cards in a row share a height: the bottom block (usage or set-up buttons) sits on the bottom edge. */
.dl-dcard > .dl-dcard-head + * { margin-top: auto; }
@media (max-width: 700px) { .dl-dgrid { grid-template-columns: minmax(0, 1fr); } }
/* No devices yet: the add card takes the whole row instead of leaving a hole. */
.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 rgba(0,0,0,.3); }
.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; }
/* people cards (extra) */
.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); }
/* Online device: a soft green chip instead of a dot */
.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); }
.dl-plist > .dl-card.dl-attn-row { border-color: color-mix(in srgb, var(--dl-warn) 35%, transparent); }
@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%, 0); opacity: 1; pointer-events: auto; }
.dl-savebar-text { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 500; }
+68
View File
@@ -0,0 +1,68 @@
/* Settings → Personal portal: address picker, link preview, readiness. */
/* Settings: portal address picker, link preview, readiness */
.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); }
/* Phones: show the whole link, wrapped, instead of cutting it */
@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: #fff; padding: 8px; border-radius: 12px; 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; }
+64
View File
@@ -0,0 +1,64 @@
/* Settings cards, groups, missing packages, backups, updates. */
/* settings */
.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; }
/* Groups inside a settings card */
.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) { border-top: 1px solid var(--dl-line); }
/* Boxed pieces (a notice, a parameters panel) keep their own padding and frame: spaced, not ruled. */
.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 > .alert-message + *, .dl-group-body > .dl-params + * { 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-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; } }
/* A missing package, shown where its feature is turned on */
.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; }
/* Monospace reads larger than the sans text around it */
.dl-sub .dl-mono { font-size: .92em; }
.dl-need-row > .cbi-button { flex: none; }
/* Backups section in Settings */
.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; } }
/* Updates: Settings-style sections, one row anatomy (name and note left, a pill or a button right) */
.dl-upd { display: flex; flex-direction: column; gap: 16px; }
.dl-upd > .dl-pagehead { margin: 0 0 4px; }
.dl-upd-bad { color: var(--dl-bad); }
-316
View File
@@ -1,316 +0,0 @@
// UI helpers on top of LuCI's `ui` and `E()`; markup stays stock LuCI
// (cbi-button, cbi-tabmenu, alert-message) so themes style it.
import type { Child } from './luci.d';
import { E } from './e';
import { icon } from '../shared/icons';
type ButtonKind = 'action' | 'positive' | 'negative' | 'neutral' | 'apply' | 'remove' | 'edit' | 'add' | 'reset' | 'save';
export function button(
label: Child,
onClick: (ev: MouseEvent) => unknown,
kind: ButtonKind = 'neutral',
extra: Record<string, unknown> = {},
): HTMLButtonElement {
// E() sets every non-null attribute, so `disabled: false` would still
// disable the button: boolean state goes through the property.
const { disabled, ...attrs } = extra;
const btn = E(
'button',
{
class: `cbi-button cbi-button-${kind}`,
type: 'button',
...attrs,
click: async (ev: MouseEvent) => {
ev.preventDefault();
ev.stopPropagation();
if (btn.disabled) return;
btn.disabled = true;
btn.classList.add('spinning');
try {
await onClick(ev);
} catch (e) {
notify(errorText(e), 'error');
} finally {
btn.disabled = false;
btn.classList.remove('spinning');
}
},
},
label,
) as HTMLButtonElement;
btn.disabled = !!disabled;
return btn;
}
export function iconButton(name: string, title: string, onClick: (ev: MouseEvent) => unknown, kind: ButtonKind = 'neutral', cls = '') {
return button([icon(name), E('span', { class: 'dl-btn-label' }, title)], onClick, kind, {
title,
class: `cbi-button cbi-button-${kind} dl-icon-btn ${cls}`.trim(),
});
}
/**
* A small toast at the bottom of the screen, above modals; replaces LuCI's
* banner at the top of the page. Errors stay longer and can be closed.
*/
export function notify(message: Child, tone: 'info' | 'error' | 'warning' | 'success' = 'info', timeout = 0) {
let stack = document.querySelector('.dl-toasts') as HTMLElement | null;
if (!stack) {
stack = E('div', { class: 'dl-toasts dl-root', role: 'status', 'aria-live': 'polite' });
document.body.appendChild(stack);
}
const ic = tone === 'error' ? 'x' : tone === 'warning' ? 'alert' : tone === 'success' ? 'check' : null;
const close = () => {
t.classList.remove('show');
setTimeout(() => t.remove(), 200);
};
const t = E('div', { class: `dl-toast ${tone}` }, [
ic ? icon(ic) : '',
E('span', {}, message),
tone === 'error' ? E('button', { type: 'button', 'aria-label': 'Close', click: close }, icon('x')) : '',
]);
stack.appendChild(t);
requestAnimationFrame(() => t.classList.add('show'));
setTimeout(close, timeout || (tone === 'error' ? 8000 : tone === 'warning' ? 5000 : 2600));
}
export function errorText(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
/** Run an action; failures become a toast. Returns undefined on error. */
export async function attempt<T>(fn: () => Promise<T>, ok?: Child): Promise<T | undefined> {
try {
const r = await fn();
if (ok) notify(ok, 'success', 3500);
return r;
} catch (e) {
notify(errorText(e), 'error', 10000);
return undefined;
}
}
export function modal(title: string, body: Child, actions: Child, cls = '') {
ui.showModal(title, [E('div', { class: `dl-modal ${cls}` }, body), E('div', { class: 'button-row' }, actions)]);
}
export function closeModal() {
ui.hideModal();
}
export function confirmDialog(title: string, body: Child, confirmLabel = 'Confirm', danger = false): Promise<boolean> {
return new Promise((resolve) => {
modal(title, body, [
E(
'button',
{
class: 'cbi-button cbi-button-neutral',
type: 'button',
click: () => {
closeModal();
resolve(false);
},
},
'Cancel',
),
' ',
E(
'button',
{
class: `cbi-button ${danger ? 'cbi-button-negative' : 'cbi-button-positive'}`,
type: 'button',
click: () => {
closeModal();
resolve(true);
},
},
confirmLabel,
),
]);
});
}
export async function copyText(text: string, what = 'Copied to clipboard') {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
} else {
const ta = E('textarea', { style: 'position:fixed;opacity:0' }, text) as HTMLTextAreaElement;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
ta.remove();
}
notify(what, 'success', 2500);
} catch (e) {
notify(errorText(e), 'error');
}
}
/** Saves a file; pass application/octet-stream for .conf, or Safari appends .txt. */
export function downloadFile(name: string, content: string | Blob, type = 'text/plain') {
const g = globalThis as unknown as { Blob: typeof Blob };
const blob = typeof content === 'string' ? new g.Blob([content], { type }) : content;
const url = URL.createObjectURL(blob);
const a = E('a', { href: url, download: name, style: 'display:none' });
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
a.remove();
}, 1000);
}
/** LuCI-style tab strip (cbi-tabmenu) for custom modal content. */
export function tabs(panes: { id: string; label: string; content: Child }[], initial?: string): HTMLElement {
const head = E('ul', { class: 'cbi-tabmenu' });
const body = E('div', { class: 'dl-tab-body' });
const show = (id: string) => {
head.querySelectorAll('li').forEach((li) => {
li.classList.toggle('cbi-tab', li.dataset.id === id);
li.classList.toggle('cbi-tab-disabled', li.dataset.id !== id);
});
body.querySelectorAll<HTMLElement>(':scope > [data-pane]').forEach((p) => (p.style.display = p.dataset.pane === id ? '' : 'none'));
};
for (const p of panes) {
head.appendChild(
E(
'li',
{ 'data-id': p.id },
E(
'a',
{
href: '#',
click: (ev: Event) => {
ev.preventDefault();
show(p.id);
},
},
p.label,
),
),
);
body.appendChild(E('div', { 'data-pane': p.id }, p.content));
}
show(initial ?? panes[0]?.id);
return E('div', { class: 'dl-tabs' }, [head, body]);
}
export function field(label: Child, widget: Child, description?: Child): HTMLElement {
return E('div', { class: 'cbi-value' }, [
E('label', { class: 'cbi-value-title' }, label),
E('div', { class: 'cbi-value-field' }, [widget, description ? E('div', { class: 'cbi-value-description' }, description) : '']),
]);
}
export function callout(tone: 'ok' | 'warn' | 'error' | 'info', children: Child): HTMLElement {
const cls = { ok: 'success', warn: 'warning', error: 'error', info: 'notice' }[tone];
return E('div', { class: `alert-message ${cls}` }, children);
}
export function pill(text: Child, tone = '', title = ''): HTMLElement {
return E('span', { class: `dl-pill ${tone}`, title }, text);
}
export function svg(markup: string, cls = ''): HTMLElement {
const el = E('div', { class: cls });
el.innerHTML = markup;
return el;
}
/** Read a picked file as text or base64. */
export function pickFile(accept: string, as: 'text' | 'base64'): Promise<{ name: string; data: string } | null> {
return new Promise((resolve) => {
const input = E('input', { type: 'file', accept, style: 'display:none' }) as HTMLInputElement;
// Closing the file picker fires "cancel" (no "change"); without it the caller waits forever.
input.addEventListener('cancel', () => {
input.remove();
resolve(null);
});
input.addEventListener('change', () => {
const f = input.files?.[0];
input.remove();
if (!f) return resolve(null);
const r = new FileReader();
r.onload = () => {
const res = String(r.result ?? '');
resolve({ name: f.name, data: as === 'base64' ? res.replace(/^data:[^,]*,/, '') : res });
};
r.onerror = () => resolve(null);
if (as === 'base64') r.readAsDataURL(f);
else r.readAsText(f);
});
document.body.appendChild(input);
input.click();
});
}
export interface MenuItem {
label: string;
icon?: Node;
danger?: boolean;
warn?: boolean;
run: () => unknown;
}
/** Small dropdown under `anchor`; closes on pick, outside click or Escape. */
type OpenMenu = HTMLElement & { dlAnchor?: HTMLElement; dlClose?: () => void };
export function dropdown(anchor: HTMLElement, items: (MenuItem | null)[]) {
// A second click on the same button closes its menu instead of reopening it.
const prev = document.querySelector('.dl-dd') as OpenMenu | null;
if (prev) {
prev.dlClose ? prev.dlClose() : prev.remove();
if (prev.dlAnchor === anchor) return;
}
const menu: OpenMenu = E(
'div',
{ class: 'dl-dd dl-root', role: 'menu' },
items.map((it) =>
it
? E(
'button',
{
type: 'button',
role: 'menuitem',
class: it.danger ? 'danger' : it.warn ? 'warn' : '',
click: () => {
close();
it.run();
},
},
[it.icon ?? '', E('span', {}, it.label)],
)
: E('hr'),
),
);
document.body.appendChild(menu);
const r = anchor.getBoundingClientRect();
const w = menu.offsetWidth,
h = menu.offsetHeight;
// Open upwards when the menu would run off the bottom of the screen.
menu.style.top = `${r.bottom + 6 + h > window.innerHeight - 8 && r.top - 6 - h > 8 ? r.top - 6 - h : r.bottom + 6}px`;
menu.style.left = `${Math.max(8, Math.min(r.right - w, window.innerWidth - w - 8))}px`;
const onDoc = (ev: Event) => {
if (!menu.contains(ev.target as Node) && !anchor.contains(ev.target as Node)) close();
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === 'Escape') close();
};
menu.dlAnchor = anchor;
menu.dlClose = close;
function close() {
menu.remove();
document.removeEventListener('mousedown', onDoc, true);
document.removeEventListener('keydown', onKey, true);
window.removeEventListener('scroll', close, true);
}
setTimeout(() => {
document.addEventListener('mousedown', onDoc, true);
document.addEventListener('keydown', onKey, true);
window.addEventListener('scroll', close, true);
});
(menu.querySelector('button') as HTMLElement | null)?.focus({ preventScroll: true });
}
+63
View File
@@ -0,0 +1,63 @@
// Small status marks: pills, a person's state and access, a device's status.
import type { Device, Person } from '../../shared/types';
import { E } from '../e';
import { icon } from '../../shared/icons';
import { ACCESS_LABEL, STATE_LABEL, ago } from '../../shared/format';
import { attachTip } from './tooltip';
export function pill(tone: string, text: string, title?: string): HTMLElement {
return E('span', { class: `dl-pill ${tone}`, title: title ?? null }, text);
}
const STATE_ICON: Record<Person['state'], string> = {
active: '',
paused: 'pause',
paused_all: 'pause',
expired: 'calendar',
quota: 'chart',
hours: 'clock',
no_server: 'alert',
};
export function stateTone(p: Person): string {
if (p.state === 'active') return 'ok';
if (p.state === 'quota' || p.state === 'expired') return 'bad';
return 'warn';
}
/** Nothing while active; otherwise a small icon with the state as tooltip. */
export function stateBadge(p: Person): HTMLElement | '' {
if (p.state === 'active') return '';
const el = E('span', { class: `dl-ibadge ${stateTone(p)}`, 'aria-label': STATE_LABEL[p.state] }, icon(STATE_ICON[p.state] || 'alert'));
attachTip(el, () => [E('div', { class: 'dl-tip-title' }, STATE_LABEL[p.state])]);
return el;
}
/** What the person can reach, as icons: home network, internet, or both. */
export function accessBadge(p: Person): HTMLElement {
const kinds = p.access === 'both' ? ['lan', 'inet'] : p.access === 'lan' ? ['lan'] : ['inet'];
const el = E(
'span',
{ class: 'dl-access', 'aria-label': ACCESS_LABEL[p.access] },
kinds.map((k) => E('span', { class: `dl-ibadge ${k}` }, icon(k === 'lan' ? 'home' : 'globe'))),
);
attachTip(el, () => [
E('div', { class: 'dl-tip-title' }, ACCESS_LABEL[p.access]),
p.access === 'lan' && p.services?.length
? E('div', { class: 'dl-muted' }, `${p.services.length} home service${p.services.length === 1 ? '' : 's'} only`)
: '',
]);
return el;
}
/**
* A device's status as coloured text, no dots (only avatars carry one). `now`
* is the router's clock; `waiting` is the text before the first connection.
*/
export function deviceStatus(d: Device, now?: number, waiting = 'Not set up yet'): HTMLElement {
if (d.disabled) return E('span', { class: 'dl-dstat' }, 'Disabled');
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
if (!d.handshake) return E('span', { class: 'dl-dstat warn', title: 'Waiting for the first connection' }, waiting);
return E('span', { class: 'dl-dstat' }, `Last seen ${ago(d.handshake, now)}`);
}
+53
View File
@@ -0,0 +1,53 @@
// Buttons: stock LuCI markup (cbi-button) so themes style them. A click runs
// the action once (disabled and spinning until it settles); failures become a toast.
import type { Child } from '../luci.d';
import { E } from '../e';
import { icon } from '../../shared/icons';
import { errorText, notify } from './toast';
export type ButtonKind = 'action' | 'positive' | 'negative' | 'neutral' | 'apply' | 'remove' | 'edit' | 'add' | 'reset' | 'save';
export function button(
label: Child,
onClick: (ev: MouseEvent) => unknown,
kind: ButtonKind = 'neutral',
extra: Record<string, unknown> = {},
): HTMLButtonElement {
// E() sets every non-null attribute, so `disabled: false` would still
// disable the button: boolean state goes through the property.
const { disabled, ...attrs } = extra;
const btn = E(
'button',
{
class: `cbi-button cbi-button-${kind}`,
type: 'button',
...attrs,
click: async (ev: MouseEvent) => {
ev.preventDefault();
ev.stopPropagation();
if (btn.disabled) return;
btn.disabled = true;
btn.classList.add('spinning');
try {
await onClick(ev);
} catch (e) {
notify(errorText(e), 'error');
} finally {
btn.disabled = false;
btn.classList.remove('spinning');
}
},
},
label,
) as HTMLButtonElement;
btn.disabled = !!disabled;
return btn;
}
export function iconButton(name: string, title: string, onClick: (ev: MouseEvent) => unknown, kind: ButtonKind = 'neutral', cls = '') {
return button([icon(name), E('span', { class: 'dl-btn-label' }, title)], onClick, kind, {
title,
class: `cbi-button cbi-button-${kind} dl-icon-btn ${cls}`.trim(),
});
}
+118
View File
@@ -0,0 +1,118 @@
// Form controls in the house style: a switch, a segmented control, a chip
// toggle and a text input.
import { E } from '../e';
/** dl-switch; `onChange` gets the new state (the switch has already flipped). */
export function sw(on: boolean, label: string, onChange?: (v: boolean) => void): HTMLButtonElement {
const b = E(
'button',
{
type: 'button',
role: 'switch',
class: `dl-switch${on ? ' on' : ''}`,
'aria-checked': on ? 'true' : 'false',
'aria-label': label,
click: () => {
const v = !b.classList.contains('on');
setSwitch(b, v);
onChange?.(v);
},
},
E('i'),
) as HTMLButtonElement;
return b;
}
export function setSwitch(b: HTMLElement, on: boolean) {
b.classList.toggle('on', on);
b.setAttribute('aria-checked', on ? 'true' : 'false');
}
export const isOn = (b: HTMLElement) => b.classList.contains('on');
export interface SegOptions<T extends string> {
/** aria-label of the group. */
label?: string;
/** Extra classes: 'sm', 'wide', 'dl-srvsections'… */
cls?: string;
/** Called with a different option than the current one. */
onChange?: (v: T) => void;
/**
* Move the selection right away (default). Off for choices that apply on the
* router at once: the page repaints from the answer, a failure leaves it as it was.
*/
optimistic?: boolean;
}
/**
* Single-choice dl-seg (radiogroup). The current choice is in `.dataset.value`.
* Unknown values get an option of their own, so nothing is lost on save.
*/
export function seg<T extends string>(options: [T, Node | string | (Node | string)[]][], value: T, o: SegOptions<T> = {}): HTMLElement {
if (!options.some(([v]) => v === value)) options = [...options, [value, value]];
const el = E('div', {
class: `dl-seg${o.cls ? ` ${o.cls}` : ''}`,
role: 'radiogroup',
'aria-label': o.label ?? null,
'data-value': value,
});
const mark = () =>
el.querySelectorAll<HTMLElement>(':scope > button').forEach((b) => {
const on = b.dataset.v === el.dataset.value;
b.classList.toggle('on', on);
b.setAttribute('aria-checked', on ? 'true' : 'false');
});
for (const [v, t] of options)
el.appendChild(
E(
'button',
{
type: 'button',
role: 'radio',
'data-v': v,
click: () => {
if (v === el.dataset.value) return;
if (o.optimistic !== false) {
el.dataset.value = v;
mark();
}
o.onChange?.(v);
},
},
t,
),
);
mark();
return el;
}
/** dl-chipbtn that toggles (aria-pressed); `onToggle` decides and may return the new state. */
export function chipToggle(
label: Node | string | (Node | string)[],
on: boolean,
onToggle: () => unknown,
attrs: Record<string, unknown> = {},
) {
return E(
'button',
{
type: 'button',
...attrs,
class: `dl-chipbtn${on ? ' on' : ''}${attrs.class ? ` ${attrs.class}` : ''}`,
'aria-pressed': on ? 'true' : 'false',
click: onToggle,
},
label,
);
}
/** Mark a chip toggle on or off in place. */
export function setChip(b: HTMLElement, on: boolean) {
b.classList.toggle('on', on);
b.setAttribute('aria-pressed', on ? 'true' : 'false');
}
export function input(value: string, attrs: Record<string, unknown> = {}): HTMLInputElement {
return E('input', { type: 'text', class: 'cbi-input-text', value, ...attrs }) as HTMLInputElement;
}
+57
View File
@@ -0,0 +1,57 @@
// A right-hand panel over the page (the device drawer). One at a time; closes
// with its button, a click outside, Escape or a navigation.
import { E } from '../e';
import { icon } from '../../shared/icons';
import { onNavigate } from './nav';
export interface Drawer {
close: () => void;
panel: HTMLElement;
}
let current: Drawer | null = null;
export function drawer(title: Node, body: Node, foot: Node | null, onClose: () => void): Drawer {
current?.close();
const panel = E('aside', { class: 'dl-drawer', role: 'dialog', 'aria-modal': 'true' }, [
E('div', { class: 'dl-drawer-head' }, [
title,
E('button', { type: 'button', class: 'dl-drawer-x', 'aria-label': 'Close', click: () => close() }, icon('x')),
]),
E('div', { class: 'dl-drawer-body' }, body),
foot ? E('div', { class: 'dl-drawer-foot' }, foot) : '',
]);
const overlay = E(
'div',
{
class: 'dl-drawer-overlay dl-root',
click: (ev: Event) => {
if (ev.target === overlay) close();
},
},
panel,
);
const onKey = (ev: KeyboardEvent) => {
// LuCI keeps an empty .modal in the page; the body class says whether one is open.
if (ev.key === 'Escape' && !document.body.classList.contains('modal-overlay-active')) close();
};
let closed = false;
const offNav = onNavigate(() => close());
function close() {
if (closed) return;
closed = true;
offNav();
document.removeEventListener('keydown', onKey);
overlay.classList.remove('open');
setTimeout(() => overlay.remove(), 220);
if (current === handle) current = null;
onClose();
}
const handle: Drawer = { close, panel };
document.addEventListener('keydown', onKey);
document.body.appendChild(overlay);
requestAnimationFrame(() => overlay.classList.add('open'));
current = handle;
return handle;
}
+63
View File
@@ -0,0 +1,63 @@
// The clipboard and files: copy, download, pick.
import { E } from '../e';
import { errorText, notify } from './toast';
export async function copyText(text: string, what = 'Copied to clipboard') {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
} else {
const ta = E('textarea', { style: 'position:fixed;opacity:0' }, text) as HTMLTextAreaElement;
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
if (!ok) throw new Error('Copying is blocked here. Select the text and copy it by hand.');
}
notify(what, 'success', 2500);
} catch (e) {
notify(errorText(e), 'error');
}
}
/** Saves a file; pass application/octet-stream for .conf, or Safari appends .txt. */
export function downloadFile(name: string, content: string | Blob, type = 'text/plain') {
const g = globalThis as unknown as { Blob: typeof Blob };
const blob = typeof content === 'string' ? new g.Blob([content], { type }) : content;
const url = URL.createObjectURL(blob);
const a = E('a', { href: url, download: name, style: 'display:none' });
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
a.remove();
}, 1000);
}
/** Read a picked file as text or base64. */
export function pickFile(accept: string, as: 'text' | 'base64'): Promise<{ name: string; data: string } | null> {
return new Promise((resolve) => {
const input = E('input', { type: 'file', accept, style: 'display:none' }) as HTMLInputElement;
// Closing the file picker fires "cancel" (no "change"); without it the caller waits forever.
input.addEventListener('cancel', () => {
input.remove();
resolve(null);
});
input.addEventListener('change', () => {
const f = input.files?.[0];
input.remove();
if (!f) return resolve(null);
const r = new FileReader();
r.onload = () => {
const res = String(r.result ?? '');
resolve({ name: f.name, data: as === 'base64' ? res.replace(/^data:[^,]*,/, '') : res });
};
r.onerror = () => resolve(null);
if (as === 'base64') r.readAsDataURL(f);
else r.readAsText(f);
});
document.body.appendChild(input);
input.click();
});
}
@@ -1,36 +1,11 @@
// Small form pieces shared by Settings and Server: a switch, a text input and
// a labelled setting row (label + help on the left, control on the right).
// Layout pieces: a labelled setting row, a settings card, a titled group, a
// "missing package" row, LuCI's callout and an SVG holder.
import { E } from './e';
import { icon } from '../shared/icons';
export function sw(on: boolean, label: string, onChange?: (v: boolean) => void): HTMLButtonElement {
const b = E(
'button',
{
type: 'button',
role: 'switch',
class: `dl-switch${on ? ' on' : ''}`,
'aria-checked': on ? 'true' : 'false',
'aria-label': label,
click: () => {
const v = !b.classList.contains('on');
b.classList.toggle('on', v);
b.setAttribute('aria-checked', v ? 'true' : 'false');
onChange?.(v);
},
},
E('i'),
) as HTMLButtonElement;
return b;
}
export const isOn = (b: HTMLElement) => b.classList.contains('on');
export function input(value: string, attrs: Record<string, unknown> = {}): HTMLInputElement {
return E('input', { type: 'text', class: 'cbi-input-text', value, ...attrs }) as HTMLInputElement;
}
import type { Child } from '../luci.d';
import { E } from '../e';
import { icon } from '../../shared/icons';
/** Label and help on the left, the control on the right. */
export function row(label: string, control: Node, help?: string): HTMLElement {
return E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-setrow-label' }, label), help ? E('span', { class: 'dl-sub' }, help) : '']),
@@ -60,3 +35,24 @@ export function group(ic: string, title: string, sub: string, items: (Node | str
),
]);
}
/** Something missing, shown where its feature is used: icon tile, title and a line, then its actions. */
export function needRow(ic: string, tone: '' | 'bad' | 'warn', title: string, sub: Child, actions: Child): HTMLElement {
return E('div', { class: `dl-row dl-need-row ${tone}` }, [
tone ? E('span', { class: 'dl-need-ic' }, icon(ic)) : icon(ic),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, sub)]),
actions,
]);
}
export function callout(tone: 'ok' | 'warn' | 'error' | 'info', children: Child): HTMLElement {
const cls = { ok: 'success', warn: 'warning', error: 'error', info: 'notice' }[tone];
return E('div', { class: `alert-message ${cls}` }, children);
}
/** Trusted SVG markup (charts, QR codes) in a div. */
export function svg(markup: string, cls = ''): HTMLElement {
const el = E('div', { class: cls });
el.innerHTML = markup;
return el;
}
+74
View File
@@ -0,0 +1,74 @@
// A small dropdown under its button; closes on pick, outside click, Escape,
// scrolling or navigation. A second click on the same button closes it.
import { E } from '../e';
import { onNavigate } from './nav';
import { run } from './toast';
export interface MenuItem {
label: string;
icon?: Node;
danger?: boolean;
warn?: boolean;
run: () => unknown;
}
type OpenMenu = HTMLElement & { dlAnchor?: HTMLElement; dlClose?: () => void };
export function dropdown(anchor: HTMLElement, items: (MenuItem | null)[]) {
const prev = document.querySelector('.dl-dd') as OpenMenu | null;
if (prev) {
prev.dlClose ? prev.dlClose() : prev.remove();
if (prev.dlAnchor === anchor) return;
}
const menu: OpenMenu = E(
'div',
{ class: 'dl-dd dl-root', role: 'menu' },
items.map((it) =>
it
? E(
'button',
{
type: 'button',
role: 'menuitem',
class: it.danger ? 'danger' : it.warn ? 'warn' : '',
click: () => {
close();
run(it.run);
},
},
[it.icon ?? '', E('span', {}, it.label)],
)
: E('hr'),
),
);
document.body.appendChild(menu);
const r = anchor.getBoundingClientRect();
const w = menu.offsetWidth,
h = menu.offsetHeight;
// Open upwards when the menu would run off the bottom of the screen.
menu.style.top = `${r.bottom + 6 + h > window.innerHeight - 8 && r.top - 6 - h > 8 ? r.top - 6 - h : r.bottom + 6}px`;
menu.style.left = `${Math.max(8, Math.min(r.right - w, window.innerWidth - w - 8))}px`;
const onDoc = (ev: Event) => {
if (!menu.contains(ev.target as Node) && !anchor.contains(ev.target as Node)) close();
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === 'Escape') close();
};
const offNav = onNavigate(close);
menu.dlAnchor = anchor;
menu.dlClose = close;
function close() {
menu.remove();
offNav();
document.removeEventListener('mousedown', onDoc, true);
document.removeEventListener('keydown', onKey, true);
window.removeEventListener('scroll', close, true);
}
setTimeout(() => {
document.addEventListener('mousedown', onDoc, true);
document.addEventListener('keydown', onKey, true);
window.addEventListener('scroll', close, true);
});
(menu.querySelector('button') as HTMLElement | null)?.focus({ preventScroll: true });
}
+65
View File
@@ -0,0 +1,65 @@
// LuCI's modal with Dawnline's body and button row, and a confirm dialog that
// always settles: replacing or closing its modal (another dialog, the
// operation modal, a navigation) answers "no".
import type { Child } from '../luci.d';
import { E } from '../e';
import { onNavigate } from './nav';
/** The answer of the confirm dialog on screen, if any. */
let pending: ((ok: boolean) => void) | null = null;
function settle(ok = false) {
const p = pending;
pending = null;
p?.(ok);
}
export function modal(title: string, body: Child, actions: Child, cls = '') {
settle();
ui.showModal(title, [E('div', { class: `dl-modal ${cls}` }, body), E('div', { class: 'button-row' }, actions)]);
}
export function closeModal() {
settle();
ui.hideModal();
}
/** "Cancel" (or another label) that closes the modal. */
export function cancelButton(label = 'Cancel', danger = false): HTMLElement {
return E(
'button',
{ class: `cbi-button ${danger ? 'cbi-button-negative' : 'cbi-button-neutral'}`, type: 'button', click: closeModal },
label,
);
}
export function confirmDialog(title: string, body: Child, confirmLabel = 'Confirm', danger = false): Promise<boolean> {
return new Promise((resolve) => {
modal(title, body, [
cancelButton(),
' ',
E(
'button',
{
class: `cbi-button ${danger ? 'cbi-button-negative' : 'cbi-button-positive'}`,
type: 'button',
click: () => {
const p = pending;
pending = null;
ui.hideModal();
p?.(true);
},
},
confirmLabel,
),
]);
pending = resolve;
});
}
onNavigate(() => {
if (!pending) return;
settle();
ui.hideModal();
});
+8
View File
@@ -0,0 +1,8 @@
// Outline's same-document router fires `luci-navigate` once the outgoing view
// is torn down. Anything Dawnline puts on <body> (drawer, tooltip, menus,
// pending dialogs) listens for it, or it would outlive its page.
export function onNavigate(fn: () => void): () => void {
document.addEventListener('luci-navigate', fn);
return () => document.removeEventListener('luci-navigate', fn);
}
+56
View File
@@ -0,0 +1,56 @@
// Toasts at the bottom of the screen (above modals) instead of LuCI's banner,
// and the helpers that turn failures into one.
import type { Child } from '../luci.d';
import { E } from '../e';
import { icon } from '../../shared/icons';
export type Tone = 'info' | 'error' | 'warning' | 'success';
/** A small toast; errors stay longer and can be closed. */
export function notify(message: Child, tone: Tone = 'info', timeout = 0) {
let stack = document.querySelector('.dl-toasts') as HTMLElement | null;
if (!stack) {
stack = E('div', { class: 'dl-toasts dl-root', role: 'status', 'aria-live': 'polite' });
document.body.appendChild(stack);
}
const ic = tone === 'error' ? 'x' : tone === 'warning' ? 'alert' : tone === 'success' ? 'check' : null;
const close = () => {
t.classList.remove('show');
setTimeout(() => t.remove(), 200);
};
const t = E('div', { class: `dl-toast ${tone}` }, [
ic ? icon(ic) : '',
E('span', {}, message),
tone === 'error' ? E('button', { type: 'button', 'aria-label': 'Close', click: close }, icon('x')) : '',
]);
stack.appendChild(t);
requestAnimationFrame(() => t.classList.add('show'));
setTimeout(close, timeout || (tone === 'error' ? 8000 : tone === 'warning' ? 5000 : 2600));
}
export function errorText(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
/** Run an action; failures become a toast. Returns undefined on error. */
export async function attempt<T>(fn: () => Promise<T>, ok?: Child): Promise<T | undefined> {
try {
const r = await fn();
if (ok) notify(ok, 'success', 3500);
return r;
} catch (e) {
notify(errorText(e), 'error', 10000);
return undefined;
}
}
/** Call something that may throw or reject without waiting for it; failures become a toast. */
export function run(fn: () => unknown): void {
try {
const r = fn();
if (r && typeof (r as Promise<unknown>).then === 'function') (r as Promise<unknown>).catch((e) => notify(errorText(e), 'error'));
} catch (e) {
notify(errorText(e), 'error');
}
}
+37
View File
@@ -0,0 +1,37 @@
// One floating tooltip that follows the pointer (small charts, meters, round
// buttons). It hides when its anchor leaves the page (a repaint replaced it)
// or the page navigates away, so it never lingers on <body>.
import { E } from '../e';
import { onNavigate } from './nav';
let floating: HTMLElement | null = null;
let anchor: HTMLElement | null = null;
let watch = 0;
export function hideTip() {
if (floating) floating.style.display = 'none';
anchor = null;
clearInterval(watch);
watch = 0;
}
export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
const show = (ev: MouseEvent) => {
floating ??= document.body.appendChild(E('div', { class: 'dl-tip dl-tip-float dl-root' }));
floating.replaceChildren(...content().map((c) => (typeof c === 'string' ? document.createTextNode(c) : c)));
floating.style.display = '';
floating.style.left = `${ev.clientX}px`;
floating.style.top = `${ev.clientY - 10}px`;
anchor = el;
// No mouseleave comes from an element that was removed under the pointer.
watch ||= window.setInterval(() => {
if (!anchor?.isConnected) hideTip();
}, 400);
};
el.addEventListener('mouseenter', show);
el.addEventListener('mousemove', show);
el.addEventListener('mouseleave', hideTip);
}
onNavigate(hideTip);
+79
View File
@@ -0,0 +1,79 @@
// Updater jobs in words: which component a job is about, its versions, its
// timer and what a finished check found. Pure (no DOM, no RPC).
import type { UpdateJob, UpdatesStatus } from '../api';
export const NAME: Record<string, string> = {
app: 'Dawnline',
amneziawg: 'AmneziaWG',
packages: 'System packages',
pkgs: 'System packages',
};
/** "app@0.3.1" → "app"; "check:amneziawg" → "amneziawg"; "check" → "all"; "pkgs:a,b" → "pkgs". */
export function jobComponent(what: string): string {
const w = what.startsWith('check') ? what.slice(6) || 'all' : what;
return w.split(/[:@ ]/)[0];
}
/** The component of a job that is already running (Components follows it). */
export function runningComponent(job: Pick<UpdateJob, 'action' | 'component'>): string {
return jobComponent(job.action === 'check' ? `check:${job.component ?? ''}` : (job.component ?? ''));
}
export function mmss(s: number) {
s = Math.max(0, Math.floor(s));
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
}
export function verText(job: Pick<UpdateJob, 'from' | 'to'> | null, fallback: string) {
if (!job?.from && !job?.to) return fallback;
if (job.from && job.to && job.from !== job.to) return `${job.from} → ${job.to}`;
return job.to ?? job.from ?? fallback;
}
export interface Verdict {
tone: 'acc' | 'ok' | 'warn';
text: string;
/** One component with an update: the version on offer. */
update?: string;
}
/** What a finished check found, for the modal and its toast. */
export function checkVerdict(st: Pick<UpdatesStatus, 'check'>, comp: string): Verdict {
const all = st.check?.components ?? {};
const list = comp === 'all' ? ['app', 'amneziawg', 'packages'] : [comp];
const found: string[] = [];
let update: string | undefined;
for (const k of list) {
const c = all[k];
if (!c) continue;
if (c.error) return { tone: 'warn', text: c.error };
if (k === 'packages' && c.updates) found.push(`${c.updates} system package${c.updates === 1 ? '' : 's'}`);
else if (k !== 'packages' && c.update && c.installed && c.latest) {
found.push(`${NAME[k]} ${c.latest}`);
if (comp !== 'all') update = c.latest;
}
}
if (found.length) return { tone: 'acc', text: `Update available: ${found.join(', ')}`, update };
const one = list.length === 1 ? all[list[0]] : null;
if (one?.status === 'dev') return { tone: 'acc', text: `Installed version is newer than the release (${one.latest})` };
if (one?.note) return { tone: 'warn', text: one.note };
return { tone: 'ok', text: list.length > 1 ? 'Everything is up to date' : 'Latest version is installed' };
}
/**
* Whether a job seen in updates_status is the one this click started: the
* known id, else a job other than the one before the click that is running
* or started at or after `since` (router time taken before starting).
*/
export function isOurJob(
j: Pick<UpdateJob, 'id' | 'state' | 'started'>,
id: string | undefined,
prevId: string | undefined,
since: number,
) {
if (id) return j.id === id;
if (prevId && j.id === prevId) return false;
return j.state === 'running' || (since > 0 && j.started >= since);
}
+94
View File
@@ -0,0 +1,94 @@
// Release notes (GitHub Markdown) as DOM: headings, lists, code, bold, links.
// No raw HTML; links only to http(s).
import { E } from '../e';
/** An address that is safe as a link target: https only (http for markdown links in notes). */
export function safeHref(url: string | null | undefined, allowHttp = false): string | null {
if (!url) return null;
return (allowHttp ? /^https?:\/\//i : /^https:\/\//i).test(url) ? url : null;
}
export function markdown(src: string): Node[] {
const out: Node[] = [];
const inline = (s: string): (Node | string)[] => {
const parts: (Node | string)[] = [];
const re = /(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\((https?:\/\/[^)\s]+)\))|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?])/g;
let last = 0;
for (let m: RegExpExecArray | null; (m = re.exec(s)); ) {
if (m.index > last) parts.push(s.slice(last, m.index));
if (m[1]) parts.push(E('code', {}, m[1].slice(1, -1)));
else if (m[2]) parts.push(E('b', {}, m[2].slice(2, -2)));
else if (m[3]) parts.push(E('a', { href: m[4], target: '_blank', rel: 'noopener' }, m[3].replace(/^\[|\]\(.*$/g, '')));
else if (m[5])
parts.push(E('a', { href: m[5], target: '_blank', rel: 'noopener' }, m[5].replace(/^https?:\/\/(github\.com\/)?/, '')));
last = m.index + m[0].length;
}
if (last < s.length) parts.push(s.slice(last));
return parts;
};
let list: HTMLElement | null = null;
let para: string[] = [];
let fence: string[] | null = null;
const flush = () => {
if (para.length) out.push(E('p', {}, inline(para.join(' '))));
para = [];
list = null;
};
for (const raw of src.replace(/\r/g, '').split('\n')) {
const line = raw.trimEnd();
if (fence) {
if (/^```/.test(line.trim())) {
out.push(E('pre', {}, fence.join('\n')));
fence = null;
} else fence.push(raw);
continue;
}
if (/^```/.test(line.trim())) {
flush();
fence = [];
continue;
}
const h = /^(#{1,6})\s+(.*)$/.exec(line);
const li = /^\s*[-*+]\s+(.*)$/.exec(line) ?? /^\s*\d+[.)]\s+(.*)$/.exec(line);
if (h) {
flush();
out.push(E('h5', {}, inline(h[2])));
} else if (li) {
if (para.length) flush();
if (!list) {
list = E('ul', {});
out.push(list);
}
list.appendChild(E('li', {}, inline(li[1])));
} else if (!line.trim()) flush();
else {
if (list) list = null;
para.push(line.trim());
}
}
if (fence) out.push(E('pre', {}, fence.join('\n')));
flush();
return out;
}
/**
* Release notes as the router shows them: without the "What's new" heading
* (the dialog says so) and without the Install section (it is installed).
*/
export function forRouter(md: string): string {
const out: string[] = [];
let skip = false;
for (const line of md.replace(/\r/g, '').split('\n')) {
const h = /^#{1,6}\s+(.*)$/.exec(line);
if (h) {
skip = /^install\b/i.test(h[1].trim());
if (/^what.s new$/i.test(h[1].trim())) continue;
} else if (/^\*\*Full Changelog\*\*/.test(line)) skip = false;
if (!skip) out.push(line);
}
return out
.join('\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
+37
View File
@@ -0,0 +1,37 @@
// "What's new" for a release: Dawnline by tag, or the AmneziaWG build's release.
import { E } from '../e';
import { api } from '../api';
import { icon } from '../../shared/icons';
import { fmtDay } from '../../shared/format';
import { button } from '../ui/button';
import { cancelButton, modal } from '../ui/modal';
import { copyText } from '../ui/files';
import { errorText } from '../ui/toast';
import { forRouter, markdown, safeHref } from './markdown';
export async function whatsNew(component: 'app' | 'amneziawg', tag: string, title: string, build?: string) {
const body = E('div', { class: 'dl-notes' }, E('p', { class: 'dl-muted dl-loading' }, 'Loading release notes…'));
const meta = E('div', { class: 'dl-op-head' });
let text = '';
modal(
title,
[meta, body],
[button([icon('copy'), ' Copy'], () => copyText(text, 'Release notes copied')), ' ', cancelButton('Close')],
'wide',
);
try {
const r = await api.updatesNotes(component, tag, build ?? '');
text = forRouter(r.body || '');
const href = safeHref(r.url);
dom.content(meta, [
r.published ? E('span', { class: 'dl-pill' }, fmtDay(r.published)) : '',
r.prerelease ? E('span', { class: 'dl-pill warn' }, 'Pre-release') : '',
E('span', { class: 'dl-spacer' }),
href ? E('a', { href, target: '_blank', rel: 'noopener', class: 'dl-linkbtn' }, ['On GitHub ', icon('open')]) : '',
]);
dom.content(body, text.trim() ? markdown(text) : E('p', { class: 'dl-muted' }, 'This release has no notes.'));
} catch (e) {
dom.content(body, E('p', { class: 'dl-muted' }, errorText(e)));
}
}
+235
View File
@@ -0,0 +1,235 @@
// Component operations (check, update, install, roll back) in one modal with
// the updater's live log. Used by Components and wherever a feature installs
// a missing package.
import { E } from '../e';
import { api, type UpdateJob, type UpdatesStatus } from '../api';
import { icon } from '../../shared/icons';
import { button, iconButton } from '../ui/button';
import { cancelButton, closeModal, modal } from '../ui/modal';
import { copyText } from '../ui/files';
import { errorText, notify } from '../ui/toast';
import { NAME, checkVerdict, isOurJob, jobComponent, mmss, runningComponent, verText } from './jobs';
export interface OpOptions {
/** Modal title, e.g. "Updating Dawnline". */
title: string;
/** Shown before the job reports its versions. */
version?: string;
/** After a check that found an update: what the Update button starts. */
onUpdate?: (st: UpdatesStatus) => void;
/** The page refreshes its cards with this. */
onDone?: (st: UpdatesStatus | null) => void;
/** As soon as the job this operation follows is known (its id). */
onJob?: (job: UpdateJob) => void;
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/**
* Start `what` (see updates_run) and follow it in a modal; resolves with the
* finished job (null when it could not start). `follow` attaches to a job
* that is already running instead.
*/
export async function runOperation(what: string | null, o: OpOptions, follow?: UpdateJob): Promise<UpdateJob | null> {
const comp = follow ? runningComponent(follow) : jobComponent(what!);
const isCheck = follow ? follow.action === 'check' : what!.startsWith('check');
const opened = Date.now();
const name = E('b', {}, NAME[comp] ?? (comp === 'all' ? 'All components' : 'Dawnline'));
const ver = E('span', { class: 'dl-pill dl-mono' }, o.version ?? '');
const phase = E('span', { class: 'dl-pill info', hidden: true });
const timer = E('span', {}, '0:00');
const log = E('pre', { class: 'dl-log' }, 'Operation started. Waiting for log output…');
const result = E('div', {});
const actions = E('div', { class: 'dl-op-actions' });
let lines: string[] = [];
const setActions = (nodes: Node[]) => dom.content(actions, nodes);
const closeBtn = (danger = false) => cancelButton('Close', danger);
modal(
o.title,
E('div', { class: 'dl-op' }, [
E('div', { class: 'dl-op-head' }, [
name,
o.version ? ver : '',
phase,
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-faint dl-op-timer' }, [icon('clock'), timer]),
]),
E('div', { class: 'dl-op-loghead' }, [
E('b', {}, 'Operation log'),
iconButton('copy', 'Copy log', () => copyText(lines.join('\n'), 'Log copied')),
]),
log,
result,
]),
[actions],
'wide',
);
setActions([
E(
'button',
{ class: 'cbi-button cbi-button-neutral spinning', type: 'button', disabled: 'disabled' },
isCheck ? 'Checking…' : 'Working…',
),
]);
let job: UpdateJob | null = follow ?? null;
let id = follow?.id;
// The job before the click and the router's clock then: a finished job from
// before must never pass for the one this click starts.
let prevId: string | undefined;
let since = 0;
const known = (j: UpdateJob) => {
if (id === j.id) return;
id = j.id;
o.onJob?.(j);
};
if (follow) o.onJob?.(follow);
else {
try {
const before = await api.updatesStatus().catch(() => null);
prevId = before?.job?.id;
since = before?.now ?? 0;
const r = await api.updatesRun(what!);
if (r.job && r.job.state === 'running' && r.job.id !== prevId) {
job = r.job;
known(r.job);
}
} catch (e) {
lines = [errorText(e)];
log.textContent = lines[0];
dom.content(result, E('div', { class: 'dl-comp-status warn' }, [icon('alert'), E('span', {}, errorText(e))]));
setActions([closeBtn(true)]);
notify(errorText(e), 'error');
return null;
}
}
let st: UpdatesStatus | null = null;
let errors = 0;
// Follow the job: log, phase and timer every second.
for (;;) {
await sleep(1000);
st = await api.updatesStatus().catch(() => null);
if (!st) {
// rpcd restarts during Dawnline's own update: keep waiting a while.
if (++errors > 60) break;
continue;
}
errors = 0;
const j = st.job;
if (!j || !isOurJob(j, id, prevId, since)) {
if (Date.now() - opened > 15000) break;
continue;
}
known(j);
job = j;
if (j.log.length) {
lines = j.log;
const atEnd = log.scrollTop + log.clientHeight >= log.scrollHeight - 8;
log.textContent = lines.join('\n');
if (atEnd) log.scrollTop = log.scrollHeight;
}
ver.textContent = verText(j, o.version ?? '');
if (!ver.isConnected && ver.textContent) name.after(ver);
timer.textContent = mmss((j.finished ?? st.now) - j.started);
if (j.state === 'running') {
phase.hidden = !j.phase;
phase.textContent = j.phase;
continue;
}
break;
}
log.scrollTop = log.scrollHeight;
phase.hidden = false;
if (!job || job.state === 'running') {
phase.className = 'dl-pill warn';
phase.textContent = 'No answer';
dom.content(
result,
E('div', { class: 'dl-comp-status warn' }, [
icon('alert'),
E('span', {}, 'The router stopped answering. The job may still finish: reopen Components in a minute.'),
]),
);
setActions([closeBtn()]);
o.onDone?.(st);
return job;
}
if (job.state === 'failed') {
phase.className = 'dl-pill bad';
phase.textContent = 'Failed';
dom.content(
result,
E('div', { class: 'dl-comp-status bad' }, [
icon('x'),
E('span', {}, [E('b', {}, job.error ?? 'Operation failed'), isCheck ? '' : '. Nothing else was changed.']),
]),
);
setActions([button('Copy log', () => copyText(lines.join('\n'), 'Log copied')), closeBtn(true)]);
notify(`${NAME[comp] ?? 'Update'}: ${job.error ?? 'failed'}`, 'error');
o.onDone?.(st);
return job;
}
phase.className = 'dl-pill ok';
phase.textContent = 'Finished';
if (isCheck && st) {
const v = checkVerdict(st, comp);
dom.content(
result,
E('div', { class: `dl-comp-status ${v.tone}` }, [
icon(v.tone === 'ok' ? 'check' : v.tone === 'warn' ? 'alert' : 'download'),
E('span', {}, v.text),
]),
);
notify(v.text, v.tone === 'warn' ? 'warning' : 'success');
o.onDone?.(st);
if (v.update && o.onUpdate) {
const s = st;
setActions([closeBtn(), button(`Update to ${v.update}`, () => o.onUpdate!(s), 'positive')]);
} else {
setActions([closeBtn()]);
// Nothing to do: the modal goes away on its own (as in the check toast).
if (v.tone === 'ok') setTimeout(() => result.isConnected && closeModal(), 1200);
}
return job;
}
// Dawnline itself: rpcd and the service restart; reload the page once they answer with the new version.
if (comp === 'app' && job.to) {
const target = job.to;
const msg = E('span', {}, 'Waiting for the router to restart its services…');
dom.content(
result,
E('div', { class: 'dl-comp-status ok' }, [icon('check'), E('span', {}, [E('b', {}, `Dawnline ${target} is installed. `), msg])]),
);
const reload = () => {
ui.menu?.flushCache();
location.reload();
};
setActions([closeBtn(), button('Reload now', reload, 'positive')]);
notify(`Dawnline updated to ${target}`, 'success', 6000);
for (let n = 1; n <= 30; n++) {
msg.textContent = `Waiting for the router to restart its services (${n} of 30)…`;
await sleep(1500);
const s = await api.updatesStatus().catch(() => null);
if (s?.version === target) {
msg.textContent = 'Services are back. Reloading…';
setTimeout(reload, 800);
return job;
}
}
msg.textContent = 'Services restarted. Reload the page to use the new version.';
return job;
}
const done =
comp === 'pkgs'
? `Updated ${[...((job.result?.pkgs?.updated as string[]) ?? []), ...((job.result?.pkgs?.installed as string[]) ?? [])].join(', ') || 'system packages'}`
: comp === 'amneziawg'
? `AmneziaWG${job.to ? ` ${job.to}` : ''} is installed`
: 'Operation completed';
dom.content(result, E('div', { class: 'dl-comp-status ok' }, [icon('check'), E('span', {}, done)]));
setActions([closeBtn()]);
notify(done, 'success');
o.onDone?.(st);
return job;
}
+37
View File
@@ -0,0 +1,37 @@
// Access choice cards (Add person): internet, home or both.
import type { Person } from '../../shared/types';
import { E } from '../e';
import { icon } from '../../shared/icons';
import { ACCESS_LABEL } from '../../shared/format';
/** Returns the element and a getter. */
export function accessPicker(initial: Person['access'], onChange?: (v: Person['access']) => void) {
let value = initial;
const opts: { v: Person['access']; ic: string; text: string }[] = [
{ 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.' },
];
const el = E(
'div',
{ class: 'dl-choices' },
opts.map((o) =>
E(
'button',
{
type: 'button',
class: `dl-choice${o.v === value ? ' selected' : ''}`,
'data-v': o.v,
click: () => {
value = o.v;
el.querySelectorAll('.dl-choice').forEach((c) => c.classList.toggle('selected', (c as HTMLElement).dataset.v === o.v));
onChange?.(o.v);
},
},
[E('span', { class: 'dl-choice-title' }, [icon(o.ic), ACCESS_LABEL[o.v]]), E('span', { class: 'dl-choice-text' }, o.text)],
),
),
);
return { el, get: () => value };
}
+87
View File
@@ -0,0 +1,87 @@
// Health checks outside the checklist: the button that fixes a check (shared
// with Diagnostics → Health) and notices for the checks that failed, as the
// server Overview shows them.
import type { HealthCheck } from '../../shared/types';
import { E } from '../e';
import { api, type Health, type Needs } from '../api';
import { installFeature } from '../pkgs';
import { button, type ButtonKind } from '../ui/button';
import { confirmDialog } from '../ui/modal';
import { attempt } from '../ui/toast';
import { needRow } from '../ui/layout';
const FIX_LABEL: Record<string, string> = {
apply: 'Repair',
sync: 'Reload devices',
restart: 'Restart service',
netrestart: 'Restart network',
updates: 'Open Components',
};
/** Run a backend fix (a network restart asks first); the checks again, or null. */
export async function runFix(fix: string): Promise<Health | null> {
if (
fix === 'netrestart' &&
!(await confirmDialog('Restart the network?', 'Every interface restarts. Connections drop for a few seconds.', 'Restart network'))
)
return null;
return (await attempt(() => api.healthFix(fix), 'Done')) ?? null;
}
/**
* The button for a check's fix, or '' when it has none. `run` performs a
* backend fix; `refresh` runs the checks again after an install.
*/
export function fixAction(c: HealthCheck, run: (fix: string) => void, refresh: () => void, kind: ButtonKind = 'action'): Node | string {
const fix = c.fix;
if (!fix) return '';
// install:awg installs AmneziaWG itself (the build for this firmware), the rest come from the feeds.
if (fix.startsWith('install:')) return button('Install', () => installFeature(fix.slice(8) as keyof Needs, refresh), kind);
if (fix === 'updates')
return E('a', { class: `cbi-button cbi-button-${kind}`, href: L.url('admin/network/dawnline/updates') }, FIX_LABEL.updates);
return button(FIX_LABEL[fix] ?? 'Fix', () => run(fix), kind);
}
/** The icon tile of a check's notice, by what it is about. */
function checkIcon(id: string): string {
if (/^(awg|up_|peers_|fw_|reply_|port_|subnet_)/.test(id)) return 'shield';
if (/^(portal|cert)/.test(id)) return 'link';
if (/^(ep_|home_|resolver)/.test(id)) return 'globe';
if (id === 'clock') return 'clock';
if (id === 'agent') return 'activity';
if (id === 'nft') return 'lock';
return 'alert';
}
/**
* The failed checks as notices (errors first, at most `max`), with their fix
* and a link to Diagnostics for the rest; '' when everything passed.
*/
export function healthNotices(checks: HealthCheck[], run: (fix: string) => void, refresh: () => void, max = 3): Node | string {
const bad = checks
.filter((c) => c.status === 'error' || c.status === 'warn')
.sort((a, b) => (a.status === b.status ? 0 : a.status === 'error' ? -1 : 1));
if (!bad.length) return '';
const rest = bad.length - max;
return E('div', { class: 'dl-list dl-notices' }, [
...bad
.slice(0, max)
.map((c) =>
needRow(
checkIcon(c.id),
c.status === 'error' ? 'bad' : 'warn',
c.problem ?? c.title,
c.detail,
fixAction(c, run, refresh, c.status === 'error' ? 'positive' : 'neutral'),
),
),
rest > 0
? E('a', { class: 'dl-row dl-notices-more', href: L.url('admin/network/dawnline/diagnostics') }, [
`${rest} more in Diagnostics`,
E('span', { class: 'dl-spacer' }),
'→',
])
: '',
]);
}
+33
View File
@@ -0,0 +1,33 @@
// Tiny daily sparkline (oldest first, the last bar is today) with per-day tooltips.
import { E } from '../e';
import { addDays, bytes, isoDay, parseDay } from '../../shared/format';
import { attachTip } from '../ui/tooltip';
/** `today` is the router's day (YYYY-MM-DD), so the labels follow its calendar. */
export function spark(values: number[], width = 120, height = 26, today = isoDay(new Date())): HTMLElement {
const max = Math.max(1, ...values);
const el = E('div', { class: 'dl-spark' });
el.style.width = `${width}px`;
el.style.height = `${height}px`;
values.forEach((v, i) => {
const b = E('i');
b.style.height = `${Math.max(6, (v / max) * 100)}%`;
if (!v) b.classList.add('zero');
const back = values.length - 1 - i;
attachTip(b, () => [
E(
'div',
{ class: 'dl-tip-title' },
back === 0
? 'Today'
: back === 1
? 'Yesterday'
: parseDay(addDays(today, -back)).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }),
),
E('div', { class: 'dl-muted' }, bytes(v)),
]);
el.appendChild(b);
});
return el;
}
+114
View File
@@ -0,0 +1,114 @@
// Bento tiles shared by the server Overview and the person page: speed now
// and the last 30 days.
import type { DayUsage } from '../../shared/types';
import { E } from '../e';
import { bits, bytes, parseDay } from '../../shared/format';
import { attachTip } from '../ui/tooltip';
import { svg } from '../ui/layout';
const dayLabel = (day: string) => parseDay(day).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
/** Throughput over the last 15 minutes plus today's total. */
export function speedTile(rate: [number, number, number][], now: number, today: [number, number]): 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
? 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'), 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}`]),
E('span', { class: 'dl-speed-val' }, bits(v)),
]);
if (pts.length > 1)
attachTip(chart, () => {
const p = pts[pts.length - 1];
return [
E('div', { class: 'dl-tip-title' }, new Date(p[0] * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })),
E('div', {}, `↓ ${bits(p[2])} · ↑ ${bits(p[1])}`),
];
});
return E('div', { class: 'dl-bento-tile' }, [
E('div', { class: 'dl-bento-head' }, [
E('span', { class: 'dl-metric-label' }, 'Speed now'),
E('span', { class: 'dl-sub' }, 'last 15 min'),
]),
E('div', { class: 'dl-speed-cols' }, [col('Download', '↓', 'dl-dn', down), col('Upload', '↑', 'dl-up', up)]),
chart,
E('div', { class: 'dl-speed-today' }, [
E('span', {}, ['Today ', E('b', {}, bytes(rx + tx))]),
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]),
]),
]);
}
/** Daily traffic for the last 30 days, today on the right. */
export function daysTile(series: DayUsage[], note: string): HTMLElement {
const days = series.slice(-30);
const vals = days.map((d) => d.rx + d.tx);
const max = Math.max(1, ...vals);
const total = vals.reduce((a, v) => a + v, 0);
const peakI = vals.reduce((a, v, i) => (v > vals[a] ? i : a), 0);
const bars = E(
'div',
{ class: 'dl-bento-bars' },
days.map((d, i) => {
const v = vals[i];
const bar = E('i', { class: i === days.length - 1 ? 'hi' : '', style: `height:${Math.max(4, (v / max) * 100)}%` });
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `Today · ${dayLabel(d.day)}` : dayLabel(d.day)),
E('div', {}, bytes(v)),
E('div', { class: 'dl-muted dl-mono' }, `↓ ${bytes(d.tx)} ↑ ${bytes(d.rx)}`),
]);
return bar;
}),
);
return E('div', { class: 'dl-bento-tile month' }, [
E('div', { class: 'dl-bento-head' }, [
E('span', {}, [E('span', { class: 'dl-metric-label' }, 'Last 30 days'), E('b', { class: 'dl-bento-total' }, bytes(total))]),
vals[peakI] > 0 ? E('span', { class: 'dl-sub' }, `peak ${bytes(vals[peakI])} · ${dayLabel(days[peakI].day)}`) : '',
]),
days.length ? bars : E('p', { class: 'dl-muted' }, 'No traffic yet.'),
E('div', { class: 'dl-bento-head' }, [
E('span', { class: 'dl-sub' }, days.length ? dayLabel(days[0].day) : ''),
E('span', { class: 'dl-sub' }, note),
E('span', { class: 'dl-sub' }, 'today'),
]),
]);
}
/** Daily traffic of one device over the last 30 days, today on the right (person page device cards). */
export function dayBars(series: DayUsage[]): HTMLElement {
const days = series.slice(-30);
const vals = days.map((x) => x.rx + x.tx);
const max = Math.max(1, ...vals);
return E(
'div',
{ class: 'dl-dbars' },
days.map((x, i) => {
const bar = E('i', { class: `${vals[i] ? '' : 'zero'}${i === days.length - 1 ? ' hi' : ''}` });
bar.style.height = `${Math.max(8, (vals[i] / max) * 100)}%`;
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `Today · ${dayLabel(x.day)}` : dayLabel(x.day)),
E('div', {}, bytes(vals[i])),
]);
return bar;
}),
);
}
+87 -42
View File
@@ -5,7 +5,20 @@
// devices on the left, access on the right.
import type { ClientConfig, Device, Kind, Person } from '../shared/types';
import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, byDeviceState, bytes, date, daysLeft, initials } from '../shared/format';
import {
ACCESS_LABEL,
KIND_LABEL,
STATE_LABEL,
addDays,
ago,
byDeviceState,
bytes,
date,
daysLeft,
initials,
isoDay,
parseDay,
} from '../shared/format';
import { iconSvg } from '../shared/icons';
import { qrSvg } from '../shared/qr';
import { vpnKey } from '../shared/vpnkey';
@@ -20,8 +33,13 @@ interface State {
can_add: boolean;
kinds: Kind[];
version: string;
/** The router's day (YYYY-MM-DD) when it sends one; the browser's otherwise. */
today?: string;
}
/** Today on the router, for days left and chart labels. */
const today = () => state?.today ?? isoDay(new Date());
type Attrs = Record<string, string | number | boolean | EventListener | null | undefined>;
type Kid = Node | string | null | undefined | false | Kid[];
@@ -109,8 +127,9 @@ async function copy(text: string, what = 'Copied') {
const ta = h('textarea', { class: 'offscreen' }, text) as HTMLTextAreaElement;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
const ok = document.execCommand('copy');
ta.remove();
if (!ok) return toast('Copying is blocked here. Select the text and copy it by hand.', true);
}
toast(what);
}
@@ -148,9 +167,12 @@ function spark(values: number[]): HTMLElement {
const b = h('i', { class: v ? '' : 'zero' });
b.style.height = `${Math.max(8, (v / max) * 100)}%`;
const back = values.length - 1 - i;
const d = new Date(Date.now() - back * 86400000);
tip(b, () => [
back === 0 ? 'Today' : back === 1 ? 'Yesterday' : d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }),
back === 0
? 'Today'
: back === 1
? 'Yesterday'
: parseDay(addDays(today(), -back)).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }),
bytes(v),
]);
el.appendChild(b);
@@ -158,6 +180,17 @@ function spark(values: number[]): HTMLElement {
return el;
}
/** Run a confirmed action once: its button stays disabled until the router answers. */
async function once(btn: HTMLButtonElement, fn: () => Promise<void>) {
if (btn.disabled) return;
btn.disabled = true;
try {
await fn();
} finally {
btn.disabled = false;
}
}
/* ---------- sheets (bottom sheet on phones, dialog on desktop) ---------- */
let sheetEl: HTMLElement | null = null;
@@ -229,8 +262,10 @@ document.addEventListener('click', (e) => {
if (menuEl && !menuEl.contains(e.target as Node)) closeMenu();
});
function menu(anchor: HTMLElement, items: ({ label: string; icon: string; danger?: boolean; run: () => unknown } | null)[]) {
function menu(anchor: HTMLElement, all: ({ label: string; icon: string; danger?: boolean; run: () => unknown } | null)[]) {
closeMenu();
// Separators only between items.
const items = all.filter((it, i) => it || (i > 0 && all[i - 1] && all.slice(i + 1).some(Boolean)));
const m = h(
'div',
{ class: 'menu', role: 'menu' },
@@ -313,7 +348,7 @@ function accessCard(st: State): HTMLElement {
const bar = h('div', { class: `meter${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` }, h('i'));
(bar.firstChild as HTMLElement).style.width = `${pct}%`;
if (p.quota_limit) tip(bar, () => [`${pct.toFixed(1)}% used`, `${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`]);
const left = daysLeft(p.expires);
const left = daysLeft(p.expires, today());
const slots = h('div', { class: 'slots' });
// Devices the admin added over the limit get their own orange slots after the allowed ones.
for (let i = 0; i < Math.max(p.device_limit, p.devices.length); i++)
@@ -481,9 +516,14 @@ function deviceCard(d: Device, st: State): HTMLElement {
null,
]
: []),
{ label: 'Rename', icon: 'edit', run: () => rename(d) },
...(d.disabled ? [] : [{ label: 'New keys', icon: 'reset', run: () => rotateKeys(d, st) }]),
{ label: 'Remove', icon: 'trash', danger: true, run: () => removeDevice(d) },
// A device the admin turned off can't be renamed, rekeyed or removed here (the router refuses).
...(d.disabled
? []
: [
{ label: 'Rename', icon: 'edit', run: () => rename(d) },
{ label: 'New keys', icon: 'reset', run: () => rotateKeys(d, st) },
{ label: 'Remove', icon: 'trash', danger: true, run: () => removeDevice(d) },
]),
]);
});
const week = d.spark.reduce((a, b) => a + b, 0);
@@ -535,7 +575,7 @@ function deviceCard(d: Device, st: State): HTMLElement {
function main(st: State) {
const p = st.person;
const left = daysLeft(p.expires);
const left = daysLeft(p.expires, today());
const notice =
p.state !== 'active'
? h(
@@ -814,6 +854,7 @@ async function connect(d: Device, initial?: 'app' | 'qr' | 'key' | 'file', cfgIn
function rename(d: Device) {
const name = h('input', { type: 'text', value: d.name, maxlength: 48, 'aria-label': 'Device name' }) as HTMLInputElement;
const save = h('button', { class: 'btn primary block', type: 'submit' }, 'Save') as HTMLButtonElement;
sheet(
`Rename ${d.name}`,
null,
@@ -821,21 +862,23 @@ function rename(d: Device) {
'form',
{
class: 'stack gap',
onsubmit: async (e: Event) => {
onsubmit: (e: Event) => {
e.preventDefault();
try {
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'rename', name: name.value });
state = r.state;
closeSheet();
main(state);
toast('Renamed');
} catch (er) {
toast((er as Error).message, true);
}
void once(save, async () => {
try {
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'rename', name: name.value });
state = r.state;
closeSheet();
main(state);
toast('Renamed');
} catch (er) {
toast((er as Error).message, true);
}
});
},
},
name,
h('button', { class: 'btn primary block', type: 'submit' }, 'Save'),
save,
),
);
setTimeout(() => name.select(), 50);
@@ -862,16 +905,17 @@ function rotateKeys(d: Device, st: State) {
'button',
{
class: 'btn primary block',
onclick: async () => {
try {
const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'rotate' });
state = r.state;
main(state);
connect(d, undefined, r.config);
} catch (er) {
toast((er as Error).message, true);
}
},
onclick: (ev: Event) =>
once(ev.currentTarget as HTMLButtonElement, async () => {
try {
const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'rotate' });
state = r.state;
main(state);
await connect(d, undefined, r.config);
} catch (er) {
toast((er as Error).message, true);
}
}),
},
'New keys',
),
@@ -892,17 +936,18 @@ function removeDevice(d: Device) {
'button',
{
class: 'btn danger-solid block',
onclick: async () => {
try {
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'delete' });
state = r.state;
closeSheet();
main(state);
toast('Device removed');
} catch (er) {
toast((er as Error).message, true);
}
},
onclick: (ev: Event) =>
once(ev.currentTarget as HTMLButtonElement, async () => {
try {
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'delete' });
state = r.state;
closeSheet();
main(state);
toast('Device removed');
} catch (er) {
toast((er as Error).message, true);
}
}),
},
'Remove',
),
-26
View File
@@ -1,26 +0,0 @@
// Tiny SVG bar chart for daily traffic (download stacked over upload).
import type { DayUsage } from './types';
import { bytes } from './format';
export function trafficChart(series: DayUsage[], height = 120): string {
const w = 600;
const pad = 2;
const n = Math.max(series.length, 1);
const bw = w / n;
const max = Math.max(1, ...series.map((d) => d.rx + d.tx));
let bars = '';
series.forEach((d, i) => {
const x = i * bw + pad / 2;
// From the person's point of view: router tx = download, rx = upload.
const hDown = (d.tx / max) * (height - 4);
const hUp = (d.rx / max) * (height - 4);
const title = `${d.day}: ↓ ${bytes(d.tx)} · ↑ ${bytes(d.rx)}`;
bars +=
`<g><title>${title}</title>` +
`<rect x="${x.toFixed(1)}" y="${(height - hDown - hUp).toFixed(1)}" width="${(bw - pad).toFixed(1)}" height="${hDown.toFixed(1)}" rx="1.5" class="dl-bar-down"/>` +
`<rect x="${x.toFixed(1)}" y="${(height - hUp).toFixed(1)}" width="${(bw - pad).toFixed(1)}" height="${hUp.toFixed(1)}" rx="1.5" class="dl-bar-up"/>` +
`<rect x="${(i * bw).toFixed(1)}" y="0" width="${bw.toFixed(1)}" height="${height}" fill="transparent"/></g>`;
});
return `<svg class="dl-chart" viewBox="0 0 ${w} ${height}" preserveAspectRatio="none" role="img" aria-label="Traffic per day">${bars}</svg>`;
}
+81 -9
View File
@@ -51,18 +51,90 @@ export function clock(ts: number): string {
return sameDay ? t : `${d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })} ${t}`;
}
export function date(s: string): string {
if (!s) return '';
const [y, m, d] = s.split('-').map(Number);
return new Date(y, m - 1, d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
/* ---------- days (YYYY-MM-DD, the router's calendar) ---------- */
/** A Date as YYYY-MM-DD in local time. */
export function isoDay(d: Date): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
/** Whole days until the end of the given YYYY-MM-DD (negative when past). */
export function daysLeft(s: string, now = Date.now()): number | null {
if (!s) return null;
/** YYYY-MM-DD as a local Date at noon: never shifted to another day by the time zone. */
export function parseDay(s: string): Date {
const [y, m, d] = s.split('-').map(Number);
const end = new Date(y, m - 1, d, 23, 59, 59).getTime();
return Math.ceil((end - now) / 86400000);
return new Date(y, (m || 1) - 1, d || 1, 12);
}
/** "1 Oct 2026". A YYYY-MM-DD is a calendar day; other strings and Dates are moments. */
export function fmtDay(d: Date | string): string {
const v = typeof d === 'string' ? (/^\d{4}-\d{2}-\d{2}$/.test(d) ? parseDay(d) : new Date(d)) : d;
return v.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}
export function date(s: string): string {
return s ? fmtDay(s) : '';
}
/** Whole days from `b` to `a` (both YYYY-MM-DD); negative when `a` is earlier. */
export function dayDiff(a: string, b: string): number {
const utc = (s: string) => {
const [y, m, d] = s.split('-').map(Number);
return Date.UTC(y, m - 1, d);
};
return Math.round((utc(a) - utc(b)) / 86400000);
}
export function addDays(day: string, n: number): string {
const d = parseDay(day);
d.setDate(d.getDate() + n);
return isoDay(d);
}
/** Months later (or earlier), the day clamped to the month's end: 31 Jan + 1 month = 28 or 29 Feb, not 3 Mar. */
export function addMonthsClamped(day: string, n: number): string {
const [y, m, d] = day.split('-').map(Number);
const t = new Date(y, m - 1 + n, 1, 12);
const last = new Date(t.getFullYear(), t.getMonth() + 1, 0).getDate();
t.setDate(Math.min(d, last));
return isoDay(t);
}
/** Today on the router: the last day of a router series, else the browser's. */
export function todayOf(series: { day: string }[] | undefined): string {
return series?.length ? series[series.length - 1].day : isoDay(new Date());
}
export type DateStep = 'day' | 'week' | 'month' | 'year' | 'custom';
/** Move an end date by n steps (negative shortens). An empty date counts from `today`. */
export function shiftDay(cur: string, step: DateStep, n: number, today: string, customDays = 30): string {
const from = cur || today;
if (step === 'day') return addDays(from, n);
if (step === 'week') return addDays(from, 7 * n);
if (step === 'month') return addMonthsClamped(from, n);
if (step === 'year') return addMonthsClamped(from, 12 * n);
return addDays(from, customDays * n);
}
/**
* Days of access left for an end date (YYYY-MM-DD), counting today: 1 on the
* last day, negative once it has passed, null without one. `today` is the
* router's day; a number (ms) is a moment in the browser's zone.
*/
export function daysLeft(s: string, today: string | number = Date.now()): number | null {
if (!s) return null;
const t = typeof today === 'number' ? isoDay(new Date(today)) : today;
const diff = dayDiff(s, t);
return diff >= 0 ? diff + 1 : diff;
}
/** "1 event", "2,000 events". */
export function plural(n: number, one: string, many = `${one}s`): string {
return `${n.toLocaleString('en-GB')} ${n === 1 ? one : many}`;
}
/** Small sizes on flash and in memory: B, KB, MB. */
export function kb(n: number): string {
return n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB` : `${(n / 1048576).toFixed(1)} MB`;
}
export const ACCESS_LABEL: Record<Access, string> = {
+26 -8
View File
@@ -54,11 +54,9 @@ export interface Person {
devices: Device[];
/** Throughput, one point a minute (last 15): [ts, rx, tx] in bytes/s (rx = from devices); admin only. */
rate?: [number, number, number][];
// admin only
code?: string;
link?: string | null;
/** Every link to the same portal (main first), one per address; admin only. */
links?: string[];
// admin only (the personal link itself comes from person_links, not the status)
/** A personal link exists (the portal is on); admin only. */
has_link?: boolean;
note?: string;
services?: string[];
/** Home networks (interfaces) this person reaches; empty = all; admin only. */
@@ -82,6 +80,10 @@ export interface Circle {
export interface Server {
id: string;
name: string;
/** The tunnel core that serves it (see admin/cores); AmneziaWG when absent. */
core?: string;
/** Why the tunnel can't run: its interface name is taken by a network section Dawnline didn't make. */
blocked?: string | null;
ifname: string;
port: number;
subnet: string;
@@ -167,6 +169,17 @@ export interface AwgCaps {
v3: boolean;
}
/** Whether AmneziaWG can run here: tools and kernel module installed, the module loaded, netifd's proto handler present. */
export interface AwgState {
tools: boolean;
kmod: boolean;
loaded: boolean;
handler: boolean;
/** Packages still to install (amneziawg-tools, kmod-amneziawg). */
missing: string[];
ok: boolean;
}
export interface Status {
geo: Geo;
version: string;
@@ -175,9 +188,8 @@ export interface Status {
settings: {
portal_enabled: boolean;
portal_port: number;
/** The port in personal links (443 when the portal also answers there). */
/** The port in personal links (the portal's own). */
portal_public_port?: number;
portal_443?: boolean;
portal_host: string;
paused_all: boolean;
default_device_limit: number;
@@ -195,6 +207,8 @@ export interface Status {
events: LogEvent[];
/** What the installed AmneziaWG supports: v2 (1.5/2.0 parameters), v3 (3.1). */
awg: AwgCaps;
/** Absent from routers that run an older backend: treat as fine. */
awg_state?: AwgState;
like_home: { active: boolean; dev?: string; address?: string; bridged?: boolean; off?: boolean; error?: string };
}
@@ -213,7 +227,7 @@ export interface AmneziaFields {
obfuscation: Record<string, string>;
}
export interface ClientConfig {
export interface AwgConfig {
name: string;
person: string;
server: string;
@@ -223,10 +237,14 @@ export interface ClientConfig {
amnezia: AmneziaFields;
}
export type ClientConfig = AwgConfig;
export interface HealthCheck {
id: string;
title: string;
status: 'ok' | 'warn' | 'error' | 'skip';
detail: string;
fix: string | null;
/** A failed check in words ("Clock isn't set"), for notices; null when it passed. */
problem?: string | null;
}
+64
View File
@@ -0,0 +1,64 @@
import { beforeAll, describe, expect, it } from 'vitest';
import { installFakeDom, text } from './fakedom';
import { csvCell, toCsv } from '../src/admin/events/csv';
import { categoryOf, eventBy, isProblem } from '../src/admin/events/model';
import { eventText } from '../src/admin/events/render';
import type { LogEvent, Person } from '../src/shared/types';
beforeAll(installFakeDom);
describe('csv', () => {
it('quotes and defuses formulas', () => {
expect(csvCell('plain')).toBe('plain');
expect(csvCell('a,b')).toBe('"a,b"');
expect(csvCell('say "hi"')).toBe('"say ""hi"""');
expect(csvCell('line\r\nbreak')).toBe('"line\r\nbreak"');
expect(csvCell('=HYPERLINK("x")')).toBe(`"'=HYPERLINK(""x"")"`);
expect(csvCell('+1')).toBe("'+1");
expect(csvCell('-1')).toBe("'-1");
expect(csvCell('@SUM(A1)')).toBe("'@SUM(A1)");
expect(csvCell('\tx')).toBe("'\tx");
expect(csvCell(null)).toBe('');
expect(csvCell(5)).toBe('5');
});
it('builds a table', () => {
expect(toCsv(['a', 'b'] as const, [{ a: 1, b: 'x,y' }])).toBe('a,b\n1,"x,y"');
});
});
describe('events', () => {
const people = [{ id: 'p1', name: 'Myata', devices: [{ id: 'd1', name: 'Phone' }] }] as unknown as Person[];
const ev = (e: Partial<LogEvent>) => ({ ts: 1, type: 'connect', ...e }) as LogEvent;
it('knows who did it', () => {
expect(eventBy(ev({ type: 'person_added' }))).toBe('admin');
expect(eventBy(ev({ type: 'device_added', detail: 'Phone (portal)' }))).toBe('portal');
expect(eventBy(ev({ type: 'connect' }))).toBeNull();
expect(eventBy(ev({ type: 'connect', by: 'admin' }))).toBe('admin');
});
it('sorts events into categories and problems', () => {
expect(categoryOf('roam')).toBe('connections');
expect(categoryOf('portal_blocked')).toBe('problems');
expect(categoryOf('something_new')).toBe('problems');
expect(isProblem({ ts: 1, sys: { ts: 1, src: 'awg', level: 'down', msg: '' } })).toBe(true);
expect(isProblem({ ts: 1, ev: ev({ type: 'connect' }) })).toBe(false);
});
it('says what happened', () => {
const st = { people };
expect(text(eventText(st, ev({ person: 'p1', device: 'd1', detail: '1.2.3.4', where: 'Berlin' })))).toBe(
'Device Myata · Phone connected from 1.2.3.4 · Berlin',
);
expect(text(eventText(st, ev({ type: 'device_added', by: 'admin', person: 'p1', detail: 'Laptop' })))).toBe(
'You added device Laptop for Myata',
);
expect(text(eventText(st, ev({ type: 'device_changed', by: 'admin', person: 'p1', device: 'd1', detail: 'renamed from Old' })))).toBe(
'You renamed device Phone of Myata · was Old',
);
// Removed since: the name from the time of the event.
expect(text(eventText(st, ev({ type: 'disconnect', person: 'gone', pname: 'Anna', dname: 'Tablet', device: 'x' })))).toBe(
'Device Anna · Tablet went offline',
);
expect(
text(eventText(st, ev({ type: 'roam', person: 'p1', device: 'd1', detail: '10.0.0.2 → 5.6.7.8', hosts: { '10.0.0.2': 'nas' } }))),
).toBe('Device Myata · Phone changed network nas (10.0.0.2) → 5.6.7.8');
});
});
+30
View File
@@ -0,0 +1,30 @@
// Just enough of LuCI's E() and Node for modules that build elements, in Node.
export class FakeNode {}
export class El extends FakeNode {
children: (El | string)[] = [];
constructor(
public tag: string,
public attrs: Record<string, unknown> = {},
children: (El | string)[] = [],
) {
super();
this.children = [...children];
}
appendChild<T extends El | string>(c: T): T {
this.children.push(c);
return c;
}
get textContent(): string {
return this.children.map((c) => (typeof c === 'string' ? c : c.textContent)).join('');
}
}
export const text = (nodes: unknown[]) => nodes.map((n) => (typeof n === 'string' ? n : (n as El).textContent)).join('');
export function installFakeDom() {
const g = globalThis as unknown as Record<string, unknown>;
g.Node = FakeNode;
g.window = { E: (tag: string, attrs: Record<string, unknown>, children: (El | string)[]) => new El(tag, attrs, children) };
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from 'vitest';
import { addDays, addMonthsClamped, date, dayDiff, daysLeft, fmtDay, kb, plural, shiftDay, todayOf } from '../src/shared/format';
describe('months', () => {
it('clamps the day to the end of the month', () => {
expect(addMonthsClamped('2026-01-31', 1)).toBe('2026-02-28');
expect(addMonthsClamped('2024-01-31', 1)).toBe('2024-02-29');
expect(addMonthsClamped('2026-03-31', -1)).toBe('2026-02-28');
expect(addMonthsClamped('2026-08-31', 1)).toBe('2026-09-30');
expect(addMonthsClamped('2026-10-15', 3)).toBe('2027-01-15');
expect(addMonthsClamped('2024-02-29', 12)).toBe('2025-02-28');
});
it('shifts an end date by steps, from today when there is none', () => {
expect(shiftDay('2026-01-31', 'month', 1, '2026-01-01')).toBe('2026-02-28');
expect(shiftDay('', 'week', 1, '2026-10-16')).toBe('2026-10-23');
expect(shiftDay('2026-12-31', 'day', 1, '2026-10-16')).toBe('2027-01-01');
expect(shiftDay('2024-02-29', 'year', 1, '2026-10-16')).toBe('2025-02-28');
expect(shiftDay('2026-10-01', 'custom', -1, '2026-10-16', 30)).toBe('2026-09-01');
});
});
describe('router days', () => {
it('counts days between calendar days, across DST changes', () => {
expect(dayDiff('2026-10-20', '2026-10-14')).toBe(6);
expect(dayDiff('2026-03-30', '2026-03-28')).toBe(2);
expect(addDays('2026-10-25', 1)).toBe('2026-10-26');
});
it('counts days left against the router day', () => {
expect(daysLeft('2026-10-14', '2026-10-14')).toBe(1);
expect(daysLeft('2026-10-20', '2026-10-14')).toBe(7);
expect(daysLeft('2026-10-13', '2026-10-14')).toBe(-1);
expect(daysLeft('', '2026-10-14')).toBeNull();
});
it('takes today from a series', () => {
expect(todayOf([{ day: '2026-10-15' }, { day: '2026-10-16' }])).toBe('2026-10-16');
});
it('shows a router day as that day in any time zone', () => {
expect(fmtDay('2026-10-01')).toBe('1 Oct 2026');
expect(date('2026-10-01')).toBe('1 Oct 2026');
expect(date('')).toBe('');
});
});
describe('numbers', () => {
it('pluralises and sizes', () => {
expect(plural(1, 'event')).toBe('1 event');
expect(plural(2000, 'address', 'addresses')).toBe('2,000 addresses');
expect(kb(512)).toBe('512 B');
expect(kb(1536)).toBe('1.5 KB');
expect(kb(3 * 1048576)).toBe('3.0 MB');
});
});
+75
View File
@@ -0,0 +1,75 @@
import { beforeAll, describe, expect, it } from 'vitest';
import { El, installFakeDom } from './fakedom';
import { checkVerdict, isOurJob, jobComponent, verText } from '../src/admin/updater/jobs';
import { forRouter, markdown, safeHref } from '../src/admin/updater/markdown';
import type { UpdatesStatus } from '../src/admin/api';
beforeAll(installFakeDom);
describe('jobs', () => {
it('names the component of a job', () => {
expect(jobComponent('app@0.3.1')).toBe('app');
expect(jobComponent('check:amneziawg')).toBe('amneziawg');
expect(jobComponent('check')).toBe('all');
expect(jobComponent('pkgs:a,b')).toBe('pkgs');
expect(jobComponent('amneziawg:auto')).toBe('amneziawg');
});
it('shows versions', () => {
expect(verText({ from: '0.3.0', to: '0.3.1' }, 'x')).toBe('0.3.0 → 0.3.1');
expect(verText({ from: null, to: null }, 'x')).toBe('x');
expect(verText({ from: '1', to: '1' }, 'x')).toBe('1');
});
it('accepts only the job this click started', () => {
const since = 1000;
// The previous job, finished: never.
expect(isOurJob({ id: 'old', state: 'done', started: 900 }, undefined, 'old', since)).toBe(false);
// A finished job from before the click without a known previous id: no.
expect(isOurJob({ id: 'x', state: 'done', started: 900 }, undefined, undefined, since)).toBe(false);
// Running, or started at/after the click: yes.
expect(isOurJob({ id: 'new', state: 'running', started: 999 }, undefined, 'old', since)).toBe(true);
expect(isOurJob({ id: 'new', state: 'done', started: 1001 }, undefined, 'old', since)).toBe(true);
// Once the id is known, only that one.
expect(isOurJob({ id: 'other', state: 'running', started: 1001 }, 'new', 'old', since)).toBe(false);
});
it('sums up a check', () => {
const st = (components: Record<string, unknown>) => ({ check: { time: 1, components } }) as unknown as UpdatesStatus;
expect(checkVerdict(st({ app: { update: true, installed: '0.3.0', latest: '0.3.1' } }), 'app')).toEqual({
tone: 'acc',
text: 'Update available: Dawnline 0.3.1',
update: '0.3.1',
});
expect(checkVerdict(st({ app: {}, amneziawg: {}, packages: { updates: 2 } }), 'all').text).toBe('Update available: 2 system packages');
expect(checkVerdict(st({ app: { error: 'GitHub is unreachable' } }), 'app')).toEqual({ tone: 'warn', text: 'GitHub is unreachable' });
expect(checkVerdict(st({ app: { status: 'dev', latest: '0.3.0' } }), 'app').text).toContain('newer than the release');
expect(checkVerdict(st({ app: {}, amneziawg: {}, packages: {} }), 'all')).toEqual({ tone: 'ok', text: 'Everything is up to date' });
});
});
describe('release notes', () => {
it('drops the What’s new heading and the Install section', () => {
const md = "## What's new\n- One\n- Two\n\n## Install\nopkg install x\n\n**Full Changelog**: a...b";
expect(forRouter(md)).toBe('- One\n- Two\n\n**Full Changelog**: a...b');
});
it('builds headings, lists, code, bold and safe links', () => {
const out = markdown('# Title\n- `code` and **bold**\n- [site](https://example.com)\n\nSee javascript:alert(1)') as unknown as El[];
expect(out.map((n) => n.tag)).toEqual(['h5', 'ul', 'p']);
const items = out[1].children as El[];
expect(items[0].children.map((c) => (typeof c === 'string' ? c : c.tag))).toEqual(['code', ' and ', 'b']);
const a = items[1].children[0] as El;
expect(a.tag).toBe('a');
expect(a.attrs.href).toBe('https://example.com');
// Not a link: only http(s) addresses become one.
expect(out[2].children).toEqual(['See javascript:alert(1)']);
});
it('keeps fenced code as it is', () => {
const out = markdown('```\n# not a heading\n```') as unknown as El[];
expect(out[0].tag).toBe('pre');
expect(out[0].textContent).toBe('# not a heading');
});
it('allows only https release pages', () => {
expect(safeHref('https://github.com/x/y/releases/tag/v1')).toBe('https://github.com/x/y/releases/tag/v1');
expect(safeHref('javascript:alert(1)')).toBeNull();
expect(safeHref('http://example.com')).toBeNull();
expect(safeHref(null)).toBeNull();
});
});
+16 -15
View File
@@ -33,19 +33,22 @@ async function minifyCss(css: string): Promise<string> {
return (await transform(css, { loader: 'css', minify: true, legalComments: 'none' })).code.trim();
}
// The admin styles live in a template string in styles.ts (rendered inside each
// view); squeeze that string before bundling. It has no ${} and no backslashes.
const minifyStylesTs: Plugin = {
name: 'minify-styles-ts',
// The admin styles are plain .css files under src/admin/styles, imported as
// text and joined in styles/index.ts (rendered inside each view): each is
// minified here. They get a namespace (and a path not ending in .css) of
// their own, so tsup's CSS handling, which would emit a stylesheet, never sees them.
const adminCss: Plugin = {
name: 'admin-css-text',
setup(build) {
build.onLoad({ filter: /admin[\\/]styles\.ts$/ }, async (args) => {
const src = fs.readFileSync(args.path, 'utf8');
const m = /const CSS = `([\s\S]*?)`;/.exec(src);
if (!m) throw new Error('styles.ts: CSS template not found');
if (/\$\{|\\/.test(m[1])) throw new Error('styles.ts: the CSS must not contain ${} or backslashes');
const css = await minifyCss(m[1]);
return { contents: src.replace(m[0], `const CSS = \`${css}\`;`), loader: 'ts' };
});
build.onResolve({ filter: /\.css$/ }, (args) =>
/admin[\\/]styles$/.test(args.resolveDir)
? { path: `${path.join(args.resolveDir, args.path)}#text`, namespace: 'dl-css' }
: undefined,
);
build.onLoad({ filter: /.*/, namespace: 'dl-css' }, async (args) => ({
contents: await minifyCss(fs.readFileSync(args.path.replace(/#text$/, ''), 'utf8')),
loader: 'text',
}));
},
};
@@ -61,17 +64,15 @@ export default defineConfig([
// Identifiers only: LuCI's require directives in the banner must stay as written.
minify: true,
noExternal: ['qrcode-generator'],
esbuildPlugins: [minifyStylesTs],
esbuildPlugins: [adminCss],
banner: {
js: [
'// Generated from dawnline/web — do not edit by hand.',
"'use strict';",
"'require baseclass';",
"'require dom';",
"'require form';",
"'require poll';",
"'require rpc';",
"'require uci';",
"'require ui';",
].join('\n'),
},