Files
dsh-lan-share/relay.js
T

730 lines
22 KiB
JavaScript

/**
* Outbound relay tunnel for the LAN Share host.
*
* The Desktop Host cannot accept inbound connections behind NAT, so it dials
* the relay and keeps one WebSocket open. The relay turns browser requests
* into stream frames; this client replays them against the local LAN listener,
* which keeps owning pairing, device cookies, and the Host proxy. No DSH
* credential leaves this process: the relay sees only the same browser headers
* the tablet would have sent to the LAN listener.
*
* Frames are JSON text with base64 bodies. A per-stream ack window keeps both
* sides bounded; the relay never buffers a whole upload or download.
*/
import http from 'node:http';
import https from 'node:https';
import net from 'node:net';
import tls from 'node:tls';
import { hostname } from 'node:os';
/** Subprotocol selected by the relay. */
const TUNNEL_PROTOCOL = 'dsh-relay.v1';
/** Subprotocol prefix carrying the agent token out of URLs and access logs. */
const TOKEN_PROTOCOL_PREFIX = 'dsh-token.';
/** Headers never replayed to the local listener. */
const HOP_BY_HOP = new Set([
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'proxy-connection',
'te',
'trailer',
'transfer-encoding',
'upgrade',
'expect',
]);
/**
* Add Secure to a Set-Cookie value when the public page is HTTPS.
* @param {string | string[]} value cookie values.
* @param {boolean} secure whether the public origin is HTTPS.
* @returns {string | string[]} values with Secure where missing.
*/
function secureCookies(value, secure) {
if (!secure) return value;
const one = (cookie) => (/;\s*secure\s*(?:;|$)/i.test(cookie) ? cookie : cookie + '; Secure');
return Array.isArray(value) ? value.map(one) : one(value);
}
/**
* Rewrite a private absolute redirect to the public origin.
* @param {string} value Location header.
* @param {string[]} privateOrigins origins the listener may emit.
* @param {string | null} publicOrigin public origin.
* @returns {string} rewritten value.
*/
function rewriteOrigin(value, privateOrigins, publicOrigin) {
if (typeof value !== 'string' || publicOrigin === null) return value;
for (const origin of privateOrigins) {
if (origin === '') continue;
if (value === origin) return publicOrigin + '/';
if (value.startsWith(origin + '/')) return publicOrigin + value.slice(origin.length);
}
return value;
}
/**
* Response headers the relay will forward.
* @param {http.IncomingHttpHeaders} headers upstream headers.
* @param {string[]} privateOrigins local listener spellings.
* @param {string | null} publicOrigin public origin.
* @param {boolean} secure whether the public origin is HTTPS.
* @returns {Record<string, string | string[]>} headers.
*/
function responseHeaders(headers, privateOrigins, publicOrigin, secure) {
const out = {};
for (const [name, value] of Object.entries(headers)) {
if (value === undefined) continue;
const lower = name.toLowerCase();
if (lower === 'location') {
out[name] = rewriteOrigin(String(value), privateOrigins, publicOrigin);
} else if (lower === 'set-cookie') {
out[name] = secureCookies(value, secure);
} else {
out[name] = value;
}
}
return out;
}
/**
* A tunnel to one relay.
*/
export class RelayTunnel {
/**
* @param {object} options composition.
* @param {string} options.url relay WebSocket URL.
* @param {string} options.token agent token.
* @param {string | null} options.agentId advertised identity.
* @param {string | null} options.publicOrigin configured public origin.
* @param {string} options.localOrigin LAN listener's advertised origin.
* @param {string} options.localBindOrigin LAN listener's bind origin.
* @param {string} options.localHost address the LAN listener is reachable at.
* @param {number} options.localPort LAN listener port.
* @param {string} options.localProtocol http: or https:.
* @param {() => Array<{ token: string, sessionId: string | null, expiresAt: number }>} options.activeTickets active ticket source.
* @param {number} [options.windowBytes] ack window.
* @param {number} [options.lowWaterBytes] resume threshold.
* @param {number} [options.reconnectMinMs] first reconnect delay.
* @param {number} [options.reconnectMaxMs] maximum reconnect delay.
* @param {(level: string, ...args: unknown[]) => void} [options.logger] host logger.
*/
constructor(options) {
this.url = options.url;
this.token = options.token;
this.agentId = options.agentId ?? undefined;
this.configuredOrigin = options.publicOrigin ?? null;
this.publicOrigin = this.configuredOrigin;
this.localOrigin = options.localOrigin;
this.localBindOrigin = options.localBindOrigin;
this.localHost = options.localHost;
this.localPort = options.localPort;
this.localProtocol = options.localProtocol;
this.localAuthority = new URL(options.localOrigin).host;
this.activeTickets = options.activeTickets ?? (() => []);
this.windowBytes = options.windowBytes ?? 2 * 1024 * 1024;
this.lowWaterBytes = options.lowWaterBytes ?? 512 * 1024;
this.reconnectMinMs = options.reconnectMinMs ?? 1000;
this.reconnectMaxMs = options.reconnectMaxMs ?? 30000;
this.log = options.logger ?? (() => {});
this.ws = null;
this.stopped = false;
this.connected = false;
this.connectedAt = null;
this.attempts = 0;
this.lastError = null;
this.reconnectTimer = null;
/** @type {Map<number, any>} */
this.streams = new Map();
this.secure = false;
this.httpAgent = new http.Agent({ keepAlive: true, maxSockets: 64, maxFreeSockets: 16 });
this.httpsAgent = new https.Agent({ keepAlive: true, maxSockets: 16, maxFreeSockets: 4, rejectUnauthorized: false });
}
/** Status for the desktop UI. Never exposes the token. */
get state() {
return {
enabled: true,
connected: this.connected,
url: this.url,
publicOrigin: this.publicOrigin,
agentId: this.agentId ?? null,
since: this.connectedAt,
attempts: this.attempts,
error: this.lastError,
};
}
/** Begin dialing and reconnecting. */
start() {
if (typeof globalThis.WebSocket !== 'function') {
this.lastError = 'websocket-unavailable';
this.log('warn', 'lan-share: this Node runtime has no global WebSocket; relay is unavailable');
return;
}
this.stopped = false;
this.connect();
}
/** Stop dialing and tear down the tunnel and its streams. */
async stop() {
this.stopped = true;
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
const ws = this.ws;
this.ws = null;
this.connected = false;
this.failAll('relay-stopped');
if (ws !== null) {
try {
ws.close(1000, 'agent stopping');
} catch {
/* already closing */
}
}
this.httpAgent.destroy();
this.httpsAgent.destroy();
}
/** One dial attempt. */
connect() {
if (this.stopped) return;
let url;
try {
url = new URL(this.url);
} catch (error) {
this.lastError = 'bad-relay-url';
this.log('warn', error);
return;
}
if (this.agentId !== undefined) url.searchParams.set('agent', this.agentId);
const tokenSafe = /^[A-Za-z0-9._~-]+$/.test(this.token);
if (!tokenSafe) url.searchParams.set('token', this.token);
const protocols = tokenSafe ? [TUNNEL_PROTOCOL, TOKEN_PROTOCOL_PREFIX + this.token] : [TUNNEL_PROTOCOL];
let ws;
try {
ws = new WebSocket(url.href, protocols);
} catch (error) {
this.lastError = 'connect-failed';
this.log('warn', error);
this.scheduleReconnect();
return;
}
this.ws = ws;
this.lastError = null;
ws.onopen = () => {
if (this.ws !== ws) return;
this.attempts = 0;
this.connectedAt = Date.now();
this.send({
t: 'hello',
agentId: this.agentId ?? null,
name: 'dsh-lan-share',
version: 1,
publicOrigin: this.configuredOrigin,
});
};
ws.onmessage = (event) => {
if (this.ws !== ws) return;
if (typeof event.data !== 'string') return;
let frame;
try {
frame = JSON.parse(event.data);
} catch {
return;
}
if (frame === null || typeof frame !== 'object' || typeof frame.t !== 'string') return;
try {
this.onFrame(frame);
} catch (error) {
this.log('warn', error);
}
};
ws.onerror = () => {
if (this.ws !== ws) return;
this.lastError = 'websocket-error';
};
ws.onclose = () => {
if (this.ws !== ws) return;
this.ws = null;
this.connected = false;
this.failAll('relay-disconnected');
this.scheduleReconnect();
};
}
/** Exponential backoff with jitter. */
scheduleReconnect() {
if (this.stopped || this.reconnectTimer !== null) return;
const ceiling = Math.min(this.reconnectMaxMs, this.reconnectMinMs * 2 ** this.attempts);
const wait = Math.max(250, Math.floor(ceiling / 2 + Math.random() * ceiling / 2));
this.attempts += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect();
}, wait);
if (typeof this.reconnectTimer.unref === 'function') this.reconnectTimer.unref();
}
/**
* Send one frame when the tunnel is open.
* @param {object} frame frame.
* @returns {boolean} whether it was handed to the socket.
*/
send(frame) {
const ws = this.ws;
if (ws === null || ws.readyState !== 1) return false;
try {
ws.send(JSON.stringify(frame));
return true;
} catch (error) {
this.log('warn', error);
return false;
}
}
/**
* Tell the relay about a one-time QR ticket.
* @param {string} token ticket.
* @param {number} expiresAt absolute expiry.
* @param {string | null} sessionId bound Session.
* @returns {boolean} whether the relay is connected.
*/
registerTicket(token, expiresAt, sessionId) {
return this.send({ t: 'ticket', ticket: token, expiresAt, sessionId: sessionId ?? null });
}
/** Withdraw a ticket the user replaced. */
dropTicket(token) {
this.send({ t: 'ticket-drop', ticket: token });
}
/** Dispatch one relay frame. */
onFrame(frame) {
if (frame.t === 'hello') {
this.connected = true;
if (typeof frame.publicOrigin === 'string' && frame.publicOrigin !== '') {
this.publicOrigin = this.configuredOrigin ?? frame.publicOrigin;
}
this.secure = this.publicOrigin !== null && this.publicOrigin.startsWith('https:');
for (const ticket of this.activeTickets()) {
this.send({ t: 'ticket', ticket: ticket.token, expiresAt: ticket.expiresAt, sessionId: ticket.sessionId });
}
return;
}
if (frame.t === 'open') {
if (typeof frame.id !== 'number' || frame.id <= 0) return;
if (frame.kind === 'http') {
const stream = new HttpAgentStream(this, frame);
this.streams.set(frame.id, stream);
stream.start();
} else if (frame.kind === 'ws') {
const stream = new WsAgentStream(this, frame);
this.streams.set(frame.id, stream);
stream.start();
}
return;
}
if (typeof frame.id !== 'number') return;
const stream = this.streams.get(frame.id);
if (stream === undefined) return;
switch (frame.t) {
case 'body':
if (typeof frame.data === 'string') stream.onBody(frame.data);
break;
case 'end':
stream.onEnd();
break;
case 'cancel':
stream.cancel();
break;
case 'ack':
stream.onAck(Number(frame.bytes) || 0);
break;
case 'ws-data':
if (typeof frame.data === 'string') stream.onWsData(frame.data);
break;
case 'ws-close':
stream.onWsClose();
break;
case 'error':
stream.onError(typeof frame.code === 'string' ? frame.code : 'relay-error', typeof frame.message === 'string' ? frame.message : '');
break;
default:
break;
}
}
/** Drop one stream from the registry. */
forget(id) {
this.streams.delete(id);
}
/** Fail every stream after a tunnel loss. */
failAll(reason) {
for (const stream of this.streams.values()) {
try {
stream.fail(reason);
} catch {
/* already failed */
}
}
this.streams.clear();
}
/** Request options for a local HTTP call. */
requestOptions(frame) {
const headers = {};
for (const [name, value] of Object.entries(frame.headers ?? {})) {
const lower = name.toLowerCase();
if (HOP_BY_HOP.has(lower) || lower.startsWith('x-forwarded-') || lower === 'forwarded') continue;
if (value !== undefined) headers[lower] = value;
}
headers.host = this.localAuthority;
return {
protocol: this.localProtocol,
hostname: this.localHost,
port: this.localPort,
method: frame.method,
path: frame.url,
headers,
...(this.localProtocol === 'https:' ? { rejectUnauthorized: false, agent: this.httpsAgent } : { agent: this.httpAgent }),
};
}
}
/**
* One HTTP request/response relayed to the LAN listener.
*/
class HttpAgentStream {
/**
* @param {RelayTunnel} tunnel owning tunnel.
* @param {any} frame open frame.
*/
constructor(tunnel, frame) {
this.tunnel = tunnel;
this.id = frame.id;
this.frame = frame;
this.request = null;
this.response = null;
this.closed = false;
this.responseUnacked = 0;
this.paused = false;
this.privateOrigins = [tunnel.localOrigin, tunnel.localBindOrigin];
}
/** Open the local request. */
start() {
const transport = this.tunnel.localProtocol === 'https:' ? https : http;
let request;
try {
request = transport.request(this.tunnel.requestOptions(this.frame));
} catch (error) {
this.tunnel.send({ t: 'error', id: this.id, code: 'request-failed', message: error instanceof Error ? error.message : String(error) });
this.finish();
return;
}
this.request = request;
request.on('response', (response) => {
if (this.closed) {
response.resume();
return;
}
this.response = response;
this.tunnel.send({
t: 'head',
id: this.id,
status: response.statusCode ?? 502,
headers: responseHeaders(response.headers, this.privateOrigins, this.tunnel.publicOrigin, this.tunnel.secure),
});
response.on('data', (chunk) => {
if (this.closed) return;
this.responseUnacked += chunk.length;
this.tunnel.send({ t: 'body', id: this.id, data: chunk.toString('base64') });
if (this.responseUnacked > this.tunnel.windowBytes && !this.paused) {
response.pause();
this.paused = true;
}
});
response.on('end', () => {
if (this.closed) return;
this.tunnel.send({ t: 'end', id: this.id });
this.finish();
});
response.on('error', () => this.fail('response-error'));
});
request.on('error', (error) => {
if (this.closed) return;
this.tunnel.send({ t: 'error', id: this.id, code: 'local-listener-error', message: error instanceof Error ? error.message : String(error) });
this.finish();
});
request.on('close', () => {
if (!this.closed && this.response === null) this.finish();
});
}
/** Write one request-body chunk and acknowledge it when flushed. */
onBody(data) {
if (this.closed || this.request === null) return;
const buffer = Buffer.from(data, 'base64');
const request = this.request;
try {
request.write(buffer, () => {
if (!this.closed) this.tunnel.send({ t: 'ack', id: this.id, bytes: buffer.length });
});
} catch {
this.fail('request-write-failed');
}
}
/** Finish the local request. */
onEnd() {
if (this.closed || this.request === null) return;
try {
this.request.end();
} catch {
this.fail('request-end-failed');
}
}
/** The relay accepted response bytes; resume a paused upstream response. */
onAck(bytes) {
if (!Number.isFinite(bytes) || bytes <= 0) return;
this.responseUnacked = Math.max(0, this.responseUnacked - bytes);
if (this.paused && this.response !== null && this.responseUnacked <= this.tunnel.lowWaterBytes) {
this.paused = false;
this.response.resume();
}
}
/** The relay refused or cancelled the stream. */
cancel() {
this.fail('cancelled');
}
/** Surface an error to the relay when possible. */
onError(code) {
this.fail(code);
}
/** Fail the local request and release the stream. */
fail(reason) {
if (this.closed) return;
this.closed = true;
try {
this.request?.destroy();
} catch {
/* already gone */
}
this.finish();
}
/** Remove this stream from the tunnel. */
finish() {
this.closed = true;
this.tunnel.forget(this.id);
}
}
/**
* One raw browser WebSocket relayed to the LAN listener.
*/
class WsAgentStream {
/**
* @param {RelayTunnel} tunnel owning tunnel.
* @param {any} frame open frame.
*/
constructor(tunnel, frame) {
this.tunnel = tunnel;
this.id = frame.id;
this.frame = frame;
this.socket = null;
this.closed = false;
this.acked = false;
this.unacked = 0;
this.paused = false;
this.buffer = Buffer.alloc(0);
}
/** Connect to the local listener and replay the upgrade. */
start() {
const transport = this.tunnel.localProtocol === 'https:' ? tls : net;
let socket;
try {
socket = this.tunnel.localProtocol === 'https:'
? tls.connect({ host: this.tunnel.localHost, port: this.tunnel.localPort, rejectUnauthorized: false })
: net.connect({ host: this.tunnel.localHost, port: this.tunnel.localPort });
} catch (error) {
this.tunnel.send({ t: 'ws-close', id: this.id });
this.finish();
return;
}
this.socket = socket;
socket.setNoDelay(true);
const event = this.tunnel.localProtocol === 'https:' ? 'secureConnect' : 'connect';
socket.once(event, () => this.writeUpgrade());
socket.on('error', () => this.closeUpstream(true));
socket.on('close', () => this.closeUpstream(true));
this.onFirstData = (chunk) => {
this.buffer = Buffer.concat([this.buffer, chunk]);
const end = this.buffer.indexOf('\r\n\r\n');
if (end === -1) {
if (this.buffer.length > 64 * 1024) this.closeUpstream();
return;
}
socket.off('data', this.onFirstData);
const head = this.buffer;
const status = /^HTTP\/1\.[01] (\d{3})/.exec(head.subarray(0, end).toString('latin1'));
const code = status === null ? 502 : Number(status[1]);
this.tunnel.send({ t: 'ws-ack', id: this.id, status: code, head: head.toString('base64') });
if (code !== 101) {
this.finish();
return;
}
this.acked = true;
socket.on('data', (next) => this.onUpstreamData(next));
};
socket.on('data', this.onFirstData);
}
/** Write the browser's upgrade request to the local listener. */
writeUpgrade() {
const socket = this.socket;
if (socket === null || this.closed) return;
const headers = {};
for (const [name, value] of Object.entries(this.frame.headers ?? {})) {
const lower = name.toLowerCase();
if (HOP_BY_HOP.has(lower) || lower.startsWith('x-forwarded-') || lower === 'forwarded') continue;
if (value !== undefined) headers[lower] = value;
}
headers.host = this.tunnel.localAuthority;
headers.connection = 'Upgrade';
headers.upgrade = 'websocket';
let text = this.frame.method + ' ' + this.frame.url + ' HTTP/1.1\r\n';
for (const [name, value] of Object.entries(headers)) {
if (Array.isArray(value)) {
for (const item of value) text += name + ': ' + item + '\r\n';
} else {
text += name + ': ' + String(value) + '\r\n';
}
}
text += '\r\n';
socket.write(text);
if (typeof this.frame.head === 'string' && this.frame.head !== '') {
socket.write(Buffer.from(this.frame.head, 'base64'));
}
}
/** Forward local upstream bytes to the relay with a window. */
onUpstreamData(chunk) {
if (this.closed) return;
this.unacked += chunk.length;
this.tunnel.send({ t: 'ws-data', id: this.id, data: chunk.toString('base64') });
if (this.unacked > this.tunnel.windowBytes && !this.paused) {
this.paused = true;
this.socket.pause();
}
}
/** Write browser bytes upstream and acknowledge after the socket accepts them. */
onWsData(data) {
if (this.closed || !this.acked || this.socket === null) return;
const buffer = Buffer.from(data, 'base64');
let accepted;
try {
accepted = this.socket.write(buffer);
} catch {
this.closeUpstream();
return;
}
const ack = () => {
if (!this.closed) this.tunnel.send({ t: 'ack', id: this.id, bytes: buffer.length });
};
if (accepted) {
ack();
return;
}
this.socket.once('drain', ack);
}
/** The relay consumed upstream bytes; resume a paused socket. */
onAck(bytes) {
if (!Number.isFinite(bytes) || bytes <= 0) return;
this.unacked = Math.max(0, this.unacked - bytes);
if (this.paused && this.socket !== null && this.unacked <= this.tunnel.lowWaterBytes) {
this.paused = false;
this.socket.resume();
}
}
/** The relay closed the browser side. */
onWsClose() {
this.closeUpstream(false);
}
/** The relay cancelled the stream. */
cancel() {
this.closeUpstream(false);
}
/** Surface a relay error. */
onError() {
this.closeUpstream(false);
}
/** The tunnel is gone; release the local socket without echoing. */
fail() {
this.closeUpstream(false);
}
/**
* Close the local upstream socket.
* @param {boolean} notify whether to tell the relay the browser side ended.
*/
closeUpstream(notify = true) {
if (this.closed) return;
this.closed = true;
if (notify) this.tunnel.send({ t: 'ws-close', id: this.id });
if (this.socket !== null) {
try {
this.socket.destroy();
} catch {
/* already gone */
}
}
this.tunnel.forget(this.id);
}
/** Local finish that also tells the relay. */
finish() {
if (this.closed) return;
this.closed = true;
if (this.socket !== null) {
try {
this.socket.destroy();
} catch {
/* already gone */
}
}
this.tunnel.forget(this.id);
}
}