feat(browser): replace the preview proxy with a real browser panel and an agent web tool (#2883)
The preview panel worked by proxying a dev server through OpenChamber's own origin and rewriting the HTML that came back. Anything the rewriter did not anticipate broke, and pages that refuse to be embedded never loaded at all. This deletes the proxy (-1604 lines and its tests) and merges the preview and browser panels into one surface backed by a real Chromium view. What the panel is now - A `<webview>` in its own session partition: logins and cookies persist, hot reload works because nothing is rewritten, DevTools are one click away. - Annotation: pick one element, drag a region, or draw freehand, write a note, and it reaches chat with a screenshot of the visible page with the marks on it. - Toolbar: hard reload, page zoom, device sizes, a light/dark switch that applies to the page rather than the app, and cookie/cache clearing scoped to the panel alone. - Several pages at once, each tab showing the page's own favicon, and an address bar that suggests pages already visited in this project. - Dev servers are listed from what is actually listening on the machine, checked against what a project announced, so a server is offered no matter how it was started. One that is still starting is waited for instead of failing. Remote dev servers The desktop app binds a local port and pipes raw bytes to the OpenChamber host over the existing authenticated connection, so the page keeps its own origin at the root of its own host. The reachable set is exactly what discovery reports and is re-checked per connection, so an authenticated client cannot dial arbitrary local services on the host. Links and redirects to another loopback port stay on the machine that served the page. A tunnel that cannot be opened is reported; it is never replaced by the plain loopback URL, which would answer from the user's own machine under a remote address. Agent control Browser actions are a separate `openchamber_web` tool: open, snapshot, click, type, scroll, inspect computed styles, resize between mobile/tablet/desktop, and capture a screenshot into `.openchamber/screenshots/` in the project. The existing `openchamber` tool keeps sessions, worktrees and scheduled tasks. Each has its own setting in the new Settings -> General -> OpenChamber Tools section, and the plugin is not injected at all when both are off. Capability belongs to the connected client, not to configuration: a client declares on its event stream that it can drive a page, which only a Chromium host does. Exactly one client performs each request — it claims the request before acting, and the first claim wins — because deciding by whose result arrives first would be too late for a click that already happened. No client listening is answered immediately with an explanation rather than a timeout. Runtime boundaries Web tabs get a plain iframe that can display a page but not inspect one. The VS Code extension no longer offers the surface at all, since nothing that makes the panel worth having works there. Mobile is unaffected. Native boundary Camera, microphone, location and device-picker requests from panel pages are denied — Electron grants them by default when no handler is set, and the panel loads whatever address the user types. Page capture, appearance emulation and storage clearing verify that their target belongs to the panel's own session instead of trusting a web-contents id from the renderer. Persisted state Stored `preview` tabs migrate to `browser` (v13 -> v14). Context panel tab limits are now per surface, so filling one surface no longer evicts another's tabs. Address history is stored per project and per runtime. Documentation `preview.mdx` and `desktop-browser.mdx` rewritten across all locales, the agent tool settings path corrected, new `DOCUMENTATION.md` for the browser-control broker and the dev tunnel, and the `ui-api-decoupling` skill updated where it still described the deleted proxy.
This commit is contained in:
committed by
GitHub
parent
50613bb170
commit
a5aa32446d
@@ -0,0 +1,57 @@
|
||||
# Dev Server Tunnel
|
||||
|
||||
## Purpose
|
||||
|
||||
This module carries raw TCP bytes between a desktop client and a dev server
|
||||
running on the OpenChamber host, so a remote dev server can be opened in the
|
||||
browser panel without anything being rewritten.
|
||||
|
||||
The page is served from a real origin at the root of its own host. That is the
|
||||
whole design: absolute URLs resolve, cookies scope correctly, HMR sockets
|
||||
connect, and developer tools behave as they do locally. No HTML, header, or
|
||||
URL is inspected or modified, which is what the previous rewriting proxy did
|
||||
and what made it fragile per framework.
|
||||
|
||||
## Boundaries
|
||||
|
||||
- `runtime.js` is the host end: it accepts the WebSocket upgrade at
|
||||
`/api/dev-tunnel`, authenticates it, opens a TCP socket to the requested
|
||||
local port, and pipes the two together.
|
||||
- `client.js` is the local end: it binds a loopback listener on the user's
|
||||
machine and pipes each accepted connection through one WebSocket. It lives in
|
||||
this package because it needs a WebSocket client the package already depends
|
||||
on; the desktop shell drives it over IPC.
|
||||
- Port discovery is not owned here. `runtime.js` is given the reachable set by
|
||||
the same dev-server discovery the user's own list is built from.
|
||||
- The browser panel decides when to tunnel; this module never chooses a target.
|
||||
`packages/ui/src/lib/browser/devTunnel.ts` owns that decision, including for
|
||||
navigations the page starts itself: a tunnelled page that sends the view to
|
||||
another loopback port means a port on the host, not on the user's machine.
|
||||
|
||||
## Invariants
|
||||
|
||||
- The reachable set is exactly what dev-server discovery offers the user, never
|
||||
"any loopback port". Without that restriction an authenticated client could
|
||||
dial arbitrary local services on the host — databases, admin panels, the
|
||||
OpenCode API — through this socket.
|
||||
- Authentication depends on whether the caller is a browser, and this is
|
||||
deliberate rather than a relaxation:
|
||||
- With an `Origin` header the request came from a browser context, and the
|
||||
usual origin allowlist applies unchanged. That check is a CSRF defence: a
|
||||
hostile page can make a browser open a WebSocket carrying ambient cookies,
|
||||
and the origin is what exposes it.
|
||||
- With no `Origin` the request must carry client-token auth. A browser cannot
|
||||
reach this path — the WebSocket API always sends an origin and never lets a
|
||||
page set an `Authorization` header — so this case is the desktop shell.
|
||||
- Concurrency is capped per host, not per page, because one page load opens
|
||||
many sockets.
|
||||
- A connection that cannot be established fails the socket rather than holding
|
||||
it open; a stalled connect is bounded by an explicit timeout, and so is the
|
||||
WebSocket handshake. While it is pending the local socket is paused and its
|
||||
buffered bytes are capped, so a local process writing into a stalled
|
||||
handshake cannot grow the desktop app's memory.
|
||||
- A tunnel that cannot be opened is reported to the panel, never replaced by the
|
||||
plain loopback URL. On a remote instance that substitution would change which
|
||||
machine answers and show local content under a remote address.
|
||||
- Closing either end closes the other. A half-open pipe would leave the page
|
||||
waiting on bytes that will never arrive.
|
||||
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Local end of the dev-server tunnel.
|
||||
*
|
||||
* Binds a loopback listener on this machine and pipes every connection to a
|
||||
* dev server on the OpenChamber host. The point of binding a real local port —
|
||||
* rather than serving the remote page under a path on some other origin — is
|
||||
* that the page then has its own origin at the root of its own host. Absolute
|
||||
* URLs resolve, cookies scope correctly, HMR sockets connect, and nothing has
|
||||
* to be rewritten.
|
||||
*
|
||||
* Lives in the web package because it needs a WebSocket client, which this
|
||||
* package already depends on; the desktop shell drives it over IPC.
|
||||
*/
|
||||
import net from 'node:net';
|
||||
import { WebSocket } from 'ws';
|
||||
|
||||
/**
|
||||
* What one connection may buffer while its WebSocket is still connecting.
|
||||
*
|
||||
* Enough for a request with generous headers, far short of a body worth
|
||||
* holding: a local process could otherwise keep writing into a stalled
|
||||
* handshake and grow the desktop app's memory without limit.
|
||||
*/
|
||||
const MAX_PENDING_BYTES = 256 * 1024;
|
||||
/** A handshake that has not completed by now is not going to. */
|
||||
const HANDSHAKE_TIMEOUT_MS = 15_000;
|
||||
|
||||
const toWebSocketUrl = (baseUrl, port) => {
|
||||
const parsed = new URL('/api/dev-tunnel', baseUrl);
|
||||
parsed.protocol = parsed.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
parsed.searchParams.set('port', String(port));
|
||||
return parsed.toString();
|
||||
};
|
||||
|
||||
export const createDevTunnelClient = ({
|
||||
logger = console,
|
||||
handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS,
|
||||
maxPendingBytes = MAX_PENDING_BYTES,
|
||||
} = {}) => {
|
||||
/** Keyed by `${baseUrl}|${remotePort}` so repeat opens reuse one listener. */
|
||||
const tunnels = new Map();
|
||||
|
||||
const closeTunnel = (key) => {
|
||||
const tunnel = tunnels.get(key);
|
||||
if (!tunnel) return false;
|
||||
tunnels.delete(key);
|
||||
for (const socket of tunnel.sockets) {
|
||||
try { socket.destroy(); } catch { /* already gone */ }
|
||||
}
|
||||
try { tunnel.server.close(); } catch { /* already closing */ }
|
||||
return true;
|
||||
};
|
||||
|
||||
return {
|
||||
/**
|
||||
* Opens (or reuses) a tunnel and resolves with the local port to browse.
|
||||
* Rejects if the listener cannot bind; per-connection failures close only
|
||||
* that connection, so one failed request cannot take the tunnel down.
|
||||
*/
|
||||
async open({ baseUrl, port, headers = {} }) {
|
||||
const remotePort = Number.parseInt(String(port), 10);
|
||||
if (!Number.isInteger(remotePort) || remotePort <= 0 || remotePort > 65535) {
|
||||
throw new Error('A valid remote port is required');
|
||||
}
|
||||
const base = String(baseUrl || '').trim();
|
||||
if (!base) throw new Error('A remote base URL is required');
|
||||
|
||||
const key = `${base}|${remotePort}`;
|
||||
const existing = tunnels.get(key);
|
||||
if (existing) return { localPort: existing.localPort, reused: true };
|
||||
|
||||
const target = toWebSocketUrl(base, remotePort);
|
||||
const sockets = new Set();
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
socket.setNoDelay(true);
|
||||
sockets.add(socket);
|
||||
|
||||
const upstream = new WebSocket(target, { headers, perMessageDeflate: false });
|
||||
upstream.binaryType = 'nodebuffer';
|
||||
let pendingWrites = [];
|
||||
let pendingBytes = 0;
|
||||
|
||||
const handshakeTimer = setTimeout(() => {
|
||||
logger.warn?.(`[dev-tunnel] handshake timed out for port ${remotePort}`);
|
||||
teardown();
|
||||
}, handshakeTimeoutMs);
|
||||
|
||||
function teardown() {
|
||||
clearTimeout(handshakeTimer);
|
||||
pendingWrites = [];
|
||||
pendingBytes = 0;
|
||||
sockets.delete(socket);
|
||||
try { socket.destroy(); } catch { /* already gone */ }
|
||||
try { upstream.close(); } catch { /* already closing */ }
|
||||
}
|
||||
|
||||
upstream.on('open', () => {
|
||||
clearTimeout(handshakeTimer);
|
||||
for (const chunk of pendingWrites) upstream.send(chunk);
|
||||
pendingWrites = [];
|
||||
pendingBytes = 0;
|
||||
// The local end was held back while there was nowhere to put its
|
||||
// bytes; there is somewhere now.
|
||||
socket.resume();
|
||||
});
|
||||
upstream.on('message', (data) => {
|
||||
if (socket.destroyed) return;
|
||||
socket.write(data);
|
||||
});
|
||||
upstream.on('error', (error) => {
|
||||
logger.warn?.(`[dev-tunnel] upstream failed for port ${remotePort}: ${error?.message || error}`);
|
||||
teardown();
|
||||
});
|
||||
upstream.on('close', teardown);
|
||||
|
||||
socket.on('data', (chunk) => {
|
||||
// Bytes can arrive before the WebSocket handshake completes; buffering
|
||||
// them is what keeps the first HTTP request intact. The buffer is
|
||||
// bounded, and the local end is paused rather than trusted to stop.
|
||||
if (upstream.readyState === WebSocket.OPEN) {
|
||||
upstream.send(chunk);
|
||||
return;
|
||||
}
|
||||
if (upstream.readyState !== WebSocket.CONNECTING) return;
|
||||
|
||||
pendingWrites.push(chunk);
|
||||
pendingBytes += chunk.length;
|
||||
if (pendingBytes > maxPendingBytes) {
|
||||
logger.warn?.(`[dev-tunnel] dropped a connection that buffered too much for port ${remotePort}`);
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
socket.pause();
|
||||
});
|
||||
socket.on('error', teardown);
|
||||
socket.on('close', teardown);
|
||||
});
|
||||
|
||||
const localPort = await new Promise((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
server.off('error', reject);
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') {
|
||||
reject(new Error('Failed to bind a local tunnel port'));
|
||||
return;
|
||||
}
|
||||
resolve(address.port);
|
||||
});
|
||||
});
|
||||
|
||||
server.on('error', (error) => {
|
||||
logger.warn?.(`[dev-tunnel] listener error for port ${remotePort}: ${error?.message || error}`);
|
||||
});
|
||||
|
||||
tunnels.set(key, { server, sockets, localPort, remotePort, baseUrl: base });
|
||||
return { localPort, reused: false };
|
||||
},
|
||||
|
||||
close({ baseUrl, port }) {
|
||||
return closeTunnel(`${String(baseUrl || '').trim()}|${Number.parseInt(String(port), 10)}`);
|
||||
},
|
||||
|
||||
/** Closes every tunnel; used when the desktop switches runtime or quits. */
|
||||
closeAll() {
|
||||
for (const key of [...tunnels.keys()]) closeTunnel(key);
|
||||
},
|
||||
|
||||
list() {
|
||||
return [...tunnels.values()].map(({ localPort, remotePort, baseUrl }) => ({ localPort, remotePort, baseUrl }));
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* Raw byte tunnel to a dev server running on the OpenChamber host.
|
||||
*
|
||||
* This is what lets a desktop client preview a dev server that lives on another
|
||||
* machine without rewriting anything. The client binds its own local port and
|
||||
* pipes it here; the page is then served from a real origin at the root of its
|
||||
* own host, so absolute URLs, cookies, HMR sockets, and DevTools all behave
|
||||
* exactly as they do locally. No HTML is inspected or modified.
|
||||
*
|
||||
* Security posture: the reachable set is the same list dev-server discovery
|
||||
* offers the user, not "any loopback port". Without that restriction an
|
||||
* authenticated client could dial arbitrary local services on the host —
|
||||
* databases, admin panels, the OpenCode API — through this socket.
|
||||
*
|
||||
* Authentication differs from the browser-facing sockets on purpose. Those
|
||||
* demand an allowed `Origin`, which is a CSRF defence: a hostile page can make
|
||||
* a browser open a WebSocket carrying the user's ambient cookies, and the
|
||||
* origin is what exposes it. This tunnel's client is the desktop shell, not a
|
||||
* browser, and it authenticates with an explicit bearer token. So:
|
||||
*
|
||||
* - With an `Origin` header, the request came from a browser context and the
|
||||
* usual origin check applies unchanged.
|
||||
* - With no `Origin`, the request must carry client-token auth. A browser
|
||||
* cannot reach this path: the WebSocket API always sends an origin and never
|
||||
* lets a page set an `Authorization` header.
|
||||
*/
|
||||
import net from 'node:net';
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
const DEV_TUNNEL_WS_PATH = '/api/dev-tunnel';
|
||||
/** One page load opens many sockets; the cap is per host, not per page. */
|
||||
const MAX_CONCURRENT_SOCKETS = 64;
|
||||
const CONNECT_TIMEOUT_MS = 5_000;
|
||||
|
||||
const parseRequestedPort = (url) => {
|
||||
try {
|
||||
const parsed = new URL(String(url || ''), 'http://localhost');
|
||||
if (parsed.pathname !== DEV_TUNNEL_WS_PATH) return null;
|
||||
const port = Number.parseInt(parsed.searchParams.get('port') || '', 10);
|
||||
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const isDevTunnelPath = (url) => {
|
||||
try {
|
||||
return new URL(String(url || ''), 'http://localhost').pathname === DEV_TUNNEL_WS_PATH;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export function createDevTunnelRuntime({
|
||||
server,
|
||||
discoverDevServers,
|
||||
uiAuthController,
|
||||
isRequestOriginAllowed,
|
||||
rejectWebSocketUpgrade,
|
||||
logger = console,
|
||||
}) {
|
||||
const wsServer = new WebSocketServer({ noServer: true });
|
||||
let openSockets = 0;
|
||||
|
||||
/**
|
||||
* A port is reachable only while discovery still reports it. Re-checked on
|
||||
* every upgrade rather than cached, so a dev server that stops listening
|
||||
* stops being reachable.
|
||||
*/
|
||||
const isAllowedPort = async (port) => {
|
||||
const result = await discoverDevServers();
|
||||
if (!result?.ok) return false;
|
||||
return result.servers.some((entry) => entry.port === port);
|
||||
};
|
||||
|
||||
wsServer.on('connection', (socket, req) => {
|
||||
const port = parseRequestedPort(req.url);
|
||||
if (port === null) {
|
||||
socket.close(1008, 'Invalid port');
|
||||
return;
|
||||
}
|
||||
|
||||
openSockets += 1;
|
||||
const upstream = net.connect({ host: '127.0.0.1', port });
|
||||
upstream.setNoDelay(true);
|
||||
|
||||
let settled = false;
|
||||
const teardown = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
openSockets -= 1;
|
||||
try { upstream.destroy(); } catch { /* already gone */ }
|
||||
try { socket.close(); } catch { /* already closing */ }
|
||||
};
|
||||
|
||||
const connectTimer = setTimeout(() => {
|
||||
if (!upstream.connecting) return;
|
||||
logger.warn?.(`[dev-tunnel] timed out connecting to 127.0.0.1:${port}`);
|
||||
teardown();
|
||||
}, CONNECT_TIMEOUT_MS);
|
||||
|
||||
upstream.on('connect', () => clearTimeout(connectTimer));
|
||||
upstream.on('data', (chunk) => {
|
||||
if (socket.readyState !== socket.OPEN) return;
|
||||
socket.send(chunk);
|
||||
// Stop reading from the dev server while the socket drains, otherwise a
|
||||
// fast response against a slow client buffers the whole body in memory.
|
||||
if (socket.bufferedAmount > 1_000_000) {
|
||||
upstream.pause();
|
||||
const resume = () => {
|
||||
if (socket.bufferedAmount > 1_000_000) {
|
||||
setTimeout(resume, 20);
|
||||
return;
|
||||
}
|
||||
upstream.resume();
|
||||
};
|
||||
setTimeout(resume, 20);
|
||||
}
|
||||
});
|
||||
upstream.on('error', () => { clearTimeout(connectTimer); teardown(); });
|
||||
upstream.on('close', () => { clearTimeout(connectTimer); teardown(); });
|
||||
|
||||
socket.on('message', (data) => {
|
||||
if (upstream.destroyed) return;
|
||||
upstream.write(data);
|
||||
});
|
||||
socket.on('close', teardown);
|
||||
socket.on('error', teardown);
|
||||
});
|
||||
|
||||
const upgradeHandler = (req, socket, head) => {
|
||||
if (!isDevTunnelPath(req.url)) return;
|
||||
void (async () => {
|
||||
try {
|
||||
if (uiAuthController?.enabled) {
|
||||
const auth = await uiAuthController.resolveAuthContext(req, null, { allowUrlToken: false });
|
||||
if (!auth) {
|
||||
rejectWebSocketUpgrade(socket, 401, 'UI authentication required');
|
||||
return;
|
||||
}
|
||||
const hasOrigin = typeof req.headers?.origin === 'string' && req.headers.origin.trim() !== '';
|
||||
if (hasOrigin) {
|
||||
if (!await isRequestOriginAllowed(req)) {
|
||||
rejectWebSocketUpgrade(socket, 403, 'Invalid origin');
|
||||
return;
|
||||
}
|
||||
} else if (auth.type !== 'client') {
|
||||
rejectWebSocketUpgrade(socket, 403, 'Client authentication required');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const port = parseRequestedPort(req.url);
|
||||
if (port === null) {
|
||||
rejectWebSocketUpgrade(socket, 400, 'Invalid port');
|
||||
return;
|
||||
}
|
||||
if (openSockets >= MAX_CONCURRENT_SOCKETS) {
|
||||
rejectWebSocketUpgrade(socket, 503, 'Too many tunnel connections');
|
||||
return;
|
||||
}
|
||||
if (!await isAllowedPort(port)) {
|
||||
// Says which port, because the alternative is an empty response in
|
||||
// the panel with nothing anywhere explaining why.
|
||||
logger.warn?.(`[dev-tunnel] refused port ${port}: not reported by dev-server discovery`);
|
||||
rejectWebSocketUpgrade(socket, 403, 'That port is not an available dev server');
|
||||
return;
|
||||
}
|
||||
|
||||
wsServer.handleUpgrade(req, socket, head, (ws) => wsServer.emit('connection', ws, req));
|
||||
} catch {
|
||||
rejectWebSocketUpgrade(socket, 500, 'Upgrade failed');
|
||||
}
|
||||
})();
|
||||
};
|
||||
|
||||
server.on('upgrade', upgradeHandler);
|
||||
|
||||
return {
|
||||
path: DEV_TUNNEL_WS_PATH,
|
||||
get openSocketCount() {
|
||||
return openSockets;
|
||||
},
|
||||
dispose() {
|
||||
server.off('upgrade', upgradeHandler);
|
||||
wsServer.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
|
||||
import { createDevTunnelClient } from './client.js';
|
||||
import { createDevTunnelRuntime, isDevTunnelPath } from './runtime.js';
|
||||
|
||||
/**
|
||||
* These exercise the real socket path end to end: a dev server, an OpenChamber
|
||||
* host tunnelling to it, and a client binding a local port. Anything less would
|
||||
* not prove the thing that matters — that a page loads over the tunnel exactly
|
||||
* as it does locally.
|
||||
*/
|
||||
|
||||
const started = [];
|
||||
|
||||
const listen = (server, host = '127.0.0.1') => new Promise((resolve) => {
|
||||
server.listen(0, host, () => resolve(server.address().port));
|
||||
});
|
||||
|
||||
const trackSockets = (server) => {
|
||||
const sockets = new Set();
|
||||
server.on('connection', (socket) => {
|
||||
sockets.add(socket);
|
||||
socket.on('close', () => sockets.delete(socket));
|
||||
});
|
||||
return sockets;
|
||||
};
|
||||
|
||||
const stopServer = (server, sockets) => async () => {
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
};
|
||||
|
||||
const startDevServer = async (handler) => {
|
||||
const server = http.createServer(handler);
|
||||
const sockets = trackSockets(server);
|
||||
const port = await listen(server);
|
||||
started.push(stopServer(server, sockets));
|
||||
return port;
|
||||
};
|
||||
|
||||
const startHost = async ({ allowedPorts, auth = null, discoveryOk = true }) => {
|
||||
const server = http.createServer((_req, res) => res.end('host'));
|
||||
const sockets = trackSockets(server);
|
||||
const port = await listen(server);
|
||||
const runtime = createDevTunnelRuntime({
|
||||
server,
|
||||
discoverDevServers: async () => (discoveryOk
|
||||
? {
|
||||
ok: true,
|
||||
servers: allowedPorts.map((value) => ({ port: value, url: `http://localhost:${value}/`, command: 'node', pid: 1 })),
|
||||
}
|
||||
: { ok: false, reason: 'no-listener-source' }),
|
||||
uiAuthController: auth ?? { enabled: false },
|
||||
isRequestOriginAllowed: async (req) => req.headers.origin === 'http://allowed.example',
|
||||
rejectWebSocketUpgrade: (socket, status, message) => {
|
||||
socket.write(`HTTP/1.1 ${status} ${message}\r\n\r\n`);
|
||||
socket.destroy();
|
||||
},
|
||||
logger: { warn: () => {} },
|
||||
});
|
||||
started.push(async () => {
|
||||
runtime.dispose();
|
||||
await stopServer(server, sockets)();
|
||||
});
|
||||
return { port, baseUrl: `http://127.0.0.1:${port}`, runtime, sockets };
|
||||
};
|
||||
|
||||
const httpGet = (port, path = '/') => new Promise((resolve, reject) => {
|
||||
const request = http.get({ host: '127.0.0.1', port, path }, (response) => {
|
||||
let body = '';
|
||||
response.on('data', (chunk) => { body += chunk; });
|
||||
response.on('end', () => resolve({ status: response.statusCode, body, headers: response.headers }));
|
||||
});
|
||||
request.on('error', reject);
|
||||
request.setTimeout(5_000, () => request.destroy(new Error('timeout')));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
while (started.length) {
|
||||
const stop = started.pop();
|
||||
await stop();
|
||||
}
|
||||
});
|
||||
|
||||
describe('dev tunnel path matching', () => {
|
||||
test('only claims its own upgrade path', () => {
|
||||
expect(isDevTunnelPath('/api/dev-tunnel?port=5173')).toBe(true);
|
||||
expect(isDevTunnelPath('/api/terminal/ws')).toBe(false);
|
||||
expect(isDevTunnelPath('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dev tunnel end to end', () => {
|
||||
test('serves the dev server through a local port, unmodified', async () => {
|
||||
const devPort = await startDevServer((req, res) => {
|
||||
res.setHeader('content-type', 'text/html');
|
||||
res.setHeader('x-dev-header', 'kept');
|
||||
res.end(`<html><body>path:${req.url}</body></html>`);
|
||||
});
|
||||
const host = await startHost({ allowedPorts: [devPort] });
|
||||
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
started.push(() => client.closeAll());
|
||||
const { localPort } = await client.open({ baseUrl: host.baseUrl, port: devPort });
|
||||
|
||||
const response = await httpGet(localPort, '/some/page?q=1');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toBe('<html><body>path:/some/page?q=1</body></html>');
|
||||
expect(response.headers['x-dev-header']).toBe('kept');
|
||||
});
|
||||
|
||||
test('drops a connection that floods a handshake that never completes', async () => {
|
||||
// A host that accepts the TCP connection and then says nothing: the
|
||||
// WebSocket handshake hangs, which is when buffering could run away.
|
||||
const stalled = net.createServer(() => {});
|
||||
const stalledSockets = trackSockets(stalled);
|
||||
const stalledPort = await listen(stalled);
|
||||
started.push(stopServer(stalled, stalledSockets));
|
||||
|
||||
const client = createDevTunnelClient({
|
||||
logger: { warn: () => {} },
|
||||
handshakeTimeoutMs: 300,
|
||||
});
|
||||
started.push(() => client.closeAll());
|
||||
const { localPort } = await client.open({ baseUrl: `http://127.0.0.1:${stalledPort}`, port: 4321 });
|
||||
|
||||
const closed = await new Promise((resolve) => {
|
||||
const socket = net.createConnection({ port: localPort, host: '127.0.0.1' }, () => {
|
||||
const chunk = Buffer.alloc(64 * 1024, 0x61);
|
||||
const write = () => {
|
||||
// Keep writing while the handshake hangs; the tunnel must stop this
|
||||
// rather than hold every byte in the desktop app's memory.
|
||||
if (socket.destroyed) return;
|
||||
socket.write(chunk, () => setTimeout(write, 1));
|
||||
};
|
||||
write();
|
||||
});
|
||||
socket.on('close', () => resolve(true));
|
||||
socket.on('error', () => resolve(true));
|
||||
setTimeout(() => resolve(false), 3_000);
|
||||
});
|
||||
|
||||
expect(closed).toBe(true);
|
||||
});
|
||||
|
||||
test('reuses one listener for repeat opens of the same target', async () => {
|
||||
const devPort = await startDevServer((_req, res) => res.end('ok'));
|
||||
const host = await startHost({ allowedPorts: [devPort] });
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
started.push(() => client.closeAll());
|
||||
|
||||
const first = await client.open({ baseUrl: host.baseUrl, port: devPort });
|
||||
const second = await client.open({ baseUrl: host.baseUrl, port: devPort });
|
||||
|
||||
expect(second.localPort).toBe(first.localPort);
|
||||
expect(second.reused).toBe(true);
|
||||
});
|
||||
|
||||
test('refuses a port discovery does not report, so it is not a loopback proxy', async () => {
|
||||
const secret = await startDevServer((_req, res) => res.end('secret service'));
|
||||
const host = await startHost({ allowedPorts: [] });
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
started.push(() => client.closeAll());
|
||||
|
||||
const { localPort } = await client.open({ baseUrl: host.baseUrl, port: secret });
|
||||
await expect(httpGet(localPort, '/')).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('closing a tunnel frees its local port', async () => {
|
||||
const devPort = await startDevServer((_req, res) => res.end('ok'));
|
||||
const host = await startHost({ allowedPorts: [devPort] });
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
|
||||
const { localPort } = await client.open({ baseUrl: host.baseUrl, port: devPort });
|
||||
expect(client.close({ baseUrl: host.baseUrl, port: devPort })).toBe(true);
|
||||
expect(client.list()).toEqual([]);
|
||||
|
||||
// The port is free again: binding it back succeeds.
|
||||
const probe = net.createServer();
|
||||
await new Promise((resolve, reject) => {
|
||||
probe.once('error', reject);
|
||||
probe.listen(localPort, '127.0.0.1', resolve);
|
||||
});
|
||||
await new Promise((resolve) => probe.close(resolve));
|
||||
});
|
||||
|
||||
test('rejects an invalid remote port before binding anything', async () => {
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
await expect(client.open({ baseUrl: 'http://127.0.0.1:1', port: 0 })).rejects.toThrow('valid remote port');
|
||||
await expect(client.open({ baseUrl: '', port: 5173 })).rejects.toThrow('base URL');
|
||||
expect(client.list()).toEqual([]);
|
||||
});
|
||||
|
||||
// Not covered here: recovery after a request the dev server kills mid-flight.
|
||||
// The behaviour is real (each connection tears down independently), but the
|
||||
// abandoned socket makes this harness's teardown unreliable, and a flaky test
|
||||
// is worse than a documented gap. Verify it by hand against a restarting dev
|
||||
// server.
|
||||
});
|
||||
|
||||
/**
|
||||
* The desktop shell dials this from the main process, where there is no browser
|
||||
* and therefore no Origin header. Requiring one — as the browser-facing sockets
|
||||
* rightly do — silently rejected every tunnel and surfaced as an empty response
|
||||
* in the panel, with nothing to connect it back to authentication.
|
||||
*/
|
||||
describe('dev tunnel authentication', () => {
|
||||
const clientAuth = {
|
||||
enabled: true,
|
||||
resolveAuthContext: async (req) => (
|
||||
req.headers.authorization === 'Bearer good' ? { type: 'client' } : null
|
||||
),
|
||||
};
|
||||
const sessionAuth = {
|
||||
enabled: true,
|
||||
resolveAuthContext: async () => ({ type: 'session' }),
|
||||
};
|
||||
|
||||
test('accepts a bearer-authenticated client that sends no origin', async () => {
|
||||
const devPort = await startDevServer((_req, res) => res.end('ok'));
|
||||
const host = await startHost({ allowedPorts: [devPort], auth: clientAuth });
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
started.push(() => client.closeAll());
|
||||
|
||||
const { localPort } = await client.open({
|
||||
baseUrl: host.baseUrl,
|
||||
port: devPort,
|
||||
headers: { Authorization: 'Bearer good' },
|
||||
});
|
||||
expect((await httpGet(localPort, '/')).body).toBe('ok');
|
||||
});
|
||||
|
||||
test('rejects a client with no credentials', async () => {
|
||||
const devPort = await startDevServer((_req, res) => res.end('ok'));
|
||||
const host = await startHost({ allowedPorts: [devPort], auth: clientAuth });
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
started.push(() => client.closeAll());
|
||||
|
||||
const { localPort } = await client.open({ baseUrl: host.baseUrl, port: devPort });
|
||||
await expect(httpGet(localPort, '/')).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('still refuses a session-authenticated request that sends no origin', async () => {
|
||||
// Only an explicit bearer may skip the origin check; ambient session
|
||||
// credentials are exactly what the origin check exists to protect.
|
||||
const devPort = await startDevServer((_req, res) => res.end('ok'));
|
||||
const host = await startHost({ allowedPorts: [devPort], auth: sessionAuth });
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
started.push(() => client.closeAll());
|
||||
|
||||
const { localPort } = await client.open({ baseUrl: host.baseUrl, port: devPort });
|
||||
await expect(httpGet(localPort, '/')).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('rejects a disallowed origin even with valid credentials', async () => {
|
||||
const devPort = await startDevServer((_req, res) => res.end('ok'));
|
||||
const host = await startHost({ allowedPorts: [devPort], auth: clientAuth });
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
started.push(() => client.closeAll());
|
||||
|
||||
const { localPort } = await client.open({
|
||||
baseUrl: host.baseUrl,
|
||||
port: devPort,
|
||||
headers: { Authorization: 'Bearer good', Origin: 'http://evil.example' },
|
||||
});
|
||||
await expect(httpGet(localPort, '/')).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('refuses every port when discovery itself is unavailable', async () => {
|
||||
const devPort = await startDevServer((_req, res) => res.end('ok'));
|
||||
const host = await startHost({ allowedPorts: [devPort], discoveryOk: false });
|
||||
const client = createDevTunnelClient({ logger: { warn: () => {} } });
|
||||
started.push(() => client.closeAll());
|
||||
|
||||
const { localPort } = await client.open({ baseUrl: host.baseUrl, port: devPort });
|
||||
await expect(httpGet(localPort, '/')).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user