Files
dsh-lan-share/test/proxy.test.mjs
T

468 lines
18 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import net from 'node:net';
import { mkdtemp, rm } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { normalizeConfig } from '../config.js';
import { DeviceStore, TicketStore } from '../store.js';
import { LanShareServer } from '../proxy.js';
/**
* A fake Desktop Host: it authenticates the launch token, demands its own
* cookie on every other request, and records what the proxy sent it.
*/
function createUpstream() {
const state = {
minted: 1,
required: 1,
requests: [],
upgrades: [],
sockets: new Set(),
body: 'UPSTREAM OK',
};
const server = http.createServer((req, res) => {
state.requests.push({ method: req.method, url: req.url, headers: req.headers });
const url = new URL(req.url ?? '/', 'http://upstream.invalid');
if (url.pathname === '/' && url.searchParams.has('token')) {
res.writeHead(303, {
location: './',
'set-cookie': 'dsh-auth-test=v' + String(state.minted++) + '; Path=/; HttpOnly; Max-Age=3600; SameSite=Strict',
});
res.end();
return;
}
const cookie = req.headers.cookie ?? '';
const offered = /dsh-auth-test=v(\d+)/.exec(cookie);
const authenticated = offered !== null && Number(offered[1]) >= state.required;
if (!authenticated) {
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('unauthorized');
return;
}
if (url.pathname === '/') {
res.writeHead(200, {
'content-type': 'text/html; charset=utf-8',
'set-cookie': ['dsh-auth-test2=should-drop; Path=/', 'other=keep; Path=/'],
});
res.end('<h1>' + state.body + '</h1>');
return;
}
if (url.pathname === '/redirect') {
res.writeHead(302, { location: 'http://' + req.headers.host + '/target' });
res.end();
return;
}
if (url.pathname === '/sse') {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
res.write('data: one\n\n');
setTimeout(() => {
res.write('data: two\n\n');
res.end();
}, 30);
return;
}
if (url.pathname === '/echo') {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ body: Buffer.concat(chunks).toString('utf8'), host: req.headers.host, origin: req.headers.origin ?? null }));
});
return;
}
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('OK');
});
server.on('upgrade', (req, socket) => {
state.upgrades.push(req.headers);
state.sockets.add(socket);
socket.on('close', () => state.sockets.delete(socket));
socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n');
socket.on('data', (chunk) => socket.write(chunk));
});
return { server, state };
}
function listen(server) {
return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port)));
}
function close(server) {
return new Promise((resolve) => {
for (const socket of server.state?.sockets ?? []) socket.destroy();
server.closeAllConnections?.();
server.close(() => resolve());
});
}
async function startFixture() {
const upstream = createUpstream();
const upstreamPort = await listen(upstream.server);
const upstreamOrigin = 'http://127.0.0.1:' + String(upstreamPort);
const dir = await mkdtemp(join(tmpdir(), 'lan-share-test-'));
const config = normalizeConfig({
host: '127.0.0.1',
port: 0,
stateFile: join(dir, 'devices.json'),
ticketTtlSeconds: 60,
deviceTtlDays: 1,
maxDevices: 2,
}, { DSH_HOME: dir });
const devices = new DeviceStore(config.stateFile, { ttlMs: config.deviceTtlMs, maxDevices: config.maxDevices });
await devices.load();
const tickets = new TicketStore({ ttlMs: config.ticketTtlMs });
const server = new LanShareServer({
config,
devices,
tickets,
upstream: { origin: upstreamOrigin, protocol: 'http:', host: '127.0.0.1', port: upstreamPort },
authenticatedUrl: () => upstreamOrigin + '/?token=LAUNCH',
});
await server.start();
assert.equal(server.state.running, true, 'listener must start');
return { upstream, upstreamPort, upstreamOrigin, server, devices, tickets, dir };
}
async function stopFixture(fixture) {
await fixture.server.stop();
await fixture.devices.close();
for (const socket of fixture.upstream.state.sockets) socket.destroy();
await close(fixture.upstream.server);
await rm(fixture.dir, { recursive: true, force: true });
}
/**
* Pair one fake tablet.
* @param {string} origin listener origin.
* @param {ReturnType<typeof startFixture> extends Promise<infer T> ? T['server'] : never} server listener.
* @returns {Promise<string>} the device cookie.
*/
async function waitForPending(server) {
for (let attempt = 0; attempt < 200; attempt += 1) {
const pending = server.state.pending[0];
if (pending !== undefined) return pending;
await sleep(5);
}
throw new Error('the scanned ticket did not create a pending request');
}
async function pair(origin, server) {
const { url } = server.createTicket(null);
const tokenPath = new URL(url).pathname;
const responsePromise = fetch(origin + tokenPath, { redirect: 'manual', headers: { accept: 'text/html' } });
const pending = await waitForPending(server);
const approved = await server.approvePending(pending.id);
assert.equal(approved.ok, true, 'the owner approval must create the device');
const response = await responsePromise;
assert.equal(response.status, 303);
const cookies = response.headers.getSetCookie();
assert.equal(cookies.length, 1);
assert.match(cookies[0], /^dsh-lan-device=/);
return cookies[0].split(';', 1)[0];
}
test('unauthenticated requests get the pairing page, not the app', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
const page = await fetch(origin + '/', { headers: { accept: 'text/html' } });
assert.equal(page.status, 401);
assert.match(await page.text(), /QR/);
const api = await fetch(origin + '/api/session/list', { headers: { accept: 'application/json' } });
assert.equal(api.status, 401);
} finally {
await stopFixture(fixture);
}
});
test('one-time ticket pairs exactly one device', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
const { url } = fixture.server.createTicket(null);
const path = new URL(url).pathname;
const firstPromise = fetch(origin + path, { redirect: 'manual' });
const pending = await waitForPending(fixture.server);
const approved = await fixture.server.approvePending(pending.id);
assert.equal(approved.ok, true);
const first = await firstPromise;
assert.equal(first.status, 303);
assert.equal(first.headers.get('location'), '/');
const cookie = first.headers.getSetCookie()[0].split(';', 1)[0];
const second = await fetch(origin + path, { redirect: 'manual' });
assert.equal(second.status, 410);
const app = await fetch(origin + '/', { headers: { cookie } });
assert.equal(app.status, 200);
assert.match(await app.text(), /UPSTREAM OK/);
assert.equal(fixture.devices.list().length, 1);
} finally {
await stopFixture(fixture);
}
});
test('a scanned ticket waits for the owner and can be denied', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
const { url } = fixture.server.createTicket(null);
const responsePromise = fetch(origin + new URL(url).pathname, {
redirect: 'manual',
headers: { accept: 'text/html', 'user-agent': 'DenyTest/1.0' },
});
const pending = await waitForPending(fixture.server);
assert.equal(pending.label.length > 0, true, 'the pending request describes the device');
assert.equal(pending.ip.length > 0, true, 'the pending request carries the peer address');
assert.equal(pending.userAgent, 'DenyTest/1.0');
assert.equal(fixture.server.state.pending.length, 1);
assert.equal(fixture.server.denyPending(pending.id), true);
const response = await responsePromise;
assert.equal(response.status, 403);
assert.equal(fixture.devices.list().length, 0, 'denial must not create a device');
const reused = await fetch(origin + new URL(url).pathname, { redirect: 'manual' });
assert.equal(reused.status, 410, 'the scanned ticket stays consumed');
} finally {
await stopFixture(fixture);
}
});
test('upstream headers are rewritten and auth cookies are withheld', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
const cookie = await pair(origin, fixture.server);
const response = await fetch(origin + '/', { headers: { cookie, origin: 'http://192.168.1.9:1234' } });
assert.equal(response.status, 200);
const setCookies = response.headers.getSetCookie();
assert.ok(setCookies.every((value) => !value.startsWith('dsh-auth-')), 'auth cookie must not reach the tablet');
assert.ok(setCookies.some((value) => value.startsWith('other=keep')), 'other cookies pass through');
const upstream = fixture.upstream.state.requests.at(-1);
assert.equal(upstream.headers.host, '127.0.0.1:' + String(fixture.upstreamPort), 'Host names the upstream');
assert.match(upstream.headers.cookie, /^dsh-auth-test=v\d+$/, 'upstream sees the minted cookie');
assert.equal(upstream.headers.origin, undefined, 'Origin is removed for HTTP');
} finally {
await stopFixture(fixture);
}
});
test('request bodies, redirects and SSE stream through', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
const cookie = await pair(origin, fixture.server);
const echo = await fetch(origin + '/echo', {
method: 'POST',
headers: { cookie, 'content-type': 'application/json' },
body: JSON.stringify({ hello: 'world' }),
});
assert.equal(echo.status, 200);
const payload = await echo.json();
assert.deepEqual(JSON.parse(payload.body), { hello: 'world' });
assert.equal(payload.host, '127.0.0.1:' + String(fixture.upstreamPort));
const redirect = await fetch(origin + '/redirect', { headers: { cookie }, redirect: 'manual' });
assert.equal(redirect.status, 302);
assert.equal(redirect.headers.get('location'), origin + '/target');
const sse = await fetch(origin + '/sse', { headers: { cookie } });
assert.equal(sse.status, 200);
assert.equal(await sse.text(), 'data: one\n\ndata: two\n\n');
} finally {
await stopFixture(fixture);
}
});
test('bootstrap, session binding and self-removal', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
const cookie = await pair(origin, fixture.server);
const bootstrap = await fetch(origin + '/api/lan-share/bootstrap', { headers: { cookie } });
assert.equal(bootstrap.status, 200);
const first = await bootstrap.json();
assert.equal(first.remote, true);
assert.equal(first.sessionId, null);
const update = await fetch(origin + '/api/lan-share/session', {
method: 'POST',
headers: { cookie, 'content-type': 'application/json' },
body: JSON.stringify({ sessionId: 'session-123' }),
});
assert.equal(update.status, 200);
const again = await (await fetch(origin + '/api/lan-share/bootstrap', { headers: { cookie } })).json();
assert.equal(again.sessionId, 'session-123');
const forbidden = await fetch(origin + '/api/lan-share/ticket', { method: 'POST', headers: { cookie } });
assert.equal(forbidden.status, 403);
const forget = await fetch(origin + '/api/lan-share/forget-self', { method: 'POST', headers: { cookie } });
assert.equal(forget.status, 200);
const after = await fetch(origin + '/', { headers: { cookie } });
assert.equal(after.status, 401);
} finally {
await stopFixture(fixture);
}
});
test('revoking a device closes its WebSocket and refuses HTTP', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
const cookie = await pair(origin, fixture.server);
const port = fixture.server.port;
const socket = net.connect(port, '127.0.0.1');
const response = await new Promise((resolve, reject) => {
let buffer = '';
const onData = (chunk) => {
buffer += chunk.toString('latin1');
if (buffer.includes('\r\n\r\n')) {
socket.off('data', onData);
resolve(buffer);
}
};
socket.on('data', onData);
socket.on('error', reject);
socket.write('GET /api/remote.mux HTTP/1.1\r\nHost: ' + new URL(origin).host + '\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\nCookie: ' + cookie + '\r\n\r\n');
});
assert.match(response, /^HTTP\/1\.1 101/);
const upgrade = fixture.upstream.state.upgrades.at(-1);
assert.equal(upgrade.cookie.includes('dsh-auth-test='), true);
assert.equal(upgrade.origin, fixture.upstreamOrigin);
assert.equal(upgrade.upgrade, 'websocket');
assert.equal(upgrade.connection, 'Upgrade');
await fixture.server.revoke({ all: true });
await new Promise((resolve) => setTimeout(resolve, 60));
assert.equal(socket.destroyed, true, 'revocation closes the live socket');
const httpAfter = await fetch(origin + '/', { headers: { cookie } });
assert.equal(httpAfter.status, 401);
} finally {
await stopFixture(fixture);
}
});
test('a stale upstream cookie is re-minted once and the GET retried', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
const cookie = await pair(origin, fixture.server);
/* The cookie minted during pairing is v1; from now on only v2+ is
* accepted, so the first GET is refused and the proxy must re-mint. */
fixture.upstream.state.required = 2;
const before = fixture.upstream.state.minted;
const response = await fetch(origin + '/', { headers: { cookie } });
assert.equal(response.status, 200, 'the retry succeeds with a fresh cookie');
assert.ok(fixture.upstream.state.minted > before, 'a new cookie was minted');
assert.ok(fixture.upstream.state.requests.filter((request) => request.url === '/').length >= 2, 'the GET was attempted twice');
} finally {
await stopFixture(fixture);
}
});
test('the device limit is enforced when the owner approves', async () => {
const fixture = await startFixture();
try {
const origin = fixture.server.publicOrigin;
await pair(origin, fixture.server);
await pair(origin, fixture.server);
const { url } = fixture.server.createTicket(null);
const responsePromise = fetch(origin + new URL(url).pathname, { redirect: 'manual' });
const pending = await waitForPending(fixture.server);
const approved = await fixture.server.approvePending(pending.id);
assert.equal(approved.ok, false);
assert.equal(approved.code, 'DEVICE_LIMIT');
assert.equal(fixture.server.denyPending(pending.id), true);
const response = await responsePromise;
assert.equal(response.status, 403);
assert.equal(fixture.devices.list().length, 2);
} finally {
await stopFixture(fixture);
}
});
test('expired devices and tickets are refused', async () => {
const dir = await mkdtemp(join(tmpdir(), 'lan-share-expiry-'));
try {
const devices = new DeviceStore(join(dir, 'devices.json'), { ttlMs: 40, maxDevices: 2 });
await devices.load();
const added = await devices.add({ label: 'iPad', ip: '127.0.0.1', sessionId: 's1' });
assert.ok(devices.verify(added.cookie) !== undefined);
await new Promise((resolve) => setTimeout(resolve, 60));
assert.equal(devices.verify(added.cookie), undefined, 'expired device cookie');
const tickets = new TicketStore({ ttlMs: 30 });
const { token } = tickets.mint('s1');
await new Promise((resolve) => setTimeout(resolve, 50));
assert.equal(tickets.consume(token), undefined, 'expired ticket');
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test('the device registry survives a reload', async () => {
const dir = await mkdtemp(join(tmpdir(), 'lan-share-reload-'));
try {
const file = join(dir, 'devices.json');
const first = new DeviceStore(file, { ttlMs: 60_000, maxDevices: 4 });
await first.load();
const added = await first.add({ label: 'iPad', ip: '192.168.1.9', sessionId: 's-9' });
await first.close();
const second = new DeviceStore(file, { ttlMs: 60_000, maxDevices: 4 });
await second.load();
const record = second.verify(added.cookie);
assert.ok(record !== undefined);
assert.equal(record.label, 'iPad');
assert.equal(record.sessionId, 's-9');
assert.equal(second.list().length, 1);
await second.revokeAll();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test('a busy port falls back to an OS-assigned port', async () => {
const blocker = http.createServer();
const blockedPort = await listen(blocker);
const upstream = createUpstream();
const upstreamPort = await listen(upstream.server);
const dir = await mkdtemp(join(tmpdir(), 'lan-share-port-'));
const config = normalizeConfig({
host: '127.0.0.1',
port: blockedPort,
stateFile: join(dir, 'devices.json'),
}, { DSH_HOME: dir });
const devices = new DeviceStore(config.stateFile, { ttlMs: config.deviceTtlMs, maxDevices: 2 });
await devices.load();
const server = new LanShareServer({
config,
devices,
tickets: new TicketStore({ ttlMs: 60_000 }),
upstream: { origin: 'http://127.0.0.1:' + String(upstreamPort), protocol: 'http:', host: '127.0.0.1', port: upstreamPort },
authenticatedUrl: () => 'http://127.0.0.1:' + String(upstreamPort) + '/?token=L',
});
try {
await server.start();
assert.equal(server.state.running, true);
assert.equal(server.state.fallbackPort, true);
assert.notEqual(server.port, blockedPort);
} finally {
await server.stop();
await devices.close();
await close(blocker);
await close(upstream.server);
await rm(dir, { recursive: true, force: true });
}
});