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:
1 parent
318276d3b9
commit
695d27cdd7
12 files changed
+545
-39
No files matched your search
@@ -5,6 +5,18 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 0.7.1 浏览器通过服务端 dev tunnel 预览(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 网络 | 不再是手机本机网络:`localhost` / `127.0.0.1` 地址改为在手机本地绑定一个随机端口的 TCP 监听器,每条连接通过 Relay/直连的 WebSocket 连到服务端 `/api/dev-tunnel?port=…&oc_url_token=…`,由服务端连接它自己 loopback 上的 dev server;页面 origin 是本地监听器,绝对路径、Cookie、HMR WebSocket 都按这个 origin 工作 |
|
||||||
|
| dev server 列表 | 从 `/api/dev-servers` 读取服务端发现且返回了网页的项目 dev server(按当前项目目录过滤,过滤掉 adb/模拟器等没有页面的端口);空状态列出标题 / URL / 命令,点击即可预览;也可以手动输入 URL |
|
||||||
|
| 地址栏 | 显示原始 `http://localhost:端口/...`,内部加载本地隧道地址;页面里的同源链接会重写到隧道,跳到另一个 loopback 端口会为新端口开隧道;历史记录保存原始地址 |
|
||||||
|
| 鉴权 | Relay 由 `RelayTransport` 自动 mint `oc_url_token`;直连时客户端 `POST /auth/url-token` 取短期 token 并缓存,WebSocket 同时带 bearer;服务端仍只允许它发现列表里的端口 |
|
||||||
|
| 版本 | **0.7.1(code 701)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 0.7.0 浏览器地址栏菜单与网络说明(分支 `flutter`)
|
## 0.7.0 浏览器地址栏菜单与网络说明(分支 `flutter`)
|
||||||
|
|
||||||
| 项 | 结果 |
|
| 项 | 结果 |
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
|
|||||||
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
|
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
|
||||||
Flutter to compare mobile UI maturity.
|
Flutter to compare mobile UI maturity.
|
||||||
|
|
||||||
Status: 0.7.0 — servers (passwordless / password login, HTTP/HTTPS and
|
Status: 0.7.1 — servers (passwordless / password login, HTTP/HTTPS and
|
||||||
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
|
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
|
||||||
over the OpenChamber private relay with end-to-end encryption; the pairing
|
over the OpenChamber private relay with end-to-end encryption; the pairing
|
||||||
link is pasted or scanned with the camera), session list with search and live
|
link is pasted or scanned with the camera), session list with search and live
|
||||||
|
|||||||
@@ -203,6 +203,27 @@ class Client {
|
|||||||
: path;
|
: 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 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
|
/// the "聊天" group, not a project; the root can be relocated away from the
|
||||||
/// home config directory, so it must come from the server.
|
/// home config directory, so it must come from the server.
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1107,3 +1107,37 @@ class ServerVersions {
|
|||||||
final String openchamber;
|
final String openchamber;
|
||||||
const ServerVersions({this.opencode = '', this.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');
|
||||||
|
}
|
||||||
+6
-1
@@ -645,5 +645,10 @@ const Map<String, String> chineseStrings = {
|
|||||||
'Invalid URL': '无效的网址',
|
'Invalid URL': '无效的网址',
|
||||||
'Could not open the browser: {0}': '无法打开浏览器:{0}',
|
'Could not open the browser: {0}': '无法打开浏览器:{0}',
|
||||||
'No history': '暂无历史记录',
|
'No history': '暂无历史记录',
|
||||||
'The browser runs on this device; for a dev server on the OpenChamber host, enter the host\'s LAN address.': '浏览器在手机本机网络上运行;要预览 OpenChamber 主机上的开发服务器,请输入该主机的局域网地址。',
|
'Dev servers': '开发服务器',
|
||||||
|
'Enter a URL above, or open a dev server found on the OpenChamber host': '在上方输入网址,或打开在 OpenChamber 主机上发现的开发服务器',
|
||||||
|
'Could not list dev servers: {0}': '无法获取开发服务器列表:{0}',
|
||||||
|
'No dev servers found. Start one in the terminal, then refresh.': '没有发现开发服务器。请在终端启动一个,然后刷新。',
|
||||||
|
'Loopback dev servers (localhost) are previewed through the OpenChamber host; other addresses use this device\'s network.': '本机回环地址(localhost)的开发服务器会通过 OpenChamber 主机预览;其他地址使用手机网络。',
|
||||||
|
'Could not open the dev server: {0}': '无法打开开发服务器:{0}',
|
||||||
};
|
};
|
||||||
+232
-33
@@ -1,17 +1,29 @@
|
|||||||
// The right sidebar's web browser: an address bar over an embedded WebView,
|
// The right sidebar's web browser: an address bar over an embedded WebView,
|
||||||
// with history navigation, reload/stop and opening the page in the system
|
// with history navigation, reload/stop and opening the page in the system
|
||||||
// browser. The panel keeps its page while another tab is shown (the tab stack
|
// browser. A loopback URL (the host's dev server) is carried over the
|
||||||
|
// OpenChamber dev tunnel through a local TCP listener, so a dev server running
|
||||||
|
// on the host can be previewed from the phone; other addresses use the phone's
|
||||||
|
// network. The panel keeps its page while another tab is shown (the tab stack
|
||||||
// keeps it alive).
|
// keeps it alive).
|
||||||
|
import 'dart:async';
|
||||||
import 'dart:io' show Platform;
|
import 'dart:io' show Platform;
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:webview_flutter/webview_flutter.dart';
|
import 'package:webview_flutter/webview_flutter.dart';
|
||||||
|
|
||||||
|
import '../api/dev_tunnel.dart';
|
||||||
|
import '../api/models.dart';
|
||||||
import '../l10n.dart';
|
import '../l10n.dart';
|
||||||
|
import '../state.dart';
|
||||||
|
|
||||||
class BrowserPanel extends StatefulWidget {
|
class BrowserPanel extends StatefulWidget {
|
||||||
const BrowserPanel({super.key});
|
final AppState app;
|
||||||
|
|
||||||
|
/// The session/project whose dev servers the empty state lists.
|
||||||
|
final String directory;
|
||||||
|
|
||||||
|
const BrowserPanel({super.key, required this.app, required this.directory});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<BrowserPanel> createState() => _BrowserPanelState();
|
State<BrowserPanel> createState() => _BrowserPanelState();
|
||||||
@@ -19,9 +31,16 @@ class BrowserPanel extends StatefulWidget {
|
|||||||
|
|
||||||
class _BrowserPanelState extends State<BrowserPanel> {
|
class _BrowserPanelState extends State<BrowserPanel> {
|
||||||
static const MethodChannel _channel = MethodChannel('openchamber/browser');
|
static const MethodChannel _channel = MethodChannel('openchamber/browser');
|
||||||
|
|
||||||
final TextEditingController _url = TextEditingController();
|
final TextEditingController _url = TextEditingController();
|
||||||
final List<String> _history = [];
|
final List<String> _history = [];
|
||||||
WebViewController? _web;
|
WebViewController? _web;
|
||||||
|
DevTunnel? _tunnel;
|
||||||
|
int? _tunnelPort;
|
||||||
|
String? _displayOrigin;
|
||||||
|
List<DevServerInfo> _servers = const [];
|
||||||
|
bool _serversLoading = false;
|
||||||
|
String? _serversError;
|
||||||
bool _loading = false;
|
bool _loading = false;
|
||||||
bool _hasPage = false;
|
bool _hasPage = false;
|
||||||
bool _canBack = false;
|
bool _canBack = false;
|
||||||
@@ -46,7 +65,7 @@ class _BrowserPanelState extends State<BrowserPanel> {
|
|||||||
_hasPage = true;
|
_hasPage = true;
|
||||||
_progress = 0;
|
_progress = 0;
|
||||||
_error = null;
|
_error = null;
|
||||||
_setUrl(url);
|
_setUrl(_displayFor(url));
|
||||||
});
|
});
|
||||||
_syncNavigation();
|
_syncNavigation();
|
||||||
},
|
},
|
||||||
@@ -55,9 +74,9 @@ class _BrowserPanelState extends State<BrowserPanel> {
|
|||||||
setState(() {
|
setState(() {
|
||||||
_loading = false;
|
_loading = false;
|
||||||
_progress = 100;
|
_progress = 100;
|
||||||
_setUrl(url);
|
_setUrl(_displayFor(url));
|
||||||
});
|
});
|
||||||
_remember(url);
|
_remember(_displayFor(url));
|
||||||
_syncNavigation();
|
_syncNavigation();
|
||||||
},
|
},
|
||||||
onProgress: (value) {
|
onProgress: (value) {
|
||||||
@@ -65,7 +84,16 @@ class _BrowserPanelState extends State<BrowserPanel> {
|
|||||||
},
|
},
|
||||||
onUrlChange: (change) {
|
onUrlChange: (change) {
|
||||||
final url = change.url;
|
final url = change.url;
|
||||||
if (url != null && mounted) setState(() => _setUrl(url));
|
if (url != null && mounted) setState(() => _setUrl(_displayFor(url)));
|
||||||
|
},
|
||||||
|
onNavigationRequest: (request) {
|
||||||
|
final rewritten = _rewriteNavigation(request.url);
|
||||||
|
if (rewritten == null) return NavigationDecision.prevent;
|
||||||
|
if (rewritten != request.url) {
|
||||||
|
_web?.loadRequest(Uri.parse(rewritten));
|
||||||
|
return NavigationDecision.prevent;
|
||||||
|
}
|
||||||
|
return NavigationDecision.navigate;
|
||||||
},
|
},
|
||||||
onWebResourceError: (error) {
|
onWebResourceError: (error) {
|
||||||
if ((error.isForMainFrame ?? true) && mounted) {
|
if ((error.isForMainFrame ?? true) && mounted) {
|
||||||
@@ -73,14 +101,48 @@ class _BrowserPanelState extends State<BrowserPanel> {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
|
_loadServers();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
unawaited(_tunnel?.close());
|
||||||
_url.dispose();
|
_url.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String _displayFor(String url) {
|
||||||
|
final tunnel = _tunnel;
|
||||||
|
final origin = _displayOrigin;
|
||||||
|
if (tunnel == null || origin == null) return url;
|
||||||
|
return displayUrlFor(url, tunnel.localPort, origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _rewriteNavigation(String url) {
|
||||||
|
final tunnel = _tunnel;
|
||||||
|
final origin = _displayOrigin;
|
||||||
|
if (tunnel == null || origin == null) return url;
|
||||||
|
final local = 'http://127.0.0.1:${tunnel.localPort}';
|
||||||
|
if (url == local || url.startsWith('$local/')) return url;
|
||||||
|
final uri = Uri.tryParse(url);
|
||||||
|
if (uri == null) return url;
|
||||||
|
final originOfUrl =
|
||||||
|
'${uri.scheme}://${uri.host}${uri.hasPort ? ':${uri.port}' : ''}';
|
||||||
|
if (originOfUrl == origin) {
|
||||||
|
return localTunnelUri(uri, tunnel.localPort).toString();
|
||||||
|
}
|
||||||
|
final port = devServerPort(uri);
|
||||||
|
if (port != null) {
|
||||||
|
if (port == _tunnelPort) {
|
||||||
|
return localTunnelUri(uri, tunnel.localPort).toString();
|
||||||
|
}
|
||||||
|
// A loopback link to another dev port means another server on the host.
|
||||||
|
unawaited(_navigate(url));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _syncNavigation() async {
|
Future<void> _syncNavigation() async {
|
||||||
final web = _web;
|
final web = _web;
|
||||||
if (web == null) return;
|
if (web == null) return;
|
||||||
@@ -109,7 +171,63 @@ class _BrowserPanelState extends State<BrowserPanel> {
|
|||||||
if (_history.length > 20) _history.removeLast();
|
if (_history.length > 20) _history.removeLast();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _navigate(String raw) {
|
Future<void> _loadServers() async {
|
||||||
|
final cl = widget.app.client;
|
||||||
|
if (cl == null) return;
|
||||||
|
setState(() {
|
||||||
|
_serversLoading = true;
|
||||||
|
_serversError = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final list = await cl.devServers(directory: widget.directory);
|
||||||
|
if (!mounted) return;
|
||||||
|
final dir = slashPath(widget.directory);
|
||||||
|
final filtered = [
|
||||||
|
for (final server in list)
|
||||||
|
// A discovered port that answered with a page is a web dev server;
|
||||||
|
// adb/emulator/native ports with no page would only be noise.
|
||||||
|
if (server.title.isNotEmpty &&
|
||||||
|
(server.directory.isEmpty ||
|
||||||
|
slashPath(server.directory) == dir ||
|
||||||
|
isUnderDirectory(server.directory, dir)))
|
||||||
|
server,
|
||||||
|
]..sort((a, b) => a.port.compareTo(b.port));
|
||||||
|
setState(() {
|
||||||
|
_servers = filtered;
|
||||||
|
_serversLoading = false;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_serversError = '$e';
|
||||||
|
_serversLoading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<DevTunnel?> _ensureTunnel(Uri uri) async {
|
||||||
|
final port = devServerPort(uri);
|
||||||
|
if (port == null) {
|
||||||
|
await _tunnel?.close();
|
||||||
|
_tunnel = null;
|
||||||
|
_tunnelPort = null;
|
||||||
|
_displayOrigin = null;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (_tunnel != null && _tunnelPort == port) return _tunnel;
|
||||||
|
await _tunnel?.close();
|
||||||
|
_tunnel = null;
|
||||||
|
_tunnelPort = null;
|
||||||
|
final tunnel = DevTunnel(widget.app, port);
|
||||||
|
await tunnel.start();
|
||||||
|
_tunnel = tunnel;
|
||||||
|
_tunnelPort = port;
|
||||||
|
_displayOrigin =
|
||||||
|
'${uri.scheme}://${uri.host}${uri.hasPort ? ':${uri.port}' : ''}';
|
||||||
|
return tunnel;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _navigate(String raw) async {
|
||||||
var text = raw.trim();
|
var text = raw.trim();
|
||||||
if (text.isEmpty) return;
|
if (text.isEmpty) return;
|
||||||
if (!text.contains('://')) {
|
if (!text.contains('://')) {
|
||||||
@@ -127,7 +245,23 @@ class _BrowserPanelState extends State<BrowserPanel> {
|
|||||||
}
|
}
|
||||||
FocusScope.of(context).unfocus();
|
FocusScope.of(context).unfocus();
|
||||||
_setUrl(text);
|
_setUrl(text);
|
||||||
_web?.loadRequest(uri);
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final tunnel = await _ensureTunnel(uri);
|
||||||
|
if (!mounted) return;
|
||||||
|
final target = tunnel == null ? uri : localTunnelUri(uri, tunnel.localPort);
|
||||||
|
setState(() => _hasPage = true);
|
||||||
|
await _web?.loadRequest(target);
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_loading = false;
|
||||||
|
_error = trArgs('Could not open the dev server: {0}', [e]);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _openExternal() async {
|
Future<void> _openExternal() async {
|
||||||
@@ -257,6 +391,14 @@ class _BrowserPanelState extends State<BrowserPanel> {
|
|||||||
onPressed: _openExternal,
|
onPressed: _openExternal,
|
||||||
child: const AppText('Open in system browser'),
|
child: const AppText('Open in system browser'),
|
||||||
),
|
),
|
||||||
|
MenuItemButton(
|
||||||
|
leadingIcon: const Icon(Icons.dns_outlined, size: 18),
|
||||||
|
onPressed: () {
|
||||||
|
setState(() => _hasPage = false);
|
||||||
|
_loadServers();
|
||||||
|
},
|
||||||
|
child: const AppText('Dev servers'),
|
||||||
|
),
|
||||||
SubmenuButton(
|
SubmenuButton(
|
||||||
leadingIcon: const Icon(Icons.history, size: 18),
|
leadingIcon: const Icon(Icons.history, size: 18),
|
||||||
menuChildren: _history.isEmpty
|
menuChildren: _history.isEmpty
|
||||||
@@ -314,32 +456,89 @@ class _BrowserPanelState extends State<BrowserPanel> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _empty(ThemeData theme) {
|
Widget _empty(ThemeData theme) {
|
||||||
return Center(
|
return SingleChildScrollView(
|
||||||
child: SingleChildScrollView(
|
padding: const EdgeInsets.all(20),
|
||||||
padding: const EdgeInsets.all(24),
|
child: Column(
|
||||||
child: Column(
|
mainAxisSize: MainAxisSize.min,
|
||||||
mainAxisSize: MainAxisSize.min,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
Icon(Icons.public, size: 48, color: theme.hintColor),
|
Icon(Icons.public, size: 40, color: theme.hintColor),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 8),
|
||||||
const AppText(
|
const AppText(
|
||||||
'Web browser',
|
'Web browser',
|
||||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
const AppText(
|
||||||
|
'Enter a URL above, or open a dev server found on the OpenChamber host',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(fontSize: 12),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 14),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
const Expanded(
|
||||||
|
child: AppText(
|
||||||
|
'Dev servers',
|
||||||
|
style: TextStyle(fontSize: 13.5, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.refresh, size: 18),
|
||||||
|
tooltip: tr('Refresh'),
|
||||||
|
onPressed: _serversLoading ? null : _loadServers,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (_serversLoading)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.all(16),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_servers.isNotEmpty)
|
||||||
|
for (final server in _servers)
|
||||||
|
ListTile(
|
||||||
|
dense: true,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(horizontal: 4),
|
||||||
|
leading: Icon(Icons.lan_outlined,
|
||||||
|
size: 20, color: theme.hintColor),
|
||||||
|
title: Text(server.label,
|
||||||
|
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
subtitle: Text(
|
||||||
|
[
|
||||||
|
if (server.url.isNotEmpty) server.url,
|
||||||
|
if (server.command.isNotEmpty) server.command,
|
||||||
|
].join(' · '),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
trailing: const Icon(Icons.chevron_right, size: 18),
|
||||||
|
onTap: () => _navigate(server.url.isEmpty
|
||||||
|
? 'http://localhost:${server.port}'
|
||||||
|
: server.url),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||||
|
child: AppText(
|
||||||
|
_serversError != null
|
||||||
|
? trArgs('Could not list dev servers: {0}', [_serversError!])
|
||||||
|
: 'No dev servers found. Start one in the terminal, then refresh.',
|
||||||
|
style: TextStyle(fontSize: 12, color: theme.hintColor),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 10),
|
||||||
const AppText(
|
const AppText(
|
||||||
'Enter a URL above to start browsing',
|
'Loopback dev servers (localhost) are previewed through the OpenChamber host; other addresses use this device\'s network.',
|
||||||
textAlign: TextAlign.center,
|
style: TextStyle(fontSize: 11.5),
|
||||||
style: TextStyle(fontSize: 12.5),
|
),
|
||||||
),
|
],
|
||||||
const SizedBox(height: 16),
|
|
||||||
AppText(
|
|
||||||
'The browser runs on this device; for a dev server on the OpenChamber host, enter the host\'s LAN address.',
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -510,7 +510,7 @@ class _FilesPanelState extends State<FilesPanel> {
|
|||||||
case 2:
|
case 2:
|
||||||
return TerminalPanel(app: widget.app, directory: _root);
|
return TerminalPanel(app: widget.app, directory: _root);
|
||||||
case 3:
|
case 3:
|
||||||
return const BrowserPanel();
|
return BrowserPanel(app: widget.app, directory: _root);
|
||||||
default:
|
default:
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import 'api/client.dart';
|
|||||||
import 'api/models.dart';
|
import 'api/models.dart';
|
||||||
import 'api/pairing.dart';
|
import 'api/pairing.dart';
|
||||||
import 'api/relay_transport.dart';
|
import 'api/relay_transport.dart';
|
||||||
|
import 'api/transport.dart';
|
||||||
import 'l10n.dart';
|
import 'l10n.dart';
|
||||||
import 'storage.dart';
|
import 'storage.dart';
|
||||||
import 'terminal_state.dart';
|
import 'terminal_state.dart';
|
||||||
@@ -613,6 +614,8 @@ class AppState extends ChangeNotifier {
|
|||||||
archivedLoaded = false;
|
archivedLoaded = false;
|
||||||
_sessionsNext = null;
|
_sessionsNext = null;
|
||||||
perms = [];
|
perms = [];
|
||||||
|
_tunnelUrlToken = '';
|
||||||
|
_tunnelUrlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
|
||||||
error = null;
|
error = null;
|
||||||
_connectionError = false;
|
_connectionError = false;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
@@ -727,6 +730,40 @@ class AppState extends ChangeNotifier {
|
|||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String _tunnelUrlToken = '';
|
||||||
|
DateTime _tunnelUrlTokenExpiresAt =
|
||||||
|
DateTime.fromMillisecondsSinceEpoch(0);
|
||||||
|
|
||||||
|
/// Opens the host's dev-server tunnel for [port] as a raw WebSocket. The
|
||||||
|
/// browser panel pipes a loopback TCP listener through it, so a page served
|
||||||
|
/// by the OpenChamber host's dev server loads on the phone.
|
||||||
|
Future<TransportSocket> openDevTunnel(int port) async {
|
||||||
|
final cl = client;
|
||||||
|
if (cl == null) throw StateError(tr('Not connected to a server'));
|
||||||
|
var query = 'port=$port';
|
||||||
|
// A relay's transport mints its own URL token; a direct socket cannot
|
||||||
|
// carry the bearer in a browser, so mint one here as the web client does.
|
||||||
|
if (conn?.isRelay != true) {
|
||||||
|
final now = DateTime.now();
|
||||||
|
if (_tunnelUrlToken.isEmpty ||
|
||||||
|
!now.isBefore(_tunnelUrlTokenExpiresAt)) {
|
||||||
|
final minted = await cl.mintUrlToken();
|
||||||
|
_tunnelUrlToken = minted.token;
|
||||||
|
_tunnelUrlTokenExpiresAt = now.add(
|
||||||
|
Duration(seconds: minted.expiresIn) - const Duration(seconds: 20));
|
||||||
|
}
|
||||||
|
if (_tunnelUrlToken.isNotEmpty) {
|
||||||
|
query += '&oc_url_token=${Uri.encodeQueryComponent(_tunnelUrlToken)}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cl.transport.webSocket('/api/dev-tunnel',
|
||||||
|
rawQuery: query,
|
||||||
|
headers: {
|
||||||
|
if (cl.token != null && cl.token!.isNotEmpty)
|
||||||
|
'authorization': 'Bearer ${cl.token}',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// Adds a folder to the server's project list, then refreshes the list so
|
/// Adds a folder to the server's project list, then refreshes the list so
|
||||||
/// its settings row decorates it. Returns the resolved project; the caller
|
/// its settings row decorates it. Returns the resolved project; the caller
|
||||||
/// may select it for a new session. Throws when the server refuses the path.
|
/// may select it for a new session. Throws when the server refuses the path.
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@ name: openchamber
|
|||||||
description: "A lightweight OpenChamber client for phones."
|
description: "A lightweight OpenChamber client for phones."
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
version: 0.7.0+700
|
version: 0.7.1+701
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.14.0
|
sdk: ^3.14.0
|
||||||
|
|||||||
@@ -42,8 +42,10 @@ void main() {
|
|||||||
|
|
||||||
testWidgets('the browser tab shows the mobile-only hint on desktop',
|
testWidgets('the browser tab shows the mobile-only hint on desktop',
|
||||||
(tester) async {
|
(tester) async {
|
||||||
await tester.pumpWidget(const MaterialApp(
|
final app = AppState();
|
||||||
home: Scaffold(body: BrowserPanel()),
|
addTearDown(app.dispose);
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(body: BrowserPanel(app: app, directory: '/home/me')),
|
||||||
));
|
));
|
||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/dev_tunnel.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('loopback hosts and ports are recognised', () {
|
||||||
|
for (final host in [
|
||||||
|
'localhost',
|
||||||
|
'127.0.0.1',
|
||||||
|
'::1',
|
||||||
|
'[::1]',
|
||||||
|
'0.0.0.0',
|
||||||
|
'::',
|
||||||
|
]) {
|
||||||
|
expect(isLoopbackDevHost(host), isTrue, reason: host);
|
||||||
|
}
|
||||||
|
expect(isLoopbackDevHost('192.168.1.10'), isFalse);
|
||||||
|
expect(devServerPort(Uri.parse('http://localhost:5173/')), 5173);
|
||||||
|
expect(devServerPort(Uri.parse('http://127.0.0.1')), 80);
|
||||||
|
expect(devServerPort(Uri.parse('https://localhost')), 443);
|
||||||
|
expect(devServerPort(Uri.parse('https://example.com:8443')), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the tunnel keeps path, query and fragment', () {
|
||||||
|
final local = localTunnelUri(
|
||||||
|
Uri.parse('http://localhost:5173/a/b?x=1#top'), 4000);
|
||||||
|
expect(local.toString(), 'http://127.0.0.1:4000/a/b?x=1#top');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the address bar is mapped back to the dev server', () {
|
||||||
|
expect(
|
||||||
|
displayUrlFor('http://127.0.0.1:4000/a', 4000, 'http://localhost:5173'),
|
||||||
|
'http://localhost:5173/a',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
displayUrlFor('http://127.0.0.1:4000', 4000, 'http://localhost:5173'),
|
||||||
|
'http://localhost:5173',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
displayUrlFor('https://example.com/x', 4000, 'http://localhost:5173'),
|
||||||
|
'https://example.com/x',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user