46 lines
2.3 KiB
JavaScript
46 lines
2.3 KiB
JavaScript
// This pinned DSH release has no --public-url. Rewrite only its printed address;
|
|
// listener authentication and Host/Origin validation remain entirely upstream.
|
|
import { spawn } from 'node:child_process';
|
|
import net from 'node:net';
|
|
const ip = process.env.DSH_BIND_IP;
|
|
const publicUrl = new URL(process.env.DSH_PUBLIC_URL);
|
|
if (!ip || !['http:', 'https:'].includes(publicUrl.protocol) || publicUrl.pathname !== '/' || publicUrl.search || publicUrl.hash || publicUrl.username || publicUrl.password) {
|
|
throw new Error('A plain HTTP(S) root URL and a container bind address are required.');
|
|
}
|
|
// User-approved LAN relay. Bytes, Host/Origin headers and authentication remain
|
|
// unchanged; DSH itself retains its required loopback listener.
|
|
const relay = net.createServer(client => {
|
|
const upstream = net.connect(3082, '127.0.0.1');
|
|
client.pipe(upstream); upstream.pipe(client);
|
|
client.on('error', () => upstream.destroy());
|
|
upstream.on('error', () => client.destroy());
|
|
client.on('close', () => upstream.destroy());
|
|
upstream.on('close', () => client.destroy());
|
|
});
|
|
relay.listen(3080, '0.0.0.0');
|
|
const child = spawn('/opt/dsh/node_modules/.bin/dsh', [
|
|
'web', '--no-open', '--port', '3082', '--host', ip,
|
|
'--trusted-host', process.env.DSH_TRUSTED_HOST,
|
|
], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
function forward(stream, destination) {
|
|
let pending = '';
|
|
const emit = line => {
|
|
for (const host of [ip, '127.0.0.1', 'localhost']) line = line.replaceAll(`http://${host}:3082/`, publicUrl.href);
|
|
destination.write(line);
|
|
};
|
|
stream.setEncoding('utf8');
|
|
stream.on('data', text => {
|
|
pending += text;
|
|
let end;
|
|
while ((end = pending.indexOf('\n')) >= 0) {
|
|
emit(pending.slice(0, end + 1)); pending = pending.slice(end + 1);
|
|
}
|
|
});
|
|
stream.on('end', () => { if (pending) emit(pending); });
|
|
}
|
|
forward(child.stdout, process.stdout); forward(child.stderr, process.stderr);
|
|
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { relay.close(); child.kill(signal); });
|
|
relay.on('error', error => { console.error(error.message); child.kill('SIGTERM'); process.exitCode = 1; });
|
|
child.on('error', error => { console.error(error.message); relay.close(); process.exitCode = 1; });
|
|
child.on('exit', (code, signal) => { relay.close(); process.exitCode = code ?? (signal ? 1 : 0); });
|