Files
dawnline/web/src/admin/pages/person/limits.ts
T
Aemeath 466ca6c7b0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
Dawnline 0.8.0
- Every field says what is wrong as you type, in the router's own words,
  and Save refuses what the router would: UDP port when editing a server,
  MTU, keep-alive, public address, DNS for devices, person name, device
  limit, end date and data limit, device names (the next free "Phone 2"
  is offered), home services, circles, portal title, redirect and other
  addresses, defaults, update time
- Cyrillic names give Latin ids, hostnames and file names; names are
  counted in characters, the rule names the characters it refuses; end
  dates must exist on the calendar; a mistyped extra portal address is
  refused instead of dropped
- The public address is checked on the router as it is typed: points at
  this router, at another address, behind Cloudflare, or the WAN is
  private or CGNAT; the wizard says so before the first step, never
  pre-fills a private WAN address and says where its suggestion came
  from; the Connection card says when the server was last reached from
  the internet; IPv6 names and literals work throughout
- A person can be moved to another server from their page; a server's
  tunnel network can be changed in the Danger zone (devices are
  renumbered and marked "Update config"); WAN and LAN zones come from the
  router's actual devices; when the public IPv4 changed, one click puts
  the new one in
- Over the data limit or outside the allowed hours the tunnel stays
  connected and the portal explains why nothing gets through, instead of
  a silent handshake failure; Health's "devices loaded" compares the
  peers themselves, not their count
- Portal: install links for this platform, two first steps on a first
  visit, the phone's back button closes a sheet, the file goes through
  the share sheet into the app, two QR codes (AmneziaVPN camera, AmneziaWG
  and WireGuard apps), the sheet notices the first connection
- Admin: Enter submits a dialog, arrow keys walk the menus, Find in People
  ("/" focuses it), a device of a paused, ended or over-limit person says
  so, "Keep access" past its end date is said on the Overview, Allowed
  hours enforce nothing until saved, the invite card shares the link
- Health warns when another package's policy routing (mwan3, pbr) sends
  tunnel traffic past the home-device path
- CLI: person ls, device ls, log with -n, --since, --level, --src and
  --json; exit code 2 for an unknown command and 1 when health finds an
  error; person rm asks for --yes when devices would go; devices added
  from the command line get their event and "issued" marker like the
  UI's
- Three disguises: Off, Balanced and Maximum. Standard and Strong (1.0-style
  junk only, which networks learned to spot) are no longer offered; a server
  still on one keeps running and its card says to switch. A new server gets
  the strongest disguise its router can run
- Portal: setting up a device is one sheet with two steps. Get the app
  (AmneziaVPN first; AmneziaWG, and WireGuard with the disguise off, behind
  "Another app") from the store of the device in hand, with the GitHub release
  where no store has it and the version the server needs said once; then add
  the connection (open in AmneziaVPN, copy the key, share or download the
  file). A device set up from another device gets its link to take there, as a
  QR code for a phone; a phone set up from a computer also gets the connection
  as a code, one code revealed at a time so the camera cannot read the wrong one
- Portal motion: the first visit comes in once (blocks in reading order,
  meters fill, the sun rises in the logo); a repaint glides cards to their
  new places and brings changed values into focus; sheets slide up on
  phones and can be pulled down, come into focus on a computer, follow
  their content's height and turn into the next sheet in place; tabs and
  segments slide, menus, tooltips and toasts grow out of what opened them,
  copy buttons turn into a check, buttons waiting for the router spin;
  with reduced motion only the fades remain
- Portal: while a device is set up, a card at the top shows the way from
  it to the router with a light running along it; on the first connection
  the way fills green, the steps fold away and the sheet closes by itself.
  The first connection is the first fresh handshake, so it is no longer
  missed while the watcher catches up (or after new keys), and the device's
  card goes on to Connected
- Portal: QR codes are light dots on a black card, fuller on dense keys,
  with "Show a light code" for scanners that read only dark on light (every
  code switches, the choice is kept); the link and code a set-up sheet
  hands to another device open that device's set-up there at once
- Portal: Remove and New keys ask in a small alert with the action's icon;
  the open one of two cards is not a button; device names are no longer
  repeated in every line of the set-up sheet; the code card lines up with
  the rest of its card (a class clash gave it the page's padding); text
  keeps the arrow cursor, store badges and link buttons are not underlined
2026-10-18 23:28:10 +03:00

333 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Person page: Access & limits — what they reach, then the tiles (devices,
// circle, end date, data, hours). Every choice applies at once.
import type { Person } from '../../../shared/types';
import { E } from '../../e';
import { notify } from '../../ui/toast';
import { seg } from '../../ui/controls';
import { button } from '../../ui/button';
import { cancelButton, closeModal, modal } from '../../ui/modal';
import { liveField } from '../../ui/layout';
import { quotaHelp } from '../../netcheck';
import { attachTip } from '../../ui/tooltip';
import { icon } from '../../../shared/icons';
import { ACCESS_LABEL, bytes, date, daysLeft, endsSoon, shiftDay } from '../../../shared/format';
import { resetUsageDialog } from '../../logs';
import { homeAccess } from '../../access';
import { endSettings } from './dialogs';
import { circleTile, devTile, dnsPicker, netsPicker, servicesPicker } from './pickers';
import type { PersonPage } from './index';
const ACCESS_TEXT: Record<Person['access'], string> = {
internet: 'Browse the internet through your router. No access to devices at home, and home cannot reach theirs.',
lan: 'Reach devices at home, and home reaches theirs. Internet stays on their own connection.',
both: 'Home devices and the internet, all through your router. Home reaches their devices too.',
};
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
function endTile(page: PersonPage): HTMLElement {
const p = page.p;
const today = page.today;
const left = daysLeft(p.expires, today);
const dateInput = E('input', {
type: 'date',
class: 'dl-date-hidden',
value: p.expires,
tabindex: '-1',
'aria-hidden': 'true',
}) as HTMLInputElement;
dateInput.addEventListener(
'change',
() => dateInput.value && page.patch({ expires: dateInput.value }, `Access until ${date(dateInput.value)}`),
);
// Extend from the current end, or from today when there is none or it has passed.
const extend = (step: 'week' | 'month' | 'year', n: number) => {
const next = shiftDay(p.expires && (left ?? -1) >= 0 ? p.expires : '', step, n, today);
void page.patch({ expires: next }, `Access until ${date(next)}`);
};
const ext = (
[
['week', 1, '+1 week'],
['month', 1, '+1 month'],
['month', 3, '+3 months'],
['year', 1, '+1 year'],
] as const
).map(([step, n, label]) => E('button', { type: 'button', class: 'dl-chipbtn', click: () => extend(step, n) }, label));
// The native date input stays hidden behind the chip and only opens its picker. It takes the
// focus first, so the page's background refresh leaves this tile (and the open picker) alone.
const pick = E('span', { class: 'dl-datechip' }, [
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: () => {
dateInput.focus({ preventScroll: true });
try {
dateInput.showPicker();
} catch {
/* focused is the best this browser offers */
}
},
},
[icon('calendar'), p.expires ? date(p.expires) : 'Date'],
),
dateInput,
]);
const action = { pause: 'pause access', notify: 'keep access', remove: 'remove their devices' }[p.expire_action];
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, [
E('span', {}, 'Access ends'),
p.expires
? E(
'span',
{ class: left != null && left < 0 ? 'dl-bad' : endsSoon(p, left) ? 'dl-warn' : 'dl-ok' },
left != null && left < 0 ? 'ended' : `${left} day${left === 1 ? '' : 's'} left`,
)
: E('span', { class: 'dl-faint' }, 'no end date'),
]),
E('div', { class: 'dl-chips-row' }, [
...ext,
pick,
p.expires
? E('button', { type: 'button', class: 'dl-chipbtn', click: () => page.patch({ expires: '' }, 'No end date') }, 'No end')
: '',
]),
E('div', { class: 'dl-tile2-foot' }, [
E(
'span',
{ class: 'dl-muted' },
`When it ends: ${action}${p.expire_warn ? `, warn ${p.expire_warn} day${p.expire_warn === 1 ? '' : 's'} before` : ''}`,
),
E(
'a',
{
href: '#',
click: (ev: Event) => {
ev.preventDefault();
endSettings(page);
},
},
'Change',
),
]),
]);
}
function dataTile(page: PersonPage): HTMLElement {
const p = page.p;
const used = p.quota_used || p.month[0] + p.month[1];
const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0;
const bar = E('div', { class: `dl-meter${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` }, [
E('i'),
p.quota_limit ? E('span', { class: 'mark', title: 'Alert at 90%' }) : '',
]);
(bar.firstChild as HTMLElement).style.width = `${pct}%`;
if (p.quota_limit)
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, `${pct.toFixed(1)}% used`),
E(
'div',
{ class: 'dl-muted' },
`${bytes(p.quota_used)} of ${bytes(p.quota_limit)} · ${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`,
),
E('div', { class: 'dl-faint' }, 'Alert at 90%'),
]);
const period = seg(
[
['month', 'Monthly'],
['total', 'Total'],
],
p.quota_period,
{ label: 'Data limit period', cls: 'sm', optimistic: false, onChange: (v) => page.patch({ quota_period: v }) },
);
const presets = [10, 50, 100].map((gb) =>
E(
'button',
{
type: 'button',
class: `dl-chipbtn${p.quota_gb === gb ? ' on' : ''}`,
click: () => page.patch({ quota_gb: String(gb) }, `Data limit ${gb} GB`),
},
`${gb} GB`,
),
);
presets.push(
E(
'button',
{ type: 'button', class: `dl-chipbtn${!p.quota_gb ? ' on' : ''}`, click: () => page.patch({ quota_gb: '' }, 'No data limit') },
'Unlimited',
),
);
presets.push(
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: () => {
const inp = E('input', {
type: 'number',
class: 'cbi-input-text dl-w-port',
min: 0,
step: 'any',
value: p.quota_gb ? String(p.quota_gb) : '',
}) as HTMLInputElement;
const row = liveField('Data limit (GB)', inp, () => quotaHelp(inp.value, p.quota_period === 'month'));
modal(
'Data limit',
[row],
[
cancelButton(),
' ',
button(
'Save',
async () => {
const h = row.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
const v = inp.value.trim();
if (await page.patch({ quota_gb: v }, v && Number(v) > 0 ? `Data limit ${v} GB` : 'No data limit')) closeModal();
},
'positive',
),
],
);
setTimeout(() => inp.select(), 50);
},
},
'Custom',
),
);
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, [E('span', {}, 'Data'), period]),
E('div', { class: 'dl-tile2-row' }, [
E('span', { class: 'dl-tile2-value' }, [
bytes(used),
p.quota_limit ? E('span', { class: 'dl-faint' }, ` of ${bytes(p.quota_limit)}`) : E('span', { class: 'dl-faint' }, ' · no limit'),
]),
p.quota_period === 'month' ? E('span', { class: 'dl-sub' }, 'resets on the 1st') : '',
]),
p.quota_limit ? bar : '',
E('div', { class: 'dl-chips-row' }, presets),
p.quota_gb && p.quota_period === 'month'
? E('div', { class: 'dl-tile2-foot' }, [
E('span', { class: 'dl-muted' }, p.bonus_gb ? `Includes +${p.bonus_gb} GB extra this month` : 'Need a little more this month?'),
E(
'a',
{
href: '#',
click: (ev: Event) => {
ev.preventDefault();
void page.patch({ bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month');
},
},
'+10 GB this month',
),
])
: '',
E('div', { class: 'dl-tile2-foot' }, [
E('span', { class: 'dl-muted' }, `${bytes(p.total[0] + p.total[1])} in total`),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => resetUsageDialog('person', p.id, p.name, () => setTimeout(() => page.refresh(), 300)),
},
'Reset usage',
),
]),
]);
}
/**
* Allowed hours. The times save when the focus leaves them (or on Enter), not
* on every change: a half-typed time would otherwise be saved and the tile
* repainted under the cursor. Both are checked first.
*/
function hoursTile(page: PersonPage): HTMLElement {
const p = page.p;
const hoursOn = !!p.hours;
const [h1, h2] = (p.hours || '07:00-23:00').split('-');
const from = E('input', { type: 'time', class: 'cbi-input-text', value: h1, 'aria-label': 'From' }) as HTMLInputElement;
const to = E('input', { type: 'time', class: 'cbi-input-text', value: h2, 'aria-label': 'To' }) as HTMLInputElement;
const times = E('div', { class: 'dl-tile2-row' }, [from, E('span', { class: 'dl-faint' }, 'to'), to]);
const commit = () => {
const v = `${from.value}-${to.value}`;
if (v === p.hours) return;
if (!TIME.test(from.value) || !TIME.test(to.value)) return notify('Enter both times, like 07:00 and 23:00.', 'warning');
if (from.value === to.value) return notify('The start and the end must differ.', 'warning');
void page.patch({ hours: v }, `Allowed ${from.value}–${to.value}`);
};
times.addEventListener('focusout', (ev: FocusEvent) => {
if (!times.contains(ev.relatedTarget as Node | null)) commit();
});
for (const t of [from, to])
t.addEventListener('keydown', (ev: KeyboardEvent) => {
if (ev.key === 'Enter') {
ev.preventDefault();
commit();
}
});
const sw = E(
'button',
{
type: 'button',
role: 'switch',
'aria-checked': hoursOn ? 'true' : 'false',
class: `dl-switch${hoursOn ? ' on' : ''}`,
'aria-label': 'Limit hours',
// Turning on shows the times to set; nothing is enforced until they are saved.
click: () => {
if (hoursOn) return page.patch({ hours: '' }, 'Any time');
sw.classList.add('on');
sw.setAttribute('aria-checked', 'true');
label.textContent = 'Set the hours, then press Enter';
tile.appendChild(times);
from.focus();
},
},
E('i'),
);
const label = E('span', {}, hoursOn ? `${h1} – ${h2} (router time)` : 'Any time');
const tile = E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-row' }, [
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-tile2-label' }, 'Allowed hours'), label]),
sw,
]),
hoursOn ? times : '',
]);
return tile;
}
export function limitsPart(page: PersonPage): HTMLElement {
const p = page.p;
const access = seg(
(['internet', 'lan', 'both'] as const).map((a) => [
a,
[icon(a === 'internet' ? 'globe' : a === 'lan' ? 'home' : 'shield'), a === 'internet' ? 'Internet' : a === 'lan' ? 'Home' : 'Both'],
]),
p.access,
{ label: 'Access', cls: 'wide', optimistic: false, onChange: (a) => page.patch({ access: a }, `Access: ${ACCESS_LABEL[a]}`) },
);
// Heading above the card, like "Devices", so both columns line up (as on the portal).
return E('section', { class: 'dl-devsec', 'aria-label': 'Access and limits' }, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Access & limits')]),
E('div', { class: 'dl-panel' }, [
E('div', { class: 'dl-stack gap8' }, [
E('span', { class: 'dl-tile2-label' }, 'Can reach'),
access,
E('span', { class: 'dl-sub' }, ACCESS_TEXT[p.access]),
p.access === 'lan' && page.st.services.length ? servicesPicker(page) : '',
homeAccess(p) ? netsPicker(page) : '',
p.access === 'lan' ? dnsPicker(page) : '',
]),
E('div', { class: 'dl-tiles2' }, [devTile(page), circleTile(page), endTile(page), dataTile(page), hoursTile(page)]),
]),
]);
}