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

- 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
This commit is contained in:
Aemeath committed 2026-10-18 23:28:10 +03:00
1 parent fd9543ce68
commit 466ca6c7b0
69 files changed
+5182 -686

No files matched your search

+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dawnline-web",
"version": "0.7.0",
"version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dawnline-web",
"version": "0.7.0",
"version": "0.8.0",
"license": "MIT",
"dependencies": {
"qrcode-generator": "1.4.4"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dawnline-web",
"version": "0.7.0",
"version": "0.8.0",
"private": true,
"license": "MIT",
"type": "module",
+20 -5
View File
@@ -6,8 +6,10 @@ import { E } from './e';
import { api, type HomeHost } from './api';
import { button } from './ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
import { attempt } from './ui/toast';
import { attempt, notify } from './ui/toast';
import { chipToggle, input } from './ui/controls';
import { firstBad, liveField } from './ui/layout';
import { circleNameHelp, ipv4Help, nameHelp, portsHelp } from './netcheck';
import { icon } from '../shared/icons';
type Service = Status['services'][number];
@@ -30,17 +32,23 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
placeholder: 'All ports, or e.g. 445, 5000',
class: 'cbi-input-text dl-mono',
});
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown to people who may reach it.'));
const addrRow = liveField('Address', addr, () => ipv4Help(addr.value));
const portsRow = liveField('Ports', ports, () => portsHelp(ports.value));
modal(
sv ? `Edit ${sv.name}` : 'Add service',
[field('Name', name), field('Address', addr), field('Ports', ports)],
[nameRow, addrRow, portsRow],
[
cancelButton(),
' ',
button(
'Save',
async () => {
const bad = firstBad([nameRow, addrRow, portsRow]);
if (bad) {
notify(bad, 'warning');
return;
}
const list = ports.value.split(/[ ,]+/).filter(Boolean);
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
closeModal();
@@ -316,11 +324,13 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
);
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
const others = st.circles.filter((c) => c.server === serverId && c.id !== ci?.id).map((c) => c.name);
const nameRow = liveField('Name', name, () => circleNameHelp(name.value, others));
modal(
ci ? `Edit ${ci.name}` : 'New circle',
[
field('Name', name),
nameRow,
field('Colour', swatches),
field('People', chips),
E('p', { class: 'dl-sub' }, 'Devices of people in one circle reach each other. A person is in one circle at a time.'),
@@ -344,6 +354,11 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
button(
'Save',
async () => {
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), 'Saved')) {
closeModal();
onDone();
+26 -2
View File
@@ -39,6 +39,24 @@ export interface SetupDefaults {
tcp_taken: PortHold[];
awg: AwgCaps;
awg_state?: AwgState;
/** Where the suggested address came from: ddns, cert, wan, portal ('' = nothing found). */
endpoint_from?: string;
/** What the WAN's IPv4 is: public, private (behind another router), cgnat, none. */
wan_kind?: 'public' | 'private' | 'cgnat' | 'none';
wan_ip?: string | null;
}
/** Where a public address points (rpc endpoint_probe): the facts and their verdict in words. */
export interface EndpointProbe {
host: string;
ips: string[];
wan: string | null;
kind: 'public' | 'private' | 'cgnat' | 'none';
cloudflare: boolean;
here: boolean;
v6_only: boolean;
status: 'ok' | 'warn' | 'error';
text: string;
}
export interface Backup {
@@ -323,7 +341,8 @@ export type PersonPatch = Partial<
| 'bonus_gb'
| 'hours'
| 'note'
| 'dns_mode',
| 'dns_mode'
| 'server',
string
>
> & { paused?: boolean; services?: string[]; circle?: string; home_nets?: string[] };
@@ -349,6 +368,7 @@ const personUpdateRaw = rpc.declare<any>({
'services',
'circle',
'home_nets',
'server',
],
});
@@ -367,7 +387,7 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
'note',
'dns_mode',
] as const;
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets];
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets, patch.server];
return settle(await personUpdateRaw(...args));
}
@@ -452,6 +472,10 @@ export const api = {
]),
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
serverUpdate: call<unknown>('server_update', ['id', 'values']),
/** What an existing server's ports and a new tunnel network must avoid (checked as you type). */
serverPorts: call<{ udp_taken: PortHold[]; tcp_taken: PortHold[]; networks?: Network[] }>('server_ports', ['id']),
/** Where a public address points, for the live help under the field (debounced by the caller). */
endpointProbe: call<EndpointProbe>('endpoint_probe', ['host', 'id', 'port']),
serverDelete: call<unknown>('server_delete', ['id']),
/** The personal link, its code and every address it works on (main first); not part of the status. */
personLinks: call<{ code: string; link: string | null; links: string[] }>('person_links', ['id']),
+67 -16
View File
@@ -10,11 +10,12 @@ import { confirmDialog } from '../ui/modal';
import { copyText, downloadFile } from '../ui/files';
import { attempt, notify } from '../ui/toast';
import { input } from '../ui/controls';
import { callout, card, group, row, svg } from '../ui/layout';
import { callout, card, firstBad, group, liveRow, row, svg } from '../ui/layout';
import { keepaliveHelp, mtuHelp, portHelp, type PortHold } from '../netcheck';
import { qrSvg } from '../../shared/qr';
import { vpnKey } from '../../shared/vpnkey';
import { icon } from '../../shared/icons';
import { methodInfo, methodPicker, type Method } from '../disguise';
import { methodInfo, methodPicker, type Method, defaultMethod, legacyTitle } from '../disguise';
import { coreHead, type Core, type CoreCtx } from './common';
/** `.conf` names of the disguise parameters, in file order. */
@@ -198,6 +199,13 @@ function fileCard(cfg: AwgConfig): HTMLElement {
]);
}
/** The configuration carries no disguise values: plain WireGuard, any WireGuard app takes it. */
export function plainWg(cfg: AwgConfig): boolean {
const o = (cfg.amnezia.obfuscation ?? {}) as Record<string, string | undefined>;
const neutral: Record<string, string> = { h1: '1', h2: '2', h3: '3', h4: '4' };
return Object.entries(o).every(([k, v]) => v == null || v === '' || v === (neutral[k] ?? '0'));
}
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
if (!cfg.has_private_key)
@@ -211,7 +219,11 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
qr: () =>
E('div', { class: 'dl-qr-pane' }, [
svg(qrSvg(cfg.conf), 'dl-qr'),
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
E(
'span',
{ class: 'dl-sub' },
plainWg(cfg) ? 'Scan with AmneziaVPN or any WireGuard app on the device.' : 'Scan with AmneziaVPN or AmneziaWG on the device.',
),
]),
key: () =>
E('div', { class: 'dl-stack gap8' }, [
@@ -243,7 +255,7 @@ async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean
const devices = people.reduce((n, p) => n + p.devices.length, 0);
const ok = await confirmDialog(
same ? 'Generate new disguise values?' : `Switch to ${info.title}?`,
`${devices} AmneziaWG device${devices === 1 ? '' : 's'} stop connecting until they import their configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : m === 'balanced' ? ' They need an app with AmneziaWG 2.0 or newer.' : ''}`,
`${devices} AmneziaWG device${devices === 1 ? ' stops' : 's stop'} connecting until ${devices === 1 ? 'it imports its' : 'they import their'} configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : m === 'balanced' ? ' They need an app with AmneziaWG 2.0 or newer.' : ''}${ctx.st.servers.length === 1 && devices ? ' To keep the old disguise for some people, add a second server and move them there.' : ''}`,
same ? 'Generate and apply' : 'Switch and apply',
true,
);
@@ -263,30 +275,54 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
inputmode: 'numeric',
class: 'cbi-input-text dl-w-port dl-mono',
});
const now = `${srv.mtus.computer} for computers and routers, ${srv.mtus.phone} for phones and tablets`;
const mtuHint = srv.mtu
? `Now ${now}. Empty = automatic.`
: `Automatic by device type and disguise: now ${now}. Lower it if some sites hang.`;
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
let selected: Method = current ?? 'standard';
let selected: Method = current ?? defaultMethod(st.awg);
const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral');
const label = () =>
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
label();
const tools = st.awg_state?.tools !== false;
// Who holds which port arrives once the card is built (netstat on the
// router); until then the port is only checked for its range.
let holds: PortHold[] = [];
const portRow = liveRow('UDP port', port, () =>
portHelp(
Number(port.value),
holds,
`Opened on the WAN firewall automatically.${Number(port.value) === 4500 ? ' 4500 is IPsec’s port: most networks let it through.' : ''}`,
),
);
api
.serverPorts(srv.id)
.then((r) => {
holds = r.udp_taken ?? [];
portRow.refresh();
})
.catch(() => {});
const mtuRow = liveRow('MTU', mtu, () => mtuHelp(mtu.value, srv.mtus));
const kaRow = liveRow('Keep-alive', ka, () => keepaliveHelp(ka.value));
return card(
'',
[
coreHead('AmneziaWG', srv.ifname),
group('globe', 'Listening', 'Where devices reach this core from the internet', [
row('UDP port', port, 'Opened on the WAN firewall automatically.'),
]),
group('globe', 'Listening', 'Where devices reach this core from the internet', [portRow]),
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
row('MTU', mtu, mtuHint),
row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'),
mtuRow,
kaRow,
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
// A server from before 0.8 on the old junk-only disguise: it runs, but is no longer offered.
legacyTitle(srv.preset)
? callout('warn', [
E('b', {}, legacyTitle(srv.preset)!),
' is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ',
E('b', {}, 'Balanced'),
' or ',
E('b', {}, 'Maximum'),
': devices import their configuration again.',
])
: '',
methodPicker(
st.awg,
selected,
@@ -331,7 +367,19 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
],
[
E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'),
button('Save', () => ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved'), 'positive'),
button(
'Save',
() => {
// The help lines already say what is wrong: do not send it anyway.
const bad = firstBad([portRow, mtuRow, kaRow]);
if (bad) {
notify(bad, 'warning');
return;
}
return ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved');
},
'positive',
),
],
);
}
@@ -361,7 +409,10 @@ function overviewTile(srv: Server): HTMLElement {
]),
E('div', { class: 'dl-disg-id' }, [
E('span', { class: 'dl-disg-ic' }, icon(m?.ic ?? 'shield')),
E('span', { class: 'dl-stack' }, [E('b', {}, m ? m.title : 'Custom'), E('span', { class: 'dl-sub' }, m ? m.short : 'Set by hand')]),
E('span', { class: 'dl-stack' }, [
E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? 'Custom')),
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? 'Switch to Balanced or Maximum' : 'Set by hand'),
]),
]),
m
? E('div', { class: 'dl-disg-meters' }, [
+45 -13
View File
@@ -11,7 +11,8 @@ import { copyText, downloadFile } from './ui/files';
import { dropdown, type MenuItem } from './ui/menu';
import { drawer } from './ui/drawer';
import { attempt, notify } from './ui/toast';
import { svg } from './ui/layout';
import { liveField, svg } from './ui/layout';
import { nameHelp } from './netcheck';
import { deviceStatus } from './ui/badges';
import { qrSvg } from '../shared/qr';
import { ago, bytes, isoDay, KIND_LABEL, KINDS, todayOf } from '../shared/format';
@@ -20,6 +21,7 @@ import { eventBy } from './events/model';
import { spark } from './widgets/spark';
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
import { coreFor, coreOf, type Core } from './cores';
import { plainWg } from './cores/awg';
import { onLiveChange } from './state/live';
import { ConnectionMap, devicePlaces, rangeControl, type MapData, type Range } from './map';
import { personUrl } from './urls';
@@ -123,7 +125,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
let geo = o.geo;
let now = o.now;
let today = o.today ?? isoDay(new Date());
const connect = await core.connectBlock(cfg);
// Phones and tablets are set up by scanning; computers and routers by a file.
const connect = await core.connectBlock(cfg, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file');
const titleEl = E('div', { class: 'dl-drawer-title' });
const stats = E('div', {});
const details = E('div', {});
@@ -183,7 +186,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
E('div', { class: 'dl-dstats' }, [
E('div', { class: 'dl-dstats-cell wide' }, [
E('span', { class: 'dl-metric-label' }, 'Status'),
deviceStatus(d, now, 'Waiting for the first connection'),
deviceStatus(d, now, 'Waiting for the first connection', p),
]),
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, 'This month'),
@@ -221,10 +224,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
]),
),
row('Added', `${when(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`),
row(
'Public key',
E('span', { class: 'dl-mono dl-faint' }, cfg.amnezia.client_pub_key ? `${cfg.amnezia.client_pub_key.slice(0, 16)}…` : '—'),
),
// The whole key, copyable: it is what another WireGuard server needs to add this device by hand.
cfg.amnezia.client_pub_key ? copyRow('Public key', cfg.amnezia.client_pub_key) : row('Public key', '—'),
]),
);
dom.content(foot, [
@@ -300,15 +301,22 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const rename = () => {
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement;
const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name);
const nameRow = liveField('Name', input, () => nameHelp(input.value, taken, 'Shown in the portal and in the app.'));
modal(
`Rename ${d.name}`,
[E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, input)])],
[nameRow],
[
cancelButton(),
' ',
button(
'Save',
async () => {
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) {
closeModal();
await changed();
@@ -426,7 +434,11 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
`${d.name} · QR code`,
E('div', { class: 'dl-qr-pane' }, [
svg(qrSvg(core.qrText(c)), 'dl-qr'),
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
E(
'span',
{ class: 'dl-sub' },
plainWg(c) ? 'Scan with AmneziaVPN or any WireGuard app on the device.' : 'Scan with AmneziaVPN or AmneziaWG on the device.',
),
]),
cancelButton('Close'),
);
@@ -500,8 +512,22 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
export function addDevice(person: Person, o: DeviceOpts) {
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: KIND_LABEL.phone, maxlength: 48 }) as HTMLInputElement;
const taken = person.devices.map((x) => x.name);
// The name a type gives when none is typed: "Phone", then "Phone 2" (as the portal does).
const suggest = (k: Kind) => {
const base = KIND_LABEL[k];
let n = 1;
let name = base;
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = `${base} ${++n}`;
return name;
};
let kind: Kind = 'phone';
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: suggest(kind), maxlength: 48 }) as HTMLInputElement;
const nameRow = liveField('Name', nameInput, () =>
nameInput.value.trim()
? nameHelp(nameInput.value, taken, 'Shown in the portal and in the app.')
: { text: `Named after its type: ${suggest(kind)}.`, bad: false },
);
const kinds = E(
'div',
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': 'Type' },
@@ -521,7 +547,8 @@ export function addDevice(person: Person, o: DeviceOpts) {
c.classList.toggle('on', on);
c.setAttribute('aria-checked', on ? 'true' : 'false');
});
nameInput.placeholder = KIND_LABEL[k];
nameInput.placeholder = suggest(k);
nameRow.refresh();
},
},
[icon(k), E('span', {}, KIND_LABEL[k])],
@@ -540,7 +567,7 @@ export function addDevice(person: Person, o: DeviceOpts) {
)
: '',
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Type'), kinds]),
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Name'), nameInput]),
nameRow,
],
[
cancelButton(),
@@ -548,7 +575,12 @@ export function addDevice(person: Person, o: DeviceOpts) {
button(
'Add device',
async () => {
const name = nameInput.value.trim() || nameInput.placeholder.replace(/^e\.g\. /, '');
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
const name = nameInput.value.trim() || suggest(kind);
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
if (!r) return;
closeModal();
+17 -24
View File
@@ -4,7 +4,7 @@ import type { AwgCaps } from '../shared/types';
import { E } from './e';
import { icon } from '../shared/icons';
export type Method = 'standard' | 'strong' | 'balanced' | 'max' | 'off';
export type Method = 'balanced' | 'max' | 'off';
/** The router features a method may need (the boolean ones of AwgCaps). */
export type AwgNeed = 'v2' | 'v3';
@@ -35,32 +35,12 @@ export const METHODS: MethodInfo[] = [
apps: 'Any WireGuard app',
short: 'Any WireGuard app',
},
{
id: 'standard',
title: 'Standard',
ic: 'shield',
stealth: 2,
speed: 4,
text: 'Junk packets and random headers. Gets through most VPN blocking with no speed cost.',
apps: 'Every AmneziaWG and AmneziaVPN app',
short: 'Any AmneziaWG app',
},
{
id: 'strong',
title: 'Strong',
ic: 'shieldplus',
stealth: 3,
speed: 3,
text: 'More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.',
apps: 'Every AmneziaWG and AmneziaVPN app',
short: 'Any AmneziaWG app',
},
{
id: 'balanced',
title: 'Balanced',
ic: 'shieldplus',
ic: 'shield',
stealth: 3,
speed: 3,
speed: 4,
needs: 'v2',
text: 'AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.',
apps: 'AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps',
@@ -81,6 +61,17 @@ export const METHODS: MethodInfo[] = [
export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id);
/** The disguise a new server gets: the strongest this router can run. */
export const defaultMethod = (caps: AwgCaps): Method => (caps.v3 ? 'max' : caps.v2 ? 'balanced' : 'off');
/**
* Servers made before 0.8 may carry the old Standard or Strong disguise
* (1.0-style junk only, which networks learned to spot). They keep running;
* the picker offers Balanced or Maximum instead. The title for such a server, or null.
*/
export const legacyTitle = (preset: string): string | null =>
preset === 'standard' ? 'Standard (old)' : preset === 'strong' ? 'Strong (old)' : null;
const NEEDS: Record<AwgNeed, string> = {
v2: 'Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).',
v3: 'Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).',
@@ -148,7 +139,9 @@ export function methodPicker(
E(
'div',
{ class: 'dl-method-foot' },
ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
ok
? [icon(m.id === 'off' ? 'wireguard' : 'amneziawg'), E('span', {}, m.apps)]
: [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
),
],
);
+2
View File
@@ -20,6 +20,8 @@ const CATEGORY: Record<string, LogCategory> = {
person_changed: 'people',
paused: 'people',
resumed: 'people',
expiring: 'people',
expired_kept: 'people',
portal_blocked: 'problems',
};
+8
View File
@@ -21,6 +21,8 @@ const EVENT_TONE: Record<string, string> = {
person_removed: '',
paused: 'warn',
resumed: 'ok',
expiring: 'warn',
expired_kept: '',
portal_blocked: 'bad',
person_changed: '',
devices_removed: 'warn',
@@ -35,6 +37,8 @@ const EVENT_ICON: Record<string, string> = {
person_changed: 'edit',
paused: 'pause',
resumed: 'play',
expiring: 'calendar',
expired_kept: 'calendar',
};
function eventIcon(st: Names, e: LogEvent): string {
@@ -135,6 +139,10 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
case 'person_changed':
// The detail lists changed fields by their option names (device_limit, expire_action).
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
case 'expiring':
return [kind('Person'), b(who), m(`’s access ends in ${e.detail ?? 'a few days'}`)];
case 'expired_kept':
return [kind('Person'), b(who), m(`’s end date passed (${e.detail ?? ''}) · access kept`)];
case 'paused':
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
case 'resumed':
+20 -14
View File
@@ -107,24 +107,30 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' });
const url = URL.createObjectURL(png);
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
const canShare = !!nav.canShare?.({ files: [file] });
// Three tiers: the card as a file, the link through the share sheet (older
// Android, Firefox on phones), else a download of the card.
const canShareFile = !!nav.canShare?.({ files: [file] });
const canShareLink = !canShareFile && typeof nav.share === 'function' && (nav.canShare?.({ url: href }) ?? true);
const close = () => {
URL.revokeObjectURL(url);
closeModal();
};
const share = canShare
? button(
[icon('link'), ' Share card'],
async () => {
try {
await nav.share({ files: [file], title: `Invite ${p.name}` });
} catch {
/* cancelled */
}
},
'positive',
)
: button([icon('download'), ' Download card'], () => downloadFile(file.name, png), 'positive');
const shareIt = async (data: ShareData) => {
try {
await nav.share(data);
} catch {
/* cancelled */
}
};
const share = canShareFile
? button([icon('link'), ' Share card'], () => shareIt({ files: [file], title: `Invite ${p.name}` }), 'positive')
: canShareLink
? button(
[icon('link'), ' Share link'],
() => shareIt({ url: href, title: `Invite ${p.name}`, text: `Your personal VPN link` }),
'positive',
)
: button([icon('download'), ' Download card'], () => downloadFile(file.name, png), 'positive');
modal(
opts.title ?? `Invite ${p.name}`,
E('div', { class: 'dl-invite' }, [
+230
View File
@@ -91,3 +91,233 @@ export function portalPortHelp(port: number, taken: PortHold[], ipLinks: boolean
const who = holder(port + 1, taken);
return who ? { text: `Links on IP addresses also need ${port + 1}, used by ${who}. Choose another port.`, bad: true } : h;
}
/* ---------- other fields, mirroring the router's rules (dawnline.util, schema, core) ---------- */
/** Characters, not UTF-16 units or bytes: what the router counts (util.ulength). */
export const chars = (s: string): number => Array.from(s).length;
const NAME_MAX = 48;
const BAD_NAME = /[<>"\\\u0000-\u001f\u007f]/;
/**
* A name people see (util.valid_name): 1–48 characters, none of < > " \.
* `taken` are names already used where it must be unique (case-insensitive).
*/
export function nameHelp(s: string, taken: string[] = [], good = ''): Help {
const t = s.trim();
if (!t) return { text: 'Enter a name.', bad: true };
if (chars(s) > NAME_MAX) return { text: `Up to ${NAME_MAX} characters (${chars(s)} now).`, bad: true };
if (BAD_NAME.test(s)) return { text: 'Names can’t contain < > " or \\.', bad: true };
if (taken.some((x) => x.toLowerCase() === t.toLowerCase())) return { text: `“${t}” already exists — pick another name.`, bad: true };
return { text: good, bad: false };
}
/** A circle's name: like a name, up to 32 characters. */
export function circleNameHelp(s: string, taken: string[] = []): Help {
if (chars(s) > 32) return { text: `Up to 32 characters (${chars(s)} now).`, bad: true };
return nameHelp(s, taken, 'Shown on the person cards.');
}
const HOSTNAME = /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
export function isIpv4(s: string): boolean {
const m = IPV4.exec(s);
return !!m && m.slice(1).every((x) => Number(x) <= 255);
}
export function isIpv6(s: string): boolean {
return /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/.test(s) && !/:::/.test(s);
}
/**
* The public address of a server or the portal (util.valid_host): a hostname
* or an IP address, nothing else. `port` names what devices connect to when
* it is fine; `empty` is what an empty field means (null: it is required).
*/
export function hostHelp(s: string, port?: number, empty: string | null = null): Help {
const t = s.trim();
if (!t) return empty != null ? { text: empty, bad: false } : { text: 'Enter a hostname or IP address.', bad: true };
if (/^[a-z]+:\/\//i.test(t)) return { text: 'Leave out https:// — just the name.', bad: true };
if (/\/.*/.test(t)) return { text: 'Just the name, without a path.', bad: true };
if (/^[^:\[]+:\d+$/.test(t)) return { text: 'Just the name, without a port (the port is on AmneziaWG).', bad: true };
if (/\s/.test(t)) return { text: 'A hostname has no spaces.', bad: true };
if (t.length > 253 || !(HOSTNAME.test(t) || isIpv4(t) || isIpv6(t))) return { text: 'Use a hostname or an IP address.', bad: true };
const shown = isIpv6(t) ? `[${t}]` : t;
return { text: port ? `Devices connect to ${shown}:${port}.` : `Links use ${shown}.`, bad: false };
}
/** The DNS list a server hands to devices (rpc/servers.uc dns_list): IPs, comma-separated; empty = this router. */
export function dnsHelp(s: string, routerAddr: string): Help {
const items = s.split(/[ ,]+/).filter(Boolean);
if (!items.length)
return { text: `This router (${routerAddr}): queries go where your home network sends them, and home names work.`, bad: false };
const bad = items.find((x) => !isIpv4(x) && !isIpv6(x));
if (bad) return { text: `“${bad}” is not an IP address. Separate several with commas.`, bad: true };
return { text: `Devices use ${items.join(' and ')} — home names and your LAN’s DNS filters no longer apply to them.`, bad: false };
}
/** MTU (rpc/servers.uc check_mtu): empty = automatic, else 1280–1500. */
export function mtuHelp(s: string, mtus: { computer: number; phone: number }): Help {
const t = s.trim();
if (!t)
return {
text: `Automatic by device type and disguise: ${mtus.computer} for computers and routers, ${mtus.phone} for phones and tablets.`,
bad: false,
};
if (!/^\d{1,4}$/.test(t) || Number(t) < 1280 || Number(t) > 1500)
return { text: 'MTU must be 1280–1500, or empty for automatic.', bad: true };
const n = Number(t);
return { text: `Computers and routers get ${n}, phones and tablets ${Math.min(n, 1280)}.`, bad: false };
}
/** Keep-alive (rpc/servers.uc): 0–600 s; empty = 25. */
export function keepaliveHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'Default: a packet every 25 s keeps NAT open and “Connected” accurate.', bad: false };
if (!/^\d{1,3}$/.test(t) || Number(t) > 600) return { text: 'Use 0–600 seconds.', bad: true };
if (Number(t) === 0) return { text: 'Off: NAT may close the tunnel when idle, and “Connected” lags.', bad: false };
return { text: `Devices send a packet every ${t} s to keep NAT open (a little battery on phones).`, bad: false };
}
/** Device limit (core.create_person): 1–32; `have` is how many they have now (an edit). */
export function limitHelp(s: string, have = 0): Help {
const t = s.trim();
if (!/^\d{1,2}$/.test(t) || Number(t) < 1 || Number(t) > 32) return { text: 'Use 1–32.', bad: true };
const n = Number(t);
if (have > n)
return { text: `Already has ${have} devices: remove ${have - n === 1 ? 'one' : `${have - n}`} first, or allow more.`, bad: true };
return { text: `They can add ${n} device${n === 1 ? '' : 's'} themselves.`, bad: false };
}
/** Monthly data in GB (core.create_person): empty = unlimited, else 0–100000. */
export function quotaHelp(s: string, monthly = true): Help {
const t = s.trim();
if (!t) return { text: 'Optional. No data limit.', bad: false };
const n = Number(t);
if (!/^\d+(\.\d+)?$/.test(t) || n < 0 || n > 100000) return { text: 'A number of GB, up to 100000.', bad: true };
if (n === 0) return { text: 'Optional. No data limit.', bad: false };
return { text: monthly ? `Paused after ${t} GB this month, resumed on the 1st.` : `Paused after ${t} GB in total.`, bad: false };
}
/** An end date (YYYY-MM-DD) against the router's day; empty = none. */
export function expiresHelp(
s: string,
today: string,
daysLeft: (d: string, t: string) => number | null,
date: (d: string) => string,
): Help {
const t = s.trim();
if (!t) return { text: 'Optional. No end date.', bad: false };
const left = daysLeft(t, today);
if (left == null) return { text: 'Use a date.', bad: true };
if (left < 0) return { text: 'That date has passed: access would end at once.', bad: true };
return { text: left === 1 ? `Access ends today (${date(t)}).` : `Access ends in ${left} days (${date(t)}).`, bad: false };
}
/** A home service's address (rpc/home.uc): IPv4; `homeNets` warn when it is outside every home network. */
export function ipv4Help(s: string, inHome: ((ip: string) => boolean) | null = null): Help {
const t = s.trim();
if (!t) return { text: 'The device’s address at home.', bad: true };
if (!isIpv4(t)) return { text: 'Use an IPv4 address, like 192.168.1.10.', bad: true };
if (inHome && !inHome(t)) return { text: `${t} is not in any home network of this server: nobody would reach it.`, bad: false };
return { text: '', bad: false };
}
/** A service's ports: empty = all, else numbers 1–65535. */
export function portsHelp(s: string): Help {
const items = s.split(/[ ,]+/).filter(Boolean);
if (!items.length) return { text: 'All ports.', bad: false };
const bad = items.find((x) => !/^\d{1,5}$/.test(x) || Number(x) < 1 || Number(x) > 65535);
if (bad) return { text: `“${bad}” is not a port (1–65535).`, bad: true };
return { text: `Port${items.length === 1 ? '' : 's'} ${items.join(', ')}.`, bad: false };
}
/** The portal's redirect for unknown links (schema portal_redirect): a full http(s) URL, or empty. */
export function urlHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'Wrong links get a bare “Not found”.', bad: false };
if (!/^https?:\/\//i.test(t)) return { text: 'Must start with http:// or https://.', bad: true };
if (t.length > 300 || !/^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^\s"'<>]*)?$/.test(t))
return { text: 'Not a usable address (no spaces or quotes).', bad: true };
return { text: 'Wrong links are sent there instead of a “Not found”.', bad: false };
}
/** The portal's title: up to 64 characters on one line. */
export function titleHelp(s: string): Help {
if (chars(s) > 64) return { text: `Up to 64 characters (${chars(s)} now).`, bad: true };
if (/[\u0000-\u001f\u007f]/.test(s)) return { text: 'One line, please.', bad: true };
return { text: 'Shown in the browser tab and at the top of the portal.', bad: false };
}
/** The home domain for device hostnames (schema domain): lowercase letters, digits, dashes, dots. */
export function domainHelp(s: string, example = 'phone.myata'): Help {
const t = s.trim();
// Empty keeps the default (the router stores nothing then).
if (!t) return { text: `The default, lan: devices get names like ${example}.lan.`, bad: false };
if (!/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(t))
return { text: /[A-Z]/.test(t) ? 'Lowercase only.' : 'Lowercase letters, digits, dashes and dots.', bad: true };
return { text: `Devices get names like ${example}.${t}.`, bad: false };
}
/** The fallback DNS for home-names devices: an IPv4 address, or empty for none. */
export function fallbackDnsHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'None: without the tunnel those devices have no DNS.', bad: false };
if (!isIpv4(t)) return { text: 'Use an IPv4 address, or leave it empty.', bad: true };
return { text: `${t} takes over when the tunnel is down.`, bad: false };
}
/** The daily update time (schema update_time): HH:MM. */
export function timeHelp(s: string): Help {
const t = s.trim();
if (!/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(t)) return { text: 'Use HH:MM, 00:00–23:59.', bad: true };
return { text: `Runs within an hour after ${t} (router time).`, bad: false };
}
/**
* A public address checked on the router as it is typed (rpc endpoint_probe:
* where it points, CGNAT, Cloudflare), debounced so a keystroke is not a
* lookup. `help()` is the row's: the syntax first (hostHelp), then the
* router's verdict once it arrives, "Checking…" in between.
*/
export function endpointProbe(
get: () => { host: string; port: number; id?: string },
probe: (host: string, id: string | undefined, port: number) => Promise<{ text: string; status?: string }>,
onResult: () => void,
opts: { empty?: string | null; idle?: () => string } = {},
) {
let timer = 0;
let asked = '';
let result: { host: string; text: string; bad: boolean } | null = null;
const schedule = () => {
const { host } = get();
const h = hostHelp(host, get().port, opts.empty ?? null);
if (h.bad || !host.trim() || host.trim() === result?.host) return;
clearTimeout(timer);
timer = window.setTimeout(async () => {
const want = host.trim();
asked = want;
try {
const { id, port } = get();
const r = await probe(want, id, port);
if (asked !== want) return;
result = { host: want, text: r.text, bad: r.status === 'error' };
} catch {
if (asked !== want) return;
result = { host: want, text: h.text, bad: false };
}
onResult();
}, 700);
};
const help = (): Help => {
const { host, port } = get();
const h = hostHelp(host, port, opts.empty ?? null);
if (h.bad || !host.trim()) return h;
if (result && result.host === host.trim()) return { text: result.text, bad: result.bad };
const idle = opts.idle?.();
return { text: idle ? `${idle} Checking where it points…` : `${h.text} Checking where it points…`, bad: false };
};
return { help, schedule };
}
+42 -3
View File
@@ -8,7 +8,7 @@ import { api } from '../api';
import { svg } from '../ui/layout';
import { attachTip } from '../ui/tooltip';
import { icon } from '../../shared/icons';
import { ago, bits, bytes, daysLeft, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
import { ago, bits, bytes, date, daysLeft, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
import { ConnectionMap, rangeControl, type Range } from '../map';
import { personUrl } from '../urls';
import { eventRow } from '../events/render';
@@ -17,6 +17,8 @@ import { repaint } from '../state/poller';
import { daysTile, speedTile } from '../widgets/tiles';
import { coreOf } from '../cores';
import { healthNotices, runFix } from '../widgets/health';
import { attempt } from '../ui/toast';
import { isIpv4 } from '../netcheck';
import { onNavigate } from '../ui/nav';
interface Attention {
@@ -48,6 +50,9 @@ function attention(st: Status): Attention[] {
else {
const left = daysLeft(p.expires, today);
if (endsSoon(p, left)) out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s access ${endsIn(left as number)}.`] });
// "Keep access" at the end date: nothing changes on its own, so it is said here.
else if (left != null && left < 0 && p.expire_action === 'notify')
out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s end date passed (${date(p.expires)}) · access kept.`] });
if (p.quota_limit && p.quota_used >= p.quota_limit * 0.9)
out.push({ tone: '', text: [link(personUrl(p.id), p.name), ' has used 90% of the data limit.'] });
}
@@ -64,12 +69,40 @@ function attention(st: Status): Attention[] {
]
: [`${stale.length} devices need their configuration again (networks or DNS changed).`],
});
// A server that gives devices an IPv4 that is no longer the router's: one click puts the new one in.
for (const s of st.servers)
if (st.wan && isIpv4(s.endpoint) && s.endpoint !== st.wan)
out.push({
tone: 'warn',
text: [
`Public address changed: ${s.name} still gives devices ${s.endpoint}, the router is ${st.wan} now. `,
E(
'button',
{
type: 'button',
class: 'dl-fix',
click: async (ev: Event) => {
const b = ev.currentTarget as HTMLButtonElement;
b.disabled = true;
await attempt(
() => api.serverUpdate(s.id, { endpoint: st.wan }),
`${s.name} uses ${st.wan} now — devices need their configuration again`,
);
b.disabled = false;
},
},
'Use the new address',
),
' A DDNS name would follow it by itself.',
],
});
if (st.servers.some((s) => s.lan_like) && st.like_home.error)
out.push({
tone: 'warn',
text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/diagnostics'), 'Details')],
});
if (!st.settings.portal_enabled)
// Only while setting up: an admin who keeps the portal off has decided so.
if (!st.settings.portal_enabled && !st.people.length)
out.push({ tone: '', text: ['The personal portal is off. ', link(L.url('admin/network/dawnline/settings'), 'Turn on')] });
return out;
}
@@ -390,6 +423,12 @@ export class ServerOverview {
/** The last 30 days, today on the right, with the peak. */
monthTile(): HTMLElement {
return daysTile(this.st.series, '');
// Who used the most this month (the People sort has it too, a click away).
const top = [...this.st.people]
.map((p) => [p, p.month[0] + p.month[1]] as const)
.filter(([, n]) => n > 0)
.sort((a, b) => b[1] - a[1])
.slice(0, 2);
return daysTile(this.st.series, top.length ? `Most: ${top.map(([p, n]) => `${p.name} ${bytes(n)}`).join(' · ')}` : '');
}
}
+131 -17
View File
@@ -17,7 +17,10 @@ import { copyPersonLink, inviteCard } from '../invite';
import { personUrl } from '../urls';
import { scoped } from '../state/scope';
import { createPoller, focusInside, type Poller } from '../state/poller';
import { onNavigate } from '../ui/nav';
import { accessPicker } from '../widgets/access-picker';
import { firstBad, liveField } from '../ui/layout';
import { expiresHelp, limitHelp, nameHelp, quotaHelp } from '../netcheck';
import { coreFor } from '../cores';
import { icon } from '../../shared/icons';
import {
@@ -38,6 +41,22 @@ import {
type Sid = string;
/** Per-browser conveniences (a tab, a sort): storage may be absent or refuse. */
function remembered(key: string): string | null {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function remember(key: string, value: string) {
try {
localStorage.setItem(key, value);
} catch {
/* no storage */
}
}
/** Device slots as a row of segments (one per allowed device, used ones lit) and "2 of 10". */
function slotBar(p: Person): HTMLElement {
const used = p.devices.length;
@@ -89,9 +108,14 @@ export class PeoplePage {
/** The cards, one per person, in the current sort order. */
private list: HTMLElement = E('div', { class: 'dl-plist', role: 'list' });
// `?filter=online` (from Overview) preselects a tab.
// The tab and the sort are remembered in this browser; ?filter= (from Overview) wins for the tab.
filter: Filter =
(['all', 'online', 'attention', 'paused'] as Filter[]).find((f) => f === new URLSearchParams(location.search).get('filter')) ?? 'all';
sort: SortBy = 'seen';
(['all', 'online', 'attention', 'paused'] as Filter[]).find(
(f) => f === (new URLSearchParams(location.search).get('filter') ?? remembered('dl.people.filter')),
) ?? 'all';
sort: SortBy = (['seen', 'name', 'usage'] as SortBy[]).find((x) => x === remembered('dl.people.sort')) ?? 'seen';
/** What the admin typed into Find (name, note, device, address). */
query = '';
noFooter = true;
/** Set when shown as a server's People section: only that server's people. */
serverId: string | null = null;
@@ -208,11 +232,37 @@ export class PeoplePage {
'aria-label': 'Sort',
change: (ev: Event) => {
page.sort = (ev.target as HTMLSelectElement).value as SortBy;
remember('dl.people.sort', page.sort);
page.decorate();
},
},
[E('option', { value: 'seen' }, 'Last seen'), E('option', { value: 'name' }, 'Name'), E('option', { value: 'usage' }, 'Usage')],
[
E('option', { value: 'seen', selected: page.sort === 'seen' ? 'selected' : null }, 'Last seen'),
E('option', { value: 'name', selected: page.sort === 'name' ? 'selected' : null }, 'Name'),
E('option', { value: 'usage', selected: page.sort === 'usage' ? 'selected' : null }, 'Usage'),
],
);
// Find, once the list is long enough to need it; "/" focuses it.
const find = E('input', {
type: 'search',
class: 'cbi-input-text dl-people-find',
placeholder: 'Find…',
'aria-label': 'Find a person or device',
hidden: st.people.length > 8 ? null : 'hidden',
input: (ev: Event) => {
page.query = (ev.target as HTMLInputElement).value.trim().toLowerCase();
page.decorate();
},
}) as HTMLInputElement;
const onSlash = (ev: KeyboardEvent) => {
const t = ev.target as HTMLElement;
if (ev.key === '/' && !find.hidden && !['INPUT', 'TEXTAREA', 'SELECT'].includes(t?.tagName) && !t?.isContentEditable) {
ev.preventDefault();
find.focus();
}
};
document.addEventListener('keydown', onSlash);
onNavigate(() => document.removeEventListener('keydown', onSlash));
const wrap = E('div', { class: 'dl-root' }, [
page.serverId
? ''
@@ -234,6 +284,7 @@ export class PeoplePage {
E('div', { class: 'dl-seg dl-people-tabs', role: 'tablist' }),
// Sort and add stay together on the right, wrapping as one group.
E('div', { class: 'dl-toolbar-end' }, [
find,
sort,
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
]),
@@ -290,6 +341,7 @@ export class PeoplePage {
class: f === this.filter ? 'on' : '',
click: () => {
this.filter = f;
remember('dl.people.filter', f);
this.decorate();
},
},
@@ -298,10 +350,14 @@ export class PeoplePage {
),
);
}
const q = this.query;
const hay = (p: Person) =>
[p.name, p.note ?? '', ...p.devices.flatMap((d) => [d.name, d.address, d.hostname, d.endpoint])].join(' ').toLowerCase();
const match = (p: Person) => {
if (this.filter === 'online' && !p.online) return false;
if (this.filter === 'attention' && !attn(p)) return false;
if (this.filter === 'paused' && !paused(p)) return false;
if (q && !hay(p).includes(q)) return false;
return true;
};
// Whatever the sort: people who can connect, then those held by a limit or an end
@@ -405,8 +461,17 @@ export class PeoplePage {
),
);
// Ending soon (the strip below handles an end that has passed).
// Ending soon (the strip below handles an end that has passed); someone new
// without a device yet gets a nudge to send the link.
const fixes: Node[] = [];
if (!p.devices.length && portal && !stopped(p))
fixes.push(
E(
'button',
{ type: 'button', class: 'dl-fix', click: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? 'Home') },
'Send invite',
),
);
if (p.expires && endsSoon(p, left) && why !== 'expired')
fixes.push(
E(
@@ -612,7 +677,15 @@ export class PeoplePage {
return;
}
const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: 'e.g. Myata', maxlength: 48 }) as HTMLInputElement;
const access = accessPicker('internet');
// The last person's access and data limit come back pre-filled (most are alike).
const last = (() => {
try {
return JSON.parse(remembered('dl.person.last') ?? '{}') as { access?: Person['access']; quota?: string };
} catch {
return {} as { access?: Person['access']; quota?: string };
}
})();
const access = accessPicker(last.access ?? 'internet');
const limit = E('input', {
type: 'number',
class: 'cbi-input-text',
@@ -627,6 +700,7 @@ export class PeoplePage {
min: 0,
step: 'any',
placeholder: 'Unlimited',
value: last.quota ?? '',
}) as HTMLInputElement;
const quick = (label: string, months: number) =>
E(
@@ -636,6 +710,7 @@ export class PeoplePage {
class: 'cbi-button cbi-button-neutral',
click: () => {
expires.value = months ? addMonthsClamped(todayOf(st.series), months) : '';
expires.dispatchEvent(new Event('change'));
},
},
label,
@@ -655,44 +730,62 @@ export class PeoplePage {
E('label', { class: 'cbi-value-title' }, label),
E('div', { class: 'cbi-value-field' }, [w, help ? E('div', { class: 'cbi-value-description' }, help) : '']),
]);
// Each field says what its value means, or what is wrong, as it is typed; Create refuses what the router would.
const today = todayOf(st.series);
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown in their portal and apps.'));
const limitRow = liveField('Devices', limit, () => limitHelp(limit.value));
const expRow = liveField(
'End date',
expires,
() => expiresHelp(expires.value, today, daysLeft, date),
E('div', { class: 'dl-actions' }, [expires, quick('1 month', 1), quick('3 months', 3), quick('1 year', 12), quick('None', 0)]),
);
const quotaRow = liveField('Monthly data (GB)', quota, () => quotaHelp(quota.value));
// The quick buttons set the date without an input event.
expires.addEventListener('change', () => expRow.refresh());
const portalOn = st.settings.portal_enabled;
modal(
'Add person',
[
row('Name', name),
nameRow,
server ? row('Server', server) : '',
E('div', { class: 'cbi-value dl-block' }, [
E('label', { class: 'cbi-value-title' }, 'Access'),
E('div', { class: 'cbi-value-field' }, access.el),
]),
row('Devices', limit, 'How many devices they can add themselves.'),
row(
'End date',
E('div', { class: 'dl-actions' }, [expires, quick('1 month', 1), quick('3 months', 3), quick('1 year', 12), quick('None', 0)]),
'Optional.',
),
row('Monthly data (GB)', quota, 'Optional. They are paused when it runs out and resumed next month.'),
limitRow,
expRow,
quotaRow,
],
[
cancelButton(),
' ',
button(
'Create and copy link',
// Without the portal there is no link to copy.
portalOn ? 'Create and copy link' : 'Create',
async () => {
const bad = firstBad([nameRow, limitRow, expRow, quotaRow]);
if (bad) {
notify(bad, 'warning');
return;
}
const r = await attempt(() =>
api.personCreate(
name.value.trim(),
'',
server?.value ?? srv.id,
access.get(),
String(Number(limit.value) || st.settings.default_device_limit),
limit.value.trim(),
expires.value,
quota.value.trim(),
'month',
),
);
if (!r) return;
if (r.link) await copyText(r.link, 'Personal link copied');
remember('dl.person.last', JSON.stringify({ access: access.get(), quota: quota.value.trim() }));
// After the await some browsers refuse the clipboard: the card has its own Copy.
if (r.link) await copyText(r.link, 'Personal link copied', true);
this.showCreated(r.id, name.value.trim(), r.link, st.servers.find((x) => x.id === (server?.value ?? srv.id))?.name ?? srv.name);
await this.refresh();
},
@@ -711,10 +804,31 @@ export class PeoplePage {
});
return;
}
// No portal, no link: the two ways on from here, as buttons.
const p = this.person(id);
modal(
`${name} is ready`,
[E('p', {}, 'Created. Turn on the personal portal in Settings to get a link, or add devices for them here.')],
[E('button', { class: 'cbi-button cbi-button-positive', click: closeModal }, 'Done')],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Done'),
' ',
E(
'a',
{ class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/network/dawnline/settings')}?section=portal` },
'Open Settings',
),
' ',
p
? button(
'Add device',
() => {
closeModal();
addDevice(p, this.deviceOpts(p));
},
'positive',
)
: '',
],
);
}
}
+1 -1
View File
@@ -50,7 +50,7 @@ export function devicesPart(page: PersonPage): HTMLElement {
E('span', { class: 'dl-dcard-ic' }, icon(d.kind)),
E('button', { type: 'button', class: 'dl-dcard-title', click: () => open(d) }, [
E('b', {}, d.name),
deviceStatus(d, now),
deviceStatus(d, now, undefined, p),
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, 'Update config') : '',
]),
more(d),
+50 -3
View File
@@ -1,11 +1,13 @@
// Person page dialogs: rename, note, when access ends, new link, invite, delete.
// Person page dialogs: rename, note, when access ends, move to a server, new link, invite, delete.
import { E } from '../../e';
import { api } from '../../api';
import { button } from '../../ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from '../../ui/modal';
import { copyText } from '../../ui/files';
import { attempt } from '../../ui/toast';
import { attempt, notify } from '../../ui/toast';
import { liveField } from '../../ui/layout';
import { nameHelp } from '../../netcheck';
import { inviteCard } from '../../invite';
import { peopleUrl } from '../../urls';
import type { PersonPage } from './index';
@@ -126,15 +128,21 @@ export function endSettings(page: PersonPage) {
export function rename(page: PersonPage) {
const input = E('input', { type: 'text', class: 'cbi-input-text', value: page.p.name, maxlength: 48 }) as HTMLInputElement;
const nameRow = liveField('Name', input, () => nameHelp(input.value, [], 'Shown in their portal and apps.'));
modal(
'Rename',
[field('Name', input)],
[nameRow],
[
cancelButton(),
' ',
button(
'Save',
async () => {
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
// The dialog stays open on a refusal, with the name still typed.
if (await page.patch({ name: input.value.trim() }, 'Renamed')) closeModal();
},
@@ -145,6 +153,45 @@ export function rename(page: PersonPage) {
setTimeout(() => input.select(), 50);
}
/** Another server: every device gets an address there and needs its configuration again. */
export function moveToServer(page: PersonPage) {
const p = page.p;
const others = page.st.servers.filter((s) => s.id !== p.server);
const sel = E(
'select',
{ class: 'cbi-input-select' },
others.map((s) => E('option', { value: s.id }, `${s.name} · ${s.endpoint || 'no address'}:${s.port}`)),
) as HTMLSelectElement;
const n = p.devices.length;
modal(
`Move ${p.name} to another server`,
[
field('Server', sel),
E(
'p',
{ class: 'dl-muted' },
n
? `${n} device${n === 1 ? ' gets a new address and stops' : 's get new addresses and stop'} connecting until ${n === 1 ? 'it imports its' : 'they import their'} configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.`
: 'They have no devices yet: nothing else changes.',
),
],
[
cancelButton(),
' ',
button(
'Move',
async () => {
if (await page.patch({ server: sel.value }, `Moved to ${others.find((s) => s.id === sel.value)?.name ?? 'the server'}`)) {
closeModal();
if (n) notify('Devices are marked “Update config” until they import again.', 'info', 6000);
}
},
'positive',
),
],
);
}
export async function remove(page: PersonPage) {
const p = page.p;
const ok = await confirmDialog(
+3 -1
View File
@@ -8,7 +8,7 @@ import { icon } from '../../../shared/icons';
import { ago, bytes, date, initials, isoDay } from '../../../shared/format';
import { copyPersonLink } from '../../invite';
import { daysTile, speedTile } from '../../widgets/tiles';
import { editNote, invite, newLink, remove, rename } from './dialogs';
import { editNote, invite, moveToServer, newLink, remove, rename } from './dialogs';
import type { PersonPage } from './index';
export function headPart(page: PersonPage): HTMLElement {
@@ -21,6 +21,8 @@ export function headPart(page: PersonPage): HTMLElement {
const menu: (MenuItem | null)[] = [
{ label: 'Rename', icon: icon('edit'), run: () => rename(page) },
{ label: p.note ? 'Edit note' : 'Add note', icon: icon('file'), run: () => editNote(page) },
// With one server there is nowhere to move to.
...(st.servers.length > 1 ? [{ label: 'Move to server…', icon: icon('server'), run: () => moveToServer(page) }] : []),
...(portal
? [
null,
+16 -9
View File
@@ -18,7 +18,7 @@ import { devicesPart } from './devices';
import { limitsPart } from './limits';
import { activityPart, placesPart } from './activity';
type Part = 'head' | 'devices' | 'traffic' | 'places' | 'activity' | 'limits';
type Part = 'crumbs' | 'head' | 'devices' | 'traffic' | 'places' | 'activity' | 'limits';
interface Loaded {
st: Status;
@@ -69,16 +69,10 @@ export class PersonPage {
E('a', { class: 'cbi-button', href: L.url('admin/network/dawnline/server') }, 'Back to Servers'),
]);
this.p = p;
for (const k of ['head', 'devices', 'traffic', 'places', 'activity', 'limits'] as Part[]) this.parts[k] = E('div', {});
for (const k of ['crumbs', 'head', 'devices', 'traffic', 'places', 'activity', 'limits'] as Part[]) this.parts[k] = E('div', {});
this.parts.devices.className = 'dl-person-devices';
const root = E('div', {}, [
E('nav', { class: 'dl-crumbs', 'aria-label': 'Breadcrumb' }, [
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? 'Servers'),
E('span', {}, '/'),
E('a', { href: peopleUrl(p.server) }, 'People'),
E('span', {}, '/'),
E('span', {}, p.name),
]),
this.parts.crumbs,
this.parts.head,
E('div', { class: 'dl-grid-person' }, [
E('div', { class: 'dl-col' }, [this.parts.devices, this.parts.traffic, this.parts.places, this.parts.activity]),
@@ -176,7 +170,20 @@ export class PersonPage {
}
/** Every part; a `quiet` (periodic) repaint leaves alone the parts that have the keyboard focus. */
/** Server / People / name: the server changes when the person is moved. */
private crumbs(): HTMLElement {
const p = this.p;
return E('nav', { class: 'dl-crumbs', 'aria-label': 'Breadcrumb' }, [
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? 'Servers'),
E('span', {}, '/'),
E('a', { href: peopleUrl(p.server) }, 'People'),
E('span', {}, '/'),
E('span', {}, p.name),
]);
}
paint(quiet = false) {
repaint(this.parts.crumbs, this.crumbs(), quiet);
repaint(this.parts.head, headPart(this), quiet);
repaint(this.parts.traffic, trafficPart(this), quiet);
repaint(this.parts.devices, devicesPart(this), quiet);
+47 -8
View File
@@ -5,6 +5,10 @@ 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';
@@ -163,8 +167,36 @@ function dataTile(page: PersonPage): HTMLElement {
type: 'button',
class: 'dl-chipbtn',
click: () => {
const v = prompt('Data limit in GB', p.quota_gb ? String(p.quota_gb) : '');
if (v != null && v.trim() !== '' && Number(v) > 0) void page.patch({ quota_gb: v.trim() }, `Data limit ${v.trim()} GB`);
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',
@@ -249,20 +281,27 @@ function hoursTile(page: PersonPage): HTMLElement {
'aria-checked': hoursOn ? 'true' : 'false',
class: `dl-switch${hoursOn ? ' on' : ''}`,
'aria-label': 'Limit hours',
click: () => page.patch({ hours: hoursOn ? '' : '07:00-23:00' }, hoursOn ? 'Any time' : 'Allowed 07:00–23:00'),
// 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'),
);
return E('div', { class: 'dl-tile2' }, [
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'),
E('span', {}, hoursOn ? `${h1} – ${h2} (router time)` : 'Any time'),
]),
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 {
+176 -29
View File
@@ -12,13 +12,13 @@ import { cancelButton, closeModal, confirmDialog, modal } from '../ui/modal';
import { copyText } from '../ui/files';
import { attempt, errorText, notify } from '../ui/toast';
import { input, seg, sw } from '../ui/controls';
import { card, group, liveRow, needRow, row } from '../ui/layout';
import { portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
import { card, firstBad, group, liveRow, needRow, row } from '../ui/layout';
import { dnsHelp, endpointProbe, hostHelp, nameHelp, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
import { icon } from '../../shared/icons';
import { duration } from '../../shared/format';
import { ago, duration } from '../../shared/format';
import { accessCards } from '../interfaces';
import { checkAccess, whoReaches } from '../access';
import { methodPicker, type Method } from '../disguise';
import { defaultMethod, methodPicker } from '../disguise';
import { coreOf } from '../cores';
import { installAwg } from '../pkgs';
import { createPoller, focusInside, repaint, type Poller } from '../state/poller';
@@ -299,7 +299,7 @@ export class ServerPage {
{ type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address', click: () => copyText(addr, 'Address copied') },
[icon('globe'), E('span', { class: 'dl-mono' }, addr), icon('copy')],
),
part('tunnel', [E('span', { class: 'dl-mono' }, `${coreOf(srv).label} :${srv.port}`)]),
part(coreOf(srv).id === 'awg' ? 'amneziawg' : 'tunnel', [E('span', { class: 'dl-mono' }, `${coreOf(srv).label} :${srv.port}`)]),
srv.up ? part('clock', [`up ${duration(srv.uptime)}`]) : '',
]),
// The reason the tunnel can't run at all ("can't use the network interface awg0: it exists and isn't Dawnline's").
@@ -318,7 +318,7 @@ export class ServerPage {
const dns = input(srv.dns.join(', '), { placeholder: 'This router (recommended)', class: 'cbi-input-text dl-mono' });
const people = this.st.people.filter((p) => p.server === srv.id).length;
const toggle = button(
srv.enabled ? 'Turn off' : 'Turn on',
[icon(srv.enabled ? 'pause' : 'play'), srv.enabled ? ' Turn off' : ' Turn on'],
async () => {
if (
srv.enabled &&
@@ -334,24 +334,51 @@ export class ServerPage {
},
srv.enabled ? 'negative' : 'positive',
);
const portalHost = this.st.settings.portal_host;
const nameRow = liveRow('Name', name, () => nameHelp(name.value, [], 'Shown to people in their portal and apps.'));
// Where the address points is checked on the router as it is typed (debounced).
const ep = endpointProbe(
() => ({ host: endpoint.value, port: srv.port, id: srv.id }),
(h, id, port) => api.endpointProbe(h, id, port),
() => epRow.refresh(),
{ empty: portalHost ? `Empty = the portal’s address (${portalHost}).` : 'Empty = the portal’s address.' },
);
const epRow = liveRow('Public address', endpoint, ep.help);
endpoint.addEventListener('input', ep.schedule);
ep.schedule();
const reached = srv.reached
? `Reached from the internet ${ago(srv.reached, this.st.now)}.`
: 'Never reached from the internet yet — test with a phone on mobile data.';
const dnsRow = liveRow('DNS for devices', dns, () => dnsHelp(dns.value, srv.address));
return E('div', { class: 'dl-stack gap16' }, [
card(
'Connection',
[
E('p', { class: 'dl-muted' }, 'The name people see, where devices find the router, and DNS. The port is on AmneziaWG.'),
group('router', 'Server', 'What people see', [row('Name', name, 'Shown to people in their portal and apps.')]),
group('globe', 'Devices connect to', 'Where the router answers from the internet', [
row(
'Public address',
endpoint,
'Hostname or IP of the router on the internet. A DDNS name keeps links working when your IP changes. It must not go through Cloudflare: use a DNS-only name or an IP.',
),
]),
group('file', 'For every device', 'Changing it marks devices “Update config” until they import again', [
row('DNS for devices', dns, 'Empty = this router, which sends each query where your home network would.'),
]),
group('router', 'Server', 'What people see', [nameRow]),
group(
'globe',
'Devices connect to',
'A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)',
[epRow, E('div', { class: `dl-sub ${srv.reached ? 'ok' : 'warn'}` }, reached)],
),
group('file', 'For every device', 'Changing it marks devices “Update config” until they import again', [dnsRow]),
],
[
E('span'),
button(
'Save',
() => {
const bad = firstBad([nameRow, epRow, dnsRow]);
if (bad) {
notify(bad, 'warning');
return;
}
return this.save(srv, { name: name.value, endpoint: endpoint.value, dns: dns.value });
},
'positive',
),
],
[E('span'), button('Save', () => this.save(srv, { name: name.value, endpoint: endpoint.value, dns: dns.value }), 'positive')],
),
card(
'Danger zone',
@@ -369,6 +396,21 @@ export class ServerPage {
]),
E('div', { class: 'dl-setrow-ctl' }, toggle),
]),
E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-setrow-label' }, 'Change the tunnel network'),
E(
'span',
{ class: 'dl-sub' },
`Devices have ${rangeOf(srv.subnet)}.x addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again.`,
),
]),
E(
'div',
{ class: 'dl-setrow-ctl' },
button([icon('edit'), ' Change'], () => this.changeSubnet(srv), 'negative'),
),
]),
E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-setrow-label' }, 'Remove server'),
@@ -434,6 +476,55 @@ export class ServerPage {
);
}
/** A new tunnel network: checked as you type against the router's networks, then every device renumbered. */
async changeSubnet(srv: Server) {
const taken = await attempt(() => api.serverPorts(srv.id));
if (!taken) return;
const nets = taken.networks ?? [];
const devices = this.st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0);
const range = input(rangeOf(srv.subnet), { class: 'cbi-input-text dl-mono dl-w-range' });
const rangeRow = liveRow('Address range', range, () => rangeHelp(range.value, nets, ''));
modal(
'Change the tunnel network',
[
rangeRow,
E(
'p',
{ class: 'dl-muted' },
devices
? `${devices} device${devices === 1 ? ' gets a new address and stops' : 's get new addresses and stop'} connecting until ${devices === 1 ? 'it imports its' : 'they import their'} configuration again (from their personal link or from you).`
: 'No devices on this server yet: nothing else changes.',
),
],
[
cancelButton(),
' ',
button(
'Change',
async () => {
const h = rangeRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
const subnet = subnetOf(range.value);
if (subnet === srv.subnet) {
closeModal();
return;
}
if (await attempt(() => api.serverUpdate(srv.id, { subnet }), 'Tunnel network changed')) {
closeModal();
if (devices) notify('Devices are marked “Update config” until they import again.', 'info', 6000);
await this.refresh();
}
},
'negative',
),
],
);
setTimeout(() => range.select(), 50);
}
async remove(srv: Server) {
const people = this.st.people.filter((p) => p.server === srv.id);
modal(
@@ -477,7 +568,7 @@ export class ServerPage {
port: d.port,
// The tunnel's first three numbers ("10.77.0"): it is that /24.
range: rangeOf(d.subnet),
preset: 'standard' as Method,
preset: defaultMethod(d.awg),
// Off by default: the portal opens a port on WAN, so it is a choice.
portal: false,
portal_port: d.portal_port || 8443,
@@ -489,7 +580,45 @@ export class ServerPage {
// The portal takes the server's port number (TCP beside UDP) until it is changed by hand.
let portalSame = !extra && state.portal_port === state.port;
const ipLinks = () => /^\d{1,3}(\.\d{1,3}){3}$/.test(state.endpoint);
const portHelpNow = () => portHelp(state.port, d.udp_taken ?? [], 'Opened on the WAN firewall automatically.');
const portHelpNow = () =>
portHelp(
state.port,
d.udp_taken ?? [],
`Opened on the WAN firewall automatically.${state.port === 4500 ? ' 4500 is IPsec’s port: most networks let it through.' : ''}`,
);
const FROM: Record<string, string> = {
ddns: 'From your DDNS name.',
cert: 'From your Let’s Encrypt certificate.',
wan: 'Your WAN address now — it may change; a DDNS name is better.',
portal: 'The portal’s address.',
};
const ep = endpointProbe(
() => ({ host: state.endpoint, port: state.port }),
(h, _id, port) => api.endpointProbe(h, '', port),
() => epRow?.refresh(),
{ idle: () => (state.endpoint === d.endpoint && d.endpoint_from ? (FROM[d.endpoint_from] ?? '') : '') },
);
let epRow: ReturnType<typeof liveRow> | null = null;
// Nobody on the internet reaches a private or CGNAT address: say it before the first step.
const wanNote =
d.wan_kind === 'cgnat' || d.wan_kind === 'private'
? needRow(
'alert',
'warn',
d.wan_kind === 'cgnat' ? 'Your router has no public address (CGNAT)' : `Your router is behind another router (WAN ${d.wan_ip})`,
d.wan_kind === 'cgnat'
? 'The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address.'
: 'Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here.',
'',
)
: '';
const restartNote =
d.awg_state?.tools && d.awg_state.handler === false
? E('div', { class: 'dl-note warn' }, [
icon('alert'),
E('span', {}, 'Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'),
])
: '';
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
const portalHelpNow = () => portalPortHelp(state.portal_port, d.tcp_taken ?? [], ipLinks());
const root = E('div', { class: 'dl-wizard' });
@@ -513,18 +642,36 @@ export class ServerPage {
E(
'p',
{ class: 'dl-muted' },
'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
extra
? 'One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page.'
: 'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
),
group('router', 'Server', 'What people see', [row('Name', field('name'), 'Shown to people in their portal and apps.')]),
group('globe', 'Devices connect to', 'Where the router answers from the internet', [
row(
'Public address',
field('endpoint', { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' }),
'Hostname or IP address of your router on the internet. Not through Cloudflare: use a DNS-only name or an IP.',
),
group('router', 'Server', 'What people see', [
liveRow('Name', field('name'), () => nameHelp(state.name, [], 'Shown to people in their portal and apps.')),
]),
group(
'globe',
'Devices connect to',
'A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT',
[
(() => {
const el = field('endpoint', { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' });
epRow = liveRow('Public address', el, ep.help);
el.addEventListener('input', ep.schedule);
ep.schedule();
return epRow;
})(),
],
),
wanNote,
restartNote,
]),
check: () => (!state.endpoint ? 'Fill in the public address.' : null),
check: () => {
const n = nameHelp(state.name);
if (n.bad) return `Name: ${n.text}`;
const h = hostHelp(state.endpoint, state.port);
return h.bad ? `Public address: ${h.text}` : null;
},
};
const awgPage: Page = {
id: 'awg',
+30 -18
View File
@@ -3,7 +3,9 @@
import { E } from '../../e';
import { button } from '../../ui/button';
import { input, isOn, sw } from '../../ui/controls';
import { row } from '../../ui/layout';
import { firstBad, liveRow } from '../../ui/layout';
import { notify } from '../../ui/toast';
import { domainHelp, fallbackDnsHelp, limitHelp } from '../../netcheck';
import { section, type SettingsHost } from './common';
export function defaultsCard(host: SettingsHost): HTMLElement {
@@ -17,28 +19,37 @@ export function defaultsCard(host: SettingsHost): HTMLElement {
inputmode: 'decimal',
class: 'cbi-input-text dl-w-ip dl-mono',
});
const limitRow = liveRow('Devices per person', limit, () => {
// Empty keeps the default (the router stores nothing then).
if (!limit.value.trim()) return { text: 'The default, 3. Pre-filled when you add someone.', bad: false };
const h = limitHelp(limit.value);
return h.bad ? h : { text: 'Pre-filled when you add someone.', bad: false };
});
const domainRow = liveRow(
'Device hostnames',
domain,
() => domainHelp(domain.value),
E('div', { class: 'dl-hostport' }, [hn, E('span', { class: 'dl-faint dl-mono' }, 'phone.myata.'), domain]),
);
const fallbackRow = liveRow('Fallback DNS', fallback, () => {
const h = fallbackDnsHelp(fallback.value);
return h.bad ? h : { text: `For Home-only devices using home names: ${h.text}`, bad: false };
});
return section(
'defaults',
'Defaults',
[
row('Devices per person', limit, 'Pre-filled when you add someone.'),
row(
'Device hostnames',
E('div', { class: 'dl-hostport' }, [hn, E('span', { class: 'dl-faint dl-mono' }, 'phone.myata.'), domain]),
'Name devices in your home DNS.',
),
row(
'Fallback DNS',
fallback,
'For Home-only devices using home names: the second DNS server, used by the device when the tunnel is down. Empty = none.',
),
],
'New people',
[limitRow, domainRow, fallbackRow],
[
E('span'),
button(
'Save',
() =>
host.save(
() => {
const bad = firstBad([limitRow, domainRow, fallbackRow]);
if (bad) {
notify(bad, 'warning');
return;
}
return host.save(
{
default_device_limit: limit.value,
hostnames: isOn(hn) ? '1' : '0',
@@ -47,7 +58,8 @@ export function defaultsCard(host: SettingsHost): HTMLElement {
},
'Saved',
'defaults',
),
);
},
'positive',
),
],
+15 -14
View File
@@ -6,8 +6,8 @@ import { E } from '../../e';
import { button } from '../../ui/button';
import { cancelButton, closeModal, modal } from '../../ui/modal';
import { input, isOn, sw } from '../../ui/controls';
import { group, liveRow, needRow, row } from '../../ui/layout';
import { portalPortHelp } from '../../netcheck';
import { firstBad, group, liveRow, needRow, row } from '../../ui/layout';
import { hostHelp, portalPortHelp, titleHelp, urlHelp } from '../../netcheck';
import { icon } from '../../../shared/icons';
import { fmtDay } from '../../../shared/format';
import { installMissing } from '../../pkgs';
@@ -132,6 +132,12 @@ export function portalCard(host: SettingsHost): HTMLElement {
button('Add', () => {
const h = other.value.trim().toLowerCase();
if (!h) return;
// The router would refuse it on Save: say so here.
const check = hostHelp(h);
if (check.bad) {
notify(check.text, 'warning');
return;
}
addRow(h);
if (!picked.includes(h)) picked = [...picked, h];
other.value = '';
@@ -273,6 +279,8 @@ export function portalCard(host: SettingsHost): HTMLElement {
portalPortHelp(port.value.trim() === '' ? eff.portal_port : Number(port.value), host.d.tcp_taken ?? [], picked.some(isIp)),
);
refreshPort = listenRow.refresh;
const titleRow = liveRow('Title', title, () => titleHelp(title.value));
const redirectRow = liveRow('Unknown links', redirect, () => urlHelp(redirect.value));
const custom = !!(s.portal_cert && s.portal_key);
const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt';
const certFiles = () => {
@@ -363,10 +371,7 @@ export function portalCard(host: SettingsHost): HTMLElement {
E('span', { class: 'dl-muted' }, 'A page where each person adds and manages their devices with their personal link.'),
httpsRow ? E('div', { class: 'dl-list' }, [httpsRow]) : '',
group('network', 'Port', 'How the portal listens (80 and 443 stay free)', [listenRow]),
group('edit', 'Appearance', 'What people see', [
row('Title', title, 'Shown at the top of the portal.'),
row('Unknown links', redirect, 'Where a wrong or old link goes, for example your website. Empty shows a plain “Not found”.'),
]),
group('edit', 'Appearance', 'What people see', [titleRow, redirectRow]),
group('link', 'Addresses', 'Pick one or more; the first is the main link', [
opts,
E('div', { class: 'dl-stack gap8' }, [
@@ -382,14 +387,10 @@ export function portalCard(host: SettingsHost): HTMLElement {
button(
'Save',
() => {
// The port's help line already says what is wrong: do not send it anyway.
const h = portalPortHelp(
port.value.trim() === '' ? eff.portal_port : Number(port.value),
host.d.tcp_taken ?? [],
picked.some(isIp),
);
if (h.bad) {
notify(`Listening port: ${h.text}`, 'warning');
// The help lines already say what is wrong: do not send it anyway.
const bad = firstBad([listenRow, titleRow, redirectRow]);
if (bad) {
notify(bad, 'warning');
return;
}
return host.save(
+13 -3
View File
@@ -6,6 +6,8 @@ import { E } from '../../e';
import { button } from '../../ui/button';
import { chipToggle, input, isOn, seg, setChip, sw } from '../../ui/controls';
import { row } from '../../ui/layout';
import { notify } from '../../ui/toast';
import { timeHelp } from '../../netcheck';
import { section, type SettingsHost } from './common';
const TARGET: [string, string][] = [
@@ -99,8 +101,15 @@ export function updatesCard(host: SettingsHost): HTMLElement {
E('span', { class: 'dl-sub' }, 'Run a check or an update by hand in Components.'),
button(
'Save',
() =>
host.save(
() => {
if (mode.dataset.value === 'scheduled') {
const h = timeHelp(at.value);
if (h.bad) {
notify(`Time: ${h.text}`, 'warning');
return;
}
}
return host.save(
{
update_check: isOn(check) ? '1' : '0',
update_interval: every.dataset.value!,
@@ -113,7 +122,8 @@ export function updatesCard(host: SettingsHost): HTMLElement {
},
'Saved',
'updates',
),
);
},
'positive',
),
],
+3
View File
@@ -16,6 +16,9 @@
/* dialogs */
.dl-modal .cbi-tabmenu { margin-bottom: 16px; }
/* A dialog field checked as you type: its help under the label, as on the cards. */
.dl-modal .cbi-value.dl-live > .cbi-value-title { display: flex; flex-direction: column; gap: 2px; text-align: left; }
.dl-modal .cbi-value.dl-live > .cbi-value-title > .dl-sub { white-space: normal; }
/* A list of things to tick (devices to remove with an old link). */
.dl-checklist { display: flex; flex-direction: column; gap: 6px; margin: 4px 0 8px; }
.dl-checklist label { display: flex; align-items: center; gap: 8px; font-size: 14px; cursor: pointer; }
+3
View File
@@ -56,3 +56,6 @@
.cbi-value.dl-block { display: block !important; }
.cbi-value.dl-block > .cbi-value-title { display: block; width: auto; float: none; text-align: left; padding: 0 0 8px; }
.cbi-value.dl-block > .cbi-value-field { display: block; width: 100%; margin: 0; }
/* Find (shown once the list is long): a compact search field beside the sort. */
.dl-people-find { width: 160px; min-width: 0; }
.dl-people-find[hidden] { display: none; }
+18 -3
View File
@@ -49,13 +49,28 @@ export function accessBadge(p: Person): HTMLElement {
return el;
}
/** Why a person's devices cannot connect right now, in two words. */
const STOPPED: Partial<Record<Person['state'], string>> = {
paused: 'Paused',
expired: 'Access ended',
quota: 'Data limit',
hours: 'Outside hours',
server_off: 'Server off',
no_server: 'No server',
};
/**
* A device's status as coloured text, no dots (only avatars carry one). `now`
* is the router's clock; `waiting` is the text before the first connection.
* With the person, a device that cannot come back says why ("Paused",
* "Data limit") instead of a "Last seen" that reads like it might.
*/
export function deviceStatus(d: Device, now?: number, waiting = 'Not set up yet'): HTMLElement {
if (d.disabled) return E('span', { class: 'dl-dstat' }, 'Disabled');
export function deviceStatus(d: Device, now?: number, waiting = 'Not set up yet', p?: Person): HTMLElement {
const seen = d.handshake ? `Last seen ${ago(d.handshake, now)} · ${new Date(d.handshake * 1000).toLocaleString()}` : '';
if (d.disabled) return E('span', { class: 'dl-dstat', title: seen }, 'Disabled');
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
const why = p && STOPPED[p.state];
if (why) return E('span', { class: 'dl-dstat warn', title: seen || 'Not connected yet' }, why);
if (!d.handshake) return E('span', { class: 'dl-dstat warn', title: 'Waiting for the first connection' }, waiting);
return E('span', { class: 'dl-dstat' }, `Last seen ${ago(d.handshake, now)}`);
return E('span', { class: 'dl-dstat', title: new Date(d.handshake * 1000).toLocaleString() }, `Last seen ${ago(d.handshake, now)}`);
}
+10 -2
View File
@@ -3,7 +3,13 @@
import { E } from '../e';
import { errorText, notify } from './toast';
export async function copyText(text: string, what = 'Copied to clipboard') {
/**
* Copy to the clipboard and say so. `quiet`: a copy that is a convenience
* after something else (a link right after creating a person): browsers
* refuse a write outside the click that started it (Safari after an await),
* and then nothing is said — the link is on screen with its own Copy button.
*/
export async function copyText(text: string, what = 'Copied to clipboard', quiet = false): Promise<boolean> {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
@@ -16,8 +22,10 @@ export async function copyText(text: string, what = 'Copied to clipboard') {
if (!ok) throw new Error('Copying is blocked here. Select the text and copy it by hand.');
}
notify(what, 'success', 2500);
return true;
} catch (e) {
notify(errorText(e), 'error');
if (!quiet) notify(errorText(e), 'error');
return false;
}
}
+49 -2
View File
@@ -23,8 +23,8 @@ export function liveRow(
el: HTMLInputElement,
help: () => { text: string; bad: boolean },
control: Node = el,
): HTMLElement & { refresh: () => void } {
const r = row(label, control, ' ') as HTMLElement & { refresh: () => void };
): HTMLElement & { refresh: () => void; help: () => { text: string; bad: boolean } } {
const r = row(label, control, ' ') as HTMLElement & { refresh: () => void; help: () => { text: string; bad: boolean } };
const sub = r.querySelector('.dl-sub') as HTMLElement;
const paint = () => {
const h = help();
@@ -34,10 +34,57 @@ export function liveRow(
};
el.addEventListener('input', paint);
r.refresh = paint;
r.help = help;
paint();
return r;
}
/**
* liveRow for a dialog field (LuCI's cbi-value layout: label beside the
* control, the help under the label as on the cards). Same contract: `help`
* repaints on input, `refresh()` when something else changes.
*/
export function liveField(
label: string,
el: HTMLInputElement | HTMLSelectElement,
help: () => { text: string; bad: boolean },
control: Node = el,
): HTMLElement & { refresh: () => void; help: () => { text: string; bad: boolean } } {
const sub = E('div', { class: 'dl-sub' });
const r = E('div', { class: 'cbi-value dl-live' }, [
E('div', { class: 'cbi-value-title' }, [E('label', {}, label), sub]),
E('div', { class: 'cbi-value-field' }, control),
]) as HTMLElement & { refresh: () => void; help: () => { text: string; bad: boolean } };
const paint = () => {
const h = help();
sub.textContent = h.text;
sub.classList.toggle('bad', h.bad);
el.classList.toggle('cbi-input-invalid', h.bad);
};
el.addEventListener('input', paint);
el.addEventListener('change', paint);
r.refresh = paint;
r.help = help;
paint();
return r;
}
/** The first problem among live rows (their help as it stands), or null: what refuses a Save. */
export function firstBad(
rows: { help?: () => { text: string; bad: boolean } }[],
helps: (() => { text: string; bad: boolean })[] = [],
): string | null {
for (const r of rows) {
const h = r.help?.();
if (h?.bad) return h.text;
}
for (const f of helps) {
const h = f();
if (h.bad) return h.text;
}
return null;
}
/** A section card with its own footer (Save etc.). */
export function card(title: string, body: (Node | string)[], foot: (Node | string)[], extra = ''): HTMLElement {
return E('section', { class: `dl-setsec ${extra}` }, [
+16 -1
View File
@@ -53,7 +53,22 @@ export function dropdown(anchor: HTMLElement, items: (MenuItem | null)[]) {
if (!menu.contains(ev.target as Node) && !anchor.contains(ev.target as Node)) close();
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === 'Escape') close();
if (ev.key === 'Escape' || ev.key === 'Tab') return close();
// Arrow keys walk the items (wrapping), Home/End jump; a menu that has the
// keyboard focus must not scroll the page under it.
const items = [...menu.querySelectorAll<HTMLButtonElement>('button:not([disabled])')];
if (!items.length || !['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(ev.key)) return;
ev.preventDefault();
const i = items.indexOf(document.activeElement as HTMLButtonElement);
const next =
ev.key === 'Home'
? 0
: ev.key === 'End'
? items.length - 1
: ev.key === 'ArrowDown'
? (i + 1) % items.length
: (i - 1 + items.length) % items.length;
items[next].focus({ preventScroll: true });
};
const offNav = onNavigate(close);
menu.dlAnchor = anchor;
+21 -1
View File
@@ -17,7 +17,27 @@ function settle(ok = false) {
export function modal(title: string, body: Child, actions: Child, cls = '') {
settle();
ui.showModal(title, [E('div', { class: `dl-modal ${cls}` }, body), E('div', { class: 'button-row' }, actions)]);
const bodyEl = E('div', { class: `dl-modal ${cls}` }, body);
const rowEl = E('div', { class: 'button-row' }, actions);
// Enter in a field submits: the dialog's positive button (buttons, selects
// and text areas keep their own Enter).
bodyEl.addEventListener('keydown', (ev: KeyboardEvent) => {
// Escape closes the dialog only: a drawer under it stays (it listens on the document).
if (ev.key === 'Escape') {
ev.preventDefault();
ev.stopPropagation();
closeModal();
return;
}
if (ev.key !== 'Enter' || ev.shiftKey || ev.ctrlKey || ev.metaKey || ev.altKey) return;
const t = ev.target as HTMLElement;
if (!t || ['TEXTAREA', 'BUTTON', 'SELECT', 'A'].includes(t.tagName)) return;
const go = rowEl.querySelector<HTMLButtonElement>('.cbi-button-positive');
if (!go || go.disabled) return;
ev.preventDefault();
go.click();
});
ui.showModal(title, [bodyEl, rowEl]);
}
export function closeModal() {
+7
View File
@@ -34,6 +34,13 @@ export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
el.addEventListener('mouseenter', show);
el.addEventListener('mousemove', show);
el.addEventListener('mouseleave', hideTip);
// No hover on a touch screen: a tap on the anchor shows it, the next tap
// anywhere (the document listener below) hides it.
el.addEventListener('pointerup', (ev: PointerEvent) => {
if (ev.pointerType === 'mouse') return;
if (anchor === el) hideTip();
else show(ev as unknown as MouseEvent);
});
}
onNavigate(hideTip);
+32
View File
@@ -0,0 +1,32 @@
// The portal's two DOM builders: an element from a tag, attributes and
// children, and an icon. No framework; shared by the page (main.ts) and the
// pieces drawn outside it (waitpath.ts).
import { iconSvg } from '../shared/icons';
export type Attrs = Record<string, string | number | boolean | EventListener | null | undefined>;
export type Kid = Node | string | null | undefined | false | Kid[];
export function h(tag: string, attrs: Attrs = {}, ...kids: Kid[]): HTMLElement {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v == null || v === false) continue;
if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v as EventListener);
else if (k === 'class') el.className = String(v);
else if (v === true) el.setAttribute(k, '');
else el.setAttribute(k, String(v));
}
const add = (c: Kid) => {
if (c == null || c === false) return;
if (Array.isArray(c)) c.forEach(add);
else el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
};
kids.forEach(add);
return el;
}
export function ic(name: string): HTMLElement {
const s = h('span', { class: 'ic' });
s.innerHTML = iconSvg(name, 'ic-svg');
return s;
}
+1129 -216
View File
File diff suppressed because it is too large. Load diff
+496
View File
@@ -0,0 +1,496 @@
// Portal motion: the moves between two states the DOM alone would snap
// between — a sheet's height following its content, cards that changed place
// after a repaint, a pane swapped for another, a sheet pulled down, a copy
// button saying it worked. This module measures and starts them; the curves,
// durations and every one-shot keyframe live in portal.css ("Motion").
//
// Everything checks `calm()` (prefers-reduced-motion) and then only fades.
// The pure decisions (rubber band, when a pull dismisses) are exported for tests.
/** The visitor asked for less motion: fades only, nothing travels. */
export const calm = (): boolean => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
/** The curves of portal.css, for animations started from script. */
const EASE = {
out: 'cubic-bezier(0.23, 1, 0.32, 1)',
in: 'cubic-bezier(0.55, 0, 1, 0.45)',
drawer: 'cubic-bezier(0.32, 0.72, 0, 1)',
};
/**
* A block inside a sheet animating its own height: the sheet's edge follows it
* frame by frame on its own, so followHeight holds off meanwhile (a count:
* several such blocks may move at once).
*/
function hold(el: Element): () => void {
const panel = el.closest<HTMLElement>('.sheet-panel');
if (!panel) return () => undefined;
panel.dataset.hold = String(+(panel.dataset.hold ?? 0) + 1);
return () => {
const n = +(panel.dataset.hold ?? 1) - 1;
if (n > 0) panel.dataset.hold = String(n);
else delete panel.dataset.hold;
};
}
/** Distance past an edge → how far it actually goes: resistance grows with the pull. */
export function rubber(dist: number, dim: number): number {
return dist <= 0 || dim <= 0 ? 0 : (1 - 1 / ((dist * 0.55) / dim + 1)) * dim;
}
/**
* Does a pulled sheet go away? A flick down (px/ms, as Vaul) or a pull past a
* third of its height does; a flick back up keeps it, however far it went.
*/
export function dismisses(dy: number, velocity: number, height: number): boolean {
if (dy <= 0 || velocity < -0.1) return false;
return velocity > 0.4 || dy > height / 3;
}
/** A height change takes longer the further it goes, inside the house range. */
export const morphMs = (dist: number): number => Math.round(Math.min(380, Math.max(220, 200 + dist * 0.35)));
/** Restart a one-shot CSS animation class on an element that already had it. */
export function replay(el: Element, cls: string) {
el.classList.remove(cls);
void (el as HTMLElement).offsetWidth;
el.classList.add(cls);
}
/**
* Keep `panel`'s size following `content`: whatever changes inside (a tab, a
* fold, a whole new sheet), the panel eases from the height it shows to the new
* one instead of jumping. Interruptible: a change mid-way starts from where it
* is. A width change (a window resize) only records, unless the panel asked for
* it (`data-morph="width"`: a question turning into a sheet), and then width
* and height morph together. Returns the stop.
*/
export function followHeight(panel: HTMLElement, content: HTMLElement): () => void {
let lastH = 0,
lastW = 0,
widthToo = false;
let anim: Animation | null = null;
const ro = new ResizeObserver(() => {
// Something inside moves its own height (hold): only keep up with the size.
if (panel.dataset.hold) {
anim?.cancel();
panel.classList.remove('morphing', 'morphing-w');
lastH = panel.offsetHeight;
lastW = panel.offsetWidth;
return;
}
const cs = getComputedStyle(panel);
const shownH = anim ? parseFloat(cs.height) : lastH;
const shownW = anim ? parseFloat(cs.width) : lastW;
anim?.cancel();
// Measure the natural size: without the uncapped width of a morph still under way.
panel.classList.remove('morphing', 'morphing-w');
const h = panel.offsetHeight,
w = panel.offsetWidth;
// Asked now, or still on its way from an earlier ask.
const asked = panel.dataset.morph === 'width' || widthToo;
delete panel.dataset.morph;
const resized = lastW !== 0 && w !== lastW;
lastH = h;
lastW = w;
if (!shownH || calm() || (resized && !asked)) return;
const dh = Math.abs(h - shownH),
dw = asked ? Math.abs(w - shownW) : 0;
if (dh < 2 && dw < 2) return;
widthToo = dw >= 2;
panel.classList.add('morphing');
panel.classList.toggle('morphing-w', widthToo);
const a = panel.animate(
widthToo
? [
{ height: `${shownH}px`, width: `${shownW}px` },
{ height: `${h}px`, width: `${w}px` },
]
: [{ height: `${shownH}px` }, { height: `${h}px` }],
{ duration: morphMs(Math.max(dh, dw)), easing: EASE.out },
);
anim = a;
const done = () => {
if (anim !== a) return;
anim = null;
widthToo = false;
panel.classList.remove('morphing', 'morphing-w');
};
a.onfinish = done;
a.oncancel = done;
});
ro.observe(content);
return () => ro.disconnect();
}
/**
* Swap `box`'s content for `next`: the old content fades out where it was
* (lifted out of the flow, so the box already takes the new height) while the
* new one comes in. `dir` -1 / 1: the new content comes from the left / right.
*/
export function swap(box: HTMLElement, next: Node[], dir = 0) {
const old = [...box.childNodes];
if (!old.length || !box.isConnected) {
box.replaceChildren(...next);
return;
}
// The ghost lays the old content out as the box did, over the box's padding edge.
const cs = getComputedStyle(box);
const ghost = document.createElement('div');
ghost.className = 'ghost';
ghost.setAttribute('aria-hidden', 'true');
ghost.inert = true;
Object.assign(ghost.style, {
display: cs.display === 'flex' ? 'flex' : 'block',
flexDirection: cs.flexDirection,
alignItems: cs.alignItems,
gap: cs.gap,
top: cs.paddingTop,
left: cs.paddingLeft,
right: cs.paddingRight,
});
ghost.append(...old);
box.replaceChildren(ghost, ...next);
// The old content drops away fast (it sits under the new one, see .ghost) so the two never read together.
const still = calm();
const out = ghost.animate(
[
{ opacity: 1, transform: 'none' },
{ opacity: 0, transform: still ? 'none' : `translateX(${-dir * 8}px)` },
],
{ duration: 120, easing: EASE.out, fill: 'forwards' },
);
const drop = () => ghost.remove();
out.onfinish = drop;
out.oncancel = drop;
for (const n of next)
if (n instanceof HTMLElement)
n.animate(
still
? [{ opacity: 0 }, { opacity: 1 }]
: [
{ opacity: 0, transform: `translate(${dir * 12}px, ${dir ? 0 : 6}px)`, filter: 'blur(4px)' },
{ opacity: 1, transform: 'none', filter: 'blur(0)' },
],
{ duration: still ? 160 : 280, delay: 50, easing: EASE.out, fill: 'backwards' },
);
}
/** Play an element's way out before it is removed (it keeps its place until then). */
export function leave(el: Element | null | undefined): Promise<void> {
if (!el || !el.isConnected) return Promise.resolve();
const a = el.animate(
calm()
? [{ opacity: 1 }, { opacity: 0 }]
: [
{ opacity: 1, transform: 'none', filter: 'blur(0)' },
{ opacity: 0, transform: 'scale(0.96)', filter: 'blur(4px)' },
],
{ duration: 200, easing: EASE.in, fill: 'forwards' },
);
return a.finished.then(
() => undefined,
() => undefined,
);
}
/** A beat between the steps of a sequence; none when the visitor asked for less motion. */
export const beat = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, calm() ? 0 : ms));
/**
* The accordion's look: the height closes on the drawer curve over `ms`; the
* content dissolves faster, from the start, as blocks leave elsewhere (blur, a
* small rise and shrink, on the strong ease-out over `contentMs`).
*/
const FOLD = { ms: 520, contentMs: 300, blur: 4, drift: 6, scale: 0.98 };
/**
* Fold a block shut like an accordion and take it out: its height closes from
* the bottom edge (the sheet's edge comes with it) while its content dissolves
* into a blur. Less motion: it fades.
*/
export async function fold(el: HTMLElement): Promise<void> {
if (!el.isConnected) return;
const release = hold(el);
const gap = parseFloat(getComputedStyle(el.parentElement as HTMLElement).rowGap) || 0;
const h = el.offsetHeight;
el.style.overflow = 'hidden';
el.style.transformOrigin = '50% 0';
el.inert = true;
const done = () => undefined;
if (calm())
await el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 160, easing: EASE.out, fill: 'forwards' }).finished.then(done, done);
else {
el.animate(
[
{ opacity: 1, filter: 'blur(0px)', transform: 'none' },
{ opacity: 0, filter: `blur(${FOLD.blur}px)`, transform: `translateY(${-FOLD.drift}px) scale(${FOLD.scale})` },
],
{ duration: FOLD.contentMs, easing: EASE.out, fill: 'forwards' },
);
await el
.animate(
[
{ height: `${h}px`, marginTop: '0px' },
{ height: '0px', marginTop: `${-gap}px` },
],
{ duration: FOLD.ms, easing: EASE.drawer, fill: 'forwards' },
)
.finished.then(done, done);
}
el.remove();
release();
}
/**
* The opposite, for a line that just got something to say: it opens from no
* height to its own (the sheet's edge comes with it) and comes into focus.
*/
export function grow(el: HTMLElement) {
if (!el.isConnected || calm()) return replay(el, 'swap');
const release = hold(el);
const gap = parseFloat(getComputedStyle(el.parentElement as HTMLElement).rowGap) || 0;
const h = el.offsetHeight;
el.style.overflow = 'hidden';
const a = el.animate(
[
{ height: '0px', marginTop: `${-gap}px`, opacity: 0, filter: 'blur(4px)' },
{ height: `${h}px`, marginTop: '0px', opacity: 1, filter: 'blur(0px)' },
],
{ duration: 380, easing: EASE.drawer },
);
const end = () => {
el.style.overflow = '';
release();
};
a.onfinish = end;
a.oncancel = end;
}
/**
* The page's first paint: the blocks matching `selector` rise in, in reading
* order (top to bottom, then left to right, whatever the layout), at most
* eight steps apart. portal.css draws `.intro`; `--i` is the step.
*/
export function intro(root: ParentNode, selector: string) {
const els = [...root.querySelectorAll<HTMLElement>(selector)].map((el) => ({ el, r: el.getBoundingClientRect() }));
els.sort((a, b) => Math.round(a.r.top - b.r.top) || a.r.left - b.r.left);
els.forEach(({ el }, i) => {
el.style.setProperty('--i', String(Math.min(i, 8)));
el.classList.add('intro');
});
}
/** Where the keyed blocks of a page are and what its keyed values say, before a repaint. */
export interface Snap {
at: Map<string, { x: number; y: number }>;
text: Map<string, string>;
}
export function snap(root: ParentNode): Snap {
const at = new Map<string, { x: number; y: number }>();
const text = new Map<string, string>();
root.querySelectorAll<HTMLElement>('[data-key]').forEach((el) => {
const r = el.getBoundingClientRect();
at.set(el.dataset.key as string, { x: r.left + scrollX, y: r.top + scrollY });
});
root.querySelectorAll<HTMLElement>('[data-v]').forEach((el) => text.set(el.dataset.v as string, el.textContent ?? ''));
return { at, text };
}
/**
* After a repaint: a keyed block that moved glides from where it was (FLIP),
* one that is new rises in, a keyed value that changed comes into focus.
* Keyed blocks are never nested, so no move is counted twice.
*/
export function settle(root: ParentNode, before: Snap) {
const still = calm();
root.querySelectorAll<HTMLElement>('[data-key]').forEach((el) => {
const was = before.at.get(el.dataset.key as string);
if (!was) {
el.classList.add('enter');
return;
}
if (still) return;
const r = el.getBoundingClientRect();
const dx = was.x - (r.left + scrollX),
dy = was.y - (r.top + scrollY);
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return;
el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {
duration: morphMs(Math.hypot(dx, dy)),
easing: EASE.out,
});
});
root.querySelectorAll<HTMLElement>('[data-v]').forEach((el) => {
const was = before.text.get(el.dataset.v as string);
if (was != null && was !== el.textContent) el.classList.add('swap');
});
}
/**
* A repaint of a sheet's content that keeps its motion: keyed controls
* (`data-m`) that flipped on or off get `to-on` / `to-off`, whose keyframes
* start from the other look; one whose text changed comes into focus (`swap`);
* one marked `data-glide` that moved within its parent (a chip beside a chevron
* that went) glides there.
*/
export function restyle(root: ParentNode, paint: () => void) {
const state = (el: Element) => el.classList.contains('on') || el.classList.contains('open');
// What it says: its text, or `data-sig` where the text says nothing (a QR code).
const says = (el: HTMLElement) => el.dataset.sig ?? el.textContent ?? '';
const inParent = (el: HTMLElement) => {
const r = el.getBoundingClientRect(),
p = (el.parentElement as HTMLElement).getBoundingClientRect();
return { x: r.left - p.left, y: r.top - p.top };
};
const before = new Map<string, { on: boolean; says: string }>();
root.querySelectorAll<HTMLElement>('[data-m]').forEach((el) => before.set(el.dataset.m as string, { on: state(el), says: says(el) }));
const placed = new Map<string, { x: number; y: number }>();
root.querySelectorAll<HTMLElement>('[data-glide]').forEach((el) => placed.set(el.dataset.glide as string, inParent(el)));
paint();
if (!calm())
root.querySelectorAll<HTMLElement>('[data-glide]').forEach((el) => {
const was = placed.get(el.dataset.glide as string);
if (!was) return;
const now = inParent(el);
const dx = was.x - now.x,
dy = was.y - now.y;
if (Math.abs(dx) >= 1 || Math.abs(dy) >= 1)
el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { duration: 280, easing: EASE.out });
});
root.querySelectorAll<HTMLElement>('[data-m]').forEach((el) => {
const was = before.get(el.dataset.m as string);
if (!was) return;
if (was.on !== state(el)) el.classList.add(state(el) ? 'to-on' : 'to-off');
else if (was.says !== says(el)) el.classList.add('swap');
});
}
/**
* A row of choices whose highlight slides to the one picked: a copy of the row
* drawn in the picked look on top, clipped to the picked button, so the colour
* changes exactly where the highlight is (clip-path tabs). The real buttons keep
* `.on`; call the returned function after changing it.
*/
export function slider(row: HTMLElement): () => void {
const hl = row.cloneNode(true) as HTMLElement;
hl.classList.add('slide-hl');
hl.setAttribute('aria-hidden', 'true');
hl.inert = true;
hl.removeAttribute('role');
hl.querySelectorAll('[role]').forEach((b) => b.removeAttribute('role'));
row.classList.add('slides');
row.appendChild(hl);
let placed = false;
const move = () => {
const on = row.querySelector<HTMLElement>(':scope > .on');
if (!on || !row.isConnected) return;
const w = row.clientWidth,
h = row.clientHeight;
const l = on.offsetLeft,
t = on.offsetTop;
hl.classList.toggle('placed', placed);
hl.style.clipPath = `inset(${t}px ${w - l - on.offsetWidth}px ${h - t - on.offsetHeight}px ${l}px round 999px)`;
placed = true;
};
// Fonts and the sheet's own layout settle after the first call: place it again, without a glide.
new ResizeObserver(() => {
placed = false;
move();
}).observe(row);
return move;
}
/** A copy button in its "Copied" moment: what to put back, and when. */
const COPIED = new WeakMap<HTMLElement, { timer: number; icon: string | null; label: string | null }>();
/**
* A copy button says it worked where the finger is: its icon turns into a
* check and a "Copy" label into "Copied", for a moment. Other labels (a host
* name on a chip) stay. `check` is the check icon's markup.
*/
export function copied(btn: HTMLElement | null | undefined, check: string) {
if (!btn) return;
const icon = btn.querySelector<HTMLElement>('.ic');
const label =
btn.querySelector<HTMLElement>('.badge-main') ??
btn.querySelector<HTMLElement>(':scope > span:not(.ic)') ??
(btn.children.length ? null : btn);
const was = COPIED.get(btn) ?? { timer: 0, icon: icon?.innerHTML ?? null, label: label?.textContent ?? null };
clearTimeout(was.timer);
const says = !!label && (label.classList.contains('badge-main') || /^copy$/i.test(was.label ?? ''));
const show = (svg: string | null, text: string | null) => {
if (icon && svg != null && icon.innerHTML !== svg) {
icon.innerHTML = svg;
replay(icon, 'swap-ic');
}
if (label && says && text != null && label.textContent !== text) {
label.textContent = text;
replay(label, 'swap');
}
};
show(check, 'Copied');
btn.classList.add('copied');
was.timer = window.setTimeout(() => {
COPIED.delete(btn);
btn.classList.remove('copied');
show(was.icon, was.label);
}, 1600);
COPIED.set(btn, was);
}
/** A button waiting for the router: after a beat (no flash on a quick answer) a spinner takes the label's place. */
export function busy(btn: HTMLElement): () => void {
const t = window.setTimeout(() => btn.classList.add('busy'), 250);
return () => {
clearTimeout(t);
btn.classList.remove('busy');
};
}
/**
* Let a bottom sheet be pulled down by its grab bar and head (a question: all of it): the panel
* follows the finger (with resistance upwards), the scrim fades with it, and
* on release it either goes (`close`) or springs back. Only while `bottom()`
* (the sheet sits at the bottom: phones). The release transitions start from
* the dragged spot because the inline transform and `.dragging` go together.
*/
export function pullToClose(panel: HTMLElement, scrim: HTMLElement, close: () => void, bottom: () => boolean) {
panel.addEventListener('pointerdown', (e) => {
const t = e.target as Element;
if (!bottom() || e.button !== 0 || !t.closest('.grab, .sheet-head, .ask') || t.closest('button, a, input')) return;
const y0 = e.clientY,
h = panel.offsetHeight;
let dy = 0;
const trail: { t: number; y: number }[] = [{ t: e.timeStamp, y: e.clientY }];
try {
panel.setPointerCapture(e.pointerId);
} catch {
/* a pointer the browser no longer tracks: the pull still follows while it is over the panel */
}
panel.classList.add('dragging');
const move = (ev: PointerEvent) => {
const raw = ev.clientY - y0;
dy = raw < 0 ? -rubber(-raw, h) : raw;
panel.style.transform = `translateY(${dy}px)`;
scrim.style.opacity = String(1 - Math.max(0, dy) / h);
trail.push({ t: ev.timeStamp, y: ev.clientY });
while (trail.length > 2 && ev.timeStamp - trail[0].t > 100) trail.shift();
};
const up = (ev: PointerEvent) => {
panel.removeEventListener('pointermove', move);
panel.removeEventListener('pointerup', up);
panel.removeEventListener('pointercancel', up);
const first = trail[0],
last = trail[trail.length - 1];
const v = last.t > first.t ? (last.y - first.y) / (last.t - first.t) : 0;
panel.classList.remove('dragging');
panel.style.transform = '';
scrim.style.opacity = '';
if (ev.type === 'pointerup' && dismisses(dy, v, h)) close();
};
panel.addEventListener('pointermove', move);
panel.addEventListener('pointerup', up);
panel.addEventListener('pointercancel', up);
});
}
+1112 -66
View File
File diff suppressed because it is too large. Load diff
+192
View File
@@ -0,0 +1,192 @@
// Setting up a device: which app, where it comes from, and whether the page
// is open on the device being set up. Pure: the sheet in main.ts draws it.
import type { Kind } from '../shared/types';
export type Platform = 'ios' | 'android' | 'windows' | 'mac' | 'linux' | 'unknown';
export type AppId = 'vpn' | 'awg' | 'wg';
/** The server's disguise generation as the portal sees it. */
export type Preset = 'off' | 'balanced' | 'max' | 'legacy';
export const APP_NAME: Record<AppId, string> = { vpn: 'AmneziaVPN', awg: 'AmneziaWG', wg: 'WireGuard' };
/** The platform the page is open on. iPadOS Safari calls itself a Mac; touch points tell. */
export function platformOf(ua: string, touchPoints = 0): Platform {
if (/iPhone|iPad|iPod/.test(ua)) return 'ios';
if (/Macintosh/.test(ua) && touchPoints > 1) return 'ios';
if (/Android/.test(ua)) return 'android';
if (/Windows/.test(ua)) return 'windows';
if (/Mac OS X|Macintosh/.test(ua)) return 'mac';
if (/CrOS/.test(ua)) return 'unknown';
if (/Linux|X11/.test(ua)) return 'linux';
return 'unknown';
}
/** A browser inside another app (Telegram, Instagram…): vpn:// and the share sheet do not work there. */
export const inWebview = (ua: string): boolean => /Telegram|FBAN|FBAV|Instagram|VKClient|Line\//i.test(ua);
/** Is the page open on the device being set up? A router never is; an unknown platform never counts. */
export function sameDevice(kind: Kind, platform: Platform): boolean {
if (kind === 'router' || platform === 'unknown') return false;
if (kind === 'phone' || kind === 'tablet') return platform === 'ios' || platform === 'android';
if (kind === 'computer') return platform === 'windows' || platform === 'mac' || platform === 'linux';
return true;
}
/** The systems a kind may run: a computer's is the person's call, the rest are read from the browser. */
export const osGroup = (kind: Kind): Platform[] => (kind === 'computer' || kind === 'other' ? ['windows', 'mac', 'linux'] : []);
export interface AppChoice {
id: AppId;
name: string;
/** The version this server needs, as "4.8.12" or ""; "current" when only the newest will do. */
need: string;
sub: string;
}
/** The apps that connect to a server with this disguise, the recommended one first. */
export function appsFor(preset: Preset): AppChoice[] {
const need = {
off: { vpn: '', awg: '' },
balanced: { vpn: '4.8.12', awg: '2.0' },
max: { vpn: 'current', awg: '3.1' },
legacy: { vpn: '', awg: '' },
}[preset];
const out: AppChoice[] = [
{ id: 'vpn', name: APP_NAME.vpn, need: need.vpn, sub: 'Connects from a link, no files' },
{ id: 'awg', name: APP_NAME.awg, need: need.awg, sub: 'The light client: a file or a QR code' },
];
if (preset === 'off') out.push({ id: 'wg', name: APP_NAME.wg, need: '', sub: 'Any WireGuard app: this server has no disguise' });
return out;
}
/** "This server needs AmneziaVPN 4.8.12 or newer. …", or "" when any version will do. */
export function updateLine(app: AppChoice): string {
if (!app.need) return '';
const what = app.need === 'current' ? `the current version of ${app.name}` : `${app.name} ${app.need} or newer`;
return `This server needs ${what}. Installed a while ago? Update it in the store.`;
}
export type Mark = 'appstore' | 'googleplay' | 'windows' | 'apple' | 'linux' | 'openwrt' | 'github' | 'site';
export interface Store {
href: string;
/** The small line and the bold line of the badge. */
top: string;
main: string;
mark: Mark;
/** A second source shown beside the first, where the store can fail (Android). */
alt?: { href: string; top: string; main: string; mark: Mark; why: string };
}
const GH_CLIENT = 'https://github.com/amnezia-vpn/amnezia-client/releases/latest';
const APK: NonNullable<Store['alt']> = {
href: GH_CLIENT,
top: 'APK file on',
main: 'GitHub',
mark: 'github',
why: 'The APK is for phones without Google Play, or where the store hides the app.',
};
/** Where the app comes from on a platform: the store first, the official GitHub release where no store has it. */
export function storeFor(app: AppId, platform: Platform): Store | null {
const S: Record<AppId, Partial<Record<Platform, Store>>> = {
vpn: {
ios: { href: 'https://apps.apple.com/app/amneziavpn/id1600529900', top: 'Download on the', main: 'App Store', mark: 'appstore' },
android: {
href: 'https://play.google.com/store/apps/details?id=org.amnezia.vpn',
top: 'Get it on',
main: 'Google Play',
mark: 'googleplay',
alt: APK,
},
windows: { href: GH_CLIENT, top: 'Official release on GitHub', main: 'Download for Windows', mark: 'windows' },
mac: { href: GH_CLIENT, top: 'Official release on GitHub', main: 'Download for Mac', mark: 'apple' },
linux: { href: GH_CLIENT, top: 'Official release on GitHub', main: 'Download for Linux', mark: 'linux' },
},
awg: {
ios: { href: 'https://apps.apple.com/us/app/amneziawg/id6478942365', top: 'Download on the', main: 'App Store', mark: 'appstore' },
android: {
href: 'https://play.google.com/store/apps/details?id=org.amnezia.awg',
top: 'Get it on',
main: 'Google Play',
mark: 'googleplay',
alt: { ...APK, href: 'https://github.com/amnezia-vpn/amneziawg-android/releases' },
},
windows: {
href: 'https://github.com/amnezia-vpn/amneziawg-windows-client/releases',
top: 'Official release on GitHub',
main: 'Download for Windows',
mark: 'windows',
},
mac: {
href: 'https://apps.apple.com/us/app/amneziawg/id6478942365',
top: 'Download on the',
main: 'Mac App Store',
mark: 'appstore',
},
linux: { href: 'https://github.com/amnezia-vpn/amneziawg-tools', top: 'On GitHub', main: 'amneziawg-tools', mark: 'linux' },
},
wg: {
ios: { href: 'https://apps.apple.com/app/wireguard/id1441195209', top: 'Download on the', main: 'App Store', mark: 'appstore' },
android: {
href: 'https://play.google.com/store/apps/details?id=com.wireguard.android',
top: 'Get it on',
main: 'Google Play',
mark: 'googleplay',
},
windows: { href: 'https://www.wireguard.com/install/', top: 'Download from', main: 'wireguard.com', mark: 'windows' },
mac: { href: 'https://apps.apple.com/app/wireguard/id1451685025', top: 'Download on the', main: 'Mac App Store', mark: 'appstore' },
linux: { href: 'https://www.wireguard.com/install/', top: 'Install from', main: 'wireguard.com', mark: 'linux' },
},
};
return S[app][platform] ?? null;
}
/** Where a router gets its client: OpenWrt packages. */
export const routerStore = (app: AppId): Store =>
app === 'wg'
? {
href: 'https://openwrt.org/docs/guide-user/services/vpn/wireguard/start',
top: 'OpenWrt packages',
main: 'wireguard-tools',
mark: 'openwrt',
}
: { href: 'https://openwrt.org/packages/start', top: 'OpenWrt packages', main: 'amneziawg-tools + kmod', mark: 'openwrt' };
/** Inside the app: where the scanner and the importer are. */
export const scanPath = (app: AppId): string =>
app === 'vpn' ? 'Add server → Scan QR' : app === 'awg' ? 'Add tunnel → Scan QR code' : 'Add tunnel → Create from QR code';
export const importPath = (app: AppId): string => (app === 'vpn' ? 'Add server → Insert key' : 'Add tunnel → Import from file');
export const PLATFORM_LABEL: Record<Platform, string> = {
ios: 'iPhone / iPad',
android: 'Android',
windows: 'Windows',
mac: 'Mac',
linux: 'Linux',
unknown: 'this device',
};
/**
* The personal link that opens straight on one device's set-up: the page then
* starts it by itself. In the fragment, which never reaches the router: the
* link stays the key, the device only says where to start.
*/
export const setupLink = (page: string, id: string): string => `${page}#setup=${id}`;
/** The device a link asks to set up (`#setup=d_…`), or null; anything else in the fragment is ignored. */
export function setupFromHash(hash: string): string | null {
return /^#setup=(d_[0-9a-f]{8})$/.exec(hash)?.[1] ?? null;
}
/**
* "the phone", "the computer": the device being set up, in a sentence. The
* sheet's title already names it; the lines under it do not repeat the name.
*/
export const deviceNoun = (kind: Kind): string =>
({ phone: 'phone', tablet: 'tablet', computer: 'computer', router: 'router', other: 'device' })[kind];
/** "This iPhone", "This Mac": the pill for the device in hand. */
export const hereLabel = (platform: Platform): string =>
({ ios: 'This iPhone', android: 'This phone', windows: 'This PC', mac: 'This Mac', linux: 'This PC', unknown: 'This device' })[platform];
+60
View File
@@ -0,0 +1,60 @@
// The set-up sheets' "waiting for the first connection" card: the way from
// the device (its icon; the sheet's title names it) to the home server, a light
// running along its dots while the page waits; the dots fill green when it connects.
// It only draws and switches its states; main.ts (watchFirstConnection)
// decides when, and what leaves around it. A live region: the changes are read out.
import type { Kind } from '../shared/types';
import { h, ic } from './dom';
import { grow, replay } from './motion';
export interface Way {
el: HTMLElement;
/** The first connection arrived. */
connected(): void;
/** The page stopped asking (ten minutes): say so instead of waiting on forever. */
gaveUp(): void;
}
export function waitPath(kind: Kind): Way {
const title = h('span', { class: 'strong s' }, 'Waiting for the connection');
// Nothing to add while it waits: the line comes with "You're all set" or the give-up.
const sub = h('span', { class: 'faint s' });
// The router end: the server's icon, as on the admin's map.
const home = h('span', { class: 'way-end home' }, ic('server'));
const el = h(
'div',
{ class: 'way', role: 'status', 'aria-live': 'polite' },
h(
'div',
{ class: 'way-row' },
h('span', { class: 'way-end' }, ic(kind)),
h('span', { class: 'way-track' }, h('span', { class: 'way-glow' }, h('i')), h('span', { class: 'way-fill' })),
home,
),
h('div', { class: 'way-text' }, title, sub),
);
const say = (t: string, s: string) => {
if (title.textContent !== t) {
title.textContent = t;
replay(title, 'swap');
}
if (sub.textContent === s) return;
// The line under the title only appears now: it opens rather than pushing the card.
const opens = !sub.textContent;
sub.textContent = s;
if (opens) grow(sub);
else replay(sub, 'swap');
};
return {
el,
connected: () => {
el.classList.add('done');
say('Connected', 'You’re all set.');
},
gaveUp: () => {
el.classList.add('stopped');
say('No connection yet', 'Close this and open it again to keep checking.');
},
};
}
+25
View File
@@ -26,6 +26,31 @@ const P: Record<string, string> = {
copy: '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/>',
download: '<path d="M12 4v11M7 10l5 5 5-5M5 20h14"/>',
link: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>',
// App logos: filled marks (the icon set is strokes), drawn at their 512 px art size and scaled to 24.
amnezia:
'<g fill="currentColor" stroke="none" transform="scale(.046875)"><path d="M511.8 185.5c.3.3.3.6 0 .6-2.2 1-4.5 2.2-6.7 3.2-17.3 7.7-33.6 16.6-47.7 29.4-4.8 4.5-9.3 9.3-13.1 14.4-3.8 4.8-5.1 10.9-5.1 17v.3c0 2.6 2.6 4.5 5.1 4.5h13.1c2.9 0 5.1 2.2 4.8 5.1-1 6.1-3.5 11.5-7.4 16.3-6.1 7.4-8.6 16-11.5 24.6-4.2 12.8-4.5 25.9-3.5 38.7 1 13.4-3.8 24.3-12.2 34.2-6.4 8-12.5 16-18.9 24s-9 17.3-8.3 27.5c1 13.1 4.2 25.9 7 39 2.2 10.6 3.2 21.4 4.5 32 .3 1.9-2.2 3.2-3.8 2.6s-3.2-1.3-4.8-2.2c-8-5.8-13.1-14.1-17-22.7-1.9-3.8-3.5-7.7-5.1-11.5-.6-1.3-1.6-2.2-2.9-2.6-3.5-1.6-5.4-2.9-6.7-5.1-1-1.9-2.9-3.2-4.8-3.2-7.7 0-15.7 1-23 3.5-14.7 5.1-29.1 9.9-43.5 15.7-16 6.1-32.6 7.4-49.3 5.4-16-1.9-31.7-5.4-47.7-8-5.4-1-10.6-1.3-16-2.2-1.3-.3-2.6-.6-3.8-1.3-9.6-4.8-19.2-9.6-28.8-14.1-10.6-4.8-18.6-1.3-22.4 9.3-1.6 4.5-2.6 9-4.2 13.4-2.2 6.7-4.8 13.4-7.7 20.2-1.6 3.5-3.8 5.8-7.4 7-2.9 1-5.4-1.6-5.1-4.8s.6-6.1 1-9c1.6-8.6 3.8-17 4.8-25.6s.3-17.6.3-26.2c0-1.3-1.3-2.9-2.2-3.8-7-7.4-14.4-14.4-21.4-21.4-7.7-7.4-15.4-15-20.5-24.6-4.8-8.6-12.2-9.9-20.2-8.3-13.1 2.6-25.9 5.8-39 9-3.2.6-6.4 1.6-9.6 2.6-.3 0-1 0-1-.3-.3-.3 0-.6 0-1 1.6-1.6 2.9-3.2 4.8-4.5 9.9-8.3 19.8-16 29.4-24.3 5.8-5.1 11.2-10.2 16.6-15.7 1-1 1.6-3.2 1.6-4.8-2.4-38.7 6.5-75.2 22.5-110.4 6.4-14.1 13.1-28.2 20.2-42.6 1-1.9 2.9-2.9 4.8-3.5 4.2-1.6 5.1-6.7 7.4-10.6 1.3-2.2 2.2-4.8 3.2-7.4 1-2.2 3.8-2.9 5.4-1.3 1.3 1.3 3.5 1.3 4.8 0 1.6-1.6 3.2-2.9 4.5-4.8 6.1-8.6 11.8-17.3 17.6-26.2 2.6-4.2 5.4-6.7 10.2-8 16-4.5 32-9.6 48-14.4.6-.3 1.3-.6 1.6-1.3 1.3-9.6 1.9-10.2 11.5-11.8 10.2-1.6 16.6-7 18.6-17.6 1.6-10.2 2.2-21.1 3.2-31.4 1-9 1.6-17.6 2.6-26.6.3-3.8 1.3-6.4 3.2-8 1.9-1.9 5.1-1 6.7 1.6 1.3 2.6 2.6 5.1 3.5 8 3.5 10.6 6.1 21.1 9.3 31.7 2.9 9 5.8 17.9 9.3 26.9 4.5 11.8 13.8 16.6 26.2 17 4.8 0 9.6.3 14.1 0 5.8-.3 11.2 1 15.7 4.5 12.5 9 25.3 17.9 37.1 27.5 8.6 6.7 16.6 14.7 25 22.4 1.3 1.3 3.2 1.6 4.8 1.6 2.9 0 5.8 1.3 8.3 2.9 2.2 1.3 2.9 4.2 1.6 6.4-.3.6-.6 1.6-1.3 2.2-1.3 2.6 0 5.8 2.6 7.4 7.4 4.2 13.1 10.6 19.5 16 2.6 2.2 5.1 4.2 7.7 6.1 5.1 3.8 10.6 4.5 16.6 3.2 11.8-2.9 23.4-6.1 35.2-8.6 9.8-3.5 18.5-4.4 28.1-3.2M264.1 440.2h28.8c2.6 0 5.4-.3 7.7-1.6 12.2-6.1 24-12.2 35.8-18.9 11.8-7 13.1-10.6 9.6-24-3.2-12.2-9.3-23.4-15.4-33.9-7.4-12.8-13.1-25.9-13.4-41-.3-8-2.6-15.7-6.4-22.7-3.2-6.4-8.6-9.3-15.7-9.3-19.2-.3-38.4 1.9-56.6 8.3-47.7 16-76.5 55.4-77.4 104-.3 11.8 4.8 19.8 15.4 24.3 7 3.2 14.7 6.1 22.1 8.3 21.4 6.8 43.4 7.5 65.5 6.5M94.5 314.5c1.9-.3 3.2-.3 4.8-.3 17-2.9 32.6-9 48-16.6 4.8-2.2 9.3-5.4 13.8-8.6 1.6-1.3 3.2-3.2 3.8-5.4 12.8-39.7 25.3-79.4 38.1-119 .6-1.9-.6-3.8-2.6-3.8-4.2 0-7.7 1.3-11.2 3.5-14.7 8.6-28.5 18.9-41 30.7-18.2 17.3-33.9 36.5-42.9 60.2-7.9 18.6-10.8 38.5-10.8 59.3m309.4-65c-1.3 0-2.6-.3-3.8 0-6.1 1-12.2 1.9-17.9 3.5-12.8 3.2-25 7.7-36.5 14.4-6.4 3.5-7.7 6.1-6.4 13.1.3 2.6 1 5.1 1.6 7.7 5.1 15.7 9.9 31.4 15.7 46.4 5.1 13.4 11.2 26.2 17.3 39 .3.3.3 1 .6 1.3 1.9 2.9 6.7 2.2 8.3-1 5.4-10.6 9.6-20.8 12.5-31.7 7.7-30.1 8.6-60.5 8.6-91.2.4-.2 0-.8 0-1.5m-197.7 18.9c1 0 1.6.3 2.2.3 13.4 0 26.9-1 40-4.5 9-2.2 17.3-5.8 25-10.9 6.1-4.2 8.6-9.6 7.7-16.6-.6-4.8-1.6-9.3-2.9-13.8-7.4-21.8-19.2-41.3-30.7-60.8-1.6-2.9-4.8-2.9-6.7 0-1 1.6-1.6 3.2-2.2 4.8-2.9 8-5.8 16-8.3 24-8 25-15.7 49.9-23.7 74.9-.1 1-.1 1.6-.4 2.6M290 154.8l-1 1s-.3.3 0 .6c5.8 17.9 11.2 35.8 17.6 53.4 2.2 6.7 5.8 12.8 9.3 18.9 3.2 5.8 8 7.7 14.7 7 16-1.3 28.8-9.6 42.2-16.3 1.6-.6 2.6-2.2 2.6-3.8 0-5.1-1.6-9.6-4.5-13.4-2.2-2.9-4.8-6.1-7.4-8.3-18.2-16.3-39-28.8-62.4-36.8-3.7-1.3-7.6-1.6-11.1-2.3M123 390.9c1.3-.3 2.2-1.6 2.6-2.9 3.5-12.5 7-24.6 10.6-36.8 0-.6.3-1.3.3-1.6.6-3.2-2.2-5.8-5.4-5.4-9.6 1-18.2 3.5-25.6 9.6-3.2 2.6-5.8 6.4-5.1 10.6 1.9 10.6 6.4 19.5 15.7 25.6 2.1.9 4.7 1.6 6.9.9"/></g>',
amneziawg:
'<g fill="currentColor" stroke="none" fill-rule="evenodd" transform="scale(.0467)"><path d="M195.7 492.3C196.5 490.2 198.3 483.3 199.6 477.0C205.9 447.1 210.2 441.9 228.7 441.9C234.0 441.9 241.9 442.5 246.2 443.1C254.7 444.3 265.4 444.0 284.6 441.9C301.1 440.2 303.8 440.9 307.4 448.5C310.3 454.6 314.0 467.5 314.0 471.4C314.0 476.0 319.2 488.2 322.7 491.6C329.7 498.7 335.1 493.9 341.0 475.5C341.7 473.3 343.3 469.9 344.5 468.0C345.7 466.1 348.3 461.1 350.2 456.9C360.1 435.6 392.7 402.2 425.2 380.2C431.2 376.1 441.1 365.0 444.5 358.6C446.0 355.8 449.9 349.4 453.2 344.4C460.0 333.9 464.1 323.2 467.4 307.0C470.0 294.9 471.5 289.8 474.8 283.4C481.7 269.8 484.0 246.8 479.6 236.2C474.6 224.1 471.8 193.1 474.1 175.0C475.9 161.2 476.7 149.7 476.0 147.0C475.3 144.1 468.2 140.2 463.6 140.1C455.1 139.9 448.8 133.7 442.5 119.1C440.2 113.8 437.1 107.2 435.7 104.3C432.5 98.0 432.4 95.7 435.0 84.8C439.6 65.1 442.1 18.0 438.5 18.0C436.5 18.0 431.4 26.1 424.2 40.7C408.7 72.1 404.8 76.3 395.0 72.4C390.1 70.4 387.6 66.6 384.0 55.2C382.4 50.5 380.4 46.0 379.3 45.2C376.5 43.1 368.4 44.3 361.3 47.9C353.7 51.8 351.8 51.8 339.5 47.6C317.5 40.2 314.1 39.1 305.0 37.1C276.2 30.5 218.2 30.4 198.0 37.0C188.6 40.1 163.2 52.8 151.2 60.4C142.6 65.9 140.2 67.0 136.6 67.0C132.5 67.0 132.0 67.3 128.0 72.5C123.5 78.3 112.5 89.0 111.0 89.0C109.9 89.0 109.3 86.9 108.4 80.5C107.5 73.4 100.4 52.6 96.6 45.5C90.3 34.0 86.5 28.1 85.5 28.4C81.5 29.5 77.7 67.2 80.1 81.8C80.6 84.9 81.0 94.3 80.9 102.6C80.8 121.3 80.0 123.3 66.7 139.0C63.0 143.3 53.3 163.1 49.5 174.0C43.4 191.5 42.3 196.1 41.1 209.0C40.4 215.9 39.0 228.7 38.0 237.5C34.9 263.0 35.1 270.8 39.0 283.5C40.1 286.8 41.6 292.4 42.5 296.0C46.4 311.3 62.6 345.6 72.4 359.0C90.2 383.5 120.7 409.9 135.1 413.3C139.2 414.3 152.5 423.4 155.3 427.1C157.6 430.2 169.4 454.7 175.0 468.0C186.7 495.8 191.7 501.7 195.7 492.3ZM243.5 407.9C241.3 407.5 237.4 407.1 234.7 407.1C230.6 407.0 229.4 406.5 225.5 402.9C220.2 398.0 220.1 397.6 224.0 389.5C225.6 386.1 227.7 380.3 228.5 376.6C229.4 372.9 230.7 368.2 231.5 366.2C234.2 359.2 237.8 345.5 240.5 332.5C244.8 311.7 249.0 296.7 254.2 284.0C256.1 279.3 258.0 274.3 258.4 272.8C260.1 265.8 264.5 274.9 269.1 294.5C269.7 297.2 271.3 303.1 272.6 307.5C273.9 311.9 275.4 318.2 275.9 321.5C277.1 329.3 285.1 358.9 288.0 366.6C291.3 375.3 291.8 386.5 289.2 391.5C282.5 404.7 262.4 411.9 243.5 407.9ZM184.8 381.8C180.9 377.6 176.4 366.0 173.9 353.6C173.3 350.8 170.3 339.5 167.3 328.5C160.2 302.8 156.8 289.4 151.9 269.0C149.7 259.9 147.0 248.9 145.9 244.5C143.9 236.3 141.8 227.4 137.5 209.0C136.1 203.2 134.2 193.0 133.1 186.2C132.0 179.5 130.8 173.5 130.5 173.0C130.2 172.5 129.5 168.4 128.9 163.8C128.4 159.2 126.8 151.0 125.5 145.5C124.1 140.0 123.0 133.9 123.0 131.9C123.0 130.0 122.5 127.9 121.9 127.3C119.1 124.5 126.3 115.6 137.7 107.7C152.0 97.7 178.7 87.0 203.0 81.5C233.5 74.6 230.5 74.9 262.0 74.8C296.3 74.7 303.8 76.3 327.4 88.2C337.4 93.2 344.8 96.0 348.6 96.0C350.5 96.0 372.4 109.2 379.6 114.7C384.3 118.2 385.6 122.0 384.2 128.2C383.5 130.9 383.0 134.8 383.0 136.8C383.0 138.9 382.5 142.1 382.0 144.0C380.3 149.7 378.2 165.7 377.5 177.0C377.0 186.5 376.4 190.9 373.0 210.5C372.5 213.8 371.7 219.2 371.4 222.5C371.1 225.8 370.2 231.0 369.4 234.0C368.6 237.0 368.0 240.3 368.0 241.5C368.0 242.6 367.2 246.2 366.1 249.5C362.8 259.8 359.8 271.2 358.5 278.5C357.8 282.4 356.3 289.3 355.1 294.0C354.0 298.7 352.4 307.4 351.5 313.5C347.4 343.1 339.0 369.4 330.6 379.5C328.2 382.3 328.1 382.4 326.1 380.6C323.5 378.3 318.4 364.4 311.6 341.5C309.2 333.5 305.8 324.8 300.0 312.4C295.9 303.5 293.0 292.7 293.0 286.3C293.0 282.8 291.5 276.7 288.5 267.6C286.0 260.1 284.0 252.8 284.0 251.4C284.0 249.0 282.9 241.8 279.9 224.6C279.3 221.4 277.5 214.6 275.9 209.6C270.0 191.3 268.1 185.3 265.5 176.8C264.1 171.9 262.6 168.0 262.2 168.0C261.3 168.0 253.1 188.4 249.5 199.5C247.1 207.1 245.0 215.9 241.5 233.5C240.6 237.9 239.3 244.2 238.5 247.5C234.6 264.6 232.9 272.2 231.4 279.5C230.5 283.9 228.0 291.8 225.8 297.0C222.3 305.3 214.6 326.6 199.6 369.8C193.4 387.3 191.4 389.0 184.8 381.8ZM370.4 368.5C370.0 367.6 371.1 362.7 372.9 357.7C378.0 343.2 379.9 335.4 381.5 323.0C383.2 310.2 383.9 306.6 386.8 296.5C391.2 280.9 396.2 258.4 397.1 249.7C397.6 244.7 398.5 239.2 399.0 237.5C399.5 235.8 400.6 230.2 401.5 225.0C402.3 219.8 403.5 213.2 404.0 210.5C404.5 207.8 405.2 203.0 405.6 200.0C405.9 197.0 407.0 191.8 408.0 188.5C409.0 185.2 410.1 179.9 410.5 176.8C411.3 169.8 412.1 169.7 417.4 175.4C424.5 182.9 427.3 189.6 430.0 205.7C435.9 240.1 430.9 279.3 417.1 306.7C415.0 311.0 412.1 317.8 410.6 321.8C407.1 331.5 405.8 333.9 397.9 345.1C384.7 363.8 372.5 374.1 370.4 368.5ZM116.2 361.0C108.1 357.3 94.1 343.1 89.3 333.6C88.5 331.9 85.3 326.7 82.4 322.0C76.7 312.9 65.8 287.4 63.5 277.5C60.9 266.7 63.1 223.5 66.9 210.4C70.4 198.3 86.0 170.5 88.0 172.7C92.4 177.1 99.3 193.3 106.5 216.0C109.0 224.0 112.1 232.3 113.4 234.5C116.9 240.6 120.6 252.8 124.5 271.5C126.4 280.9 129.1 293.9 130.5 300.5C134.9 321.0 134.7 353.9Line truncated
wireguard:
'<g fill="currentColor" stroke="none" transform="scale(.046875)"><path d="M511.6 248.4S523.4 0 250.4 0C8.9 0 1.4 238.3 1.4 238.3S-34.1 512 255.9 512c278.3 0 255.7-263.6 255.7-263.6M174 161.6c51.2-31.3 116.7-12.2 141.2 34.9 4.6 8.9 5.2 22.7 2.3 32-10.2 32.4-34.2 50.5-67.1 58.2 9.7-8.3 17.4-17.7 19.9-30.8 2.6-12.5-.2-25.5-7.8-35.8-12-16.5-33.4-23-52.6-16-20.3 7.7-31.4 26.2-29.4 49 1.9 21.1 17.9 34.8 47.9 40-4.5 2.4-7.9 4.1-11.3 6-13.7 7.5-25.7 17.9-35.1 30.5-3 4.1-5.1 4.4-9.8 1.6-60.2-36.7-64.1-129.3 1.8-169.6m-45.2 227.9c-9.7 2.5-19.1 6.1-29 9.3 4.8-32.7 43.1-62.8 75.5-59.4-9.4 12.9-14.8 28.3-15.8 44.2-10.7 2.1-20.8 3.4-30.7 5.9M335 70.4c9.6.4 19.2.2 28.8.4 2.4.2 4.8.5 7.1 1-2.1 3.3-4.6 6.4-7.2 9.3-3.4 3.2-7.3 6.3-12.2 1.5-1.2-1.2-4-.9-6.1-.9-9.5-.1-19.1-.4-28.6-.1-8.3.3-16.5 1.1-24.6 2.5-1.5.3-3.8 5.3-3.1 7.2 1.6 4.4 4.1 9.3 7.6 12.1 13.2 10.4 27.3 19.8 40.5 30.1 12.9 10.1 24.9 21.1 32.2 36.3 9.5 19.8 9.8 40.5 5.7 61.4-6.9 34.8-24.5 63.6-53 84.5-11.5 8.4-25.7 13.2-38.8 19.3-11.6 5.3-23.5 9.9-35.1 15.2-20.9 9.5-32.7 32.2-29.2 55.8 3.2 21.6 22.2 39.7 43.9 43.4 26.1 4.5 53-12.5 59.4-39 7.2-29.8-9-56.5-39.4-64.5-1.3-.4-2.7-.7-5.5-1.4 8.1-3.6 15.1-6.2 21.6-9.8 11.3-6.2 22.4-12.8 33.2-19.7 3.2-2 4.9-2 7.7.3 20.9 18 33.3 40.5 36.8 68 5.8 45.5-15.8 87.4-56.4 108.8-62.9 33.2-139.9-4.6-153.8-74.3-11.9-59.7 30.3-113.9 81-124.4 21.8-4.5 41.8-13.6 57.3-30.4 10-10.8 14.9-20.1 16.5-24.4 3.1-7.9 4.7-16.2 4.6-24.7-.3-7.3-2-14.5-5.1-21.2-5.3-12.1-25.6-31.3-30.6-35.3L242.6 120c-1.7-1.4-3.6-1.3-7.7-1-4.9.3-17.4 1-22.8-.4 4.4-3.3 16.2-8.1 21.3-12-15.5-10.5-33.2-6.7-49.4-9.8 3.7-7 22.3-17.7 32.9-18.9-.6-5.9-1.6-11.8-2.9-17.6-.6-2.4-3.3-4.7-5.6-6-5.6-3.3-11.6-6-18-9.3 5.8-3.7 12.5-5.8 19.3-6 6.5-.2 13 .4 19.4 1.9 11.5 2.6 20.7.9 29.8-6.9-7.2-2.9-14.4-5.6-21.4-8.7q-10.35-4.65-20.1-10.5c18.1 2.5 35.7 9.3 54.2 6.8l.5-2.5-42.9-10c25.7-2.4 49.6-2.7 72.2 8.3 6.4 3.1 13 5.7 19.1 9.2 3 1.7 5 5.1 7.4 7.8 1.9 2.1 3.5 4.9 5.9 6.2 9 4.8 19 5 29.2 4.8l.2-3.4c10.2 3.2 21.7 15 21.7 23.6-16.5 0-33.1-.1-49.6.1-1.8 0-3.5 1.3-5.3 2 1.6.9 3.3 2.6 5 2.7m-21.3-24.5c-1.2.7-1.5 2.3-.8 3.5.1.2.3.4.5.6 1 1.8 3.4 2.5 5.2 1.4 1.6-.8 3.2-1.7 5.1-2.7-1.6-1.3-2.8-2.4-4.1-3.5-2.3-1.8-4.1-.7-5.9.7"/></g>',
// Store and platform marks for the portal's set-up sheet (filled, 512 px art scaled to 24).
appstore:
'<g fill="currentColor" stroke="none" transform="scale(.046875)"><path d="M401 0H111C49.7 0 0 49.7 0 111v290c0 61.3 49.7 111 111 111h290c61.3 0 111-49.7 111-111V111C512 49.7 462.3 0 401 0M147.8 400.9c-1.3 2.2-2.6 4.5-4 6.6-1.3 2-2.7 3.8-4.4 5.5-3.5 3.5-8.1 5.7-13 6.3s-9.9-.4-14.2-2.8c-4.3-2.5-7.6-6.3-9.6-10.9-1.9-4.6-2.2-9.6-1-14.4.6-2.3 1.5-4.4 2.5-6.5 1.2-2.3 2.5-4.5 3.8-6.8l12.5-21.6c30.5-7.9 44 11.1 45.4 13.3zM306.2 341c-.6 2.1-1.3 3.5-1.5 4H102.4c-2.1 0-4.3 0-6.4-.1-2.3-.1-4.6-.4-6.9-1.1-4.8-1.3-8.9-4.2-12-8.2-3-4-4.6-8.8-4.6-13.8s1.6-9.8 4.6-13.8 7.2-6.8 12-8.2c2.3-.6 4.5-.9 6.9-1.1 2.6-.1 5.1-.1 7.7-.1h51.1L229.4 168l-19.2-33.6c-1.3-2.2-2.6-4.5-3.7-6.8-1-2.1-1.9-4.2-2.5-6.6-1.2-4.8-.9-9.9 1-14.5s5.2-8.5 9.5-11 9.2-3.5 14.1-2.9 9.4 2.9 13 6.4c1.7 1.7 3.1 3.5 4.3 5.5 1.4 2.2 2.7 4.4 4 6.7l5.9 10.4 5.9-10.4c1.3-2.2 2.6-4.5 4-6.7 1.3-2 2.7-3.8 4.3-5.5 3.5-3.5 8-5.7 13-6.4 4.9-.6 9.9.4 14.1 2.9 4.3 2.5 7.6 6.3 9.5 11 1.9 4.6 2.2 9.7 1 14.5-.6 2.3-1.5 4.4-2.5 6.6-1.2 2.3-2.5 4.6-3.7 6.8l-93.8 164.3H275c21.8 0 37.6 21.2 31.2 42.3m128.7-5.5c-3 4-7.2 6.8-12 8.2-2.3.6-4.6.9-6.9 1.1-2.2.1-4.3.1-6.5.1h-25.9l18.8 32.7c1.3 2.3 2.6 4.5 3.8 6.8 1.1 2.1 2 4.3 2.5 6.6 1.2 4.9.9 9.9-1 14.6-1.9 4.6-5.3 8.5-9.6 11s-9.3 3.5-14.2 2.9c-5-.6-9.5-2.9-13-6.4-1.7-1.7-3.1-3.5-4.4-5.5-1.4-2.2-2.7-4.4-4-6.7l-81.4-141.8c-7.9-13.7-11-29.7-8.4-45.3 1.8-10.8 6.4-22.6 16.6-33.2l67.7 118h51.3c2.6 0 5.2 0 7.8.1 2.3.1 4.6.4 6.9 1.1 4.8 1.3 9 4.2 12 8.2s4.6 8.8 4.6 13.8-1.7 9.7-4.7 13.7"/></g>',
googleplay:
'<g fill="currentColor" stroke="none" transform="scale(.046875)"><path d="M241.9 246.7 27.5 35C35.1 14.2 55.1 0 77.4 0h.1c9.6 0 19.1 2.6 27.4 7.5L345 145zM24.6 52.1v409l37.6-37.2L232.3 256l-2.7-2.7-205-202.4zm26.9 453.1c12.4 6.9 26.7 8.6 40.4 4.8 4.3-1.2 8.4-2.9 12.2-5.2l240.4-136.9-102.7-102.4L27.5 477c4.4 12 12.8 21.9 24 28.2M357 151.9 251.3 256.1l81.3 81.1 23.9 23.9 103.2-58.7c25.2-13.2 35-44.5 21.8-69.7-4.9-9.4-11.4-14.6-21.8-21.8"/></g>',
github:
'<g fill="currentColor" stroke="none" transform="scale(.046875)"><path d="M256 6.3C114.6 6.3 0 120.9 0 262.3c0 113.3 73.3 209 175 242.9 12.8 2.2 17.6-5.4 17.6-12.2 0-6.1-.3-26.2-.3-47.7-64.3 11.8-81-15.7-86.1-30.1-2.9-7.4-15.4-30.1-26.2-36.2-9-4.8-21.8-16.6-.3-17 20.2-.3 34.6 18.6 39.4 26.2 23 38.7 59.8 27.8 74.6 21.1 2.2-16.6 9-27.8 16.3-34.2-57-6.4-116.5-28.5-116.5-126.4 0-27.8 9.9-50.9 26.2-68.8-2.6-6.4-11.5-32.6 2.6-67.8 0 0 21.4-6.7 70.4 26.2 20.5-5.8 42.2-8.6 64-8.6s43.5 2.9 64 8.6c49-33.3 70.4-26.2 70.4-26.2 14.1 35.2 5.1 61.4 2.6 67.8 16.3 17.9 26.2 40.6 26.2 68.8 0 98.2-59.8 120-116.8 126.4 9.3 8 17.3 23.4 17.3 47.4 0 34.2-.3 61.8-.3 70.4 0 6.7 4.8 14.7 17.6 12.2C438.7 471.3 512 375.3 512 262.3c0-141.4-114.6-256-256-256"/></g>',
openwrt:
'<g fill="currentColor" stroke="none" transform="scale(.046875)"><path d="M255.9 267.3c-19.2-.3-35 14.9-35.3 34.1s14.9 35 34.1 35.3h1.3c19.2-.3 34.5-16.2 34.1-35.3-.4-18.7-15.5-33.8-34.2-34.1M42.6 88.7l36.2 36.2c47-47.1 110.7-73.4 177.2-73.3 66.5-.1 130.3 26.4 177.2 73.3l36.2-36.2C414.8 34 339.3 0 256 0 172.6 0 97.1 34 42.6 88.7m65.2 65.2 36.2 36.2c29.7-29.7 70-46.4 112-46.4s82.3 16.6 112 46.4l36.2-36.2C366.3 116 313.8 92.2 256 92.2S145.7 116 107.8 153.9m64.8 64.9 36.2 36.2c26-26 68.3-26 94.3 0l36.2-36.2c-22-22.1-52.1-34.5-83.3-34.3-32.3-.1-61.8 13-83.4 34.3m211.6-9.9c19.8 27 30.5 59.7 30.5 93.2 0 87.6-71.3 158.8-158.8 158.8-87.6 0-158.8-71.3-158.8-158.8 0-34.8 11.3-67 30.5-93.2l-36.5-36.5C61.8 209.3 45.9 255 46 302.1 46 417.7 140.3 512 255.9 512s209.9-94.3 209.9-209.9c0-48.9-17.1-94-45-129.7z"/></g>',
apple:
'<g fill="currentColor" stroke="none" transform="scale(.046875)"><path d="M451.1 174.6c-3 2.3-55.4 31.8-55.4 97.5 0 76 66.7 102.9 68.7 103.5-.3 1.6-10.6 36.8-35.2 72.7-21.9 31.5-44.8 63-79.6 63s-43.8-20.2-84-20.2c-39.2 0-53.1 20.9-84.9 20.9s-54.1-29.2-79.6-65c-29.6-42.1-53.5-107.5-53.5-169.5 0-99.5 64.7-152.3 128.4-152.3 33.8 0 62.1 22.2 83.3 22.2 20.2 0 51.8-23.6 90.3-23.6 14.6 0 67 1.3 101.5 50.8m-119.8-93c15.9-18.9 27.2-45.1 27.2-71.3 0-3.6-.3-7.3-1-10.3-25.9 1-56.7 17.3-75.3 38.8-14.6 16.6-28.2 42.8-28.2 69.4 0 4 .7 8 1 9.3 1.6.3 4.3.7 7 .7 23.2-.1 52.4-15.6 69.3-36.6"/></g>',
windows:
'<g fill="currentColor" stroke="none"><path d="M3 3h8.5v8.5H3zM12.5 3H21v8.5h-8.5zM3 12.5h8.5V21H3zM12.5 12.5H21V21h-8.5z"/></g>',
linux:
'<path d="M4 17V7a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10"/><path d="M2 17h20v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2z"/><path d="m8 9 2 2-2 2M12 13h3"/>',
eye: '<path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6z"/><circle cx="12" cy="12" r="3"/>',
share: '<path d="M12 3v12M8 7l4-4 4 4M5 14v5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5"/>',
arrow: '<path d="M5 12h14M13 6l6 6-6 6"/>',
trash: '<path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/>',
edit: '<path d="M4 20h4L19 9l-4-4L4 16z"/>',
pause: '<path d="M9 5v14M15 5v14"/>',
+74 -27
View File
@@ -1,49 +1,96 @@
// QR codes rendered in the browser as a single-path SVG, with the Dawnline
// mark in the middle. The mark hides about 5% of the code; error correction
// H (30%) covers that for links, Q (25%) keeps long configurations scannable.
// QR codes rendered in the browser as SVG, with the Dawnline mark in the
// middle. The mark hides about 5% of the code; error correction H (30%) covers
// that for links. A long configuration (an AmneziaVPN key is about 1.5 KB) gets
// no mark and level L: every step up in correction adds modules, and a dense
// code fails on the camera before it fails on damage.
//
// Two looks. `plain`: black squares on white in one path (the admin's cards and
// the invite image). `night`: light dots on black with rounded finder eyes (the
// portal). Light dots on dark lose a dense code to blur sooner, so a dense night
// code gets fuller dots: checked with a QR reader, r 0.42 lost a 1.5 KB key at
// 1.2 px of blur where r 0.48 read as well as the plain code.
import qrcode from 'qrcode-generator';
/** The icon's dome and bar (64×64 viewBox, see portal/icon.svg). */
const MARK = '<path d="M14 38a18 18 0 0 1 36 0z" fill="#fff"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#fff" opacity=".5"/>';
export type QrLook = 'plain' | 'night';
export function qrSvg(text: string, margin = 3, logo = true): string {
const qr = qrcode(0, text.length > 300 ? 'Q' : 'H');
/** The icon's dome and bar (64×64 viewBox, see portal/icon.svg), in a colour. */
const mark = (fill: string) =>
`<path d="M14 38a18 18 0 0 1 36 0z" fill="${fill}"/><rect x="12" y="43" width="40" height="4" rx="2" fill="${fill}" opacity=".5"/>`;
const NIGHT_BG = '#0a0a0a';
const NIGHT_FG = '#f2f2f2';
/** Long content: fewer modules matter more than the mark. */
export const denseQr = (text: string): boolean => text.length > 300;
const n2 = (v: number) => +v.toFixed(2);
/** A rounded rectangle as a sub-path. */
function rrect(x: number, y: number, w: number, h: number, r: number): string {
return (
`M${n2(x + r)} ${n2(y)}h${n2(w - 2 * r)}a${r} ${r} 0 0 1 ${r} ${r}v${n2(h - 2 * r)}a${r} ${r} 0 0 1 -${r} ${r}` +
`h-${n2(w - 2 * r)}a${r} ${r} 0 0 1 -${r} -${r}v-${n2(h - 2 * r)}a${r} ${r} 0 0 1 ${r} -${r}z`
);
}
export function qrSvg(text: string, margin = 3, logo = true, look: QrLook = 'plain'): string {
const dense = denseQr(text);
const night = look === 'night';
const qr = qrcode(0, dense ? 'L' : 'H');
qr.addData(text, 'Byte');
qr.make();
const n = qr.getModuleCount();
const size = n + margin * 2;
// A centred, module-aligned hole for the mark (same parity as n).
let hole = logo ? Math.round(n * 0.22) : 0;
let hole = logo && !dense ? Math.round(n * 0.22) : 0;
if (hole && (n - hole) % 2) hole++;
const h0 = (n - hole) / 2,
h1 = h0 + hole;
const inHole = (x: number, y: number) => hole > 0 && x >= h0 && x < h1 && y >= h0 && y < h1;
// The three finder patterns, drawn whole as eyes in the night look.
const inEye = (x: number, y: number) => night && ((y < 7 && x < 7) || (y < 7 && x >= n - 7) || (y >= n - 7 && x < 7));
let d = '';
for (let y = 0; y < n; y++) {
let x = 0;
while (x < n) {
if (!qr.isDark(y, x) || inHole(x, y)) {
x++;
continue;
if (night) {
const r = dense ? 0.48 : 0.42;
for (let y = 0; y < n; y++)
for (let x = 0; x < n; x++)
if (qr.isDark(y, x) && !inHole(x, y) && !inEye(x, y))
d += `M${x + margin + 0.5 - r} ${y + margin + 0.5}a${r} ${r} 0 1 0 ${2 * r} 0a${r} ${r} 0 1 0 -${2 * r} 0z`;
} else
for (let y = 0; y < n; y++) {
let x = 0;
while (x < n) {
if (!qr.isDark(y, x) || inHole(x, y)) {
x++;
continue;
}
let w = 1;
while (x + w < n && qr.isDark(y, x + w) && !inHole(x + w, y)) w++;
d += `M${x + margin} ${y + margin}h${w}v1h-${w}z`;
x += w;
}
let w = 1;
while (x + w < n && qr.isDark(y, x + w) && !inHole(x + w, y)) w++;
d += `M${x + margin} ${y + margin}h${w}v1h-${w}z`;
x += w;
}
}
let mark = '';
// Each eye: a 7×7 ring around a gap and a 3×3 pupil, one even-odd path.
let eyes = '';
if (night)
for (const [x, y] of [
[margin, margin],
[margin + n - 7, margin],
[margin, margin + n - 7],
])
eyes += rrect(x, y, 7, 7, 2.6) + rrect(x + 1, y + 1, 5, 5, 1.8) + rrect(x + 2, y + 2, 3, 3, 1.5);
let logoTile = '';
if (hole) {
const pad = 0.6,
s = hole - pad * 2,
o = h0 + margin + pad;
mark =
`<rect x="${o}" y="${o}" width="${s}" height="${s}" rx="${s * 0.25}" fill="#0a0a0a"/>` +
`<g transform="translate(${o} ${o}) scale(${s / 64})">${MARK}</g>`;
logoTile =
`<rect x="${o}" y="${o}" width="${s}" height="${s}" rx="${s * (night ? 0.28 : 0.25)}" fill="${night ? NIGHT_FG : '#0a0a0a'}"/>` +
`<g transform="translate(${o} ${o}) scale(${s / 64})">${mark(night ? NIGHT_BG : '#fff')}</g>`;
}
return (
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" role="img" aria-label="QR code">` +
`<rect width="${size}" height="${size}" fill="#fff"/><path d="${d}" fill="#000" shape-rendering="crispEdges"/>${mark}</svg>`
);
const open = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" role="img" aria-label="QR code">`;
return night
? `${open}<rect width="${size}" height="${size}" fill="${NIGHT_BG}"/><path d="${d}" fill="${NIGHT_FG}"/>` +
`<path d="${eyes}" fill="${NIGHT_FG}" fill-rule="evenodd"/>${logoTile}</svg>`
: `${open}<rect width="${size}" height="${size}" fill="#fff"/><path d="${d}" fill="#000" shape-rendering="crispEdges"/>${logoTile}</svg>`;
}
+4
View File
@@ -116,6 +116,8 @@ export interface Server {
up: boolean;
uptime: number;
peers: number;
/** The newest handshake from a public address that is not the router's own (0: never). */
reached?: number;
online: number;
obf: Record<string, string>;
}
@@ -218,6 +220,8 @@ export interface Status {
awg: AwgCaps;
/** Absent from routers that run an older backend: treat as fine. */
awg_state?: AwgState;
/** The router's public IPv4 (null when none or private). */
wan?: string | null;
like_home: { active: boolean; dev?: string; address?: string; bridged?: boolean; off?: boolean; error?: string };
}
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest';
import { dismisses, morphMs, rubber } from '../src/portal/motion';
describe('motion', () => {
it('pulls past an edge with growing resistance, never further than the box', () => {
expect(rubber(0, 400)).toBe(0);
expect(rubber(-20, 400)).toBe(0);
expect(rubber(40, 400)).toBeLessThan(40);
expect(rubber(40, 400)).toBeGreaterThan(15);
// Each further step gives less than the one before.
expect(rubber(200, 400) - rubber(100, 400)).toBeLessThan(rubber(100, 400) - rubber(0, 400));
expect(rubber(100_000, 400)).toBeLessThan(400);
});
it('dismisses a sheet on a flick down or a pull past a third, not on a flick back up', () => {
expect(dismisses(12, 0.6, 500)).toBe(true);
expect(dismisses(200, 0, 500)).toBe(true);
expect(dismisses(120, 0.1, 500)).toBe(false);
expect(dismisses(300, -0.5, 500)).toBe(false);
expect(dismisses(0, 1, 500)).toBe(false);
expect(dismisses(-40, 1, 500)).toBe(false);
});
it('times a height change by its distance, inside 220–380 ms', () => {
expect(morphMs(0)).toBe(220);
expect(morphMs(200)).toBe(270);
expect(morphMs(2000)).toBe(380);
});
});
+79
View File
@@ -62,3 +62,82 @@ describe('netcheck', () => {
expect(portalPortHelp(8444, taken, false).bad).toBe(true);
});
});
import {
chars,
circleNameHelp,
dnsHelp,
domainHelp,
expiresHelp,
fallbackDnsHelp,
hostHelp,
ipv4Help,
keepaliveHelp,
limitHelp,
mtuHelp,
nameHelp,
portsHelp,
quotaHelp,
timeHelp,
titleHelp,
urlHelp,
} from '../src/admin/netcheck';
import { date, daysLeft } from '../src/shared/format';
describe('field helps', () => {
it('counts characters like the router', () => {
expect(chars('Мама')).toBe(4);
expect(nameHelp('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧ').bad).toBe(false);
expect(nameHelp('a'.repeat(49)).bad).toBe(true);
expect(nameHelp('Bob "B"').bad).toBe(true);
expect(nameHelp(' ').bad).toBe(true);
expect(nameHelp('Phone', ['phone']).text).toContain('already exists');
expect(circleNameHelp('x'.repeat(33)).bad).toBe(true);
});
it('explains the public address', () => {
expect(hostHelp('https://vpn.example.com').text).toContain('Leave out https://');
expect(hostHelp('vpn.example.com:4500').text).toContain('without a port');
expect(hostHelp('vpn.example.com', 4500)).toEqual({ text: 'Devices connect to vpn.example.com:4500.', bad: false });
expect(hostHelp('2001:db8::1', 4500).text).toBe('Devices connect to [2001:db8::1]:4500.');
expect(hostHelp('', 4500).bad).toBe(true);
expect(hostHelp('', 4500, 'Empty = the portal address.').bad).toBe(false);
expect(hostHelp('bad_host!').bad).toBe(true);
});
it('checks DNS, MTU, keep-alive', () => {
expect(dnsHelp('', '10.77.0.1').bad).toBe(false);
expect(dnsHelp('1.1.1.1, foo', '10.77.0.1').text).toContain('“foo” is not an IP address');
expect(dnsHelp('1.1.1.1 8.8.8.8', '10.77.0.1').text).toContain('1.1.1.1 and 8.8.8.8');
expect(mtuHelp('', { computer: 1368, phone: 1280 }).text).toContain('1368');
expect(mtuHelp('1200', { computer: 1368, phone: 1280 }).bad).toBe(true);
expect(mtuHelp('1400', { computer: 1368, phone: 1280 }).text).toContain('phones and tablets 1280');
expect(keepaliveHelp('601').bad).toBe(true);
expect(keepaliveHelp('0').bad).toBe(false);
});
it('checks limits, quota and dates', () => {
expect(limitHelp('0').bad).toBe(true);
expect(limitHelp('33').bad).toBe(true);
expect(limitHelp('2', 4).text).toContain('Already has 4');
expect(quotaHelp('').bad).toBe(false);
expect(quotaHelp('100001').bad).toBe(true);
expect(quotaHelp('50').text).toContain('Paused after 50 GB');
expect(expiresHelp('2026-10-13', '2026-10-14', daysLeft, date).bad).toBe(true);
expect(expiresHelp('2026-10-14', '2026-10-14', daysLeft, date).text).toContain('ends today');
expect(expiresHelp('2026-10-20', '2026-10-14', daysLeft, date).text).toContain('ends in 7 days');
});
it('checks services, portal and settings fields', () => {
expect(ipv4Help('10.0.1.300').bad).toBe(true);
expect(ipv4Help('10.0.1.5', () => false).text).toContain('not in any home network');
expect(portsHelp('445, 5000').text).toBe('Ports 445, 5000.');
expect(portsHelp('70000').bad).toBe(true);
expect(urlHelp('vpn.example.com').bad).toBe(true);
expect(urlHelp('https://example.com/x').bad).toBe(false);
expect(titleHelp('x'.repeat(65)).bad).toBe(true);
expect(domainHelp('').bad).toBe(false);
expect(domainHelp('').text).toContain('phone.myata.lan');
expect(domainHelp('Home.LAN').text).toBe('Lowercase only.');
expect(domainHelp('home.lan').text).toContain('phone.myata.home.lan');
expect(fallbackDnsHelp('abc').bad).toBe(true);
expect(timeHelp('4:00').bad).toBe(false);
expect(timeHelp('24:00').bad).toBe(true);
});
});
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { denseQr, qrSvg } from '../src/shared/qr';
const LINK = 'https://engage.example.eu:4500/abcdef-ghijkl-mnopqr';
const KEY = `vpn://${'A1b2C3d4'.repeat(180)}`;
describe('qr', () => {
it('draws the plain look as black squares on white in one path', () => {
const svg = qrSvg(LINK);
expect(svg).toContain('fill="#fff"');
expect(svg).toContain('shape-rendering="crispEdges"');
expect(svg).not.toContain('evenodd');
});
it('draws the night look as light dots on black with eyes, marked on links only', () => {
const link = qrSvg(LINK, 3, true, 'night');
expect(link).toContain('fill="#0a0a0a"');
expect(link).toContain('fill-rule="evenodd"');
expect(link).not.toContain('crispEdges');
// The mark's light tile on a short code, none on a dense one.
expect(link).toContain('fill="#f2f2f2"/><g transform');
expect(denseQr(KEY)).toBe(true);
expect(qrSvg(KEY, 3, true, 'night')).not.toContain('<g transform');
});
it('gives a dense night code fuller dots', () => {
expect(qrSvg(LINK, 3, true, 'night')).toContain('a0.42 0.42');
expect(qrSvg(KEY, 3, true, 'night')).toContain('a0.48 0.48');
});
});
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest';
import {
appsFor,
deviceNoun,
inWebview,
platformOf,
sameDevice,
setupFromHash,
setupLink,
storeFor,
updateLine,
} from '../src/portal/setup';
const IPHONE =
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1';
const IPAD_AS_MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15';
const ANDROID = 'Mozilla/5.0 (Linux; Android 14; SM-S921B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Mobile Safari/537.36';
const WINDOWS = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36';
const LINUX = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36';
describe('setup', () => {
it('reads the platform from the browser, iPad included', () => {
expect(platformOf(IPHONE)).toBe('ios');
expect(platformOf(IPAD_AS_MAC, 5)).toBe('ios');
expect(platformOf(IPAD_AS_MAC, 0)).toBe('mac');
expect(platformOf(ANDROID)).toBe('android');
expect(platformOf(WINDOWS)).toBe('windows');
expect(platformOf(LINUX)).toBe('linux');
expect(platformOf('Mozilla/5.0 (X11; CrOS x86_64)')).toBe('unknown');
});
it('links straight to the set-up of a device through the fragment, and reads only that back', () => {
const page = 'https://engage.example.eu:4500/abcdef-ghijkl-mnopqr';
expect(setupLink(page, 'd_bf0b30e9')).toBe(`${page}#setup=d_bf0b30e9`);
expect(setupFromHash('#setup=d_bf0b30e9')).toBe('d_bf0b30e9');
expect(setupFromHash('')).toBeNull();
expect(setupFromHash('#setup=')).toBeNull();
expect(setupFromHash('#setup=d_bf0b30e9&x=1')).toBeNull();
expect(setupFromHash('#setup=../../api')).toBeNull();
});
it('names the device being set up by its kind, not its name', () => {
expect(deviceNoun('phone')).toBe('phone');
expect(deviceNoun('computer')).toBe('computer');
expect(deviceNoun('other')).toBe('device');
});
it('knows whether the page is open on the device being set up', () => {
expect(sameDevice('phone', 'ios')).toBe(true);
expect(sameDevice('phone', 'mac')).toBe(false);
expect(sameDevice('computer', 'windows')).toBe(true);
expect(sameDevice('computer', 'android')).toBe(false);
expect(sameDevice('router', 'linux')).toBe(false);
expect(sameDevice('phone', 'unknown')).toBe(false);
});
it('lists the apps a disguise allows, AmneziaVPN first', () => {
expect(appsFor('max').map((a) => a.id)).toEqual(['vpn', 'awg']);
expect(appsFor('off').map((a) => a.id)).toEqual(['vpn', 'awg', 'wg']);
expect(appsFor('balanced')[0].need).toBe('4.8.12');
expect(updateLine(appsFor('balanced')[0])).toContain('4.8.12 or newer');
expect(updateLine(appsFor('max')[0])).toContain('the current version');
expect(updateLine(appsFor('off')[0])).toBe('');
});
it('sends people to the store first and to GitHub where no store has the app', () => {
expect(storeFor('vpn', 'ios')?.mark).toBe('appstore');
expect(storeFor('vpn', 'android')?.alt?.mark).toBe('github');
expect(storeFor('vpn', 'windows')?.href).toContain('github.com/amnezia-vpn/amnezia-client');
expect(storeFor('awg', 'mac')?.main).toBe('Mac App Store');
expect(storeFor('wg', 'ios')?.alt).toBeUndefined();
expect(storeFor('vpn', 'unknown')).toBeNull();
});
it('spots in-app browsers', () => {
expect(inWebview(`${ANDROID} Telegram-Android/10.0`)).toBe(true);
expect(inWebview(IPHONE)).toBe(false);
});
});