LuCI admin (people, devices, limits, disguise, health, updates, backups) and a personal self-service portal, built as ipk (OpenWrt 24.10) and apk (OpenWrt 25.12) with the OpenWrt SDK. Successor of openwrt-liminal. - install.sh: checks the router, installs AmneziaWG for its firmware, then the release package verified against sha256sums.txt - CI: Prettier, types, tests, committed bundles, ShellCheck, ucode checks; tagged releases build both packages and publish them - Web bundles minified with esbuild (JS and CSS) - README with framed screenshots
This commit is contained in:
commit
a3910f8b97
105 files changed
+22278
No files matched your search
@@ -0,0 +1,344 @@
|
||||
// luci.dawnline RPC bindings. The backend reports failures as { error }.
|
||||
|
||||
import type { AwgCaps, ClientConfig, DayUsage, HealthCheck, LogEvent, Person, Status } from '../shared/types';
|
||||
|
||||
function call<T>(method: string, params: string[] = []) {
|
||||
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params });
|
||||
return async (...args: unknown[]): Promise<T> => {
|
||||
const r = await fn(...args);
|
||||
if (r && typeof r === 'object' && typeof r.error === 'string') throw new Error(r.error);
|
||||
return r as T;
|
||||
};
|
||||
}
|
||||
|
||||
export interface SetupDefaults {
|
||||
id: string;
|
||||
name: string;
|
||||
ifname: string;
|
||||
port: number;
|
||||
subnet: string;
|
||||
endpoint: string;
|
||||
mtu: number;
|
||||
zones: string[];
|
||||
lan_zone: string;
|
||||
wan_zone: string;
|
||||
portal_port: number;
|
||||
taken: string[];
|
||||
awg: AwgCaps;
|
||||
}
|
||||
|
||||
export interface Backup {
|
||||
name: string;
|
||||
created: number;
|
||||
size: number;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export type AwgSource = 'slava' | 'grey';
|
||||
|
||||
export interface UpdateComponent {
|
||||
installed?: string | null;
|
||||
latest?: string | null;
|
||||
update?: boolean;
|
||||
note?: string;
|
||||
error?: string;
|
||||
repo?: string;
|
||||
tag?: string;
|
||||
packages?: Record<string, string | null>;
|
||||
// AmneziaWG: the installed build and both builds for this firmware
|
||||
current?: AwgSource | null;
|
||||
gen?: '2.0' | '3.1' | null;
|
||||
ru?: boolean;
|
||||
release?: string;
|
||||
sources?: Partial<
|
||||
Record<
|
||||
AwgSource,
|
||||
{
|
||||
label: string;
|
||||
repo: string;
|
||||
tag: string;
|
||||
version: string | null;
|
||||
gen: '2.0' | '3.1' | null;
|
||||
date: string | null;
|
||||
newer?: { tag: string; gen: '3.1' };
|
||||
}
|
||||
>
|
||||
>;
|
||||
// OpenWrt packages Dawnline uses
|
||||
pkgs?: Record<string, { installed: string | null; latest: string | null; with?: string[] }>;
|
||||
updates?: number;
|
||||
}
|
||||
|
||||
export interface UpdatesStatus {
|
||||
version: string;
|
||||
firmware?: { version: string; target: string; arch: string };
|
||||
/** The personal portal is on: its HTTPS packages are listed too. */
|
||||
portal?: boolean;
|
||||
/** A server uses the home-like link. */
|
||||
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;
|
||||
}
|
||||
|
||||
/** Missing packages by feature: the portal's HTTPS, ACME certificates, the home-like link. */
|
||||
export interface Needs {
|
||||
https: string[];
|
||||
acme: string[];
|
||||
home: string[];
|
||||
}
|
||||
|
||||
export interface SettingsData {
|
||||
settings: Record<string, string>;
|
||||
needs?: Needs;
|
||||
effective: Record<string, unknown>;
|
||||
services: { id: string; name: string; address: string; ports: string[] }[];
|
||||
cert: { path: string; self_signed: boolean; expires: string | null } | null;
|
||||
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;
|
||||
}
|
||||
|
||||
export type LogCategory = 'connections' | 'devices' | 'people' | 'problems';
|
||||
|
||||
export interface LogsInfo {
|
||||
policy: {
|
||||
keep_days: number;
|
||||
max: number;
|
||||
categories: LogCategory[];
|
||||
persist: '10min' | 'hourly' | 'off';
|
||||
usage_days: number;
|
||||
usage_months: number;
|
||||
};
|
||||
events: number;
|
||||
oldest: number;
|
||||
by_category: Record<LogCategory, number>;
|
||||
log_ram: number;
|
||||
log_flash: number;
|
||||
usage_flash: number;
|
||||
usage_since: string;
|
||||
usage_days: number;
|
||||
geo_flash: number;
|
||||
}
|
||||
|
||||
/** The path that makes tunnel clients' internet traffic enter from the LAN. */
|
||||
export interface LikeHome {
|
||||
active: boolean;
|
||||
dev?: string;
|
||||
address?: string;
|
||||
dns?: string;
|
||||
gateway?: string;
|
||||
bridged?: boolean;
|
||||
off?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export type IfaceCategory = 'wan' | 'ethernet' | 'wifi' | 'vpn' | 'other';
|
||||
|
||||
export interface NetDevice {
|
||||
name: string;
|
||||
category: IfaceCategory;
|
||||
kind: 'bridge' | IfaceCategory;
|
||||
up: boolean;
|
||||
master: string | null;
|
||||
members: string[];
|
||||
nets: string[];
|
||||
addrs: string[];
|
||||
logical: string | null;
|
||||
proto: string | null;
|
||||
zone: string | null;
|
||||
/** The server's own tunnel interface. */
|
||||
own?: boolean;
|
||||
/** Part of the server's home network (auto = via Auto-detect LAN). */
|
||||
home?: boolean;
|
||||
auto?: boolean;
|
||||
/** Saved but not present right now. */
|
||||
missing?: boolean;
|
||||
}
|
||||
|
||||
export interface InterfacesData {
|
||||
server: string;
|
||||
/** Packages the home-like link still needs. */
|
||||
needs?: string[];
|
||||
ifname: string;
|
||||
detected: { wan: string | null; lan: string | null };
|
||||
saved: { wan: string; lan: string };
|
||||
config: { auto_wan: boolean; wan_device: string; auto_lan: boolean; lan_devices: string[]; lan_like: boolean };
|
||||
like_home: LikeHome;
|
||||
effective: {
|
||||
wan: { dev: string | null; zone: string; auto: boolean; missing: boolean };
|
||||
home: { dev: string; auto: boolean; nets: string[]; zone: string | null; missing: boolean }[];
|
||||
nets: string[];
|
||||
zones: string[];
|
||||
};
|
||||
zones: string[];
|
||||
devices: NetDevice[];
|
||||
/** People on this server with Home-only access (their AllowedIPs follow the home networks). */
|
||||
lan_only: number;
|
||||
nets_changed?: boolean;
|
||||
}
|
||||
|
||||
/** Filters for logs_clear; all empty clears the whole log. */
|
||||
export interface LogFilter {
|
||||
person?: string;
|
||||
device?: string;
|
||||
category?: string;
|
||||
older_days?: string;
|
||||
}
|
||||
|
||||
const logsClearRaw = call<{ removed: number }>('logs_clear', ['person', 'device', 'category', 'older_days']);
|
||||
const logsClear = (f: LogFilter = {}) => logsClearRaw(f.person ?? '', f.device ?? '', f.category ?? '', f.older_days ?? '');
|
||||
|
||||
/** Fields for person_update; send strings ('' clears an optional value). */
|
||||
export type PersonPatch = Partial<
|
||||
Record<
|
||||
| 'name'
|
||||
| 'access'
|
||||
| 'device_limit'
|
||||
| 'expires'
|
||||
| 'expire_action'
|
||||
| 'expire_warn'
|
||||
| 'quota_gb'
|
||||
| 'quota_period'
|
||||
| 'bonus_gb'
|
||||
| 'hours'
|
||||
| 'note'
|
||||
| 'dns_mode',
|
||||
string
|
||||
>
|
||||
> & { paused?: boolean; services?: string[] };
|
||||
|
||||
const personUpdateRaw = rpc.declare<any>({
|
||||
object: 'luci.dawnline',
|
||||
method: 'person_update',
|
||||
params: [
|
||||
'id',
|
||||
'name',
|
||||
'access',
|
||||
'device_limit',
|
||||
'expires',
|
||||
'expire_action',
|
||||
'expire_warn',
|
||||
'quota_gb',
|
||||
'quota_period',
|
||||
'bonus_gb',
|
||||
'hours',
|
||||
'note',
|
||||
'dns_mode',
|
||||
'paused',
|
||||
'services',
|
||||
],
|
||||
});
|
||||
|
||||
async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: Person }> {
|
||||
const keys = [
|
||||
'name',
|
||||
'access',
|
||||
'device_limit',
|
||||
'expires',
|
||||
'expire_action',
|
||||
'expire_warn',
|
||||
'quota_gb',
|
||||
'quota_period',
|
||||
'bonus_gb',
|
||||
'hours',
|
||||
'note',
|
||||
'dns_mode',
|
||||
] as const;
|
||||
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services];
|
||||
const r = await personUpdateRaw(...args);
|
||||
if (r && typeof r.error === 'string') throw new Error(r.error);
|
||||
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;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
personUpdate,
|
||||
settingsGet: call<SettingsData>('settings_get'),
|
||||
settingsUpdate: call<SettingsData>('settings_update', ['values']),
|
||||
serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']),
|
||||
serviceDelete: call<unknown>('service_delete', ['id']),
|
||||
geoClear: call<unknown>('geo_clear'),
|
||||
events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit']),
|
||||
logsClear,
|
||||
interfaces: call<InterfacesData>('interfaces', ['id']),
|
||||
serverInterfaces: call<InterfacesData>('server_interfaces', ['id', 'auto_wan', 'wan_device', 'auto_lan', 'lan_devices', 'lan_like']),
|
||||
usageClear: call<unknown>('usage_clear', ['scope', 'id']),
|
||||
uninstall: call<unknown>('uninstall', ['confirm']),
|
||||
status,
|
||||
setupDefaults: call<SetupDefaults>('setup_defaults'),
|
||||
serverCreate: call<{ id: string }>('server_create', [
|
||||
'id',
|
||||
'name',
|
||||
'ifname',
|
||||
'port',
|
||||
'subnet',
|
||||
'endpoint',
|
||||
'mtu',
|
||||
'preset',
|
||||
'lan_zone',
|
||||
'wan_zone',
|
||||
'lan_like',
|
||||
'portal_enabled',
|
||||
'portal_port',
|
||||
]),
|
||||
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
|
||||
serverUpdate: call<unknown>('server_update', ['id', 'values']),
|
||||
serverDelete: call<unknown>('server_delete', ['id']),
|
||||
personCreate: call<{ id: string; link: string | null }>('person_create', [
|
||||
'name',
|
||||
'slug',
|
||||
'server',
|
||||
'access',
|
||||
'device_limit',
|
||||
'expires',
|
||||
'quota_gb',
|
||||
'quota_period',
|
||||
]),
|
||||
personPause: call<unknown>('person_pause', ['id', 'paused']),
|
||||
personRegen: call<{ link: string | null }>('person_regen', ['id']),
|
||||
personDelete: call<unknown>('person_delete', ['id']),
|
||||
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
|
||||
pauseAll: call<unknown>('pause_all', ['paused']),
|
||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
|
||||
deviceConfig: call<ClientConfig>('device_config', ['id']),
|
||||
deviceUpdate: call<unknown>('device_update', ['id', 'name', 'disabled']),
|
||||
deviceDelete: call<unknown>('device_delete', ['id']),
|
||||
deviceRotate: call<ClientConfig>('device_rotate', ['id']),
|
||||
apply: call<unknown>('apply'),
|
||||
health: call<{ checks: HealthCheck[] }>('health'),
|
||||
healthFix: call<{ checks: HealthCheck[] }>('health_fix', ['id']),
|
||||
backupList: call<{ backups: Backup[] }>('backup_list'),
|
||||
backupCreate: call<{ name: string }>('backup_create'),
|
||||
backupRestore: call<unknown>('backup_restore', ['name']),
|
||||
backupDelete: call<unknown>('backup_delete', ['name']),
|
||||
backupRead: call<{ data: string }>('backup_read', ['name']),
|
||||
backupUpload: call<unknown>('backup_upload', ['data']),
|
||||
exportJson: call<Record<string, unknown>>('export'),
|
||||
importJson: call<unknown>('import', ['data']),
|
||||
updatesStatus: call<UpdatesStatus>('updates_status'),
|
||||
updatesRun: call<{ started: boolean }>('updates_run', ['what']),
|
||||
};
|
||||
@@ -0,0 +1,171 @@
|
||||
// Backups: a section of the Settings page. 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';
|
||||
|
||||
const REASON: Record<string, string> = {
|
||||
manual: 'Manual',
|
||||
auto: 'Nightly',
|
||||
'pre-restore': 'Before restore',
|
||||
'pre-import': 'Before import',
|
||||
'pre-delete': 'Before removing a server',
|
||||
'pre-update': 'Before update',
|
||||
};
|
||||
const SHOWN = 3;
|
||||
|
||||
/** "Today, 03:00", "Yesterday, 03:00" or "12 Oct, 03:00". */
|
||||
function when(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
const t = d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
|
||||
const days = Math.round((new Date(new Date().toDateString()).getTime() - new Date(d.toDateString()).getTime()) / 86400000);
|
||||
return `${days === 0 ? 'Today' : days === 1 ? 'Yesterday' : d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}, ${t}`;
|
||||
}
|
||||
|
||||
async function download(b: Backup) {
|
||||
const r = await attempt(() => api.backupRead(b.name));
|
||||
if (!r) return;
|
||||
const bin = atob(r.data);
|
||||
const arr = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
|
||||
const g = globalThis as unknown as { Blob: typeof Blob };
|
||||
downloadFile(b.name, new g.Blob([arr], { type: 'application/gzip' }));
|
||||
}
|
||||
|
||||
function backupRow(b: Backup, done: () => void): 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' }, [
|
||||
E('b', {}, when(b.created)),
|
||||
E('span', { class: 'dl-sub' }, `${REASON[b.reason] ?? b.reason} · ${bytes(b.size)}`),
|
||||
]),
|
||||
E('span', { class: 'dl-pcard-actions' }, [
|
||||
iconButton('download', 'Download', () => download(b), 'neutral', 'dl-icon-only'),
|
||||
iconButton(
|
||||
'more',
|
||||
'More',
|
||||
(ev: MouseEvent) =>
|
||||
dropdown(ev.currentTarget as HTMLElement, [
|
||||
{
|
||||
label: 'Restore',
|
||||
icon: icon('reset'),
|
||||
run: async () => {
|
||||
const ok = await confirmDialog(
|
||||
'Restore this backup?',
|
||||
`Everything returns to ${when(b.created)}. The current state is backed up first.`,
|
||||
'Restore',
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.backupRestore(b.name), 'Restored'))) done();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Delete',
|
||||
icon: icon('trash'),
|
||||
danger: true,
|
||||
run: async () => {
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
'Delete this backup?',
|
||||
`The backup from ${when(b.created)} is removed from the router.`,
|
||||
'Delete',
|
||||
true,
|
||||
))
|
||||
)
|
||||
return;
|
||||
if (await attempt(() => api.backupDelete(b.name), 'Backup deleted')) done();
|
||||
},
|
||||
},
|
||||
]),
|
||||
'neutral',
|
||||
'dl-icon-only',
|
||||
),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/** The Backups section; `done` reloads the list (and the page data after a restore). */
|
||||
export function backupsSection(list: Backup[], done: () => void): HTMLElement {
|
||||
const rows = list.slice(0, SHOWN).map((b) => backupRow(b, done));
|
||||
const older = list.slice(SHOWN);
|
||||
const body = list.length
|
||||
? E('div', { class: 'dl-list' }, [
|
||||
...rows,
|
||||
older.length
|
||||
? E('details', { class: 'dl-bk-older' }, [
|
||||
E('summary', {}, [icon('chevron'), `${older.length} older backup${older.length === 1 ? '' : 's'}`]),
|
||||
...older.map((b) => backupRow(b, done)),
|
||||
])
|
||||
: '',
|
||||
])
|
||||
: E('div', { class: 'dl-list' }, [E('div', { class: 'dl-row dl-muted' }, 'No backups yet.')]);
|
||||
|
||||
const restoreFile = button('Restore from file', async () => {
|
||||
const f = await pickFile('.tar.gz,.tgz,application/gzip', 'base64');
|
||||
if (!f) return;
|
||||
const ok = await confirmDialog(
|
||||
'Restore from file?',
|
||||
`Replace the current Dawnline configuration with ${f.name}? The current state is backed up first.`,
|
||||
'Restore',
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.backupUpload(f.data), 'Restored'))) done();
|
||||
});
|
||||
const exportJson = button('Export JSON', async () => {
|
||||
const r = await attempt(() => api.exportJson());
|
||||
if (r) downloadFile(`dawnline-export-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(r, null, 2), 'application/json');
|
||||
});
|
||||
const importJson = button('Import JSON', async () => {
|
||||
const f = await pickFile('.json,application/json', 'text');
|
||||
if (!f) return;
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(f.data);
|
||||
} catch {
|
||||
notify('Not a JSON file.', 'error');
|
||||
return;
|
||||
}
|
||||
const ok = await confirmDialog(
|
||||
'Import?',
|
||||
'This replaces the whole Dawnline configuration on this router. The current state is backed up first.',
|
||||
'Import',
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.importJson(data), 'Imported'))) done();
|
||||
});
|
||||
|
||||
return E('section', { class: 'dl-setsec', id: 'dl-set-backups' }, [
|
||||
E('div', { class: 'dl-setsec-body' }, [
|
||||
E('div', { class: 'dl-setsec-head' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('h3', {}, 'Backups'),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
'Nightly when something changed, and before every restore, import or update. The last 10 are kept.',
|
||||
),
|
||||
]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
button(
|
||||
[icon('plus'), ' Back up now'],
|
||||
async () => {
|
||||
if (await attempt(() => api.backupCreate(), 'Backup created')) done();
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
]),
|
||||
body,
|
||||
]),
|
||||
E('div', { class: 'dl-setsec-foot' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
'Backups contain private keys: keep downloads safe. JSON moves everything except usage history to another router.',
|
||||
),
|
||||
E('span', { class: 'dl-row-actions dl-bk-actions' }, [restoreFile, exportJson, importJson]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
// Device drawer: a right-hand panel with the device's status, connection
|
||||
// (QR / key / file), details and actions. Replaces the old tabbed modal.
|
||||
|
||||
import type { ClientConfig, 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 { qrSvg } from '../shared/qr';
|
||||
import { vpnKey } from '../shared/vpnkey';
|
||||
import { ago, bytes, KIND_LABEL, KINDS } from '../shared/format';
|
||||
import { icon } from '../shared/icons';
|
||||
import { spark } from './charts';
|
||||
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
|
||||
|
||||
let current: { close: () => void } | null = null;
|
||||
|
||||
function iso(ts: number): string {
|
||||
return ts
|
||||
? new Date(ts * 1000).toLocaleString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
|
||||
: '—';
|
||||
}
|
||||
|
||||
function copyRow(label: string, value: string, mono = true): HTMLElement {
|
||||
return E('div', { class: 'dl-kvrow' }, [
|
||||
E('span', { class: 'dl-kvrow-k' }, label),
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: `dl-kvrow-v copy${mono ? ' dl-mono' : ''}`, title: 'Copy', click: () => copyText(value, `${label} copied`) },
|
||||
[E('span', {}, value), icon('copy')],
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
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,
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/** QR / key / file switcher for a client configuration. */
|
||||
export async function connectBlock(cfg: ClientConfig): 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 [
|
||||
['qr', 'QR code'],
|
||||
['key', 'Key'],
|
||||
['file', 'File'],
|
||||
])
|
||||
seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
|
||||
show('qr');
|
||||
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]> = {
|
||||
connect: ['ok', 'Connected'],
|
||||
disconnect: ['', 'Went offline'],
|
||||
roam: ['', 'Changed network'],
|
||||
device_added: ['accent', 'Added'],
|
||||
device_removed: ['', 'Removed'],
|
||||
};
|
||||
|
||||
/** Activity of one device, newest first. */
|
||||
function deviceEvents(events: LogEvent[], id: string): HTMLElement {
|
||||
const mine = events
|
||||
.filter((e) => e.device === id && DEV_EVENT[e.type])
|
||||
.reverse()
|
||||
.slice(0, 12);
|
||||
if (!mine.length) return E('div', { class: 'dl-sub' }, 'No activity yet.');
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'dl-dev-log' },
|
||||
mine.map((e) => {
|
||||
const [tone, label] = DEV_EVENT[e.type];
|
||||
const extra =
|
||||
e.type === 'connect'
|
||||
? [
|
||||
e.detail ? E('span', { class: 'dl-mono' }, ` ${e.detail}`) : '',
|
||||
e.where ? E('span', { class: 'dl-faint' }, ` · ${e.where}`) : '',
|
||||
]
|
||||
: e.type === 'roam'
|
||||
? [E('span', { class: 'dl-mono dl-faint' }, ` ${e.detail ?? ''}`)]
|
||||
: e.type === 'device_added'
|
||||
? [E('span', { class: 'dl-faint' }, (e.detail ?? '').includes('(portal)') ? ' from the portal' : ' by you')]
|
||||
: [];
|
||||
const t = new Date(e.ts * 1000);
|
||||
return E('div', { class: 'dl-dev-log-row' }, [
|
||||
E('span', { class: `dl-ev-dot ${tone}` }),
|
||||
E('span', { class: 'dl-row-main' }, [E('span', {}, label), ...extra]),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts)),
|
||||
]);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function statusLine(d: Device): HTMLElement {
|
||||
if (d.disabled) return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), 'Disabled']);
|
||||
if (d.online) return E('span', { class: 'dl-dstat ok' }, [E('i', { class: 'dot ok' }), `Online from ${d.endpoint}`]);
|
||||
if (!d.handshake) return E('span', { class: 'dl-dstat warn' }, [E('i', { class: 'dot warn' }), 'Waiting for the first connection']);
|
||||
return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), `Last seen ${ago(d.handshake)}`]);
|
||||
}
|
||||
|
||||
/** Device drawer; `refresh` reloads the page after changes. */
|
||||
export async function openDevice(person: Person, dev: Device, refresh: () => unknown, geo?: Geo) {
|
||||
const cfg = await attempt(() => api.deviceConfig(dev.id));
|
||||
if (!cfg) return;
|
||||
let d = dev;
|
||||
let p = person;
|
||||
const connect = await connectBlock(cfg);
|
||||
const titleEl = E('div', { class: 'dl-drawer-title' });
|
||||
const stats = E('div', {});
|
||||
const details = E('div', {});
|
||||
const live = E('div', { class: 'dl-live' });
|
||||
const log = E('div', {}, E('div', { class: 'dl-sub' }, 'Loading…'));
|
||||
let logEvents: LogEvent[] = [];
|
||||
const loadLog = async () => {
|
||||
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));
|
||||
};
|
||||
|
||||
const paint = () => {
|
||||
const place = geo?.points.find((x) => x.device === d.id && x.ip === d.endpoint);
|
||||
dom.content(titleEl, [
|
||||
E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('div', { class: 'dl-title-row' }, [
|
||||
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]}`]),
|
||||
]),
|
||||
]);
|
||||
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' }, [
|
||||
E('span', { class: 'dl-metric-label' }, 'This month'),
|
||||
E('b', {}, bytes(d.month[0] + d.month[1])),
|
||||
E('span', { class: 'dl-sub dl-mono' }, `↓ ${bytes(d.month[1])} ↑ ${bytes(d.month[0])}`),
|
||||
]),
|
||||
E('div', { class: 'dl-dstats-cell' }, [
|
||||
E('span', { class: 'dl-metric-label' }, 'Last 7 days'),
|
||||
E('b', {}, bytes(week)),
|
||||
spark(d.spark, 120, 22),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
dom.content(
|
||||
details,
|
||||
E('div', { class: 'dl-kv2' }, [
|
||||
copyRow('Tunnel address', d.address),
|
||||
d.hostname && p.access !== 'internet' ? copyRow('Local address', d.hostname) : '',
|
||||
d.endpoint
|
||||
? row(
|
||||
'Client IP',
|
||||
E('span', {}, [
|
||||
E('span', { class: 'dl-mono' }, d.endpoint),
|
||||
place ? E('span', { class: 'dl-faint' }, ` · ${[place.city, place.org].filter(Boolean).join(' · ')}`) : '',
|
||||
]),
|
||||
)
|
||||
: '',
|
||||
row(
|
||||
'Total',
|
||||
E('span', { class: 'dl-kv-act' }, [
|
||||
`↓ ${bytes(d.total[1])} · ↑ ${bytes(d.total[0])}`,
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-linkbtn danger',
|
||||
click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(reload, 300)),
|
||||
},
|
||||
'Reset',
|
||||
),
|
||||
]),
|
||||
),
|
||||
row('Added', `${iso(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)}…` : '—'),
|
||||
),
|
||||
]),
|
||||
);
|
||||
dom.content(
|
||||
live,
|
||||
d.online
|
||||
? [E('i', { class: 'dot ok' }), E('span', { class: 'dl-ok' }, 'Connected')]
|
||||
: d.handshake
|
||||
? [E('i', { class: 'dot' }), E('span', { class: 'dl-muted' }, `Last connected ${ago(d.handshake)}`)]
|
||||
: [E('i', { class: 'dot warn pulse' }), E('span', { class: 'dl-muted' }, 'Waiting for the first connection…')],
|
||||
);
|
||||
dom.content(foot, [
|
||||
button(
|
||||
[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();
|
||||
},
|
||||
'neutral',
|
||||
d.disabled ? {} : { class: 'cbi-button cbi-button-neutral dl-btn-warn' },
|
||||
),
|
||||
button([icon('key'), ' New keys'], async () => {
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
'Generate new keys?',
|
||||
'The current configuration on this device stops working until it is imported again.',
|
||||
'Generate',
|
||||
true,
|
||||
))
|
||||
)
|
||||
return;
|
||||
const c = await attempt(() => api.deviceRotate(d.id), 'New keys generated');
|
||||
if (c) {
|
||||
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);
|
||||
}
|
||||
}),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
button(
|
||||
[icon('trash'), ' Remove'],
|
||||
async () => {
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
`Remove ${d.name}?`,
|
||||
'The device is disconnected immediately and its configuration stops working.',
|
||||
'Remove',
|
||||
true,
|
||||
))
|
||||
)
|
||||
return;
|
||||
if (await attempt(() => api.deviceDelete(d.id), 'Device removed')) {
|
||||
handle.close();
|
||||
refresh();
|
||||
}
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
]);
|
||||
};
|
||||
|
||||
const reload = async () => {
|
||||
const st = await api.status(1).catch(() => null);
|
||||
const p2 = st?.people.find((x) => x.id === p.id);
|
||||
const d2 = p2?.devices.find((x) => x.id === d.id);
|
||||
if (!st || !p2 || !d2) return;
|
||||
p = p2;
|
||||
d = d2;
|
||||
geo = st.geo;
|
||||
paint();
|
||||
refresh();
|
||||
};
|
||||
|
||||
const rename = () => {
|
||||
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement;
|
||||
modal(
|
||||
`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'),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
async () => {
|
||||
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) {
|
||||
closeModal();
|
||||
await reload();
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
setTimeout(() => input.select(), 50);
|
||||
};
|
||||
|
||||
const foot = E('div', { class: 'dl-drawer-actions' });
|
||||
const body = E('div', { class: 'dl-stack gap16' }, [
|
||||
stats,
|
||||
E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, 'Connect'), live]),
|
||||
d.config_stale
|
||||
? E('div', { class: 'dl-note warn' }, [
|
||||
icon('alert'),
|
||||
E(
|
||||
'span',
|
||||
{},
|
||||
'This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.',
|
||||
),
|
||||
])
|
||||
: '',
|
||||
connect,
|
||||
]),
|
||||
E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, [
|
||||
E('h4', {}, 'Activity'),
|
||||
E('div', { class: 'dl-dsec-actions' }, [
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-linkbtn', click: () => exportEvents({ people: [p] }, logEvents, 'csv', d.id) },
|
||||
'Export',
|
||||
),
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-linkbtn danger',
|
||||
click: () => clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, loadLog),
|
||||
},
|
||||
'Clear',
|
||||
),
|
||||
E('a', { href: L.url('admin/network/dawnline/activity') }, 'All activity'),
|
||||
]),
|
||||
]),
|
||||
log,
|
||||
]),
|
||||
E('section', { class: 'dl-dsec' }, [E('div', { class: 'dl-dsec-head' }, E('h4', {}, 'Details')), details]),
|
||||
]);
|
||||
loadLog();
|
||||
const watch = window.setInterval(() => {
|
||||
reload();
|
||||
loadLog();
|
||||
}, 8000);
|
||||
const handle = drawer(titleEl, body, foot, () => clearInterval(watch));
|
||||
paint();
|
||||
}
|
||||
|
||||
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
|
||||
export function addDevice(person: Person, refresh: () => unknown) {
|
||||
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(
|
||||
'div',
|
||||
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': 'Type' },
|
||||
KINDS.map((k) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'radio',
|
||||
class: k === kind ? 'on' : '',
|
||||
'aria-checked': k === kind ? 'true' : 'false',
|
||||
'data-kind': k,
|
||||
click: () => {
|
||||
kind = k;
|
||||
kinds.querySelectorAll('button').forEach((c) => {
|
||||
const on = (c as HTMLElement).dataset.kind === k;
|
||||
c.classList.toggle('on', on);
|
||||
c.setAttribute('aria-checked', on ? 'true' : 'false');
|
||||
});
|
||||
nameInput.placeholder = KIND_LABEL[k];
|
||||
},
|
||||
},
|
||||
[icon(k), E('span', {}, KIND_LABEL[k])],
|
||||
),
|
||||
),
|
||||
);
|
||||
const over = person.devices.length >= person.device_limit;
|
||||
modal(
|
||||
`Add a device for ${person.name}`,
|
||||
[
|
||||
over
|
||||
? E(
|
||||
'p',
|
||||
{ class: 'dl-hint' },
|
||||
`${person.name} already has ${person.devices.length} of ${person.device_limit} devices. As admin you can still add one.`,
|
||||
)
|
||||
: '',
|
||||
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Type'), kinds]),
|
||||
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Name'), nameInput]),
|
||||
],
|
||||
[
|
||||
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
|
||||
' ',
|
||||
button(
|
||||
'Add device',
|
||||
async () => {
|
||||
const name = nameInput.value.trim() || nameInput.placeholder.replace(/^e\.g\. /, '');
|
||||
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
|
||||
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);
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
setTimeout(() => nameInput.focus(), 50);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// Disguise methods: one picker for the Server page and the setup wizard.
|
||||
|
||||
import type { AwgCaps } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { icon } from '../shared/icons';
|
||||
|
||||
export type Method = 'standard' | 'strong' | 'max' | 'off';
|
||||
|
||||
export interface MethodInfo {
|
||||
id: Method;
|
||||
title: string;
|
||||
ic: string;
|
||||
text: string;
|
||||
/** 0-4, shown as dots. */
|
||||
stealth: number;
|
||||
speed: number;
|
||||
/** Which apps can connect. */
|
||||
apps: string;
|
||||
/** The same, short (server header). */
|
||||
short: string;
|
||||
/** Router capability it needs. */
|
||||
needs?: keyof AwgCaps;
|
||||
}
|
||||
|
||||
export const METHODS: MethodInfo[] = [
|
||||
{
|
||||
id: 'off',
|
||||
title: 'Off',
|
||||
ic: 'zap',
|
||||
stealth: 0,
|
||||
speed: 4,
|
||||
text: 'Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.',
|
||||
apps: 'Any WireGuard app',
|
||||
short: 'Any WireGuard app',
|
||||
},
|
||||
{
|
||||
id: 'standard',
|
||||
title: 'Standard',
|
||||
ic: 'shield',
|
||||
stealth: 2,
|
||||
speed: 4,
|
||||
text: 'Junk packets and random headers. Gets through most VPN blocking with no speed cost.',
|
||||
apps: 'Every AmneziaWG and AmneziaVPN app',
|
||||
short: 'Any AmneziaWG app',
|
||||
},
|
||||
{
|
||||
id: 'strong',
|
||||
title: 'Strong',
|
||||
ic: 'shieldplus',
|
||||
stealth: 3,
|
||||
speed: 3,
|
||||
text: 'More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.',
|
||||
apps: 'Every AmneziaWG and AmneziaVPN app',
|
||||
short: 'Any AmneziaWG app',
|
||||
},
|
||||
{
|
||||
id: 'max',
|
||||
title: 'Maximum',
|
||||
ic: 'lock',
|
||||
stealth: 4,
|
||||
speed: 3,
|
||||
needs: 'v3',
|
||||
text: 'AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.',
|
||||
apps: 'Apps with AmneziaWG 3.1 (current AmneziaVPN)',
|
||||
short: 'AmneziaWG 3.1 apps',
|
||||
},
|
||||
];
|
||||
|
||||
export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id);
|
||||
|
||||
const NEEDS: Record<keyof AwgCaps, string> = {
|
||||
v2: 'Needs AmneziaWG 1.5 or newer on the router.',
|
||||
v3: 'Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).',
|
||||
};
|
||||
|
||||
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),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-dots-row' },
|
||||
[0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method cards. `current` gets a badge; unavailable methods stay visible but
|
||||
* disabled with the reason, so it is clear what an upgrade would bring.
|
||||
*/
|
||||
export function methodPicker(caps: AwgCaps, selected: Method, onSelect: (m: Method) => void, current?: string): HTMLElement {
|
||||
const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': 'Disguise method' });
|
||||
const paint = () =>
|
||||
dom.content(
|
||||
el,
|
||||
METHODS.map((m) => {
|
||||
const ok = !m.needs || caps[m.needs];
|
||||
const on = m.id === selected;
|
||||
return E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'radio',
|
||||
'aria-checked': on ? 'true' : 'false',
|
||||
'aria-disabled': ok ? null : 'true',
|
||||
class: `dl-method${on ? ' on' : ''}${ok ? '' : ' off'}`,
|
||||
click: () => {
|
||||
if (!ok || on) return;
|
||||
selected = m.id;
|
||||
paint();
|
||||
onSelect(m.id);
|
||||
},
|
||||
},
|
||||
[
|
||||
E('div', { class: 'dl-method-head' }, [
|
||||
E('span', { class: 'dl-method-ic' }, icon(m.ic)),
|
||||
E('b', {}, m.title),
|
||||
m.id === current
|
||||
? E('span', { class: 'dl-pill ok' }, 'Current')
|
||||
: m.id === 'standard' && !current
|
||||
? E('span', { class: 'dl-pill' }, 'Recommended')
|
||||
: '',
|
||||
]),
|
||||
E('p', {}, m.text),
|
||||
E('div', { class: 'dl-method-meters' }, [dots(m.stealth, 'Stealth'), dots(m.speed, 'Speed')]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-method-foot' },
|
||||
ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, NEEDS[m.needs!])],
|
||||
),
|
||||
],
|
||||
);
|
||||
}),
|
||||
);
|
||||
paint();
|
||||
return el;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// LuCI's global E() appends array children only one level deep and
|
||||
// stringifies nested arrays ("[object HTMLDivElement]"). This wrapper
|
||||
// flattens children recursively and drops empty values, so components can
|
||||
// compose freely. Modules import it and thereby shadow the global.
|
||||
|
||||
import type { Child } from './luci.d';
|
||||
|
||||
function flatten(c: Child, out: (Node | string)[]): (Node | string)[] {
|
||||
if (c == null || c === false || c === '') return out;
|
||||
if (Array.isArray(c)) c.forEach((x) => flatten(x, out));
|
||||
else out.push(c instanceof Node ? c : String(c));
|
||||
return out;
|
||||
}
|
||||
|
||||
export function E(tag: string, attrs?: Record<string, unknown> | Child, children?: Child): HTMLElement {
|
||||
const luciE = (window as unknown as { E: (t: string, a: Record<string, unknown>, c: Child) => HTMLElement }).E;
|
||||
const isAttrs = attrs != null && typeof attrs === 'object' && !Array.isArray(attrs) && !(attrs instanceof Node);
|
||||
if (!isAttrs && children === undefined) return luciE(tag, {}, flatten(attrs as Child, []));
|
||||
return luciE(tag, (isAttrs ? attrs : {}) as Record<string, unknown>, flatten(children, []));
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
// Interfaces card (Server page): auto-detected WAN and LAN, plus a picker for
|
||||
// the interfaces that make up a server's home network.
|
||||
|
||||
import { E } from './e';
|
||||
import { api, type IfaceCategory, type InterfacesData, type NetDevice } from './api';
|
||||
import { attempt, button, notify } from './ui';
|
||||
import { installMissing } from './pkgs';
|
||||
import { attachTip } from './charts';
|
||||
import { icon } from '../shared/icons';
|
||||
|
||||
const GROUPS: [IfaceCategory, string][] = [
|
||||
['wan', 'WAN'],
|
||||
['ethernet', 'Ethernet'],
|
||||
['wifi', 'Wi-Fi'],
|
||||
['vpn', 'VPN & tunnels'],
|
||||
['other', 'Other'],
|
||||
];
|
||||
|
||||
const ICON: Record<NetDevice['kind'], string> = {
|
||||
wan: 'globe',
|
||||
ethernet: 'ethernet',
|
||||
bridge: 'bridge',
|
||||
wifi: 'wifi',
|
||||
vpn: 'tunnel',
|
||||
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;
|
||||
}
|
||||
|
||||
export function interfacesCard(serverId: string, title = 'Interfaces'): HTMLElement {
|
||||
const root = E(
|
||||
'section',
|
||||
{ class: 'dl-setsec dl-ifcard' },
|
||||
E('div', { class: 'dl-setsec-body' }, E('p', { class: 'dl-muted' }, 'Loading interfaces…')),
|
||||
);
|
||||
let d: InterfacesData;
|
||||
let autoWan = true,
|
||||
wanDev = '',
|
||||
autoLan = true,
|
||||
lanLike = true;
|
||||
let lans = new Set<string>();
|
||||
let initial = '';
|
||||
|
||||
const snapshot = () => JSON.stringify([lanLike, autoWan, autoWan ? '' : wanDev, autoLan, [...lans].sort()]);
|
||||
const liveLan = () => d.detected.lan || d.saved.lan || '';
|
||||
const currentWan = () => (autoWan ? d.detected.wan || d.saved.wan : wanDev) || '';
|
||||
const byName = () => new Map(d.devices.map((x) => [x.name, x]));
|
||||
|
||||
/** Home devices as the server would use them after Save. */
|
||||
const homeDevs = (): NetDevice[] => {
|
||||
const m = byName();
|
||||
const names = [...(autoLan && liveLan() ? [liveLan()] : []), ...[...lans].filter((n) => n !== liveLan())];
|
||||
return names.filter((n) => n !== currentWan()).map((n) => m.get(n) ?? ({ name: n, nets: [], missing: true } as unknown as NetDevice));
|
||||
};
|
||||
|
||||
const take = (r: InterfacesData, resetChoice: boolean) => {
|
||||
d = r;
|
||||
if (resetChoice) {
|
||||
autoWan = r.config.auto_wan;
|
||||
wanDev = r.config.wan_device || r.detected.wan || r.saved.wan || '';
|
||||
autoLan = r.config.auto_lan;
|
||||
lanLike = r.config.lan_like;
|
||||
lans = new Set(r.config.lan_devices);
|
||||
initial = snapshot();
|
||||
}
|
||||
paint();
|
||||
};
|
||||
|
||||
const load = async (reset: boolean) => {
|
||||
const r = await api.interfaces(serverId).catch((e: Error) => {
|
||||
notify(e.message, 'error');
|
||||
return null;
|
||||
});
|
||||
if (r) take(r, reset);
|
||||
};
|
||||
|
||||
function tile(x: NetDevice): HTMLElement {
|
||||
const isAuto = autoLan && x.name === liveLan();
|
||||
const isWan = x.name === currentWan();
|
||||
const sel = !isAuto && lans.has(x.name);
|
||||
const blocked = !!x.own || !!x.master || isWan || isAuto;
|
||||
const usable = !blocked && (x.nets.length > 0 || sel || !!x.missing);
|
||||
const noZone = (sel || isAuto) && !x.zone && !x.missing;
|
||||
const sub = x.missing
|
||||
? 'Not present right now'
|
||||
: x.own
|
||||
? 'This server'
|
||||
: x.master
|
||||
? `Port of ${x.master}`
|
||||
: isWan
|
||||
? `Internet${x.zone ? ` · zone ${x.zone}` : ''}`
|
||||
: x.nets.length
|
||||
? x.nets.join(', ')
|
||||
: 'No IPv4 network';
|
||||
const el = E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-if${sel ? ' sel' : ''}${isAuto ? ' auto' : ''}${!usable && !sel && !isAuto ? ' off' : ''}${noZone ? ' warn' : ''}`,
|
||||
'aria-pressed': sel || isAuto ? 'true' : 'false',
|
||||
// aria-disabled, not disabled: the tooltip should still explain why.
|
||||
'aria-disabled': usable ? null : 'true',
|
||||
click: () => {
|
||||
if (!usable) return;
|
||||
if (lans.has(x.name)) lans.delete(x.name);
|
||||
else lans.add(x.name);
|
||||
paint();
|
||||
},
|
||||
},
|
||||
[
|
||||
E('span', { class: 'dl-if-ic' }, icon(ICON[x.kind] ?? 'link')),
|
||||
E('span', { class: 'dl-if-main' }, [E('span', { class: 'dl-if-name' }, x.name), E('span', { class: 'dl-if-sub' }, sub)]),
|
||||
isAuto
|
||||
? E('span', { class: 'dl-if-badge ok' }, [E('i', { class: 'dot ok' }), 'Auto'])
|
||||
: sel
|
||||
? E('span', { class: 'dl-if-check' }, icon('check'))
|
||||
: '',
|
||||
],
|
||||
);
|
||||
attachTip(el, () => [
|
||||
E('div', { class: 'dl-tip-title' }, x.name),
|
||||
E('div', { class: 'dl-muted' }, [
|
||||
x.logical ? `Interface ${x.logical}` : 'No netifd interface',
|
||||
x.zone ? ` · zone ${x.zone}` : ' · no firewall zone',
|
||||
]),
|
||||
x.members.length ? E('div', { class: 'dl-muted' }, `Ports: ${x.members.join(', ')}`) : '',
|
||||
x.nets.length ? E('div', { class: 'dl-mono' }, x.nets.join(', ')) : '',
|
||||
noZone ? E('div', { class: 'dl-warn' }, 'Not in a firewall zone: the firewall rejects this traffic.') : '',
|
||||
x.master ? E('div', { class: 'dl-muted' }, `Choose ${x.master} to include it.`) : '',
|
||||
]);
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Tile colour: green while traffic really enters the LAN, orange when it should but can't. */
|
||||
function likeHomeTone(): string {
|
||||
const lh = d.like_home;
|
||||
if (!lanLike || !d.config.lan_like) return '';
|
||||
return !d.needs?.length && lh.active && lh.bridged ? 'ok' : 'warn';
|
||||
}
|
||||
|
||||
function likeHomeText(): (Node | string)[] {
|
||||
const lh = d.like_home;
|
||||
if (!lanLike) return ['Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router.'];
|
||||
if (d.needs?.length)
|
||||
return [
|
||||
E('span', { class: 'dl-warn' }, `Needs ${d.needs.join(' and ')}.`),
|
||||
' Until they are installed, internet traffic goes straight to the WAN.',
|
||||
];
|
||||
if (!d.config.lan_like)
|
||||
return ['Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.'];
|
||||
if (lh.active && lh.bridged)
|
||||
return [
|
||||
'Internet traffic enters ',
|
||||
E('span', { class: 'dl-mono' }, lh.dev ?? ''),
|
||||
' as ',
|
||||
E('span', { class: 'dl-mono' }, lh.address ?? ''),
|
||||
', so whatever handles home traffic (proxies, filters, DNS) handles it too.',
|
||||
];
|
||||
return [
|
||||
E('span', { class: 'dl-warn' }, `Not working: ${lh.error ?? 'the link is down'}`),
|
||||
' Internet traffic goes straight to the WAN for now.',
|
||||
];
|
||||
}
|
||||
|
||||
function paint() {
|
||||
const wanSel = E(
|
||||
'select',
|
||||
{
|
||||
class: 'cbi-input-select',
|
||||
'aria-label': 'Internet interface',
|
||||
change: (ev: Event) => {
|
||||
wanDev = (ev.target as HTMLSelectElement).value;
|
||||
paint();
|
||||
},
|
||||
},
|
||||
d.devices
|
||||
.filter((x) => !x.own && !x.master && x.zone && !x.missing)
|
||||
.map((x) => E('option', { value: x.name, selected: x.name === wanDev ? 'selected' : null }, `${x.name} · zone ${x.zone}`)),
|
||||
) as HTMLSelectElement;
|
||||
|
||||
const hint = (live: string | null, saved: string) =>
|
||||
E('span', {}, [' Live: ', E('span', { class: 'dl-mono' }, live || '—'), ' · Saved: ', E('span', { class: 'dl-mono' }, saved || '—')]);
|
||||
|
||||
const groups = GROUPS.map(([cat, label]) => {
|
||||
const list = d.devices.filter((x) => x.category === cat);
|
||||
return list.length ? E('div', { class: 'dl-ifgroup' }, [E('h4', {}, label), E('div', { class: 'dl-ifgrid' }, list.map(tile))]) : '';
|
||||
});
|
||||
|
||||
const home = homeDevs();
|
||||
const nets = home.flatMap((x) => x.nets.map((n) => [n, x.name] as const));
|
||||
const dirty = snapshot() !== initial;
|
||||
const save = button(
|
||||
'Save',
|
||||
async () => {
|
||||
const r = await attempt(
|
||||
() => api.serverInterfaces(serverId, autoWan, autoWan ? '' : wanDev, autoLan, [...lans], lanLike),
|
||||
'Interfaces saved',
|
||||
);
|
||||
if (!r) return;
|
||||
take(r, true);
|
||||
if (r.nets_changed && r.lan_only)
|
||||
notify(
|
||||
`${r.lan_only} ${r.lan_only === 1 ? 'person has' : 'people have'} Home-only access: their devices need the configuration again to reach the new networks.`,
|
||||
'warning',
|
||||
10000,
|
||||
);
|
||||
},
|
||||
'positive',
|
||||
{ disabled: !dirty },
|
||||
);
|
||||
|
||||
dom.content(root, [
|
||||
E('div', { class: 'dl-setsec-body' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [
|
||||
E('h3', {}, title),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
button([icon('reset'), ' Rescan'], () => load(false), 'neutral', { title: 'Read the interfaces again' }),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-lh-main' }, [
|
||||
E('span', { class: `dl-need-ic ${likeHomeTone()}` }, icon('home')),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-setrow-label' }, 'Internet like a home device'),
|
||||
E('span', { class: 'dl-sub' }, likeHomeText()),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow-ctl dl-if-wanctl' }, [
|
||||
lanLike && d.needs?.length ? button('Install', () => installMissing('home', d.needs!, () => load(false)), 'positive') : '',
|
||||
sw(lanLike, 'Internet like a home device', (v) => {
|
||||
lanLike = v;
|
||||
paint();
|
||||
}),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-lh-main' }, [
|
||||
E('span', { class: 'dl-need-ic' }, icon('globe')),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-setrow-label' }, 'Auto-detect WAN'),
|
||||
E('span', { class: 'dl-sub' }, [
|
||||
'The interface with the default route: the server port opens there and Internet access leaves through it.',
|
||||
hint(d.detected.wan, d.saved.wan),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow-ctl dl-if-wanctl' }, [
|
||||
autoWan ? '' : wanSel,
|
||||
sw(autoWan, 'Auto-detect WAN', (v) => {
|
||||
autoWan = v;
|
||||
paint();
|
||||
}),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-lh-main' }, [
|
||||
E('span', { class: 'dl-need-ic' }, icon('network')),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-setrow-label' }, 'Auto-detect LAN'),
|
||||
E('span', { class: 'dl-sub' }, ['Adds the detected LAN to the home network.', hint(d.detected.lan, d.saved.lan)]),
|
||||
]),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-setrow-ctl' },
|
||||
sw(autoLan, 'Auto-detect LAN', (v) => {
|
||||
autoLan = v;
|
||||
paint();
|
||||
}),
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-iflead' }, [
|
||||
E('b', {}, 'Home network'),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
'What people with Home access can reach. Click to add an interface; bridge ports and Wi-Fi in a bridge come with the bridge.',
|
||||
),
|
||||
]),
|
||||
...groups,
|
||||
]),
|
||||
E('div', { class: 'dl-setsec-foot' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub dl-if-summary' },
|
||||
nets.length
|
||||
? [
|
||||
'Home access reaches ',
|
||||
...nets.flatMap(([n, dev], i) => [i ? ', ' : '', E('span', { class: 'dl-mono' }, n), ` (${dev})`]),
|
||||
lanLike ? ' · Internet like a home device' : currentWan() ? ` · Internet via ${currentWan()}` : '',
|
||||
]
|
||||
: ['No home network: Home access reaches nothing but this router.', currentWan() ? ` Internet via ${currentWan()}.` : ''],
|
||||
),
|
||||
save,
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
load(true);
|
||||
return root;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Invite card: a picture with the person's QR code, link and three steps,
|
||||
// made in the browser to share (Telegram, AirDrop) or print.
|
||||
|
||||
import type { Person } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { attempt, button, closeModal, copyText, downloadFile, modal, notify } from './ui';
|
||||
import { icon } from '../shared/icons';
|
||||
import { qrSvg } from '../shared/qr';
|
||||
|
||||
const W = 1080,
|
||||
H = 1512;
|
||||
/** One margin for everything: header, greeting and the QR tile share both edges. */
|
||||
const M = 96;
|
||||
const SANS = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
|
||||
const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!);
|
||||
|
||||
function cardSvg(p: Person, 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).
|
||||
const nameSize = Math.min(92, Math.floor((W - 2 * M) / (0.58 * (4 + p.name.length))));
|
||||
const tile = W - 2 * M,
|
||||
top = 392,
|
||||
pad = 40;
|
||||
const qr = qrSvg(link, 2).replace('<svg ', `<svg x="${M + pad}" y="${top + pad}" width="${tile - 2 * pad}" height="${tile - 2 * pad}" `);
|
||||
const text = (x: number, y: number, size: number, fill: string, body: string, extra = '') =>
|
||||
`<text x="${x}" y="${y}" font-size="${size}" fill="${fill}" font-family="${SANS}" ${extra}>${body}</text>`;
|
||||
return (
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
|
||||
`<rect width="${W}" height="${H}" rx="72" fill="#0b0b0b"/>` +
|
||||
// Mark and server name
|
||||
`<g transform="translate(${M} ${M})"><rect width="60" height="60" rx="15" fill="#fff"/>` +
|
||||
`<g transform="scale(.9375)"><path d="M14 38a18 18 0 0 1 36 0z" fill="#0b0b0b"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0b0b0b" opacity=".5"/></g></g>` +
|
||||
text(M + 82, M + 42, 36, '#a3a3a3', esc(server)) +
|
||||
// Greeting
|
||||
text(M, 276, nameSize, '#ffffff', `Hi, ${esc(p.name)}`, 'font-weight="600"') +
|
||||
text(M, 340, 40, '#8a8a8a', `Scan to connect to ${esc(server)}`) +
|
||||
// Big QR on a white tile, edge to edge with the text above
|
||||
`<rect x="${M}" y="${top}" width="${tile}" height="${tile}" rx="52" fill="#ffffff"/>` +
|
||||
qr +
|
||||
// The link: three words, then the host
|
||||
`<text x="${W / 2}" y="${top + tile + 100}" font-size="58" fill="#ffffff" font-family="${MONO}" text-anchor="middle">${esc(word)}</text>` +
|
||||
text(W / 2, top + tile + 156, 34, '#737373', esc(url.host), 'text-anchor="middle"') +
|
||||
`</svg>`
|
||||
);
|
||||
}
|
||||
|
||||
async function toPng(svg: string): Promise<Blob> {
|
||||
const img = new Image();
|
||||
img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
||||
await img.decode();
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = W;
|
||||
canvas.height = H;
|
||||
canvas.getContext('2d')!.drawImage(img, 0, 0, W, H);
|
||||
return new Promise((resolve, reject) =>
|
||||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('Could not draw the card'))), 'image/png'),
|
||||
);
|
||||
}
|
||||
|
||||
type Invitee = Pick<Person, 'id' | 'name' | 'link'> & { links?: string[] };
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
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)));
|
||||
if (!png) return;
|
||||
const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' });
|
||||
const url = URL.createObjectURL(png);
|
||||
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
|
||||
const canShare = !!nav.canShare?.({ files: [file] });
|
||||
const close = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
closeModal();
|
||||
};
|
||||
const share = canShare
|
||||
? button(
|
||||
[icon('link'), ' Share card'],
|
||||
async () => {
|
||||
try {
|
||||
await nav.share({ files: [file], title: `Invite ${p.name}` });
|
||||
} catch {
|
||||
/* cancelled */
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
)
|
||||
: button([icon('download'), ' Download card'], () => downloadFile(file.name, png), 'positive');
|
||||
modal(
|
||||
opts.title ?? `Invite ${p.name}`,
|
||||
E('div', { class: 'dl-invite' }, [
|
||||
E('img', { src: url, alt: `Invite card for ${p.name}` }),
|
||||
E('div', { class: 'dl-invite-side' }, [
|
||||
E(
|
||||
'p',
|
||||
{ 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:\/\//, '')),
|
||||
icon('copy'),
|
||||
]),
|
||||
...(p.links ?? [])
|
||||
.filter((l) => l !== link)
|
||||
.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?:\/\//, '')),
|
||||
E('span', { class: `dl-pill ${l.startsWith('http:') ? 'warn' : ''}` }, l.startsWith('http:') ? 'HTTP' : 'Also'),
|
||||
icon('copy'),
|
||||
]),
|
||||
),
|
||||
E('ol', { class: 'dl-invite-steps' }, [
|
||||
E('li', {}, ['Install ', E('b', {}, 'AmneziaVPN'), ' on the device']),
|
||||
E('li', {}, 'Open the link or scan the code'),
|
||||
E('li', {}, 'Add the device and connect'),
|
||||
]),
|
||||
E('div', { class: 'dl-invite-actions' }, [
|
||||
share,
|
||||
button([icon('copy'), ' Copy link'], () => copyText(link, 'Personal link copied')),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
[E('button', { class: 'cbi-button cbi-button-neutral', click: close }, 'Done')],
|
||||
'wide',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// 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).
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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) : '']),
|
||||
E('div', { class: 'dl-setrow-ctl' }, control),
|
||||
]);
|
||||
}
|
||||
|
||||
/** A section card with its own footer (Save etc.). */
|
||||
export function card(title: string, body: (Node | string)[], foot: (Node | string)[], extra = ''): HTMLElement {
|
||||
return E('section', { class: `dl-setsec ${extra}` }, [
|
||||
E('div', { class: 'dl-setsec-body' }, [title ? E('h3', {}, title) : '', ...body]),
|
||||
foot.length ? E('div', { class: 'dl-setsec-foot' }, foot) : '',
|
||||
]);
|
||||
}
|
||||
|
||||
/** A titled group inside a settings card: icon, title and a short line, then its rows separated by hairlines. */
|
||||
export function group(ic: string, title: string, sub: string, items: (Node | string)[]): HTMLElement {
|
||||
return E('div', { class: 'dl-group' }, [
|
||||
E('div', { class: 'dl-group-head' }, [
|
||||
E('span', { class: 'dl-group-ic' }, icon(ic)),
|
||||
E('span', { class: 'dl-stack' }, [E('b', {}, title), sub ? E('span', { class: 'dl-sub' }, sub) : '']),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-group-body' },
|
||||
items.filter((x) => x !== ''),
|
||||
),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// Activity log helpers shared by Activity, Settings, the person page and the
|
||||
// device drawer: categories, export, and the clear / reset dialogs.
|
||||
|
||||
import type { LogEvent, Status } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api, type LogCategory, type LogFilter } from './api';
|
||||
import { attempt, button, closeModal, downloadFile, modal, notify } from './ui';
|
||||
|
||||
/** Mirrors CATEGORY in dawnline.live. */
|
||||
const CATEGORY: Record<string, LogCategory> = {
|
||||
connect: 'connections',
|
||||
disconnect: 'connections',
|
||||
roam: 'connections',
|
||||
device_added: 'devices',
|
||||
device_removed: 'devices',
|
||||
devices_removed: 'devices',
|
||||
person_added: 'people',
|
||||
person_removed: 'people',
|
||||
person_changed: 'people',
|
||||
paused: 'people',
|
||||
resumed: 'people',
|
||||
paused_all: 'people',
|
||||
resumed_all: 'people',
|
||||
server_down: 'problems',
|
||||
server_up: 'problems',
|
||||
portal_blocked: 'problems',
|
||||
};
|
||||
|
||||
export const CATEGORIES: LogCategory[] = ['connections', 'devices', 'people', 'problems'];
|
||||
|
||||
export const CATEGORY_LABEL: Record<LogCategory, string> = {
|
||||
connections: 'Connections',
|
||||
devices: 'Devices',
|
||||
people: 'People',
|
||||
problems: 'Problems',
|
||||
};
|
||||
|
||||
export const CATEGORY_HELP: Record<LogCategory, string> = {
|
||||
connections: 'Connects, disconnects and IP changes',
|
||||
devices: 'Devices added and removed',
|
||||
people: 'People added, changed, paused',
|
||||
problems: 'Tunnel down, blocked portal sign-ins',
|
||||
};
|
||||
|
||||
export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems';
|
||||
|
||||
function names(st: Pick<Status, 'people'>) {
|
||||
const people = new Map(st.people.map((p) => [p.id, p.name]));
|
||||
const devices = new Map(st.people.flatMap((p) => p.devices.map((d) => [d.id, d.name] as [string, string])));
|
||||
return { people, devices };
|
||||
}
|
||||
|
||||
function csvCell(v: unknown): string {
|
||||
const s = v == null ? '' : String(v);
|
||||
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||
}
|
||||
|
||||
/** Download events as CSV or JSON (person and device names resolved). */
|
||||
export function exportEvents(st: Pick<Status, 'people'>, events: LogEvent[], format: 'csv' | 'json', suffix = '') {
|
||||
const n = names(st);
|
||||
const rows = events.map((e) => ({
|
||||
time: new Date(e.ts * 1000).toISOString(),
|
||||
category: categoryOf(e.type),
|
||||
type: e.type,
|
||||
person: e.person ? (n.people.get(e.person) ?? e.person) : '',
|
||||
device: e.device ? (n.devices.get(e.device) ?? e.device) : '',
|
||||
detail: e.detail ?? '',
|
||||
where: e.where ?? '',
|
||||
}));
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
const name = `dawnline-activity${suffix ? `-${suffix}` : ''}-${stamp}.${format}`;
|
||||
if (format === 'json') {
|
||||
downloadFile(name, JSON.stringify(rows, null, 2), 'application/json');
|
||||
return;
|
||||
}
|
||||
const cols = ['time', 'category', 'type', 'person', 'device', 'detail', 'where'] as const;
|
||||
const csv = [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
|
||||
downloadFile(name, csv, 'text/csv');
|
||||
}
|
||||
|
||||
const AGES: [string, string][] = [
|
||||
['', 'Everything'],
|
||||
['7', 'Older than 7 days'],
|
||||
['30', 'Older than 30 days'],
|
||||
['90', 'Older than 90 days'],
|
||||
];
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function clearLogDialog(title: string, what: string, base: LogFilter, done: () => unknown, category?: LogCategory) {
|
||||
const cat = E('select', { class: 'cbi-input-select' }, [
|
||||
E('option', { value: '' }, 'All categories'),
|
||||
...CATEGORIES.map((c) => E('option', { value: c, selected: c === category ? 'selected' : null }, CATEGORY_LABEL[c])),
|
||||
]) as HTMLSelectElement;
|
||||
const age = E(
|
||||
'select',
|
||||
{ class: 'cbi-input-select' },
|
||||
AGES.map(([v, t]) => E('option', { value: v }, t)),
|
||||
) as HTMLSelectElement;
|
||||
modal(
|
||||
title,
|
||||
[
|
||||
E('p', { class: 'dl-muted' }, `${what} This cannot be undone; export first if you want a copy.`),
|
||||
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Category'), cat]),
|
||||
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'),
|
||||
' ',
|
||||
button(
|
||||
'Clear',
|
||||
async () => {
|
||||
const r = await attempt(() => api.logsClear({ ...base, category: cat.value, older_days: age.value }));
|
||||
if (!r) return;
|
||||
closeModal();
|
||||
notify(r.removed ? `${r.removed} event${r.removed === 1 ? '' : 's'} removed` : 'Nothing matched', 'success', 3000);
|
||||
done();
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/** Confirm and reset traffic history for everyone, a person or a device. */
|
||||
export function resetUsageDialog(scope: 'all' | 'person' | 'device', id: string, label: string, done: () => unknown) {
|
||||
const body =
|
||||
scope === 'device'
|
||||
? `Clears ${label}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`
|
||||
: scope === 'person'
|
||||
? `Clears ${label}'s traffic history and that of their devices. Their data limit starts again from zero.`
|
||||
: 'Clears traffic history for everyone. Data limits start again from zero.';
|
||||
modal(
|
||||
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'),
|
||||
' ',
|
||||
button(
|
||||
'Reset',
|
||||
async () => {
|
||||
if (!(await attempt(() => api.usageClear(scope, id), 'Traffic history reset'))) return;
|
||||
closeModal();
|
||||
done();
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
Vendored
+129
@@ -0,0 +1,129 @@
|
||||
// Minimal typings for the parts of the LuCI client SDK (luci.js / ui.js /
|
||||
// rpc.js / poll.js / dom.js) that Dawnline uses. The module is evaluated by
|
||||
// LuCI's loader, which injects the `'require'`d classes as these identifiers.
|
||||
|
||||
type Child = Node | string | number | null | undefined | false | Child[];
|
||||
|
||||
interface ElementAttrs {
|
||||
[key: string]: unknown;
|
||||
class?: string;
|
||||
style?: string;
|
||||
click?: (ev: MouseEvent) => void;
|
||||
change?: (ev: Event) => void;
|
||||
input?: (ev: Event) => void;
|
||||
keydown?: (ev: KeyboardEvent) => void;
|
||||
}
|
||||
|
||||
interface LuciWidget {
|
||||
render(): Node | Promise<Node>;
|
||||
getValue(): any;
|
||||
setValue(v: any): void;
|
||||
isValid(): boolean;
|
||||
triggerValidation(): void;
|
||||
setChangeEvents?(node: Node, ...events: string[]): void;
|
||||
node?: HTMLElement;
|
||||
}
|
||||
|
||||
interface WidgetOptions {
|
||||
id?: string;
|
||||
name?: string;
|
||||
optional?: boolean;
|
||||
datatype?: string;
|
||||
placeholder?: string;
|
||||
validate?: (value: string) => true | string;
|
||||
disabled?: boolean;
|
||||
readonly?: boolean;
|
||||
widget?: 'select' | 'radio' | 'checkbox';
|
||||
sort?: boolean | string[];
|
||||
create?: boolean;
|
||||
multiple?: boolean;
|
||||
size?: number;
|
||||
rows?: number;
|
||||
cols?: number;
|
||||
monospace?: boolean;
|
||||
password?: boolean;
|
||||
value_enabled?: string;
|
||||
value_disabled?: string;
|
||||
hiddenname?: string;
|
||||
}
|
||||
|
||||
interface LuciUI {
|
||||
showModal(title: string | null, children: Child, ...classes: string[]): HTMLElement;
|
||||
hideModal(): void;
|
||||
addNotification(title: string | null, children: Child, ...classes: string[]): HTMLElement;
|
||||
addTimeLimitedNotification(title: string | null, children: Child, timeout?: number, ...classes: string[]): HTMLElement;
|
||||
changes: any;
|
||||
itemlist(node: Node, items: unknown[], separators?: unknown): HTMLElement;
|
||||
createHandlerFn(ctx: unknown, fn: string | ((...args: any[]) => unknown), ...args: unknown[]): (ev: Event) => void;
|
||||
Textfield: new (value: string | null, options?: WidgetOptions) => LuciWidget;
|
||||
Textarea: new (value: string | null, options?: WidgetOptions) => LuciWidget;
|
||||
Select: new (value: string | string[] | null, choices: Record<string, string | Node>, options?: WidgetOptions) => LuciWidget;
|
||||
Checkbox: new (value: string | null, options?: WidgetOptions) => LuciWidget;
|
||||
DynamicList: new (values: string[] | null, choices?: Record<string, string>, options?: WidgetOptions) => LuciWidget;
|
||||
Dropdown: new (value: string | string[] | null, choices: Record<string, string | Node>, options?: WidgetOptions) => LuciWidget;
|
||||
}
|
||||
|
||||
interface LuciRpc {
|
||||
declare<T = any>(spec: {
|
||||
object: string;
|
||||
method: string;
|
||||
params?: string[];
|
||||
expect?: Record<string, unknown>;
|
||||
filter?: (data: any, args: unknown[], ...extra: unknown[]) => any;
|
||||
reject?: boolean;
|
||||
}): (...args: any[]) => Promise<T>;
|
||||
}
|
||||
|
||||
interface LuciPoll {
|
||||
add(fn: () => unknown, interval?: number): boolean;
|
||||
remove(fn: () => unknown): boolean;
|
||||
start(): void;
|
||||
stop(): void;
|
||||
active(): boolean;
|
||||
}
|
||||
|
||||
interface LuciDom {
|
||||
content(node: Node, children: Child): Node;
|
||||
findClassInstance(node: Node): any;
|
||||
append(node: Node, children: Child): Node;
|
||||
isEmpty(node: Node): boolean;
|
||||
}
|
||||
|
||||
interface LuciEnv {
|
||||
sessionid?: string;
|
||||
rpctimeout?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface LuciL {
|
||||
env: LuciEnv;
|
||||
url(...parts: string[]): string;
|
||||
resolveDefault<T>(p: Promise<T>, def: T): Promise<T>;
|
||||
resource(...parts: string[]): string;
|
||||
itemlist(node: Node, items: unknown[], separators?: unknown): HTMLElement;
|
||||
bind<F extends (...args: any[]) => any>(fn: F, self: unknown, ...args: unknown[]): F;
|
||||
raise(type: string, fmt: string, ...args: unknown[]): never;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface String {
|
||||
format(...args: unknown[]): string;
|
||||
}
|
||||
|
||||
const E: (tag: string, attrs?: ElementAttrs | Child, children?: Child) => HTMLElement;
|
||||
const _: (msg: string, ctx?: string) => string;
|
||||
const N_: (n: number, singular: string, plural: string, ctx?: string) => string;
|
||||
const L: LuciL;
|
||||
const ui: LuciUI;
|
||||
const rpc: LuciRpc;
|
||||
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 };
|
||||
@@ -0,0 +1,51 @@
|
||||
// LuCI module `dawnline.app`: one factory per admin view. The thin files in
|
||||
// view/dawnline/*.js do `return view.extend(app.<page>())`.
|
||||
|
||||
import { PeoplePage } from './pages/people';
|
||||
import { ServerPage } from './pages/server';
|
||||
import { SettingsPage } from './pages/settings';
|
||||
import { HealthPage, UpdatesPage } from './pages/maintenance';
|
||||
import { PersonPage } from './pages/person';
|
||||
import { ActivityPage } from './pages/activity';
|
||||
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. */
|
||||
noFooter?: boolean;
|
||||
}
|
||||
|
||||
function factory<P extends Page>(Cls: new () => P, formBased: boolean) {
|
||||
return () => {
|
||||
const page = new Cls();
|
||||
const v: Record<string, unknown> = {
|
||||
load: () => page.load(),
|
||||
render: async (data: unknown) => {
|
||||
const node = await page.render(data);
|
||||
const root = document.createElement('div');
|
||||
root.className = 'dl-root';
|
||||
root.append(styleNode(), node);
|
||||
return root;
|
||||
},
|
||||
addFooter(this: any) {
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
// 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 activity = factory(ActivityPage, false);
|
||||
const health = factory(HealthPage, false);
|
||||
const updates = factory(UpdatesPage, false);
|
||||
|
||||
export { overview, people, person, activity, server, settings, health, updates };
|
||||
@@ -0,0 +1,476 @@
|
||||
// Connection map: MapLibre GL with a CARTO basemap (light or dark, following
|
||||
// the Outline theme), the router as origin, one marker per device and an arc
|
||||
// from the router to each one — solid and animated while the tunnel is live,
|
||||
// dashed for recently seen. MapLibre loads from a CDN on first use.
|
||||
|
||||
import type { Geo, GeoPoint, Person } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { ago } from '../shared/format';
|
||||
import { icon, iconSvg } from '../shared/icons';
|
||||
|
||||
const MAPLIBRE = 'https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl';
|
||||
const STYLE_DARK = 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json';
|
||||
const STYLE_LIGHT = 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json';
|
||||
|
||||
export type Range = 'online' | '24h' | '7d' | '30d';
|
||||
const WINDOW: Record<Range, number> = { online: 0, '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 };
|
||||
|
||||
let loading: Promise<any> | null = null;
|
||||
|
||||
/**
|
||||
* Load MapLibre once; tags go inside `host` so Outline's router is not
|
||||
* disturbed. The stylesheet goes into every map's own container: Outline
|
||||
* drops the previous page's DOM on navigation (and with it a shared link),
|
||||
* and without it HTML markers lose their positioning and vanish.
|
||||
*/
|
||||
function loadMapLibre(host: HTMLElement): Promise<any> {
|
||||
const w = window as any;
|
||||
host.appendChild(E('link', { rel: 'stylesheet', href: `${MAPLIBRE}.css` }));
|
||||
if (w.maplibregl) return Promise.resolve(w.maplibregl);
|
||||
if (loading) return loading;
|
||||
loading = new Promise((resolve, reject) => {
|
||||
const s = E('script', { src: `${MAPLIBRE}.js` }) as HTMLScriptElement;
|
||||
s.onload = () => (w.maplibregl ? resolve(w.maplibregl) : reject(new Error('MapLibre failed to load')));
|
||||
s.onerror = () => {
|
||||
loading = null;
|
||||
reject(new Error('Could not load the map library (no internet access from this browser?)'));
|
||||
};
|
||||
host.appendChild(s);
|
||||
});
|
||||
return loading;
|
||||
}
|
||||
|
||||
function isDark(): boolean {
|
||||
const attr = document.documentElement.getAttribute('data-darkmode');
|
||||
if (attr != null) return attr === 'true';
|
||||
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false;
|
||||
}
|
||||
|
||||
/** A gentle arc between two [lng, lat] points (quadratic Bézier in map space). */
|
||||
function arc(a: [number, number], b: [number, number], steps = 48): [number, number][] {
|
||||
const mx = (a[0] + b[0]) / 2;
|
||||
const my = (a[1] + b[1]) / 2;
|
||||
const dx = b[0] - a[0];
|
||||
const dy = b[1] - a[1];
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
// Bend to the left of the direction of travel, proportional to distance.
|
||||
const k = Math.min(0.25 * len, 12);
|
||||
const cx = mx - (dy / len) * k;
|
||||
const cy = my + (dx / len) * k;
|
||||
const out: [number, number][] = [];
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const t = i / steps;
|
||||
const u = 1 - t;
|
||||
out.push([u * u * a[0] + 2 * u * t * cx + t * t * b[0], u * u * a[1] + 2 * u * t * cy + t * t * b[1]]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface MapCallbacks {
|
||||
openPerson: (personId: string) => void;
|
||||
openDevice: (personId: string, deviceId: string) => void;
|
||||
}
|
||||
|
||||
export interface MapData {
|
||||
geo: Geo;
|
||||
people: Person[];
|
||||
now: number;
|
||||
/** Restrict to one person (person page). */
|
||||
person?: string;
|
||||
}
|
||||
|
||||
/** Latest point per device inside the time window. */
|
||||
export function visiblePoints(data: MapData, range: Range): GeoPoint[] {
|
||||
const best = new Map<string, GeoPoint>();
|
||||
for (const p of data.geo.points) {
|
||||
if (data.person && p.person !== data.person) continue;
|
||||
if (range === 'online' ? !p.online : data.now - p.ts > WINDOW[range]) continue;
|
||||
const cur = best.get(p.device);
|
||||
if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(p.device, p);
|
||||
}
|
||||
return [...best.values()];
|
||||
}
|
||||
|
||||
export class ConnectionMap {
|
||||
private map: any = null;
|
||||
private gl: any = null;
|
||||
private markers: any[] = [];
|
||||
private popup: any = null;
|
||||
private anim = 0;
|
||||
private data: MapData | null = null;
|
||||
private range: Range;
|
||||
private fitted = false;
|
||||
readonly el: HTMLElement;
|
||||
private status: HTMLElement;
|
||||
|
||||
constructor(
|
||||
private cb: MapCallbacks,
|
||||
range: Range = 'online',
|
||||
height = 380,
|
||||
) {
|
||||
this.range = range;
|
||||
this.status = E('div', { class: 'dl-map-status' });
|
||||
this.el = E('div', { class: 'dl-geomap', style: `height:${height}px` }, this.status);
|
||||
}
|
||||
|
||||
async mount(data: MapData) {
|
||||
this.data = data;
|
||||
try {
|
||||
this.gl = await loadMapLibre(this.el);
|
||||
} catch (e) {
|
||||
this.status.textContent = (e as Error).message;
|
||||
return;
|
||||
}
|
||||
this.map = new this.gl.Map({
|
||||
container: this.el,
|
||||
style: isDark() ? STYLE_DARK : STYLE_LIGHT,
|
||||
center: [data.geo.home?.lon ?? 20, data.geo.home?.lat ?? 50],
|
||||
zoom: 3,
|
||||
attributionControl: { compact: true },
|
||||
dragRotate: false,
|
||||
pitchWithRotate: false,
|
||||
cooperativeGestures: true,
|
||||
});
|
||||
this.map.addControl(new this.gl.NavigationControl({ showCompass: false }), 'bottom-right');
|
||||
this.map.on('load', () => {
|
||||
// City-level accuracy: a soft zone instead of a precise pin.
|
||||
this.map.addSource('dl-areas', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||
this.map.addLayer({
|
||||
id: 'dl-area',
|
||||
type: 'circle',
|
||||
source: 'dl-areas',
|
||||
paint: {
|
||||
'circle-radius': ['interpolate', ['exponential', 2], ['zoom'], 2, 6, 6, 26, 9, 140, 12, 900],
|
||||
'circle-color': ['case', ['get', 'online'], '#40c977', isDark() ? '#ededed' : '#0d0d0d'],
|
||||
'circle-opacity': ['case', ['get', 'online'], 0.12, 0.06],
|
||||
'circle-stroke-width': 1,
|
||||
'circle-stroke-color': ['case', ['get', 'online'], '#40c977', isDark() ? '#ededed' : '#0d0d0d'],
|
||||
'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.15],
|
||||
},
|
||||
});
|
||||
this.map.addSource('dl-arcs', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||
this.map.addLayer({
|
||||
id: 'dl-arc-recent',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], false],
|
||||
layout: { 'line-cap': 'round' },
|
||||
paint: { 'line-color': isDark() ? '#ededed' : '#0d0d0d', 'line-opacity': 0.35, 'line-width': 1.5, 'line-dasharray': [2, 3] },
|
||||
});
|
||||
this.map.addLayer({
|
||||
id: 'dl-arc-glow',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], true],
|
||||
layout: { 'line-cap': 'round' },
|
||||
paint: { 'line-color': '#40c977', 'line-opacity': 0.18, 'line-width': 7 },
|
||||
});
|
||||
this.map.addLayer({
|
||||
id: 'dl-arc-live',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], true],
|
||||
layout: { 'line-cap': 'round' },
|
||||
paint: { 'line-color': '#40c977', 'line-width': 2 },
|
||||
});
|
||||
this.map.addLayer({
|
||||
id: 'dl-arc-flow',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], true],
|
||||
layout: { 'line-cap': 'round' },
|
||||
paint: { 'line-color': '#ffffff', 'line-width': 2, 'line-opacity': 0.8, 'line-dasharray': [0, 4, 3] },
|
||||
});
|
||||
this.animate();
|
||||
this.draw();
|
||||
});
|
||||
}
|
||||
|
||||
setRange(r: Range) {
|
||||
this.range = r;
|
||||
this.fitted = false;
|
||||
this.draw();
|
||||
}
|
||||
|
||||
update(data: MapData) {
|
||||
this.data = data;
|
||||
this.draw();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
cancelAnimationFrame(this.anim);
|
||||
this.map?.remove();
|
||||
this.map = null;
|
||||
}
|
||||
|
||||
/** Moving highlight along live arcs (MapLibre "animated line" technique). */
|
||||
private animate() {
|
||||
const seq = [
|
||||
[0, 4, 3],
|
||||
[0.5, 4, 2.5],
|
||||
[1, 4, 2],
|
||||
[1.5, 4, 1.5],
|
||||
[2, 4, 1],
|
||||
[2.5, 4, 0.5],
|
||||
[3, 4, 0],
|
||||
[0, 0.5, 3, 3.5],
|
||||
[0, 1, 3, 3],
|
||||
[0, 1.5, 3, 2.5],
|
||||
[0, 2, 3, 2],
|
||||
[0, 2.5, 3, 1.5],
|
||||
[0, 3, 3, 1],
|
||||
[0, 3.5, 3, 0.5],
|
||||
];
|
||||
let step = -1;
|
||||
let last = 0;
|
||||
const tick = (t: number) => {
|
||||
if (!this.map) return;
|
||||
if (t - last > 70) {
|
||||
last = t;
|
||||
step = (step + 1) % seq.length;
|
||||
if (this.map.getLayer('dl-arc-flow')) this.map.setPaintProperty('dl-arc-flow', 'line-dasharray', seq[step]);
|
||||
}
|
||||
this.anim = requestAnimationFrame(tick);
|
||||
};
|
||||
this.anim = requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
/** Devices grouped by network operator and city: one marker per group. */
|
||||
private groups(pts: GeoPoint[]): Group[] {
|
||||
const map = new Map<string, Group>();
|
||||
for (const p of pts) {
|
||||
const key = `${p.asn || p.org || p.ip}|${p.city}|${p.cc}`;
|
||||
let g = map.get(key);
|
||||
if (!g) {
|
||||
g = {
|
||||
key,
|
||||
lat: p.lat,
|
||||
lon: p.lon,
|
||||
city: p.city,
|
||||
country: p.country,
|
||||
cc: p.cc,
|
||||
asn: p.asn,
|
||||
org: p.org,
|
||||
online: false,
|
||||
ts: 0,
|
||||
points: [],
|
||||
};
|
||||
map.set(key, g);
|
||||
}
|
||||
g.points.push(p);
|
||||
g.online ||= p.online;
|
||||
g.ts = Math.max(g.ts, p.ts);
|
||||
}
|
||||
return [...map.values()];
|
||||
}
|
||||
|
||||
private draw() {
|
||||
if (!this.map || !this.data || !this.map.getSource('dl-arcs')) return;
|
||||
const data = this.data;
|
||||
const groups = this.groups(visiblePoints(data, this.range));
|
||||
const home = data.geo.home;
|
||||
for (const m of this.markers) m.remove();
|
||||
this.markers = [];
|
||||
|
||||
// Operators in the same city sit side by side so every marker stays clickable.
|
||||
const perCity = new Map<string, number>();
|
||||
const placed = groups.map((g) => {
|
||||
const c = `${g.lat.toFixed(2)},${g.lon.toFixed(2)}`;
|
||||
const n = perCity.get(c) ?? 0;
|
||||
perCity.set(c, n + 1);
|
||||
return { g, at: [g.lon + n * 0.25, g.lat] as [number, number] };
|
||||
});
|
||||
|
||||
this.map.getSource('dl-areas').setData({
|
||||
type: 'FeatureCollection',
|
||||
features: placed.map(({ g, at }) => ({
|
||||
type: 'Feature',
|
||||
properties: { online: g.online },
|
||||
geometry: { type: 'Point', coordinates: at },
|
||||
})),
|
||||
});
|
||||
this.map.getSource('dl-arcs').setData({
|
||||
type: 'FeatureCollection',
|
||||
features: home
|
||||
? placed.map(({ g, at }) => ({
|
||||
type: 'Feature',
|
||||
properties: { online: g.online },
|
||||
geometry: { type: 'LineString', coordinates: arc([home.lon, home.lat], at) },
|
||||
}))
|
||||
: [],
|
||||
});
|
||||
|
||||
if (home) {
|
||||
const el = E('div', {
|
||||
class: 'dl-mk-home',
|
||||
title: `Home router${home.city ? ` · ${home.city}` : ''}${home.org ? ` · ${home.org}` : ''}`,
|
||||
});
|
||||
el.innerHTML = iconSvg('home', 'dl-mk-home-ic');
|
||||
this.markers.push(new this.gl.Marker({ element: el }).setLngLat([home.lon, home.lat]).addTo(this.map));
|
||||
}
|
||||
|
||||
for (const { g, at } of placed) {
|
||||
const n = g.points.length;
|
||||
const el = E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-mk${g.online ? ' online' : ''}${n > 1 ? ' multi' : ''}`,
|
||||
'aria-label': `${n} device${n === 1 ? '' : 's'} via ${g.org || 'unknown network'} in ${g.city || 'unknown city'}`,
|
||||
},
|
||||
n > 1 ? E('span', { class: 'dl-mk-count' }, String(n)) : E('span', { class: 'dl-mk-dot' }),
|
||||
);
|
||||
const nearHome = !!home && Math.abs(at[0] - home.lon) < 0.02 && Math.abs(at[1] - home.lat) < 0.02;
|
||||
const shift: [number, number] = nearHome ? [22, -16] : [0, 0];
|
||||
el.addEventListener('click', (ev) => {
|
||||
ev.stopPropagation();
|
||||
this.openPopup(g, at, shift);
|
||||
});
|
||||
this.markers.push(new this.gl.Marker({ element: el, offset: shift }).setLngLat(at).addTo(this.map));
|
||||
}
|
||||
|
||||
if (!this.fitted) {
|
||||
const coords: [number, number][] = placed.map((x) => x.at);
|
||||
if (home && (coords.length === 0 || this.range !== 'online' || placed.some((x) => x.g.online))) coords.push([home.lon, home.lat]);
|
||||
this.fit(coords);
|
||||
this.fitted = true;
|
||||
}
|
||||
this.status.textContent = placed.length || home ? '' : 'No locations yet';
|
||||
this.status.style.display = this.status.textContent ? '' : 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* Zoom to what matters: a single city fills the map at city level, a few
|
||||
* places get just enough room, and lone outliers never shrink everything to
|
||||
* a continent (the farthest 10% are left out when the rest are clustered).
|
||||
*/
|
||||
private fit(coords: [number, number][]) {
|
||||
if (!coords.length) return;
|
||||
const km = (a: [number, number], b: [number, number]) => {
|
||||
const r = Math.PI / 180;
|
||||
const dLat = (b[1] - a[1]) * r,
|
||||
dLon = (b[0] - a[0]) * r;
|
||||
const h = Math.sin(dLat / 2) ** 2 + Math.cos(a[1] * r) * Math.cos(b[1] * r) * Math.sin(dLon / 2) ** 2;
|
||||
return 12742 * Math.asin(Math.sqrt(h));
|
||||
};
|
||||
const center: [number, number] = [
|
||||
coords.reduce((s, c) => s + c[0], 0) / coords.length,
|
||||
coords.reduce((s, c) => s + c[1], 0) / coords.length,
|
||||
];
|
||||
let pts = coords;
|
||||
if (coords.length >= 5) {
|
||||
const sorted = [...coords].sort((a, b) => km(center, a) - km(center, b));
|
||||
pts = sorted.slice(0, Math.ceil(sorted.length * 0.9));
|
||||
}
|
||||
const spread = Math.max(...pts.map((c) => km(center, c)));
|
||||
if (spread < 25) {
|
||||
// Everyone in one city: show the city, accuracy zones included.
|
||||
this.map.jumpTo({ center, zoom: 9.5 });
|
||||
return;
|
||||
}
|
||||
const b = new this.gl.LngLatBounds(pts[0], pts[0]);
|
||||
pts.forEach((c) => b.extend(c));
|
||||
const h = this.el.clientHeight || 380;
|
||||
this.map.fitBounds(b, {
|
||||
padding: { top: Math.min(90, h / 4), bottom: Math.min(70, h / 5), left: 60, right: 60 },
|
||||
maxZoom: 9,
|
||||
duration: 0,
|
||||
});
|
||||
}
|
||||
|
||||
private openPopup(g: Group, at: [number, number], shift: [number, number] = [0, 0]) {
|
||||
const data = this.data!;
|
||||
this.popup?.remove();
|
||||
const where = [g.city, g.cc || g.country].filter(Boolean).join(', ');
|
||||
const people = [...new Set(g.points.map((p) => p.person))];
|
||||
const rows = g.points
|
||||
.sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts)
|
||||
.map((p) => {
|
||||
const person = data.people.find((x) => x.id === p.person);
|
||||
const dev = person?.devices.find((d) => d.id === p.device);
|
||||
return E('button', { type: 'button', class: 'dl-pop-row', click: () => this.cb.openDevice(p.person, p.device) }, [
|
||||
E('span', { class: `dl-pop-dot${p.online ? ' on' : ''}` }),
|
||||
E('span', { class: 'dl-pop-name' }, [E('b', {}, person?.name ?? p.person), ` · ${dev?.name ?? 'device'}`]),
|
||||
E('span', { class: 'dl-faint dl-nowrap' }, p.online ? 'now' : ago(p.ts, data.now)),
|
||||
]);
|
||||
});
|
||||
const body = E('div', { class: 'dl-pop' }, [
|
||||
E('div', { class: 'dl-pop-head' }, [
|
||||
E('span', { class: 'dl-pop-net' }, icon('globe')),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('strong', {}, g.org || 'Unknown network'),
|
||||
E('span', { class: 'dl-faint' }, [g.asn ? `AS${g.asn} · ` : '', where ? `${where} · approximate` : 'approximate location']),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-pop-list' }, rows),
|
||||
people.length === 1
|
||||
? E('div', { class: 'dl-pop-actions' }, [
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'cbi-button cbi-button-positive important', click: () => this.cb.openPerson(people[0]) },
|
||||
`Open ${data.people.find((x) => x.id === people[0])?.name ?? 'person'}`,
|
||||
),
|
||||
])
|
||||
: '',
|
||||
]);
|
||||
// Make room above the marker so the popup is never cut by the map edge.
|
||||
const h = this.el.clientHeight || 380;
|
||||
this.map.easeTo({ center: at, offset: [0, Math.min(140, h * 0.32)], duration: 300 });
|
||||
this.popup = new this.gl.Popup({
|
||||
offset: [shift[0], shift[1] - 18],
|
||||
anchor: 'bottom',
|
||||
closeButton: false,
|
||||
focusAfterOpen: false,
|
||||
maxWidth: '300px',
|
||||
className: 'dl-popup',
|
||||
})
|
||||
.setLngLat(at)
|
||||
.setDOMContent(body)
|
||||
.addTo(this.map);
|
||||
}
|
||||
}
|
||||
|
||||
interface Group {
|
||||
key: string;
|
||||
lat: number;
|
||||
lon: number;
|
||||
city: string;
|
||||
country: string;
|
||||
cc: string;
|
||||
asn: number;
|
||||
org: string;
|
||||
online: boolean;
|
||||
ts: number;
|
||||
points: GeoPoint[];
|
||||
}
|
||||
|
||||
/** Segmented range control for the map header. */
|
||||
export function rangeControl(initial: Range, onChange: (r: Range) => void, online = true): HTMLElement {
|
||||
const opts: [Range, string][] = [
|
||||
['online', 'Online now'],
|
||||
['24h', '24h'],
|
||||
['7d', '7 days'],
|
||||
['30d', '30 days'],
|
||||
];
|
||||
const el = E('div', { class: 'dl-seg', role: 'tablist' });
|
||||
for (const [v, label] of opts) {
|
||||
if (v === 'online' && !online) continue;
|
||||
el.appendChild(
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
class: v === initial ? 'on' : '',
|
||||
'data-v': v,
|
||||
click: () => {
|
||||
el.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.v === v));
|
||||
onChange(v);
|
||||
},
|
||||
},
|
||||
label,
|
||||
),
|
||||
);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// Activity: the full event log, grouped by day, with filters, search,
|
||||
// export and clearing.
|
||||
|
||||
import type { LogEvent, Status } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { api, type LogCategory, type LogsInfo } from '../api';
|
||||
import { button, dropdown } from '../ui';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { installPalette } from '../palette';
|
||||
import { CATEGORIES, CATEGORY_LABEL, categoryOf, clearLogDialog, exportEvents } from '../logs';
|
||||
import { eventRow, eventText } from './overview';
|
||||
|
||||
type Kind = 'all' | LogCategory;
|
||||
type Loaded = [Status, Awaited<ReturnType<typeof api.events>>];
|
||||
|
||||
/** Rows painted at a time; "Show more" adds another page. */
|
||||
const PAGE = 300;
|
||||
|
||||
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 class ActivityPage {
|
||||
st!: Status;
|
||||
events: LogEvent[] = [];
|
||||
policy!: LogsInfo['policy'];
|
||||
kind: Kind = 'all';
|
||||
query = '';
|
||||
shown = PAGE;
|
||||
list = E('div', {});
|
||||
sub = E('span', { class: 'dl-muted' });
|
||||
tabs = E('div', { class: 'dl-seg', role: 'tablist' });
|
||||
|
||||
async load(): Promise<Loaded> {
|
||||
return Promise.all([api.status(1), api.events(20000)]);
|
||||
}
|
||||
|
||||
render([st, ev]: Loaded): HTMLElement {
|
||||
this.st = st;
|
||||
this.take(ev);
|
||||
installPalette(st);
|
||||
const search = E('input', {
|
||||
type: 'search',
|
||||
class: 'dl-search-input',
|
||||
placeholder: 'Search people, devices, IPs',
|
||||
input: (e: Event) => {
|
||||
this.query = (e.target as HTMLInputElement).value.trim().toLowerCase();
|
||||
this.shown = PAGE;
|
||||
this.paint();
|
||||
},
|
||||
});
|
||||
const exp = button([icon('download'), ' Export'], () =>
|
||||
dropdown(exp, [
|
||||
{
|
||||
label: 'CSV (spreadsheet)',
|
||||
icon: icon('download'),
|
||||
run: () => exportEvents(this.st, this.filtered().reverse(), 'csv', this.kind === 'all' ? '' : this.kind),
|
||||
},
|
||||
{
|
||||
label: 'JSON',
|
||||
icon: icon('download'),
|
||||
run: () => exportEvents(this.st, this.filtered().reverse(), 'json', this.kind === 'all' ? '' : this.kind),
|
||||
},
|
||||
]),
|
||||
);
|
||||
const clear = button([icon('trash'), ' Clear'], () =>
|
||||
clearLogDialog(
|
||||
'Clear activity',
|
||||
'Removes events from the log on the router.',
|
||||
{},
|
||||
() => this.reload(),
|
||||
this.kind === 'all' ? undefined : this.kind,
|
||||
),
|
||||
);
|
||||
this.paint();
|
||||
poll.add(async () => {
|
||||
const r = await api.events(20000).catch(() => null);
|
||||
if (r) {
|
||||
this.take(r);
|
||||
this.paint();
|
||||
}
|
||||
}, 15);
|
||||
return E('div', {}, [
|
||||
E('div', { class: 'dl-pagehead' }, [
|
||||
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Activity'), this.sub]),
|
||||
E('div', { class: 'dl-row-actions' }, [exp, clear]),
|
||||
]),
|
||||
E('div', { class: 'dl-toolbar' }, [
|
||||
this.tabs,
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('label', { class: 'dl-search' }, [icon('search'), search]),
|
||||
]),
|
||||
this.list,
|
||||
]);
|
||||
}
|
||||
|
||||
take(r: Awaited<ReturnType<typeof api.events>>) {
|
||||
this.events = r.events;
|
||||
this.policy = r.policy;
|
||||
const off = CATEGORIES.filter((c) => !r.policy.categories.includes(c));
|
||||
this.sub.textContent = `${retentionText(r.policy)}${off.length ? ` Not recorded: ${off.map((c) => CATEGORY_LABEL[c].toLowerCase()).join(', ')}.` : ''}`;
|
||||
}
|
||||
|
||||
async reload() {
|
||||
const r = await api.events(20000).catch(() => null);
|
||||
if (r) {
|
||||
this.take(r);
|
||||
this.paint();
|
||||
}
|
||||
}
|
||||
|
||||
/** Newest first, matching the current tab and search. */
|
||||
filtered(): LogEvent[] {
|
||||
return [...this.events].reverse().filter((e) => {
|
||||
if (this.kind !== 'all' && categoryOf(e.type) !== this.kind) return false;
|
||||
if (!this.query) return true;
|
||||
const text = eventText(this.st, e)
|
||||
.map((n) => n.textContent ?? '')
|
||||
.join(' ');
|
||||
return `${text} ${e.detail ?? ''} ${e.where ?? ''}`.toLowerCase().includes(this.query);
|
||||
});
|
||||
}
|
||||
|
||||
paintTabs() {
|
||||
const count = (k: Kind) => (k === 'all' ? this.events.length : this.events.filter((e) => categoryOf(e.type) === k).length);
|
||||
dom.content(
|
||||
this.tabs,
|
||||
(['all', ...CATEGORIES] as Kind[]).map((k) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
class: k === this.kind ? 'on' : '',
|
||||
click: () => {
|
||||
this.kind = k;
|
||||
this.shown = PAGE;
|
||||
this.paint();
|
||||
},
|
||||
},
|
||||
[k === 'all' ? 'All' : CATEGORY_LABEL[k], E('b', {}, String(count(k)))],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
paint() {
|
||||
this.paintTabs();
|
||||
const evs = this.filtered();
|
||||
if (!evs.length) {
|
||||
dom.content(this.list, E('div', { class: 'dl-empty' }, [E('p', {}, this.events.length ? 'No events match.' : 'The log is empty.')]));
|
||||
return;
|
||||
}
|
||||
const groups: HTMLElement[] = [];
|
||||
let day = '';
|
||||
let panel: HTMLElement | null = null;
|
||||
for (const e of evs.slice(0, this.shown)) {
|
||||
const t = dayTitle(e.ts);
|
||||
if (t !== day) {
|
||||
day = t;
|
||||
panel = E('div', { class: 'dl-panel flush' }, E('div', { class: 'dl-panel-head pad' }, E('h3', {}, t)));
|
||||
groups.push(panel);
|
||||
}
|
||||
const row = eventRow(this.st, e);
|
||||
row.lastElementChild!.textContent = new Date(e.ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
|
||||
panel!.appendChild(row);
|
||||
}
|
||||
if (evs.length > this.shown)
|
||||
groups.push(
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-more-row' },
|
||||
button(`Show ${Math.min(PAGE, evs.length - this.shown)} more of ${evs.length - this.shown}`, () => {
|
||||
this.shown += PAGE;
|
||||
this.paint();
|
||||
}),
|
||||
),
|
||||
);
|
||||
dom.content(this.list, groups);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// Health and Updates pages.
|
||||
|
||||
import type { HealthCheck } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { api, type AwgSource, type Needs, type UpdatesStatus } from '../api';
|
||||
import { installFeature } from '../pkgs';
|
||||
import { attempt, button, callout, confirmDialog } from '../ui';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { clock } from '../../shared/format';
|
||||
|
||||
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' };
|
||||
|
||||
export class HealthPage {
|
||||
root!: HTMLElement;
|
||||
|
||||
load() {
|
||||
return api.health();
|
||||
}
|
||||
|
||||
render(r: { checks: HealthCheck[] }) {
|
||||
this.root = E('div', { class: 'dl-root' });
|
||||
this.paint(r.checks);
|
||||
return E('div', {}, [
|
||||
E('h2', {}, 'Health'),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'cbi-map-descr' },
|
||||
'Everything Dawnline depends on, checked live. Problems come with a fix button where one exists.',
|
||||
),
|
||||
this.root,
|
||||
]);
|
||||
}
|
||||
|
||||
paint(checks: HealthCheck[]) {
|
||||
const bad = checks.filter((c) => c.status === 'error').length;
|
||||
const warn = checks.filter((c) => c.status === 'warn').length;
|
||||
dom.content(this.root, [
|
||||
bad
|
||||
? callout('error', `${bad} problem${bad > 1 ? 's' : ''} need attention.`)
|
||||
: warn
|
||||
? callout('warn', `${warn} warning${warn > 1 ? 's' : ''}.`)
|
||||
: callout('ok', 'All checks passed.'),
|
||||
E('div', { class: 'dl-panel' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [
|
||||
E('h3', {}, 'Checks'),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
button('Run again', async () => {
|
||||
const r = await attempt(() => api.health());
|
||||
if (r) this.paint(r.checks);
|
||||
}),
|
||||
]),
|
||||
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),
|
||||
]),
|
||||
c.fix
|
||||
? c.fix.startsWith('install:')
|
||||
? button(
|
||||
'Install',
|
||||
() =>
|
||||
installFeature(c.fix!.slice(8) as keyof Needs, async () => {
|
||||
const r = await api.health().catch(() => null);
|
||||
if (r) this.paint(r.checks);
|
||||
}),
|
||||
'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',
|
||||
async () => {
|
||||
const r = await attempt(() => api.healthFix(c.fix!), 'Done');
|
||||
if (r) this.paint(r.checks);
|
||||
},
|
||||
'action',
|
||||
)
|
||||
: '',
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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') 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,605 @@
|
||||
// A server's Overview section (first tab on the Servers page): who is
|
||||
// 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 { E } from '../e';
|
||||
import { api } from '../api';
|
||||
import { svg } from '../ui';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ago, bits, bytes, daysLeft, initials } from '../../shared/format';
|
||||
import { ConnectionMap, rangeControl, type Range } from '../map';
|
||||
import { attachTip } from '../charts';
|
||||
import { methodInfo } from '../disguise';
|
||||
import { personUrl } from '../palette';
|
||||
|
||||
const EVENT_TONE: Record<string, string> = {
|
||||
connect: 'ok',
|
||||
disconnect: '',
|
||||
roam: '',
|
||||
device_added: 'accent',
|
||||
device_removed: '',
|
||||
person_added: '',
|
||||
person_removed: '',
|
||||
paused: 'warn',
|
||||
resumed: 'ok',
|
||||
paused_all: 'warn',
|
||||
resumed_all: 'ok',
|
||||
server_down: 'bad',
|
||||
server_up: 'ok',
|
||||
portal_blocked: 'bad',
|
||||
person_changed: '',
|
||||
devices_removed: 'warn',
|
||||
};
|
||||
|
||||
export function eventText(st: Status, e: LogEvent): Node[] {
|
||||
const person = st.people.find((p) => p.id === e.person);
|
||||
const who = person?.name ?? e.person ?? '';
|
||||
const dev = person?.devices.find((d) => d.id === e.device)?.name ?? '';
|
||||
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);
|
||||
const wd = dev ? `${who} · ${dev}` : who;
|
||||
switch (e.type) {
|
||||
case 'connect':
|
||||
return [b(wd), m(' connected'), ...(e.detail ? [m(' from '), mono(e.detail)] : []), ...(e.where ? [m(` · ${e.where}`)] : [])];
|
||||
case 'disconnect':
|
||||
return [b(wd), m(' went offline')];
|
||||
case 'roam':
|
||||
return [b(wd), m(' changed network '), mono(e.detail ?? '')];
|
||||
case 'device_added':
|
||||
return [b(who), m(' added '), E('span', {}, e.detail ?? 'a device')];
|
||||
case 'device_removed':
|
||||
return [b(who), m(' removed '), E('span', {}, e.detail ?? 'a device')];
|
||||
case 'person_added':
|
||||
return [m('You added '), b(e.detail ?? who)];
|
||||
case 'person_removed':
|
||||
return [m('You removed '), b(e.detail ?? who)];
|
||||
case 'person_changed':
|
||||
return [m('You changed '), b(who), m(` · ${e.detail ?? ''}`)];
|
||||
case 'paused':
|
||||
return [b(who), m(` paused — ${e.detail ?? ''}`)];
|
||||
case 'resumed':
|
||||
return [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 'server_down':
|
||||
return [m('Tunnel '), mono(e.detail ?? ''), m(' went down')];
|
||||
case 'server_up':
|
||||
return [m('Tunnel '), mono(e.detail ?? ''), m(' is back up')];
|
||||
case 'portal_blocked':
|
||||
return [m('Portal blocked '), mono(e.detail ?? ''), m(' for 15 min after too many wrong codes')];
|
||||
case 'devices_removed':
|
||||
return [b(who), m('’s devices were removed — end date reached')];
|
||||
default:
|
||||
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
|
||||
}
|
||||
}
|
||||
|
||||
export function eventRow(st: Status, e: LogEvent): HTMLElement {
|
||||
return E('div', { class: 'dl-row' }, [
|
||||
E('span', { class: `dl-ev-dot ${EVENT_TONE[e.type] ?? ''}` }),
|
||||
E('span', { class: 'dl-row-main' }, eventText(st, e)),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, ago(e.ts, st.now)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** 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)[] }[] = [];
|
||||
const link = (href: string, t: string) => E('a', { href }, t);
|
||||
for (const s of st.servers)
|
||||
if (s.enabled && !s.up)
|
||||
out.push({ tone: 'bad', text: [`Tunnel ${s.ifname} is down. `, link(L.url('admin/network/dawnline/health'), 'Open Health')] });
|
||||
if (st.settings.paused_all) out.push({ tone: 'warn', text: ['Everyone is paused.'] });
|
||||
for (const p of st.people) {
|
||||
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);
|
||||
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)
|
||||
out.push({ tone: '', text: [link(personUrl(p.id), p.name), ' has used 90% of the data limit.'] });
|
||||
}
|
||||
}
|
||||
const stale = st.people.flatMap((p) => p.devices.filter((d) => d.config_stale).map((d) => [p, d] as const));
|
||||
if (stale.length)
|
||||
out.push({
|
||||
tone: 'warn',
|
||||
text:
|
||||
stale.length === 1
|
||||
? [
|
||||
link(personUrl(stale[0][0].id, stale[0][1].id), `${stale[0][0].name} · ${stale[0][1].name}`),
|
||||
' needs its configuration again.',
|
||||
]
|
||||
: [`${stale.length} devices need their configuration again (networks or DNS changed).`],
|
||||
});
|
||||
if (st.servers.some((s) => s.lan_like) && st.like_home.error)
|
||||
out.push({
|
||||
tone: 'warn',
|
||||
text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/health'), 'Details')],
|
||||
});
|
||||
if (!st.settings.portal_enabled)
|
||||
out.push({ tone: '', text: ['The personal portal is off. ', link(L.url('admin/network/dawnline/settings'), 'Turn on')] });
|
||||
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' });
|
||||
map: ConnectionMap | null = null;
|
||||
range: Range = 'online';
|
||||
parts: Record<string, HTMLElement> = {};
|
||||
healthAt = 0;
|
||||
|
||||
/** `go` switches the Servers page to another section in place. */
|
||||
constructor(
|
||||
readonly srvId: string,
|
||||
private go?: (section: string, filter?: string) => void,
|
||||
) {}
|
||||
|
||||
/** Build once; later calls to update() keep the map instance. */
|
||||
mount(st: Status): HTMLElement {
|
||||
this.st = scoped(st, this.srvId);
|
||||
for (const k of ['health', 'bento', 'side', 'activity']) this.parts[k] = E('div', {});
|
||||
dom.content(this.el, [
|
||||
this.parts.health,
|
||||
this.parts.bento,
|
||||
this.mapCard(),
|
||||
E('div', { class: 'dl-grid2' }, [this.parts.activity, this.parts.side]),
|
||||
]);
|
||||
this.paint();
|
||||
void this.loadHealth();
|
||||
return this.el;
|
||||
}
|
||||
|
||||
update(st: Status) {
|
||||
this.st = scoped(st, this.srvId);
|
||||
this.paint();
|
||||
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. */
|
||||
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(
|
||||
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/health') }, bad.some((c) => c.fix) ? 'Fix in Health →' : 'Open Health →'),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
mapData() {
|
||||
return { geo: this.st.geo, people: this.st.people, now: this.st.now };
|
||||
}
|
||||
|
||||
mapCard(): HTMLElement {
|
||||
const st = this.st;
|
||||
const head = E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('h3', {}, 'Where people connect from'),
|
||||
E('span', { class: 'dl-sub' }, 'City-level, from the client IP · locations cached on the router'),
|
||||
]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
rangeControl(this.range, (r) => {
|
||||
this.range = r;
|
||||
this.map?.setRange(r);
|
||||
}),
|
||||
]);
|
||||
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'),
|
||||
'.',
|
||||
]),
|
||||
]);
|
||||
this.map = new ConnectionMap(
|
||||
{
|
||||
openPerson: (id) => (location.href = personUrl(id)),
|
||||
openDevice: (id, dev) => (location.href = personUrl(id, dev)),
|
||||
},
|
||||
this.range,
|
||||
);
|
||||
const legend = E('div', { class: 'dl-map-legend' }, [
|
||||
E('span', {}, [E('i', { class: 'dot ok' }), 'Online']),
|
||||
E('span', {}, [E('i', { class: 'dot' }), 'Seen recently']),
|
||||
E('span', {}, [E('i', { class: 'line' }), 'Live tunnel']),
|
||||
]);
|
||||
const wrap = E('div', { class: 'dl-map-wrap' }, [this.map.el, legend]);
|
||||
requestAnimationFrame(() => this.map!.mount(this.mapData()));
|
||||
return E('div', { class: 'dl-panel flush' }, [head, wrap]);
|
||||
}
|
||||
|
||||
paint() {
|
||||
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(
|
||||
this.parts.bento,
|
||||
E('div', { class: 'dl-bento' }, [this.onlineTile(online), this.speedTile(), this.disguiseTile(srv), this.monthTile(slots)]),
|
||||
);
|
||||
|
||||
const att = attention(st);
|
||||
dom.content(
|
||||
this.parts.side,
|
||||
E('div', { class: 'dl-panel flush' }, [
|
||||
E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, 'Needs attention'),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('a', { href: L.url('admin/network/dawnline/health') }, 'Health'),
|
||||
]),
|
||||
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)]))
|
||||
: E('div', { class: 'dl-row dl-muted' }, [icon('check'), 'All good. Nothing needs you right now.']),
|
||||
]),
|
||||
);
|
||||
|
||||
const events = [...st.events].reverse().slice(0, 8);
|
||||
dom.content(
|
||||
this.parts.activity,
|
||||
E('div', { 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/activity') }, 'View all'),
|
||||
]),
|
||||
events.length
|
||||
? events.map((e) => eventRow(st, e))
|
||||
: E('div', { class: 'dl-row dl-muted' }, 'Nothing yet. Connections, new devices and pauses appear here.'),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Who is connected right now, and nothing else. One or two people: avatar,
|
||||
* name, device icons and city; three or more: a grid of avatars (two rows,
|
||||
* 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 {
|
||||
const st = this.st;
|
||||
const CAP = 12;
|
||||
const today = (d: Device) => d.spark[d.spark.length - 1] ?? 0;
|
||||
const cityOf = (d: Device) => st.geo.points.find((g) => g.device === d.id && g.city)?.city;
|
||||
const home = (d: Device) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(d.endpoint ?? '');
|
||||
const where = (d: Device) => (home(d) ? 'home' : cityOf(d)) ?? '';
|
||||
const connectedAt = (d: Device) => [...st.events].reverse().find((e) => e.type === 'connect' && e.device === d.id)?.ts ?? 0;
|
||||
const on = st.people
|
||||
.map((p) => ({ p, devs: p.devices.filter((d) => d.online).sort((a, b) => today(b) - today(a)) }))
|
||||
.filter((x) => x.devs.length)
|
||||
.sort((a, b) => b.devs.reduce((n, d) => n + today(d), 0) - a.devs.reduce((n, d) => n + today(d), 0));
|
||||
const big = on.length <= 2;
|
||||
|
||||
const card = ({ p, devs }: { p: Person; devs: Device[] }): Node[] => {
|
||||
const starts = devs.map(connectedAt).filter(Boolean);
|
||||
const since = starts.length ? Math.min(...starts) : 0;
|
||||
const pts = (p.rate ?? []).slice(-15);
|
||||
const last = pts[pts.length - 1];
|
||||
const fresh = last && st.now - last[0] < 180 ? last : null;
|
||||
const W = 200,
|
||||
H = 30,
|
||||
max = Math.max(1, ...pts.map((x) => Math.max(x[1], x[2])));
|
||||
const line = (k: 1 | 2) => pts.map((x, i) => `${pts.length > 1 ? (i / (pts.length - 1)) * W : W},${H - 2 - (x[k] / max) * (H - 6)}`);
|
||||
const chart =
|
||||
pts.length > 1
|
||||
? svg(
|
||||
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-hc-chart" aria-hidden="true">` +
|
||||
`<path d="M${line(2).join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${line(2).join(' L')}" class="dn"/><path d="M${line(1).join(' L')}" class="up"/></svg>`,
|
||||
)
|
||||
: '';
|
||||
const idle = !fresh || (fresh[1] < 64 && fresh[2] < 64);
|
||||
const reach = p.access === 'both' ? ['home', 'globe'] : p.access === 'lan' ? ['home'] : ['globe'];
|
||||
return [
|
||||
E('div', { class: 'dl-hc' }, [
|
||||
E('div', { class: 'dl-hc-head' }, [
|
||||
E('span', { class: 'dl-onl-av sm' }, initials(p.name)),
|
||||
E('span', { class: 'dl-stack' }, [
|
||||
E('b', {}, p.name),
|
||||
E('span', { class: 'dl-hc-since' }, since ? `online for ${ago(since, st.now).replace(' ago', '')}` : 'online'),
|
||||
]),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-hc-reach' },
|
||||
reach.map((r) => E('span', { class: `dl-ibadge ${r === 'home' ? 'lan' : 'inet'}` }, icon(r))),
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-hc-speed' }, [
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-hc-speed-row' },
|
||||
idle
|
||||
? [E('span', { class: 'dl-faint' }, 'Idle right now')]
|
||||
: [
|
||||
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bits(fresh![2])}`]),
|
||||
E('span', {}, [E('span', { class: 'dl-up' }, '↑'), ` ${bits(fresh![1])}`]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-faint' }, '15 min'),
|
||||
],
|
||||
),
|
||||
chart,
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-hc-devs' },
|
||||
devs.map((d) => E('span', { class: 'dl-hc-dev' }, [icon(d.kind), [d.name, where(d)].filter(Boolean).join(' · ')])),
|
||||
),
|
||||
E('div', { class: 'dl-hc-foot' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
`${bytes(devs.reduce((n, d) => n + today(d), 0))} today · ${bytes(p.month[0] + p.month[1])} this month`,
|
||||
),
|
||||
]),
|
||||
]),
|
||||
];
|
||||
};
|
||||
|
||||
const person = (x: { p: Person; devs: Device[] }) => {
|
||||
const { p, devs } = x;
|
||||
const badge = E('span', { class: 'dl-onl-dev' }, devs.length > 1 ? String(devs.length) : icon(devs[0].kind));
|
||||
const el = E('a', { class: `dl-onl-p${big ? '' : ' sm'}`, href: personUrl(p.id), 'aria-label': `${p.name}, online` }, [
|
||||
E('span', { class: 'dl-onl-av' }, [initials(p.name), badge]),
|
||||
big ? E('span', { class: 'dl-onl-name' }, p.name) : '',
|
||||
big
|
||||
? E('span', { class: 'dl-onl-meta' }, [
|
||||
...devs.slice(0, 3).map((d) => icon(d.kind)),
|
||||
devs.length > 3 ? `+${devs.length - 3}` : '',
|
||||
where(devs[0]) ? E('span', {}, ` · ${where(devs[0])}`) : '',
|
||||
])
|
||||
: '',
|
||||
]);
|
||||
attachTip(el, () => card(x));
|
||||
return el;
|
||||
};
|
||||
|
||||
const count = E('b', { class: `dl-onl-count${on.length ? '' : ' none'}` }, String(on.length));
|
||||
const ndev = on.reduce((n, x) => n + x.devs.length, 0);
|
||||
if (on.length)
|
||||
attachTip(count, () => [`${on.length} ${on.length === 1 ? 'person' : 'people'} · ${ndev} device${ndev === 1 ? '' : 's'}`]);
|
||||
const shown = on.length > CAP ? on.slice(0, CAP - 1) : on;
|
||||
const last = st.people
|
||||
.flatMap((p) => p.devices.map((d) => ({ p, d })))
|
||||
.filter((x) => x.d.handshake)
|
||||
.sort((a, b) => b.d.handshake - a.d.handshake)[0];
|
||||
return E('div', { class: 'dl-bento-tile online' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [E('span', { class: 'dl-metric-label' }, 'Online'), count]),
|
||||
on.length
|
||||
? E('div', { class: `dl-onl-row${big ? '' : ' grid'}` }, [
|
||||
...shown.map(person),
|
||||
on.length > CAP
|
||||
? E(
|
||||
'a',
|
||||
{
|
||||
class: 'dl-onl-p sm more',
|
||||
href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(this.srvId)}§ion=people&filter=online`,
|
||||
title: 'Everyone online',
|
||||
click: (ev: Event) => {
|
||||
if (this.go) {
|
||||
ev.preventDefault();
|
||||
this.go('people', 'online');
|
||||
}
|
||||
},
|
||||
},
|
||||
[E('span', { class: 'dl-onl-av' }, `+${on.length - shown.length}`)],
|
||||
)
|
||||
: '',
|
||||
])
|
||||
: E('div', { class: 'dl-onl-empty' }, [
|
||||
E('span', {}, 'Nobody is connected'),
|
||||
last
|
||||
? E('span', { class: 'dl-sub' }, `Last: ${last.p.name}, ${ago(last.d.handshake, st.now)}`)
|
||||
: E('span', { class: 'dl-sub' }, 'No device has connected yet'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Throughput right now (from the agent's minute samples): download and
|
||||
* upload side by side, the last 15 minutes as a small chart, today's total.
|
||||
*/
|
||||
speedTile(): HTMLElement {
|
||||
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)}§ion=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;
|
||||
const paused = this.st.people.filter((p) => p.state !== 'active').length;
|
||||
return daysTile(
|
||||
this.st.series,
|
||||
`${t.people} ${t.people === 1 ? 'person' : 'people'}${paused ? ` · ${paused} paused` : ''} · ${slots} device slot${slots === 1 ? '' : 's'} free`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,726 @@
|
||||
// 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.
|
||||
|
||||
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 { installPalette, personUrl } from '../palette';
|
||||
import { scoped } from './overview';
|
||||
import { attachTip } from '../charts';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, bits, bytes, date, daysLeft, initials } 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;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
return (
|
||||
p.state === 'quota' ||
|
||||
p.state === 'expired' ||
|
||||
(left != null && left <= Math.max(p.expire_warn, 3)) ||
|
||||
(!!p.quota_limit && p.quota_used >= p.quota_limit * 0.9)
|
||||
);
|
||||
}
|
||||
|
||||
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')}`;
|
||||
}
|
||||
|
||||
let addOpened = false;
|
||||
|
||||
export class PeoplePage {
|
||||
st!: Status;
|
||||
map: any;
|
||||
query = '';
|
||||
// `?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';
|
||||
sort: SortBy = 'seen';
|
||||
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;
|
||||
|
||||
async load(): Promise<Status> {
|
||||
return api.status(30);
|
||||
}
|
||||
|
||||
/** The status limited to this page's server (or everything). */
|
||||
scope(st: Status): Status {
|
||||
return this.serverId ? scoped(st, this.serverId) : st;
|
||||
}
|
||||
|
||||
/** Render as a section of the Servers page. */
|
||||
embed(st: Status, serverId: string): Promise<Node> {
|
||||
this.serverId = serverId;
|
||||
return this.render(st);
|
||||
}
|
||||
|
||||
person(sid: Sid): Person | undefined {
|
||||
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;
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const st = await this.latestStatus();
|
||||
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.decorate();
|
||||
}
|
||||
|
||||
paintCards() {
|
||||
for (const p of this.st.people) {
|
||||
const card = document.getElementById(`dl-card-${p.id}`);
|
||||
if (card) this.renderCard(card, p.id);
|
||||
}
|
||||
}
|
||||
|
||||
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');
|
||||
installPalette(st);
|
||||
const search = E('input', {
|
||||
type: 'search',
|
||||
class: 'dl-search-input',
|
||||
placeholder: 'Search people, devices, IPs',
|
||||
input: (ev: Event) => {
|
||||
page.query = (ev.target as HTMLInputElement).value.trim().toLowerCase();
|
||||
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') : '',
|
||||
]),
|
||||
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' }),
|
||||
// Search, sort and add stay together on the right, wrapping as one group.
|
||||
E('div', { class: 'dl-toolbar-end' }, [
|
||||
E('label', { class: 'dl-search' }, [icon('search'), search, E('kbd', {}, '/')]),
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
countText(): string {
|
||||
const t = this.st.totals;
|
||||
return `${t.people} ${t.people === 1 ? 'person' : 'people'} · ${t.devices} device${t.devices === 1 ? '' : 's'} · ${t.online} online`;
|
||||
}
|
||||
|
||||
/** Row classes, counters, filter tabs, search and sort order. */
|
||||
decorate() {
|
||||
const c = document.getElementById('dl-people-count');
|
||||
if (c) c.textContent = this.countText();
|
||||
const people = this.st.people;
|
||||
const counts: Record<Filter, number> = {
|
||||
all: people.length,
|
||||
online: people.filter((p) => p.online > 0).length,
|
||||
attention: people.filter(needsAttention).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 label: Record<Filter, string> = { all: 'All', online: 'Online', attention: 'Needs attention', paused: 'Paused' };
|
||||
dom.content(
|
||||
tabs,
|
||||
(Object.keys(label) as Filter[]).map((f) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
class: f === this.filter ? 'on' : '',
|
||||
click: () => {
|
||||
this.filter = f;
|
||||
this.decorate();
|
||||
},
|
||||
},
|
||||
[label[f], E('b', { class: f === 'attention' && counts[f] ? 'warn' : '' }, String(counts[f]))],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
const match = (p: Person) => {
|
||||
if (this.filter === 'online' && !p.online) return false;
|
||||
if (this.filter === 'attention' && !needsAttention(p)) return false;
|
||||
if (this.filter === 'paused' && !(p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired')) return false;
|
||||
if (!this.query) return true;
|
||||
const hay = [p.name, p.id, ...p.devices.flatMap((d) => [d.name, d.address, d.endpoint, d.hostname])].join(' ').toLowerCase();
|
||||
return hay.includes(this.query);
|
||||
};
|
||||
const order = [...people].sort((a, b) =>
|
||||
this.sort === 'name'
|
||||
? a.name.localeCompare(b.name)
|
||||
: this.sort === 'usage'
|
||||
? 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 hit = match(p);
|
||||
row.classList.toggle('dl-filtered', !hit);
|
||||
if (hit) shown++;
|
||||
}
|
||||
// Say so when the filter or search 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', {}, this.query ? `No one matches “${this.query}”.` : 'No one here right now.'));
|
||||
if (none.parentElement !== table.parentElement) table.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();
|
||||
}
|
||||
|
||||
renderCard(node: HTMLElement, sid: Sid): HTMLElement {
|
||||
const p = this.person(sid);
|
||||
if (!p) {
|
||||
dom.content(node, E('em', {}, 'Not saved yet — use “Save & Apply”.'));
|
||||
return node;
|
||||
}
|
||||
const left = daysLeft(p.expires);
|
||||
const free = Math.max(0, p.device_limit - p.devices.length);
|
||||
|
||||
// Term and hours sit by the name; online/last seen lives in the strip below.
|
||||
const pills: Node[] = [];
|
||||
if (p.expires) {
|
||||
const soon = left != null && left >= 0 && left <= Math.max(p.expire_warn, 3);
|
||||
const over = left != null && left < 0;
|
||||
pills.push(
|
||||
E('span', { class: `dl-pill-ic${over ? ' bad' : soon ? ' warn' : ''}`, title: `Access ends ${date(p.expires)}` }, [
|
||||
icon('calendar'),
|
||||
over ? `ended ${date(p.expires)}` : soon ? `ends in ${left} day${left === 1 ? '' : 's'}` : `until ${date(p.expires)}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (p.hours) pills.push(E('span', { class: 'dl-pill-ic', title: 'Allowed hours' }, [icon('clock'), p.hours.replace('-', '–')]));
|
||||
|
||||
const chips = p.devices.map((d) => {
|
||||
return E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-chip${d.disabled ? ' disabled' : ''}${d.online ? ' live' : ''}`,
|
||||
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);
|
||||
},
|
||||
},
|
||||
[
|
||||
icon(d.kind),
|
||||
E('span', { class: 'dl-chip-name' }, d.name),
|
||||
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '',
|
||||
// Online shows as the green dashed chip (.dl-chip.live); no dots.
|
||||
],
|
||||
);
|
||||
});
|
||||
if (free > 0)
|
||||
chips.push(
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-chip add',
|
||||
title: `${p.devices.length} of ${p.device_limit} devices`,
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
addDevice(p, () => this.refresh());
|
||||
},
|
||||
},
|
||||
[icon('plus'), E('span', { class: 'dl-chip-name' }, 'Add device')],
|
||||
),
|
||||
);
|
||||
|
||||
const fixes: Node[] = [];
|
||||
if (p.state === 'quota' && p.quota_period === 'month')
|
||||
fixes.push(
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-fix',
|
||||
click: () => this.quick(p, { bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month'),
|
||||
},
|
||||
'+10 GB this month',
|
||||
),
|
||||
);
|
||||
if (p.expires && left != null && left <= Math.max(p.expire_warn, 3))
|
||||
fixes.push(
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-fix', click: () => this.quick(p, { expires: addMonth(p.expires) }, 'Extended by 1 month') },
|
||||
'Extend 1 month',
|
||||
),
|
||||
);
|
||||
|
||||
const more = iconButton(
|
||||
'more',
|
||||
'More',
|
||||
(ev: MouseEvent) =>
|
||||
dropdown(
|
||||
ev.currentTarget as HTMLElement,
|
||||
[
|
||||
{
|
||||
label: 'Open',
|
||||
icon: icon('open'),
|
||||
run: () => {
|
||||
location.href = personUrl(p.id);
|
||||
},
|
||||
},
|
||||
p.link
|
||||
? {
|
||||
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,
|
||||
null,
|
||||
{
|
||||
label: p.paused ? 'Resume' : 'Pause',
|
||||
icon: icon(p.paused ? 'play' : 'pause'),
|
||||
warn: !p.paused,
|
||||
run: () => this.togglePause(p),
|
||||
},
|
||||
{ label: 'Delete', icon: icon('trash'), danger: true, run: () => this.remove(p.id) },
|
||||
].filter((x, i, a) => x || (i > 0 && a[i - 1])) as MenuItem[],
|
||||
),
|
||||
'neutral',
|
||||
'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') : '',
|
||||
more,
|
||||
]);
|
||||
|
||||
dom.content(
|
||||
node,
|
||||
E('div', { class: 'dl-pcard' }, [
|
||||
E('div', { class: 'dl-pcard-main' }, [
|
||||
E('div', { class: 'dl-card-head' }, [
|
||||
E('span', { class: `dl-avatar${p.online ? ' online' : ''}` }, initials(p.name)),
|
||||
E('a', { class: 'dl-card-name', href: personUrl(p.id) }, p.name),
|
||||
stateBadge(p),
|
||||
accessBadge(p),
|
||||
...pills,
|
||||
]),
|
||||
E('div', { class: 'dl-meta' }, [
|
||||
E('span', {}, `${p.devices.length} of ${p.device_limit} devices`),
|
||||
E('span', { class: 'dl-sep' }, '·'),
|
||||
E('span', {}, p.online ? 'online now' : p.last_seen ? `seen ${ago(p.last_seen, this.st.now)}` : 'never connected'),
|
||||
]),
|
||||
E('div', { class: 'dl-chips' }, chips),
|
||||
fixes.length ? E('div', { class: 'dl-fixes' }, fixes) : '',
|
||||
]),
|
||||
this.usageSide(p, actions),
|
||||
]),
|
||||
);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Status and actions, this month's usage, a bar split by device (or filled toward the limit), today or live speed. */
|
||||
usageSide(p: Person, actions: HTMLElement): HTMLElement {
|
||||
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 today = p.devices.reduce((a, d) => a + (d.spark[d.spark.length - 1] ?? 0), 0);
|
||||
const r = p.rate?.[p.rate.length - 1];
|
||||
const live = p.online && r && this.st.now - r[0] < 180;
|
||||
|
||||
const bar = E('div', { class: `dl-usebar${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` });
|
||||
if (p.quota_limit) {
|
||||
const fill = E('i', { class: 'fill' });
|
||||
fill.style.width = `${pct}%`;
|
||||
bar.appendChild(fill);
|
||||
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' },
|
||||
p.quota_period === 'total' ? 'In total' : `This month${p.bonus_gb ? ` · includes +${p.bonus_gb} GB extra` : ''}`,
|
||||
),
|
||||
]);
|
||||
} else {
|
||||
const devs = p.devices
|
||||
.map((d) => ({ d, v: d.month[0] + d.month[1] }))
|
||||
.filter((x) => x.v > 0)
|
||||
.sort((a, b) => b.v - a.v);
|
||||
devs.forEach((x, i) => {
|
||||
const seg = E('i', { class: `c${Math.min(i, 4)}` });
|
||||
seg.style.flexGrow = String(x.v);
|
||||
bar.appendChild(seg);
|
||||
});
|
||||
if (devs.length)
|
||||
attachTip(bar, () => [
|
||||
E('div', { class: 'dl-tip-title' }, 'This month by device'),
|
||||
...devs.map((x, i) =>
|
||||
E('div', { class: 'dl-tip-row' }, [
|
||||
E('span', { class: `dl-swatch c${Math.min(i, 4)}` }),
|
||||
E('span', {}, x.d.name),
|
||||
E('b', {}, bytes(x.v)),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
const limitText = p.quota_limit ? `${bytes(Math.max(0, p.quota_limit - p.quota_used))} left` : 'no limit';
|
||||
return E('div', { class: 'dl-pside' }, [
|
||||
E('div', { class: 'dl-pside-top' }, [
|
||||
live
|
||||
? E('span', { class: 'dl-pside-state live' }, [E('i', { class: 'dl-dot online' }), 'Live'])
|
||||
: E('span', { class: 'dl-pside-state' }, p.online ? 'Online' : p.last_seen ? 'Offline' : 'Not connected'),
|
||||
actions,
|
||||
]),
|
||||
E('div', { class: 'dl-use-num' }, [
|
||||
E('b', { class: used ? '' : 'dl-faint' }, bytes(used)),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
p.quota_limit ? `of ${bytes(p.quota_limit)}` : p.quota_period === 'total' && p.quota_gb ? 'in total' : 'this month',
|
||||
),
|
||||
]),
|
||||
bar,
|
||||
live
|
||||
? E('div', { class: 'dl-use-live', title: 'Right now' }, [`↓ ${bits(r![2])}`, E('span', { class: 'dl-faint' }, `↑ ${bits(r![1])}`)])
|
||||
: E('div', { class: 'dl-faint dl-pside-foot' }, today ? `today ${bytes(today)} · ${limitText}` : limitText),
|
||||
]);
|
||||
}
|
||||
|
||||
async togglePause(p: Person) {
|
||||
if (await attempt(() => api.personPause(p.id, !p.paused), p.paused ? `${p.name} resumed` : `${p.name} paused`)) await this.refresh();
|
||||
}
|
||||
|
||||
async remove(sid: Sid) {
|
||||
const p = this.person(sid);
|
||||
const ok = await confirmDialog(
|
||||
`Remove ${p?.name ?? sid}?`,
|
||||
`All ${p?.devices.length ?? 0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`,
|
||||
'Remove',
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.personDelete(sid), 'Person removed'))) await this.refresh();
|
||||
}
|
||||
|
||||
openCreate() {
|
||||
const st = this.st;
|
||||
if (!st.servers.length) {
|
||||
notify('Set up the server first.', 'warning');
|
||||
return;
|
||||
}
|
||||
const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: 'e.g. Myata', maxlength: 48 }) as HTMLInputElement;
|
||||
const access = accessPicker('internet');
|
||||
const limit = E('input', {
|
||||
type: 'number',
|
||||
class: 'cbi-input-text',
|
||||
min: 1,
|
||||
max: 32,
|
||||
value: st.settings.default_device_limit,
|
||||
}) as HTMLInputElement;
|
||||
const expires = E('input', { type: 'date', class: 'cbi-input-text' }) as HTMLInputElement;
|
||||
const quota = E('input', {
|
||||
type: 'number',
|
||||
class: 'cbi-input-text',
|
||||
min: 0,
|
||||
step: 'any',
|
||||
placeholder: 'Unlimited',
|
||||
}) as HTMLInputElement;
|
||||
const quick = (label: string, months: number) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
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);
|
||||
}
|
||||
},
|
||||
},
|
||||
label,
|
||||
);
|
||||
const srv = st.servers[0];
|
||||
const server =
|
||||
!this.serverId && st.servers.length > 1
|
||||
? (E(
|
||||
'select',
|
||||
{ class: 'cbi-input-select' },
|
||||
st.servers.map((s) => E('option', { value: s.id }, s.name)),
|
||||
) as HTMLSelectElement)
|
||||
: null;
|
||||
|
||||
const row = (label: string, w: Node, help?: string) =>
|
||||
E('div', { class: 'cbi-value' }, [
|
||||
E('label', { class: 'cbi-value-title' }, label),
|
||||
E('div', { class: 'cbi-value-field' }, [w, help ? E('div', { class: 'cbi-value-description' }, help) : '']),
|
||||
]);
|
||||
|
||||
modal(
|
||||
'Add person',
|
||||
[
|
||||
row('Name', name),
|
||||
server ? row('Server', server) : '',
|
||||
E('div', { class: 'cbi-value dl-block' }, [
|
||||
E('label', { class: 'cbi-value-title' }, 'Access'),
|
||||
E('div', { class: 'cbi-value-field' }, access.el),
|
||||
]),
|
||||
row('Devices', limit, 'How many devices they can add themselves.'),
|
||||
row(
|
||||
'End date',
|
||||
E('div', { class: 'dl-actions' }, [expires, quick('1 month', 1), quick('3 months', 3), quick('1 year', 12), quick('None', 0)]),
|
||||
'Optional.',
|
||||
),
|
||||
row('Monthly data (GB)', quota, 'Optional. They are paused when it runs out and resumed next month.'),
|
||||
],
|
||||
[
|
||||
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
|
||||
' ',
|
||||
button(
|
||||
'Create and copy link',
|
||||
async () => {
|
||||
const r = await attempt(() =>
|
||||
api.personCreate(
|
||||
name.value.trim(),
|
||||
'',
|
||||
server?.value ?? srv.id,
|
||||
access.get(),
|
||||
Number(limit.value) || st.settings.default_device_limit,
|
||||
expires.value,
|
||||
Number(quota.value) || 0,
|
||||
'month',
|
||||
),
|
||||
);
|
||||
if (!r) return;
|
||||
if (r.link) await copyText(r.link, 'Personal link copied');
|
||||
this.showCreated(r.id, name.value.trim(), r.link, st.servers.find((x) => x.id === (server?.value ?? srv.id))?.name ?? srv.name);
|
||||
await this.refresh();
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
setTimeout(() => name.focus(), 50);
|
||||
}
|
||||
|
||||
showCreated(id: string, name: string, link: string | null, server: string) {
|
||||
if (link) {
|
||||
inviteCard({ id, name, link }, server, {
|
||||
title: `${name} is ready`,
|
||||
lead: `Send ${name} the card or the link. They open it, add their devices and connect — no account needed.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
modal(
|
||||
`${name} is ready`,
|
||||
[E('p', {}, 'Created. Turn on the personal portal in Settings to get a link, or add devices for them here.')],
|
||||
[E('button', { class: 'cbi-button cbi-button-positive', click: closeModal }, 'Done')],
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,834 @@
|
||||
// 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.
|
||||
|
||||
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 { icon } from '../../shared/icons';
|
||||
import { duration } from '../../shared/format';
|
||||
import { interfacesCard } from '../interfaces';
|
||||
import { card, group, input, row } from '../kit';
|
||||
import { methodInfo, methodPicker, type Method } from '../disguise';
|
||||
import { ServerOverview } from './overview';
|
||||
import { PeoplePage } from './people';
|
||||
import { installPalette, openPalette } from '../palette';
|
||||
|
||||
type Section = 'overview' | 'people' | 'connection' | 'access' | 'disguise' | 'tunnel';
|
||||
const SECTIONS: [Section, string][] = [
|
||||
['overview', 'Overview'],
|
||||
['people', 'People'],
|
||||
['connection', 'Connection'],
|
||||
['access', 'Access'],
|
||||
['disguise', 'Disguise'],
|
||||
['tunnel', 'Tunnel'],
|
||||
];
|
||||
/** Section names from before the regrouping, for old links. */
|
||||
const OLD_SECTIONS: Record<string, Section> = { general: 'connection', network: 'connection', interfaces: 'access', advanced: 'tunnel' };
|
||||
function choices<T extends string>(items: { v: T; title: string; text: string; ic?: string }[], initial: T, onChange: (v: T) => void) {
|
||||
const el = E(
|
||||
'div',
|
||||
{ class: 'dl-choices' },
|
||||
items.map((o) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-choice${o.v === initial ? ' selected' : ''}`,
|
||||
'data-v': o.v,
|
||||
click: () => {
|
||||
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' }, [o.ic ? icon(o.ic) : '', o.title]), E('span', { class: 'dl-choice-text' }, o.text)],
|
||||
),
|
||||
),
|
||||
);
|
||||
return el;
|
||||
}
|
||||
|
||||
/** `.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 url = (server?: string, section?: string) => {
|
||||
const q = new URLSearchParams();
|
||||
if (server) q.set('server', server);
|
||||
if (section && section !== 'overview') q.set('section', section);
|
||||
const s = q.toString();
|
||||
return `${L.url('admin/network/dawnline/server')}${s ? `?${s}` : ''}`;
|
||||
};
|
||||
|
||||
export class ServerPage {
|
||||
st!: Status;
|
||||
noFooter = true;
|
||||
root = E('div', { class: 'dl-root' });
|
||||
section: Section = 'overview';
|
||||
srvId = '';
|
||||
/** Per-server sections kept between switches (the map stays mounted). */
|
||||
ov: Record<string, ServerOverview> = {};
|
||||
pp: Record<string, PeoplePage> = {};
|
||||
tabsEl = E('div', {});
|
||||
headEl = E('div', {});
|
||||
secEl = E('div', {});
|
||||
bodyEl = E('div', { class: 'dl-srvbody' });
|
||||
|
||||
async load(): Promise<[Status, SetupDefaults | null]> {
|
||||
const st = await api.status(31);
|
||||
const d = st.servers.length ? null : await api.setupDefaults();
|
||||
return [st, d];
|
||||
}
|
||||
|
||||
render([st, d]: [Status, SetupDefaults | null]): Node {
|
||||
this.st = st;
|
||||
if (!st.servers.length && d) return this.wizard(d);
|
||||
// Deep links (?server=…§ion=…) pick the starting tab; switching later
|
||||
// happens in place, without touching the URL (the theme's router would
|
||||
// treat that as a navigation and redraw the page).
|
||||
const q = new URLSearchParams(location.search);
|
||||
const raw = q.get('section') ?? '';
|
||||
const want = (OLD_SECTIONS[raw] ?? raw) as Section;
|
||||
if (SECTIONS.some(([k]) => k === want)) this.section = want;
|
||||
this.srvId = (st.servers.find((x) => x.id === q.get('server')) ?? st.servers[0]).id;
|
||||
installPalette(st);
|
||||
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);
|
||||
return this.root;
|
||||
}
|
||||
|
||||
current(): Server {
|
||||
return this.st.servers.find((x) => x.id === this.srvId) ?? this.st.servers[0];
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const st = await api.status(31).catch(() => null);
|
||||
if (!st) return;
|
||||
this.st = st;
|
||||
if (!st.servers.length) location.href = url();
|
||||
else this.paint();
|
||||
}
|
||||
|
||||
/* ---------------- page ---------------- */
|
||||
|
||||
/** Everything: server tabs, head, section tabs and the current section. */
|
||||
paint() {
|
||||
this.paintTabs();
|
||||
dom.content(this.headEl, this.head(this.current()));
|
||||
this.paintSections();
|
||||
this.showSection(this.section);
|
||||
}
|
||||
|
||||
paintTabs() {
|
||||
const srv = this.current();
|
||||
dom.content(
|
||||
this.tabsEl,
|
||||
E('div', { class: 'dl-srvtabs', role: 'tablist', 'aria-label': 'Servers' }, [
|
||||
...this.st.servers.map((x) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
class: `dl-srvtab${x.id === srv.id ? ' on' : ''}`,
|
||||
'aria-selected': x.id === srv.id ? 'true' : 'false',
|
||||
click: () => {
|
||||
if (x.id === this.srvId) return;
|
||||
this.srvId = x.id;
|
||||
this.paint();
|
||||
},
|
||||
},
|
||||
[E('i', { class: `dot ${x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name), E('span', { class: 'dl-mono dl-faint' }, `:${x.port}`)],
|
||||
),
|
||||
),
|
||||
E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), 'Add server']),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
paintSections() {
|
||||
dom.content(
|
||||
this.secEl,
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-seg dl-srvsections', role: 'tablist', 'aria-label': 'Server' },
|
||||
SECTIONS.map(([k, t]) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
'data-section': k,
|
||||
class: k === this.section ? 'on' : '',
|
||||
'aria-selected': k === this.section ? 'true' : 'false',
|
||||
click: () => this.showSection(k),
|
||||
},
|
||||
t,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Jump to a section, optionally with a People filter (from the Overview). */
|
||||
go(k: Section, filter?: string) {
|
||||
const pp = this.pp[this.current().id];
|
||||
if (filter && pp) {
|
||||
pp.filter = filter as PeoplePage['filter'];
|
||||
if (pp.el) pp.decorate();
|
||||
} else if (filter) {
|
||||
const page = (this.pp[this.current().id] = new PeoplePage());
|
||||
page.filter = filter as PeoplePage['filter'];
|
||||
}
|
||||
this.showSection(k);
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}
|
||||
|
||||
/** Swap only the section body; the rest of the page stays as it is. */
|
||||
showSection(k: Section) {
|
||||
this.section = k;
|
||||
this.secEl.querySelectorAll<HTMLElement>('[data-section]').forEach((b) => {
|
||||
const on = b.dataset.section === k;
|
||||
b.classList.toggle('on', on);
|
||||
b.setAttribute('aria-selected', on ? 'true' : 'false');
|
||||
});
|
||||
const st = this.st;
|
||||
const srv = this.current();
|
||||
const body: Record<Section, () => Node> = {
|
||||
overview: () => {
|
||||
const ov = this.ov[srv.id];
|
||||
if (!ov) return (this.ov[srv.id] = new ServerOverview(srv.id, (k, f) => this.go(k as Section, f))).mount(st);
|
||||
ov.update(st);
|
||||
return ov.el;
|
||||
},
|
||||
people: () => {
|
||||
const pp = this.pp[srv.id];
|
||||
if (pp?.el) {
|
||||
void pp.poll();
|
||||
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);
|
||||
});
|
||||
return holder;
|
||||
},
|
||||
connection: () => this.connection(srv),
|
||||
access: () => this.access(srv),
|
||||
disguise: () => this.disguise(srv),
|
||||
tunnel: () => this.tunnel(srv),
|
||||
};
|
||||
dom.content(this.bodyEl, body[k]());
|
||||
}
|
||||
|
||||
/** 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}`;
|
||||
// Search, plus "Turn on" while the server is off (turning off lives in Tunnel;
|
||||
// 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' }, [
|
||||
button([icon('search'), ' Search ', E('kbd', {}, '⌘K')], () => openPalette(), 'neutral', {
|
||||
class: 'cbi-button cbi-button-neutral dl-searchbtn',
|
||||
}),
|
||||
off
|
||||
? button(
|
||||
[icon('play'), ' Turn on'],
|
||||
async () => {
|
||||
if (st.settings.paused_all && !(await attempt(() => api.pauseAll(false)))) return;
|
||||
if (!srv.enabled) await this.save(srv, { enabled: '1' }, 'Server turned on');
|
||||
else await this.refresh();
|
||||
},
|
||||
'positive',
|
||||
)
|
||||
: '',
|
||||
]);
|
||||
// Actions sit on the name's line; the address bar gets the whole next line.
|
||||
return E('div', { class: 'dl-srvpagehead' }, [
|
||||
E('div', { class: 'dl-title-row' }, [
|
||||
E('h2', { class: 'dl-h1' }, srv.name),
|
||||
E('span', { class: `dl-pill ${!srv.enabled ? 'off' : srv.up ? 'ok' : 'bad'}` }, [
|
||||
E('i', { class: 'dl-pill-dot' }),
|
||||
!srv.enabled ? 'Disabled' : srv.up ? 'Ready' : 'Down',
|
||||
]),
|
||||
st.settings.paused_all && srv.enabled ? E('span', { class: 'dl-pill warn' }, 'Off') : '',
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
actions,
|
||||
]),
|
||||
E('div', { class: 'dl-addrbar' }, [
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address and port', 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)}`]) : '',
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
async save(srv: Server, values: Record<string, unknown>, ok = 'Saved') {
|
||||
if (await attempt(() => api.serverUpdate(srv.id, values), ok)) await this.refresh();
|
||||
}
|
||||
|
||||
/** How devices find the server and what goes into their configuration. */
|
||||
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, WAN, home network, services. */
|
||||
access(srv: Server): HTMLElement {
|
||||
const svcs = this.st.services;
|
||||
return E('div', { class: 'dl-stack gap16' }, [
|
||||
interfacesCard(srv.id, 'Access'),
|
||||
card(
|
||||
'Home services',
|
||||
[
|
||||
E(
|
||||
'p',
|
||||
{ class: 'dl-muted' },
|
||||
'People with Home-only access can be limited to these services instead of the whole home network (chosen per person). The list is shared by all servers.',
|
||||
),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-list' },
|
||||
svcs.length
|
||||
? svcs.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'}`,
|
||||
),
|
||||
]),
|
||||
]),
|
||||
)
|
||||
: [E('div', { class: 'dl-row dl-muted' }, 'No services yet.')],
|
||||
),
|
||||
],
|
||||
[
|
||||
E('span'),
|
||||
E(
|
||||
'a',
|
||||
{ class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/network/dawnline/settings')}#dl-set-services` },
|
||||
'Edit in Settings',
|
||||
),
|
||||
],
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
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',
|
||||
async () => {
|
||||
if (
|
||||
srv.enabled &&
|
||||
!(await confirmDialog(
|
||||
`Turn off ${srv.name}?`,
|
||||
`The tunnel stops and ${people} ${people === 1 ? 'person is' : 'people are'} disconnected until you turn it back on. Nothing is deleted.`,
|
||||
'Turn off',
|
||||
true,
|
||||
))
|
||||
)
|
||||
return;
|
||||
await this.save(srv, { enabled: srv.enabled ? '0' : '1' }, srv.enabled ? 'Server turned off' : 'Server turned on');
|
||||
},
|
||||
srv.enabled ? 'negative' : 'positive',
|
||||
);
|
||||
return E('div', { class: 'dl-stack gap16' }, [
|
||||
card(
|
||||
'Tunnel',
|
||||
[
|
||||
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',
|
||||
}),
|
||||
]),
|
||||
),
|
||||
row('Link path', E('span', { class: 'dl-mono' }, `/${srv.id}/`), 'Changing it would break every personal link already sent.'),
|
||||
],
|
||||
[],
|
||||
),
|
||||
card(
|
||||
'Danger zone',
|
||||
[
|
||||
E('div', { class: 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-setrow-label' }, srv.enabled ? 'Turn off this server' : 'This server is off'),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
srv.enabled
|
||||
? 'Stops the tunnel and disconnects everyone on it. Settings and people are kept.'
|
||||
: 'Nobody can connect. Turn it on to bring the tunnel back.',
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow-ctl' }, toggle),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-setrow-label' }, 'Remove server'),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
`Removes the tunnel, its firewall rules and ${people} ${people === 1 ? 'person' : 'people'} with all their devices. A backup is made first.`,
|
||||
),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-setrow-ctl' },
|
||||
button([icon('trash'), ' Remove'], () => this.remove(srv), 'negative'),
|
||||
),
|
||||
]),
|
||||
],
|
||||
[],
|
||||
'danger',
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/* ---------------- add / remove ---------------- */
|
||||
|
||||
async addServer() {
|
||||
const d = await attempt(() => api.setupDefaults());
|
||||
if (!d) return;
|
||||
dom.content(
|
||||
this.root,
|
||||
this.wizard(d, true, () => {
|
||||
dom.content(this.root, [this.tabsEl, this.headEl, this.secEl, this.bodyEl]);
|
||||
this.paint();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async remove(srv: Server) {
|
||||
const people = this.st.people.filter((p) => p.server === srv.id);
|
||||
modal(
|
||||
`Remove ${srv.name}?`,
|
||||
[
|
||||
E(
|
||||
'p',
|
||||
{},
|
||||
`This removes the tunnel, its firewall rules and ${people.length} ${people.length === 1 ? 'person' : 'people'} with all their devices. A backup is made first.`,
|
||||
),
|
||||
],
|
||||
[
|
||||
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
|
||||
' ',
|
||||
button(
|
||||
'Remove',
|
||||
async () => {
|
||||
closeModal();
|
||||
if (await attempt(() => api.serverDelete(srv.id), 'Server removed'))
|
||||
setTimeout(() => {
|
||||
location.href = url();
|
||||
}, 800);
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------- wizard ---------------- */
|
||||
|
||||
/**
|
||||
* Setup wizard. `extra` adds one more server next to existing ones: the
|
||||
* portal is already set up then, so that step is left out.
|
||||
*/
|
||||
wizard(d: SetupDefaults, extra = false, onCancel?: () => void): HTMLElement {
|
||||
const state = {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
endpoint: d.endpoint,
|
||||
port: d.port,
|
||||
subnet: d.subnet,
|
||||
preset: 'standard' as Method,
|
||||
portal: true,
|
||||
portal_port: d.portal_port || 8443,
|
||||
lan_zone: d.lan_zone,
|
||||
wan_zone: d.wan_zone,
|
||||
};
|
||||
let step = 0;
|
||||
const root = E('div', { class: 'dl-wizard' });
|
||||
const field = (key: 'id' | 'name' | 'endpoint' | 'port' | 'subnet' | 'portal_port', attrs: Record<string, unknown> = {}) => {
|
||||
const el = input(String(state[key]), attrs);
|
||||
el.addEventListener('input', () => {
|
||||
(state as any)[key] = key === 'port' || key === 'portal_port' ? Number(el.value) : el.value.trim();
|
||||
});
|
||||
return el;
|
||||
};
|
||||
|
||||
const steps = extra ? ['Connection', 'Disguise'] : ['Connection', 'Disguise', 'Portal'];
|
||||
const pages: (() => Node)[] = [
|
||||
() =>
|
||||
E('div', {}, [
|
||||
E(
|
||||
'p',
|
||||
{},
|
||||
'Where devices connect to. Use a hostname that always points at your router (DDNS), so links keep working when your IP changes.',
|
||||
),
|
||||
row('Name', field('name'), 'Shown to people in their portal.'),
|
||||
row(
|
||||
'Link path',
|
||||
field('id', { maxlength: 24, class: 'cbi-input-text dl-mono' }),
|
||||
'First part of personal links: https://address:port/<path>/<person>.',
|
||||
),
|
||||
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.',
|
||||
),
|
||||
row(
|
||||
'UDP port',
|
||||
field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }),
|
||||
'Opened on the WAN firewall automatically. A random high port is fine.',
|
||||
),
|
||||
row(
|
||||
'Tunnel subnet',
|
||||
field('subnet', { class: 'cbi-input-text dl-mono' }),
|
||||
`Addresses for devices. Must not overlap your networks (${d.taken.join(', ') || 'none found'}).`,
|
||||
),
|
||||
]),
|
||||
() =>
|
||||
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)),
|
||||
]),
|
||||
() => {
|
||||
const portalPort = field('portal_port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
||||
return E('div', {}, [
|
||||
callout(
|
||||
'info',
|
||||
'Devices reach the internet the way devices on your home network do: whatever handles home traffic on this router handles theirs too. You can change this later under Servers → Access.',
|
||||
),
|
||||
E('h4', {}, 'Personal portal'),
|
||||
E('p', {}, 'A small page where each person adds their own devices, with their personal link. It gets its own HTTPS port on WAN.'),
|
||||
choices(
|
||||
[
|
||||
{ v: 'on', title: 'On', ic: 'link', text: 'People manage their devices themselves within the limits you set.' },
|
||||
{ v: 'off', title: 'Off', ic: 'x', text: 'Only you add devices, from LuCI.' },
|
||||
],
|
||||
'on',
|
||||
(v) => {
|
||||
state.portal = v === 'on';
|
||||
portalPort.disabled = !state.portal;
|
||||
},
|
||||
),
|
||||
row('Portal port', portalPort, 'TCP port on WAN. The whole port belongs to the portal.'),
|
||||
]);
|
||||
},
|
||||
];
|
||||
|
||||
const paint = () => {
|
||||
dom.content(root, [
|
||||
E('h2', {}, extra ? 'Add a server' : 'Set up Dawnline'),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-steps' },
|
||||
steps.map((s, i) =>
|
||||
E('span', { class: `dl-step${i === step ? ' current' : i < step ? ' done' : ''}` }, [
|
||||
E('b', {}, i < step ? '✓' : String(i + 1)),
|
||||
s,
|
||||
]),
|
||||
),
|
||||
),
|
||||
E('div', { class: 'dl-panel' }, pages[step]()),
|
||||
E('div', { class: 'dl-actions' }, [
|
||||
step > 0
|
||||
? button('Back', () => {
|
||||
step--;
|
||||
paint();
|
||||
})
|
||||
: onCancel
|
||||
? button('Cancel', onCancel)
|
||||
: '',
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
step < steps.length - 1
|
||||
? button(
|
||||
'Next',
|
||||
() => {
|
||||
if (step === 0 && (!state.endpoint || !state.port || !state.subnet)) {
|
||||
notify('Fill in the public address, port and subnet.', 'warning');
|
||||
return;
|
||||
}
|
||||
step++;
|
||||
paint();
|
||||
},
|
||||
'positive',
|
||||
)
|
||||
: button(
|
||||
'Create server',
|
||||
async () => {
|
||||
// An extra server leaves the portal settings alone (undefined is not sent).
|
||||
const r = await attempt(
|
||||
() =>
|
||||
api.serverCreate(
|
||||
state.id,
|
||||
state.name,
|
||||
d.ifname,
|
||||
state.port,
|
||||
state.subnet,
|
||||
state.endpoint,
|
||||
d.mtu,
|
||||
state.preset,
|
||||
state.lan_zone,
|
||||
state.wan_zone,
|
||||
true,
|
||||
extra ? undefined : state.portal,
|
||||
extra ? undefined : state.portal_port,
|
||||
),
|
||||
'Server created',
|
||||
);
|
||||
if (r)
|
||||
setTimeout(() => {
|
||||
location.href = url(r.id);
|
||||
}, 1500);
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
]),
|
||||
]);
|
||||
};
|
||||
paint();
|
||||
return root;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,839 @@
|
||||
// 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, confirmDialog, modal } from '../ui';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { installPalette } from '../palette';
|
||||
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;
|
||||
installPalette();
|
||||
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();
|
||||
|
||||
// Home services
|
||||
const svcRows = this.d.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', () => this.editService(sv)),
|
||||
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'))
|
||||
)
|
||||
this.reload();
|
||||
},
|
||||
'negative',
|
||||
{ title: 'Remove' },
|
||||
),
|
||||
]),
|
||||
);
|
||||
const services = this.section(
|
||||
'services',
|
||||
'Home services',
|
||||
[
|
||||
E(
|
||||
'p',
|
||||
{ class: 'dl-muted' },
|
||||
'Give people with home-network access only specific services instead of the whole network (choose them per person).',
|
||||
),
|
||||
E('div', { class: 'dl-list' }, svcRows.length ? svcRows : [E('div', { class: 'dl-row dl-muted' }, 'No services yet.')]),
|
||||
],
|
||||
[E('span'), button([icon('plus'), ' Add service'], () => this.editService(null), 'add')],
|
||||
);
|
||||
|
||||
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, services, 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();
|
||||
}
|
||||
}
|
||||
|
||||
editService(sv: SettingsData['services'][number] | null) {
|
||||
const name = input(sv?.name ?? '', { placeholder: 'NAS' });
|
||||
const addr = input(sv?.address ?? '', { placeholder: '192.168.1.10' });
|
||||
const ports = input(sv?.ports.join(', ') ?? '', { placeholder: 'All ports, or e.g. 445, 5000' });
|
||||
modal(
|
||||
sv ? `Edit ${sv.name}` : 'Add service',
|
||||
[
|
||||
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, name)]),
|
||||
E('div', { class: 'cbi-value' }, [
|
||||
E('label', { class: 'cbi-value-title' }, 'Address'),
|
||||
E('div', { class: 'cbi-value-field' }, addr),
|
||||
]),
|
||||
E('div', { class: 'cbi-value' }, [
|
||||
E('label', { class: 'cbi-value-title' }, 'Ports'),
|
||||
E('div', { class: 'cbi-value-field' }, ports),
|
||||
]),
|
||||
],
|
||||
[
|
||||
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
async () => {
|
||||
const list = ports.value.split(/[ ,]+/).filter(Boolean);
|
||||
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
|
||||
closeModal();
|
||||
this.reload();
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
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',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// ⌘K / Ctrl+K command menu: jump to people and devices (also by IP or
|
||||
// address) and run the common actions without leaving the keyboard.
|
||||
|
||||
import type { Person, Status } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api } from './api';
|
||||
import { attempt, copyText } from './ui';
|
||||
import { icon } from '../shared/icons';
|
||||
import { ACCESS_SHORT, initials } from '../shared/format';
|
||||
|
||||
interface Item {
|
||||
group: string;
|
||||
label: string;
|
||||
hint?: string;
|
||||
icon?: string;
|
||||
avatar?: string;
|
||||
kbd?: string;
|
||||
run: () => unknown;
|
||||
}
|
||||
|
||||
let cache: { st: Status; at: number } | null = null;
|
||||
let open = false;
|
||||
|
||||
/** A server's People section (Servers page). */
|
||||
export function peopleUrl(server?: string): string {
|
||||
return `${L.url('admin/network/dawnline/server')}?${server ? `server=${encodeURIComponent(server)}&` : ''}section=people`;
|
||||
}
|
||||
|
||||
export function personUrl(id: string, device?: string): string {
|
||||
return `${L.url('admin/network/dawnline/person')}?id=${encodeURIComponent(id)}${device ? `&device=${encodeURIComponent(device)}` : ''}`;
|
||||
}
|
||||
|
||||
function go(path: string) {
|
||||
location.href = L.url(`admin/network/dawnline/${path}`);
|
||||
}
|
||||
|
||||
function addMonths(iso: string, n: number): string {
|
||||
const base = iso ? new Date(`${iso}T12:00:00`) : new Date();
|
||||
const from = base.getTime() < Date.now() ? new Date() : base;
|
||||
from.setMonth(from.getMonth() + n);
|
||||
return `${from.getFullYear()}-${String(from.getMonth() + 1).padStart(2, '0')}-${String(from.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function personActions(p: Person, done: () => void): Item[] {
|
||||
const g = `Actions for ${p.name}`;
|
||||
const items: Item[] = [];
|
||||
if (p.link)
|
||||
items.push({ group: g, label: 'Copy personal link', icon: 'link', kbd: 'C', run: () => copyText(p.link!, 'Personal link copied') });
|
||||
items.push({ group: g, label: `Add device for ${p.name}`, icon: 'plus', run: () => (location.href = `${personUrl(p.id)}&add=1`) });
|
||||
items.push({
|
||||
group: g,
|
||||
label: p.paused ? `Resume ${p.name}` : `Pause ${p.name}`,
|
||||
icon: p.paused ? 'play' : 'pause',
|
||||
kbd: 'P',
|
||||
run: async () => {
|
||||
await attempt(() => api.personPause(p.id, !p.paused), p.paused ? `${p.name} resumed` : `${p.name} paused`);
|
||||
done();
|
||||
},
|
||||
});
|
||||
items.push({
|
||||
group: g,
|
||||
label: 'Extend access by 1 month',
|
||||
icon: 'key',
|
||||
run: async () => {
|
||||
await attempt(() => api.personUpdate(p.id, { expires: addMonths(p.expires, 1) }), 'Access extended');
|
||||
done();
|
||||
},
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
function build(st: Status, q: string, done: () => void): Item[] {
|
||||
const query = q.trim().toLowerCase();
|
||||
const items: Item[] = [];
|
||||
const people = st.people.filter((p) => !query || [p.name, p.id].some((x) => x.toLowerCase().includes(query)));
|
||||
for (const p of people.slice(0, 6))
|
||||
items.push({
|
||||
group: 'People',
|
||||
label: p.name,
|
||||
hint: `${ACCESS_SHORT[p.access]} · ${p.online ? `${p.online} online` : `${p.devices.length} devices`}`,
|
||||
avatar: initials(p.name),
|
||||
run: () => (location.href = personUrl(p.id)),
|
||||
});
|
||||
for (const p of st.people)
|
||||
for (const d of p.devices) {
|
||||
const hay = [d.name, d.address, d.endpoint, d.hostname].join(' ').toLowerCase();
|
||||
if (query && !hay.includes(query)) continue;
|
||||
if (!query && !d.online) continue;
|
||||
items.push({
|
||||
group: 'Devices',
|
||||
label: d.name,
|
||||
hint: `${p.name} · ${d.address}${d.online ? ` · ${d.endpoint}` : ''}`,
|
||||
icon: d.kind,
|
||||
run: () => (location.href = personUrl(p.id, d.id)),
|
||||
});
|
||||
}
|
||||
if (people.length === 1 || (people.length && query)) items.push(...personActions(people[0], done));
|
||||
const pages: [string, string, string][] = [
|
||||
['overview', 'Overview', 'globe'],
|
||||
['people', 'People', 'shield'],
|
||||
['activity', 'Activity', 'file'],
|
||||
['server', 'Server', 'key'],
|
||||
['health', 'Health', 'check'],
|
||||
['settings?section=backups', 'Backups', 'archive'],
|
||||
['settings', 'Settings', 'edit'],
|
||||
];
|
||||
for (const [path, label, ic] of pages)
|
||||
if (!query || label.toLowerCase().includes(query)) items.push({ group: 'Go to', label, icon: ic, run: () => go(path) });
|
||||
if (!query || 'add person'.includes(query))
|
||||
items.push({
|
||||
group: 'Go to',
|
||||
label: 'Add person',
|
||||
icon: 'plus',
|
||||
run: () => (location.href = `${L.url('admin/network/dawnline/server')}?section=people&add=1`),
|
||||
});
|
||||
return items;
|
||||
}
|
||||
|
||||
export async function openPalette() {
|
||||
if (open) return;
|
||||
open = true;
|
||||
const input = E('input', {
|
||||
type: 'text',
|
||||
class: 'dl-pal-input',
|
||||
placeholder: 'Search people, devices, IPs or actions…',
|
||||
'aria-label': 'Search',
|
||||
}) as HTMLInputElement;
|
||||
const list = E('div', { class: 'dl-pal-list', role: 'listbox' });
|
||||
const box = E('div', { class: 'dl-pal', role: 'dialog', 'aria-label': 'Command menu' }, [
|
||||
E('label', { class: 'dl-pal-search' }, [icon('search'), input, E('kbd', {}, 'Esc')]),
|
||||
list,
|
||||
E('div', { class: 'dl-pal-foot' }, [
|
||||
E('span', {}, [E('kbd', {}, '↑↓'), ' navigate']),
|
||||
E('span', {}, [E('kbd', {}, '↵'), ' open']),
|
||||
E('span', {}, [E('kbd', {}, '⌘K'), ' toggle']),
|
||||
]),
|
||||
]);
|
||||
const overlay = E('div', { class: 'dl-pal-overlay dl-root' }, box);
|
||||
let items: Item[] = [];
|
||||
let sel = 0;
|
||||
const close = () => {
|
||||
overlay.remove();
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
open = false;
|
||||
};
|
||||
const render = () => {
|
||||
const st = cache?.st;
|
||||
if (!st) {
|
||||
list.replaceChildren(E('div', { class: 'dl-pal-empty' }, 'Loading…'));
|
||||
return;
|
||||
}
|
||||
items = build(st, input.value, () => {
|
||||
cache = null;
|
||||
close();
|
||||
location.reload();
|
||||
});
|
||||
sel = Math.min(sel, Math.max(0, items.length - 1));
|
||||
const nodes: Node[] = [];
|
||||
let group = '';
|
||||
items.forEach((it, i) => {
|
||||
if (it.group !== group) {
|
||||
group = it.group;
|
||||
nodes.push(E('div', { class: 'dl-pal-group' }, group));
|
||||
}
|
||||
const row = E(
|
||||
'div',
|
||||
{
|
||||
class: `dl-pal-item${i === sel ? ' sel' : ''}`,
|
||||
role: 'option',
|
||||
'aria-selected': i === sel ? 'true' : 'false',
|
||||
click: () => {
|
||||
close();
|
||||
it.run();
|
||||
},
|
||||
mousemove: () => {
|
||||
if (sel !== i) {
|
||||
sel = i;
|
||||
render();
|
||||
}
|
||||
},
|
||||
},
|
||||
[
|
||||
it.avatar ? E('span', { class: 'dl-avatar sm' }, it.avatar) : it.icon ? icon(it.icon) : E('span', { class: 'dl-pal-ic' }),
|
||||
E('span', { class: 'dl-pal-label' }, [it.label, it.hint ? E('span', { class: 'dl-faint' }, ` · ${it.hint}`) : '']),
|
||||
it.kbd ? E('kbd', {}, it.kbd) : '',
|
||||
],
|
||||
);
|
||||
nodes.push(row);
|
||||
});
|
||||
if (!items.length) nodes.push(E('div', { class: 'dl-pal-empty' }, 'Nothing found.'));
|
||||
list.replaceChildren(...nodes);
|
||||
list.querySelector('.sel')?.scrollIntoView({ block: 'nearest' });
|
||||
};
|
||||
const onKey = (ev: KeyboardEvent) => {
|
||||
if (ev.key === 'Escape') {
|
||||
ev.preventDefault();
|
||||
close();
|
||||
} else if (ev.key === 'ArrowDown') {
|
||||
ev.preventDefault();
|
||||
sel = Math.min(items.length - 1, sel + 1);
|
||||
render();
|
||||
} else if (ev.key === 'ArrowUp') {
|
||||
ev.preventDefault();
|
||||
sel = Math.max(0, sel - 1);
|
||||
render();
|
||||
} else if (ev.key === 'Enter') {
|
||||
ev.preventDefault();
|
||||
const it = items[sel];
|
||||
if (it) {
|
||||
close();
|
||||
it.run();
|
||||
}
|
||||
}
|
||||
};
|
||||
input.addEventListener('input', () => {
|
||||
sel = 0;
|
||||
render();
|
||||
});
|
||||
overlay.addEventListener('click', (ev) => {
|
||||
if (ev.target === overlay) close();
|
||||
});
|
||||
document.addEventListener('keydown', onKey, true);
|
||||
document.body.appendChild(overlay);
|
||||
input.focus();
|
||||
render();
|
||||
if (!cache || Date.now() - cache.at > 10000) {
|
||||
const st = await api.status(1).catch(() => null);
|
||||
if (st) cache = { st, at: Date.now() };
|
||||
if (open) render();
|
||||
}
|
||||
}
|
||||
|
||||
/** Install the global shortcut once per page load. */
|
||||
export function installPalette(seed?: Status) {
|
||||
if (seed) cache = { st: seed, at: Date.now() };
|
||||
const w = window as any;
|
||||
if (w.__dlPalette) return;
|
||||
w.__dlPalette = true;
|
||||
// Capture phase on window, so Outline's own ⌘K search does not open too.
|
||||
window.addEventListener(
|
||||
'keydown',
|
||||
(ev) => {
|
||||
if (!location.pathname.includes('/admin/network/dawnline')) return;
|
||||
const typing =
|
||||
/^(INPUT|TEXTAREA|SELECT)$/.test((ev.target as HTMLElement)?.tagName ?? '') || (ev.target as HTMLElement)?.isContentEditable;
|
||||
const cmdK = (ev.key === 'k' || ev.key === 'K') && (ev.metaKey || ev.ctrlKey);
|
||||
const slash = ev.key === '/' && !typing && !document.body.classList.contains('modal-overlay-active');
|
||||
if (!cmdK && !slash) return;
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
openPalette();
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Installing a missing package from wherever a feature is turned on: runs the
|
||||
// updater job and follows it with toasts.
|
||||
|
||||
import { api, type Needs } from './api';
|
||||
import { attempt, confirmDialog, notify } from './ui';
|
||||
|
||||
const WHAT: Record<keyof Needs, string> = { https: 'HTTPS for the portal', acme: 'ACME certificates', home: 'the home-like link' };
|
||||
const WAIT_MS = 5 * 60 * 1000;
|
||||
|
||||
/** Install `names` for `feature`; resolves true when the job finished, then calls `done`. */
|
||||
export async function installMissing(feature: keyof Needs, names: string[], done?: () => void): Promise<boolean> {
|
||||
if (!names.length) return true;
|
||||
const ok = await confirmDialog(
|
||||
`Install ${WHAT[feature]}?`,
|
||||
`${names.join(', ')} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,
|
||||
'Install',
|
||||
);
|
||||
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) {
|
||||
const st = await attempt(() => api.updatesStatus());
|
||||
if (st) return installMissing(feature, st.needs?.[feature] ?? [], done);
|
||||
return false;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,316 @@
|
||||
// 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 });
|
||||
}
|
||||
Reference in new issue
Block a user