253 lines
11 KiB
JavaScript
253 lines
11 KiB
JavaScript
#!/usr/bin/env node
|
|
'use strict';
|
|
|
|
// Serve existing HTML and static assets. No build step, proxy, or network configuration.
|
|
const fs = require('node:fs');
|
|
const http = require('node:http');
|
|
const os = require('node:os');
|
|
const path = require('node:path');
|
|
const crypto = require('node:crypto');
|
|
const net = require('node:net');
|
|
const { spawn } = require('node:child_process');
|
|
|
|
class PreviewError extends Error {
|
|
constructor(code, message) { super(message); this.code = code; }
|
|
}
|
|
const fail = (code, message) => { throw new PreviewError(code, message); };
|
|
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
const statusPath = '/.previewer-status';
|
|
const types = {
|
|
'.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8',
|
|
'.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
'.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8',
|
|
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
'.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon',
|
|
'.woff': 'font/woff', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8',
|
|
'.pdf': 'application/pdf', '.wasm': 'application/wasm',
|
|
};
|
|
|
|
function parseArgs(argv) {
|
|
const args = { host: '127.0.0.1', port: 0, ttl: 3600, file: null };
|
|
for (let index = 0; index < argv.length; index++) {
|
|
const value = argv[index];
|
|
if (['--host', '--port', '--ttl'].includes(value)) {
|
|
const next = argv[++index];
|
|
if (next === undefined || next.startsWith('--')) fail('ARGUMENT', 'Missing value for ' + value);
|
|
args[value.slice(2)] = value === '--host' ? next : Number(next);
|
|
} else if (value.startsWith('-')) {
|
|
fail('ARGUMENT', 'Unknown option: ' + value);
|
|
} else if (args.file === null) args.file = value;
|
|
else fail('ARGUMENT', 'Unexpected argument: ' + value);
|
|
}
|
|
if (!args.file) fail('ARGUMENT', 'An HTML or static file is required');
|
|
if (args.host === 'localhost') args.host = '127.0.0.1';
|
|
if (!net.isIP(args.host)) fail('ARGUMENT', '--host must be an IPv4 or IPv6 address');
|
|
if (!Number.isInteger(args.port) || args.port < 0 || args.port > 65535) fail('ARGUMENT', '--port must be 0..65535');
|
|
// Node timers use a signed 32-bit millisecond delay.
|
|
if (!Number.isInteger(args.ttl) || args.ttl < 1 || args.ttl > 2147483) fail('ARGUMENT', '--ttl must be 1..2147483 seconds');
|
|
try {
|
|
args.file = fs.realpathSync(path.resolve(args.file));
|
|
if (!fs.statSync(args.file).isFile()) fail('FILE_INVALID', 'Input is not a regular file');
|
|
} catch (error) {
|
|
if (error instanceof PreviewError) throw error;
|
|
fail('FILE_INVALID', 'File is unavailable: ' + path.resolve(args.file));
|
|
}
|
|
return args;
|
|
}
|
|
|
|
function urlHost(host) { return net.isIPv6(host) ? '[' + host + ']' : host; }
|
|
function probeHost(host) { return host === '0.0.0.0' ? '127.0.0.1' : host === '::' ? '::1' : host; }
|
|
function urlsFor(config, port) {
|
|
const filename = encodeURIComponent(path.basename(config.file));
|
|
const address = probeHost(config.host);
|
|
const local = 'http://' + urlHost(address) + ':' + port + '/' + filename;
|
|
const urls = [local];
|
|
if (config.host === '0.0.0.0' || config.host === '::') {
|
|
for (const entries of Object.values(os.networkInterfaces())) for (const entry of entries ?? []) {
|
|
if (entry.internal || entry.family !== 'IPv4') continue;
|
|
const url = 'http://' + entry.address + ':' + port + '/' + filename;
|
|
if (!urls.includes(url)) urls.push(url);
|
|
}
|
|
}
|
|
return { url: local, urls };
|
|
}
|
|
|
|
function probe(state) {
|
|
return new Promise((resolve) => {
|
|
if (!state || !Number.isInteger(state.port) || typeof state.token !== 'string') return resolve(false);
|
|
const request = http.get({
|
|
host: probeHost(state.host), port: state.port, path: statusPath,
|
|
headers: { 'X-Previewer-Token': state.token }, timeout: 1000,
|
|
}, (response) => {
|
|
let body = '';
|
|
response.on('data', (chunk) => { body += chunk; });
|
|
response.on('end', () => {
|
|
try {
|
|
const actual = JSON.parse(body);
|
|
resolve(response.statusCode === 200 && actual.pid === state.pid && actual.key === state.key && actual.file === state.file);
|
|
} catch { resolve(false); }
|
|
});
|
|
response.on('error', () => resolve(false));
|
|
});
|
|
request.on('error', () => resolve(false));
|
|
request.on('timeout', () => { request.destroy(); resolve(false); });
|
|
});
|
|
}
|
|
|
|
function publicResult(state, reused) {
|
|
const { token, key, ...result } = state;
|
|
return { ...result, reused, stopCommand: 'kill -TERM ' + state.pid };
|
|
}
|
|
|
|
function startWorker(config) {
|
|
return new Promise((resolve, reject) => {
|
|
const child = spawn(process.execPath, [__filename, '--worker'], {
|
|
detached: true, stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
|
});
|
|
let diagnostics = '';
|
|
child.stderr.on('data', (chunk) => { diagnostics += chunk; });
|
|
const timer = setTimeout(() => {
|
|
child.kill();
|
|
reject(new PreviewError('START_TIMEOUT', 'Static server did not become ready'));
|
|
}, 5000);
|
|
child.once('message', (message) => {
|
|
clearTimeout(timer);
|
|
if (message.error) {
|
|
child.kill();
|
|
reject(new PreviewError(message.code ?? 'START_FAILED', message.error));
|
|
return;
|
|
}
|
|
child.disconnect();
|
|
child.stderr.destroy();
|
|
child.unref();
|
|
resolve(message);
|
|
});
|
|
child.once('error', (error) => {
|
|
clearTimeout(timer);
|
|
reject(new PreviewError('START_FAILED', error.message));
|
|
});
|
|
child.once('exit', (code) => {
|
|
clearTimeout(timer);
|
|
reject(new PreviewError('START_FAILED', 'Static server exited: ' + code + ' ' + diagnostics.trim()));
|
|
});
|
|
child.send(config);
|
|
});
|
|
}
|
|
|
|
async function launch(config) {
|
|
const root = path.dirname(config.file);
|
|
const key = crypto.createHash('sha256').update(JSON.stringify(config)).digest('hex');
|
|
const stateDir = path.join(os.tmpdir(), 'previewer-' + (process.getuid?.() ?? os.userInfo().username));
|
|
fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
const statePath = path.join(stateDir, key + '.json');
|
|
const lockPath = statePath + '.lock';
|
|
let locked = false;
|
|
for (let attempt = 0; attempt < 120; attempt++) {
|
|
try { fs.mkdirSync(lockPath); locked = true; break; }
|
|
catch (error) {
|
|
if (error.code !== 'EEXIST') throw error;
|
|
try {
|
|
// Recover an empty lock left by a launcher that crashed.
|
|
if (Date.now() - fs.statSync(lockPath).mtimeMs > 15000) fs.rmdirSync(lockPath);
|
|
} catch {}
|
|
await delay(50);
|
|
}
|
|
}
|
|
if (!locked) fail('BUSY', 'Another launcher is starting this preview; retry shortly');
|
|
let childState;
|
|
try {
|
|
let previous;
|
|
try { previous = JSON.parse(fs.readFileSync(statePath, 'utf8')); } catch {}
|
|
if (previous && await probe(previous)) return publicResult(previous, true);
|
|
childState = await startWorker({ ...config, root, key, statePath, token: crypto.randomUUID() });
|
|
if (!await probe(childState)) fail('VERIFY_FAILED', 'Static server readiness check failed');
|
|
fs.writeFileSync(statePath, JSON.stringify(childState), { mode: 0o600 });
|
|
return publicResult(childState, false);
|
|
} catch (error) {
|
|
if (childState?.pid) { try { process.kill(childState.pid, 'SIGTERM'); } catch {} }
|
|
throw error;
|
|
} finally {
|
|
fs.rmdirSync(lockPath);
|
|
}
|
|
}
|
|
|
|
function runWorker(config) {
|
|
let shuttingDown = false;
|
|
let timer;
|
|
let state;
|
|
const server = http.createServer((request, response) => {
|
|
if (!['GET', 'HEAD'].includes(request.method)) {
|
|
response.writeHead(405, { Allow: 'GET, HEAD' }).end('Method not allowed');
|
|
return;
|
|
}
|
|
let pathname;
|
|
try { pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); }
|
|
catch { response.writeHead(400).end('Bad request'); return; }
|
|
if (pathname === statusPath) {
|
|
if (request.headers['x-previewer-token'] !== config.token) { response.writeHead(404).end('Not found'); return; }
|
|
response.setHeader('Content-Type', 'application/json');
|
|
response.end(request.method === 'HEAD' ? undefined : JSON.stringify(state));
|
|
return;
|
|
}
|
|
let candidate;
|
|
try {
|
|
const relative = pathname === '/' ? path.basename(config.file) : pathname.replace(/^\/+/, '');
|
|
candidate = fs.realpathSync(path.resolve(config.root, relative));
|
|
const inside = path.relative(config.root, candidate);
|
|
if (inside === '..' || inside.startsWith('..' + path.sep) || path.isAbsolute(inside)) {
|
|
response.writeHead(403).end('Forbidden');
|
|
return;
|
|
}
|
|
// Explicit filenames only; no directory listings.
|
|
if (!fs.statSync(candidate).isFile()) { response.writeHead(404).end('Not found'); return; }
|
|
} catch { response.writeHead(404).end('Not found'); return; }
|
|
response.writeHead(200, {
|
|
'Content-Type': types[path.extname(candidate).toLowerCase()] ?? 'application/octet-stream',
|
|
'Cache-Control': 'no-store',
|
|
'X-Content-Type-Options': 'nosniff',
|
|
});
|
|
if (request.method === 'HEAD') { response.end(); return; }
|
|
fs.createReadStream(candidate).on('error', () => response.destroy()).pipe(response);
|
|
});
|
|
function shutdown() {
|
|
if (shuttingDown) return;
|
|
shuttingDown = true;
|
|
clearTimeout(timer);
|
|
try {
|
|
const record = JSON.parse(fs.readFileSync(config.statePath, 'utf8'));
|
|
if (record.pid === process.pid && record.token === config.token) fs.unlinkSync(config.statePath);
|
|
} catch {}
|
|
server.close(() => process.exit(0));
|
|
setTimeout(() => process.exit(0), 1000).unref();
|
|
}
|
|
process.on('SIGTERM', shutdown);
|
|
process.on('SIGINT', shutdown);
|
|
server.once('error', (error) => {
|
|
process.send?.({ code: error.code === 'EADDRINUSE' ? 'PORT_IN_USE' : 'START_FAILED', error: error.message });
|
|
process.exitCode = 2;
|
|
});
|
|
server.listen(config.port, config.host, () => {
|
|
const port = server.address().port;
|
|
state = {
|
|
file: config.file, directory: config.root, host: config.host, port, pid: process.pid,
|
|
ttl: config.ttl, expiresAt: new Date(Date.now() + config.ttl * 1000).toISOString(),
|
|
...urlsFor(config, port), token: config.token, key: config.key,
|
|
};
|
|
timer = setTimeout(shutdown, config.ttl * 1000);
|
|
process.send?.(state);
|
|
});
|
|
}
|
|
|
|
if (process.argv[2] === '--worker') {
|
|
process.once('message', runWorker);
|
|
} else if (process.argv.includes('--help') || process.argv.includes('-h')) {
|
|
console.log('Usage: node serve_file.js FILE [--host IP] [--port PORT] [--ttl SECONDS]\nServe existing HTML/static assets. Defaults: 127.0.0.1, automatic port, 3600 seconds.');
|
|
} else {
|
|
Promise.resolve().then(() => launch(parseArgs(process.argv.slice(2)))).then((result) => {
|
|
console.log(JSON.stringify(result));
|
|
}).catch((error) => {
|
|
console.error(JSON.stringify({ code: error.code ?? 'PREVIEW_FAILED', message: error.message }));
|
|
process.exitCode = 2;
|
|
});
|
|
}
|