From caed976e63b2dcf2eb57c0ac10f4e995b748e76c Mon Sep 17 00:00:00 2001 From: Aemeath <35622087+tickcount@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:47:38 +0300 Subject: [PATCH] Portal demo for Vercel - The real portal over a router that lives in the page (web/src/portal/demo): "User" on "Dawnline Preview", ten scenarios (first visit, settings changed, out of data, outside the hours, paused, ended, plain HTTP, plain WireGuard, no free slots), devices kept per visitor in localStorage. Keys are random and the server's address never resolves: nothing is installed and nothing connects - A "Demo" chip after the breadcrumb opens a drawer with the scenarios and Start over; a new device "connects" a few seconds after its settings - A GitHub pill beside the page's QR knob; on a phone, where the names need the room, a GitHub button in the drawer instead - npm run build:demo builds the static site into web/dist/demo; web/vercel.json deploys it with the portal's CSP and headers, and builds only commits on main that change web/ - README links to the live demo (dawnline-demo.vercel.app) - Tests for the demo router (tests/demo.test.ts) --- README.md | 7 +- web/.prettierignore | 1 + web/package.json | 1 + web/src/portal/demo/crumbs.ts | 34 +++++ web/src/portal/demo/data.ts | 222 ++++++++++++++++++++++++++++++++ web/src/portal/demo/demo.css | 151 ++++++++++++++++++++++ web/src/portal/demo/index.html | 20 +++ web/src/portal/demo/main.ts | 24 ++++ web/src/portal/demo/picker.ts | 104 +++++++++++++++ web/src/portal/demo/router.ts | 226 +++++++++++++++++++++++++++++++++ web/src/portal/demo/serve.ts | 45 +++++++ web/tests/demo.test.ts | 112 ++++++++++++++++ web/tsup.demo.config.ts | 41 ++++++ web/vercel.json | 22 ++++ 14 files changed, 1007 insertions(+), 3 deletions(-) create mode 100644 web/src/portal/demo/crumbs.ts create mode 100644 web/src/portal/demo/data.ts create mode 100644 web/src/portal/demo/demo.css create mode 100644 web/src/portal/demo/index.html create mode 100644 web/src/portal/demo/main.ts create mode 100644 web/src/portal/demo/picker.ts create mode 100644 web/src/portal/demo/router.ts create mode 100644 web/src/portal/demo/serve.ts create mode 100644 web/tests/demo.test.ts create mode 100644 web/tsup.demo.config.ts create mode 100644 web/vercel.json diff --git a/README.md b/README.md index 87bc566..3859cbb 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ OpenWrt 25.12 AmneziaWG 2.0 and 3.1 -[**Quick start**](#-quick-start)  ·  [Features](#-features)  ·  [How it works](#-how-it-works)  ·  [Screenshots](#-a-closer-look)  ·  [FAQ](#-faq)  ·  [Development](#-development) +[**Quick start**](#-quick-start)  ·  [**Live demo**](https://dawnline-demo.vercel.app)  ·  [Features](#-features)  ·  [How it works](#-how-it-works)  ·  [Screenshots](#-a-closer-look)  ·  [FAQ](#-faq)  ·  [Development](#-development) @@ -31,9 +31,10 @@ computers** and connect with AmneziaVPN, AmneziaWG or WireGuard. You decide **for how long, how much and when**.

- The personal portal: devices and access, and adding a phone in three steps + The personal portal: devices and access, and adding a phone in three steps
- A person's own page: their devices and access. Adding a phone takes three steps, and the page sees it connect. + A person's own page: their devices and access. Adding a phone takes three steps, and the page sees it connect. + Try it in the live demo: nothing installs and nothing connects.

## 💡 Why Dawnline? diff --git a/web/.prettierignore b/web/.prettierignore index 1de8c4e..e4d719f 100644 --- a/web/.prettierignore +++ b/web/.prettierignore @@ -3,3 +3,4 @@ coverage/ package-lock.json src/portal/fonts/ src/admin/styles/*.css +dist/ diff --git a/web/package.json b/web/package.json index 32bdb3d..35d79c3 100644 --- a/web/package.json +++ b/web/package.json @@ -7,6 +7,7 @@ "scripts": { "build": "tsc --noEmit && tsup", "dev": "tsup --watch", + "build:demo": "tsc --noEmit && tsup --config tsup.demo.config.ts", "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json", "test": "vitest run", "format": "prettier --write .", diff --git a/web/src/portal/demo/crumbs.ts b/web/src/portal/demo/crumbs.ts new file mode 100644 index 0000000..d637b2d --- /dev/null +++ b/web/src/portal/demo/crumbs.ts @@ -0,0 +1,34 @@ +// What the demo adds to the breadcrumb: the scenario chip right after the path, +// and a GitHub pill just before the page's QR knob (at the end where there is +// none: a card alone). On a phone the pill would crowd out the names, so it +// gives way to a button in the scenario drawer (demo.css). The portal redraws +// the breadcrumb with the page and knows nothing of either, so both go back in +// place after each redraw. + +import { h, ic } from '../dom'; +import { REPO } from './data'; +import { scenarioChip } from './picker'; +import type { DemoRouter } from './router'; + +export function mountCrumbs(router: DemoRouter) { + const app = document.getElementById('app')!; + const chip = scenarioChip(router); + const gh = h( + 'a', + { class: 'dm-gh', href: REPO, target: '_blank', rel: 'noopener', 'aria-label': 'Dawnline on GitHub' }, + ic('github'), + h('span', {}, 'GitHub'), + ); + // Our own insertions call this again: by then both are in place and nothing moves. + const keep = () => { + const crumbs = app.querySelector('.crumbs'); + const path = crumbs?.querySelector('.cr-path'); + if (!crumbs || !path) return; + if (path.nextElementSibling !== chip) path.after(chip); + const qr = crumbs.querySelector('.cr-qr'); + if (qr && qr.previousElementSibling !== gh) qr.before(gh); + else if (!qr && crumbs.lastElementChild !== gh) crumbs.append(gh); + }; + new MutationObserver(keep).observe(app, { childList: true, subtree: true }); + keep(); +} diff --git a/web/src/portal/demo/data.ts b/web/src/portal/demo/data.ts new file mode 100644 index 0000000..bb574da --- /dev/null +++ b/web/src/portal/demo/data.ts @@ -0,0 +1,222 @@ +// The demo's made-up person ("User" on the server "Dawnline Preview"), their devices, and the +// page state the router would send for her in each scenario. Pure: no DOM, no +// storage, no fetch (router.ts keeps the devices and answers the API; the +// scenario picker is picker.ts). + +import type { State } from '../state'; +import type { Device, Kind, Person } from '../../shared/types'; + +export const GB = 2 ** 30; +const HOUR = 3600; +const DAY = 86400; + +export type ScenarioId = 'normal' | 'first' | 'stale' | 'quota' | 'hours' | 'paused' | 'expired' | 'http' | 'plain' | 'full'; + +export interface Scenario { + id: ScenarioId; + label: string; + /** One line on what the page shows in it. */ + about: string; +} + +/** What can be tried, in the picker's groups. */ +export const GROUPS: { title: string; items: Scenario[] }[] = [ + { + title: 'Your page', + items: [ + { id: 'normal', label: 'Everything works', about: 'Three devices: one online, one waiting to be set up.' }, + { id: 'first', label: 'First visit', about: 'A fresh link with no devices yet.' }, + { id: 'stale', label: 'Settings changed', about: 'The admin changed something: a device needs an update.' }, + ], + }, + { + title: 'Stopped by the admin', + items: [ + { id: 'quota', label: 'Out of data', about: 'The month’s limit is used up.' }, + { id: 'hours', label: 'Outside allowed hours', about: 'Access only at certain hours of the day.' }, + { id: 'paused', label: 'Paused by the admin', about: 'The page turns into one card.' }, + { id: 'expired', label: 'Access ended', about: 'The end date has passed.' }, + ], + }, + { + title: 'Other cases', + items: [ + { id: 'http', label: 'Opened over plain HTTP', about: 'Settings only travel over HTTPS.' }, + { id: 'plain', label: 'Plain WireGuard', about: 'Disguise off: any WireGuard app connects.' }, + { id: 'full', label: 'No free slots', about: 'Every device slot is taken.' }, + ], + }, +]; +export const SCENARIOS: Scenario[] = GROUPS.flatMap((g) => g.items); +export const isScenario = (id: unknown): id is ScenarioId => SCENARIOS.some((s) => s.id === id); + +/** A device as the demo keeps it; the page's Device is made from it on every answer. */ +export interface DemoDevice { + id: string; + name: string; + kind: Kind; + /** The last part of its tunnel address (10.8.0.n). */ + n: number; + /** Data this month, in GB. */ + gb: number; + /** Last handshake (epoch seconds), 0: never. */ + hs: number; + /** A device being set up "connects" at this time (0: not waiting). */ + connectAt: number; + created: number; + by: 'admin' | 'portal'; + stale: boolean; +} + +/** The scenario's own devices, as it starts. */ +export function seedDevices(s: ScenarioId, t: number, id: () => string): DemoDevice[] { + if (s === 'first') return []; + const dev = (name: string, kind: Kind, n: number, gb: number, hs: number): DemoDevice => ({ + id: id(), + name, + kind, + n, + gb, + hs, + connectAt: 0, + created: t - 40 * DAY, + by: 'admin', + stale: false, + }); + return [ + dev('iPhone 16', 'phone', 2, 14.2, t - 40), + { ...dev('MacBook Pro', 'computer', 3, 21.9, t - 3 * HOUR), stale: s === 'stale' }, + { ...dev('iPad Air', 'tablet', 4, 0, 0), created: t - 2 * DAY, by: 'portal' }, + ]; +} + +/** The person's state in the scenario: the four the admin's limits stop them in, else active. */ +export function personState(s: ScenarioId): Person['state'] { + return s === 'quota' || s === 'hours' || s === 'paused' || s === 'expired' ? s : 'active'; +} +export const locked = (s: ScenarioId) => s === 'paused' || s === 'expired'; +export const deviceLimit = (s: ScenarioId) => (s === 'full' ? 3 : 4); + +/** The local day (YYYY-MM-DD) of a time: in the demo, the visitor's clock is the router's. */ +export function isoDay(t: number): string { + const d = new Date(t * 1000); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +} + +/** A name as a host label: what the router's DHCP names look like. */ +const label = (s: string) => + s + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') || 'device'; + +/** How busy each day of the week is, Monday first. */ +const WEEK = [0.9, 1.15, 0.8, 1.05, 1.3, 0.75, 1.1]; + +/** The month so far, day by day, adding up to `total` bytes (today only partly gone). */ +export function monthDays(total: number, t: number): number[] { + const d = new Date(t * 1000); + const days = d.getDate(); + const w = Array.from({ length: days }, (_, i) => { + const wd = (new Date(d.getFullYear(), d.getMonth(), i + 1).getDay() + 6) % 7; + return WEEK[wd] * (i === days - 1 ? 0.45 : 1) * (0.85 + ((i * 37) % 11) / 30); + }); + const sum = w.reduce((a, b) => a + b, 0); + return w.map((x) => Math.round((x / sum) * total)); +} + +/** A window of the day that leaves `t` out (the visitor's hours): the hours scenario is outside it. */ +export function hoursAway(t: number): string { + const at = new Date(t * 1000).getHours(); + const p = (h: number) => `${String(h % 24).padStart(2, '0')}:00`; + return `${p(at + 2)}-${p(at + 10)}`; +} + +/** The handshake the page sees: a device being set up has "connected" once its time came. */ +export const handshakeOf = (d: DemoDevice, t: number) => (d.connectAt && t >= d.connectAt ? d.connectAt : d.hs); + +function device(d: DemoDevice, t: number, st: Person['state']): Device { + const hs = handshakeOf(d, t); + const month = d.gb * GB; + return { + id: d.id, + name: d.name, + kind: d.kind, + address: `10.8.0.${d.n}`, + disabled: false, + created: d.created, + created_by: d.by, + // A stopped person's tunnels are down; the rest count as online for three minutes after a handshake. + online: !!hs && t - hs < 180 && st !== 'paused' && st !== 'expired', + handshake: hs, + endpoint: hs ? `203.0.113.${20 + d.n}` : '', + active: true, + month: [Math.round(month / 8), Math.round((month * 7) / 8)], + total: [Math.round(month / 4), Math.round((month * 7) / 4)], + spark: [0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f) => (hs ? Math.round(((month / 4) * f) / 7) : 0)), + hostname: `${label(d.name)}.user.lan`, + browser_key: false, + config_stale: d.stale, + }; +} + +/** Everything the page shows, as portal.uc's state() sends it. `secureUrl`: this page over HTTPS, for the plain-HTTP scenario. */ +export function pageState(s: ScenarioId, devs: DemoDevice[], t: number, secureUrl: string): State { + const st = personState(s); + const devices = devs.map((d) => device(d, t, st)); + const quota = s === 'quota' ? 20 : 100; + // Out of data: a little over the limit. Otherwise what the devices used, and a bit from one removed (a fresh link: nothing). + const removed = s === 'first' ? 0 : 2.5 * GB; + const used = s === 'quota' ? 20.4 * GB : devices.reduce((a, d) => a + d.month[0] + d.month[1], 0) + removed; + const limit = deviceLimit(s); + const person: Person = { + id: 'user', + name: 'User', + server: 'home', + access: 'both', + device_limit: limit, + expires: isoDay(t + (s === 'expired' ? -3 : 41) * DAY), + quota_gb: quota, + quota_period: 'month', + quota_used: used, + quota_limit: quota * GB, + bonus_gb: 0, + expire_action: 'pause', + expire_warn: 7, + dns_mode: 'home', + paused: s === 'paused', + hours: s === 'hours' ? hoursAway(t) : '', + state: st, + month: [Math.round(used / 8), Math.round((used * 7) / 8)], + total: [Math.round(used / 3), Math.round((used * 7) / 3)], + online: devices.filter((d) => d.online).length, + last_seen: Math.max(0, ...devices.map((d) => d.handshake)), + devices, + month_days: monthDays(used, t), + }; + return { + person, + here: null, + server: { + name: 'Dawnline Preview', + endpoint: ENDPOINT, + device_mesh: true, + awg_disguise: s !== 'plain', + preset: s === 'plain' ? 'off' : 'max', + }, + can_add: devs.length < limit, + locked: locked(s), + https_url: s === 'http' ? secureUrl : null, + kinds: ['computer', 'phone', 'tablet', 'router', 'other'], + version: 'demo', + today: isoDay(t), + now: t, + tz_offset: -new Date(t * 1000).getTimezoneOffset(), + }; +} + +/** Where Dawnline lives: the breadcrumb's GitHub pill, on a phone the drawer's GitHub button. */ +export const REPO = 'https://github.com/tickcount/luci-app-dawnline'; + +/** The server's address in every configuration: a name that never resolves (RFC 2606). */ +export const ENDPOINT = 'demo.dawnline.invalid'; diff --git a/web/src/portal/demo/demo.css b/web/src/portal/demo/demo.css new file mode 100644 index 0000000..09a4870 --- /dev/null +++ b/web/src/portal/demo/demo.css @@ -0,0 +1,151 @@ +/* The portal demo's stylesheet: the portal's own, then the demo's pieces in its tokens — the "Demo" + chip after the breadcrumb's path, the GitHub pill beside the page's QR knob, and the scenario + rows in the drawer. */ +@import '../styles/index.css'; + +/* The path keeps its width so the chip sits right after it; the page's QR stays at the end. */ +.cr-path { + flex: 0 1 auto; +} +.dm-chip { + display: inline-flex; + align-items: center; + gap: 4px; + height: 26px; + padding: 0 8px 0 10px; + margin-right: auto; + border-radius: 999px; + background: var(--accent-soft); + color: var(--accent); + font-size: 13px; + font-weight: 600; + flex: none; + transition: + transform 150ms var(--ease-out), + background-color 150ms; +} +.dm-chip:hover { + background: color-mix(in srgb, var(--accent) 20%, transparent); +} +.dm-chip:active { + transform: scale(0.94); +} +.dm-chip .i { + width: 14px; + height: 14px; + transform: rotate(90deg); +} +/* A card alone (paused): the breadcrumb is centred, the chip with it. */ +.page.single .dm-chip { + margin-right: 0; +} + +/* GitHub: a pill of the QR knob's height and fill, just before it. On a phone it would crowd out the + names (the server's and the person's): there it is a button in the drawer instead. */ +.dm-gh { + display: inline-flex; + align-items: center; + gap: 6px; + height: 32px; + padding: 0 12px 0 10px; + border-radius: 999px; + background: var(--knob); + color: var(--text); + font-size: 14px; + font-weight: 500; + letter-spacing: -0.01em; + text-decoration: none; + flex: none; + transition: + transform 150ms var(--ease-out), + background-color 150ms; +} +.dm-gh:hover { + background: color-mix(in srgb, var(--knob), var(--text) 6%); +} +.dm-gh:active { + transform: scale(0.94); +} +.dm-gh .i { + width: 16px; + height: 16px; +} +@media (max-width: 479px) { + .dm-gh { + display: none; + } +} + +/* The drawer: groups of rows that touch, one step lighter than the sheet, the current one in the accent. */ +.dm-group { + margin: 0 0 18px; +} +.dm-group .lbl-s { + margin: 0 4px 8px; +} +.dm-list { + display: flex; + flex-direction: column; + gap: 2px; + border-radius: var(--r-row); + overflow: hidden; +} +.dm-row { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + min-height: 60px; + padding: 10px 14px 10px 12px; + background: var(--field); + text-align: left; + transition: background-color 150ms; +} +.dm-row:hover { + background: color-mix(in srgb, var(--field), var(--text) 4%); +} +.dm-row .gi { + width: 30px; + height: 30px; + flex: none; +} +.dm-row .t { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; +} +.dm-row b { + font-size: 15px; + font-weight: 500; + line-height: 20px; + letter-spacing: -0.02em; +} +.dm-row .t span { + color: var(--text-2); + font-size: 13px; + line-height: 18px; +} +.dm-row.on b { + color: var(--accent); +} +.dm-tick { + width: 18px; + height: 18px; + color: var(--accent); + flex: none; +} + +/* The drawer's foot: Start over, and on a phone GitHub beside it. */ +.dm-foot { + display: flex; + gap: 8px; +} +.dm-foot .btn { + flex: 1; +} +@media (min-width: 480px) { + .dm-gh-alt { + display: none; + } +} diff --git a/web/src/portal/demo/index.html b/web/src/portal/demo/index.html new file mode 100644 index 0000000..8bcaf80 --- /dev/null +++ b/web/src/portal/demo/index.html @@ -0,0 +1,20 @@ + + + + + + + + Dawnline Preview + + + + + +
+ + + diff --git a/web/src/portal/demo/main.ts b/web/src/portal/demo/main.ts new file mode 100644 index 0000000..73bb4f1 --- /dev/null +++ b/web/src/portal/demo/main.ts @@ -0,0 +1,24 @@ +// The portal demo (npm run build:demo → dist/demo, a static site): the real +// portal over a router that lives in the page (serve.ts, router.ts, data.ts), +// with a scenario picker and a GitHub link in the breadcrumb (crumbs.ts, +// picker.ts). The order of the imports is the boot order: the router owns +// fetch before the portal loads. + +import { router } from './serve'; +import '../main'; +import { toast } from '../ui/feedback'; +import { mountCrumbs } from './crumbs'; + +mountCrumbs(router); + +// An AmneziaVPN key would add a server that connects nowhere to the visitor's app: the demo keeps it on the page. +document.addEventListener( + 'click', + (e) => { + if (!(e.target as Element).closest?.('a[href^="vpn:"]')) return; + e.preventDefault(); + e.stopPropagation(); + toast('Demo keys connect nowhere', true); + }, + true, +); diff --git a/web/src/portal/demo/picker.ts b/web/src/portal/demo/picker.ts new file mode 100644 index 0000000..d5a7543 --- /dev/null +++ b/web/src/portal/demo/picker.ts @@ -0,0 +1,104 @@ +// The demo's scenario picker: the "Demo" chip, opening a drawer with the +// scenarios in groups (glass icon, name, what the page shows) and "Start over". +// Picking one swaps the page in place. Built only from the portal's own parts +// (sheet, glass icons, toast, motion); where the chip sits is crumbs.ts. On a +// phone the drawer's foot also links to GitHub, the breadcrumb having no room. + +import { h, ic } from '../dom'; +import { call } from '../api'; +import { repaint, setState, type State } from '../state'; +import { closeSheet, head, openSheet, sub, type View } from '../ui/sheet'; +import { glass, type Tone } from '../ui/glass'; +import { toast } from '../ui/feedback'; +import { EASE_OUT, play } from '../motion'; +import { GROUPS, REPO, type Scenario, type ScenarioId } from './data'; +import type { DemoRouter } from './router'; + +/** Each scenario's glass icon and tone (the glass set is smaller than the line icons). */ +const LOOK: Record = { + normal: ['check', 'green'], + first: ['plus', 'blue'], + stale: ['refresh', 'orange'], + quota: ['chart', 'red'], + hours: ['clock', 'orange'], + paused: ['pause', 'orange'], + expired: ['calendar', 'red'], + http: ['lock', 'orange'], + plain: ['shield', 'grey'], + full: ['phone', 'grey'], +}; + +/** The chip that opens the scenarios. */ +export function scenarioChip(router: DemoRouter): HTMLElement { + const app = document.getElementById('app')!; + + /** Swap the page in place: it dims away and comes back drawn from the scenario, the link saying which. */ + async function pick(s: ScenarioId, done?: string) { + closeSheet(); + router.use(s); + const u = new URL(location.href); + u.searchParams.set('s', s); + history.replaceState(history.state, '', u); + const out = play(app, [{ opacity: 1 }, { opacity: 0, filter: 'blur(4px)' }], { duration: 160, easing: EASE_OUT, fill: 'forwards' }); + const st = await call('state'); + await out.finished; + setState(st); + repaint(); + out.cancel(); + play( + app, + [ + { opacity: 0, filter: 'blur(4px)', transform: 'translateY(6px)' }, + { opacity: 1, filter: 'none', transform: 'none' }, + ], + { + duration: 420, + easing: EASE_OUT, + }, + ); + if (done) toast(done); + } + + function row(s: Scenario): HTMLElement { + const on = s.id === router.scenario(); + const [icon, tone] = LOOK[s.id]; + return h( + 'button', + { type: 'button', class: `dm-row${on ? ' on' : ''}`, 'aria-pressed': String(on), onclick: () => pick(s.id) }, + glass(icon, tone), + h('span', { class: 't' }, h('b', {}, s.label), h('span', {}, s.about)), + on ? ic('check', 'i dm-tick') : null, + ); + } + + function scenarios(): View { + const el = h( + 'div', + { class: 'view' }, + head('Try a scenario'), + sub('How the page looks in each case. Nothing here connects.'), + ...GROUPS.map((g) => + h('div', { class: 'dm-group' }, h('div', { class: 'lbl-s' }, g.title), h('div', { class: 'dm-list' }, ...g.items.map(row))), + ), + h( + 'div', + { class: 'dm-foot' }, + h( + 'button', + { type: 'button', class: 'btn soft', onclick: () => pick(router.scenario(), 'The demo started over') }, + ic('reset'), + h('span', {}, 'Start over'), + ), + h('a', { class: 'btn soft dm-gh-alt', href: REPO, target: '_blank', rel: 'noopener' }, ic('github'), h('span', {}, 'GitHub')), + ), + ); + return { el, label: 'Try a scenario' }; + } + + return h( + 'button', + { type: 'button', class: 'dm-chip', 'aria-haspopup': 'dialog', onclick: () => openSheet(scenarios) }, + h('span', {}, 'Demo'), + ic('chevron', 'i'), + ); +} diff --git a/web/src/portal/demo/router.ts b/web/src/portal/demo/router.ts new file mode 100644 index 0000000..f583688 --- /dev/null +++ b/web/src/portal/demo/router.ts @@ -0,0 +1,226 @@ +// The demo's router: portal.uc's API (state, add a device, its settings, +// rename / reconnect / remove) answered from the demo's own devices, which it +// keeps per visitor. The refusals are the router's (paused, ended, plain HTTP, +// no free slot, a name taken). Nothing is installed and no tunnel exists: the +// keys are random and the server's address never resolves. The page state +// itself is data.ts; serve.ts puts this router behind the page's fetch. + +import type { AwgConfig, Kind } from '../../shared/types'; +import { ENDPOINT, deviceLimit, isScenario, pageState, seedDevices, type DemoDevice, type ScenarioId } from './data'; + +/** What the router remembers for this visitor. */ +export interface DemoDb { + scenario: ScenarioId; + devs: DemoDevice[]; + /** The next tunnel address (10.8.0.n). */ + next: number; +} + +/** Where the devices are kept between visits (localStorage in the page, a map in tests). */ +export interface Keep { + load(): unknown; + save(db: DemoDb): void; +} + +export interface Answer { + status: number; + body: unknown; +} + +export interface RouterOpts { + keep: Keep; + /** The scenario the link asks for (?s=), if any: it wins over the one kept. */ + want: string | null; + /** This page over HTTPS, for the plain-HTTP scenario's refusals. */ + secureUrl: () => string; + /** Epoch seconds. */ + clock?: () => number; + /** Random bytes (the keys and ids). */ + random?: (n: number) => Uint8Array; +} + +/** A settings sheet waits for the first connection: it comes this long after the settings are shown. */ +export const CONNECT_AFTER = [6, 9]; + +class Refusal { + constructor( + public status: number, + public body: Record, + ) {} +} +function refuse(status: number, error: string, extra: Record = {}): never { + throw new Refusal(status, { error, ...extra }); +} + +/** A kept db that still fits the demo, or null (an older demo, a hand-edited one). */ +function valid(v: unknown): DemoDb | null { + const db = v as DemoDb | null; + return db && isScenario(db.scenario) && Array.isArray(db.devs) && Number.isInteger(db.next) ? db : null; +} + +const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other']; +const NAME_MAX = 32; + +export function createRouter(o: RouterOpts) { + const clock = o.clock ?? (() => Math.floor(Date.now() / 1000)); + const random = o.random ?? ((n: number) => crypto.getRandomValues(new Uint8Array(n))); + const hex = (n: number) => [...random(n)].map((b) => b.toString(16).padStart(2, '0')).join(''); + const key = () => btoa(String.fromCharCode(...random(32))); + const newId = () => `d_${hex(4)}`; + const soon = () => clock() + CONNECT_AFTER[0] + (random(1)[0] % (CONNECT_AFTER[1] - CONNECT_AFTER[0] + 1)); + + const seed = (s: ScenarioId): DemoDb => ({ scenario: s, devs: seedDevices(s, clock(), newId), next: 5 }); + const kept = valid(o.keep.load()); + let db = kept && (!o.want || kept.scenario === o.want) ? kept : seed(isScenario(o.want) ? o.want : 'normal'); + + const state = () => pageState(db.scenario, db.devs, clock(), o.secureUrl()); + + function needOpen() { + if (db.scenario === 'paused') refuse(403, 'Your access is paused.'); + if (db.scenario === 'expired') refuse(403, 'Your access has ended.'); + } + function needHttps() { + if (db.scenario === 'http') refuse(403, 'Open this link over HTTPS to get the connection settings.', { https_url: o.secureUrl() }); + } + function own(id: string): DemoDevice { + return db.devs.find((x) => x.id === id) ?? refuse(404, 'Device not found.'); + } + function checkName(v: unknown, self?: DemoDevice): string { + const name = String(v ?? '').trim(); + if (!name) refuse(400, 'Give the device a name.'); + if (name.length > NAME_MAX) refuse(400, `A name is at most ${NAME_MAX} characters.`); + if (db.devs.some((d) => d !== self && d.name.toLowerCase() === name.toLowerCase())) + refuse(409, 'You already have a device with this name.'); + return name; + } + + /** A configuration that looks the part and connects nowhere: random keys, the server's address never resolves. */ + function config(d: DemoDevice): AwgConfig { + const plain = db.scenario === 'plain'; + const priv = key(); + const psk = key(); + const srv = 'DEMOdemoDEMOdemoDEMOdemoDEMOdemoDEMOdemo0k='; + const mtu = d.kind === 'phone' || d.kind === 'tablet' ? '1280' : '1376'; + const obf: Record = plain ? {} : OBF; + const lines = ['[Interface]', `PrivateKey = ${priv}`, `Address = 10.8.0.${d.n}/32`, 'DNS = 10.8.0.1', `MTU = ${mtu}`]; + // The .conf names: jc → Jc, jmin → Jmin, h1 → H1. + for (const [k, v] of Object.entries(obf)) lines.push(`${k[0].toUpperCase()}${k.slice(1)} = ${v}`); + lines.push('', '[Peer]', `PublicKey = ${srv}`, `PresharedKey = ${psk}`, 'AllowedIPs = 0.0.0.0/0, ::/0'); + lines.push(`Endpoint = ${ENDPOINT}:51820`, 'PersistentKeepalive = 25'); + return { + name: d.name, + person: 'User', + server: 'Dawnline Preview', + filename: 'Dawnline-Preview.conf', + conf: lines.join('\n') + '\n', + has_private_key: true, + amnezia: { + host: ENDPOINT, + port: 51820, + mtu, + dns: ['10.8.0.1'], + allowed_ips: ['0.0.0.0/0', '::/0'], + client_ip: `10.8.0.${d.n}`, + client_priv_key: priv, + client_pub_key: key(), + psk_key: psk, + server_pub_key: srv, + persistent_keep_alive: '25', + obfuscation: obf, + }, + }; + } + + function add(b: Record) { + needOpen(); + needHttps(); + if (db.devs.length >= deviceLimit(db.scenario)) refuse(409, 'All your device slots are taken.'); + const d: DemoDevice = { + id: newId(), + name: checkName(b.name), + kind: KINDS.includes(b.kind as Kind) ? (b.kind as Kind) : 'other', + n: db.next++, + gb: 0, + hs: 0, + connectAt: soon(), + created: clock(), + by: 'portal', + stale: false, + }; + db.devs.push(d); + return { id: d.id, config: config(d), state: state() }; + } + + /** Showing the settings is "issuing" them: no longer stale, and a device never set up connects soon. */ + function settings(id: string) { + const d = own(id); + needOpen(); + needHttps(); + d.stale = false; + if (!d.hs && !d.connectAt) d.connectAt = soon(); + return config(d); + } + + function act(id: string, b: Record) { + const d = own(id); + needOpen(); + let extra = {}; + if (b.action === 'rename') d.name = checkName(b.name, d); + else if (b.action === 'reconnect') { + needHttps(); + // New keys: the old handshake no longer counts, the device connects again once set up. + d.hs = 0; + d.stale = false; + d.connectAt = soon(); + extra = { config: config(d) }; + } else if (b.action === 'delete') db.devs = db.devs.filter((x) => x !== d); + else refuse(400, 'Unknown action.'); + return { ok: true, ...extra, state: state() }; + } + + /** One API call: `path` is what follows //api/. */ + function answer(method: string, path: string, body: Record = {}): Answer { + const segs = path.split('/').filter(Boolean); + const route = `${method} ${segs.map((s, i) => (i === 1 && segs[0] === 'devices' ? '*' : s)).join('/')}`; + try { + let res: unknown; + if (route === 'GET state') res = state(); + else if (route === 'POST devices') res = add(body); + else if (route === 'GET devices/*/config') res = settings(segs[1]); + else if (route === 'POST devices/*') res = act(segs[1], body); + else refuse(404, 'Not found.'); + o.keep.save(db); + return { status: 200, body: res }; + } catch (e) { + if (e instanceof Refusal) return { status: e.status, body: e.body }; + throw e; + } + } + + return { + answer, + scenario: () => db.scenario, + /** Start a scenario over: its own devices, nothing added. */ + use(s: ScenarioId) { + db = seed(s); + o.keep.save(db); + }, + }; +} + +export type DemoRouter = ReturnType; + +/** The disguise the demo's server would hand out (AmneziaWG 2.0 shapes, made-up values). */ +const OBF: Record = { + jc: '4', + jmin: '40', + jmax: '70', + s1: '57', + s2: '121', + s3: '29', + s4: '18', + h1: '1293844551-1293844599', + h2: '2741190832-2741190880', + h3: '3820045117-3820045165', + h4: '918274635-918274683', +}; diff --git a/web/src/portal/demo/serve.ts b/web/src/portal/demo/serve.ts new file mode 100644 index 0000000..1476aff --- /dev/null +++ b/web/src/portal/demo/serve.ts @@ -0,0 +1,45 @@ +// Puts the demo's router behind the page: fetch() to /api/... is answered +// in the browser, after a router-like pause, and never leaves the page. The +// devices are kept in localStorage (a private window starts fresh each time). +// Imported first by demo/main.ts: it must own fetch before the portal asks. + +import { createRouter, type DemoDb } from './router'; + +const STORE = 'dawnline-demo'; + +export const router = createRouter({ + keep: { + load() { + try { + return JSON.parse(localStorage.getItem(STORE) ?? 'null'); + } catch { + return null; // storage off or a broken entry: the demo starts over + } + }, + save(db: DemoDb) { + try { + localStorage.setItem(STORE, JSON.stringify(db)); + } catch { + /* storage off: the devices last until the page is closed */ + } + }, + }, + want: new URLSearchParams(location.search).get('s'), + // "Open securely" leads back to the demo as it is with HTTPS. + secureUrl: () => `${location.origin}${location.pathname}?s=normal`, +}); + +const pause = (ms: number) => new Promise((ok) => setTimeout(ok, ms)); + +const realFetch = window.fetch.bind(window); +window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : String(input), location.href); + const at = url.pathname.indexOf('/api/'); + if (url.origin !== location.origin || at < 0) return realFetch(input, init); + const method = init?.method ?? 'GET'; + const body = typeof init?.body === 'string' ? (JSON.parse(init.body) as Record) : {}; + // A router takes a moment, a change longer: busy buttons show their orb, as they would. + await pause(method === 'POST' ? 450 + Math.random() * 350 : 120); + const a = router.answer(method, url.pathname.slice(at + 5), body); + return new Response(JSON.stringify(a.body), { status: a.status, headers: { 'Content-Type': 'application/json' } }); +}; diff --git a/web/tests/demo.test.ts b/web/tests/demo.test.ts new file mode 100644 index 0000000..6b678c3 --- /dev/null +++ b/web/tests/demo.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from 'vitest'; +import { createRouter, type DemoDb, type Keep } from '../src/portal/demo/router'; +import { SCENARIOS, hoursAway, monthDays } from '../src/portal/demo/data'; +import type { State } from '../src/portal/state'; +import type { AwgConfig } from '../src/shared/types'; + +const SECURE = 'https://demo.example/?s=normal'; + +/** A router over a kept db in memory, on a clock the test moves. */ +function demo(want: string | null = null, kept: unknown = null) { + let t = 1_792_400_000; + let saved: unknown = kept; + const keep: Keep = { load: () => saved, save: (db: DemoDb) => (saved = JSON.parse(JSON.stringify(db))) }; + const r = createRouter({ keep, want, secureUrl: () => SECURE, clock: () => t }); + const state = () => r.answer('GET', 'state').body as State; + return { r, state, saved: () => saved, later: (s: number) => (t += s) }; +} + +describe('demo router', () => { + it('answers every scenario with a page state', () => { + for (const s of SCENARIOS) { + const { state } = demo(s.id); + const st = state(); + expect(st.person.name).toBe('User'); + expect(st.person.devices.length).toBe(s.id === 'first' ? 0 : 3); + } + expect(demo('paused').state().person.state).toBe('paused'); + expect(demo('paused').state().locked).toBe(true); + expect(demo('plain').state().server).toMatchObject({ awg_disguise: false, preset: 'off' }); + expect(demo('full').state().can_add).toBe(false); + expect(demo('http').state().https_url).toBe(SECURE); + expect( + demo('stale') + .state() + .person.devices.find((d) => d.name === 'MacBook Pro')?.config_stale, + ).toBe(true); + }); + + it('starts on the scenario the link asks for, else the one kept', () => { + const first = demo('quota'); + first.state(); // the page's first call keeps what it showed + expect(demo(null, first.saved()).r.scenario()).toBe('quota'); + expect(demo('paused', first.saved()).r.scenario()).toBe('paused'); + expect(demo('nonsense').r.scenario()).toBe('normal'); + expect(demo(null, { scenario: 'gone', devs: 3 }).r.scenario()).toBe('normal'); + }); + + it('adds a device that connects a few seconds after its settings', () => { + const { r, state, later } = demo(); + const a = r.answer('POST', 'devices', { name: 'Pixel 9', kind: 'phone' }); + expect(a.status).toBe(200); + const { id, config } = a.body as { id: string; config: AwgConfig }; + expect(config.conf).toMatch(/^Endpoint = demo\.dawnline\.invalid:51820$/m); + expect(config.conf).toMatch(/^Jmin = 40$/m); + expect(state().person.devices.find((d) => d.id === id)?.handshake).toBe(0); + later(10); + const d = state().person.devices.find((x) => x.id === id)!; + expect(d.handshake).toBeGreaterThan(0); + expect(d.online).toBe(true); + }); + + it('refuses what the router refuses', () => { + const { r } = demo(); + expect(r.answer('POST', 'devices', { name: 'iphone 16', kind: 'phone' }).status).toBe(409); + expect(r.answer('POST', 'devices', { name: ' ', kind: 'phone' }).status).toBe(400); + expect(r.answer('GET', 'devices/d_00000000/config').status).toBe(404); + expect(r.answer('POST', 'devices/d_00000000', { action: 'rename', name: 'x' }).status).toBe(404); + expect(demo('paused').r.answer('POST', 'devices', { name: 'New', kind: 'phone' }).body).toEqual({ error: 'Your access is paused.' }); + const http = demo('http'); + const id = http.state().person.devices[0].id; + expect(http.r.answer('GET', `devices/${id}/config`)).toEqual({ + status: 403, + body: { error: 'Open this link over HTTPS to get the connection settings.', https_url: SECURE }, + }); + }); + + it('renames, reconnects and removes a device', () => { + const { r, state, later } = demo(); + const id = state().person.devices[0].id; + r.answer('POST', `devices/${id}`, { action: 'rename', name: 'Work iPhone' }); + expect(state().person.devices[0].name).toBe('Work iPhone'); + const re = r.answer('POST', `devices/${id}`, { action: 'reconnect' }).body as { config: AwgConfig; state: State }; + expect(re.config.conf).toMatch(/^PrivateKey = .{44}$/m); + expect(re.state.person.devices[0].handshake).toBe(0); + later(10); + expect(state().person.devices[0].handshake).toBeGreaterThan(0); + r.answer('POST', `devices/${id}`, { action: 'delete' }); + expect(state().person.devices.map((d) => d.id)).not.toContain(id); + }); + + it('starts a scenario over', () => { + const { r, state } = demo('normal'); + r.answer('POST', 'devices', { name: 'Pixel 9', kind: 'phone' }); + r.use('first'); + expect(state().person.devices).toEqual([]); + expect(r.scenario()).toBe('first'); + }); +}); + +describe('demo data', () => { + it('spreads the month over its days', () => { + const t = new Date(2026, 9, 19, 12).getTime() / 1000; + const days = monthDays(1000, t); + expect(days).toHaveLength(19); + expect(Math.abs(days.reduce((a, b) => a + b, 0) - 1000)).toBeLessThanOrEqual(19); + }); + + it('keeps the hours scenario outside its window', () => { + expect(hoursAway(new Date(2026, 9, 19, 22, 30).getTime() / 1000)).toBe('00:00-08:00'); + expect(hoursAway(new Date(2026, 9, 19, 9).getTime() / 1000)).toBe('11:00-19:00'); + }); +}); diff --git a/web/tsup.demo.config.ts b/web/tsup.demo.config.ts new file mode 100644 index 0000000..7c8e458 --- /dev/null +++ b/web/tsup.demo.config.ts @@ -0,0 +1,41 @@ +import { defineConfig } from 'tsup'; +import { build } from 'esbuild'; +import fs from 'node:fs'; +import path from 'node:path'; + +// The portal demo: a static site in dist/demo (vercel.json deploys it). The +// real portal with the demo's router in the page (src/portal/demo); its +// stylesheet is the portal's plus the demo's pieces, its shell is portal.uc's. +const OUT = 'dist/demo'; + +export default defineConfig({ + entry: { portal: 'src/portal/demo/main.ts' }, + format: ['iife'], + outDir: OUT, + outExtension: () => ({ js: '.js' }), + target: 'es2019', + // Not cleaned: the folder may hold Vercel's project link (.vercel). + clean: false, + sourcemap: false, + minify: true, + noExternal: ['qrcode-generator'], + esbuildOptions(o) { + o.legalComments = 'none'; + o.charset = 'utf8'; + }, + onSuccess: async () => { + const css = await build({ + entryPoints: ['src/portal/demo/demo.css'], + bundle: true, + minify: true, + write: false, + legalComments: 'none', + external: ['*.woff2'], + logLevel: 'silent', + }); + fs.writeFileSync(path.join(OUT, 'portal.css'), css.outputFiles[0].text.trim() + '\n'); + fs.copyFileSync('src/portal/demo/index.html', path.join(OUT, 'index.html')); + fs.copyFileSync('src/portal/icon.svg', path.join(OUT, 'icon.svg')); + for (const f of fs.readdirSync('src/portal/fonts')) fs.copyFileSync(path.join('src/portal/fonts', f), path.join(OUT, f)); + }, +}); diff --git a/web/vercel.json b/web/vercel.json new file mode 100644 index 0000000..59f9e7e --- /dev/null +++ b/web/vercel.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "framework": null, + "installCommand": "npm ci", + "buildCommand": "npm run build:demo", + "outputDirectory": "dist/demo", + "ignoreCommand": "[ \"$VERCEL_GIT_COMMIT_REF\" != main ] || git diff --quiet HEAD^ HEAD -- .", + "headers": [ + { + "source": "/(.*)", + "headers": [ + { + "key": "Content-Security-Policy", + "value": "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'" + }, + { "key": "X-Content-Type-Options", "value": "nosniff" }, + { "key": "Referrer-Policy", "value": "no-referrer" }, + { "key": "X-Frame-Options", "value": "DENY" } + ] + } + ] +}