Dawnline 0.20.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / Backend (Go: vet, tests, a real ubusd and uhttpd) (push) Blocked by required conditions
CI / Package files (push) Blocked by required conditions

- **Backend rewritten in Go.** One daemon, `dawnlined`, replaces the whole ucode backend: the rpcd plugin, the agent, the CLI and the updater. The package no longer depends on ucode.
- **Per-architecture builds.** The release carries the backend for arm64, ARMv7, mips, mipsle and amd64; the router fetches its own after the package is installed and checks its sha256. Dawnline does not run on other architectures (older ARM, 32-bit x86, RISC-V).
- **Faster on the router.** A firewall sync takes 0.06 s instead of 0.9 s; a full apply takes about 300 ms. The portal is served by the daemon itself, without a CGI process per request.
- **Live pages.** The admin and the portal follow a live stream from the router instead of re-fetching the whole state every 30 seconds.
- **Admin redesigned in the portal's style.** Three sections (Overview · Log · Settings); a server is a page of its own with People, Places and Settings; a device opens as a dialog over its person.
- **Changes wait for «Apply».** Every setting, and a person's access, is staged in one dock before it reaches the router.
- **Configuration rollout.** After a change that makes devices fetch their configuration again, the admin shows how many have fetched it and who has not. Every setting shows beforehand (⟳N) how many devices it will touch.
- **Waiting for a decision.** Overview and People put first the people who need one (access ended, limit reached, a device that does not connect), each with its one action a tap away.
- **Bulk actions on people.** «Select» (or a long press on a card) picks several people to extend by a month, pause or resume at once.
- **Undo.** An action done from a card or a request is undone from its toast.
- **Update dialogs redesigned.** An update is one view from its question to its result; Dawnline's own update runs in it like every other, and the page reloads itself once the new version answers. Other versions are a list, each with its notes and Install on a page of its own.
- **Site to site: networks behind a router.** A router connected as a device can have networks behind it (up to eight, /16 to /30): the server routes them and applies the router's access to them. A network that shares addresses with a tunnel, the router's own networks or another site is refused by name.
- **Routers from the portal.** People can add a router and name its networks on their own page; the admin accepts or declines with a reason, or lets them through without asking.
- **Check access and Health know the networks behind routers.**
- **Usage limits reworked.** A monthly limit no longer follows the calendar. A person's month starts with their first traffic and ends a month later; the next one starts only when they connect again, so time away uses up none of it. Before, everyone's limit reset on the 1st.
- Extra data lasts until that person's month ends; «Reset usage» starts the month anew.
- A limit is for a month or for the whole term; the admin and the portal show when it resets.
- Charts that said «this month» show the last 30 days.
- After the update nobody loses what was counted: the month that was running becomes the person's first and ends on the 1st.
- **Access by time of day removed.** The Hours limit is gone from the admin, the portal and the backend; saved hours are dropped.
- **Expiry simplified.** An end date always stops access, with a heads-up three days before; the per-person choice is gone.
- **No false disconnects from sleeping phones.** A phone or a tablet stays online through ten minutes of silence.
- **Mobile Safari fixes.** Pressing a control no longer sends the page to its top; tab tracks that do not fit scroll; switches animate after a press.
This commit is contained in:
Aemeath committed 2026-11-13 09:43:50 +03:00
1 parent f8130e39a8
commit ac90575b0b
788 files changed
+139244 -41720

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
// The admin's demo router (src/admin/demo: past.ts, status.ts, router.ts): the README's pictures are taken from its answers, so they
// hold a cast of the size the README says, the same every time, with nobody's real address in it.
import { describe, expect, it } from 'vitest';
import { joinStatus } from '../src/admin/state/join';
import { PEOPLE } from '../src/admin/demo/cast';
import { NOW } from '../src/admin/demo/past';
import { config, events, health, interfaces, meter, serviceLog } from '../src/admin/demo/router';
import { status, usage } from '../src/admin/demo/status';
const LANGS = ['en', 'ru'] as const;
/** Every IPv4 address written anywhere in a value. */
function addresses(v: unknown, out: string[] = []): string[] {
if (typeof v === 'string') out.push(...(v.match(/\b\d{1,3}(?:\.\d{1,3}){3}\b/g) ?? []));
else if (v && typeof v === 'object') for (const x of Object.values(v)) addresses(x, out);
return out;
}
/** Private, or kept for documentation (RFC 5737): nobody's. */
const nobodys = (ip: string) => /^(10\.|192\.168\.|203\.0\.113\.|198\.51\.100\.|0\.0\.0\.0$)/.test(ip);
describe('the admin demo router', () => {
it('shows eight people with fifteen devices, six of them online', () => {
for (const lang of LANGS) {
const st = status(lang);
const devices = st.people.flatMap((p) => p.devices);
expect([st.people.length, devices.length, devices.filter((d) => d.online).length]).toEqual([8, 15, 6]);
expect(st.totals).toMatchObject({ people: 8, devices: 15, online: 6 });
expect(new Set(devices.map((d) => d.address)).size).toBe(15);
}
});
it('puts people in the states the pictures are about', () => {
const state = Object.fromEntries(status('en').people.map((p) => [p.id, p.state]));
expect(state).toMatchObject({ p_misha: 'quota', p_kirill: 'paused', p_artem: 'active', p_lena: 'active' });
});
it('answers the same every time', () => {
expect(JSON.stringify(events('ru', 5000))).toBe(JSON.stringify(events('ru', 5000)));
expect(status('en').now).toBe(NOW);
});
it('gives no address that is somebody’s', () => {
for (const lang of LANGS) {
const said = [status(lang), events(lang, 5000), health(lang), serviceLog(), interfaces('s_home'), config('d_a1', lang), meter()];
const all = addresses(said);
expect(all.length).toBeGreaterThan(100);
expect(all.filter((ip) => !nobodys(ip))).toEqual([]);
}
});
it('keeps a device’s log, usage and places about that device', () => {
const mine = events('en', 5000, undefined, undefined, 'd_a1').events;
expect(mine.length).toBeGreaterThan(20);
expect(mine.every((e) => e.device === 'd_a1' && e.ts <= NOW)).toBe(true);
// online now: its last event is a connection with no end
expect(mine[mine.length - 1].type).toBe('connect');
const u = usage('p_artem', 31);
expect(u?.person.length).toBe(31);
expect(Object.keys(u?.devices ?? {})).toEqual(PEOPLE.find((p) => p.id === 'p_artem')?.devices.map((d) => d.id));
expect(usage('nobody', 31)).toBeNull();
});
it('cuts into the topics a status is joined from', () => {
const { now, tz, servers, people, circles, services, geo, events: recent, totals, series, hours, ...router } = status('en');
const docs: Record<string, unknown> = {
router,
clock: { now, tz },
traffic: { totals, series, hours },
servers,
people,
circles,
services,
places: geo,
recent,
};
expect(joinStatus((t) => docs[t])).toEqual(status('en'));
});
});
+159
View File
@@ -0,0 +1,159 @@
import { describe, expect, it } from 'vitest';
import {
asksNow,
asksOf,
askCount,
behindRefetch,
netsOf,
reachers,
routerAsks,
routerDeclined,
routersOf,
takenFor,
wishOf,
} from '../src/admin/servers/behind';
import { netRefusal, normNet, tooMany } from '../src/shared/nets';
import { deviceChangedText } from '../src/admin/events/model';
import type { Device, Person } from '../src/shared/types';
const dev = (o: Partial<Device> = {}): Device =>
({
id: 'd1',
name: 'Phone',
kind: 'phone',
disabled: false,
handshake: 100,
config_stale: false,
config_issued: 100,
lan_bypass: false,
...o,
}) as Device;
const person = (o: Partial<Person> = {}): Person =>
({ id: 'p1', name: 'Lena', server: 's1', access: 'both', state: 'active', services: [], home_nets: [], devices: [], ...o }) as Person;
describe('what a router has and asks for', () => {
const has = dev({ id: 'r1', kind: 'router', behind: ['192.168.2.0/24'], ask: ['192.168.3.0/24', '192.168.2.0/24'] });
const waits = dev({ id: 'r2', kind: 'router', waiting: true, ask: ['192.168.4.0/24'] });
const turned = dev({ id: 'r3', kind: 'router', waiting: true, declined: 'talk', ask: ['192.168.5.0/24'] });
const phone = dev({ behind: ['192.168.9.0/24'], ask: ['192.168.8.0/24'], waiting: true });
it('only a router has networks or asks', () => {
expect(netsOf(has)).toEqual(['192.168.2.0/24']);
expect(netsOf(phone)).toEqual([]);
expect(asksNow(phone)).toBe(false);
});
it('a network asked for is one it does not have', () => {
expect(asksOf(has)).toEqual(['192.168.3.0/24']);
expect(asksNow(has)).toBe(true);
expect(asksNow(dev({ kind: 'router', behind: ['192.168.2.0/24'] }))).toBe(false);
});
it('a router asked for is the whole question, its networks with it', () => {
expect(routerAsks(waits)).toBe(true);
expect(asksOf(waits)).toEqual([]);
expect(wishOf(waits)).toEqual(['192.168.4.0/24']);
expect(asksNow(waits)).toBe(true);
});
it('one turned down asks for nothing and is no router of the server', () => {
expect(routerAsks(turned)).toBe(false);
expect(routerDeclined(turned)).toBe(true);
expect(asksNow(turned)).toBe(false);
const people = [
person({ devices: [has, waits, turned, phone] }),
person({ id: 'p2', server: 's2', devices: [dev({ id: 'r9', kind: 'router', waiting: true })] }),
];
expect(routersOf(people, 's1').map((x) => x.d.id)).toEqual(['r1', 'r2']);
expect(askCount(people, 's1')).toBe(2);
expect(askCount(people, 's2')).toBe(1);
});
});
describe('a network typed', () => {
const taken = [{ cidr: '10.77.0.0/24', who: 'the tunnel network of Home' }];
it('is kept from its first address', () => {
expect(normNet(' 192.168.2.7/24 ')).toBe('192.168.2.0/24');
expect(normNet('10.5.200.1/16')).toBe('10.5.0.0/16');
});
it('is a private network of a site’s size', () => {
expect(netRefusal('192.168.2.0/24', taken)).toBeNull();
expect(netRefusal('10.5.0.0/16', taken)).toBeNull();
expect(netRefusal('192.168.2.0', taken)).toContain('is not a network like');
expect(netRefusal('8.8.8.0/24', taken)).toContain('not a private network');
expect(netRefusal('172.32.0.0/24', taken)).toContain('not a private network');
expect(netRefusal('10.0.0.0/8', taken)).toContain('too wide');
expect(netRefusal('10.4.0.0/15', taken)).toContain('too wide');
});
it('shares no address with what something has', () => {
expect(netRefusal('10.77.0.128/25', taken)).toBe(
'10.77.0.0/24 is taken: it is the tunnel network of Home. The two ends need different ranges.',
);
expect(netRefusal('10.77.0.0/16', taken)).toContain('10.77.0.0/24 is taken');
});
it('is one of eight at the most', () => {
expect(tooMany(8)).toBeNull();
expect(tooMany(9)).toContain('8 networks behind one router');
});
it('is held against tunnels, the router’s own and other devices’ networks, a staged list included', () => {
const r1 = dev({ id: 'r1', kind: 'router', behind: ['192.168.2.0/24'] });
const r2 = dev({ id: 'r2', name: 'Dacha', kind: 'router', behind: ['192.168.3.0/24'] });
const people = [person({ devices: [r1, r2] })];
const t = takenFor([{ name: 'Home', subnet: '10.77.0.0/24' }], [{ name: 'br-lan', nets: ['192.168.1.0/24'] }], people, r1, (o) =>
o.id === 'r2' ? ['192.168.30.0/24'] : (o.behind ?? []),
);
expect(t.map((x) => x.cidr)).toEqual(['10.77.0.0/24', '192.168.1.0/24', '192.168.30.0/24']);
expect(t[2].who).toBe('the network behind Dacha');
});
});
describe('who fetches again when a router’s networks change', () => {
const router = dev({ id: 'r1', kind: 'router' });
const owner = person({ id: 'boris', circle: 'fam', devices: [router, dev({ id: 'b2', lan_bypass: true })] });
const people = [
owner,
// sends everything into the tunnel: no word of any network in its configuration
person({
id: 'anna',
circle: 'fam',
devices: [dev({ id: 'a1' }), dev({ id: 'a2', lan_bypass: true }), dev({ id: 'a3', lan_bypass: true, disabled: true })],
}),
person({ id: 'dima', access: 'lan', circle: 'work', devices: [dev({ id: 'd1' }), dev({ id: 'd2', config_issued: 0, handshake: 0 })] }),
person({ id: 'eva', access: 'lan', services: ['nas'], devices: [dev({ id: 'e1' })] }),
person({ id: 'clara', access: 'internet', devices: [dev({ id: 'c1', lan_bypass: true })] }),
person({ id: 'far', server: 's2', devices: [dev({ id: 'f1', lan_bypass: true })] }),
];
const ids = (mesh: 'off' | 'all' | 'circles') => reachers(people, { id: 's1', mesh }, owner, router).map((x) => x.d.id);
it('everyone who is part of home, where everyone reaches everyone; never the router itself', () => {
expect(ids('all')).toEqual(['b2', 'a2', 'd1', 'd2']);
});
it('the circle, where devices are kept within circles', () => {
expect(ids('circles')).toEqual(['b2', 'a2']);
});
it('nobody while devices are kept apart, or when its owner is no part of home', () => {
expect(ids('off')).toEqual([]);
expect(reachers(people, { id: 's1', mesh: 'all' }, people[4], dev({ id: 'c1' }))).toEqual([]);
});
it('counts those that hold a configuration, each once', () => {
expect(behindRefetch(people, { id: 's1', mesh: 'all' }, [{ p: owner, d: router }])).toBe(3);
expect(
behindRefetch(people, { id: 's1', mesh: 'all' }, [
{ p: owner, d: router },
{ p: people[1], d: dev({ id: 'a1' }) },
]),
).toBe(3);
expect(behindRefetch(people, { id: 's1', mesh: 'off' }, [{ p: owner, d: router }])).toBe(0);
});
});
describe('what the log says of a router’s networks and requests', () => {
it('words each change the router writes', () => {
expect(deviceChangedText('networks=192.168.2.0/24 172.20.0.0/16')).toBe('networks behind it: 192.168.2.0/24, 172.20.0.0/16');
expect(deviceChangedText('networks=none')).toBe('no networks behind it');
expect(deviceChangedText('asked=router, asked=192.168.88.0/24')).toBe('the router is asked for, asked for: 192.168.88.0/24');
expect(deviceChangedText('withdrew=192.168.3.128/25')).toBe('no longer asked for: 192.168.3.128/25');
expect(deviceChangedText('accepted=router, accepted=192.168.88.0/24')).toBe('the router accepted, accepted: 192.168.88.0/24');
expect(deviceChangedText('declined=192.168.89.0/24, reason=overlap')).toBe(
'declined: 192.168.89.0/24, reason: It shares addresses with a network here',
);
expect(deviceChangedText('declined=router, reason=plain')).toBe('the router declined, no reason given');
expect(deviceChangedText('reopened=router')).toBe('the router is asked for again');
expect(deviceChangedText('kind=phone, networks=none')).toBe('type: Phone, no networks behind it');
});
});
+359
View File
@@ -0,0 +1,359 @@
import { describe, expect, it } from 'vitest';
import { byAttention, cardParts, groupOf, ofLimit, type CardFacts, type CardParts, type Ranked } from '../src/admin/people/card';
import { byPerson, midnight, presence, timeIn } from '../src/admin/people/presence';
import type { Device, LogEvent, Person, Server } from '../src/shared/types';
// The matrix of a person's card (the concept's docs/ia2/10-people-cards.md with its amendments), a row a state:
// what the card must have. The router at 2026-11-07 14:00 UTC+3.
const NOW = Date.UTC(2026, 10, 7, 11, 0) / 1000;
const T = { today: '2026-11-07', now: NOW };
const H = 3600;
const DAY = 86400;
const GB = 2 ** 30;
const dev = (o: Partial<Device> = {}): Device =>
({
id: 'd1',
name: 'iPhone',
kind: 'phone',
address: '10.8.0.2',
disabled: false,
online: false,
handshake: NOW - 3 * H,
endpoint: '91.1.2.3:51820',
config_stale: false,
lan_bypass: false,
link: null,
spark: [],
month: [0, 0],
total: [0, 0],
...o,
}) as Device;
const person = (o: Partial<Person> = {}): Person =>
({
id: 'p',
name: 'Test',
server: 's',
access: 'internet',
device_limit: 3,
expires: '',
quota_gb: 0,
quota_period: 'month',
quota_used: 0,
quota_limit: 0,
// their limit month began on 19 Oct with their first traffic: it ends on 19 Nov, not on the 1st
quota_month: [0, 0],
quota_resets: NOW + 12 * DAY,
quota_reset_day: '2026-11-19',
bonus_gb: 0,
dns_mode: 'device',
paused: false,
state: 'active',
month: [1 * GB, 9 * GB],
total: [0, 0],
online: 0,
last_seen: NOW - 3 * H,
devices: [dev()],
has_link: true,
...o,
}) as Person;
const on = { id: 's', name: 'Home', enabled: true } as Server;
const off = { id: 's', name: 'Dacha', enabled: false } as Server;
interface Row {
name: string;
p: Person;
srv?: Server;
facts?: CardFacts;
want: Partial<Pick<CardParts, 'state' | 'group' | 'presence' | 'traffic' | 'meter' | 'tiles' | 'quiet'>> & {
line: RegExp | null;
action: RegExp | null;
};
}
const rows: Row[] = [
{
name: 'no server',
p: person({ state: 'no_server', server: '' }),
want: {
state: 'no_server',
group: 'need',
line: /^No server$/,
presence: null,
traffic: false,
tiles: false,
action: /^Choose a server$/,
quiet: false,
},
},
{
name: 'server turned off',
p: person({ state: 'server_off' }),
srv: off,
want: {
state: 'server_off',
group: 'rest',
line: /^Server Dacha is turned off$/,
presence: null,
traffic: false,
tiles: true,
action: null,
},
},
{
name: 'paused',
p: person({ state: 'paused', paused: true }),
srv: on,
facts: { pausedAt: '2026-11-03' },
want: {
state: 'paused',
group: 'paused',
line: /^Paused since 3 Nov$/,
presence: null,
traffic: false,
tiles: true,
action: /^Resume$/,
quiet: true,
},
},
{
name: 'access ended',
p: person({ state: 'expired', expires: '2026-11-03' }),
srv: on,
want: { state: 'expired', group: 'need', line: /^Access ended 3 Nov$/, presence: null, traffic: false, action: /^Extend to 7 Dec$/ },
},
{
name: 'limit reached',
p: person({ state: 'quota', quota_gb: 50, quota_limit: 50 * GB, quota_used: 50.3 * GB }),
srv: on,
want: {
state: 'quota',
group: 'need',
line: /^Limit reached · 50\.3 of 50 GB$/,
presence: null,
traffic: false,
action: /^\+20 GB until 19 Nov$/,
},
},
{
name: 'a term limit reached',
p: person({ state: 'quota', quota_period: 'total', quota_gb: 5, quota_limit: 5 * GB, quota_used: 9 * GB }),
srv: on,
want: { state: 'quota', group: 'need', line: /^Term limit reached · 9 of 5 GB$/, action: /^Change the limit$/ },
},
{
name: 'a device fails',
p: person({ devices: [dev({ name: 'ThinkPad', link: { state: 'trying', since: NOW - H } as Device['link'] })] }),
srv: on,
want: {
state: 'device',
group: 'need',
line: /^ThinkPad does not connect$/,
presence: null,
traffic: false,
tiles: true,
action: /^Advice · ThinkPad$/,
},
},
{
name: 'a new configuration (a rollout, not a decision)',
p: person({ devices: [dev({ name: 'Laptop', config_stale: true })] }),
srv: on,
want: { state: 'offline', group: 'rest', line: null, presence: 'offline', traffic: true, tiles: true, action: null },
},
{
name: 'a new configuration and the end near',
p: person({ expires: '2026-11-09', devices: [dev({ name: 'Laptop', config_stale: true })] }),
srv: on,
want: { state: 'soon', group: 'need', line: /^Access until 9 Nov · 3 days$/, action: /^Extend to 9 Dec$/ },
},
{
name: 'the end near',
p: person({ expires: '2026-11-09' }),
srv: on,
want: {
state: 'soon',
group: 'need',
line: /^Access until 9 Nov · 3 days$/,
presence: null,
traffic: false,
action: /^Extend to 9 Dec$/,
},
},
{
name: 'the last day',
p: person({ expires: '2026-11-07' }),
srv: on,
want: { state: 'soon', group: 'need', line: /^Access until 7 Nov · last day$/, action: /^Extend to 7 Dec$/ },
},
{
name: 'the limit nearly reached',
p: person({ quota_gb: 50, quota_limit: 50 * GB, quota_used: 46 * GB }),
srv: on,
want: {
state: 'almost',
group: 'need',
line: /^Limit nearly reached · 46 of 50 GB$/,
presence: null,
traffic: false,
action: /^\+10 GB until 19 Nov$/,
},
},
{
name: 'no devices',
p: person({ devices: [], last_seen: 0, month: [0, 0] }),
srv: on,
want: {
state: 'no_devices',
group: 'rest',
line: /^No devices yet$/,
presence: null,
traffic: false,
tiles: false,
action: /^Invite$/,
},
},
{
name: 'online',
p: person({ online: 1, last_seen: NOW - 20, devices: [dev({ online: true })] }),
srv: on,
want: { state: 'online', group: 'online', line: null, presence: 'online', traffic: true, meter: null, tiles: true, action: null },
},
{
name: 'online, a limit used 9 %',
p: person({ online: 1, devices: [dev({ online: true })], quota_gb: 100, quota_limit: 100 * GB, quota_used: 9 * GB }),
srv: on,
want: { state: 'online', group: 'online', line: null, presence: 'online', traffic: true, meter: 'of', action: null },
},
{
name: 'offline, a limit used 60 %',
p: person({ quota_gb: 100, quota_limit: 100 * GB, quota_used: 60 * GB }),
srv: on,
want: { state: 'offline', group: 'rest', line: null, presence: 'offline', traffic: true, meter: 'bar', action: null },
},
{
name: 'offline for up to 7 days',
p: person(),
srv: on,
want: { state: 'offline', group: 'rest', line: null, presence: 'offline', traffic: true, meter: null, action: null },
},
{
name: 'long away, traffic in the last 30 days',
p: person({ last_seen: NOW - 12 * DAY }),
srv: on,
facts: { city: 'Moscow' },
want: {
state: 'away',
group: 'rest',
line: /^Not connected for 12 days · Moscow$/,
presence: null,
traffic: true,
action: null,
},
},
{
name: 'long away, nothing this month',
p: person({ last_seen: NOW - 21 * DAY, month: [0, 0] }),
srv: on,
facts: { city: 'Moscow' },
want: { state: 'away', group: 'rest', line: /^Not connected for 21 days · Moscow$/, presence: null, traffic: true, action: null },
},
{
name: 'never connected, a link',
p: person({ last_seen: 0, month: [0, 0], devices: [dev({ handshake: 0 })] }),
srv: on,
want: { state: 'never', group: 'rest', line: /^Not connected yet$/, presence: null, traffic: false, action: /^Link$/, quiet: true },
},
{
name: 'never connected, no link',
p: person({ last_seen: 0, has_link: false, month: [0, 0], devices: [dev({ handshake: 0 })] }),
srv: on,
want: { state: 'never', group: 'rest', line: /^Not connected yet$/, action: /^Invite$/, quiet: false },
},
];
describe('the card matrix', () => {
it.each(rows.map((r) => [r.name, r] as const))('%s', (_n, r) => {
const c = cardParts(r.p, r.srv, T, r.facts);
// the line keeps its «·» with the word before it (a no-break space): read with plain spaces
const line = c.line?.replace(/ /g, ' ') ?? null;
const { line: wantLine, action, ...rest } = r.want;
expect(c).toMatchObject(rest);
if (wantLine) expect(line).toMatch(wantLine);
else expect(line).toBeNull();
if (action) expect(c.action?.label ?? '').toMatch(action);
else expect(c.action).toBeNull();
});
it('says the first problem, counts the others, and keeps a rollout out of it', () => {
const p = person({
expires: '2026-11-09',
devices: [
dev({ name: 'ThinkPad', link: { state: 'trying', since: NOW - H } as Device['link'] }),
dev({ id: 'd2', config_stale: true }),
],
});
const c = cardParts(p, on, T);
expect(c.state).toBe('device');
expect(c.more).toEqual(['Access until 9 Nov · 3 days']);
expect(c.title).toContain('ThinkPad does not connect');
expect(c.stale).toEqual(['d2']);
});
it('keeps a dot with the word before it', () => {
expect(cardParts(person({ expires: '2026-11-09' }), on, T).line).toBe('Access until 9 Nov · 3 days');
});
it('says a limit with its unit once', () => {
expect(ofLimit(50.3 * GB, 50 * GB)).toBe('50.3 of 50 GB');
expect(ofLimit(512 * 2 ** 20, 50 * GB)).toBe('512 MB of 50 GB');
});
it('groups by the matrix: the chip, the heads and Overview count one way', () => {
expect(groupOf(person({ devices: [dev({ config_stale: true })] }), T)).toBe('rest');
expect(groupOf(person({ state: 'server_off' }), T)).toBe('rest');
expect(groupOf(person({ state: 'paused', paused: true }), T)).toBe('paused');
expect(groupOf(person({ expires: '2026-11-09' }), T)).toBe('need');
});
});
describe('the order of attention', () => {
const ranked = (p: Person, o: Partial<Ranked> = {}): Ranked => ({ p, parts: cardParts(p, on, T), speed: 0, week: 0, pausedAt: '', ...o });
it('puts the groups in order, and each in its own', () => {
const list = [
ranked(person({ id: 'away', last_seen: NOW - 20 * DAY })),
ranked(person({ id: 'slow', online: 1, devices: [dev({ online: true })] }), { speed: 10 }),
ranked(person({ id: 'soon', expires: '2026-11-09' })),
ranked(person({ id: 'off', last_seen: NOW - 2 * H })),
ranked(person({ id: 'p2', state: 'paused', paused: true }), { pausedAt: '2026-11-05' }),
ranked(person({ id: 'p1', state: 'paused', paused: true }), { pausedAt: '2026-11-01' }),
ranked(person({ id: 'fast', online: 1, devices: [dev({ online: true })] }), { speed: 99 }),
ranked(person({ id: 'ended', state: 'expired', expires: '2026-11-01' })),
ranked(person({ id: 'never', last_seen: 0, devices: [dev({ handshake: 0 })] })),
];
expect(byAttention(list, T.today).map((x) => x.p.id)).toEqual(['ended', 'soon', 'fast', 'slow', 'off', 'away', 'never', 'p1', 'p2']);
});
});
describe('presence from the log', () => {
const ev = (ts: number, type: string, device = 'd1'): LogEvent => ({ ts, type, person: 'p', device, where: 'Krasnodar · MTS' });
it('says since when they are online and their hours this week', () => {
const p = person({ online: 1, devices: [dev({ online: true, handshake: NOW - 10 })] });
const log = [ev(NOW - 2 * DAY, 'connect'), ev(NOW - 2 * DAY + 5 * H, 'disconnect'), ev(NOW - 3 * H, 'connect')];
const pr = presence(p, on, log, NOW, 180);
expect(pr.since).toBe(NOW - 3 * H);
expect(Math.round(pr.week / H)).toBe(8);
expect(pr.devices.map((x) => x.d.id)).toEqual(['d1']);
});
it('is offline without an open stretch', () => {
const pr = presence(person(), on, [ev(NOW - 5 * H, 'connect'), ev(NOW - 3 * H, 'disconnect')], NOW, 180);
expect(pr.since).toBe(0);
expect(Math.round(pr.week / H)).toBe(2);
});
it('sorts the log by person and counts time in a window', () => {
const m = byPerson([ev(1, 'connect'), { ts: 2, type: 'x' }, { ...ev(3, 'connect'), person: 'q' }]);
expect([...m.keys()]).toEqual(['p', 'q']);
expect(timeIn([{ a: 0, b: 10 }], 5, 20)).toBe(5);
expect(midnight(Date.UTC(2026, 10, 7, 23, 0) / 1000, 180)).toBe(Date.UTC(2026, 10, 7, 21, 0) / 1000);
});
});
+100
View File
@@ -0,0 +1,100 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { carryControls, carryOn, flippedNow } from '../src/portal/ui/carry';
/** A control as far as the carry reads it: its class `on`, its ARIA state, its title, and the moves under way on it. */
class Ctl {
on: boolean;
attrs = new Map<string, string>();
isConnected = true;
offsetWidth = 0;
tagName = 'BUTTON';
textContent: string;
/** How many times it was given a state to show (its class set). */
turns = 0;
moves: { currentTime: number }[] = [];
constructor(title: string, on: boolean, aria: 'aria-checked' | 'aria-pressed' = 'aria-checked', role: string | null = 'switch') {
this.textContent = title;
this.on = on;
this.attrs.set(aria, String(on));
if (role) this.attrs.set('role', role);
}
classList = {
contains: (c: string) => c === 'on' && this.on,
toggle: (c: string, v: boolean) => {
if (c === 'on') this.on = v;
this.turns++;
},
};
/** What it shows now. */
get says() {
return `${this.on ? 'on' : 'off'}/${this.attrs.get('aria-checked') ?? this.attrs.get('aria-pressed')}`;
}
getAttribute = (a: string) => this.attrs.get(a) ?? null;
hasAttribute = (a: string) => this.attrs.has(a);
setAttribute(a: string, v: string) {
this.attrs.set(a, v);
}
querySelector = () => null;
querySelectorAll = () => [];
matches = () => true;
getAnimations = () => this.moves;
}
/** A region: the controls in it. */
const region = (...list: Ctl[]) => ({ querySelectorAll: () => list }) as unknown as ParentNode;
const el = (c: Ctl) => c as unknown as HTMLElement;
/** The task ends: what waits for the controls to be in the page runs. */
const settle = () => new Promise<void>((r) => queueMicrotask(r));
describe('the controls of a region drawn again', () => {
beforeEach(() => {
vi.stubGlobal('HTMLElement', Ctl);
vi.stubGlobal('CSSTransition', Object);
});
afterEach(() => vi.unstubAllGlobals());
it('one that shows another state starts as the old one stood, then turns to its own', async () => {
const old = new Ctl('Mirrors', false);
const neu = new Ctl('Mirrors', true);
carryControls(region(old), [el(neu)]);
expect(neu.says).toBe('off/false');
await settle();
expect(neu.says).toBe('on/true');
});
it('one that shows the same and was not just pressed is left alone', async () => {
const neu = new Ctl('Mirrors', true);
carryControls(region(new Ctl('Mirrors', true)), [el(neu)]);
await settle();
expect(neu.turns).toBe(0);
});
it('one whose old one moved its knob itself a moment ago goes on with that move', async () => {
const old = new Ctl('Mirrors', true);
flippedNow(el(old));
const neu = new Ctl('Mirrors', true);
neu.moves = [{ currentTime: 0 }, { currentTime: 0 }];
await new Promise((r) => setTimeout(r, 30));
carryControls(region(old), [el(neu)]);
expect(neu.says).toBe('off/false');
await settle();
expect(neu.says).toBe('on/true');
// as far into the move as the old one was
for (const m of neu.moves) expect(m.currentTime).toBeGreaterThanOrEqual(25);
});
it('pairs by name, not by place: a control that came in between takes nobody else’s state', async () => {
const [a, b] = [new Ctl('Keep the previous version', true), new Ctl('Mirrors', false)];
const [x, y, z] = [new Ctl('Keep the previous version', true), new Ctl('New one', true), new Ctl('Mirrors', true)];
carryControls(region(a, b), [el(x), el(y), el(z)]);
await settle();
expect([x.turns, y.turns, z.turns]).toEqual([0, 0, 2]);
expect(z.says).toBe('on/true');
});
it('leaves a control that was carried by its own name', async () => {
const old = new Ctl('AmneziaWG', false, 'aria-pressed', null);
const neu = new Ctl('AmneziaWG', true, 'aria-pressed', null);
carryOn('test-chip', el(old), false);
carryOn('test-chip', el(neu), true);
carryControls(region(old), [el(neu)]);
await settle();
// turned once: from the old state to its own
expect([neu.turns, neu.says]).toEqual([2, 'on/true']);
});
});
+11 -33
View File
@@ -1,7 +1,17 @@
import { describe, expect, it } from 'vitest';
import { calendar, clockOf, hoursFor, minuteAt, minuteOf, monthOf, stretches } from '../src/portal/days';
import { calendar, weeks } from '../src/portal/days';
describe('days', () => {
it('lays a far end out one cell a week, to the week it ends in', () => {
// Wed 21 Oct 2026 to Mon 8 Feb 2027: this week, fifteen between, the last one.
const w = weeks('2026-10-21', '2027-02-08')!;
expect(w).toHaveLength(17);
expect(w[0]).toEqual({ day: '2026-10-19', kind: 'today' });
expect(w[16]).toEqual({ day: '2027-02-08', kind: 'end' });
expect(w.slice(1, 16).every((x) => x.kind === 'left')).toBe(true);
// past 28 weeks the number of days says it alone
expect(weeks('2026-10-21', '2027-10-21')).toBeNull();
});
it('lays the weeks to the end out Monday first, one cell a day', () => {
// Mon 19 Oct 2026 to Fri 23 Oct: one week.
const c = calendar('2026-10-19', '2026-10-23')!;
@@ -17,36 +27,4 @@ describe('days', () => {
expect(calendar('2026-10-19', '2026-12-27')).not.toBeNull();
expect(calendar('2026-10-19', '2027-03-01')).toBeNull();
});
it('reads and writes clock times', () => {
expect(minuteOf('08:30')).toBe(510);
expect(minuteOf('8:05')).toBe(485);
expect(minuteOf('24:00')).toBeNull();
expect(clockOf(510)).toBe('08:30');
expect(clockOf(-30)).toBe('23:30');
expect(clockOf(1440 + 60)).toBe('01:00');
});
it('moves the hours into the visitor’s time', () => {
// Router on UTC+3, visitor on UTC+1: two hours earlier.
expect(hoursFor('08:00-23:00', 180, 60)).toEqual({ from: 360, to: 1260, yours: true });
// Without the router's offset: its own time, as set.
expect(hoursFor('08:00-23:00', undefined, 60)).toEqual({ from: 480, to: 1380, yours: false });
expect(hoursFor('nonsense', 0, 0)).toBeNull();
});
it('splits a window over midnight into two stretches', () => {
expect(stretches({ from: 480, to: 1380, yours: true })).toEqual([[480, 1380]]);
expect(stretches({ from: 1320, to: 360, yours: true })).toEqual([
[1320, 1440],
[0, 360],
]);
});
it('finds the minute of the day and the days of the month', () => {
// 2026-10-19 12:00 UTC is 15:00 on UTC+3.
expect(minuteAt(Date.UTC(2026, 9, 19, 12) / 1000, 180)).toBe(900);
expect(monthOf('2026-10-19')).toEqual({ days: 31, day: 19 });
expect(monthOf('2028-02-03')).toEqual({ days: 29, day: 3 });
});
});
+68 -10
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { createRouter, type DemoDb, type Keep } from '../src/portal/demo/router';
import { SCENARIOS, hoursAway, monthDays } from '../src/portal/demo/data';
import { SCENARIOS, monthDays } from '../src/portal/demo/data';
import { wayState } from '../src/portal/way';
import type { State } from '../src/portal/state';
import type { AwgConfig } from '../src/shared/types';
@@ -23,7 +23,8 @@ describe('demo router', () => {
const { state } = demo(s.id);
const st = state();
expect(st.person.name).toBe('User');
expect(st.person.devices.length).toBe(s.id === 'first' ? 0 : 3);
expect(st.person.devices.length).toBe(s.id === 'first' ? 0 : s.id === 'site' ? 4 : 3);
expect(st.server).toMatchObject({ routers: 'ask', nets: 'ask' });
}
expect(demo('paused').state().person.state).toBe('paused');
expect(demo('paused').state().locked).toBe(true);
@@ -89,6 +90,68 @@ describe('demo router', () => {
expect(state().person.devices.map((d) => d.id)).not.toContain(id);
});
it('asks the admin for a router, which waits with its networks and gets no settings', () => {
const { r, state, later } = demo();
expect(r.answer('POST', 'devices', { name: 'Tablet', kind: 'tablet', networks: ['192.168.9.0/24'] }).body).toMatchObject({
error: 'Only a router has networks behind it.',
});
expect(r.answer('POST', 'devices', { name: 'Dacha', kind: 'router', networks: ['192.168.1.0/24'] }).status).toBe(400);
const a = r.answer('POST', 'devices', { name: 'Dacha', kind: 'router', networks: ['192.168.88.7/24', '192.168.88.0/24'] });
const { id, waiting, config } = a.body as { id: string; waiting?: boolean; config?: AwgConfig };
expect(a.status).toBe(200);
expect(waiting).toBe(true);
expect(config).toBeUndefined();
later(60);
expect(state().person.devices.find((d) => d.id === id)).toMatchObject({
kind: 'router',
waiting: true,
ask: ['192.168.88.0/24'],
handshake: 0,
online: false,
});
expect(r.answer('GET', `devices/${id}/config`).status).toBe(409);
expect(r.answer('POST', `devices/${id}`, { action: 'reconnect' }).status).toBe(400);
// what is asked for with it changes while it waits; nothing is its own yet
r.answer('POST', `devices/${id}`, { action: 'networks', networks: ['192.168.89.0/24'] });
expect(state().person.devices.find((d) => d.id === id)).toMatchObject({ ask: ['192.168.89.0/24'] });
expect(state().person.devices.find((d) => d.id === id)?.behind).toBeUndefined();
// a phone is not made a router by setting it up again
const phone = state().person.devices.find((d) => d.kind === 'phone')!;
expect(r.answer('POST', `devices/${phone.id}`, { action: 'reconnect', kind: 'router' }).status).toBe(400);
});
it('takes a network away at once, asks for a new one and puts a turned-down one away', () => {
const { r, state } = demo('site');
const router = () => state().person.devices.find((d) => d.kind === 'router')!;
expect(router()).toMatchObject({
behind: ['192.168.2.0/24'],
ask: ['192.168.20.0/24'],
declined: 'overlap',
declined_nets: ['192.168.1.0/24'],
});
const id = router().id;
// one more asked for, the one that waited taken back, the turned-down one put away
expect(
r.answer('POST', `devices/${id}`, {
action: 'networks',
networks: ['192.168.2.0/24', '192.168.30.0/24'],
cleared: ['192.168.1.0/24'],
}).status,
).toBe(200);
expect(router()).toMatchObject({ behind: ['192.168.2.0/24'], ask: ['192.168.30.0/24'] });
expect(router().declined).toBeUndefined();
// its own network taken away: gone at once
r.answer('POST', `devices/${id}`, { action: 'networks', networks: [] });
expect(router().behind).toBeUndefined();
expect(router().ask).toBeUndefined();
// what the page checks, the router checks too
expect(r.answer('POST', `devices/${id}`, { action: 'networks', networks: ['8.8.8.0/24'] }).status).toBe(400);
const phone = state().person.devices.find((d) => d.kind === 'phone')!;
expect(r.answer('POST', `devices/${phone.id}`, { action: 'networks', networks: ['192.168.9.0/24'] }).body).toMatchObject({
error: 'Only a router has networks behind it.',
});
});
it('starts a scenario over', () => {
const { r, state } = demo('normal');
r.answer('POST', 'devices', { name: 'Pixel 9', kind: 'phone' });
@@ -99,11 +162,11 @@ describe('demo router', () => {
});
describe('demo data', () => {
it('spreads the month over its days', () => {
it('spreads the last 30 days over their days', () => {
const t = new Date(2026, 9, 19, 12).getTime() / 1000;
const days = monthDays(1000, t);
expect(days).toHaveLength(19);
expect(Math.abs(days.reduce((a, [rx, tx]) => a + rx + tx, 0) - 1000)).toBeLessThanOrEqual(19);
expect(days).toHaveLength(30);
expect(Math.abs(days.reduce((a, [rx, tx]) => a + rx + tx, 0) - 1000)).toBeLessThanOrEqual(30);
});
it('holds the device being set up in the state the visitor picks', () => {
@@ -134,9 +197,4 @@ describe('demo data', () => {
r.answer('POST', `devices/${id}`, { action: 'delete' });
expect(r.settingUp()).toBe(null);
});
it('keeps the hours scenario outside its window', () => {
expect(hoursAway(new Date(2026, 9, 19, 22, 30).getTime() / 1000)).toBe('00:00-08:00');
expect(hoursAway(new Date(2026, 9, 19, 9).getTime() / 1000)).toBe('11:00-19:00');
});
});
+82
View File
@@ -0,0 +1,82 @@
import { describe, expect, it } from 'vitest';
import type { Device, Person } from '../src/shared/types';
import { draftCount, draftParts, draftRefetch, preview, split, stageDraft } from '../src/admin/people/draft';
const GIB = 1073741824;
const dev = (o: Partial<Device>): Device =>
({ id: 'd', name: 'Phone', kind: 'phone', handshake: 100, disabled: false, lan_bypass: false, ...o }) as Device;
const person = (o: Partial<Person> = {}): Person =>
({
id: 'p',
name: 'Lena',
server: 's1',
access: 'both',
device_limit: 4,
expires: '',
quota_gb: 100,
quota_period: 'month',
quota_used: 30 * GIB,
quota_limit: 110 * GIB,
bonus_gb: 10,
dns_mode: 'home',
paused: false,
state: 'active',
month: [10 * GIB, 20 * GIB],
total: [100 * GIB, 200 * GIB],
online: 1,
last_seen: 0,
devices: [dev({ id: 'a' }), dev({ id: 'b', lan_bypass: true }), dev({ id: 'c', handshake: 0 })],
services: ['nas'],
home_nets: [],
circle: 'c1',
...o,
}) as Person;
describe("a person's changes that wait", () => {
it('splits a patch into what waits and what is saved at once', () => {
expect(split({ name: 'Lena K', access: 'lan', quota_gb: '', paused: true, note: undefined })).toEqual({
waits: { access: 'lan', quota_gb: '' },
now: { name: 'Lena K', paused: true },
});
});
it('keeps one value a field and lets go of one put back', () => {
const p = person();
let d = stageDraft({}, p, { access: 'lan' });
d = stageDraft(d, p, { quota_gb: '50', services: ['nas', 'printer'] });
expect(d).toEqual({ access: 'lan', quota_gb: '50', services: ['nas', 'printer'] });
expect(draftCount(d)).toBe(3);
expect([...draftParts(d)].sort()).toEqual(['limit', 'reach']);
d = stageDraft(d, p, { access: 'both', quota_gb: '100', services: ['nas'] });
expect(d).toEqual({});
// no limit is '' or 0, a list is the same in any order, no circle is ''
expect(stageDraft({}, person({ quota_gb: 0 }), { quota_gb: '' })).toEqual({});
expect(stageDraft({}, person({ home_nets: ['br-lan', 'guest'] }), { home_nets: ['guest', 'br-lan'] })).toEqual({});
expect(stageDraft({}, person({ circle: undefined }), { circle: '' })).toEqual({});
expect(stageDraft({}, p, { device_limit: '4' })).toEqual({});
expect(stageDraft({}, p, { device_limit: '5' })).toEqual({ device_limit: '5' });
});
it('shows the person as they would be', () => {
const p = person();
expect(preview(p, {})).toBe(p);
const q = preview(p, { access: 'internet', quota_gb: '50', device_limit: '6', circle: '' });
expect(q).toMatchObject({ access: 'internet', quota_gb: 50, device_limit: 6, circle: '' });
// this month's 10 GB extra stays on top of the new limit
expect(q.quota_limit).toBe(60 * GIB);
expect(preview(p, { quota_gb: '' }).quota_limit).toBe(0);
expect(preview(p, { quota_period: 'total' })).toMatchObject({ quota_period: 'total', quota_used: 300 * GIB });
// the person the router answered with is not touched
expect(p.access).toBe('both');
});
it('counts the devices that fetch again once, whatever of their access changes', () => {
const p = person();
// both → internet: only the one with LAN Bypass; to Home only: every one that has connected
expect(draftRefetch(p, { access: 'internet' })).toBe(1);
expect(draftRefetch(p, { access: 'lan' })).toBe(2);
expect(draftRefetch(p, { access: 'lan', home_nets: ['br-lan'], dns_mode: 'device' })).toBe(2);
expect(draftRefetch(p, { home_nets: ['br-lan'] })).toBe(1);
expect(draftRefetch(p, { quota_gb: '50', device_limit: '6', services: [] })).toBe(0);
});
});
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it, vi } from 'vitest';
import { failureKind, failureText } from '../src/admin/failure';
describe('failure', () => {
it('says a sentence as it came: the backend refusal, the page’s own, in any script', () => {
expect(failureKind(new Error('Port 51820 is already taken.'))).toBe('said');
expect(failureKind(new Error('Порт 51820 уже занят.'))).toBe('said');
expect(failureText(new Error(' Port 51820 is already taken. '))).toBe('Port 51820 is already taken.');
});
it('tells LuCI’s reports of the bus by their code', () => {
const rpc = (tail: string) => new Error(`RPC call to dawnline/status failed with ${tail}`);
expect(failureKind(rpc('ubus code 4: Resource not found'))).toBe('away');
expect(failureKind(rpc('ubus code 10: Connection lost'))).toBe('away');
expect(failureKind(rpc('ubus code 7: Request timeout'))).toBe('slow');
expect(failureKind(rpc('ubus code 6: Permission denied'))).toBe('denied');
expect(failureKind(rpc('ubus code 3: Method not found'))).toBe('mismatch');
expect(failureKind(rpc('error -32002: Access denied'))).toBe('session');
expect(failureKind(rpc('error -32000: Object not found'))).toBe('away');
expect(failureKind(rpc('HTTP error 0: ?'))).toBe('offline');
expect(failureKind(rpc('HTTP error 502: Bad Gateway'))).toBe('server');
expect(failureKind(new Error('RPC call to dawnline/status returned invalid message frame'))).toBe('mismatch');
});
it('tells the network’s and the engine’s own, and a programmer’s text', () => {
expect(failureKind(new Error('XHR request timed out'))).toBe('slow');
expect(failureKind(new TypeError('Failed to fetch'))).toBe('offline');
expect(failureKind(new TypeError('Cannot read properties of undefined'))).toBe('bug');
expect(failureKind(new Error('integrity'))).toBe('bug');
expect(failureKind(new Error('open /etc/config/dawnline: no such file or directory'))).toBe('bug');
expect(failureKind(undefined)).toBe('bug');
});
it('never shows what it does not say, and puts it in the console once', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
const e = new Error('RPC call to dawnline/updates_notes failed with ubus code 4: Resource not found');
const text = failureText(e);
expect(text).not.toContain('RPC');
expect(text).toMatch(/^Dawnline is not answering/);
failureText(e);
expect(warn).toHaveBeenCalledTimes(1);
warn.mockRestore();
});
});
+6 -7
View File
@@ -46,13 +46,12 @@ describe('router days', () => {
expect(daysLeft('2026-10-13', '2026-10-14')).toBe(-1);
expect(daysLeft('', '2026-10-14')).toBeNull();
});
it('warns by the person’s own window, never with 0', () => {
expect(endsSoon({ expire_warn: 3 }, 1)).toBe(true);
expect(endsSoon({ expire_warn: 3 }, 3)).toBe(true);
expect(endsSoon({ expire_warn: 3 }, 4)).toBe(false);
expect(endsSoon({ expire_warn: 0 }, 1)).toBe(false);
expect(endsSoon({ expire_warn: 3 }, -1)).toBe(false);
expect(endsSoon({ expire_warn: 3 }, null)).toBe(false);
it('warns in the last three days of a term, for everyone alike', () => {
expect(endsSoon(1)).toBe(true);
expect(endsSoon(3)).toBe(true);
expect(endsSoon(4)).toBe(false);
expect(endsSoon(-1)).toBe(false);
expect(endsSoon(null)).toBe(false);
});
it('says when access ends', () => {
expect(endsIn(1)).toBe('ends today');
+485
View File
@@ -0,0 +1,485 @@
import { describe, expect, it } from 'vitest';
import { batch, computed, effect, signal } from '../src/shared/live/signal';
import { appended, merge, rows } from '../src/shared/live/patch';
import { LiveStore, type LiveEvent } from '../src/shared/live/store';
import { Follower, type Answer, type Hello, type StreamMessage, type Transport } from '../src/shared/live/follow';
import { share } from '../src/shared/live/share';
import { LiveDoc } from '../src/shared/live/doc';
describe('signals', () => {
it('runs an effect again only for what it read', () => {
const a = signal(1);
const b = signal(10);
const seen: number[] = [];
const stop = effect(() => void seen.push(a()));
b.set(11);
a.set(2);
a.set(2);
stop();
a.set(3);
expect(seen).toEqual([1, 2]);
});
it('works a computed out again only when read after a change', () => {
const a = signal(2);
let runs = 0;
const double = computed(() => (runs++, a() * 2));
expect(runs).toBe(0);
expect(double()).toBe(4);
expect(double()).toBe(4);
a.set(3);
expect(runs).toBe(1);
expect(double()).toBe(6);
expect(runs).toBe(2);
});
it('follows a computed from an effect, and drops what a branch no longer reads', () => {
const on = signal(true);
const name = signal('Myata');
const label = computed(() => (on() ? name() : 'off'));
const seen: string[] = [];
effect(() => void seen.push(label()));
name.set('Guest');
on.set(false);
name.set('Nobody');
expect(seen).toEqual(['Myata', 'Guest', 'off']);
});
it('runs effects once for a batch', () => {
const a = signal(1);
const b = signal(1);
let runs = 0;
effect(() => void (a(), b(), runs++));
batch(() => {
a.set(2);
b.set(2);
});
expect(runs).toBe(2);
});
it('puts an effect off, once, however much changed; a run that did nothing keeps what it read', () => {
const a = signal(1);
const b = signal(1);
const due: (() => void)[] = [];
const seen: string[] = [];
let skip = false;
const stop = effect(
() => {
if (skip) return false;
seen.push(`${a()}/${b()}`);
},
(run) => void due.push(run),
);
a.set(2);
b.set(2);
expect([seen, due.length]).toEqual([['1/1'], 1]);
due.splice(0).forEach((run) => run());
expect(seen).toEqual(['1/1', '2/2']);
// skipped: it read nothing this time, and is still told when `a` changes
skip = true;
a.set(3);
due.splice(0).forEach((run) => run());
skip = false;
b.set(3);
due.splice(0).forEach((run) => run());
expect(seen).toEqual(['1/1', '2/2', '3/3']);
stop();
a.set(4);
expect(due.length).toBe(0);
});
it('lets a computed go', () => {
const a = signal(1);
let runs = 0;
const c = computed(() => (runs++, a()));
c();
c.stop();
a.set(2);
expect(runs).toBe(1);
expect(c()).toBe(2);
});
});
describe('an answer laid over the last one', () => {
it('keeps every part that did not change the object it was', () => {
const old = {
people: [
{ id: 'a', online: 0, devices: [{ id: 'd1' }] },
{ id: 'b', online: 1 },
],
tz: 'UTC',
};
const next = {
people: [
{ id: 'a', online: 1, devices: [{ id: 'd1' }] },
{ id: 'b', online: 1 },
],
tz: 'UTC',
};
const got = share(old, next);
expect(got).toEqual(next);
expect(got.people[1]).toBe(old.people[1]);
expect(got.people[0]).not.toBe(old.people[0]);
expect(got.people[0].devices).toBe(old.people[0].devices);
expect(share(old, structuredClone(old))).toBe(old);
});
it('knows a thing by its id wherever it stands, and a list that grew or shrank', () => {
const a = { id: 'a', n: 1 };
const b = { id: 'b', n: 2 };
const got = share(
[a, b],
[
{ id: 'b', n: 2 },
{ id: 'c', n: 3 },
{ id: 'a', n: 1 },
],
);
expect([got[0], got[2]]).toEqual([b, a]);
expect(got[0]).toBe(b);
expect(got[2]).toBe(a);
expect(share([1, 2], [1, 2, 3])).toEqual([1, 2, 3]);
expect(share({ a: 1, b: 2 }, { a: 1 })).toEqual({ a: 1 });
expect(share(null, { a: 1 })).toEqual({ a: 1 });
expect(share([1], { 0: 1 })).toEqual({ 0: 1 });
});
it("tells a field's readers only when that field changed", () => {
const doc = new LiveDoc<{ servers: { id: string; up: boolean }[]; now: number; tz?: string }>();
doc.feed({ servers: [{ id: 's1', up: true }], now: 1, tz: 'UTC' });
const seen: string[] = [];
const stop = effect(() => void seen.push(doc.view.servers.map((s) => `${s.id}:${s.up}`).join()));
const first = doc.view.servers[0];
doc.feed({ servers: [{ id: 's1', up: true }], now: 2, tz: 'UTC' });
expect(seen).toEqual(['s1:true']);
expect(doc.view.servers[0]).toBe(first);
doc.feed({ servers: [{ id: 's1', up: false }], now: 3 });
expect(seen).toEqual(['s1:true', 's1:false']);
expect('tz' in doc.view).toBe(false);
expect({ ...doc.view }).toEqual({ servers: [{ id: 's1', up: false }], now: 3 });
expect(doc.plain()).toEqual({ servers: [{ id: 's1', up: false }], now: 3 });
stop();
});
});
describe('merge patch', () => {
it('applies a patch and shares what it did not touch', () => {
const doc = { p1: { name: 'Myata', devices: { d1: { online: false }, d2: { online: true } } }, p2: { name: 'Guest' } };
const next = merge(doc, { p1: { devices: { d1: { online: true } } } }) as typeof doc;
expect(next.p1.devices.d1.online).toBe(true);
expect(doc.p1.devices.d1.online).toBe(false);
expect(next.p2).toBe(doc.p2);
expect(next.p1.devices.d2).toBe(doc.p1.devices.d2);
expect(next.p1).not.toBe(doc.p1);
});
it('removes with null, replaces lists whole, and returns the same object for no change', () => {
const doc = { a: 1, l: [1, 2, 3], t: { x: 1 } };
expect(merge(doc, { a: null, l: [9] })).toEqual({ l: [9], t: { x: 1 } });
expect(merge(doc, { t: { x: 1 }, gone: null })).toBe(doc);
expect(merge('text', { a: 1 })).toEqual({ a: 1 });
expect(merge(doc, [1])).toEqual([1]);
});
it('keeps the newest entries of a list, and reads a keyed list in order', () => {
expect(appended([1, 2], [3, 4], 3)).toEqual([2, 3, 4]);
expect(appended(undefined, [1], 0)).toEqual([1]);
expect(rows({ order: ['b', 'a', 'gone'], items: { a: 1, b: 2 } })).toEqual([2, 1]);
expect(rows(undefined)).toEqual([]);
});
});
describe('store', () => {
it('tells a place only when that place changed', () => {
const store = new LiveStore();
const online = store.at<boolean>('people', 'items', 'p1', 'online');
const name = store.at<string>('people', 'items', 'p1', 'name');
const seen: unknown[] = [];
let names = 0;
effect(() => void seen.push(online()));
effect(() => void (name(), names++));
store.apply({ seq: 1, topic: 'people', op: 'put', data: { items: { p1: { name: 'Myata', online: false } } } });
store.apply({ seq: 2, topic: 'people', op: 'patch', data: { items: { p1: { online: true } } } });
store.apply({ seq: 3, topic: 'people', op: 'patch', data: { items: { p2: { name: 'Guest' } } } });
expect(seen).toEqual([undefined, false, true]);
expect(names).toBe(2);
});
it('knows pending from ready from stale', () => {
const store = new LiveStore();
const st = store.state('people');
expect(st()).toBe('pending');
store.reset({ people: { items: {} } });
expect(st()).toBe('ready');
store.offline(true);
expect(st()).toBe('stale');
expect(store.state('meter')()).toBe('pending');
store.offline(false);
store.reset({});
expect(st()).toBe('pending');
expect(store.peek('people')).toBeUndefined();
});
it('appends to a list and drops a topic', () => {
const store = new LiveStore();
store.apply({ seq: 1, topic: 'meter', op: 'append', data: { items: [1, 2], keep: 3 } });
store.apply({ seq: 2, topic: 'meter', op: 'append', data: { items: [3, 4], keep: 3 } });
expect(store.peek('meter')).toEqual([2, 3, 4]);
store.apply({ seq: 3, topic: 'meter', op: 'drop' });
expect(store.state('meter')()).toBe('pending');
});
});
/** A backend to follow: a hub in a few lines, and a clock the test moves. */
function stand(mode: 'sse' | 'poll') {
let seq = 0;
let epoch = 'run1';
let docs: Record<string, unknown> = {};
const journal: LiveEvent[] = [];
const waiters: (() => void)[] = [];
const streams = new Set<(m: StreamMessage) => void>();
const calls = { hello: 0, sync: 0, wait: 0, watch: [] as string[][], streams: 0, refresh: 0 };
let onRefresh: (() => void) | null = null;
const timers: { at: number; f: () => void; id: number }[] = [];
let now = 0;
let ids = 0;
let failing = false;
let dropNext = false;
const answer = (at: { epoch?: string; seq?: number }): Answer => {
if (at.epoch === epoch && at.seq != null && at.seq <= seq) return { epoch, seq, events: journal.filter((e) => e.seq > at.seq!) };
return { epoch, seq, docs: structuredClone(docs) };
};
const transport: Transport = {
async hello(): Promise<Hello> {
calls.hello++;
if (failing) throw new Error('down');
return { version: '1', stream: mode, epoch, seq, lease: 30 };
},
async sync(at) {
calls.sync++;
if (failing) throw new Error('down');
return answer(at);
},
wait(at, stop) {
calls.wait++;
return new Promise<Answer>((done, fail) => {
const settle = (): void => (failing ? fail(new Error('down')) : done(answer(at)));
if (answer(at).docs || answer(at).events!.length) return settle();
waiters.push(settle);
stop.addEventListener('abort', () => fail(new Error('aborted')));
});
},
async watch(topics) {
calls.watch.push(topics);
},
async refresh() {
calls.refresh++;
onRefresh?.();
},
stream(on, stop) {
calls.streams++;
return new Promise<void>((_done, fail) => {
if (failing) return fail(new Error('down'));
streams.add(on);
stop.addEventListener('abort', () => {
streams.delete(on);
fail(new Error('aborted'));
});
});
},
};
return {
transport,
calls,
put(topic: string, doc: unknown): void {
docs[topic] = doc;
const e: LiveEvent = { seq: ++seq, topic, op: 'put', data: structuredClone(doc) };
journal.push(e);
waiters.splice(0).forEach((w) => w());
if (dropNext) dropNext = false;
else streams.forEach((s) => s({ kind: 'event', epoch, event: e }));
},
ping: (): void => streams.forEach((s) => s({ kind: 'ping', epoch, seq })),
/** What the backend finds on the router when it is asked to look now. */
whenRefreshed: (f: () => void): void => void (onRefresh = f),
/** The next event is not sent down the stream. */
loseNext: (): void => void (dropNext = true),
restart(): void {
epoch = 'run2';
seq = 0;
docs = {};
journal.length = 0;
},
fail(on: boolean): void {
failing = on;
if (on) waiters.splice(0).forEach((w) => w());
},
options: {
setTimeout: (f: () => void, ms: number): unknown => (timers.push({ at: now + ms, f, id: ++ids }), ids),
clearTimeout: (id: unknown): void => {
const i = timers.findIndex((t) => t.id === id);
if (i >= 0) timers.splice(i, 1);
},
},
/** Let the promises settle, then move the clock and run what is due. */
async pass(ms = 0): Promise<void> {
for (let i = 0; i < 20; i++) await Promise.resolve();
now += ms;
for (const t of timers.filter((x) => x.at <= now)) {
timers.splice(timers.indexOf(t), 1);
t.f();
}
for (let i = 0; i < 20; i++) await Promise.resolve();
},
};
}
describe.each(['poll', 'sse'] as const)('following by %s', (mode) => {
it('takes a snapshot, then every change', async () => {
const s = stand(mode);
s.put('people', { n: 1 });
const store = new LiveStore();
const f = new Follower(store, s.transport, s.options);
f.start();
await s.pass();
expect(f.link()).toBe('live');
expect(store.peek('people')).toEqual({ n: 1 });
s.put('people', { n: 2 });
s.put('servers', { up: true });
await s.pass();
expect(store.peek('people')).toEqual({ n: 2 });
expect(store.state('servers')()).toBe('ready');
f.pause();
});
it('keeps what it shows when the backend goes away, and catches up when it is back', async () => {
const s = stand(mode);
s.put('people', { n: 1 });
const store = new LiveStore();
const f = new Follower(store, s.transport, s.options);
f.start();
await s.pass();
s.fail(true);
if (mode === 'sse') {
f.pause();
f.start();
}
await s.pass();
expect(f.link()).toBe('offline');
expect(store.state('people')()).toBe('stale');
expect(store.peek('people')).toEqual({ n: 1 });
s.fail(false);
s.put('people', { n: 2 });
await s.pass(1000);
await s.pass(2000);
expect(f.link()).toBe('live');
expect(store.peek('people')).toEqual({ n: 2 });
expect(store.state('people')()).toBe('ready');
f.pause();
});
it('starts over after the backend restarted', async () => {
const s = stand(mode);
s.put('people', { n: 1 });
s.put('old', { x: 1 });
const store = new LiveStore();
const f = new Follower(store, s.transport, s.options);
f.start();
await s.pass();
f.pause();
s.restart();
s.put('people', { n: 5 });
f.start();
await s.pass();
expect(store.peek('people')).toEqual({ n: 5 });
expect(store.state('old')()).toBe('pending');
f.pause();
});
it('follows nothing while paused, and renews what is watched while it runs', async () => {
const s = stand(mode);
const store = new LiveStore();
const f = new Follower(store, s.transport, s.options);
const release = f.watch('meter');
f.start();
await s.pass();
expect(s.calls.watch).toEqual([['meter']]);
await s.pass(10_000);
expect(s.calls.watch.length).toBe(2);
release();
await s.pass(10_000);
expect(s.calls.watch.length).toBe(2);
f.pause();
s.put('people', { n: 1 });
await s.pass();
expect(store.peek('people')).toBeUndefined();
f.start();
await s.pass();
expect(store.peek('people')).toEqual({ n: 1 });
f.pause();
});
it('reads what was just written: the store holds it when the question returns', async () => {
const b = stand(mode);
const store = new LiveStore();
const f = new Follower(store, b.transport, b.options);
b.put('people', { n: 1 });
f.start();
await b.pass();
// the page wrote; the backend sees it on disk only when it looks
b.loseNext();
b.whenRefreshed(() => b.put('people', { n: 2 }));
await f.fresh();
expect([b.calls.refresh, store.peek('people')]).toEqual([1, { n: 2 }]);
// the answers that crossed it add nothing twice, and the next change is followed as before
await b.pass();
b.put('people', { n: 3 });
await b.pass();
expect(store.peek('people')).toEqual({ n: 3 });
f.pause();
});
});
describe('the event stream', () => {
it('asks for what it missed when a number is skipped, or a ping is ahead', async () => {
const s = stand('sse');
const store = new LiveStore();
const f = new Follower(store, s.transport, s.options);
f.start();
await s.pass();
s.loseNext();
s.put('a', { n: 1 });
s.put('b', { n: 1 });
await s.pass();
expect(store.peek('a')).toEqual({ n: 1 });
expect(store.peek('b')).toEqual({ n: 1 });
s.loseNext();
s.put('a', { n: 2 });
await s.pass();
expect(store.peek('a')).toEqual({ n: 1 });
s.ping();
await s.pass();
expect(store.peek('a')).toEqual({ n: 2 });
f.pause();
});
it('gives a silent stream up, and the stream itself after two failures', async () => {
const s = stand('sse');
const store = new LiveStore();
const f = new Follower(store, s.transport, s.options);
f.start();
await s.pass();
expect(s.calls.streams).toBe(1);
await s.pass(40_000);
expect(f.link()).toBe('offline');
await s.pass(1000);
expect(s.calls.streams).toBe(2);
await s.pass(40_000);
await s.pass(2000);
expect(s.calls.streams).toBe(2);
expect(s.calls.wait).toBeGreaterThan(0);
expect(f.link()).toBe('live');
f.pause();
});
});
+220
View File
@@ -0,0 +1,220 @@
import { describe, expect, it } from 'vitest';
import type { LogEvent } from '../src/shared/types';
import type { ServiceLogEntry } from '../src/admin/api';
import { sessions, type FeedItem } from '../src/admin/events/sessions';
import {
WHOLE,
choices,
inScope,
logQueryParams,
narrowed,
parseLogQuery,
withFilters,
type LogQuery,
type Who,
} from '../src/admin/events/scope';
// 2026-11-09 09:00 at the router (+3 h): 06:00 UTC.
const NOW = Date.UTC(2026, 10, 9, 6, 0) / 1000;
const TZ = 180;
const clock = { now: NOW, tz: TZ };
const HOUR = 3600;
const who = {
people: [
{
id: 'p_lena',
name: 'Lena',
server: 's_home',
devices: [
{ id: 'd_mac', name: 'MacBook' },
{ id: 'd_ipad', name: 'iPad' },
],
},
{ id: 'p_dima', name: 'Dima', server: 's_dacha', devices: [{ id: 'd_xi', name: 'Xiaomi 14' }] },
{ id: 'p_new', name: 'Katya', server: 's_home', devices: [{ id: 'd_none', name: 'Phone' }] },
],
servers: [
{ id: 's_home', name: 'Home' },
{ id: 's_dacha', name: 'Dacha' },
],
} as unknown as Who;
const ev = (ago: number, type: string, person?: string, device?: string, extra: Partial<LogEvent> = {}): LogEvent => ({
ts: NOW - ago,
type,
person,
device,
...extra,
});
const sys = (ago: number, extra: Partial<ServiceLogEntry> = {}): ServiceLogEntry => ({
ts: NOW - ago,
src: 'awg',
level: 'info',
msg: 'up',
...extra,
});
/** The feed: today 4 rows, yesterday 3, five days ago 1, ten days ago 1. */
const feed = (): FeedItem[] =>
sessions(
[
ev(1 * HOUR, 'paused', 'p_lena'),
ev(2 * HOUR, 'device_failing', 'p_dima', 'd_xi'),
ev(3 * HOUR, 'device_changed', 'p_lena', 'd_mac'),
// 23:00 the day before at the router
ev(10 * HOUR, 'device_changed', 'p_lena', 'd_ipad'),
ev(20 * HOUR, 'device_changed', 'p_dima', 'd_xi'),
ev(5 * 24 * HOUR, 'device_changed', 'p_lena', 'd_mac'),
ev(10 * 24 * HOUR, 'device_removed', 'p_gone', 'd_gone', { server: 's_dacha', pname: 'Gone' }),
],
[sys(4 * HOUR, { who: 'Home' }), sys(12 * HOUR, { sid: 's_dacha', who: 'Renamed since' }), sys(13 * HOUR, { who: 'Personal portal' })],
() => false,
);
const ask = (patch: Partial<LogQuery>): LogQuery => ({ ...WHOLE, ...patch });
const kept = (q: Partial<LogQuery>) => feed().filter(inScope(ask(q), who, clock));
describe('the log’s address', () => {
it('reads what it knows and leaves out the rest', () => {
expect(parseLogQuery('')).toEqual(WHOLE);
expect(parseLogQuery('kind=problems&day=yesterday&person=p_dima&device=d_xi&server=s_home&q=176.59')).toEqual({
kind: 'problems',
day: 'yesterday',
person: 'p_dima',
device: 'd_xi',
server: 's_home',
q: '176.59',
});
expect(parseLogQuery('kind=everything&day=tomorrow&sheet=x')).toEqual(WHOLE);
expect(parseLogQuery('q=%20two%20words%20').q).toBe('two words');
});
it('takes the 7 days by both of their names and writes one', () => {
expect(parseLogQuery('day=7d').day).toBe('7d');
expect(parseLogQuery('day=week').day).toBe('7d');
expect(logQueryParams(parseLogQuery('day=week')).day).toBe('7d');
});
it('writes only what narrows the log, and reads it back the same', () => {
expect(logQueryParams(WHOLE)).toEqual({});
const q = ask({ kind: 'system', day: 'today', person: 'p_lena', q: 'no route' });
const params = logQueryParams(q);
expect(params).toEqual({ kind: 'system', day: 'today', person: 'p_lena', q: 'no route' });
const query = new URLSearchParams(Object.entries(params).filter((e): e is [string, string] => !!e[1])).toString();
expect(parseLogQuery(query)).toEqual(q);
});
it('knows when something narrows it', () => {
expect(narrowed(WHOLE)).toBe(false);
for (const patch of [
{ kind: 'people' },
{ day: '7d' },
{ person: 'p' },
{ device: 'd' },
{ server: 's' },
{ q: 'x' },
] as Partial<LogQuery>[])
expect(narrowed(ask(patch))).toBe(true);
});
});
describe('changing the log’s filters', () => {
it('keeps a person with a device of theirs', () => {
expect(withFilters(ask({ person: 'p_lena' }), { device: 'd_mac' }, who.people)).toMatchObject({ person: 'p_lena', device: 'd_mac' });
expect(withFilters(ask({ device: 'd_mac' }), { person: 'p_lena' }, who.people)).toMatchObject({ person: 'p_lena', device: 'd_mac' });
});
it('drops the person when a device of someone else is picked, and the device when another person is', () => {
expect(withFilters(ask({ person: 'p_lena' }), { device: 'd_xi' }, who.people)).toMatchObject({ person: '', device: 'd_xi' });
expect(withFilters(ask({ device: 'd_mac' }), { person: 'p_dima' }, who.people)).toMatchObject({ person: 'p_dima', device: '' });
});
it('leaves the rest alone', () => {
const q = ask({ person: 'p_lena', device: 'd_mac', day: 'today', q: 'x' });
expect(withFilters(q, { day: '' }, who.people)).toEqual({ ...q, day: '' });
expect(withFilters(q, { person: '' }, who.people)).toEqual({ ...q, person: '' });
expect(withFilters(q, WHOLE, who.people)).toEqual(WHOLE);
});
});
describe('the log’s scope', () => {
it('keeps everything when nothing is asked, whatever the kind and the search', () => {
expect(kept({})).toHaveLength(10);
expect(kept({ kind: 'problems', q: 'nothing like it' })).toHaveLength(10);
});
it('keeps one person’s rows, or one device’s, without the service lines', () => {
expect(kept({ person: 'p_lena' }).map((x) => x.ev?.device)).toEqual([undefined, 'd_mac', 'd_ipad', 'd_mac']);
expect(kept({ device: 'd_xi' })).toHaveLength(2);
expect(kept({ person: 'p_lena', device: 'd_xi' })).toHaveLength(0);
expect(kept({ person: 'p_dima' }).some((x) => x.sys)).toBe(false);
});
it('reads a row’s server from its person, from the event itself for someone removed, from a service line’s id or name', () => {
const dacha = kept({ server: 's_dacha' });
expect(dacha.map((x) => x.ev?.person ?? x.sys?.who)).toEqual(['p_dima', 'Renamed since', 'p_dima', 'p_gone']);
const home = kept({ server: 's_home' });
expect(home.filter((x) => x.sys).map((x) => x.sys!.who)).toEqual(['Home']);
expect(home.filter((x) => x.ev).every((x) => x.ev!.person === 'p_lena')).toBe(true);
// the portal's line is no server's
expect([...dacha, ...home]).toHaveLength(9);
});
it('tells today from yesterday by the router’s day, and the 7 days by the clock', () => {
expect(kept({ day: 'today' })).toHaveLength(4);
// 10 h ago is 23:00 yesterday at the router (and still today in UTC)
expect(kept({ day: 'yesterday' }).map((x) => NOW - x.ts)).toEqual([10 * HOUR, 12 * HOUR, 13 * HOUR, 20 * HOUR]);
expect(kept({ day: '7d' })).toHaveLength(9);
expect(kept({ day: 'yesterday', person: 'p_lena' })).toHaveLength(1);
});
});
describe('what the log’s chips offer', () => {
it('lists the people with rows, the most first', () => {
expect(choices(feed(), WHOLE, who, clock).people).toEqual([
{ id: 'p_lena', n: 4 },
{ id: 'p_dima', n: 2 },
]);
});
it('counts under the other filters, not under its own', () => {
const c = choices(feed(), ask({ day: 'yesterday', person: 'p_dima', device: 'd_xi' }), who, clock);
// another person takes the device off: people are counted without it
expect(c.people).toEqual([
{ id: 'p_lena', n: 1 },
{ id: 'p_dima', n: 1 },
]);
expect(c.devices).toEqual([{ id: 'd_xi', n: 1 }]);
expect(c.servers).toEqual([
{ id: 's_home', n: 0 },
{ id: 's_dacha', n: 1 },
]);
});
it('offers the picked person’s devices only, and everyone’s with nobody picked', () => {
expect(choices(feed(), ask({ person: 'p_lena' }), who, clock).devices).toEqual([
{ id: 'd_mac', n: 2 },
{ id: 'd_ipad', n: 1 },
]);
expect(choices(feed(), WHOLE, who, clock).devices.map((d) => d.id)).toEqual(['d_mac', 'd_xi', 'd_ipad']);
});
it('keeps the picked one in its list with no rows, and when the router no longer has it', () => {
expect(choices(feed(), ask({ day: 'today', person: 'p_new' }), who, clock).people.map((p) => p.id)).toEqual([
'p_lena',
'p_dima',
'p_new',
]);
const gone = choices(feed(), ask({ person: 'p_gone', device: 'd_gone' }), who, clock);
expect(gone.people).toContainEqual({ id: 'p_gone', n: 1 });
expect(gone.devices).toEqual([{ id: 'd_gone', n: 1 }]);
});
it('lists every server in the router’s order', () => {
expect(choices(feed(), WHOLE, who, clock).servers).toEqual([
{ id: 's_home', n: 5 },
{ id: 's_dacha', n: 4 },
]);
});
});
+20 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { arc, cityPlaces, devicePlaces, separate, type MapData } from '../src/admin/map';
import { arc, cityPlaces, devicePlaces, markInitials, separate, type MapData } from '../src/admin/map';
describe('arc (mapcn buildArcCoordinates)', () => {
it('runs from one point to the other', () => {
@@ -170,3 +170,22 @@ describe('cityPlaces', () => {
expect(cityPlaces([{ key: 'a', ...msk }], msk).get('a')).toEqual(a);
});
});
describe('markInitials', () => {
it('leaves a part in brackets out', () => {
expect(markInitials('Кирилл (гость)')).toBe(markInitials('Кирилл'));
expect(markInitials('Кирилл (гость)')).not.toContain('(');
});
it('skips words with no letters', () => {
expect(markInitials('Офис — 2')).toBe(markInitials('Офис'));
});
it('takes a bracketed name when it is all there is', () => {
expect(markInitials('(гость)')).toBe(markInitials('гость'));
});
it('gives the usual two initials for a full name', () => {
expect(markInitials('Лена Константинопольская')).toHaveLength(2);
});
});
+28 -3
View File
@@ -49,10 +49,34 @@ describe('live meter', () => {
expect(m.speed('nope', 0).pts).toEqual([]);
});
it("adds every server up for the router, and one person's devices for them", () => {
const m = new LiveMeter();
m.take({ meter: meter(points(1001, 1004)) }, 0);
expect(m.speed(null, 0).pts).toEqual([
[1001, 1001, 2002],
[1002, 1003, 2005],
[1003, 1003, 2006],
[1004, 1005, 2009],
]);
m.take({ meter: meter([{ ts: 1005, servers: { a: [9, 9] }, dev: { d1: [3, 4], d2: [1, 1], d3: [7, 7] } }], 1006) }, 1000);
// the mean of the newest three seconds: theirs moved nothing in the two before
expect(m.speed(null, 1000, ['d1', 'd2'])).toMatchObject({ rx: 1, tx: 2 });
});
it('says the mean of the seconds its words stand for: no zero between two bursts', () => {
const m = new LiveMeter();
const at = (ts: number, tx: number): MeterPoint => ({ ts, servers: { a: [0, tx] }, dev: tx ? { d1: [0, tx] } : {} });
m.take({ meter: meter([at(1001, 9000), at(1002, 300), at(1003, 0)], 1004) }, 0);
expect(m.speed('a', 0, ['d1']).tx).toBe(3100);
// nothing in all three: a zero that is one
m.take({ meter: meter([at(1004, 0), at(1005, 0)], 1006) }, 1000);
expect(m.speed('a', 1000, ['d1']).tx).toBe(0);
});
it('reads the speed now from a fresh point only', () => {
const m = new LiveMeter();
m.take({ meter: meter(points(1001, 1010), 1011) }, 0);
expect(m.speed('a', 0)).toMatchObject({ rx: 1010, tx: 2020, error: null });
expect(m.speed('a', 0)).toMatchObject({ rx: 1009, tx: 2018, error: null });
// The agent stopped: its last point stays behind the router's clock.
m.take({ meter: meter([], 1030) }, 1000);
expect(m.speed('a', 1000)).toMatchObject({ rx: 0, tx: 0 });
@@ -77,7 +101,7 @@ describe('live meter', () => {
expect(m.since(1000)).toBe(0);
expect(m.speed('a', 1000)).toMatchObject({ pts: [], rx: 0, tx: 0 });
m.take({ meter: meter(points(405, 410), 411) }, 2000);
expect(m.speed('a', 2000)).toMatchObject({ rx: 410, tx: 820 });
expect(m.speed('a', 2000)).toMatchObject({ rx: 409, tx: 818 });
});
it('never takes a point dated after the router clock for the speed now', () => {
@@ -132,7 +156,8 @@ describe('live meter, a person', () => {
[1002, 0, 0],
[1004, 7, 9],
]);
expect(s).toMatchObject({ rx: 7, tx: 9 });
// 1002 and 1004: the seconds read among the newest three
expect(s).toMatchObject({ rx: 4, tx: 5 });
expect(m.speed('a', 0, []).pts.map((p) => p[1])).toEqual([0, 0, 0]);
});
});
+20 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { kept } from '../src/portal/ui/morph';
import { kept, paired } from '../src/portal/ui/morph';
/** The letters a morph keeps, as the new text shows them (the rest come in). */
const keeps = (from: string, to: string) =>
@@ -41,3 +41,22 @@ describe('kept letters', () => {
});
});
});
describe('pieces paired by a refill', () => {
it('pairs a keyed piece with its own key wherever it went, the rest in order', () => {
// two rows swapped places, a head before them and a foot after
const a = ['DIV.head.', 'DIV.row.a', 'DIV.row.b', 'DIV.foot.'];
const b = ['DIV.head.', 'DIV.row.b', 'DIV.row.a', 'DIV.foot.'];
expect(paired(a, b).sort((x, y) => x[1] - y[1])).toEqual([
[0, 0],
[2, 1],
[1, 2],
[3, 3],
]);
});
it('leaves a key that is not once on each side to the order', () => {
expect(paired(['DIV.row.a', 'DIV.row.a'], ['DIV.row.a'])).toEqual(kept(['DIV.row.a', 'DIV.row.a'], ['DIV.row.a']));
expect(paired(['#text', 'B..'], ['B..', '#text'])).toEqual(kept(['#text', 'B..'], ['B..', '#text']));
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest';
import { plainOrg, plainWhere } from '../src/shared/org';
describe('plainOrg', () => {
it('leaves the legal form out, before or after the name', () => {
expect(plainOrg('PJSC Rostelecom')).toBe('Rostelecom');
expect(plainOrg('ПАО Ростелеком')).toBe('Ростелеком');
expect(plainOrg('Example Networks LLC')).toBe('Example Networks');
expect(plainOrg('Hetzner Online GmbH')).toBe('Hetzner Online');
});
it('drops the quotes around what is left', () => {
expect(plainOrg('ООО «Ромашка»')).toBe('Ромашка');
});
it('keeps a name that is nothing but a legal form, and plain names', () => {
expect(plainOrg('LLC')).toBe('LLC');
expect(plainOrg('MegaFon')).toBe('MegaFon');
});
});
describe('plainWhere', () => {
it('plains the operator after the city only', () => {
expect(plainWhere('Krasnodar · PJSC Rostelecom')).toBe('Krasnodar · Rostelecom');
expect(plainWhere('Moscow')).toBe('Moscow');
});
});
+340
View File
@@ -0,0 +1,340 @@
import { beforeAll, describe, expect, it } from 'vitest';
import fs from 'node:fs';
import {
checkGroups,
checkList,
fixPlace,
hourBars,
ownFix,
serverNumbers,
stateLine,
stillWaiting,
systemNews,
topMonth,
topProblem,
waitRows,
waiting,
} from '../src/admin/overview/model';
import { scoped } from '../src/admin/people/roster';
import { serverState } from '../src/admin/servers/state';
import type { Device, HealthCheck, Person } from '../src/shared/types';
import type { ServiceLog } from '../src/admin/api';
// The router at 2026-11-08 12:40 UTC+3.
const NOW = Date.UTC(2026, 10, 8, 9, 40) / 1000;
const T = { today: '2026-11-08', now: NOW };
beforeAll(() => {
Object.assign(globalThis, { L: { url: (p: string) => `/cgi-bin/luci/${p}` } });
});
const check = (id: string, status: HealthCheck['status'], fix: string | null = null): HealthCheck => ({
id,
title: id,
status,
detail: '',
fix,
problem: status === 'ok' ? null : `${id} failed`,
});
const person = (o: Partial<Person> = {}): Person =>
({
id: 'p1',
name: 'Lena',
server: 's1',
state: 'active',
paused: false,
expires: '',
quota_limit: 0,
quota_used: 0,
month: [0, 0],
total: [0, 0],
online: 0,
last_seen: NOW - 3600,
devices: [],
has_link: true,
...o,
}) as Person;
describe('the router in one phrase and its checks as a list', () => {
it('counts the checks in the phrase, the worst first', () => {
expect(stateLine(null)).toEqual({ text: 'Checking…', tone: '' });
expect(stateLine(null, true)).toEqual({ text: 'The checks did not run', tone: '' });
expect(stateLine([check('clock', 'ok'), check('cert', 'skip')])).toEqual({ text: 'Everything works', tone: 'ok' });
expect(stateLine([check('cert', 'warn')])).toEqual({ text: '1 warning', tone: 'warn' });
expect(stateLine([check('cert', 'warn'), check('flash', 'warn'), check('dns', 'ok')])).toEqual({
text: '2 warnings',
tone: 'warn',
});
// problems are said alone: the warnings are in the list under them
expect(stateLine([check('cert', 'warn'), check('up_s1', 'error'), check('flash', 'error')])).toEqual({
text: '2 problems',
tone: 'bad',
});
});
it('puts an error before a warning in the notice', () => {
expect(topProblem([check('cert', 'warn'), check('up_s1', 'error')])?.id).toBe('up_s1');
expect(topProblem([check('cert', 'warn'), check('flash', 'warn')])?.id).toBe('cert');
expect(topProblem([check('cert', 'ok'), check('x', 'skip')])).toBeNull();
expect(topProblem(null)).toBeNull();
});
it('splits the checks: the notice, the other failing ones with errors first, and all that passed', () => {
const l = checkList([
check('clock', 'ok'),
check('cert', 'warn'),
check('srv_s2', 'skip'),
check('flash', 'warn'),
check('up_s1', 'error'),
check('agent', 'error'),
check('nft', 'ok'),
]);
expect(l.top?.id).toBe('up_s1');
expect(l.failing.map((c) => c.id)).toEqual(['agent', 'cert', 'flash']);
// nothing is folded away: the skipped one stays among them
expect(l.passed.map((c) => c.id)).toEqual(['clock', 'srv_s2', 'nft']);
expect([l.ok, l.of]).toEqual([2, 6]);
// every check stands in exactly one place
expect(1 + l.failing.length + l.passed.length).toBe(7);
expect(checkList([check('clock', 'ok')])).toEqual({ top: null, failing: [], passed: [check('clock', 'ok')], ok: 1, of: 1 });
});
it('groups what passed by what it is about, a server’s checks under its own name', () => {
const servers = [
{ id: 's1', name: 'Home' },
{ id: 'x_s1', name: 'Cabin' },
];
const t = (c: HealthCheck, title: string): HealthCheck => ({ ...c, title });
const gs = checkGroups(
[
t(check('awg', 'ok'), 'AmneziaWG installed'),
t(check('clock', 'ok'), 'Clock is set'),
t(check('up_s1', 'ok'), 'Tunnel running (Home)'),
t(check('fw_s1', 'error'), 'Firewall rules (Home)'),
t(check('ep_s1', 'warn'), 'Public address (Home)'),
// the other server's id ends with the first one's: the check is its own
t(check('srv_x_s1', 'skip'), 'Server (Cabin)'),
t(check('portal', 'ok'), 'Personal portal'),
t(check('cert', 'skip'), 'Portal certificate'),
],
servers,
);
expect(gs.map((g) => [g.kind, g.name, g.ok, g.of, g.tone])).toEqual([
['router', undefined, 2, 2, 'ok'],
['server', 'Home', 1, 3, 'bad'],
['server', 'Cabin', 0, 0, 'off'],
['portal', undefined, 1, 1, 'ok'],
]);
// what did not pass stands in the notice and the rows above: a group names only what passed or was skipped
expect(gs[1].passed.map((x) => x.title)).toEqual(['Tunnel running']);
expect(gs[2].passed.map((x) => [x.title, x.check.status])).toEqual([['Server', 'skip']]);
expect(gs[3].passed.map((x) => x.title)).toEqual(['Personal portal', 'Portal certificate']);
// a group with no check is left out
expect(checkGroups([check('clock', 'ok')], servers).map((g) => g.kind)).toEqual(['router']);
});
it('leads each problem to where it is set (a section of Settings, a part of its server’s page), or nowhere', () => {
const base = '/cgi-bin/luci/admin/services/dawnline';
expect(fixPlace({ id: 'cert', fix: null }, ['s1'])).toBe(`${base}/settings?p=portal`);
expect(fixPlace({ id: 'portal_dns', fix: null }, ['s1'])).toBe(`${base}/settings?p=portal`);
expect(fixPlace({ id: 'app', fix: 'updates' }, ['s1'])).toBe(`${base}/settings?p=updates`);
expect(fixPlace({ id: 'port_s1', fix: null }, ['s1'])).toBe(`${base}/server?p=general&s=entry`);
expect(fixPlace({ id: 'up_s2', fix: null }, ['s1', 's2'])).toBe(`${base}/server?server=s2&p=network&s=tunnel`);
expect(fixPlace({ id: 'srv_s2', fix: null }, ['s1', 's2'])).toBe(`${base}/server?server=s2`);
expect(fixPlace({ id: 'awg', fix: 'install:awg' }, ['s1', 's2'])).toBe(`${base}/server?p=core&s=disguise`);
// nothing set anywhere is about the clock, the agent, the flash, the data, or a router with no server
for (const id of ['clock', 'agent', 'flash', 'data', 'server']) expect(fixPlace({ id, fix: null }, ['s1'])).toBeNull();
});
it('keeps a fix in the list only for a check with no Settings section', () => {
expect(ownFix({ id: 'agent', fix: 'restart' }, ['s1'])).toBe('restart');
// advice only: no button
expect(ownFix({ id: 'clock', fix: null }, ['s1'])).toBeNull();
// fixed where the problem is (its stage, the portal, Updates): a signal here, no second button
expect(ownFix({ id: 'nft', fix: 'apply' }, ['s1'])).toBeNull();
expect(ownFix({ id: 'up_s1', fix: 'netrestart' }, ['s1'])).toBeNull();
expect(ownFix({ id: 'portal', fix: 'install:https' }, ['s1'])).toBeNull();
expect(ownFix({ id: 'app', fix: 'updates' }, ['s1'])).toBeNull();
});
});
describe('people and traffic', () => {
it('lists who waits for a decision (not who is fine or paused)', () => {
const ps = [
person({ id: 'a', name: 'Ann', state: 'active', online: 1 }),
person({ id: 'b', name: 'Bob', state: 'expired', expires: '2026-11-01', last_seen: NOW - 60 }),
person({ id: 'c', name: 'Cat', state: 'no_server' }),
person({ id: 'd', name: 'Dan', state: 'paused', paused: true }),
];
const w = waiting(ps, T).map((p) => p.id);
expect([...w].sort()).toEqual(['b', 'c']);
// by the weight of what stops them (the cards' matrix): no server before an end date
expect(w).toEqual(['c', 'b']);
});
it('shows the first who wait and counts as People does', () => {
const ps = [
person({ id: 'ok', state: 'active', online: 1 }),
person({ id: 'paused', state: 'paused', paused: true }),
...Array.from({ length: 7 }, (_x, i) =>
person({ id: `w${i}`, name: `W${i}`, state: i < 2 ? 'no_server' : 'expired', expires: '2026-11-01', last_seen: NOW - i }),
),
];
const wide = waitRows(ps, T, false);
expect(wide.rows.map((p) => p.id)).toEqual(['w0', 'w1', 'w2', 'w3', 'w4']);
expect([wide.total, wide.more]).toEqual([7, 2]);
const phone = waitRows(ps, T, true);
expect(phone.rows).toHaveLength(3);
expect([phone.total, phone.more]).toEqual([7, 4]);
// «N more» leads to People filtered to them: the same people there
expect(
scoped(ps, { group: 'need' }, T)
.map((p) => p.id)
.sort(),
).toEqual(
waiting(ps, T)
.map((p) => p.id)
.sort(),
);
// few enough: nothing is left to People
expect(waitRows(ps.slice(0, 4), T, false)).toMatchObject({ total: 2, more: 0 });
expect(waitRows([person()], T, false)).toEqual({ rows: [], total: 0, more: 0 });
});
it("says a server card's numbers", () => {
const srv = {
id: 's1',
enabled: true,
up: true,
rate: [
[NOW - 120, 5, 50],
[NOW - 60, 10, 100],
] as [number, number, number][],
series: [
{ day: '2026-11-07', rx: 1, tx: 1 },
{ day: '2026-11-08', rx: 30, tx: 12 },
],
};
const st = { now: NOW, people: [person(), person({ id: 'p2' }), person({ id: 'p3', server: 's2' })] };
expect(serverNumbers(srv, st, T.today)).toEqual({ people: 2, down: 100, today: 42 });
// the last minute gone stale, a server that is off or down: no speed said
expect(serverNumbers(srv, { ...st, now: NOW + 600 }, T.today).down).toBeNull();
expect(serverNumbers({ ...srv, enabled: false }, st, T.today).down).toBeNull();
expect(serverNumbers({ ...srv, up: false }, st, T.today).down).toBeNull();
expect(serverNumbers({ ...srv, rate: [] }, st, T.today).down).toBeNull();
// the newest day counted is not today: nothing moved today; no days at all: nothing said
expect(serverNumbers(srv, st, '2026-11-09').today).toBe(0);
expect(serverNumbers({ ...srv, series: [] }, st, T.today).today).toBeNull();
});
it('names the first devices of a rollout that still wait', () => {
const item = (pid: string, did: string, stale: boolean) => ({
p: person({ id: pid }),
d: { id: did, name: did, config_stale: stale } as Device,
});
const items = [
item('a', 'a1', true),
item('a', 'a2', false),
item('b', 'b1', true),
item('c', 'c1', true),
item('c', 'c2', true),
item('d', 'd1', true),
item('d', 'd2', true),
];
const w = stillWaiting(items);
expect(w.named.map((x) => x.d.id)).toEqual(['a1', 'b1', 'c1', 'c2']);
expect([w.more, w.people]).toEqual([2, 4]);
expect(stillWaiting(items.slice(0, 3))).toMatchObject({ more: 0, people: 2 });
expect(stillWaiting([item('a', 'a2', false)])).toEqual({ named: [], more: 0, people: 0 });
});
it('names who moved most this month, only those who moved', () => {
const ps = [
person({ id: 'a', month: [5, 5] }),
person({ id: 'b', month: [50, 1] }),
person({ id: 'c' }),
person({ id: 'd', month: [1, 0] }),
];
expect(topMonth(ps).map((x) => [x.p.id, x.bytes])).toEqual([
['b', 51],
['a', 10],
['d', 1],
]);
expect(topMonth([person()])).toEqual([]);
});
it('draws today as 24 bars, the hours to come empty', () => {
const bars = hourBars([
[10, 10],
[0, 0],
[30, 10],
]);
expect(bars).toHaveLength(24);
expect(bars.slice(0, 3).map((b) => b.share)).toEqual([0.5, 0, 1]);
expect(bars[3]).toEqual({ share: null, bytes: 0 });
expect(hourBars([]).every((b) => b.share === null)).toBe(true);
});
});
describe("the watchdog's news and a server's state", () => {
const sl = (o: Partial<ServiceLog['watchdog']>): ServiceLog => ({
watchdog: { enabled: true, last: NOW, beat: NOW, now: NOW, targets: [], repairs: [], ...o },
log: [],
});
it("says the watchdog's news, and nothing without it", () => {
expect(systemNews(null)).toBeNull();
expect(systemNews(sl({}))).toBeNull();
expect(systemNews(sl({ beat: NOW - 600 }))).toEqual({ kind: 'quiet', minutes: 10 });
expect(
systemNews(
sl({
repairs: [
{ ts: NOW - 7200, id: 'up_s1', name: 'Tunnel' },
{ ts: NOW - 600, id: 'portal', name: 'Portal' },
{ ts: NOW - 90000, id: 'nft', name: 'Old' },
],
}),
),
).toEqual({ kind: 'repair', ts: NOW - 600, name: 'Portal' });
expect(systemNews(sl({ repairs: [{ ts: NOW - 90000, id: 'nft', name: 'Old' }] }))).toBeNull();
});
it('says whether a server runs', () => {
expect(serverState({ enabled: false, up: false, uptime: 0 })).toEqual({ text: 'Turned off', tone: 'warn' });
expect(serverState({ enabled: true, up: true, uptime: 0 })).toEqual({ text: 'Running', tone: 'ok' });
expect(serverState({ enabled: true, up: true, uptime: 7200 }).tone).toBe('ok');
expect(serverState({ enabled: true, up: false, uptime: 0, blocked: 'awg0 is taken' })).toEqual({ text: 'Can’t start', tone: 'bad' });
expect(serverState({ enabled: true, up: false, uptime: 0 })).toEqual({ text: 'Not running', tone: 'bad' });
});
});
describe("LuCI's side: the menu and the views", () => {
const PKG = '../package/luci-app-dawnline';
const menu = JSON.parse(fs.readFileSync(`${PKG}/root/usr/share/luci/menu.d/luci-app-dawnline.json`, 'utf8')) as Record<
string,
{ title?: string; action: { type: string; path: string } }
>;
const main = fs.readFileSync('src/admin/main.ts', 'utf8');
const exported = (main.match(/export \{([^}]*)\}/)?.[1] ?? '').split(',').map((s) => s.trim());
it('opens Dawnline on Overview, one titled item with untitled sections', () => {
expect(menu['admin/services/dawnline'].action).toEqual({ type: 'alias', path: 'admin/services/dawnline/overview' });
expect(
Object.entries(menu)
.filter(([, n]) => n.title)
.map(([k]) => k),
).toEqual(['admin/services/dawnline']);
});
it('has a view for every node, each on the one module and a factory of it', () => {
for (const [key, node] of Object.entries(menu)) {
if (node.action.type !== 'view') continue;
const name = key.split('/').pop()!;
expect(node.action.path).toBe(`dawnline/${name}`);
const view = fs.readFileSync(`${PKG}/htdocs/luci-static/resources/view/dawnline/${name}.js`, 'utf8');
expect(view).toContain("'require dawnline.app as app'");
expect(view).toContain(`app.${name}()`);
expect(exported).toContain(name);
}
});
});
+13 -9
View File
@@ -19,20 +19,24 @@ describe('pace', () => {
});
it('says when a limit fills at this pace', () => {
expect(forecast(46 * GB, 50 * GB, 2 * GB, false, '2026-11-02')).toEqual({ kind: 'fills', days: 2, on: '2026-11-04' });
// A monthly limit filling before the 1st is the same.
expect(forecast(40 * GB, 50 * GB, 1 * GB, true, '2026-11-15')).toEqual({ kind: 'fills', days: 10, on: '2026-11-25' });
// a limit for all time, or no limit month running: no reset to hold until
expect(forecast(46 * GB, 50 * GB, 2 * GB, null, '2026-11-02')).toEqual({ kind: 'fills', days: 2, on: '2026-11-04' });
// A limit month that fills before it ends is the same.
expect(forecast(40 * GB, 50 * GB, 1 * GB, '2026-12-14', '2026-11-15')).toEqual({ kind: 'fills', days: 10, on: '2026-11-25' });
});
it('says what a monthly limit reaches by the reset when that comes first', () => {
const f = forecast(12 * GB, 100 * GB, 1 * GB, true, '2026-11-02');
expect(f).toEqual({ kind: 'holds', on: '2026-12-01', reach: 41 * GB });
it('says what a limit month reaches by its reset when that comes first', () => {
// the month is the person's own: it ends the day it began a month before, not on the 1st
const f = forecast(12 * GB, 100 * GB, 1 * GB, '2026-11-14', '2026-11-02');
expect(f).toEqual({ kind: 'holds', on: '2026-11-14', reach: 24 * GB });
// the reset is today: what is used is what it reaches
expect(forecast(12 * GB, 100 * GB, 1 * GB, '2026-11-02', '2026-11-02')).toEqual({ kind: 'holds', on: '2026-11-02', reach: 12 * GB });
});
it('has nothing to say without a limit, when full or idle', () => {
expect(forecast(5, 0, 1, true, '2026-11-02').kind).toBe('none');
expect(forecast(10, 10, 1, true, '2026-11-02').kind).toBe('none');
expect(forecast(1, 10, 0, true, '2026-11-02').kind).toBe('none');
expect(forecast(5, 0, 1, '2026-12-01', '2026-11-02').kind).toBe('none');
expect(forecast(10, 10, 1, '2026-12-01', '2026-11-02').kind).toBe('none');
expect(forecast(1, 10, 0, '2026-12-01', '2026-11-02').kind).toBe('none');
});
it('takes a week ahead, capped at the limit', () => {
+290
View File
@@ -0,0 +1,290 @@
import { describe, expect, it } from 'vitest';
import { monthOn, personLine, share } from '../src/admin/people/lines';
import { groupOf } from '../src/admin/people/card';
import { find, litAt, words } from '../src/admin/people/find';
import { inFilter, lastPlace, onlineAbove, scoped, sortBy, sortOf, sortPeople } from '../src/admin/people/roster';
import { extendAll, pauseAll, resumes } from '../src/admin/people/bulk';
import { refetchCount } from '../src/admin/people/refetch';
import type { Device, Person } from '../src/shared/types';
// The router at 2026-11-08 12:40 UTC+3.
const NOW = Date.UTC(2026, 10, 8, 9, 40) / 1000;
const T = { today: '2026-11-08', now: NOW };
const GB = 2 ** 30;
const dev = (o: Partial<Device> = {}): Device =>
({
id: 'd1',
name: 'Phone',
kind: 'phone',
address: '10.8.0.2',
disabled: false,
online: false,
handshake: NOW - 3600,
endpoint: '91.1.2.3:51820',
hostname: 'phone',
config_stale: false,
lan_bypass: false,
link: null,
spark: [],
month: [0, 0],
total: [0, 0],
...o,
}) as Device;
const person = (o: Partial<Person> = {}): Person =>
({
id: 'p1',
name: 'Lena',
server: 's1',
access: 'internet',
device_limit: 3,
expires: '',
quota_gb: 0,
quota_period: 'month',
quota_used: 0,
quota_limit: 0,
bonus_gb: 0,
dns_mode: 'device',
paused: false,
state: 'active',
month: [0, 0],
total: [0, 0],
online: 0,
last_seen: NOW - 3600,
devices: [dev()],
has_link: true,
...o,
}) as Person;
describe('personLine', () => {
it('names the backend state in its order, each with the action that fixes it', () => {
expect(personLine(person({ state: 'no_server' }), T)).toMatchObject({ text: 'No server', tone: 'bad', act: { id: 'server' } });
expect(personLine(person({ state: 'server_off', paused: true }), T)).toMatchObject({ tone: 'warn', act: { id: 'enable' } });
expect(personLine(person({ state: 'paused', paused: true }), T)).toMatchObject({ text: 'Paused', act: { id: 'resume' } });
// paused, and the end date passed while paused: resuming alone would end at once
expect(personLine(person({ state: 'paused', paused: true, expires: '2026-11-01' }), T).act).toMatchObject({
id: 'resume',
extend: true,
});
expect(personLine(person({ state: 'expired', expires: '2026-11-03' }), T)).toMatchObject({ tone: 'bad', act: { id: 'extend' } });
});
it('offers data that leaves them 10 GB or more (in tens), or the limit itself for a whole-term limit', () => {
const monthly = personLine(person({ state: 'quota', quota_used: 53 * GB, quota_limit: 50 * GB }), T);
expect(monthly.act).toMatchObject({ id: 'bonus', gb: 20 });
const over = personLine(person({ state: 'quota', quota_used: 75 * GB, quota_limit: 50 * GB }), T);
expect(over.act?.gb).toBe(40);
expect(personLine(person({ state: 'quota', quota_period: 'total', quota_used: 9 * GB, quota_limit: 5 * GB }), T).act?.id).toBe('limit');
});
it('warns of an end date in its last three days, for everyone alike', () => {
expect(personLine(person({ expires: '2026-11-10' }), T)).toMatchObject({ tone: 'warn', act: { id: 'extend' } });
expect(personLine(person({ expires: '2026-11-12' }), T).tone).toBe('');
});
it('says a device that needs something, and what fixes it', () => {
const trying = (stale: boolean) =>
personLine(person({ devices: [dev({ link: { state: 'trying', since: NOW - 600 } as Device['link'], config_stale: stale })] }), T).act;
expect(trying(false)).toMatchObject({ id: 'tell', device: 'd1' });
expect(trying(true)).toMatchObject({ id: 'show', device: 'd1' });
const stale = personLine(person({ devices: [dev({ config_stale: true })] }), T);
expect(stale).toMatchObject({ tone: 'warn', act: { id: 'show' } });
});
it('invites someone without devices where the portal is on, else offers adding one', () => {
expect(personLine(person({ devices: [] }), T).act?.id).toBe('invite');
expect(personLine(person({ devices: [], has_link: false }), T).act?.id).toBe('add-device');
expect(personLine(person({ last_seen: 0 }), T).text).toBe('No connections yet');
expect(personLine(person({ online: 2 }), T)).toMatchObject({ tone: 'ok', text: 'Online · 2 devices' });
});
});
describe('groups and order', () => {
it('puts a person in the group of what they need', () => {
expect(groupOf(person({ state: 'paused', paused: true }), T)).toBe('paused');
expect(groupOf(person({ state: 'expired', expires: '2026-11-03' }), T)).toBe('need');
// waiting on the person to fetch a new configuration is not the admin's decision
expect(groupOf(person({ devices: [dev({ config_stale: true })] }), T)).toBe('rest');
expect(groupOf(person({ online: 1 }), T)).toBe('online');
});
it('extends a month from the later of today and the end date, clamped to the month', () => {
expect(monthOn({ expires: '' }, '2026-11-08')).toBe('2026-12-08');
expect(monthOn({ expires: '2026-11-03' }, '2026-11-08')).toBe('2026-12-08');
expect(monthOn({ expires: '2027-01-31' }, '2026-11-08')).toBe('2027-02-28');
expect(share({ quota_used: 45, quota_limit: 50 })).toBe(0.9);
});
});
describe('find', () => {
const p = person({
name: 'Алёна Ким',
note: 'сестра',
devices: [
dev({ id: 'd1', name: 'MacBook Air', address: '10.8.0.7', hostname: 'macbook.alena.lan', endpoint: '[2a02:6b8::1]:4500' }),
dev({ id: 'd2', name: 'iPhone', address: '10.8.0.8', endpoint: '176.59.46.100:51820' }),
],
});
const hit = (q: string) => find(p, words(q)).hit;
it('finds by every word, in names, notes, devices and addresses, ё as е', () => {
expect(hit('')).toBe(true);
expect(hit('алена')).toBe(true);
expect(hit('ким macbook')).toBe(true);
expect(hit('10.8.0.7')).toBe(true);
expect(hit('2a02:6b8::1')).toBe(true);
expect(hit('СЕСТРА')).toBe(true);
expect(hit('ким ipad')).toBe(false);
});
it('says which device a word was found on and by what, not when the person answers it', () => {
expect(find(p, words('алена сестра')).match).toBeNull();
expect(find(p, words('176.59')).match).toMatchObject({ device: { id: 'd2' }, what: 'ip', value: '176.59.46.100' });
expect(find(p, words('10.8.0.7')).match).toMatchObject({ device: { id: 'd1' }, what: 'address' });
expect(find(p, words('ким alena.lan')).match).toMatchObject({ device: { id: 'd1' }, what: 'hostname', value: 'macbook.alena.lan' });
expect(find(p, words('iphone')).match).toMatchObject({ device: { id: 'd2' }, what: 'name' });
// the first device found is the one shown
expect(find(p, words('macbook iphone')).match).toMatchObject({ device: { id: 'd1' } });
expect(find(p, words('macbook pixel')).match).toBeNull();
});
it('finds where the longest word stands in a text', () => {
expect(litAt('176.59.46.100', words('176.59'))).toEqual([0, 6]);
expect(litAt('Алёна Ким', words('ким алена'))).toEqual([0, 5]);
expect(litAt('MacBook Air', words('pixel'))).toBeNull();
});
});
describe('the roster', () => {
const a = person({
id: 'a',
name: 'Аня',
server: 's1',
online: 1,
last_seen: NOW,
month: [GB, GB],
devices: [dev({ id: 'da', online: true })],
});
const b = person({
id: 'b',
name: 'Боря',
server: 's2',
expires: '2026-11-09',
last_seen: NOW - 3600,
devices: [dev({ id: 'db', config_stale: true })],
});
const c = person({
id: 'c',
name: 'Вика',
server: 's1',
state: 'paused',
paused: true,
expires: '2026-12-01',
quota_limit: 10 * GB,
quota_used: 9 * GB,
});
const d = person({
id: 'd',
name: 'Гена',
server: 's1',
online: 1,
state: 'quota',
quota_limit: GB,
quota_used: GB,
devices: [dev({ id: 'dd', online: true })],
});
const all = [a, b, c, d];
const ids = (ps: Person[]) => ps.map((p) => p.id).join('');
it('keeps who the address asks for: the server, a waiting configuration, a chip', () => {
expect(ids(scoped(all, {}, T))).toBe('abcd');
expect(ids(scoped(all, { server: 's1' }, T))).toBe('acd');
expect(ids(scoped(all, { need: 'config' }, T))).toBe('b');
expect(ids(scoped(all, { group: 'online' }, T))).toBe('ad');
expect(ids(scoped(all, { group: 'paused' }, T))).toBe('c');
expect(ids(scoped(all, { group: 'need' }, T))).toBe(ids(all.filter((p) => groupOf(p, T) === 'need')));
// a chip's count is of the people the other filters leave
expect(ids(scoped(all, { group: 'paused', server: 's1' }, T, false))).toBe('acd');
expect(inFilter(d, 'online', T)).toBe(true);
});
it('counts online the same in the head and in the groups', () => {
// Гена is online and needs a decision: «Online» lists Аня alone and owes one more above
expect(groupOf(d, T)).toBe('need');
expect(all.filter((p) => groupOf(p, T) === 'online').length + onlineAbove(all, T)).toBe(all.filter((p) => p.online > 0).length);
expect(onlineAbove(all, T)).toBe(1);
expect(onlineAbove([a], T)).toBe(0);
});
it('sorts by a column, names breaking ties', () => {
expect(ids(sortPeople(all, { key: 'name', dir: -1 }))).toBe('dcba');
// no end date sorts as the farthest
expect(ids(sortPeople(all, { key: 'term', dir: 1 }))).toBe('bcad');
expect(ids(sortPeople(all, { key: 'traffic', dir: -1 }))).toBe('dcab');
expect(ids(sortPeople(all, { key: 'seen', dir: -1 })).slice(0, 2)).toBe('ad');
});
it('keeps an order in the address: its key, the other way round after a dash', () => {
expect(sortBy('term')).toBe('term');
expect(sortBy('traffic')).toBe('-traffic');
expect(sortOf('-traffic')).toEqual({ key: 'traffic', dir: -1 });
expect(sortOf('term')).toEqual({ key: 'term', dir: 1 });
expect(sortOf('nope')).toBeNull();
});
it('knows where someone was last: live first, then the newest', () => {
const pt = (o: object) => ({
person: 'a',
device: 'da',
ip: '1.1.1.1',
ts: 1,
online: false,
lat: 0,
lon: 0,
city: 'A',
country: '',
cc: '',
asn: 0,
org: '',
...o,
});
const geo = {
enabled: true,
points: [pt({ city: 'Old', ts: 5 }), pt({ city: 'Live', ts: 2, online: true }), pt({ person: 'b', city: 'Other', ts: 9 })],
};
expect(lastPlace(a, geo as never)?.city).toBe('Live');
expect(lastPlace(c, geo as never)).toBeNull();
});
});
describe('picks', () => {
it('extends only those with an end date, and undoes to what each had', () => {
const b = extendAll([person({ id: 'a', expires: '2026-11-03' }), person({ id: 'b' })], '2026-11-08');
expect(b.changes).toEqual([{ id: 'a', patch: { expires: '2026-12-08' } }]);
expect(b.undo).toEqual([{ id: 'a', patch: { expires: '2026-11-03' } }]);
});
it('pauses those not paused yet; resumes when everyone picked is paused', () => {
const ps = [person({ id: 'a', paused: true }), person({ id: 'b' })];
expect(resumes(ps)).toBe(false);
expect(pauseAll(ps, true)).toEqual({ changes: [{ id: 'b', patch: { paused: true } }], undo: [{ id: 'b', patch: { paused: false } }] });
expect(resumes([ps[0]])).toBe(true);
expect(pauseAll([ps[0]], false).changes).toEqual([{ id: 'a', patch: { paused: false } }]);
expect(resumes([])).toBe(false);
});
});
describe('refetchCount', () => {
const p = person({
devices: [dev({ id: 'a' }), dev({ id: 'b', lan_bypass: true }), dev({ id: 'c', handshake: 0 }), dev({ id: 'd', disabled: true })],
});
it('counts the devices that have connected whose configuration the change rewrites', () => {
expect(refetchCount(p, { access: 'both' })).toBe(1);
expect(refetchCount(p, { access: 'lan' })).toBe(2);
expect(refetchCount(person({ ...p, access: 'lan' }), { access: 'internet' })).toBe(2);
expect(refetchCount(p, { dns_mode: 'home' })).toBe(0);
expect(refetchCount(person({ ...p, access: 'lan' }), { dns_mode: 'home' })).toBe(2);
expect(refetchCount(person({ ...p, access: 'both' }), { home_nets: ['lan'] })).toBe(1);
expect(refetchCount(p, { access: 'internet' })).toBe(0);
});
});
+144 -1
View File
@@ -1,5 +1,21 @@
import { describe, expect, it } from 'vitest';
import { moment, msAt, placeKey, replayStays, shares, stays, stretches, ticks, timeline, visits } from '../src/admin/places/model';
import {
cities,
inPeriod,
moment,
msAt,
placeKey,
replayStays,
shares,
stays,
stretches,
stripRuns,
ticks,
timeline,
union,
visits,
visitsOf,
} from '../src/admin/places/model';
import type { GeoPoint, LogEvent } from '../src/shared/types';
const D = 'd_1';
@@ -148,3 +164,130 @@ describe('ticks', () => {
expect(t.every(([, l]) => /^\d\d:00$/.test(l))).toBe(true);
});
});
describe('cities', () => {
const at = (device: string, city: string, ts: number, online = false, cc = 'RU'): GeoPoint => ({
...pt(`10.0.0.${ts % 250}`, city, 45, 39, device),
ts,
online,
cc,
});
it('puts each device once per place: live over newest, newest over older', () => {
const [krd] = cities([at('a', 'Krasnodar', 100), at('a', 'Krasnodar', 300), at('a', 'Krasnodar', 200, true), at('b', 'Krasnodar', 50)]);
expect(krd.points.map((p) => [p.device, p.ts])).toEqual([
['a', 200],
['b', 50],
]);
expect(krd.live).toBe(1);
expect(krd.last).toBe(200);
});
it('orders places: someone there now, then more devices, then the most recent', () => {
const list = cities([
at('a', 'Sochi', 900),
at('b', 'Moscow', 100),
at('c', 'Moscow', 120),
at('d', 'Tula', 50, true),
at('e', 'Kazan', 950),
]);
expect(list.map((c) => c.name)).toEqual(['Tula', 'Moscow', 'Kazan', 'Sochi']);
});
it('keeps one city name in two countries apart, and names a place without a city by its country', () => {
const list = cities([at('a', 'Paris', 10, false, 'FR'), at('b', 'Paris', 20, false, 'US'), at('c', '', 30, false, 'TR')]);
expect(list).toHaveLength(3);
expect(list.map((c) => c.name).sort()).toEqual(['Paris', 'Paris', 'TR']);
});
it('is empty for no points', () => {
expect(cities([])).toEqual([]);
});
});
describe('inPeriod', () => {
it('takes live points now, and points seen within the period', () => {
const p = { ...pt('1.1.1.1', 'X', 0, 0), ts: 1000 - 3600 };
expect(inPeriod(p, 'online', 1000)).toBe(false);
expect(inPeriod({ ...p, online: true }, 'online', 1000)).toBe(true);
expect(inPeriod(p, '24h', 1000)).toBe(true);
expect(inPeriod({ ...p, ts: 1000 - 2 * 86400 }, '24h', 1000)).toBe(false);
expect(inPeriod({ ...p, ts: 1000 - 2 * 86400 }, '7d', 1000)).toBe(true);
});
});
describe("a place row's strip", () => {
it("lays a place's visits out as shares of the period, clipped to it", () => {
const now = 100_000;
const span = 10_000;
const v = [
{ key: 'a', point: HOME, from: 80_000, to: 92_000, live: false },
{ key: 'b', point: MOBILE, from: 92_000, to: 95_000, live: false },
{ key: 'a', point: HOME, from: 95_000, to: 100_000, live: true },
{ key: 'a', point: HOME, from: 10_000, to: 20_000, live: false },
];
expect(stripRuns(v, 'a', now, span)).toEqual([
[0, 0.2],
[0.5, 0.5],
]);
expect(stripRuns(v, 'b', now, span)).toEqual([[0.2, 0.3]]);
expect(stripRuns(v, 'c', now, span)).toEqual([]);
});
});
describe("a person's devices together", () => {
const PHONE = 'd_phone';
const LAPTOP = 'd_laptop';
const events = [
ev(0, 'connect', HOME.ip, PHONE),
ev(1000, 'roam', `${HOME.ip} → ${MOBILE.ip}`, PHONE),
ev(2000, 'disconnect', undefined, PHONE),
ev(500, 'connect', HOME.ip, LAPTOP),
ev(1500, 'disconnect', undefined, LAPTOP),
];
const points = [HOME, MOBILE].flatMap((x) => [
{ ...x, device: PHONE },
{ ...x, device: LAPTOP },
]);
const v = visitsOf(
events,
[
{ id: PHONE, online: false },
{ id: LAPTOP, online: false },
],
points,
3000,
0,
);
it('joins spans that overlap or touch', () => {
expect(
union([
[5, 8],
[0, 2],
[1, 3],
[3, 4],
[9, 9],
]),
).toEqual([
[0, 4],
[5, 8],
]);
expect(union([])).toEqual([]);
});
it("lists every device's visits in time order", () => {
expect(v.map((x) => [x.key, x.from, x.to])).toEqual([
['Krasnodar|RU', 0, 1000],
['Krasnodar|RU', 500, 1500],
['Novocherkassk|RU', 1000, 2000],
]);
});
it('shares the time any of them was at a place against the time any of them was anywhere', () => {
const sh = shares(v);
// Krasnodar 0–1500 of 0–2000; Novocherkassk 1000–2000, at once with the laptop at home
expect(sh.get('Krasnodar|RU')).toBeCloseTo(0.75);
expect(sh.get('Novocherkassk|RU')).toBeCloseTo(0.5);
});
});
+100
View File
@@ -0,0 +1,100 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { followLive, hasLive } from '../src/portal/live';
import type { State } from '../src/portal/state';
/** A browser to follow in: the page's #app, its visibility, and streams the test speaks through. */
function browser(live: boolean) {
const streams: Fake[] = [];
const onShow: (() => void)[] = [];
class Fake {
static CLOSED = 2;
readyState = 0;
onerror: (() => void) | null = null;
private on = new Map<string, (e: { data: string }) => void>();
constructor(readonly url: string) {
streams.push(this);
}
addEventListener(name: string, f: (e: { data: string }) => void) {
this.on.set(name, f);
}
close() {
this.readyState = 2;
}
say(name: string, data: unknown) {
this.on.get(name)?.({ data: JSON.stringify(data) });
}
refuse() {
this.readyState = 2;
this.onerror?.();
}
}
const doc = {
hidden: false,
getElementById: () => ({ dataset: live ? { base: '/kamiro-telosu-bavine', live: '1' } : { base: '/kamiro-telosu-bavine' } }),
addEventListener: (_n: string, f: () => void) => void onShow.push(f),
};
vi.stubGlobal('document', doc);
vi.stubGlobal('window', { EventSource: Fake });
vi.stubGlobal('EventSource', Fake);
return {
streams,
show(visible: boolean) {
doc.hidden = !visible;
onShow.forEach((f) => f());
},
};
}
const person = (online: number) => ({ person: { name: 'Anna', online, devices: [] }, can_add: true }) as unknown as State;
describe("the portal's stream", () => {
afterEach(() => vi.unstubAllGlobals());
it('is followed only where the router offers one', () => {
browser(false);
expect(hasLive()).toBe(false);
browser(true);
expect(hasLive()).toBe(true);
});
it('takes the state whole, then each change laid over it', () => {
const b = browser(true);
const seen: State[] = [];
followLive({ state: (st) => void seen.push(st), gone: () => undefined, failed: () => undefined });
expect(b.streams[0].url).toBe('/kamiro-telosu-bavine/api/live');
b.streams[0].say('put', person(0));
b.streams[0].say('patch', { person: { online: 1 }, here: 'd1' });
expect(seen[1]).toEqual({ person: { name: 'Anna', online: 1, devices: [] }, can_add: true, here: 'd1' });
// what did not change is the object it was: the page draws nothing of it again
expect(seen[1].person.devices).toBe(seen[0].person.devices);
// a field the router takes away
b.streams[0].say('patch', { here: null });
expect('here' in seen[2]).toBe(false);
});
it('lets the stream go while the page is hidden, and opens on the whole state again', () => {
const b = browser(true);
followLive({ state: () => undefined, gone: () => undefined, failed: () => undefined });
b.show(false);
expect(b.streams[0].readyState).toBe(2);
b.show(true);
expect(b.streams.length).toBe(2);
});
it('asks the router itself when no stream opens, and stops for good when the link is gone', () => {
let b = browser(true);
const said: string[] = [];
const on = { state: () => void said.push('state'), gone: () => void said.push('gone'), failed: () => void said.push('failed') };
followLive(on);
b.streams[0].refuse();
b.show(true);
expect([said, b.streams.length]).toEqual([['failed'], 1]);
b = browser(true);
said.length = 0;
followLive(on);
b.streams[0].say('put', person(0));
b.streams[0].say('gone', {});
b.show(true);
expect([said, b.streams.length, b.streams[0].readyState]).toEqual([['state', 'gone'], 1, 2]);
});
});
+135
View File
@@ -0,0 +1,135 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { keepPlace, putChildren } from '../src/portal/ui/put';
/** A node and a box of nodes, as far as putChildren reads the DOM: who stands where, and what was taken out. */
class N {
parentNode: Box | null = null;
/** How many times it left a box (a move within the box counts: its focus and scroll would go with it). */
left = 0;
constructor(public name: string) {}
get nextSibling(): N | null {
const list = this.parentNode?.kids ?? [];
return list[list.indexOf(this) + 1] ?? null;
}
remove() {
const p = this.parentNode;
if (!p) return;
p.kids.splice(p.kids.indexOf(this), 1);
this.parentNode = null;
this.left++;
p.seen();
}
}
class Box {
kids: N[] = [];
/** The fewest children it ever held between two calls: an emptied box loses the page's scroll in WebKit. */
fewest = Infinity;
constructor(...kids: N[]) {
for (const k of kids) {
k.parentNode = this;
this.kids.push(k);
}
}
seen() {
this.fewest = Math.min(this.fewest, this.kids.length);
}
get firstChild(): N | null {
return this.kids[0] ?? null;
}
get childNodes(): N[] {
return this.kids;
}
insertBefore(n: N, at: N | null) {
n.remove();
n.parentNode = this;
this.kids.splice(at ? this.kids.indexOf(at) : this.kids.length, 0, n);
this.seen();
}
names() {
return this.kids.map((k) => k.name).join(' ');
}
}
const put = (box: Box, next: N[]) => putChildren(box as unknown as Element, next as unknown as Node[]);
describe('a box given its next children', () => {
it('holds exactly them, in order', () => {
const [a, b, c, x] = ['a', 'b', 'c', 'x'].map((n) => new N(n));
const box = new Box(a, b, c);
put(box, [c, x, a]);
expect(box.names()).toBe('c x a');
expect(b.parentNode).toBeNull();
});
it('leaves alone what stays where it stood', () => {
const [a, b, c, x, y] = ['a', 'b', 'c', 'x', 'y'].map((n) => new N(n));
const box = new Box(a, b, c);
// b is built anew (y takes its place), x comes at the end: a and c are never taken out
put(box, [a, y, c, x]);
expect(box.names()).toBe('a y c x');
expect([a.left, c.left]).toEqual([0, 0]);
});
it('is never emptied on the way, even when every child is new', () => {
const old = ['a', 'b', 'c'].map((n) => new N(n));
const next = ['x', 'y'].map((n) => new N(n));
const box = new Box(...old);
box.fewest = Infinity;
put(box, next);
expect(box.names()).toBe('x y');
// the new ones stood before the old ones left: never fewer than it ends with
expect(box.fewest).toBeGreaterThanOrEqual(2);
});
it('empties a box that is to be empty, and fills an empty one', () => {
const [a, b] = ['a', 'b'].map((n) => new N(n));
const box = new Box(a);
put(box, []);
expect(box.names()).toBe('');
put(box, [b, a]);
expect(box.names()).toBe('b a');
});
});
/** A page as far as the hold reads it: boxes one in another, a shadow root between, each with where it is scrolled to. */
class El {
scrollTop = 0;
scrollLeft = 0;
constructor(public parentNode: El | Root | null = null) {}
}
class Root {
parentNode = null;
constructor(public host: El) {}
}
describe('the page keeps its place over a redraw', () => {
afterEach(() => vi.unstubAllGlobals());
const page = () => {
vi.stubGlobal('Element', El);
vi.stubGlobal('ShadowRoot', Root);
// the main area scrolls; the admin's host stands in it, its page under a shadow root, a track of tabs in the page
const main = new El();
const host = new El(main);
const track = new El(new El(new Root(host)));
const box = new El(track);
main.scrollTop = 841;
track.scrollLeft = 120;
return { main, track, box: box as unknown as Element };
};
it('puts back every scrolled box around the one that changes, across the shadow root', () => {
const { main, track, box } = page();
// (what WebKit does when a section on screen is swapped for a newly built one)
const said = keepPlace(box, () => {
main.scrollTop = 0;
track.scrollLeft = 0;
return 'drawn';
});
expect([main.scrollTop, track.scrollLeft, said]).toEqual([841, 120, 'drawn']);
});
it('puts it back when the redraw throws, and the throw goes on', () => {
const { main, box } = page();
expect(() =>
keepPlace(box, () => {
main.scrollTop = 0;
throw new Error('no');
}),
).toThrow('no');
expect(main.scrollTop).toBe(841);
});
});
+255
View File
@@ -0,0 +1,255 @@
import { beforeAll, describe, expect, it } from 'vitest';
import {
SECTIONS,
deviceUrl,
href,
logUrl,
peopleAt,
peopleUrl,
personUrl,
placesUrl,
sectionOf,
healthUrl,
serverUrl,
settingsUrl,
sectionPlace,
withCloseUp,
} from '../src/admin/shell/routes';
import { follow, listOf, parseRoute, routeQuery } from '../src/admin/people/route';
import { target } from '../src/admin/shell/redirects';
import { partOf } from '../src/admin/pages/settings/route';
beforeAll(() => {
Object.assign(globalThis, { L: { url: (p: string) => `/cgi-bin/luci/${p}` } });
});
describe('sections', () => {
it('knows the section of every view', () => {
expect(SECTIONS).toEqual(['overview', 'log', 'settings']);
expect(sectionOf('log', '')).toBe('log');
expect(sectionOf('activity', '')).toBe('log');
// a server's page stands behind Overview: its own view, and People (a person, a device, Places) inside its frame
expect(sectionOf('server', '')).toBe('overview');
expect(sectionOf('server', 'server=s1&p=core')).toBe('overview');
expect(sectionOf('people', '')).toBe('overview');
expect(sectionOf('people', 'view=map&device=d1')).toBe('overview');
expect(sectionOf('person', 'id=p1&device=d1')).toBe('overview');
expect(sectionOf('device', 'id=d1')).toBe('overview');
expect(sectionOf('places', 'sheet=places&device=d1')).toBe('overview');
// Settings: the router's own sections; the old System page leads there
expect(sectionOf('settings', '')).toBe('settings');
expect(sectionOf('settings', 'p=backups')).toBe('settings');
expect(sectionOf('system', 'open=updates')).toBe('settings');
expect(sectionOf('updates', '')).toBe('settings');
// Overview, and Dawnline's own menu item (an alias of it); Health is Overview's now
expect(sectionOf('overview', '')).toBe('overview');
expect(sectionOf('dawnline', '')).toBe('overview');
expect(sectionOf('health', '')).toBe('overview');
expect(sectionOf('system', 'open=health')).toBe('overview');
expect(sectionOf('diagnostics', '')).toBe('overview');
expect(sectionOf('diagnostics', 'tab=log')).toBe('log');
expect(sectionOf('elsewhere', '')).toBeNull();
});
it('opens every section on a page that lights its tab', () => {
expect(SECTIONS[0]).toBe('overview');
for (const s of SECTIONS) {
const p = sectionPlace(s);
expect(sectionOf(p.view, p.query ?? '')).toBe(s);
}
expect(sectionPlace('settings')).toEqual({ view: 'settings' });
});
});
describe('addresses', () => {
it('builds them with L.url; a person, a device and places are People with the old query names', () => {
const at = '/cgi-bin/luci/admin/services/dawnline/';
expect(href({ view: 'log' })).toBe(`${at}log`);
expect(href({ view: 'settings', query: 'p=entry' })).toBe(`${at}settings?p=entry`);
expect(personUrl('p 1')).toBe(`${at}people?id=p+1`);
expect(personUrl('p1', 'traffic')).toBe(`${at}people?id=p1&s=traffic`);
expect(deviceUrl('d&2')).toBe(`${at}people?device=d%262`);
expect(deviceUrl('d1', 'setup')).toBe(`${at}people?device=d1&sheet=setup`);
expect(placesUrl()).toBe(`${at}people?view=map`);
expect(placesUrl({ person: 'p1' })).toBe(`${at}people?view=map&id=p1`);
expect(placesUrl({ server: 's1' })).toBe(`${at}people?view=map&server=s1`);
expect(placesUrl({ device: 'd1' })).toBe(`${at}people?device=d1&sheet=places`);
expect(peopleUrl('s1')).toBe(`${at}people?server=s1`);
expect(peopleUrl('s1', 'config')).toBe(`${at}people?server=s1&need=config`);
expect(peopleUrl()).toBe(`${at}people`);
expect(peopleAt({ view: 'map', device: 'd1', range: '7d' })).toBe(`${at}people?view=map&device=d1&range=7d`);
expect(logUrl({ device: 'd1' })).toBe(`${at}log?device=d1`);
expect(logUrl({ kind: 'problems' })).toBe(`${at}log?kind=problems`);
expect(logUrl()).toBe(`${at}log`);
expect(logUrl({ kind: 'problems', day: 'yesterday' })).toBe(`${at}log?kind=problems&day=yesterday`);
expect(logUrl({ server: 's1', q: '176.59' })).toBe(`${at}log?server=s1&q=176.59`);
// a server's page: its Overview, a part of its settings, its people and places (the People view in its frame)
expect(serverUrl()).toBe(`${at}server`);
expect(serverUrl('s1')).toBe(`${at}server?server=s1`);
expect(serverUrl('s1', 'core')).toBe(`${at}server?server=s1&p=core`);
expect(serverUrl('s1', 'people')).toBe(`${at}people?server=s1`);
expect(serverUrl('s1', 'places')).toBe(`${at}people?view=map&server=s1`);
// where something is set: a router's section in Settings, a stage of a server's path on the server's page
expect(settingsUrl('backups')).toBe(`${at}settings?p=backups`);
expect(settingsUrl('backups', 's1')).toBe(`${at}settings?p=backups`);
expect(settingsUrl()).toBe(`${at}server`);
expect(settingsUrl(undefined, 's1')).toBe(`${at}server?server=s1`);
expect(settingsUrl('home', 's1')).toBe(`${at}server?server=s1&p=network&s=home`);
expect(settingsUrl('entry')).toBe(`${at}server?p=general&s=entry`);
expect(settingsUrl('disguise', 's2')).toBe(`${at}server?server=s2&p=core&s=disguise`);
expect(settingsUrl('check', 's1')).toBe(`${at}server?server=s1&s=check`);
expect(healthUrl()).toBe(`${at}overview?s=health`);
});
});
describe('the People route', () => {
it('reads an address and writes it back the same', () => {
expect(parseRoute('')).toEqual(listOf({}));
expect(routeQuery(parseRoute('id=p1&group=need&sort=-traffic'))).toBe('id=p1&group=need&sort=-traffic');
expect(routeQuery(parseRoute('range=7d&view=map&server=s1'))).toBe('view=map&server=s1&range=7d');
// a device's panel takes the person's place
expect(parseRoute('id=p1&device=d1')).toMatchObject({ id: undefined, device: 'd1' });
expect(routeQuery({ id: 'p1', device: 'd1' })).toBe('device=d1');
// what is not a value of its key is dropped
expect(parseRoute('view=grid&group=all&need=1&range=year')).toEqual(listOf({}));
// the old ?add=1 asks for the Add sheet
expect(parseRoute('add=1').sheet).toBe('add');
expect(parseRoute('device=d1&sheet=setup').sheet).toBe('setup');
});
it('opens a link to an object beside the list as it stands, and takes a link to a view whole', () => {
const cur = parseRoute('view=map&server=s1&range=7d&id=p1');
expect(routeQuery(follow(cur, parseRoute('device=d1')))).toBe('view=map&device=d1&server=s1&range=7d');
expect(routeQuery(follow(cur, parseRoute('id=p2&s=term')))).toBe('view=map&id=p2&server=s1&range=7d&s=term');
// the way back to the list: the panel shuts, the list stays
expect(routeQuery(follow(cur, parseRoute('')))).toBe('view=map&server=s1&range=7d');
expect(routeQuery(follow(parseRoute('group=need&id=p1'), parseRoute('view=map&id=p1')))).toBe('view=map&id=p1');
expect(routeQuery(follow(parseRoute('id=p1'), parseRoute('server=s2')))).toBe('server=s2');
});
});
describe('redirects', () => {
it('sends old addresses on', () => {
expect(target('activity', '')).toEqual({ view: 'log' });
expect(target('diagnostics', 'tab=log')).toEqual({ view: 'log' });
// Diagnostics and Health are Overview's health checks
const health = { view: 'overview', query: 's=health' };
expect(target('health', '')).toEqual(health);
expect(target('diagnostics', '')).toEqual(health);
expect(target('diagnostics', 'tab=health')).toEqual(health);
expect(target('system', 'open=health')).toEqual(health);
// Components and the System page's rows are the router's own sections of Settings
expect(target('updates', '')).toEqual({ view: 'settings', query: 'p=updates' });
expect(target('system', '')).toEqual({ view: 'settings', query: 'p=updates' });
expect(target('system', 'open=portal')).toEqual({ view: 'settings', query: 'p=portal' });
expect(target('system', 'open=backups')).toEqual({ view: 'settings', query: 'p=backups' });
expect(target('system', 'open=history')).toEqual({ view: 'settings', query: 'p=history' });
expect(target('system', 'open=remove')).toEqual({ view: 'settings', query: 'p=remove' });
expect(target('system', 'open=nonsense')).toEqual({ view: 'settings', query: 'p=updates' });
// Settings keeps the router's sections: its old queries are sent on, and a server's path (it was Settings'
// own) goes to the server's page
expect(target('settings', '')).toBeNull();
expect(target('settings', 'p=portal')).toBeNull();
expect(target('settings', 'p=nonsense')).toBeNull();
expect(target('settings', 'p=portal&server=s1')).toEqual({ view: 'settings', query: 'p=portal' });
expect(target('settings', 'server=s1')).toEqual({ view: 'server', query: 'server=s1' });
expect(target('settings', 'p=home&server=s1')).toEqual({ view: 'server', query: 'server=s1&p=network&s=home' });
expect(target('settings', 'p=entry')).toEqual({ view: 'server', query: 'p=general&s=entry' });
expect(target('settings', 'p=rollout&server=s2')).toEqual({ view: 'server', query: 'server=s2&s=rollout' });
expect(target('settings', 'section=backups')).toEqual({ view: 'settings', query: 'p=backups' });
expect(target('settings', 'section=map')).toEqual({ view: 'settings', query: 'p=history' });
expect(target('settings', 'tab=map')).toEqual({ view: 'settings', query: 'p=history' });
expect(target('settings', 'section=logs')).toEqual({ view: 'settings', query: 'p=history' });
expect(target('settings', 'section=danger')).toEqual({ view: 'settings', query: 'p=remove' });
expect(target('settings', 'section=portal')).toEqual({ view: 'settings', query: 'p=portal' });
expect(target('settings', 'tab=general')).toEqual({ view: 'settings', query: 'p=updates' });
// a server's People section is People, filtered to that server; its old filters are the groups now
expect(target('server', 'server=s1&section=people&filter=online')).toEqual({ view: 'people', query: 'server=s1' });
expect(target('server', 'section=people')).toEqual({ view: 'people', query: undefined });
// the server's page is a page of its own; its old rows (?open=) and the Servers page's sections before them
// (?section=) are parts of it
expect(target('server', '')).toBeNull();
expect(target('server', 'server=s2')).toBeNull();
expect(target('server', 'server=s2&p=core')).toBeNull();
expect(target('server', 'server=s1&open=home')).toEqual({ view: 'server', query: 'server=s1&p=network&s=home' });
expect(target('server', 'open=check')).toEqual({ view: 'server', query: 's=check' });
expect(target('server', 'open=nonsense')).toEqual({ view: 'server', query: undefined });
expect(target('server', 'server=s1&section=connection')).toEqual({ view: 'server', query: 'server=s1&p=general&s=entry' });
expect(target('server', 'section=access')).toEqual({ view: 'server', query: 'p=network&s=home' });
expect(target('server', 'server=s2&section=awg')).toEqual({ view: 'server', query: 'server=s2&p=core&s=disguise' });
expect(target('server', 'section=tunnel')).toEqual({ view: 'server', query: 'p=network&s=tunnel' });
expect(target('server', 'section=advanced')).toEqual({ view: 'server', query: 'p=core&s=devices' });
expect(target('server', 'server=s1&section=overview')).toEqual({ view: 'server', query: 'server=s1' });
expect(target('server', 'section=overview')).toEqual({ view: 'server', query: undefined });
// Overview is a page of its own again
expect(target('overview', 'server=s1')).toBeNull();
expect(target('overview', '')).toBeNull();
});
it('sends a person, a device and Places into People, keeping the query names', () => {
expect(target('person', 'id=p1')).toEqual({ view: 'people', query: 'id=p1' });
expect(target('person', 'id=p+1&open=traffic')).toEqual({ view: 'people', query: 'id=p+1&s=traffic' });
expect(target('person', 'id=p1&open=networks')).toEqual({ view: 'people', query: 'id=p1&s=reach' });
// the devices row is the panel's first block: nothing to scroll to
expect(target('person', 'id=p1&open=devices')).toEqual({ view: 'people', query: 'id=p1' });
expect(target('person', 'id=p1&add=1')).toEqual({ view: 'people', query: 'id=p1&sheet=add' });
// older still: a person's page with a device's drawer open
expect(target('person', 'id=p1&device=d+1')).toEqual({ view: 'people', query: 'device=d+1' });
expect(target('person', '')).toEqual({ view: 'people', query: undefined });
expect(target('device', 'id=d1')).toEqual({ view: 'people', query: 'device=d1' });
expect(target('device', 'id=d1&sheet=setup')).toEqual({ view: 'people', query: 'device=d1&sheet=setup' });
expect(target('device', 'id=d1&sheet=places&device=d1')).toEqual({ view: 'people', query: 'device=d1&sheet=places' });
expect(target('places', '')).toEqual({ view: 'people', query: 'view=map' });
expect(target('places', 'person=p1')).toEqual({ view: 'people', query: 'view=map&id=p1' });
expect(target('places', 'server=s1')).toEqual({ view: 'people', query: 'view=map&server=s1' });
expect(target('places', 'person=p1&sheet=places&device=d1')).toEqual({ view: 'people', query: 'device=d1&sheet=places' });
});
it('leaves pages of their own alone', () => {
expect(target('log', '')).toBeNull();
expect(target('settings', 'p=updates')).toBeNull();
expect(target('server', 'server=s1&p=network&s=home')).toBeNull();
expect(target('overview', 's=health')).toBeNull();
expect(target('people', 'id=p1')).toBeNull();
expect(target('people', 'view=map')).toBeNull();
});
});
describe('the close-up in the address', () => {
it('adds and takes away sheet=places&device=, keeping what the page had', () => {
const at = 'http://r/cgi-bin/luci/admin/services/dawnline/';
expect(withCloseUp(`${at}overview`, 'd1')).toBe('/cgi-bin/luci/admin/services/dawnline/overview?sheet=places&device=d1');
expect(withCloseUp(`${at}overview?sheet=places&device=d1`, null)).toBe('/cgi-bin/luci/admin/services/dawnline/overview');
expect(withCloseUp(`${at}log?device=d1&sheet=places`, null)).toBe('/cgi-bin/luci/admin/services/dawnline/log?device=d1');
expect(withCloseUp(`${at}log?device=d1`, 'd1')).toBe('/cgi-bin/luci/admin/services/dawnline/log?device=d1&sheet=places');
// on People ?device= is the open panel: it stays when the close-up shuts
expect(withCloseUp(`${at}people?view=map&device=d1`, 'd1')).toBe(
'/cgi-bin/luci/admin/services/dawnline/people?view=map&device=d1&sheet=places',
);
expect(withCloseUp(`${at}people?view=map&device=d1&sheet=places`, null)).toBe(
'/cgi-bin/luci/admin/services/dawnline/people?view=map&device=d1',
);
});
it("keeps a person's page theirs: all their devices, or the one picked as pick=", () => {
const at = 'http://r/cgi-bin/luci/admin/services/dawnline/';
expect(withCloseUp(`${at}people?id=p1`, null, true)).toBe('/cgi-bin/luci/admin/services/dawnline/people?id=p1&sheet=places');
expect(withCloseUp(`${at}people?id=p1&sheet=places`, 'd2', true)).toBe(
'/cgi-bin/luci/admin/services/dawnline/people?id=p1&sheet=places&pick=d2',
);
expect(withCloseUp(`${at}people?id=p1&sheet=places&pick=d2`, null, true)).toBe(
'/cgi-bin/luci/admin/services/dawnline/people?id=p1&sheet=places',
);
// closed: back to the person's page
expect(withCloseUp(`${at}people?id=p1&sheet=places&pick=d2`, null)).toBe('/cgi-bin/luci/admin/services/dawnline/people?id=p1');
});
});
describe('the Settings route', () => {
it('names one of the router’s sections; none, or one that does not exist: Updates', () => {
for (const p of ['updates', 'portal', 'defaults', 'history', 'backups', 'remove']) expect(partOf(`p=${p}`)).toBe(p);
expect(partOf('')).toBe('updates');
expect(partOf('p=tunnel&server=s2')).toBe('updates');
expect(partOf('p=health')).toBe('updates');
});
});
+305
View File
@@ -0,0 +1,305 @@
import { describe, expect, it } from 'vitest';
import { issued, lastChange, meshRewrites, refetch, refetchAny, rollout, rolloutItems } from '../src/admin/servers/rollout';
import { fieldsPatch, netPatch, refetchOf, stage, stagedOf, summary, unstage, type Staged } from '../src/admin/servers/pending';
import { stageChecks, stageOf, stageStates, wanMoved } from '../src/admin/servers/path';
import { homeAccess, whoReaches } from '../src/admin/servers/reach';
import { paramCount, paramGroups, paramsConf } from '../src/admin/servers/params';
import { fixLabel } from '../src/admin/servers/fixes';
import type { ServiceLogEntry } from '../src/admin/api';
import type { Device, HealthCheck, Person, Server } from '../src/shared/types';
const NOW = Date.UTC(2026, 10, 8, 9, 40) / 1000;
const dev = (o: Partial<Device> = {}): Device =>
({
id: 'd1',
name: 'Phone',
kind: 'phone',
disabled: false,
online: false,
handshake: NOW - 3600,
config_stale: false,
config_issued: NOW - 7200,
lan_bypass: false,
mtu: 0,
keepalive: null,
...o,
}) as Device;
const person = (o: Partial<Person> = {}): Person =>
({
id: 'p1',
name: 'Lena',
server: 's1',
access: 'internet',
state: 'active',
services: [],
home_nets: [],
devices: [dev()],
...o,
}) as Person;
const server = (o: Partial<Server> = {}): Server =>
({ id: 's1', name: 'Home', enabled: true, up: true, endpoint: 'vpn.example.com', lan_like: false, mesh: 'off', ...o }) as Server;
describe('rollout', () => {
const people = [
person({
id: 'a',
devices: [dev({ id: 'a1', config_stale: true }), dev({ id: 'a2' }), dev({ id: 'a3', disabled: true, config_stale: true })],
}),
// never given one: not counted; given one before the router kept the time (stale or a handshake): counted
person({
id: 'b',
devices: [dev({ id: 'b1', config_issued: 0, handshake: 0 }), dev({ id: 'b2', config_issued: 0, config_stale: true, handshake: 0 })],
}),
// paused and ended people fetch nothing until they are back
person({ id: 'c', state: 'paused', devices: [dev({ id: 'c1', config_stale: true })] }),
person({ id: 'd', server: 's2', devices: [dev({ id: 'd1', config_stale: true })] }),
];
it('counts the devices that hold a configuration, of people the tunnel carries', () => {
expect(rolloutItems(people, 's1').map((x) => x.d.id)).toEqual(['a1', 'a2', 'b2']);
expect(rollout(people, 's1')).toEqual({ done: 1, of: 3 });
expect(rollout([person()], 's1')).toBeNull();
});
it('knows a device that was given one', () => {
expect(issued(dev())).toBe(true);
expect(issued(dev({ config_issued: 0, handshake: 0 }))).toBe(false);
expect(issued(dev({ config_issued: 0, handshake: 0, config_stale: true }))).toBe(true);
expect(issued(dev({ config_issued: 0 }))).toBe(true);
});
});
describe('refetch (⟳N)', () => {
const people = [
person({ id: 'i', access: 'internet', devices: [dev({ id: 'i1', mtu: 1400 }), dev({ id: 'i2', keepalive: 30, lan_bypass: true })] }),
person({ id: 'l', access: 'lan', devices: [dev({ id: 'l1' }), dev({ id: 'l2', handshake: 0, config_issued: 0 })] }),
person({ id: 'b', access: 'both', home_nets: ['br-lan'], devices: [dev({ id: 'b1', lan_bypass: true }), dev({ id: 'b2' })] }),
person({ id: 'p', state: 'expired', devices: [dev({ id: 'p1' })] }),
];
it('counts what a change rewrites', () => {
expect(refetch(people, 's1', 'all')).toEqual({ n: 6, paused: 1, fresh: 1, people: 4 });
// their own MTU or keep-alive wins over the server's
expect(refetch(people, 's1', 'mtu').n).toBe(5);
expect(refetch(people, 's1', 'keepalive').n).toBe(5);
// Home-only devices never ask the server's DNS
expect(refetch(people, 's1', 'dns').n).toBe(5);
// routes: Home only, and both with LAN Bypass
expect(refetch(people, 's1', 'routes').n).toBe(2);
// home networks: the same, unless their page picked networks of their own
expect(refetch(people, 's1', 'home').n).toBe(1);
});
it('rewrites routes only between apart and together', () => {
expect(meshRewrites('off', 'all')).toBe(true);
expect(meshRewrites('circles', 'off')).toBe(true);
expect(meshRewrites('all', 'circles')).toBe(false);
});
});
describe('pending changes', () => {
const people = [
person({ id: 'i', access: 'internet', devices: [dev({ id: 'i1', mtu: 1400 }), dev({ id: 'i2', keepalive: 30, lan_bypass: true })] }),
person({ id: 'l', access: 'lan', devices: [dev({ id: 'l1' }), dev({ id: 'l2', handshake: 0, config_issued: 0 })] }),
person({ id: 'b', access: 'both', home_nets: ['br-lan'], devices: [dev({ id: 'b1', lan_bypass: true }), dev({ id: 'b2' })] }),
person({ id: 'p', state: 'expired', devices: [dev({ id: 'p1' })] }),
];
const mtu: Staged = { kind: 'mtu', label: 'MTU: 1380', value: '1380', values: { mtu: '1380' } };
const port: Staged = { kind: 'port', label: 'UDP port: 443', value: '443', values: { port: '443' } };
const dns: Staged = { kind: 'dns', label: 'DNS: 1.1.1.1', value: '1.1.1.1', values: { dns: '1.1.1.1' } };
it('counts a device once whatever number of changes rewrite it', () => {
// MTU leaves out i1 (its own MTU), DNS leaves out the Home-only l1: together everyone but nobody twice
expect(refetchAny(people, 's1', ['mtu']).n).toBe(5);
expect(refetchAny(people, 's1', ['dns']).n).toBe(5);
expect(refetchAny(people, 's1', ['mtu', 'dns'])).toEqual({ n: 6, paused: 1, fresh: 1, people: 4 });
expect(refetchAny(people, 's1', [])).toEqual({ n: 0, paused: 0, fresh: 0, people: 0 });
expect(refetchOf('mtu', 's1', people)).toBe(5);
expect(refetchOf('mesh', 's1', people)).toBe(2);
expect(refetchOf('port', 's2', people)).toBe(0);
});
it('keeps one staged change a kind, the later one in the place of the earlier', () => {
let list = stage(stage(stage([], mtu), port), dns);
expect(list.map((x) => x.kind)).toEqual(['mtu', 'port', 'dns']);
list = stage(list, { ...mtu, value: '1300', label: 'MTU: 1300', values: { mtu: '1300' } });
expect(list.map((x) => x.label)).toEqual(['MTU: 1300', 'UDP port: 443', 'DNS: 1.1.1.1']);
expect(stagedOf(list, 'mtu')?.value).toBe('1300');
expect(unstage(list, 'port').map((x) => x.kind)).toEqual(['mtu', 'dns']);
expect(stagedOf(unstage(list, 'port'), 'port')).toBeUndefined();
});
it('holds a disguise and its new values as one, and the home networks choice as one', () => {
let list = stage([], { kind: 'disguise', label: 'Disguise: Maximum', value: 'Maximum', preset: 'max' });
list = stage(list, { kind: 'renew', label: 'New disguise values', value: 'Balanced', preset: 'balanced' });
expect(list).toHaveLength(1);
expect(list[0]).toMatchObject({ kind: 'renew', preset: 'balanced' });
expect(stagedOf(list, 'disguise')?.kind).toBe('renew');
list = stage(list, { kind: 'home', label: 'Home networks', value: 'guest', net: { lan_devices: ['br-lan', 'guest'] } });
// the section hands in the whole choice that differs from the server's: a later one replaces the earlier
list = stage(list, { kind: 'home', label: 'Home networks', value: 'Off', net: { lan_devices: ['br-lan', 'guest'], auto_lan: false } });
expect(stagedOf(list, 'home')?.net).toEqual({ lan_devices: ['br-lan', 'guest'], auto_lan: false });
list = stage(list, { kind: 'home', label: 'Home networks', value: 'On', net: { lan_devices: ['br-lan', 'guest'] } });
expect(stagedOf(list, 'home')?.net).toEqual({ lan_devices: ['br-lan', 'guest'] });
expect(list).toHaveLength(2);
});
it('holds who sees whom as one whichever way it changes, and what reaches no device counts none', () => {
let list = stage([], { kind: 'mesh', label: 'Devices see each other: Everyone', value: 'Everyone', values: { mesh: 'all' } });
list = stage(list, { kind: 'rule', label: 'Devices see each other: In circles', value: 'In circles', values: { mesh: 'circles' } });
expect(list).toHaveLength(1);
expect(stagedOf(list, 'mesh')?.kind).toBe('rule');
expect(refetchOf('rule', 's1', people)).toBe(0);
expect(refetchOf('route', 's1', people)).toBe(0);
expect(refetchOf('wan', 's1', people)).toBe(0);
const route: Staged = {
kind: 'route',
label: 'Internet traffic: Like a home device',
value: 'Like a home device',
net: { lan_like: true },
};
expect(summary([route], people, 's1')).toMatchObject({ changes: 1, breaks: false, refetch: { n: 0, fresh: 0 } });
expect(summary([route, mtu], people, 's1')).toMatchObject({ changes: 2, refetch: { n: 5 } });
});
it('makes one server_interfaces patch of every staged part of that choice', () => {
expect(netPatch([mtu])).toBeNull();
expect(
netPatch([
{ kind: 'route', label: '', value: '', net: { lan_like: true } },
{ kind: 'wan', label: '', value: '', net: { auto_wan: false, wan_device: 'pppoe-wan' } },
{ kind: 'home', label: '', value: '', net: { lan_devices: ['br-lan'] } },
mtu,
]),
).toEqual({ lan_like: true, auto_wan: false, wan_device: 'pppoe-wan', lan_devices: ['br-lan'] });
});
it('makes one server_update patch of every staged field', () => {
expect(fieldsPatch([])).toBeNull();
expect(fieldsPatch([{ kind: 'disguise', label: '', value: '', preset: 'max' }])).toBeNull();
expect(fieldsPatch([mtu, port, dns, { kind: 'disguise', label: '', value: '', preset: 'max' }])).toEqual({
mtu: '1380',
port: '443',
dns: '1.1.1.1',
});
});
it('says what applying them means: how many devices, and whether they stop connecting', () => {
expect(summary([mtu], people, 's1')).toMatchObject({ changes: 1, breaks: false, refetch: { n: 5 } });
expect(summary([mtu, dns], people, 's1')).toMatchObject({ changes: 2, breaks: false, refetch: { n: 6, people: 4 } });
// a port change rewrites everyone's and cuts them off until they fetch
expect(summary([mtu, port], people, 's1')).toMatchObject({ changes: 2, breaks: true, refetch: { n: 6, paused: 1, fresh: 1 } });
expect(summary([], people, 's1')).toMatchObject({ changes: 0, breaks: false, refetch: { n: 0 } });
});
});
describe('lastChange', () => {
const e = (o: Partial<ServiceLogEntry>): ServiceLogEntry => ({
ts: NOW,
src: 'dawnline',
level: 'info',
msg: 'changed',
by: 'admin',
kind: 'server',
...o,
});
it('finds the newest change of this server, by id or by its old name', () => {
const log = [
e({ ts: NOW - 300, who: 'Home', note: 'DNS' }),
e({ ts: NOW - 100, who: 'Home', note: 'name' }),
e({ ts: NOW - 200, who: 'Renamed', sid: 's1', note: 'disguise: max' }),
e({ ts: NOW - 50, who: 'Home', sid: 's2', note: 'MTU' }),
e({ ts: NOW - 10, who: 'Home', msg: 'turned off' }),
];
expect(lastChange(log, server())).toEqual({ note: 'disguise: max', ts: NOW - 200 });
expect(lastChange([], server())).toBeNull();
});
});
describe('the path', () => {
const ck = (id: string, status: HealthCheck['status']): HealthCheck => ({ id, title: id, status, detail: '', fix: null });
it('puts each check on its stage', () => {
expect(stageOf('ep_s1', 's1')).toBe('entry');
expect(stageOf('reply_s1', 's1')).toBe('entry');
expect(stageOf('up_s1', 's1')).toBe('tunnel');
expect(stageOf('up_s_home', 's_home')).toBe('tunnel');
expect(stageOf('homenet_s1', 's1')).toBe('home');
expect(stageOf('home_s1', 's1')).toBe('internet');
expect(stageOf('awg', 's1')).toBe('disguise');
expect(stageOf('resolver', 's1')).toBe('home');
// another server's, and the router's own that are no stage
expect(stageOf('up_s2', 's1')).toBeNull();
expect(stageOf('portal', 's1')).toBeNull();
});
it('colours the stages by their checks and what the status says', () => {
const failed = stageChecks(
[ck('up_s1', 'ok'), ck('fw_s1', 'error'), ck('homenet_s1', 'warn'), ck('ep_s2', 'error'), ck('policy', 'skip')],
's1',
);
expect(failed.entry.map((c) => c.id)).toEqual(['fw_s1']);
expect(failed.internet).toEqual([]);
const st = { wan: '91.1.2.4', like_home: { active: false, error: 'no route' } };
expect(stageStates(st, server(), failed)).toEqual({
devices: 'ok',
disguise: 'ok',
entry: 'bad',
tunnel: 'ok',
internet: 'ok',
home: 'warn',
});
const down = stageStates(st, server({ up: false, endpoint: '91.1.2.3', lan_like: true }), stageChecks([], 's1'));
expect([down.tunnel, down.entry, down.internet]).toEqual(['bad', 'warn', 'warn']);
expect(Object.values(stageStates(st, server({ enabled: false }), failed)).every((s) => s === 'off')).toBe(true);
});
it('notices the public address left behind', () => {
expect(wanMoved({ wan: '91.1.2.4' }, server({ endpoint: '91.1.2.3' }))).toBe(true);
expect(wanMoved({ wan: '91.1.2.4' }, server({ endpoint: 'vpn.example.com' }))).toBe(false);
expect(wanMoved({ wan: null }, server({ endpoint: '91.1.2.3' }))).toBe(false);
});
});
describe('who reaches what', () => {
it('says it by kind of access', () => {
const people = [
person({ access: 'internet' }),
person({ id: 'l', access: 'lan', services: ['sv1'] }),
person({ id: 'b', access: 'both', home_nets: ['br-lan'] }),
person({ id: 'x', server: 's2', access: 'both' }),
];
const r = whoReaches(people, server({ lan_like: true, mesh: 'circles' }));
expect(r.map((x) => [x.access, x.people, x.internet, x.home, x.each])).toEqual([
['internet', 1, 'home', null, 'no'],
['lan', 1, 'own', ['services'], 'circle'],
['both', 1, 'home', ['some'], 'circle'],
]);
expect(homeAccess(person({ access: 'lan', services: ['sv1'] }))).toBe(false);
expect(homeAccess(person({ access: 'lan' }))).toBe(true);
});
});
describe('disguise parameters', () => {
it('groups them and writes them as configuration lines, the key left out', () => {
const o = { jc: '4', jmin: '40', jmax: '70', s1: '52', h1: '123', i1: '<b 0x85800001>' };
expect(paramCount(o, true)).toBe(7);
expect(paramGroups(o, true).map((g) => [g.title, g.items.length])).toEqual([
['Junk packets', 3],
['Padding', 1],
['Packet types', 1],
['Signatures', 1],
['Protection', 1],
]);
expect(paramsConf(o)).toBe('Jc = 4\nJmin = 40\nJmax = 70\nS1 = 52\nH1 = 123\nI1 = <b 0x85800001>');
});
});
describe('fixes', () => {
it('names a fix on its button', () => {
expect(fixLabel('netrestart')).toBe('Restart network');
expect(fixLabel('install:awg')).toBe('Install');
expect(fixLabel('weird')).toBe('Fix');
});
});
+149
View File
@@ -0,0 +1,149 @@
import { describe, expect, it } from 'vitest';
import type { LogEvent, Status } from '../src/shared/types';
import type { ServiceLogEntry } from '../src/admin/api';
import { byDay, sessions } from '../src/admin/events/sessions';
import { dayBefore, dayTitle, routerDay, routerTime } from '../src/admin/events/clock';
import { haystack, kindCounts, matchesKind, matchesQuery } from '../src/admin/events/find';
const ev = (ts: number, type: string, device?: string, extra: Partial<LogEvent> = {}): LogEvent => ({
ts,
type,
device,
person: 'p1',
...extra,
});
const sys = (ts: number, level: ServiceLogEntry['level'], msg = 'up'): ServiceLogEntry => ({ ts, src: 'awg', level, msg, who: 'Home' });
describe('sessions', () => {
it('folds a connect and its disconnect into one row, newest first', () => {
const rows = sessions([ev(100, 'connect', 'd1'), ev(200, 'disconnect', 'd1'), ev(150, 'paused')]);
expect(rows.map((r) => [r.ts, r.ev!.type, r.until])).toEqual([
[150, 'paused', undefined],
[100, 'connect', 200],
]);
});
it('keeps a session open while the device is online, and says nothing of its end when it is not', () => {
expect(sessions([ev(100, 'connect', 'd1')])[0].until).toBeNull();
expect('until' in sessions([ev(100, 'connect', 'd1')], [], () => false)[0]).toBe(false);
});
it('pairs each device with its own disconnect, in time order whatever the input order', () => {
const rows = sessions([ev(300, 'disconnect', 'd2'), ev(250, 'disconnect', 'd1'), ev(100, 'connect', 'd1'), ev(120, 'connect', 'd2')]);
expect(rows.map((r) => [r.ev!.device, r.ts, r.until])).toEqual([
['d2', 120, 300],
['d1', 100, 250],
]);
});
it('leaves a connect whose end was never logged as a plain event', () => {
const rows = sessions([ev(100, 'connect', 'd1'), ev(200, 'connect', 'd1'), ev(300, 'disconnect', 'd1')]);
expect(rows.map((r) => [r.ts, r.until])).toEqual([
[200, 300],
[100, undefined],
]);
expect('until' in rows[1]).toBe(false);
});
it('keeps a disconnect with no connect before it (the log was cut) as its own row', () => {
expect(sessions([ev(100, 'disconnect', 'd1')]).map((r) => r.ev!.type)).toEqual(['disconnect']);
});
it('puts the service log beside the events', () => {
const rows = sessions([ev(100, 'connect', 'd1')], [sys(150, 'down'), sys(50, 'info')]);
expect(rows.map((r) => r.ts)).toEqual([150, 100, 50]);
expect(rows[0].sys?.level).toBe('down');
});
});
describe('router clock', () => {
// 2026-11-08 21:30 UTC: the 9th already at +3 h.
const ts = Date.UTC(2026, 10, 8, 21, 30) / 1000;
it('reads days and times in the router time zone', () => {
expect(routerDay(ts, 180)).toBe('2026-11-09');
expect(routerTime(ts, 180)).toBe('00:30');
expect(routerDay(ts, 0)).toBe('2026-11-08');
expect(routerTime(ts, -300)).toBe('16:30');
});
it('groups rows by the day they began on', () => {
const rows = sessions([ev(ts - 3600, 'connect', 'd1'), ev(ts + 60, 'disconnect', 'd1'), ev(ts + 120, 'paused')]);
expect(byDay(rows, 180).map((d) => [d.day, d.items.length])).toEqual([
['2026-11-09', 1],
['2026-11-08', 1],
]);
});
it('names days', () => {
expect(dayBefore('2026-03-01')).toBe('2026-02-28');
expect(dayTitle('2026-11-09', '2026-11-09')).toBe('Today');
expect(dayTitle('2026-11-08', '2026-11-09')).toBe('Yesterday');
expect(dayTitle('2026-11-06', '2026-11-09')).toMatch(/6/);
expect(dayTitle('2025-12-31', '2026-01-02')).toMatch(/2025/);
});
});
describe('finding rows', () => {
const names = {
people: [{ id: 'p1', name: 'Dima', devices: [{ id: 'd1', name: 'Xiaomi 14' }] }],
} as unknown as Pick<Status, 'people'>;
it('counts and filters by kind', () => {
const rows = sessions([ev(1, 'connect', 'd1'), ev(2, 'paused'), ev(3, 'device_failing', 'd1')], [sys(4, 'error'), sys(5, 'info')]);
expect(kindCounts(rows)).toEqual({ all: 5, connections: 1, people: 1, system: 2, problems: 2 });
expect(rows.filter((r) => matchesKind(r, 'problems')).map((r) => r.ts)).toEqual([4, 3]);
});
it('finds a row by names now and then, its address, place and words', () => {
const row = sessions([ev(1, 'connect', 'd1', { detail: '91.203.14.7', where: 'Krasnodar · Rostelecom', pname: 'Dmitry' })])[0];
const hay = haystack(row, names, 'Xiaomi 14 · Dima online now');
for (const q of ['dima', 'XIAOMI', '91.203', 'krasnodar', 'dmitry', 'online now', 'dima xiaomi'])
expect(matchesQuery(hay, q)).toBe(true);
expect(matchesQuery(hay, 'lena')).toBe(false);
expect(matchesQuery(hay, ' ')).toBe(true);
const line = haystack(
sessions([], [{ ts: 1, src: 'awg', level: 'down', msg: 'stopped', who: 'Home', detail: 'wg0: no route' }])[0],
names,
);
expect(matchesQuery(line, 'home no route')).toBe(true);
});
});
describe('quick reconnects', () => {
const at = (m: number) => 1_000_000 + m * 60;
const ev = (type: string, m: number, where = 'Krasnodar · Rostelecom'): LogEvent => ({
ts: at(m),
type,
device: 'd1',
person: 'p1',
where,
});
it('folds a device back within 15 minutes from the same place into one session', () => {
const out = sessions([
ev('connect', 0),
ev('disconnect', 30),
ev('connect', 40),
ev('disconnect', 70),
ev('connect', 80),
ev('disconnect', 95),
]);
expect(out).toHaveLength(1);
expect(out[0].ts).toBe(at(0));
expect(out[0].until).toBe(at(95));
expect(out[0].rejoins).toBe(2);
});
it('keeps a session still open when the last return has no end', () => {
const out = sessions([ev('connect', 0), ev('disconnect', 30), ev('connect', 35)]);
expect(out).toHaveLength(1);
expect(out[0].until).toBeNull();
expect(out[0].rejoins).toBe(1);
});
it('starts a new session after a longer gap or from another place', () => {
expect(sessions([ev('connect', 0), ev('disconnect', 30), ev('connect', 60)])).toHaveLength(2);
expect(sessions([ev('connect', 0), ev('disconnect', 30), ev('connect', 35, 'Sochi · MTS')])).toHaveLength(2);
});
});
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from 'vitest';
import type { SettingsData, UpdatePolicy } from '../src/admin/api';
import { draftSections, settingsCount, stageSettings, withDraft } from '../src/admin/system/draft';
const upd = {
check: true,
interval: '1d',
auto: false,
mode: 'night',
time: '04:00',
targets: ['app'],
keep: true,
mirrors: false,
} as unknown as UpdatePolicy;
const set = (): SettingsData =>
({
settings: { portal_redirect: '', domain: '', home_dns_fallback: '', portal_enabled: '' },
effective: {
portal_enabled: true,
portal_port: 8443,
portal_host: 'vpn.example',
portal_alt: ['b.example'],
hostnames: true,
geo_enabled: false,
updates: upd,
},
services: [],
cert: null,
tcp_taken: [],
geo_cached: 0,
logs: {
policy: {
keep_days: 30,
max: 5000,
categories: ['connections', 'people', 'problems'],
persist: 'hourly',
usage_days: 90,
usage_months: 12,
},
},
}) as unknown as SettingsData;
describe('router-wide settings that wait', () => {
it('stages a value and lets go of one put back, whatever shape the router keeps it in', () => {
const s = set();
let d = stageSettings({}, s, { portal_port: '8444', geo_enabled: '1', log_keep_days: '7', update_auto: '1' });
expect(d).toEqual({ portal_port: '8444', geo_enabled: '1', log_keep_days: '7', update_auto: '1' });
expect(settingsCount(d)).toBe(4);
expect([...draftSections(d)].sort()).toEqual(['history', 'portal', 'updates']);
d = stageSettings(d, s, { portal_port: '8443', geo_enabled: '0', log_keep_days: '30', update_auto: '0' });
expect(d).toEqual({});
// a switch that is on by default (nothing stored) is not a change when turned on
expect(stageSettings({}, s, { portal_enabled: '1' })).toEqual({});
expect(stageSettings({}, s, { portal_enabled: '0' })).toEqual({ portal_enabled: '0' });
// the categories are a set, the portal's addresses a list whose first is the main one
expect(stageSettings({}, s, { log_category: ['problems', 'people', 'connections'] })).toEqual({});
expect(stageSettings({}, s, { portal_host: 'b.example', portal_alt: ['vpn.example'] })).toEqual({
portal_host: 'b.example',
portal_alt: ['vpn.example'],
});
expect(stageSettings({}, s, { portal_host: 'vpn.example', portal_alt: ['b.example'] })).toEqual({});
expect(stageSettings({}, s, { domain: 'home' })).toEqual({ domain: 'home' });
});
it('draws the router’s answer with what waits over it, each value where its section reads it', () => {
const s = set();
expect(withDraft(s, {})).toBe(s);
const p = withDraft(s, {
portal_port: '8444',
portal_enabled: '0',
portal_redirect: 'https://example.org',
log_category: ['problems'],
log_max: '1000',
update_auto: '1',
update_targets: ['app', 'packages'],
domain: 'home',
});
expect(p.effective).toMatchObject({ portal_port: 8444, portal_enabled: false });
expect(p.settings).toMatchObject({ portal_redirect: 'https://example.org', domain: 'home', portal_port: '8444' });
expect(p.logs.policy).toMatchObject({ categories: ['problems'], max: 1000, keep_days: 30 });
expect((p.effective.updates as UpdatePolicy).auto).toBe(true);
expect((p.effective.updates as UpdatePolicy).targets).toEqual(['app', 'packages']);
// the answer itself is not touched
expect(s.effective.portal_port).toBe(8443);
expect(s.logs.policy.categories).toHaveLength(3);
expect(upd.auto).toBe(false);
});
it('falls back to the updater’s own policy when the settings do not carry one', () => {
const s = set();
delete (s.effective as { updates?: unknown }).updates;
expect(stageSettings({}, s, { update_keep: '1' }, upd)).toEqual({});
expect(stageSettings({}, s, { update_keep: '0' }, upd)).toEqual({ update_keep: '0' });
expect((withDraft(s, { update_keep: '0' }, upd).effective.updates as UpdatePolicy).keep).toBe(false);
});
});
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest';
import { hostSelector, shadowCss, splitList } from '../build/shadow-css.ts';
const o = { rootClasses: ['kbd', 'own-tsel'] };
describe('shadow-css', () => {
it('turns the document root into the host', () => {
expect(shadowCss(':root{--bg:#000}html{touch-action:manipulation}body{margin:0}')).toBe(
':host{--bg:#000}:host{touch-action:manipulation}:host{margin:0}',
);
expect(shadowCss('body.locked{overflow:hidden}html[lang] p{x:1}')).toBe(':host(.locked){overflow:hidden}:host([lang]) p{x:1}');
expect(shadowCss('body.scrolled .edge-fade.top{opacity:1}')).toBe(':host(.scrolled) .edge-fade.top{opacity:1}');
});
it('leaves look-alikes and other selectors alone', () => {
expect(shadowCss('.acc-body{a:1}.page-body,.html{b:2}button{c:3}')).toBe('.acc-body{a:1}.page-body,.html{b:2}button{c:3}');
expect(shadowCss('*{box-sizing:border-box}::selection{color:red}')).toBe('*{box-sizing:border-box}::selection{color:red}');
});
it('moves the classes the page sets on <html> to the host', () => {
expect(shadowCss('.kbd :focus-visible{outline:2px}.kbd .mi:focus-visible{x:1}', o)).toBe(
':host(.kbd) :focus-visible{outline:2px}:host(.kbd) .mi:focus-visible{x:1}',
);
expect(shadowCss('.own-tsel .mono::selection{x:1}.kbdx a{y:2}', o)).toBe(':host(.own-tsel) .mono::selection{x:1}.kbdx a{y:2}');
});
it('follows the host theme instead of the system colour scheme', () => {
expect(shadowCss('@media (prefers-color-scheme: light){:root{--bg:#fff}.a,.b>i{c:1}}')).toBe(
':host([data-theme=light]){--bg:#fff}:host([data-theme=light]) .a,:host([data-theme=light]) .b>i{c:1}',
);
expect(shadowCss('@media(prefers-color-scheme:dark){html.kbd a{x:1}}', o)).toBe(':host([data-theme=dark].kbd) a{x:1}');
expect(shadowCss('@media (prefers-color-scheme: light){.kbd a{x:1}:host(.on) b{y:2}}', o)).toBe(
':host([data-theme=light].kbd) a{x:1}:host([data-theme=light].on) b{y:2}',
);
});
it('recurses into nesting at-rules and copies the rest', () => {
expect(shadowCss('@media (max-width:559px){:root{--g:8px}@media (prefers-color-scheme:light){.a{b:1}}}')).toBe(
'@media (max-width:559px){:host{--g:8px}:host([data-theme=light]) .a{b:1}}',
);
expect(shadowCss('@supports (x:y){html{a:b}}@container p (min-width:840px){.c{d:e}}')).toBe(
'@supports (x:y){:host{a:b}}@container p (min-width:840px){.c{d:e}}',
);
const kf = '@keyframes spin{from{transform:none}to{transform:rotate(1turn)}}';
expect(shadowCss(kf)).toBe(kf);
expect(shadowCss('@charset "UTF-8";html{a:b}')).toBe('@charset "UTF-8";:host{a:b}');
});
it('keeps strings and functions with commas and braces whole', () => {
expect(shadowCss('.a::before{content:"}{,"}body{b:1}')).toBe('.a::before{content:"}{,"}:host{b:1}');
expect(splitList(':is(.a,.b) i,[data-x="1,2"],.c')).toEqual([':is(.a,.b) i', '[data-x="1,2"]', '.c']);
expect(hostSelector(':root:not([data-x]) .bar')).toBe(':host(:not([data-x])) .bar');
});
it('refuses CSS with unbalanced braces', () => {
expect(() => shadowCss('.a{b:1')).toThrow(/unbalanced/);
});
});
+7
View File
@@ -36,6 +36,13 @@ describe('format', () => {
it('makes initials and slugs', () => {
expect(initials('myata')).toBe('MY');
expect(initials('Anna Maria Lee')).toBe('AL');
// an emoji is one sign, never half of one; a word that begins with a letter wins over it
expect(initials('🦊 Лис')).toBe('ЛИ');
expect(initials('🦊')).toBe('🦊');
expect(initials('👨‍👩‍👧 Family Chat')).toBe('FC');
expect(initials('Ю')).toBe('Ю');
expect(initials('a.b@example.com')).toBe('AB');
expect(initials(' ')).toBe('?');
expect(slugify('Ünïcode Name!')).toBe('unicode-name');
});
it('describes quotas', () => {
+28
View File
@@ -0,0 +1,28 @@
import fs from 'node:fs';
import { describe, expect, it } from 'vitest';
import { joinStatus, unkey } from '../src/admin/state/join';
const DATA = new URL('../../backend/bridge/testdata/', import.meta.url);
const read = (name: string) => JSON.parse(fs.readFileSync(new URL(name, DATA), 'utf8'));
describe('a status from the topics', () => {
it('joins what the bridge split back into the very answer', () => {
// the Go side holds Split(status.json) to topics.json (backend/bridge/topics_test.go)
const topics = read('topics.json');
expect(joinStatus((name) => topics[name])).toEqual(read('status.json'));
});
it('waits for every topic', () => {
const topics = read('topics.json');
expect(joinStatus((name) => (name === 'people' ? undefined : topics[name]))).toBeNull();
});
it('reads keyed lists in their order, nulls, and leaves the rest', () => {
expect(unkey({ order: ['b', 'a', 'gone'], items: { a: { id: 'a', link: { $null: true } }, b: { id: 'b', spark: [1, 2] } } })).toEqual([
{ id: 'b', spark: [1, 2] },
{ id: 'a', link: null },
]);
// an object that only looks like one is left alone
expect(unkey({ order: 'asc', items: 3 })).toEqual({ order: 'asc', items: 3 });
});
});
+269
View File
@@ -0,0 +1,269 @@
import { describe, expect, it } from 'vitest';
import { checkChoice, checkValues, installChoice, installValues, nextCheck, autoInstalls } from '../src/admin/updater/policy';
import { addPhase, phaseSteps } from '../src/admin/updater/jobs';
import { routerDate, whenAt, zoneLabel } from '../src/admin/events/clock';
import {
certDays,
certPart,
certSoon,
defaultsWord,
fallbackRefetch,
historyWord,
isIp,
linkBase,
portalHealth,
portalState,
portalWord,
reasonLabel,
shortPoint,
storage,
updatesHealth,
updatesTone,
updatesWord,
type PortalFacts,
} from '../src/admin/system/model';
import type { LogsInfo, UpdatesStatus } from '../src/admin/api';
import type { HealthCheck, Person } from '../src/shared/types';
const NOW = Date.UTC(2026, 10, 8, 9, 40) / 1000;
describe('automatic updates as choices', () => {
it('reads and saves the Check row', () => {
expect(checkChoice({ check: false, interval: '1d' })).toBe('off');
expect(checkChoice({ check: true, interval: '12h' })).toBe('12h');
expect(checkValues('off')).toEqual({ update_check: '0' });
expect(checkValues('7d')).toEqual({ update_check: '1', update_interval: '7d' });
});
it('reads and saves the Install row', () => {
expect(installChoice({ auto: false, mode: 'scheduled' })).toBe('off');
expect(installChoice({ auto: true, mode: 'immediate' })).toBe('immediate');
expect(installValues('off')).toEqual({ update_auto: '0' });
expect(installValues('scheduled')).toEqual({ update_auto: '1', update_mode: 'scheduled' });
});
it('knows the next check and what installs on its own', () => {
expect(nextCheck({ check: true, interval: '6h' }, 1000)).toBe(1000 + 6 * 3600);
expect(nextCheck({ check: false, interval: '6h' }, 1000)).toBe(0);
expect(nextCheck({ check: true, interval: '1d' }, undefined)).toBe(0);
expect(autoInstalls({ auto: true, targets: ['app', 'packages'] }, 'app')).toBe(true);
expect(autoInstalls({ auto: true, targets: ['packages'] }, 'amneziawg')).toBe(false);
expect(autoInstalls({ auto: false, targets: ['app'] }, 'app')).toBe(false);
});
});
describe('a job as steps', () => {
it('adds each new phase once and leaves out the end', () => {
let seen: string[] = [];
seen = addPhase(seen, 'Downloading', 'Finished');
expect(addPhase(seen, 'Downloading', 'Finished')).toBe(seen);
seen = addPhase(seen, 'Installing', 'Finished');
expect(addPhase(seen, 'Finished', 'Finished')).toBe(seen);
expect(addPhase(seen, '', 'Finished')).toBe(seen);
expect(seen).toEqual(['Downloading', 'Installing']);
});
it('marks the last step by how the job stands', () => {
// under way is where the job is, not a warning
expect(phaseSteps(['a', 'b'], 'running').map((s) => s.state)).toEqual(['ok', 'run']);
expect(phaseSteps(['a', 'b'], 'done').map((s) => s.state)).toEqual(['ok', 'ok']);
expect(phaseSteps(['a', 'b'], 'failed').map((s) => s.state)).toEqual(['ok', 'bad']);
});
});
describe('the router clock', () => {
it('says when, in the router’s time', () => {
// 09:40 UTC is 12:40 at UTC+3
expect(whenAt(NOW - 600, NOW, 180)).toBe('today at 12:30');
expect(whenAt(NOW - 86400, NOW, 180)).toBe('yesterday at 12:40');
expect(whenAt(NOW - 3 * 86400, NOW, 180)).toMatch(/at 12:40$/);
expect(routerDate(NOW, 180)).toMatch(/12:40$/);
});
it('names the zone', () => {
expect(zoneLabel(180)).toBe('UTC+3');
expect(zoneLabel(330)).toBe('UTC+5:30');
expect(zoneLabel(-240)).toBe('UTC−4');
expect(zoneLabel(0)).toBe('UTC');
});
});
describe('the router sections’ words', () => {
it('names why a backup was made', () => {
expect(reasonLabel('auto')).toBe('Nightly');
expect(reasonLabel('pre-remove')).toBe('Before removing Dawnline');
expect(reasonLabel('later-kind')).toBe('later-kind');
});
it('counts the devices a fallback DNS change rewrites', () => {
const p = (access: Person['access'], dns: Person['dns_mode'], devs: Partial<Person['devices'][number]>[]) =>
({
access,
dns_mode: dns,
devices: devs.map((d) => ({ disabled: false, handshake: 0, config_issued: 0, ...d })),
}) as unknown as Person;
const people = [
p('lan', 'home', [{ handshake: 1 }, { config_issued: 1 }, {}, { handshake: 1, disabled: true }]),
p('lan', 'device', [{ handshake: 1 }]),
p('both', 'home', [{ handshake: 1 }]),
];
expect(fallbackRefetch({ people })).toBe(2);
});
it('shortens a release note’s point', () => {
expect(shortPoint('Portal: **faster** sign-in; keys stay')).toBe('Portal: faster sign-in');
expect(shortPoint('Short one')).toBe('Short one');
expect(shortPoint('x '.repeat(60)).endsWith('…')).toBe(true);
});
it('builds a link’s base on an address', () => {
expect(linkBase('vpn.example.com', 8443)).toBe('https://vpn.example.com:8443/');
expect(linkBase('vpn.example.com', 443)).toBe('https://vpn.example.com/');
expect(linkBase('91.203.14.7', 8443)).toBe('http://91.203.14.7:8444/');
expect(linkBase('91.203.14.7', 79)).toBe('http://91.203.14.7/');
});
it('counts the certificate’s days', () => {
expect(certDays(null, NOW)).toBeNull();
expect(certDays({ self_signed: true, expires: '2026-12-01' }, NOW)).toBeNull();
expect(certDays({ self_signed: false, expires: '2026-11-17T09:40:00Z' }, NOW)).toBe(9);
});
});
const check = (id: string, status: HealthCheck['status'], fix: string | null = null, problem?: string): HealthCheck => ({
id,
title: id,
status,
detail: '',
fix,
problem: problem ?? null,
});
describe('a certificate’s term', () => {
it('is soon under 21 days, and never without an end', () => {
expect(certSoon(20)).toBe(true);
expect(certSoon(21)).toBe(false);
expect(certSoon(-3)).toBe(true);
expect(certSoon(null)).toBe(false);
});
it('measures what is left of 90 days', () => {
expect(certPart(9)).toBeCloseTo(0.1);
expect(certPart(365)).toBe(1);
expect(certPart(-2)).toBe(0);
expect(certPart(null)).toBeNull();
});
it('tells an address from a name', () => {
expect(isIp('91.203.14.7')).toBe(true);
expect(isIp('vpn.example.com')).toBe(false);
expect(isIp('2001:db8::1')).toBe(false);
});
});
describe('the checks a section shows', () => {
const checks = [
check('awg', 'error', 'updates'),
check('portal', 'ok'),
check('portal_dns', 'warn'),
check('portal_reply', 'skip'),
check('cert', 'error'),
check('clock', 'error', 'restart'),
check('tunnel_s1', 'warn'),
];
it('takes the portal’s by their ids', () => {
const p = portalHealth(checks);
expect(p.failed.map((k) => k.id)).toEqual(['portal_dns', 'cert']);
expect(p.passed).toBe(1);
expect(portalHealth([])).toEqual({ failed: [], passed: 0 });
});
it('takes those fixed in Updates, without the fix that would lead to itself', () => {
expect(updatesHealth(checks)).toEqual([{ ...checks[0], fix: null }]);
expect(updatesHealth([check('awg', 'ok', 'updates')])).toEqual([]);
});
});
describe('what is stored against its limits', () => {
const logs = (o: Partial<LogsInfo> = {}, policy: Partial<LogsInfo['policy']> = {}): LogsInfo => ({
policy: { keep_days: 30, max: 5000, categories: ['connections'], persist: 'hourly', usage_days: 365, usage_months: 24, ...policy },
events: 1284,
oldest: NOW - 29 * 86400 - 3600,
by_category: { connections: 1012, people: 214, problems: 58 },
log_ram: 1000,
log_flash: 160_000,
usage_flash: 40_000,
usage_since: '2026-01-04',
usage_days: 309,
geo_flash: 6000,
...o,
});
it('measures the log and the traffic history', () => {
const s = storage(logs(), NOW);
expect(s.age).toBe(29);
expect(s.events).toBeCloseTo(1284 / 5000);
expect(s.depth).toBeCloseTo(29 / 30);
expect(s.usage).toBeCloseTo(309 / 365);
expect(s.flash).toBe(206_000);
});
it('has no measure without a limit, and no age in an empty log', () => {
expect(storage(logs({}, { keep_days: 0 }), NOW).depth).toBeNull();
const empty = storage(logs({ events: 0, oldest: 0 }), NOW);
expect(empty.age).toBe(0);
expect(empty.depth).toBe(0);
});
});
describe('a section on the rail', () => {
const upd = (o: Partial<UpdatesStatus> = {}): UpdatesStatus => ({ version: '0.18.0', check: null, job: null, ...o }) as UpdatesStatus;
const app = (latest: string) => ({ time: NOW, components: { app: { update: true, latest } } });
const job = (action: string) => ({ state: 'running', action }) as UpdatesStatus['job'];
it('says how Updates stand', () => {
expect(updatesWord(upd())).toEqual({ text: 'Dawnline 0.18.0' });
expect(updatesWord(upd({ check: app('0.19.0') }))).toEqual({ text: '0.19.0 is available' });
expect(updatesWord(upd({ check: app('0.19.0'), needs: { awg: ['kmod-amneziawg'], https: [], acme: [], home: [] } }))).toEqual({
text: 'AmneziaWG not installed',
tone: 'warn',
});
expect(updatesWord(upd({ job: job('install') })).text).toBe('an update is running');
expect(updatesWord(upd({ job: job('check') })).text).toBe('a check is running');
});
it('names a check that is fixed in Updates before anything but a job', () => {
const awg = { ...check('awg', 'error', null, 'AmneziaWG’s kernel module doesn’t load') };
expect(updatesWord(upd({ check: app('0.19.0') }), [awg])).toEqual({ text: 'AmneziaWG’s kernel module doesn’t load', tone: 'bad' });
expect(updatesWord(upd({ job: job('install') }), [awg]).text).toBe('an update is running');
expect(updatesTone(upd({ check: app('0.19.0') }), [awg])).toBe('red');
expect(updatesTone(upd(), [{ ...awg, status: 'warn' }])).toBe('orange');
});
it('tones Updates’ glass', () => {
expect(updatesTone(upd())).toBe('grey');
expect(updatesTone(upd({ check: app('0.19.0') }))).toBe('blue');
expect(updatesTone(upd({ job: job('check') }))).toBe('blue');
expect(updatesTone(upd({ check: app('0.19.0'), needs: { awg: ['awg'], https: [], acme: [], home: [] } }))).toBe('orange');
});
const portal = (o: Partial<PortalFacts> = {}): PortalFacts => ({
enabled: true,
host: 'vpn.example.com',
blocked: false,
days: 60,
failed: [],
...o,
});
it('says how the portal stands, the most pressing first', () => {
expect(portalWord(portal())).toEqual({ text: 'vpn.example.com' });
expect(portalWord(portal({ host: '' }))).toEqual({ text: 'on' });
expect(portalWord(portal({ enabled: false, blocked: true, days: 3 }))).toEqual({ text: 'off', tone: 'off' });
expect(portalWord(portal({ blocked: true, days: 3 }))).toEqual({ text: 'can’t start', tone: 'bad' });
expect(portalWord(portal({ days: 9 }))).toEqual({ text: 'certificate: 9 d', tone: 'warn' });
expect(portalWord(portal({ days: -2 })).text).toBe('certificate: 0 d');
});
it('names what did not pass, and counts several', () => {
const dns = check('portal_dns', 'warn', null, 'Portal address doesn’t point here');
const down = check('portal', 'error', 'restart', 'Personal portal isn’t working');
const cert = check('cert', 'warn', null, 'Portal certificate needs attention');
expect(portalWord(portal({ failed: [dns] }))).toEqual({ text: 'Portal address doesn’t point here', tone: 'warn' });
expect(portalWord(portal({ failed: [dns, down] }))).toEqual({ text: '2 problems', tone: 'bad' });
expect(portalWord(portal({ failed: [dns, cert] }))).toEqual({ text: '2 warnings', tone: 'warn' });
// the certificate's own check gives way to its days; without days (self-signed) it is named
expect(portalState(portal({ failed: [cert], days: 9 }))).toEqual({ state: 'cert', tone: 'warn' });
expect(portalState(portal({ failed: [cert, dns], days: 9 })).state).toBe('failed');
expect(portalWord(portal({ failed: [cert], days: null })).text).toBe('Portal certificate needs attention');
expect(portalState(portal())).toEqual({ state: 'fine', tone: '' });
});
it('says what new people start with and how long the log is kept', () => {
expect(defaultsWord(1).text).toBe('up to 1 device');
expect(defaultsWord(3).text).toBe('up to 3 devices');
expect(historyWord(30).text).toBe('log: 30 d');
expect(historyWord(0).text).toBe('log: no limit');
});
});
+200
View File
@@ -0,0 +1,200 @@
import { describe, expect, it } from 'vitest';
import { linkTimeline, summary, timeIn, type TimelineInput } from '../src/admin/events/timeline';
import { briefDiagnosis, deviceLine, diagnose } from '../src/admin/people/diagnosis';
import type { Device, LogEvent, Person, Server } from '../src/shared/types';
// The router at 2026-11-08 12:40 UTC+3 (the stand-in's moment), its offset in minutes.
const NOW = Date.UTC(2026, 10, 8, 9, 40) / 1000;
const TZ = 180;
const H = 3600;
const D = 86400;
/** Router time `hh:mm`, `back` days ago. */
const at = (back: number, hh: number, mm = 0) => Date.UTC(2026, 10, 8 - back, hh - 3, mm) / 1000;
const dev = (o: Partial<Device> = {}): Device => ({
id: 'd1',
name: 'Phone',
kind: 'phone',
address: '10.8.0.2',
disabled: false,
created: NOW - 40 * D,
created_by: 'admin',
online: false,
handshake: 0,
endpoint: '',
active: false,
month: [0, 0],
total: [0, 0],
spark: [],
hostname: 'phone',
browser_key: false,
config_stale: false,
config_issued: 0,
lan_bypass: true,
mtu: 0,
keepalive: null,
mtu_used: 1280,
keepalive_used: 25,
link: null,
setup: null,
...o,
});
const person = (o: Partial<Person> = {}): Person =>
({
id: 'p1',
name: 'Lena',
server: 's1',
access: 'internet',
device_limit: 3,
expires: '',
quota_gb: 0,
quota_period: 'month',
quota_used: 0,
quota_limit: 0,
bonus_gb: 0,
dns_mode: 'device',
paused: false,
state: 'active',
month: [0, 0],
total: [0, 0],
online: 0,
last_seen: 0,
devices: [],
...o,
}) as Person;
const server = { id: 's1', name: 'Home', enabled: true, reached: NOW - 60 } as Server;
const ev = (ts: number, type: string, o: Partial<LogEvent> = {}): LogEvent => ({ ts, type, person: 'p1', device: 'd1', ...o });
const input = (d: Device, p: Person, events: LogEvent[]): TimelineInput => ({ device: d, person: p, server, events, now: NOW, tz: TZ });
describe('linkTimeline', () => {
it('makes a run of each session, the open one up to now while online', () => {
const d = dev({ online: true, handshake: NOW - 30 });
const t = linkTimeline(
input(d, person(), [
ev(at(1, 9), 'connect', { where: 'Krasnodar · PJSC Rostelecom' }),
ev(at(1, 13), 'disconnect'),
ev(at(0, 7, 5), 'connect', { where: 'Sochi · MTS' }),
]),
);
expect(t.runs).toEqual([
{ a: at(1, 9), b: at(1, 13), s: 'ok', where: 'Krasnodar · Rostelecom' },
{ a: at(0, 7, 5), b: NOW, s: 'ok', where: 'Sochi · MTS' },
]);
expect(timeIn(t.runs, '24h', NOW)).toBe(NOW - at(0, 7, 5) + (at(1, 13) - NOW + D));
});
it('marks a failing link from device_failing until device_recovered, connected or not', () => {
const d = dev({ handshake: at(2, 12) });
const t = linkTimeline(
input(d, person(), [
ev(at(2, 10), 'connect'),
ev(at(2, 12), 'disconnect'),
ev(at(1, 8), 'device_failing', { detail: 'trying' }),
ev(at(1, 9), 'device_recovered'),
]),
);
expect(t.runs.map((r) => [r.a, r.b, r.s])).toEqual([
[at(2, 10), at(2, 12), 'ok'],
[at(1, 8), at(1, 9), 'warn'],
]);
});
it('keeps a failure open to now while the link still fails', () => {
const d = dev({ handshake: at(4, 16), link: { state: 'trying', since: at(0, 8, 40) } });
const t = linkTimeline(input(d, person(), [ev(at(0, 8, 40), 'device_failing', { detail: 'trying' })]));
expect(t.runs).toEqual([{ a: at(0, 8, 40), b: NOW, s: 'warn', where: '' }]);
});
it('colours connected time past the limit', () => {
const d = dev({ online: true, handshake: NOW });
const t = linkTimeline(
input(d, person({ state: 'quota' }), [ev(at(0, 10), 'connect'), ev(at(0, 11), 'quota_reached', { device: undefined })]),
);
expect(t.runs.map((r) => [r.a, r.b, r.s])).toEqual([
[at(0, 10), at(0, 11), 'ok'],
[at(0, 11), NOW, 'bad'],
]);
});
it('ticks where its settings, keys, its person or its server changed', () => {
const t = linkTimeline({
...input(dev(), person(), [
ev(at(3, 9), 'device_changed', { detail: 'mtu=1400', by: 'admin' }),
ev(at(2, 9), 'person_changed', { device: undefined, detail: 'expires', by: 'admin' }),
ev(at(40, 9), 'device_keys'),
]),
system: [
{ ts: at(1, 18, 20), src: 'dawnline', level: 'info', msg: 'changed', by: 'admin', kind: 'server', who: 'Home', note: 'dns' },
{ ts: at(1, 18, 30), src: 'dawnline', level: 'info', msg: 'changed', by: 'admin', kind: 'server', who: 'Other' },
// renamed since: its id says it is this server; another server once named Home is not
{ ts: at(1, 19), src: 'awg', level: 'info', msg: 'changed', by: 'admin', kind: 'server', who: 'Old name', sid: 's1' },
{ ts: at(1, 20), src: 'awg', level: 'info', msg: 'changed', by: 'admin', kind: 'server', who: 'Home', sid: 's2' },
] as TimelineInput['system'],
});
expect(t.ticks.map((k) => k.t)).toEqual([at(3, 9), at(2, 9), at(1, 18, 20), at(1, 19)]);
});
});
describe('summary', () => {
const day = (d: string) => d.slice(5);
it('says since when it is online, and how the period went', () => {
const d = dev({ online: true, handshake: NOW });
const i = input(d, person(), [ev(at(0, 7, 5), 'connect')]);
const s = summary(linkTimeline(i), i, '7d', day);
expect(s).toEqual({ value: 'Online since 07:05', tone: 'ok', sub: 'online 6 hours in the last 7 days · no failures' });
});
it('says a failing link in its own words, a day back with its date', () => {
const d = dev({ handshake: at(4, 16), link: { state: 'trying', since: at(1, 8, 40) } });
const i = input(d, person(), [ev(at(1, 8, 40), 'device_failing', { detail: 'trying' })]);
const s = summary(linkTimeline(i), i, '7d', day);
expect(s.value).toBe('Unable to complete the handshake since 11-07 08:40');
expect(s.tone).toBe('warn');
});
it('says it never connected, or how long it is offline', () => {
const none = input(dev(), person(), []);
expect(summary(linkTimeline(none), none, '7d', day).value).toBe('It has not connected yet');
const off = input(dev({ handshake: NOW - 3 * H }), person(), []);
expect(summary(linkTimeline(off), off, '7d', day).tone).toBe('');
});
});
describe('diagnosis', () => {
const c = { now: NOW, today: '2026-11-08', tz: TZ };
it('holds all along for a device that works: the brief one says nothing', () => {
const d = dev({ online: true, handshake: NOW - 30 });
const steps = diagnose(d, person(), server, c);
expect(steps.every((s) => s.state === 'ok')).toBe(true);
expect(briefDiagnosis(steps)).toEqual([]);
expect(deviceLine(d, person(), c)).toEqual({ text: 'Online', tone: 'ok' });
});
it('stops at the first break, with its fix; what follows waits', () => {
const d = dev({ handshake: NOW - D, link: { state: 'trying', since: at(0, 8, 40) } });
const steps = diagnose(d, person(), server, c);
expect(steps.map((s) => s.state)).toEqual(['ok', 'ok', 'ok', 'bad', 'wait']);
expect(steps[3].fix).toEqual(['tell']);
expect(steps[3].line).toContain('08:40');
const brief = briefDiagnosis(steps);
expect(brief.map((s) => [s.title, s.state])).toEqual([
['Access, server and device', 'ok'],
['Connection', 'bad'],
['Traffic', 'wait'],
]);
});
it('puts the person and the server before the device', () => {
expect(diagnose(dev({ disabled: true }), person({ state: 'paused' }), server, c)[0].fix).toEqual(['resume']);
const off = diagnose(dev(), person(), { ...server, enabled: false }, c);
expect(off.map((s) => s.state)).toEqual(['ok', 'bad', 'wait', 'wait', 'wait']);
expect(off[1].fix).toEqual(['server']);
expect(diagnose(dev(), person(), undefined, c)[1].fix).toEqual(['person']);
});
it('asks for the set-up when it never connected or holds an old configuration', () => {
expect(diagnose(dev(), person(), server, c)[3].fix).toEqual(['show']);
expect(diagnose(dev({ config_stale: true, handshake: NOW - H }), person(), server, c)[2].fix).toEqual(['show']);
expect(deviceLine(dev(), person(), c).text).toBe('Not set up yet');
});
});
+52 -8
View File
@@ -1,6 +1,6 @@
import { beforeAll, describe, expect, it } from 'vitest';
import { El, installFakeDom } from './fakedom';
import { checkVerdict, isOurJob, jobComponent, verText } from '../src/admin/updater/jobs';
import { checkVerdict, isOurJob, jobComponent, jobIcon, jobTitle, verText } from '../src/admin/updater/jobs';
import { forRouter, markdown, safeHref } from '../src/admin/updater/markdown';
import type { UpdatesStatus } from '../src/admin/api';
@@ -31,17 +31,61 @@ describe('jobs', () => {
// Once the id is known, only that one.
expect(isOurJob({ id: 'other', state: 'running', started: 1001 }, 'new', 'old', since)).toBe(false);
});
it('sums up a check', () => {
it('sums up a check as a row a component', () => {
const st = (components: Record<string, unknown>) => ({ check: { time: 1, components } }) as unknown as UpdatesStatus;
// one component with an update: its versions, and the version on offer for the sheet's own button
expect(checkVerdict(st({ app: { update: true, installed: '0.3.0', latest: '0.3.1' } }), 'app')).toEqual({
tone: 'acc',
text: 'Update available: Dawnline 0.3.1',
tone: 'new',
title: 'There is an update',
rows: [{ icon: 'dawnline', name: 'Dawnline', tone: 'new', line: '0.3.0 → 0.3.1', mono: true }],
update: '0.3.1',
});
expect(checkVerdict(st({ app: {}, amneziawg: {}, packages: { updates: 2 } }), 'all').text).toBe('Update available: 2 system packages');
expect(checkVerdict(st({ app: { error: 'GitHub is unreachable' } }), 'app')).toEqual({ tone: 'warn', text: 'GitHub is unreachable' });
expect(checkVerdict(st({ app: { status: 'dev', latest: '0.3.0' } }), 'app').text).toContain('newer than the release');
expect(checkVerdict(st({ app: {}, amneziawg: {}, packages: {} }), 'all')).toEqual({ tone: 'ok', text: 'Everything is up to date' });
// all of them: a row each, the title counts what has an update, and no single version is on offer
const all = checkVerdict(
st({ app: { installed: '0.3.1' }, amneziawg: { update: true, installed: '1.0', latest: '1.1' }, packages: { updates: 2 } }),
'all',
);
expect(all.tone).toBe('new');
expect(all.title).toBe('There are updates');
expect(all.update).toBeUndefined();
expect(all.rows.map((r) => [r.icon, r.tone, r.line])).toEqual([
['dawnline', 'ok', '0.3.1'],
['amneziawg', 'new', '1.0 → 1.1'],
['openwrt', 'new', '2 updates'],
]);
// a check that failed is the worst of it, whatever the others found
const failed = checkVerdict(
st({ app: { error: 'GitHub is unreachable' }, amneziawg: { update: true, installed: '1.0', latest: '1.1' } }),
'all',
);
expect(failed.tone).toBe('bad');
expect(failed.title).toBe('Not everything was checked');
expect(failed.rows[0]).toMatchObject({ tone: 'bad', line: 'GitHub is unreachable' });
expect(checkVerdict(st({ app: { error: 'GitHub is unreachable' } }), 'app').title).toBe('The check failed');
expect(checkVerdict(st({ app: { status: 'dev', installed: '0.4.0', latest: '0.3.0' } }), 'app').rows[0].line).toContain(
'Newer than the release',
);
expect(checkVerdict(st({ amneziawg: {} }), 'amneziawg').rows[0]).toMatchObject({ tone: 'quiet', line: 'Not installed' });
expect(checkVerdict(st({ app: { installed: '1' }, amneziawg: { installed: '2' }, packages: {} }), 'all')).toMatchObject({
tone: 'ok',
title: 'Everything is up to date',
});
expect(checkVerdict(st({ app: { installed: '1' } }), 'app').title).toBe('Latest version is installed');
});
it('draws a job by its component', () => {
expect(jobIcon('app')).toBe('dawnline');
expect(jobIcon('amneziawg')).toBe('amneziawg');
expect(jobIcon('pkgs')).toBe('openwrt');
expect(jobIcon('all')).toBe('update');
});
it('titles a job found running', () => {
expect(jobTitle({ action: 'check', component: 'all' })).toBe('Checking all components');
expect(jobTitle({ action: 'check', component: 'amneziawg' })).toBe('Checking AmneziaWG');
expect(jobTitle({ action: 'update', component: 'app@v0.3.1' })).toBe('Updating Dawnline');
expect(jobTitle({ action: 'update', component: 'app:nolang' })).toBe('Removing the Russian translation');
expect(jobTitle({ action: 'update', component: 'app:lang:ru' })).toBe('Adding the Russian translation');
expect(jobTitle({ action: 'update', component: 'amneziawg:slava:ru' })).toBe('Updating AmneziaWG');
expect(jobTitle({ action: 'update', component: 'pkgs:ip-full' })).toBe('Updating system packages');
});
});
+89
View File
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest';
import { pageView, type Page } from '../src/admin/shell/view';
/** A page that, like the real ones, keeps what it drew in its own fields. */
class Counting implements Page<number> {
static made = 0;
drawn = 0;
constructor() {
Counting.made++;
}
load() {
return Promise.resolve(Counting.made);
}
render() {
this.drawn++;
return {} as HTMLElement;
}
}
const view = () =>
pageView(
() => new Counting(),
() => null,
(page) => {
page.render(0);
return (page as Counting).drawn;
},
() => Promise.resolve('css'),
);
describe('pageView', () => {
it('gives every visit a page of its own (LuCI shares one load and render between visits)', async () => {
Counting.made = 0;
const v = view();
// first visit
expect(v.render(await v.load())).toBe(1);
// back to the same view: a new page, drawn once, not the old one drawn into again
expect(v.render(await v.load())).toBe(1);
expect(Counting.made).toBe(2);
});
it('never waits for the router: a page that does is handed over still waiting, to be drawn in its waiting state', async () => {
let answer: (n: number) => void = () => undefined;
const slow: Page<number> = { load: () => new Promise((done) => (answer = done)), render: () => ({}) as HTMLElement };
const v = pageView(
() => slow,
() => null,
(_page, got) => got,
() => Promise.resolve(''),
);
const got = await v.load();
expect('pending' in got).toBe(true);
answer(7);
expect('pending' in got && (await got.pending)).toBe(7);
// one that answers at once (it draws itself from a sample) is rendered from its answer
const fast = pageView(
() => new Counting(),
() => null,
(_page, g) => g,
() => Promise.resolve(''),
);
expect('data' in (await fast.load())).toBe(true);
// a refusal is the waiting page's to tell, not an error of the load
const failing = pageView(
(): Page<number> => ({
load: () => new Promise((_ok, no) => setTimeout(() => no(new Error('down')), 5)),
render: () => ({}) as HTMLElement,
}),
() => null,
(_page, g) => g,
() => Promise.resolve(''),
);
const f = await failing.load();
await expect('pending' in f ? f.pending : null).rejects.toThrow('down');
});
it('does not load a page that only sends the browser on', () => {
Counting.made = 0;
const away = new Promise<never>(() => {});
const v = pageView(
() => new Counting(),
() => away,
() => 0,
() => Promise.resolve(''),
);
expect(v.load()).toBe(away);
expect(Counting.made).toBe(0);
});
});
+1
View File
@@ -25,6 +25,7 @@ function dev(o: Partial<Device> = {}): Device {
hostname: 'pixel-9.user.lan',
browser_key: false,
config_stale: false,
config_issued: 0,
lan_bypass: false,
mtu: 0,
keepalive: null,