From f8e7c4ab7aa30cdd76e79fd784f50338e4be935f Mon Sep 17 00:00:00 2001 From: leo Date: Thu, 5 Nov 2026 22:32:21 +0800 Subject: [PATCH] feat(browser): Let the extension reach local files, and say when it may not MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chrome shows an extension's "Allow access to file URLs" switch only if it could want file access; ours could not, so the switch never showed, and through the debugger it could neither open a file:// page ("Navigating to local URL is not allowed") nor give a file input its files ("Not allowed"). activeTab makes it one that could, with no install warning. The extension says in its hello whether the switch is on: off, browser_open/navigate of a file and upload tell the agent what the user has to turn on, and Settings → Browser says so too. browser_open takes a local file's path as well. Co-Authored-By: BaoCode --- browser_extension/background.js | 28 +++++++++++++++------- browser_extension/manifest.json | 3 ++- lib/browser/browser_actions.dart | 3 +++ lib/browser/browser_bridge.dart | 12 ++++++++++ lib/browser/browser_tools.dart | 28 ++++++++++++++++++---- lib/l10n/app_en.arb | 2 ++ lib/l10n/app_localizations.dart | 12 ++++++++++ lib/l10n/app_localizations_en.dart | 7 ++++++ lib/l10n/app_localizations_zh.dart | 7 ++++++ lib/l10n/app_zh.arb | 2 ++ lib/settings/pages/browser_page.dart | 6 +++++ test/browser/browser_bridge_live_test.dart | 13 ++++++++++ test/browser/browser_bridge_test.dart | 21 ++++++++++++++++ 13 files changed, 129 insertions(+), 15 deletions(-) diff --git a/browser_extension/background.js b/browser_extension/background.js index 3f0e2d78b..ce3992d4d 100644 --- a/browser_extension/background.js +++ b/browser_extension/background.js @@ -66,15 +66,25 @@ function setConnected(value) { subscribed.clear(); } showState(); - if (value) { - send({ - type: 'hello', - protocol: BRIDGE, - capabilities: CAPABILITIES, - browser: browserName(), - version: chrome.runtime.getManifest().version, - }); - } + if (value) hello(); +} + +async function hello() { + // Whether the user let it reach file:// pages and local files (to open an + // HTML file, to choose files for a page's input): "Allow access to file + // URLs", off till they turn it on, the extension reloaded when they do. + // The browser shows that switch only to an extension that could want it: + // activeTab, in the manifest for that alone, makes this one such. + const fileAccess = await chrome.extension.isAllowedFileSchemeAccess().catch(() => null); + if (!connected) return; + send({ + type: 'hello', + protocol: BRIDGE, + capabilities: CAPABILITIES, + browser: browserName(), + version: chrome.runtime.getManifest().version, + fileAccess, + }); } // The toolbar button's badge and title: recording, connected, or not. diff --git a/browser_extension/manifest.json b/browser_extension/manifest.json index 39d3bc05c..380d3f0dc 100644 --- a/browser_extension/manifest.json +++ b/browser_extension/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 3, "name": "__MSG_name__", - "version": "0.1.0", + "version": "0.2.0", "description": "__MSG_description__", "default_locale": "en", "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw/z7XPTL8VYzRrKO5N7N14kL3MuvHD528smBkU6Odvd3L4/BHTaNmtwhOhEEE1q6DamfoekiwcgQWM2aoH32QAi1La7ZM7MXpFsQYkFQh8G7rbzrX5eronOSiPEeoeiXUNyNgnk4jxSAr0HKc7oiFzKtw7lAEXf83A0dFSbhNrLwRZIAqqA9s1qHNeglbG2j7UBf4C92NpdQXqJzs00MXb2gMh7IWIQwigL61nQtS2ZJKkWMTJJpE6TPiqGYiMEpBSjazUOcNzu28/X03iuPUVNgEzWbKe1DvqIOr7keI2QCnOlC2PkWIx2oNQnBZWgQsvffpdakemj7YC/MTIoyywIDAQAB", @@ -12,6 +12,7 @@ "permissions": [ "nativeMessaging", "debugger", + "activeTab", "tabs", "tabGroups", "alarms" diff --git a/lib/browser/browser_actions.dart b/lib/browser/browser_actions.dart index a85e6412d..0664f7d88 100644 --- a/lib/browser/browser_actions.dart +++ b/lib/browser/browser_actions.dart @@ -371,6 +371,9 @@ Future _upload( for (final file in files) { if (!File(file).existsSync()) throw BrowserError('No file $file.'); } + if (browser.fileAccess == false) { + throw const BrowserError(BrowserConnection.fileAccessHelp); + } final target = _targetOf(step); if (target == null) { throw const BrowserError( diff --git a/lib/browser/browser_bridge.dart b/lib/browser/browser_bridge.dart index 218d16b76..30e3cac0c 100644 --- a/lib/browser/browser_bridge.dart +++ b/lib/browser/browser_bridge.dart @@ -527,6 +527,17 @@ class BrowserConnection { bool can(String capability) => capabilities.contains(capability); + /// Whether the user let the extension reach file:// pages and local files + /// (its "Allow access to file URLs"): null for one from before it said. + bool? fileAccess; + + /// What to tell when [fileAccess] is false: only the user can turn it on. + static const fileAccessHelp = + 'The browser does not let BaoCode\'s extension reach local files. Ask ' + 'the user to open chrome://extensions, click Details on BaoCode and ' + 'turn on "Allow access to file URLs" (then try again; the extension ' + 'reloads).'; + int _lastId = 0; final Map> _pending = {}; final BytesBuilder _buffer = BytesBuilder(copy: false); @@ -679,6 +690,7 @@ class BrowserConnection { case 'hello': browser = message['browser'] as String? ?? 'Browser'; version = message['version'] as String?; + fileAccess = message['fileAccess'] as bool?; protocol = (message['protocol'] as num?)?.toInt() ?? 1; capabilities = { for (final capability in message['capabilities'] as List? ?? []) diff --git a/lib/browser/browser_tools.dart b/lib/browser/browser_tools.dart index 4084fa099..b754f893a 100644 --- a/lib/browser/browser_tools.dart +++ b/lib/browser/browser_tools.dart @@ -236,7 +236,10 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea inputSchema: { 'type': 'object', 'properties': { - 'url': {'type': 'string', 'description': 'The URL to open.'}, + 'url': { + 'type': 'string', + 'description': 'The URL to open, or a local file\'s path.', + }, }, 'required': ['url'], }, @@ -247,7 +250,11 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea await browser.request('tabs.create', {'url': 'about:blank'}) as Map; final tabId = tab['tabId'] as int; await _watch(tabId); - final url = await _reachable(call.cwd, input['url'] as String?); + final url = await _reachable( + browser, + call.cwd, + input['url'] as String?, + ); await _loading( browser, tabId, @@ -280,7 +287,7 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea await _go( browser, tabId, - await _reachable(call.cwd, input['url'] as String?), + await _reachable(browser, call.cwd, input['url'] as String?), input['action'] as String?, ); return _arrived(browser, tabId); @@ -468,10 +475,21 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea /// [url] as this machine's browser reaches it, for an agent working in /// [cwd]: on an SSH host, its loopback's port forwarded here first, and - /// the URL on the port here (see PortForwards.localUrl). - static Future _reachable(String cwd, String? url) async { + /// the URL on the port here (see PortForwards.localUrl). A file here, by + /// its path too, is its file:// URL, if the extension may reach it. + static Future _reachable( + BrowserConnection browser, + String cwd, + String? url, + ) async { final host = RemoteLocation.hostOf(cwd); + if (url != null && host == null && p.isAbsolute(url)) { + url = Uri.file(url).toString(); + } final uri = url == null ? null : Uri.tryParse(url); + if (uri != null && uri.isScheme('file') && browser.fileAccess == false) { + throw const BrowserError(BrowserConnection.fileAccessHelp); + } if (host == null || RemoteLocation.isWsl(host) || uri == null) return url; try { return '${await PortForwards.instance.localUrl(host, uri)}'; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 5557b684e..88ef7dff8 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -7347,6 +7347,8 @@ "@browserSettingsExtensionVersion": {"description": "The version of BaoCode's extension in a connected browser.", "placeholders": {"version": {"type": "String"}}}, "browserSettingsExtensionOld": "The extension is out of date. From the store, it updates automatically, or click Update in chrome://extensions; installed manually, download the zip again, replace the folder's contents and click reload.", "browserSettingsAppOld": "The extension is newer than this BaoCode. Update BaoCode.", + "browserSettingsNoFileAccess": "File access is off", + "browserSettingsNoFileAccessDescription": "Agents can't open local HTML files or upload files. In chrome://extensions, click Details on BaoCode and turn on Allow access to file URLs.", "browserSettingsInstall": "Get the Extension", "browserSettingsStore": "Chrome Web Store", "browserSettingsStoreDescription": "Recommended. Updates automatically; works in Chrome, Edge, Brave, Arc and other Chromium browsers.", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 18e2130fc..6f84c6a8c 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -16693,6 +16693,18 @@ abstract class AppLocalizations { /// **'The extension is newer than this BaoCode. Update BaoCode.'** String get browserSettingsAppOld; + /// No description provided for @browserSettingsNoFileAccess. + /// + /// In en, this message translates to: + /// **'File access is off'** + String get browserSettingsNoFileAccess; + + /// No description provided for @browserSettingsNoFileAccessDescription. + /// + /// In en, this message translates to: + /// **'Agents can\'t open local HTML files or upload files. In chrome://extensions, click Details on BaoCode and turn on Allow access to file URLs.'** + String get browserSettingsNoFileAccessDescription; + /// No description provided for @browserSettingsInstall. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 033c8c385..0aade51ee 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -10238,6 +10238,13 @@ class AppLocalizationsEn extends AppLocalizations { String get browserSettingsAppOld => 'The extension is newer than this BaoCode. Update BaoCode.'; + @override + String get browserSettingsNoFileAccess => 'File access is off'; + + @override + String get browserSettingsNoFileAccessDescription => + 'Agents can\'t open local HTML files or upload files. In chrome://extensions, click Details on BaoCode and turn on Allow access to file URLs.'; + @override String get browserSettingsInstall => 'Get the Extension'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index e984cba03..da0df793b 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -9695,6 +9695,13 @@ class AppLocalizationsZh extends AppLocalizations { @override String get browserSettingsAppOld => '扩展比当前的 BaoCode 新,请更新 BaoCode。'; + @override + String get browserSettingsNoFileAccess => '没有开文件访问权限'; + + @override + String get browserSettingsNoFileAccessDescription => + '打不开本地 HTML,也传不了文件。在 chrome://extensions 里点 BaoCode 的「详细信息」,打开「允许访问文件网址」。'; + @override String get browserSettingsInstall => '安装扩展'; diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index f3c78852a..81e65c15f 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2772,6 +2772,8 @@ "browserSettingsExtensionVersion": "扩展版本 {version}", "browserSettingsExtensionOld": "扩展版本太旧,需要更新。商店版会自动更新,也可以在 chrome://extensions 里点「更新」;手动安装的请重新下载 zip,覆盖原来的文件夹后点刷新。", "browserSettingsAppOld": "扩展比当前的 BaoCode 新,请更新 BaoCode。", + "browserSettingsNoFileAccess": "没有开文件访问权限", + "browserSettingsNoFileAccessDescription": "打不开本地 HTML,也传不了文件。在 chrome://extensions 里点 BaoCode 的「详细信息」,打开「允许访问文件网址」。", "browserSettingsInstall": "安装扩展", "browserSettingsStore": "Chrome 应用商店", "browserSettingsStoreDescription": "推荐。会自动更新,Chrome、Edge、Brave、Arc 等 Chromium 内核的浏览器都能装。", diff --git a/lib/settings/pages/browser_page.dart b/lib/settings/pages/browser_page.dart index 5653bace1..c3ce370d1 100644 --- a/lib/settings/pages/browser_page.dart +++ b/lib/settings/pages/browser_page.dart @@ -222,6 +222,12 @@ class BrowserSettingsPage extends StatelessWidget { l10n.browserSettingsConnected(browser.browser ?? ''), l10n.browserSettingsExtensionVersion(browser.version ?? '?'), ), + for (final browser in browsers) + if (browser.fileAccess == false) + ( + l10n.browserSettingsNoFileAccess, + l10n.browserSettingsNoFileAccessDescription, + ), for (final browser in mismatched) ( l10n.browserSettingsIncompatible(browser.browser ?? ''), diff --git a/test/browser/browser_bridge_live_test.dart b/test/browser/browser_bridge_live_test.dart index 311ff8b15..b499e21be 100644 --- a/test/browser/browser_bridge_live_test.dart +++ b/test/browser/browser_bridge_live_test.dart @@ -170,6 +170,19 @@ void main() { return content; } + // A local HTML file, by its path: the extension let reach files (an + // unpacked one is; from the store, the user turns it on). + expect(bridge.browsers.single.fileAccess, isTrue); + final local = File(p.join(profile.path, 'local.html')) + ..writeAsStringSync('Local

From a file.

'); + final file = await call('browser_open', {'url': local.path}); + expect(file.first['text'], contains('From a file.')); + await call('browser_close', { + 'tabId': int.parse( + RegExp(r'\[(\d+)\]').firstMatch(file.first['text'] as String)![1]!, + ), + }); + final opened = await call('browser_open', {'url': page}); final tabId = int.parse( RegExp(r'\[(\d+)\]').firstMatch(opened.first['text'] as String)![1]!, diff --git a/test/browser/browser_bridge_test.dart b/test/browser/browser_bridge_test.dart index 4abf38f46..216f7f583 100644 --- a/test/browser/browser_bridge_test.dart +++ b/test/browser/browser_bridge_test.dart @@ -126,6 +126,27 @@ void main() { ]); }, skip: Platform.isWindows); + test('an extension not let reach local files is said so', () async { + await bridge.start(); + final host = await connect({ + 'browser': 'Google Chrome', + 'version': '0.2.0', + 'fileAccess': false, + }); + addTearDown(host.destroy); + await until(() => bridge.browsers.isNotEmpty); + expect(bridge.browsers.single.fileAccess, isFalse); + + final l10n = AppLocalizationsEn(); + expect( + BrowserSettingsPage.status(l10n, bridge), + contains(( + l10n.browserSettingsNoFileAccess, + l10n.browserSettingsNoFileAccessDescription, + )), + ); + }, skip: Platform.isWindows); + test('a big answer, in many chunks, is read whole', () async { await bridge.start(); final host = await connect({