Files

1215 lines
43 KiB
JavaScript

/**
* The LAN listener: an authenticated reverse proxy in front of the Desktop
* Host's loopback Web server.
*
* The Host's own server is deliberately loopback-only and authenticates a
* browser with an authority-bound signed cookie obtained from a per-process
* launch token. This listener therefore never forwards that cookie to the
* tablet. It pairs a tablet with a one-time QR ticket, keeps its own revocable
* device cookie, and speaks to the upstream as a synthetic authenticated
* browser: it mints the upstream cookie through the Host's launch URL, keeps it
* warm, and replaces it when the upstream authority changes or answers 401.
*
* Everything that reaches the upstream is re-written exactly the way the
* Electron shell's own dsh-app://app forwarding does it: Host names the
* upstream authority, cookies are the minted set, and Origin is either removed
* (HTTP) or set to the upstream origin (WebSocket), so the Host's DNS-rebinding
* and cross-site fences keep their meaning.
*/
import { randomBytes } from 'node:crypto';
import { readFileSync } from 'node:fs';
import http from 'node:http';
import https from 'node:https';
import net from 'node:net';
import tls from 'node:tls';
import {
describeUserAgent,
isWildcardHost,
originOf,
peerAddress,
} from './config.js';
import { encodeQr } from './qr.js';
/** Cookie carrying the device secret to this listener. */
const DEVICE_COOKIE = 'dsh-lan-device';
/** How long a minted upstream cookie is trusted when it carries no expiry. */
const FALLBACK_COOKIE_TTL_MS = 6 * 60 * 60 * 1000;
/** Refresh the upstream cookie before it expires. */
const COOKIE_REFRESH_MARGIN_MS = 10 * 60 * 1000;
/** How long a scanned QR waits for the desktop owner's confirmation. */
const PENDING_TTL_MS = 120 * 1000;
/** Bound on pairing requests that can wait for confirmation at once. */
const MAX_PENDING = 8;
/** Headers that describe one hop and never cross a proxy. */
const HOP_BY_HOP = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'proxy-connection',
'te',
'trailer',
'transfer-encoding',
'upgrade',
]);
/** Request headers the proxy always replaces or removes. */
const REQUEST_REWRITE = new Set([
...HOP_BY_HOP,
'host',
'origin',
'cookie',
'sec-fetch-site',
'expect',
]);
/** Response headers the proxy always replaces or removes. */
const RESPONSE_DROP = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'proxy-connection',
'trailer',
'transfer-encoding',
]);
/**
* Escape text for HTML interpolation.
* @param {string} value raw text.
* @returns {string} escaped text.
*/
function escapeHtml(value) {
return String(value)
.replaceAll('&', '&')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
/**
* A self-contained status page for pairing failures and missing cookies.
* @param {{ title: string, message: string, detail?: string }} content page copy.
* @returns {string} complete HTML.
*/
function htmlPage(content) {
const detail = content.detail === undefined ? '' : '<p class="detail">' + escapeHtml(content.detail) + '</p>';
return '<!doctype html><html lang="ru"><head><meta charset="utf-8">'
+ '<meta name="viewport" content="width=device-width, initial-scale=1">'
+ '<title>' + escapeHtml(content.title) + '</title><style>'
+ ':root{color-scheme:light dark;--bg:#f6f6f7;--fg:#1b1c1e;--muted:#67696e;--line:#d9dadf;--card:#fff}'
+ '@media (prefers-color-scheme:dark){:root{--bg:#131416;--fg:#ececf1;--muted:#9a9ca3;--line:#303238;--card:#1b1c20}}'
+ '*{box-sizing:border-box}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;'
+ 'background:var(--bg);color:var(--fg);font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;padding:24px}'
+ 'main{width:min(460px,100%);background:var(--card);border:1px solid var(--line);border-radius:16px;padding:28px 24px}'
+ 'h1{font-size:20px;line-height:1.3;margin:0 0 10px}p{margin:0 0 10px;color:var(--muted)}p.detail{font-size:13px;'
+ 'word-break:break-word;color:var(--muted);margin-top:16px;padding-top:14px;border-top:1px solid var(--line)}'
+ '</style></head><body><main><h1>' + escapeHtml(content.title) + '</h1>'
+ '<p>' + content.message + '</p>' + detail + '</main></body></html>';
}
/**
* Send a complete response.
* @param {http.ServerResponse} res response.
* @param {number} status status code.
* @param {Record<string, string | string[]>} headers response headers.
* @param {string | Buffer} body response body.
*/
function send(res, status, headers, body) {
res.writeHead(status, { 'cache-control': 'no-store', ...headers });
res.end(body);
}
/**
* Send one JSON response.
* @param {http.ServerResponse} res response.
* @param {number} status status code.
* @param {unknown} body JSON value.
*/
function sendJson(res, status, body) {
send(res, status, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify(body));
}
/**
* Read a small JSON request body.
* @param {http.IncomingMessage} req request.
* @param {number} limit byte limit.
* @returns {Promise<unknown>} parsed JSON, or undefined.
*/
async function readJson(req, limit = 8192) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > limit) return undefined;
chunks.push(chunk);
}
if (chunks.length === 0) return undefined;
try {
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
} catch {
return undefined;
}
}
/**
* All values of one cookie name in a Cookie header.
* @param {string | undefined} header Cookie header.
* @param {string} name cookie name.
* @returns {string | undefined} the last value.
*/
function cookieValue(header, name) {
if (typeof header !== 'string') return undefined;
let value;
for (const segment of header.split(';')) {
const equals = segment.indexOf('=');
if (equals === -1) continue;
if (segment.slice(0, equals).trim() === name) value = segment.slice(equals + 1).trim();
}
return value;
}
/**
* Parse the lifetime a Set-Cookie header advertises.
* @param {string} header one Set-Cookie value.
* @returns {number | undefined} absolute expiry, when parseable.
*/
function cookieExpiry(header) {
const expires = /(?:^|;)\s*expires=([^;]+)/i.exec(header);
if (expires !== null) {
const time = Date.parse(expires[1]);
if (Number.isFinite(time)) return time;
}
const maxAge = /(?:^|;)\s*max-age=(-?\d+)/i.exec(header);
if (maxAge !== null) {
const seconds = Number(maxAge[1]);
if (Number.isFinite(seconds)) return Date.now() + seconds * 1000;
}
return undefined;
}
/**
* The LAN Share listener and proxy.
*/
export class LanShareServer {
/**
* @param {object} options composition.
* @param {ReturnType<typeof import('./config.js').normalizeConfig>} options.config normalized config.
* @param {import('./store.js').DeviceStore} options.devices device registry.
* @param {import('./store.js').TicketStore} options.tickets ticket registry.
* @param {{ origin: string, protocol: string, host: string, port: number }} options.upstream Desktop Host facts.
* @param {() => string} options.authenticatedUrl returns the Host's launch URL.
* @param {(level: string, ...args: unknown[]) => void} [options.logger] host logger.
*/
constructor(options) {
this.config = options.config;
this.devices = options.devices;
this.tickets = options.tickets;
this.upstream = {
...options.upstream,
authority: new URL(options.upstream.origin).host,
};
this.authenticatedUrl = options.authenticatedUrl;
this.log = options.logger ?? (() => {});
/** @type {http.Server | https.Server | tls.Server | null} */
this.server = null;
this.bindHost = null;
this.publicHost = null;
this.protocol = this.config.tls === null ? 'http:' : 'https:';
this.port = null;
this.fallbackPort = false;
this.lastError = null;
this.ready = false;
/** @type {{ header: string, expiresAt: number } | null} */
this.cookie = null;
/** @type {Promise<{ header: string, expiresAt: number }> | null} */
this.cookieMint = null;
this.lastMintError = null;
/** @type {Map<string, Set<net.Socket>>} */
this.sockets = new Map();
/** @type {Map<string, object>} pairing requests waiting for the owner. */
this.pending = new Map();
this.agent = new http.Agent({ keepAlive: true, maxSockets: 64, maxFreeSockets: 16 });
this.secureAgent = new https.Agent({ keepAlive: true, maxSockets: 32, maxFreeSockets: 8, rejectUnauthorized: false });
}
/** The public origin a QR URL uses. */
get publicOrigin() {
if (this.port === null || this.publicHost === null) return null;
return originOf({ protocol: this.protocol, host: this.publicHost, port: this.port });
}
/** Status and devices for the desktop UI. */
get state() {
return {
enabled: this.config.enabled,
running: this.ready,
origin: this.publicOrigin,
protocol: this.protocol,
bindHost: this.bindHost,
port: this.port,
fallbackPort: this.fallbackPort,
error: this.lastError,
mintError: this.lastMintError,
upstream: this.upstream.origin,
pending: this.listPending(),
devices: this.devices.list().map((device) => ({
...device,
online: device.online === true || this.sockets.has(device.id),
})),
};
}
/**
* Start listening. A bind failure is reported through state, never thrown
* into the Host's plugin load.
*/
async start() {
if (!this.config.enabled) {
this.lastError = 'disabled';
return;
}
let host = this.config.host;
if (host === null) host = await this.resolveAddress();
if (host === null || host === undefined) {
this.lastError = 'no-lan-address';
this.log('warn', 'lan-share: no LAN address was found; set config.host explicitly');
return;
}
this.bindHost = host;
this.publicHost = this.config.publicHost ?? (isWildcardHost(host) ? null : host);
if (this.publicHost === null) {
this.lastError = 'public-host-required';
return;
}
let server;
try {
if (this.config.tls !== null) {
server = tls.createServer({
cert: readFileSyncSafe(this.config.tls.certFile),
key: readFileSyncSafe(this.config.tls.keyFile),
}, (req, res) => this.handleRequest(req, res));
} else {
server = http.createServer((req, res) => this.handleRequest(req, res));
}
} catch (error) {
this.lastError = 'tls: ' + this.describeError(error);
this.log('warn', error);
return;
}
server.on('upgrade', (req, socket, head) => this.handleUpgrade(req, socket, head));
server.on('clientError', (error, socket) => {
if (socket.writable) socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
socket.destroy();
});
const firstPort = this.config.port;
try {
await this.listen(server, firstPort, host);
} catch (error) {
if (error?.code === 'EADDRINUSE' && firstPort !== 0) {
try {
await this.listen(server, 0, host);
this.fallbackPort = true;
} catch (fallbackError) {
this.lastError = 'bind: ' + this.describeError(fallbackError);
this.log('warn', fallbackError);
return;
}
} else {
this.lastError = 'bind: ' + this.describeError(error);
this.log('warn', error);
return;
}
}
this.server = server;
const address = server.address();
this.port = typeof address === 'object' && address !== null ? address.port : this.config.port;
this.ready = true;
this.lastError = null;
this.log('info', 'lan-share: listening on ' + String(this.publicOrigin));
}
/**
* Resolve the address to bind without importing the Host's services.
* @returns {Promise<string | null>} an address, or null.
*/
async resolveAddress() {
const { detectLanAddress } = await import('./config.js');
return (await detectLanAddress()) ?? null;
}
/**
* Bind one server and wait for the listener.
* @param {http.Server} server server to bind.
* @param {number} port port.
* @param {string} host address.
* @returns {Promise<void>} completion.
*/
listen(server, port, host) {
return new Promise((resolveListen, rejectListen) => {
const onError = (error) => {
server.off('listening', onListening);
rejectListen(error);
};
const onListening = () => {
server.off('error', onError);
resolveListen();
};
server.once('error', onError);
server.once('listening', onListening);
server.listen(port, host);
});
}
/** Stop the listener and every upgraded socket. */
async stop() {
this.ready = false;
this.cancelAllPending();
for (const set of this.sockets.values()) for (const socket of set) socket.destroy();
this.sockets.clear();
const server = this.server;
this.server = null;
if (server !== null) {
await new Promise((resolveClose) => {
server.close(() => resolveClose());
server.closeAllConnections?.();
const timer = setTimeout(resolveClose, 2000);
if (typeof timer.unref === 'function') timer.unref();
});
}
this.agent.destroy();
this.secureAgent.destroy();
}
/** Public pending pairing requests for the desktop confirmation card. */
listPending() {
const now = Date.now();
return [...this.pending.values()]
.filter((entry) => entry.done !== true && entry.expiresAt > now)
.map(({ id, label, ip, userAgent, createdAt, expiresAt }) => ({
id,
label,
ip,
userAgent: typeof userAgent === 'string' ? userAgent : '',
createdAt,
expiresAt,
}));
}
/**
* Register one scanned ticket and hold it until the owner decides.
* @param {{ label: string, ip: string, userAgent?: string, sessionId: string | null }} facts device facts.
* @returns {{ id: string, promise: Promise<{ outcome: string, pairing: object | null }> } | undefined} pending request.
*/
beginPending({ label, ip, userAgent, sessionId }) {
const now = Date.now();
for (const [id, entry] of this.pending) {
if (entry.done !== true && entry.expiresAt <= now) this.finishPending(id, 'expired');
}
if (this.pending.size >= MAX_PENDING) return undefined;
const id = randomBytes(12).toString('base64url');
let resolve;
const promise = new Promise((done) => { resolve = done; });
const entry = {
id,
label,
ip,
userAgent: typeof userAgent === 'string' ? userAgent : '',
sessionId: sessionId ?? null,
createdAt: now,
expiresAt: now + PENDING_TTL_MS,
done: false,
pairing: null,
resolve,
timer: null,
};
entry.timer = setTimeout(() => this.finishPending(id, 'expired'), PENDING_TTL_MS);
if (typeof entry.timer.unref === 'function') entry.timer.unref();
this.pending.set(id, entry);
this.log('info', 'lan-share: pairing request from ' + label + ' at ' + ip);
return { id, promise };
}
/**
* Settle one pending request exactly once.
* @param {string} id pending id.
* @param {'approved' | 'denied' | 'expired' | 'canceled'} outcome decision.
* @returns {object | undefined} the settled entry.
*/
finishPending(id, outcome) {
const entry = this.pending.get(id);
if (entry === undefined || entry.done === true) return undefined;
entry.done = true;
if (entry.timer !== null) clearTimeout(entry.timer);
this.pending.delete(id);
entry.resolve({ outcome, pairing: entry.pairing });
return entry;
}
/**
* Owner approved a request: register the device, then release the waiting
* browser. The device is created only at this point.
* @param {string} id pending id.
* @returns {Promise<{ ok: boolean, code?: string }>} decision result.
*/
approvePending(id) {
const entry = this.pending.get(id);
if (entry === undefined || entry.done === true) {
return Promise.resolve({ ok: false, code: 'unknown-pending' });
}
return this.devices.add({
label: entry.label,
ip: entry.ip,
sessionId: entry.sessionId,
}).then((pairing) => {
entry.pairing = pairing;
this.finishPending(id, 'approved');
this.log('info', 'lan-share: approved ' + entry.label + ' from ' + entry.ip);
return { ok: true };
}, (error) => {
if (error?.code === 'DEVICE_LIMIT') return { ok: false, code: 'DEVICE_LIMIT' };
throw error;
});
}
/**
* Owner rejected a request; the scanning browser gets a denial page.
* @param {string} id pending id.
* @returns {boolean} whether a live request was denied.
*/
denyPending(id) {
const entry = this.pending.get(id);
if (entry === undefined || entry.done === true) return false;
this.finishPending(id, 'denied');
this.log('info', 'lan-share: denied a pairing request');
return true;
}
/**
* The scanning browser went away before a decision.
* @param {string} id pending id.
*/
cancelPending(id) {
const entry = this.pending.get(id);
if (entry === undefined || entry.done === true) return;
this.finishPending(id, 'canceled');
}
/** Resolve every held pairing request when the listener stops. */
cancelAllPending() {
for (const entry of [...this.pending.values()]) {
if (entry.done === true) continue;
if (entry.timer !== null) clearTimeout(entry.timer);
entry.done = true;
entry.resolve({ outcome: 'canceled', pairing: null });
}
this.pending.clear();
}
/**
* Pair one tablet and return everything a QR dialog renders.
* @param {string | null} sessionId Session the device should open.
* @returns {{ ticketId: string, url: string, expiresAt: number, qr: { size: number, rows: string[] } }} ticket facts.
*/
createTicket(sessionId, origin = undefined) {
const base = origin ?? this.publicOrigin;
if (!this.ready || base === null) {
const error = new Error('lan-share: listener is not running');
error.code = 'NOT_RUNNING';
throw error;
}
const ticket = this.tickets.mint(sessionId ?? null);
const url = base + '/s/' + ticket.token;
return {
ticketId: ticket.ticketId,
token: ticket.token,
url,
expiresAt: ticket.expiresAt,
qr: encodeQr(url),
};
}
/**
* Revoke devices by id or all at once, closing their WebSockets.
* @param {{ deviceId?: string, all?: boolean }} request what to revoke.
* @returns {Promise<number>} number of revoked devices.
*/
async revoke(request) {
if (request.all === true) {
const count = await this.devices.revokeAll();
for (const set of this.sockets.values()) for (const socket of set) socket.destroy();
this.sockets.clear();
this.log('info', 'lan-share: all devices revoked (' + String(count) + ')');
return count;
}
const id = typeof request.deviceId === 'string' ? request.deviceId : '';
if (id === '') return 0;
const sockets = this.sockets.get(id);
if (sockets !== undefined) {
for (const socket of sockets) socket.destroy();
this.sockets.delete(id);
}
const removed = await this.devices.revoke(id);
if (removed) this.log('info', 'lan-share: device revoked');
return removed ? 1 : 0;
}
/**
* Dispatch one HTTP request.
* @param {http.IncomingMessage} req request.
* @param {http.ServerResponse} res response.
*/
async handleRequest(req, res) {
try {
const pathname = this.pathnameOf(req.url);
if (pathname === undefined) return send(res, 400, { 'content-type': 'text/plain; charset=utf-8' }, 'bad request');
if (pathname.startsWith('/s/')) return await this.handlePair(req, res, pathname);
if (pathname === '/api/lan-share/bootstrap') return this.handleBootstrap(req, res);
if (pathname === '/api/lan-share/session') return await this.handleSession(req, res);
if (pathname === '/api/lan-share/forget-self') return await this.handleForgetSelf(req, res);
if (pathname.startsWith('/api/lan-share/')) return sendJson(res, 403, { ok: false, code: 'host-only' });
const device = this.deviceOf(req);
if (device === undefined) return this.rejectUnauthenticated(req, res);
await this.forwardHttp(req, res);
} catch (error) {
this.log('warn', error);
if (!res.headersSent) {
send(res, 502, { 'content-type': 'text/plain; charset=utf-8' }, 'lan-share: upstream request failed\n');
} else {
res.destroy();
}
}
}
/**
* Parse a request target's pathname.
* @param {string | undefined} url request target.
* @returns {string | undefined} pathname.
*/
pathnameOf(url) {
if (typeof url !== 'string') return undefined;
try {
return new URL(url, 'http://lan-share.invalid').pathname;
} catch {
return undefined;
}
}
/**
* Resolve the caller's device from its cookie.
* @param {http.IncomingMessage} req request.
* @returns {import('./store.js').DeviceRecord | undefined} live device.
*/
deviceOf(req) {
return this.devices.verify(cookieValue(req.headers.cookie, DEVICE_COOKIE));
}
/**
* Answer a request without a valid device cookie.
* @param {http.IncomingMessage} req request.
* @param {http.ServerResponse} res response.
*/
rejectUnauthenticated(req, res) {
const accept = typeof req.headers.accept === 'string' ? req.headers.accept : '';
const navigate = req.headers['sec-fetch-mode'] === 'navigate';
const acceptsHtml = accept.includes('text/html') || accept.includes('*/*') || accept === '';
if ((acceptsHtml || navigate) && (req.method === 'GET' || req.method === 'HEAD')) {
const page = htmlPage({
title: 'Нужен QR-код / Pairing required',
message: 'Это устройство не подключено. На компьютере откройте DSH → «Поделиться» и отсканируйте новый QR-код.',
detail: 'This tablet is not paired. On the host computer, open DSH → Share and scan a new QR code.',
});
return send(res, 401, { 'content-type': 'text/html; charset=utf-8' }, page);
}
send(res, 401, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({ ok: false, code: 'unauthorized' }));
}
/**
* Consume one ticket and pair the scanning browser.
* @param {http.IncomingMessage} req request.
* @param {http.ServerResponse} res response.
* @param {string} pathname request path, beginning with /s/.
*/
async handlePair(req, res, pathname) {
if (req.method !== 'GET') return send(res, 405, { allow: 'GET' }, '');
const token = pathname.slice(3);
if (token === '' || token.includes('/')) return send(res, 404, { 'content-type': 'text/plain; charset=utf-8' }, 'not found');
const grant = this.tickets.consume(token);
if (grant === undefined) {
const page = htmlPage({
title: 'Код недействителен / Code expired',
message: 'QR-код уже использован или истёк. Запросите новый код на компьютере.',
detail: 'This one-time code was already used or has expired. Request a new QR code on the host computer.',
});
return send(res, 410, { 'content-type': 'text/html; charset=utf-8' }, page);
}
try {
await this.ensureUpstreamCookie();
} catch (error) {
this.log('warn', error);
const page = htmlPage({
title: 'Не удалось авторизоваться / Host authentication failed',
message: 'Компьютер не подтвердил сеанс. Проверьте, что DSH запущен, и запросите новый код.',
detail: 'The Desktop Host did not confirm the browser session. Request a new QR code.',
});
return send(res, 502, { 'content-type': 'text/html; charset=utf-8' }, page);
}
const pending = this.beginPending({
label: this.describeRequest(req),
ip: this.peerOf(req),
userAgent: req.headers['user-agent'],
sessionId: grant.sessionId,
});
if (pending === undefined) {
const page = htmlPage({
title: 'Слишком много запросов / Too many requests',
message: 'Подождите, пока владелец компьютера подтвердит одно из подключений.',
detail: 'Wait until the host owner confirms or rejects one of the pending connections.',
});
return send(res, 429, { 'content-type': 'text/html; charset=utf-8' }, page);
}
let settled = false;
const onClose = () => {
if (settled === true) return;
settled = true;
this.cancelPending(pending.id);
};
res.on('close', onClose);
const outcome = await pending.promise;
settled = true;
res.off('close', onClose);
if (outcome.outcome === 'canceled') return;
if (outcome.outcome === 'approved' && outcome.pairing !== null) {
if (res.destroyed || res.writableEnded) {
await this.devices.revoke(outcome.pairing.record.id).catch(() => {});
return;
}
const pairing = outcome.pairing;
const maxAge = Math.max(1, Math.floor((pairing.record.expiresAt - Date.now()) / 1000));
const secure = this.protocol === 'https:' ? '; Secure' : '';
const cookie = DEVICE_COOKIE + '=' + pairing.cookie + '; Max-Age=' + String(maxAge)
+ '; Path=/; HttpOnly; SameSite=Lax' + secure;
send(res, 303, {
location: '/',
'set-cookie': cookie,
'referrer-policy': 'no-referrer',
'content-type': 'text/plain; charset=utf-8',
}, '');
return;
}
if (outcome.outcome === 'denied') {
const page = htmlPage({
title: 'Подключение отклонено / Connection declined',
message: 'Владелец компьютера отклонил подключение этого устройства.',
detail: 'The host owner declined this device. Request a new QR code to try again.',
});
return send(res, 403, { 'content-type': 'text/html; charset=utf-8' }, page);
}
const page = htmlPage({
title: 'Подтверждение не получено / Confirmation timed out',
message: 'Владелец компьютера не подтвердил подключение. Запросите новый QR-код.',
detail: 'The host did not confirm the connection in time. Request a new QR code.',
});
return send(res, 408, { 'content-type': 'text/html; charset=utf-8' }, page);
}
/**
* Tell a remote client which Session it is bound to.
* @param {http.IncomingMessage} req request.
* @param {http.ServerResponse} res response.
*/
handleBootstrap(req, res) {
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'method' });
const device = this.deviceOf(req);
if (device === undefined) return this.rejectUnauthenticated(req, res);
const advertised = req.headers['x-dsh-public-origin'];
sendJson(res, 200, {
remote: true,
version: 1,
deviceId: device.id,
label: device.label,
sessionId: device.sessionId,
origin: typeof advertised === 'string' && advertised !== '' ? advertised : this.publicOrigin,
});
}
/**
* Remember the Session a paired browser is looking at.
* @param {http.IncomingMessage} req request.
* @param {http.ServerResponse} res response.
*/
async handleSession(req, res) {
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, code: 'method' });
const device = this.deviceOf(req);
if (device === undefined) return this.rejectUnauthenticated(req, res);
const body = await readJson(req);
if (body === null || typeof body !== 'object') return sendJson(res, 400, { ok: false, code: 'bad-request' });
const sessionId = body.sessionId;
if (sessionId !== null && (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 200)) {
return sendJson(res, 400, { ok: false, code: 'bad-session' });
}
this.devices.setSession(device.id, sessionId);
sendJson(res, 200, { ok: true });
}
/**
* Remove this browser's own pairing.
* @param {http.IncomingMessage} req request.
* @param {http.ServerResponse} res response.
*/
async handleForgetSelf(req, res) {
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, code: 'method' });
const device = this.deviceOf(req);
if (device === undefined) return this.rejectUnauthenticated(req, res);
const sockets = this.sockets.get(device.id);
if (sockets !== undefined) for (const socket of sockets) socket.destroy();
this.sockets.delete(device.id);
await this.devices.revoke(device.id);
const secure = this.protocol === 'https:' ? '; Secure' : '';
send(res, 200, {
'content-type': 'application/json; charset=utf-8',
'set-cookie': DEVICE_COOKIE + '=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax' + secure,
}, JSON.stringify({ ok: true }));
}
/**
* Proxy one authenticated HTTP request to the Desktop Host.
* @param {http.IncomingMessage} req request.
* @param {http.ServerResponse} res response.
*/
async forwardHttp(req, res) {
let cookie = await this.ensureUpstreamCookie();
const run = (header) => new Promise((resolveRun, rejectRun) => {
const transport = this.upstream.protocol === 'https:' ? https : http;
const request = transport.request({
protocol: this.upstream.protocol,
hostname: this.upstream.host,
port: this.upstream.port,
method: req.method,
path: req.url,
headers: this.forwardHeaders(req.headers, header),
agent: this.upstream.protocol === 'https:' ? this.secureAgent : this.agent,
...(this.upstream.protocol === 'https:' ? { rejectUnauthorized: false } : {}),
}, (response) => {
const status = response.statusCode ?? 502;
if (status === 401) {
/* The Host rejected our synthetic cookie: replace it for the next call. */
this.ensureUpstreamCookie(true).catch(() => {});
if (req.method === 'GET' || req.method === 'HEAD') {
response.resume();
resolveRun({ retry: true });
return;
}
}
res.writeHead(status, this.responseHeaders(response.headers));
response.pipe(res);
response.on('error', () => res.destroy());
resolveRun({ retry: false });
});
request.on('error', rejectRun);
res.on('close', () => {
if (!res.writableEnded) request.destroy();
});
req.pipe(request);
});
try {
const first = await run(cookie);
if (!first.retry) return;
cookie = await this.ensureUpstreamCookie(true);
await new Promise((resolveRun, rejectRun) => {
const transport = this.upstream.protocol === 'https:' ? https : http;
const request = transport.request({
protocol: this.upstream.protocol,
hostname: this.upstream.host,
port: this.upstream.port,
method: req.method,
path: req.url,
headers: this.forwardHeaders(req.headers, cookie),
agent: this.upstream.protocol === 'https:' ? this.secureAgent : this.agent,
...(this.upstream.protocol === 'https:' ? { rejectUnauthorized: false } : {}),
}, (response) => {
res.writeHead(response.statusCode ?? 502, this.responseHeaders(response.headers));
response.pipe(res);
response.on('error', () => res.destroy());
resolveRun();
});
request.on('error', rejectRun);
res.on('close', () => {
if (!res.writableEnded) request.destroy();
});
req.pipe(request);
});
} catch (error) {
this.log('warn', error);
if (!res.headersSent) send(res, 502, { 'content-type': 'text/plain; charset=utf-8' }, 'lan-share: upstream request failed\n');
else res.destroy();
}
}
/**
* Build the headers sent upstream: the same rewriting the Electron shell
* applies to its dsh-app://app requests.
* @param {http.IncomingHttpHeaders} incoming client headers.
* @param {string} cookie minted upstream cookie.
* @returns {http.OutgoingHttpHeaders} upstream headers.
*/
forwardHeaders(incoming, cookie) {
/** @type {http.OutgoingHttpHeaders} */
const out = {};
for (const [name, value] of Object.entries(incoming)) {
const lower = name.toLowerCase();
if (REQUEST_REWRITE.has(lower) || lower.startsWith('x-forwarded-') || lower === 'forwarded') continue;
if (value !== undefined) out[lower] = value;
}
out.host = this.upstream.authority;
out.cookie = cookie;
return out;
}
/**
* Filter and rewrite upstream response headers.
* @param {http.IncomingHttpHeaders} incoming upstream headers.
* @returns {http.OutgoingHttpHeaders} response headers.
*/
responseHeaders(incoming) {
/** @type {http.OutgoingHttpHeaders} */
const out = {};
for (const [name, value] of Object.entries(incoming)) {
const lower = name.toLowerCase();
if (RESPONSE_DROP.has(lower) || value === undefined) continue;
if (lower === 'set-cookie') {
const cookies = Array.isArray(value) ? value : [value];
const kept = cookies.filter((cookie) => !String(cookie).startsWith('dsh-auth-'));
if (kept.length > 0) out['set-cookie'] = kept;
continue;
}
if (lower === 'location') {
out.location = this.rewriteLocation(String(value));
continue;
}
out[lower] = value;
}
return out;
}
/**
* Point an absolute upstream redirect at the public origin.
* @param {string} location Location header.
* @returns {string} rewritten Location.
*/
rewriteLocation(location) {
const upstream = this.upstream.origin;
if (location.startsWith(upstream)) {
const suffix = location.slice(upstream.length);
return (this.publicOrigin ?? '') + (suffix.startsWith('/') ? suffix : '/' + suffix);
}
return location;
}
/**
* Ensure the Host's browser cookie is cached and fresh.
* @param {boolean} [force] mint even when the cached cookie looks valid.
* @returns {Promise<string>} Cookie header value.
*/
async ensureUpstreamCookie(force = false) {
const now = Date.now();
if (!force && this.cookie !== null && this.cookie.expiresAt - COOKIE_REFRESH_MARGIN_MS > now) return this.cookie.header;
if (this.cookieMint === null) {
this.cookieMint = this.mintUpstreamCookie()
.then((minted) => {
this.cookie = minted;
this.lastMintError = null;
return minted;
})
.catch((error) => {
this.lastMintError = this.describeError(error);
throw error;
})
.finally(() => {
this.cookieMint = null;
});
}
const minted = await this.cookieMint;
return minted.header;
}
/**
* Exchange the Host's launch URL for its authority-bound browser cookie.
* @returns {Promise<{ header: string, expiresAt: number }>} cookie and expiry.
*/
async mintUpstreamCookie() {
const launch = new URL(this.authenticatedUrl());
const transport = launch.protocol === 'https:' ? https : http;
return await new Promise((resolveMint, rejectMint) => {
const request = transport.request({
protocol: launch.protocol,
hostname: this.upstream.host,
port: this.upstream.port,
method: 'GET',
path: launch.pathname + launch.search,
headers: { host: this.upstream.authority, accept: 'text/html', 'cache-control': 'no-store' },
...(launch.protocol === 'https:' ? { rejectUnauthorized: false } : {}),
}, (response) => {
response.resume();
if (response.statusCode !== 303) {
rejectMint(new Error('lan-share: host authentication answered ' + String(response.statusCode)));
return;
}
const raw = response.headers['set-cookie'];
const cookie = Array.isArray(raw) ? raw[0] : raw;
if (typeof cookie !== 'string' || cookie === '') {
rejectMint(new Error('lan-share: host authentication returned no cookie'));
return;
}
const semicolon = cookie.indexOf(';');
const header = semicolon === -1 ? cookie : cookie.slice(0, semicolon);
resolveMint({ header, expiresAt: cookieExpiry(cookie) ?? Date.now() + FALLBACK_COOKIE_TTL_MS });
});
request.on('error', rejectMint);
request.setTimeout(10_000, () => request.destroy(new Error('lan-share: host authentication timed out')));
request.end();
});
}
/**
* Proxy one WebSocket upgrade, with one re-mint retry on a 401 response.
* @param {http.IncomingMessage} req upgrade request.
* @param {net.Socket} socket client socket.
* @param {Buffer} head bytes already read by the HTTP parser.
*/
async handleUpgrade(req, socket, head) {
const pathname = this.pathnameOf(req.url);
if (pathname === undefined || pathname.startsWith('/api/lan-share/')) {
socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');
return;
}
const device = this.deviceOf(req);
if (device === undefined) {
socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
return;
}
try {
let cookie = await this.ensureUpstreamCookie();
let first = await this.openUpgrade(req, head, cookie);
if (first.status === 401) {
first.socket.destroy();
cookie = await this.ensureUpstreamCookie(true);
first = await this.openUpgrade(req, head, cookie);
}
const upstream = first.socket;
if (first.status !== 101) {
socket.write(first.head);
upstream.pipe(socket);
socket.pipe(upstream);
const finish = () => {
socket.destroy();
upstream.destroy();
};
upstream.on('error', finish);
socket.on('error', finish);
upstream.on('close', finish);
socket.on('close', finish);
return;
}
/* Track the socket so revoking this device tears the live stream down. */
let set = this.sockets.get(device.id);
if (set === undefined) {
set = new Set();
this.sockets.set(device.id, set);
}
set.add(socket);
socket.setNoDelay(true);
upstream.setNoDelay(true);
socket.write(first.head);
upstream.pipe(socket);
socket.pipe(upstream);
const cleanup = () => {
socket.destroy();
upstream.destroy();
const current = this.sockets.get(device.id);
if (current !== undefined) {
current.delete(socket);
if (current.size === 0) this.sockets.delete(device.id);
}
};
upstream.on('error', cleanup);
socket.on('error', cleanup);
upstream.on('close', cleanup);
socket.on('close', cleanup);
} catch (error) {
this.log('warn', error);
socket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n');
}
}
/**
* Open the upstream side of one upgrade and read its response headers.
* @param {http.IncomingMessage} req upgrade request.
* @param {Buffer} head client bytes already read.
* @param {string} cookie upstream cookie.
* @returns {Promise<{ socket: net.Socket, status: number | null, head: Buffer }>} connected socket and response.
*/
async openUpgrade(req, head, cookie) {
const headers = this.forwardHeaders(req.headers, cookie);
headers.connection = 'Upgrade';
headers.upgrade = typeof req.headers.upgrade === 'string' ? req.headers.upgrade : 'websocket';
headers.origin = this.upstream.origin;
headers['sec-fetch-site'] = 'same-origin';
let requestText = req.method + ' ' + req.url + ' HTTP/1.1\r\n';
for (const [name, value] of Object.entries(headers)) {
if (value === undefined) continue;
if (Array.isArray(value)) for (const item of value) requestText += name + ': ' + item + '\r\n';
else requestText += name + ': ' + String(value) + '\r\n';
}
requestText += '\r\n';
const socket = await this.connectUpstream();
socket.write(requestText);
if (head.length > 0) socket.write(head);
const response = await this.readUpgradeResponse(socket);
return { socket, status: response.status, head: response.head };
}
/**
* Connect to the upstream WebSocket port.
* @returns {Promise<net.Socket>} connected socket.
*/
connectUpstream() {
return new Promise((resolveConnect, rejectConnect) => {
const socket = this.upstream.protocol === 'https:'
? tls.connect({ host: this.upstream.host, port: this.upstream.port, rejectUnauthorized: false })
: net.connect({ host: this.upstream.host, port: this.upstream.port });
const event = this.upstream.protocol === 'https:' ? 'secureConnect' : 'connect';
const onError = (error) => {
socket.off(event, onConnect);
rejectConnect(error);
};
const onConnect = () => {
socket.off('error', onError);
resolveConnect(socket);
};
socket.once('error', onError);
socket.once(event, onConnect);
socket.setNoDelay(true);
});
}
/**
* Buffer the upstream handshake response and split it from any following bytes.
* @param {net.Socket} socket upstream socket.
* @returns {Promise<{ status: number | null, head: Buffer }>} status and the response bytes.
*/
readUpgradeResponse(socket) {
return new Promise((resolveRead, rejectRead) => {
const chunks = [];
let size = 0;
const onData = (chunk) => {
chunks.push(chunk);
size += chunk.length;
const buffer = Buffer.concat(chunks, size);
const end = buffer.indexOf('\r\n\r\n');
if (end === -1) {
if (size > 64 * 1024) {
cleanup();
rejectRead(new Error('lan-share: oversized upstream handshake'));
}
return;
}
cleanup();
const match = /^HTTP\/1\.[01] (\d{3})/.exec(buffer.subarray(0, end).toString('latin1'));
resolveRead({ status: match === null ? null : Number(match[1]), head: buffer });
};
const onError = (error) => {
cleanup();
rejectRead(error);
};
const onClose = () => {
cleanup();
rejectRead(new Error('lan-share: upstream closed during handshake'));
};
const cleanup = () => {
socket.off('data', onData);
socket.off('error', onError);
socket.off('close', onClose);
};
socket.on('data', onData);
socket.once('error', onError);
socket.once('close', onClose);
});
}
/**
* Build a human device label from the request.
* @param {http.IncomingMessage} req request.
* @returns {string} label.
*/
describeRequest(req) {
return describeUserAgent(req.headers['user-agent']);
}
/**
* The client's address for display.
* @param {http.IncomingMessage} req request.
* @returns {string} address.
*/
peerOf(req) {
return peerAddress(req.socket.remoteAddress);
}
/**
* Turn an error into a short diagnostic without leaking contents.
* @param {unknown} error thrown value.
* @returns {string} message.
*/
describeError(error) {
return error instanceof Error ? error.message : String(error);
}
}
/**
* Read a TLS file, reporting its path rather than its contents on failure.
* @param {string} file path.
* @returns {Buffer} file bytes.
*/
function readFileSyncSafe(file) {
try {
return readFileSync(file);
} catch (error) {
throw new Error('cannot read ' + file + ': ' + (error instanceof Error ? error.message : String(error)));
}
}