feat: preview the host's dev servers through the dev tunnel

- loopback dev-server URLs are no longer opened on the phone's network: the
  panel binds a local 127.0.0.1 TCP listener and pipes each connection over
  an authenticated WebSocket to the host's /api/dev-tunnel, which dials its
  own loopback port; the WebView keeps the original address in the bar while
  the page, absolute URLs, cookies and HMR sockets use the tunneled origin
- the empty state lists /api/dev-servers results for the project (only ports
  that answered with a web page), with title, URL and command; tapping one
  opens it through the tunnel
- relay transports mint oc_url_token themselves; a direct connection mints
  and caches /auth/url-token and also sends the bearer
- a new loopback port opened from a tunnelled page gets its own tunnel
- version 0.7.1+701; tests cover the URL mapping and tunnel helpers
This commit is contained in:
blumia committed 2026-12-04 12:21:09 +08:00
1 parent 318276d3b9
commit 695d27cdd7
12 files changed
+545 -39

No files matched your search

+21
View File
@@ -203,6 +203,27 @@ class Client {
: path;
}
/// The dev servers the host discovered, for the browser panel's preview
/// list. [directory] scopes the discovery to a space's own listener.
Future<List<DevServerInfo>> devServers({String? directory}) async {
final r = await _json('GET', '/api/dev-servers', directory: directory);
return [
for (final e in (r['servers'] as List? ?? []))
if (e is Map<String, dynamic>) DevServerInfo.fromJson(e),
];
}
/// A short-lived token for WebSocket upgrades that cannot carry the bearer
/// header. The dev tunnel appends it as `oc_url_token`.
Future<({String token, int expiresIn})> mintUrlToken() async {
final r = await _json('POST', '/auth/url-token');
final expires = r['expiresIn'];
return (
token: r['token'] as String? ?? '',
expiresIn: expires is num ? expires.toInt() : 240,
);
}
/// The server's home and chats root. Sessions filed under a chats root are
/// the "聊天" group, not a project; the root can be relocated away from the
/// home config directory, so it must come from the server.
+153
View File
@@ -0,0 +1,153 @@
// A loopback TCP listener that carries each accepted connection through the
// OpenChamber host's dev-server tunnel. The WebView loads
// http://127.0.0.1:<localPort>, so a dev server running on the host (its own
// localhost) can be previewed from the phone; the original URL stays in the
// address bar.
import 'dart:async';
import 'dart:io';
import '../state.dart';
import 'transport.dart';
/// True for an address that means "the host running the dev server".
bool isLoopbackDevHost(String host) {
final h = host.trim().toLowerCase();
return h == 'localhost' ||
h == '127.0.0.1' ||
h == '::1' ||
h == '[::1]' ||
h == '0.0.0.0' ||
h == '::';
}
/// The port a dev-server URL names (80/443 when it has none), or null.
int? devServerPort(Uri uri) {
if (!isLoopbackDevHost(uri.host)) return null;
if (uri.hasPort) return uri.port > 0 ? uri.port : null;
return uri.scheme == 'https' ? 443 : 80;
}
/// The URL the WebView loads: the same path on the tunnel's local port.
Uri localTunnelUri(Uri original, int localPort) => original.replace(
scheme: 'http',
host: '127.0.0.1',
port: localPort,
);
/// Maps a URL the WebView reports back to the original host's URL, so the
/// address bar and history show the dev server's address, not the listener's.
String displayUrlFor(String webUrl, int localPort, String displayOrigin) {
final local = 'http://127.0.0.1:$localPort';
if (webUrl == local) return displayOrigin;
if (webUrl.startsWith('$local/')) {
return '$displayOrigin${webUrl.substring(local.length)}';
}
return webUrl;
}
/// A local TCP listener for [remotePort] on the OpenChamber host.
class DevTunnel {
final AppState app;
final int remotePort;
ServerSocket? _server;
final Set<_Pipe> _pipes = {};
bool _closed = false;
DevTunnel(this.app, this.remotePort);
int get localPort => _server?.port ?? 0;
Future<int> start() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
if (_closed) {
await server.close();
return 0;
}
_server = server;
server.listen(_accept);
return server.port;
}
Future<void> _accept(Socket socket) async {
if (_closed) {
socket.destroy();
return;
}
TransportSocket? tunnel;
try {
tunnel = await app.openDevTunnel(remotePort);
} catch (_) {
socket.destroy();
return;
}
if (_closed) {
socket.destroy();
await tunnel.close().catchError((Object _) {});
return;
}
late final _Pipe pipe;
pipe = _Pipe(socket, tunnel, () => _pipes.remove(pipe));
_pipes.add(pipe);
socket.listen(
pipe.toTunnel,
onError: (_) => pipe.close(),
onDone: () => pipe.close(),
);
tunnel.messages.listen(
pipe.toSocket,
onError: (_) => pipe.close(),
onDone: () => pipe.close(),
);
}
Future<void> close() async {
if (_closed) return;
_closed = true;
await _server?.close();
_server = null;
for (final pipe in [..._pipes]) {
await pipe.close();
}
_pipes.clear();
}
}
class _Pipe {
final Socket socket;
final TransportSocket tunnel;
final void Function() onClosed;
bool _closed = false;
_Pipe(this.socket, this.tunnel, this.onClosed);
void toTunnel(List<int> data) {
if (_closed) return;
try {
tunnel.add(data);
} catch (_) {
close();
}
}
void toSocket(List<int> data) {
if (_closed) return;
try {
socket.add(data);
} catch (_) {
close();
}
}
Future<void> close() async {
if (_closed) return;
_closed = true;
try {
socket.destroy();
} catch (_) {}
try {
await tunnel.close();
} catch (_) {}
onClosed();
}
}
+34
View File
@@ -1107,3 +1107,37 @@ class ServerVersions {
final String openchamber;
const ServerVersions({this.opencode = '', this.openchamber = ''});
}
/// A dev server the OpenChamber host discovered (`GET /api/dev-servers`).
/// [url] is the address to preview (usually a loopback URL on the host); the
/// browser tunnels its port through `/api/dev-tunnel`.
class DevServerInfo {
final int port;
final String url;
final String command;
final String directory;
final String title;
const DevServerInfo({
this.port = 0,
this.url = '',
this.command = '',
this.directory = '',
this.title = '',
});
factory DevServerInfo.fromJson(Map<String, dynamic> j) {
final page = j['page'];
return DevServerInfo(
port: (j['port'] as num?)?.toInt() ?? 0,
url: j['url'] as String? ?? '',
command: j['command'] as String? ?? '',
directory: j['directory'] as String? ?? '',
title: page is Map && page['title'] is String
? (page['title'] as String).trim()
: '',
);
}
String get label => title.isNotEmpty ? title : (url.isNotEmpty ? url : ':$port');
}