Dawnline 0.1.0: AmneziaWG access server for OpenWrt
Build packages / Version (push) Waiting to run

LuCI admin (people, devices, limits, disguise, health, updates, backups)
and a personal self-service portal, built as ipk (OpenWrt 24.10) and apk
(OpenWrt 25.12) with the OpenWrt SDK. Successor of openwrt-liminal.

- install.sh: checks the router, installs AmneziaWG for its firmware,
  then the release package verified against sha256sums.txt
- CI: Prettier, types, tests, committed bundles, ShellCheck, ucode checks;
  tagged releases build both packages and publish them
- Web bundles minified with esbuild (JS and CSS)
- README with framed screenshots
This commit is contained in:
Aemeath committed 2026-10-15 03:29:30 +03:00
commit a3910f8b97
105 files changed
+22278

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
// Tiny SVG bar chart for daily traffic (download stacked over upload).
import type { DayUsage } from './types';
import { bytes } from './format';
export function trafficChart(series: DayUsage[], height = 120): string {
const w = 600;
const pad = 2;
const n = Math.max(series.length, 1);
const bw = w / n;
const max = Math.max(1, ...series.map((d) => d.rx + d.tx));
let bars = '';
series.forEach((d, i) => {
const x = i * bw + pad / 2;
// From the person's point of view: router tx = download, rx = upload.
const hDown = (d.tx / max) * (height - 4);
const hUp = (d.rx / max) * (height - 4);
const title = `${d.day}: ↓ ${bytes(d.tx)} · ↑ ${bytes(d.rx)}`;
bars +=
`<g><title>${title}</title>` +
`<rect x="${x.toFixed(1)}" y="${(height - hDown - hUp).toFixed(1)}" width="${(bw - pad).toFixed(1)}" height="${hDown.toFixed(1)}" rx="1.5" class="dl-bar-down"/>` +
`<rect x="${x.toFixed(1)}" y="${(height - hUp).toFixed(1)}" width="${(bw - pad).toFixed(1)}" height="${hUp.toFixed(1)}" rx="1.5" class="dl-bar-up"/>` +
`<rect x="${(i * bw).toFixed(1)}" y="0" width="${bw.toFixed(1)}" height="${height}" fill="transparent"/></g>`;
});
return `<svg class="dl-chart" viewBox="0 0 ${w} ${height}" preserveAspectRatio="none" role="img" aria-label="Traffic per day">${bars}</svg>`;
}
+120
View File
@@ -0,0 +1,120 @@
// Formatting helpers shared by the admin UI and the portal (English only).
import type { Access, Kind, PersonState } from './types';
export function bytes(n: number): string {
if (!n || n < 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let v = n;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
}
/** Bytes per second as a bit rate. */
export function bits(bps: number): string {
const b = bps * 8;
if (b < 1000) return `${Math.round(b)} bit/s`;
if (b < 1e6) return `${(b / 1e3).toFixed(b < 1e4 ? 1 : 0)} kbit/s`;
if (b < 1e9) return `${(b / 1e6).toFixed(b < 1e7 ? 1 : 0)} Mbit/s`;
return `${(b / 1e9).toFixed(1)} Gbit/s`;
}
export function ago(ts: number, now = Date.now() / 1000): string {
if (!ts) return 'never';
const d = Math.max(0, Math.round(now - ts));
if (d < 60) return 'just now';
if (d < 3600) return `${Math.floor(d / 60)} min ago`;
if (d < 86400) return `${Math.floor(d / 3600)} h ago`;
if (d < 86400 * 30) return `${Math.floor(d / 86400)} d ago`;
return new Date(ts * 1000).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}
export function duration(sec: number): string {
if (!sec || sec < 0) return '—';
const d = Math.floor(sec / 86400);
const h = Math.floor((sec % 86400) / 3600);
const m = Math.floor((sec % 3600) / 60);
if (d) return `${d}d ${h}h`;
if (h) return `${h}h ${m}m`;
return `${m}m`;
}
export function clock(ts: number): string {
const d = new Date(ts * 1000);
const today = new Date();
const sameDay = d.toDateString() === today.toDateString();
const t = d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
return sameDay ? t : `${d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })} ${t}`;
}
export function date(s: string): string {
if (!s) return '';
const [y, m, d] = s.split('-').map(Number);
return new Date(y, m - 1, d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}
/** Whole days until the end of the given YYYY-MM-DD (negative when past). */
export function daysLeft(s: string, now = Date.now()): number | null {
if (!s) return null;
const [y, m, d] = s.split('-').map(Number);
const end = new Date(y, m - 1, d, 23, 59, 59).getTime();
return Math.ceil((end - now) / 86400000);
}
export const ACCESS_LABEL: Record<Access, string> = {
lan: 'Home network',
internet: 'Internet',
both: 'Home network + Internet',
};
export const ACCESS_SHORT: Record<Access, string> = { lan: 'LAN', internet: 'Internet', both: 'LAN + Internet' };
/** In picker order. */
export const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other'];
export const KIND_LABEL: Record<Kind, string> = {
computer: 'PC',
phone: 'Phone',
tablet: 'Tablet',
router: 'Router',
other: 'Other',
};
export const STATE_LABEL: Record<PersonState, string> = {
active: 'Active',
paused: 'Paused',
paused_all: 'Paused (everyone)',
expired: 'Expired',
quota: 'Data limit reached',
hours: 'Outside allowed hours',
no_server: 'No server',
};
export function initials(name: string): string {
const parts = name.trim().split(/\s+/).filter(Boolean);
if (!parts.length) return '?';
const a = parts[0][0] ?? '';
const b = parts.length > 1 ? (parts[parts.length - 1][0] ?? '') : (parts[0][1] ?? '');
return (a + b).toUpperCase();
}
/** "1.2 GB of 50 GB" style quota text, or just usage when unlimited. */
export function quotaText(used: number, quotaGb: number, period: 'month' | 'total'): string {
const u = bytes(used);
if (!quotaGb) return `${u} ${period === 'total' ? 'in total' : 'this month'}`;
return `${u} of ${quotaGb} GB${period === 'total' ? '' : ' this month'}`;
}
export function slugify(s: string): string {
return s
.toLowerCase()
.normalize('NFKD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 32);
}
+67
View File
@@ -0,0 +1,67 @@
// Inline SVG icons (stroke = currentColor), sized by CSS.
const P: Record<string, string> = {
phone: '<rect x="7" y="2.5" width="10" height="19" rx="2.2"/><path d="M11 18.5h2"/>',
computer: '<rect x="3" y="4.5" width="18" height="12" rx="1.8"/><path d="M2 19.5h20"/>',
tablet: '<rect x="4.5" y="2.5" width="15" height="19" rx="2.2"/><path d="M11 18.5h2"/>',
router: '<rect x="3" y="13" width="18" height="7" rx="1.8"/><path d="M7 16.5h.01M10.5 16.5h.01M8 13l-2-6M16 13l2-6"/>',
other: '<path d="M12 3 20 7.5v9L12 21l-8-4.5v-9L12 3Z"/><path d="M4 7.5 12 12l8-4.5M12 12v9"/>',
ethernet:
'<rect x="9" y="3" width="6" height="5" rx="1"/><rect x="3" y="16" width="6" height="5" rx="1"/><rect x="15" y="16" width="6" height="5" rx="1"/><path d="M12 8v4M6 16v-4h12v4"/>',
bridge: '<circle cx="6" cy="6" r="2.2"/><circle cx="18" cy="18" r="2.2"/><path d="M6 8.2v4.3a4 4 0 0 0 4 4h5.8"/>',
wifi: '<path d="M4.5 9.5a11 11 0 0 1 15 0M7.5 12.8a6.5 6.5 0 0 1 9 0M10.6 16a2 2 0 0 1 2.8 0"/><circle cx="12" cy="19" r=".6"/>',
tunnel: '<path d="M9.5 14.5 14.5 9.5"/><path d="M11 6.5l1.5-1.5a4.2 4.2 0 0 1 6 6L17 12.5M13 17.5 11.5 19a4.2 4.2 0 0 1-6-6L7 11.5"/>',
plus: '<path d="M12 5v14M5 12h14"/>',
chart: '<path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/>',
reset: '<path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.5"/><path d="M4 4v4.5h4.5"/>',
package: '<path d="M12 3 20 7.5v9L12 21l-8-4.5v-9L12 3Z"/><path d="M4 7.5 12 12l8-4.5M12 12v9M8 5.3l8 4.5"/>',
code: '<path d="m8 8-4 4 4 4M16 8l4 4-4 4M13.5 5l-3 14"/>',
plug: '<path d="M9 3v5M15 3v5M6 8h12v3a6 6 0 0 1-12 0V8ZM12 17v4"/>',
sunrise: '<path d="M4 16a8 8 0 0 1 16 0z"/><path d="M2 19.5h20"/>',
refresh: '<path d="M20 12a8 8 0 1 1-2.4-5.7L20 8.5"/><path d="M20 4v4.5h-4.5"/>',
archive: '<rect x="3" y="4" width="18" height="5" rx="1.2"/><path d="M5 9v10h14V9M10 13h4"/>',
qr: '<rect x="4" y="4" width="6" height="6" rx="1"/><rect x="14" y="4" width="6" height="6" rx="1"/><rect x="4" y="14" width="6" height="6" rx="1"/><path d="M14 14h2v2h-2zM18 18h2v2h-2zM14 18h2M18 14h2"/>',
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"/>',
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"/>',
play: '<path d="M7 4l13 8-13 8z"/>',
key: '<circle cx="8" cy="15" r="4"/><path d="M11 12l8-8M16 7l2 2"/>',
out: '<path d="M14 4h6v16h-6M10 8l-4 4 4 4M6 12h10"/>',
shield: '<path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"/>',
shieldplus: '<path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"/><path d="M12 9v6M9 12h6"/>',
lock: '<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/><path d="M12 14.5v2"/>',
zap: '<path d="M13 3 5 13.5h6L10 21l8-10.5h-6L13 3z"/>',
check: '<path d="M5 12.5l4.5 4.5L19 7.5"/>',
alert: '<path d="M12 3l9.5 17h-19z"/><path d="M12 10v4M12 17h.01"/>',
x: '<path d="M6 6l12 12M18 6L6 18"/>',
globe: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.5 3 14.5 0 18M12 3c-3 3.5-3 14.5 0 18"/>',
home: '<path d="M3 11l9-7 9 7"/><path d="M5 10v10h14V10"/>',
open: '<path d="M14 4h6v6M20 4l-9 9M18 14v6H4V6h6"/>',
file: '<path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/>',
search: '<circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/>',
network:
'<circle cx="12" cy="12" r="2.5"/><circle cx="5" cy="5" r="1.8"/><circle cx="19" cy="5" r="1.8"/><circle cx="5" cy="19" r="1.8"/><circle cx="19" cy="19" r="1.8"/><path d="m6.4 6.4 3.8 3.8M17.6 6.4l-3.8 3.8M6.4 17.6l3.8-3.8M17.6 17.6l-3.8-3.8"/>',
moon: '<path d="M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z"/>',
chevron: '<path d="m9 6 6 6-6 6"/>',
clock: '<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/>',
calendar: '<rect x="4" y="5" width="16" height="16" rx="2"/><path d="M8 3v4M16 3v4M4 10h16"/>',
minus: '<path d="M5 12h14"/>',
more: '<circle cx="5" cy="12" r="1.2"/><circle cx="12" cy="12" r="1.2"/><circle cx="19" cy="12" r="1.2"/>',
pin: '<path d="M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z"/><circle cx="12" cy="9.5" r="2.5"/>',
activity: '<path d="M3 12h4l3-8 4 16 3-8h4"/>',
};
export function iconSvg(name: string, cls = 'dl-icon'): string {
const body = P[name] ?? P.phone;
return `<svg class="${cls}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
}
export function icon(name: string, cls = 'dl-icon'): HTMLElement {
const span = document.createElement('span');
span.className = 'dl-icon-wrap';
span.innerHTML = iconSvg(name, cls);
return span;
}
+49
View File
@@ -0,0 +1,49 @@
// 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.
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 function qrSvg(text: string, margin = 3, logo = true): string {
const qr = qrcode(0, text.length > 300 ? 'Q' : '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;
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;
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;
}
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 = '';
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>`;
}
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>`
);
}
+202
View File
@@ -0,0 +1,202 @@
// Shapes returned by the luci.dawnline RPC object and the portal API.
export type Access = 'lan' | 'internet' | 'both';
export type Kind = 'computer' | 'phone' | 'tablet' | 'router' | 'other';
export type PersonState = 'active' | 'paused' | 'paused_all' | 'expired' | 'quota' | 'hours' | 'no_server';
export type Pair = [number, number]; // [rx, tx] from the router's point of view
export interface Device {
id: string;
name: string;
kind: Kind;
address: string;
disabled: boolean;
created: number;
created_by: 'admin' | 'portal';
online: boolean;
handshake: number;
endpoint: string;
active: boolean;
month: Pair;
total: Pair;
/** Daily totals (rx+tx) for the last 7 days, oldest first. */
spark: number[];
hostname: string;
browser_key: boolean;
/** Its configuration changed (networks, DNS, keys...) since it was last shown or downloaded. */
config_stale: boolean;
}
export interface Person {
id: string;
name: string;
server: string;
access: Access;
device_limit: number;
expires: string;
quota_gb: number;
quota_period: 'month' | 'total';
quota_used: number;
/** Effective limit in bytes for the current period (incl. this month's extra), 0 = unlimited. */
quota_limit: number;
bonus_gb: number;
expire_action: 'pause' | 'notify' | 'remove';
expire_warn: number;
/** Home-only access: the device keeps its own DNS, or uses home names through the tunnel. */
dns_mode: 'device' | 'home';
paused: boolean;
hours: string;
state: PersonState;
month: Pair;
total: Pair;
online: number;
last_seen: number;
devices: Device[];
/** Throughput, one point a minute (last 15): [ts, rx, tx] in bytes/s (rx = from devices); admin only. */
rate?: [number, number, number][];
// admin only
code?: string;
link?: string | null;
/** Every link to the same portal (main first), one per address; admin only. */
links?: string[];
note?: string;
services?: string[];
created?: number;
}
export interface Server {
id: string;
name: string;
ifname: string;
port: number;
subnet: string;
endpoint: string;
public_key: string;
enabled: boolean;
/** Internet traffic enters the router from the LAN, like a home device's. */
lan_like: boolean;
preset: string;
mtu: number;
keepalive: number;
/** DNS servers given to devices; empty = this router. */
dns: string[];
/** Daily traffic of the people on this server. */
series: DayUsage[];
/** Throughput, one point a minute: [ts, rx, tx] in bytes/s (rx = from devices). */
rate: [number, number, number][];
address: string;
up: boolean;
uptime: number;
peers: number;
online: number;
obf: Record<string, string>;
}
export interface DayUsage {
day: string;
rx: number;
tx: number;
}
export interface LogEvent {
ts: number;
type: string;
person?: string;
device?: string;
server?: string;
detail?: string;
/** City · network operator, when known at the time of the event. */
where?: string | null;
}
export interface GeoPoint {
person: string;
device: string;
ip: string;
ts: number;
online: boolean;
lat: number;
lon: number;
city: string;
country: string;
cc: string;
/** Network operator (from the geolocation service); 0 / '' when unknown. */
asn: number;
org: string;
}
export interface Geo {
enabled: boolean;
provider?: string;
cached?: number;
home: { lat: number; lon: number; city: string; country: string; cc: string; asn?: number; org?: string } | null;
points: GeoPoint[];
}
export interface AwgCaps {
v2: boolean;
v3: boolean;
}
export interface Status {
geo: Geo;
version: string;
now: number;
hostname: string;
settings: {
portal_enabled: boolean;
portal_port: number;
/** The port in personal links (443 when the portal also answers there). */
portal_public_port?: number;
portal_443?: boolean;
portal_host: string;
paused_all: boolean;
default_device_limit: number;
domain: string;
hostnames: boolean;
geo_enabled: boolean;
home_dns_fallback: string;
};
servers: Server[];
people: Person[];
services: { id: string; name: string; address: string; ports: string[] }[];
totals: { people: number; devices: number; online: number; active: number; today: Pair; month: Pair };
series: DayUsage[];
events: LogEvent[];
/** What the installed AmneziaWG supports: v2 (1.5/2.0 parameters), v3 (3.1). */
awg: AwgCaps;
like_home: { active: boolean; dev?: string; address?: string; bridged?: boolean; off?: boolean; error?: string };
}
export interface AmneziaFields {
host: string;
port: number;
mtu: string;
dns: string[];
allowed_ips: string[];
client_ip: string;
client_priv_key: string;
client_pub_key: string;
psk_key: string;
server_pub_key: string;
persistent_keep_alive: string;
obfuscation: Record<string, string>;
}
export interface ClientConfig {
name: string;
person: string;
server: string;
filename: string;
conf: string;
has_private_key: boolean;
amnezia: AmneziaFields;
}
export interface HealthCheck {
id: string;
title: string;
status: 'ok' | 'warn' | 'error' | 'skip';
detail: string;
fix: string | null;
}
+146
View File
@@ -0,0 +1,146 @@
// AmneziaVPN `vpn://` keys: "vpn://" + base64url (no padding) of Qt's
// qCompress(JSON) — a 4-byte big-endian length followed by a zlib stream.
// AmneziaVPN also accepts plain JSON, used when CompressionStream is missing.
import type { ClientConfig } from './types';
const DEFAULTS: Record<string, string> = {
jc: '0',
jmin: '0',
jmax: '0',
s1: '0',
s2: '0',
s3: '0',
s4: '0',
h1: '1',
h2: '2',
h3: '3',
h4: '4',
i1: '',
i2: '',
i3: '',
i4: '',
i5: '',
};
/** AmneziaWG 3.1 settings, under the names AmneziaVPN uses; only those that are set. */
const AWG3: Record<string, string> = {
header_protection_key: 'HeaderProtectionKey',
content_padding_addition: 'ContentPaddingAddition',
rekey_after_time: 'RekeyAfterTime',
rekey_timeout: 'RekeyTimeout',
reject_after_time: 'RejectAfterTime',
keepalive_timeout: 'KeepaliveTimeout',
max_handshake_attempts: 'MaxHandshakeAttempts',
random_trailers: 'RandomTrailers',
disable_cookies: 'DisableCookies',
};
function awg3(o: Record<string, string>): Record<string, string> {
const out: Record<string, string> = {};
for (const [k, name] of Object.entries(AWG3)) if (o[k] != null && o[k] !== '') out[name] = String(o[k]);
return out;
}
export function amneziaJson(cfg: ClientConfig, description: string): Record<string, unknown> {
const a = cfg.amnezia;
const o = a.obfuscation ?? {};
const v = (k: string) => (o[k] != null && o[k] !== '' ? String(o[k]) : DEFAULTS[k]);
const host = a.host.replace(/^\[(.*)\]$/, '$1');
const last = {
H1: v('h1'),
H2: v('h2'),
H3: v('h3'),
H4: v('h4'),
I1: v('i1'),
I2: v('i2'),
I3: v('i3'),
I4: v('i4'),
I5: v('i5'),
Jc: v('jc'),
Jmin: v('jmin'),
Jmax: v('jmax'),
S1: v('s1'),
S2: v('s2'),
S3: v('s3'),
S4: v('s4'),
...awg3(o),
allowed_ips: a.allowed_ips,
client_ip: a.client_ip,
client_priv_key: a.client_priv_key,
client_pub_key: a.client_pub_key,
config: cfg.conf.replace(/\r?\n/g, '\r\n'),
hostName: host,
mtu: a.mtu,
persistent_keep_alive: a.persistent_keep_alive,
port: Number(a.port),
psk_key: a.psk_key,
server_pub_key: a.server_pub_key,
};
const out: Record<string, unknown> = {
containers: [
{
container: 'amnezia-awg',
awg: {
isThirdPartyConfig: true,
last_config: JSON.stringify(last),
port: String(a.port),
protocol_version: o.header_protection_key ? '3.1' : '2',
transport_proto: 'udp',
},
},
],
defaultContainer: 'amnezia-awg',
description,
hostName: host,
};
if (a.dns[0]) out.dns1 = a.dns[0];
if (a.dns[1]) out.dns2 = a.dns[1];
return out;
}
export function base64Url(bytes: Uint8Array): string {
let bin = '';
for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function fromBase64Url(s: string): Uint8Array {
const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4);
const bin = atob(b64);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
export async function qCompress(data: Uint8Array): Promise<Uint8Array | null> {
// LuCI's module loader shadows some globals; always go through globalThis.
const g = globalThis as unknown as { CompressionStream?: typeof CompressionStream; Blob: typeof Blob; Response: typeof Response };
if (typeof g.CompressionStream === 'undefined') return null;
try {
const stream = new g.Blob([data as Uint8Array<ArrayBuffer>]).stream().pipeThrough(new g.CompressionStream('deflate'));
const zlib = new Uint8Array(await new g.Response(stream).arrayBuffer());
const out = new Uint8Array(4 + zlib.length);
new DataView(out.buffer).setUint32(0, data.length, false);
out.set(zlib, 4);
return out;
} catch {
return null;
}
}
export async function vpnKey(cfg: ClientConfig, description: string, compress = true): Promise<string> {
const json = new TextEncoder().encode(JSON.stringify(amneziaJson(cfg, description)));
const packed = compress ? await qCompress(json) : null;
return `vpn://${base64Url(packed ?? json)}`;
}
/** The .conf with a browser-held private key substituted in. */
export function withPrivateKey(cfg: ClientConfig, priv: string): ClientConfig {
return {
...cfg,
has_private_key: true,
conf: cfg.conf.replace(/^PrivateKey = .*$/m, `PrivateKey = ${priv}`),
amnezia: { ...cfg.amnezia, client_priv_key: priv },
};
}