Files
dsh-lan-share/config.js
T

365 lines
14 KiB
JavaScript

/**
* Configuration, address discovery, and authority helpers for LAN Share.
*
* Everything here is pure Node: the host half validates its own config, finds
* the LAN address a tablet can reach, and turns host/port/protocol into the
* spellings HTTP, cookies, and QR payloads need. No bare package imports, so a
* linked plugin resolves from its own directory without the runtime's
* node_modules.
*/
import { createSocket } from 'node:dgram';
import { isIP } from 'node:net';
import { homedir, networkInterfaces } from 'node:os';
import { isAbsolute, join, resolve } from 'node:path';
/** The default LAN port; a fixed port keeps a paired tablet's bookmark usable across restarts. */
export const DEFAULT_PORT = 47820;
/** The default one-time ticket lifetime. */
export const DEFAULT_TICKET_TTL_SECONDS = 60;
/** The default device lifetime after pairing. */
export const DEFAULT_DEVICE_TTL_DAYS = 7;
/** The default device limit. */
export const DEFAULT_MAX_DEVICES = 16;
/** Default settings for every field. */
export const DEFAULTS = Object.freeze({
enabled: true,
host: null,
publicHost: null,
port: DEFAULT_PORT,
ticketTtlSeconds: DEFAULT_TICKET_TTL_SECONDS,
deviceTtlDays: DEFAULT_DEVICE_TTL_DAYS,
maxDevices: DEFAULT_MAX_DEVICES,
stateFile: null,
tls: null,
relay: {
enabled: false,
url: null,
token: null,
publicOrigin: null,
agentId: null,
fallbackToLan: false,
},
});
/**
* Resolve the Harness home exactly as the host does: DSH_HOME wins, else ~/.dsh.
* @param {NodeJS.ProcessEnv} [env] environment to read.
* @returns {string} absolute home path.
*/
export function resolveDshHome(env = process.env) {
const configured = env.DSH_HOME;
if (typeof configured === 'string' && configured.trim() !== '') return resolve(configured.replace(/^~(?=$|[\\/])/, homedir()));
return join(homedir(), '.dsh');
}
/**
* A positive integer inside a range, or the fallback.
* @param {unknown} value candidate.
* @param {number} fallback default.
* @param {number} min inclusive minimum.
* @param {number} max inclusive maximum.
* @param {string} field field name for the diagnostic.
* @returns {number} the accepted value.
*/
function integerIn(value, fallback, min, max, field) {
if (value === undefined || value === null) return fallback;
if (!Number.isInteger(value) || value < min || value > max) {
throw new TypeError('lan-share: ' + field + ' must be an integer between ' + String(min) + ' and ' + String(max));
}
return value;
}
/**
* Whether a string is a concrete IP literal or an unspecified one.
* @param {string} host candidate.
* @returns {boolean} true for an IPv4 or IPv6 literal.
*/
export function isIpLiteral(host) {
return isIP(host) !== 0;
}
/**
* Whether an address is the unspecified address of its family.
* @param {string} host bind address.
* @returns {boolean} true for 0.0.0.0 or ::.
*/
export function isWildcardHost(host) {
return host === '0.0.0.0' || host === '::' || host === '[::]';
}
/**
* Normalize an absolute http(s) origin without path/query/fragment.
* @param {unknown} value candidate.
* @param {string} field config field for diagnostics.
* @returns {string} origin.
*/
function normalizePublicOrigin(value, field) {
if (typeof value !== 'string' || value === '') throw new TypeError('lan-share: ' + field + ' must be an http(s) origin');
let url;
try {
url = new URL(value);
} catch {
throw new TypeError('lan-share: ' + field + ' must be an http(s) origin');
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new TypeError('lan-share: ' + field + ' must use http or https');
if (url.pathname !== '/' || url.search !== '' || url.hash !== '') {
throw new TypeError('lan-share: ' + field + ' must not carry a path, query, or fragment');
}
return url.origin;
}
/**
* Normalize a tunnel WebSocket URL.
* @param {unknown} value candidate.
* @returns {string} ws(s) URL.
*/
function normalizeRelayUrl(value) {
if (typeof value !== 'string' || value === '') throw new TypeError('lan-share: relay.url must be a ws(s) URL');
let url;
try {
url = new URL(value);
} catch {
throw new TypeError('lan-share: relay.url must be a ws(s) URL');
}
if (url.protocol !== 'ws:' && url.protocol !== 'wss:') throw new TypeError('lan-share: relay.url must use ws or wss');
if (url.hash !== '') throw new TypeError('lan-share: relay.url must not carry a fragment');
return url.href;
}
/**
* Validate and normalize the plugin config object.
* @param {unknown} raw config from the Loader row.
* @param {NodeJS.ProcessEnv} [env] environment for the state-file default.
* @returns {typeof DEFAULTS & { stateFile: string, ticketTtlMs: number, deviceTtlMs: number }} normalized config.
*/
export function normalizeConfig(raw, env = process.env) {
const input = raw !== null && typeof raw === 'object' ? raw : {};
const host = input.host === undefined || input.host === null || input.host === '' ? null : String(input.host);
if (host !== null && !isIpLiteral(host)) throw new TypeError('lan-share: host must be an IP literal or null');
const publicHost = input.publicHost === undefined || input.publicHost === null || input.publicHost === ''
? null
: String(input.publicHost);
if (publicHost !== null) {
if (publicHost.includes('/') || publicHost.includes('://') || /\s/.test(publicHost)) {
throw new TypeError('lan-share: publicHost must be a hostname or IP literal without a scheme or path');
}
}
const port = integerIn(input.port, DEFAULTS.port, 0, 65535, 'port');
const ticketTtlSeconds = integerIn(input.ticketTtlSeconds, DEFAULTS.ticketTtlSeconds, 15, 3600, 'ticketTtlSeconds');
const deviceTtlDays = integerIn(input.deviceTtlDays, DEFAULTS.deviceTtlDays, 1, 365, 'deviceTtlDays');
const maxDevices = integerIn(input.maxDevices, DEFAULTS.maxDevices, 1, 128, 'maxDevices');
const enabled = input.enabled === undefined ? DEFAULTS.enabled : input.enabled === true;
let stateFile;
if (typeof input.stateFile === 'string' && input.stateFile !== '') {
stateFile = isAbsolute(input.stateFile) ? input.stateFile : resolve(input.stateFile);
} else {
stateFile = join(resolveDshHome(env), 'lan-share', 'devices.json');
}
let tls = null;
if (input.tls !== undefined && input.tls !== null) {
const certFile = input.tls.certFile;
const keyFile = input.tls.keyFile;
if (typeof certFile !== 'string' || certFile === '' || typeof keyFile !== 'string' || keyFile === '') {
throw new TypeError('lan-share: tls requires certFile and keyFile paths');
}
tls = { certFile: resolve(certFile), keyFile: resolve(keyFile) };
}
if (host !== null && isWildcardHost(host) && publicHost === null) {
throw new TypeError('lan-share: a wildcard host needs an explicit publicHost for the QR address');
}
const relayRaw = input.relay !== null && typeof input.relay === 'object' ? input.relay : {};
const relayUrlValue = env.DSH_RELAY_URL ?? relayRaw.url ?? null;
const relayTokenValue = env.DSH_RELAY_TOKEN ?? relayRaw.token ?? null;
const relayPublicValue = env.DSH_RELAY_PUBLIC_ORIGIN ?? relayRaw.publicOrigin ?? null;
const relayAgentValue = env.DSH_RELAY_AGENT_ID ?? relayRaw.agentId ?? null;
const relayEnabledRaw = env.DSH_RELAY_ENABLED ?? relayRaw.enabled;
const relayEnabled = relayEnabledRaw === undefined
? Boolean(relayUrlValue !== null && relayTokenValue !== null)
: relayEnabledRaw === true || relayEnabledRaw === '1' || relayEnabledRaw === 'true';
let relay = {
enabled: relayEnabled,
url: null,
token: null,
publicOrigin: null,
agentId: null,
fallbackToLan: relayRaw.fallbackToLan === true,
};
if (relayEnabled) {
if (relayUrlValue === null || relayUrlValue === '') throw new TypeError('lan-share: relay.url is required when the relay is enabled');
if (relayTokenValue === null || relayTokenValue === '') throw new TypeError('lan-share: relay.token is required when the relay is enabled');
if (typeof relayTokenValue !== 'string' || relayTokenValue.length > 512) throw new TypeError('lan-share: relay.token must be a string of at most 512 characters');
relay.url = normalizeRelayUrl(relayUrlValue);
relay.token = relayTokenValue;
relay.publicOrigin = relayPublicValue === null || relayPublicValue === '' ? null : normalizePublicOrigin(relayPublicValue, 'relay.publicOrigin');
if (relayAgentValue !== null && relayAgentValue !== '') {
if (typeof relayAgentValue !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(relayAgentValue)) {
throw new TypeError('lan-share: relay.agentId must match [A-Za-z0-9._-]{1,64}');
}
relay.agentId = relayAgentValue;
}
}
return {
...DEFAULTS,
enabled,
host,
publicHost,
port,
ticketTtlSeconds,
deviceTtlDays,
maxDevices,
stateFile,
tls,
relay,
ticketTtlMs: ticketTtlSeconds * 1000,
deviceTtlMs: deviceTtlDays * 24 * 60 * 60 * 1000,
};
}
/**
* Whether an IPv4 address is a private LAN address (RFC 1918). The UDP
* default-route probe can report a Tailscale/CGNAT address (100.64/10) or a
* VPN address that the local relay agent cannot dial back. Prefer a real LAN
* address so both the tablet and the local relay tunnel reach the listener.
* @param {string} address IPv4 text.
* @returns {boolean} true for 10/8, 172.16/12 or 192.168/16.
*/
export function isPrivateLanAddress(address) {
const parts = String(address).split('.').map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false;
if (parts[0] === 10) return true;
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
return parts[0] === 192 && parts[1] === 168;
}
/**
* Ask the routing table for the local address the network would use, then fall
* back to the first non-internal IPv4 interface (physical interfaces first).
* @returns {Promise<string | undefined>} a LAN address literal, if any.
*/
export async function detectLanAddress() {
for (const target of ['8.8.8.8', '1.1.1.1', '9.9.9.9']) {
const socket = createSocket('udp4');
try {
await new Promise((resolveConnect, rejectConnect) => {
socket.once('error', rejectConnect);
socket.connect(53, target, resolveConnect);
});
const address = socket.address().address;
/* A Tailscale/CGNAT or public default route is not necessarily reachable
* from the local relay tunnel or the LAN tablet; prefer RFC 1918 below. */
if (typeof address === 'string' && address !== '' && address !== '0.0.0.0' && isPrivateLanAddress(address)) {
return address;
}
} catch {
/* try the next probe */
} finally {
socket.close();
}
}
const interfaces = networkInterfaces();
const candidates = [];
for (const [name, entries] of Object.entries(interfaces)) {
for (const entry of entries ?? []) {
if (entry.internal) continue;
if (entry.family !== 'IPv4' && entry.family !== 4) continue;
candidates.push({ name, address: entry.address });
}
}
const rank = (name) => {
if (/^(en\d|eth\d|wlan\d|wl|Wi-?Fi)/i.test(name)) return 0;
if (/^(utun|tun|tap|bridge|vmnet|vboxnet|docker|vEthernet|awdl|llw)/i.test(name)) return 2;
return 1;
};
candidates.sort((left, right) => {
const leftPrivate = isPrivateLanAddress(left.address) ? 0 : 1;
const rightPrivate = isPrivateLanAddress(right.address) ? 0 : 1;
if (leftPrivate !== rightPrivate) return leftPrivate - rightPrivate;
return rank(left.name) - rank(right.name);
});
return candidates[0]?.address;
}
/**
* The host text a URL can carry: IPv6 literals are bracketed, IPv4 is as-is.
* @param {string} host address or hostname.
* @returns {string} URL host text.
*/
export function urlHost(host) {
if (host.startsWith('[') && host.endsWith(']')) return host;
return isIP(host) === 6 ? '[' + host + ']' : host;
}
/**
* Compose the public origin of the LAN listener.
* @param {{ protocol: string, host: string, port: number }} listener listening facts.
* @returns {string} origin with no trailing slash.
*/
export function originOf(listener) {
return listener.protocol + '//' + urlHost(listener.host) + ':' + String(listener.port);
}
/**
* The authority spelling used for Host headers and cookie audiences.
* @param {string} origin an http(s) origin.
* @returns {string} host[:port].
*/
export function authorityOf(origin) {
return new URL(origin).host;
}
/**
* Extract the bind host from an upstream origin, without brackets.
* @param {string} origin upstream origin.
* @returns {string} the hostname.
*/
export function upstreamHostOf(origin) {
const url = new URL(origin);
const host = url.hostname;
return host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
}
/**
* A short human label for a browser's User-Agent, for the device list.
* @param {string | undefined} userAgent request User-Agent.
* @returns {string} a label such as "iPad · Safari".
*/
export function describeUserAgent(userAgent) {
const ua = typeof userAgent === 'string' ? userAgent : '';
let device = 'Browser';
if (/iPad/.test(ua)) device = 'iPad';
else if (/iPhone/.test(ua)) device = 'iPhone';
else if (/Android/.test(ua)) device = /Mobile/.test(ua) ? 'Android phone' : 'Android tablet';
else if (/Macintosh|Mac OS X/.test(ua)) device = 'Mac';
else if (/Windows/.test(ua)) device = 'Windows';
else if (/Linux/.test(ua)) device = 'Linux';
else if (/CrOS/.test(ua)) device = 'Chromebook';
let browser = 'Browser';
if (/Edg\//.test(ua)) browser = 'Edge';
else if (/OPR\/|Opera/.test(ua)) browser = 'Opera';
else if (/Firefox\//.test(ua)) browser = 'Firefox';
else if (/Chrome\//.test(ua) && !/Chromium/.test(ua)) browser = 'Chrome';
else if (/Safari\//.test(ua)) browser = 'Safari';
return device + ' · ' + browser;
}
/**
* Normalize a socket peer address for display and storage.
* @param {string | undefined} address remote address.
* @returns {string} an address without an IPv4-mapped prefix.
*/
export function peerAddress(address) {
if (typeof address !== 'string' || address === '') return 'unknown';
return address.startsWith('::ffff:') ? address.slice(7) : address;
}