diff --git a/browser_extension/background.js b/browser_extension/background.js index ce3992d4d..f68a287a1 100644 --- a/browser_extension/background.js +++ b/browser_extension/background.js @@ -76,17 +76,34 @@ async function hello() { // 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); + // The engine, which tells a browser that borrows another's name (Cent + // Browser says Google Chrome): its version is what differs. + const version = await chromiumVersion(); if (!connected) return; send({ type: 'hello', protocol: BRIDGE, capabilities: CAPABILITIES, browser: browserName(), + engine: version ? `Chromium ${version}` : 'Chromium', version: chrome.runtime.getManifest().version, fileAccess, }); } +// The Chromium under the browser: the one in its user agent's full list, +// where it says, else its user agent's Chrome/… +async function chromiumVersion() { + try { + const { fullVersionList } = await navigator.userAgentData.getHighEntropyValues(['fullVersionList']); + const chromium = fullVersionList?.find((b) => b.brand === 'Chromium'); + if (chromium?.version) return chromium.version; + } catch (error) { + // Not there, or not let: the user agent says. + } + return /(?:Chrome|Chromium)\/([\d.]+)/.exec(navigator.userAgent)?.[1] ?? null; +} + // The toolbar button's badge and title: recording, connected, or not. function showState() { chrome.action.setBadgeBackgroundColor({ color: '#c0392b' }); @@ -371,7 +388,14 @@ chrome.tabs.onCreated.addListener(async (tab) => { // --- The tabs shared: the "BaoCode" group's, in any window. async function groups() { - return chrome.tabGroups.query({ title: GROUP }); + try { + return await chrome.tabGroups.query({ title: GROUP }); + } catch (error) { + // No window open: a browser left running in the background. It has no + // group, and a window is made with the first tab asked for (createTab). + if (/No current window/i.test(String(error?.message))) return []; + throw error; + } } async function sharedTabs() { diff --git a/browser_extension/manifest.json b/browser_extension/manifest.json index 380d3f0dc..3bb5a73f6 100644 --- a/browser_extension/manifest.json +++ b/browser_extension/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 3, "name": "__MSG_name__", - "version": "0.2.0", + "version": "0.2.1", "description": "__MSG_description__", "default_locale": "en", "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw/z7XPTL8VYzRrKO5N7N14kL3MuvHD528smBkU6Odvd3L4/BHTaNmtwhOhEEE1q6DamfoekiwcgQWM2aoH32QAi1La7ZM7MXpFsQYkFQh8G7rbzrX5eronOSiPEeoeiXUNyNgnk4jxSAr0HKc7oiFzKtw7lAEXf83A0dFSbhNrLwRZIAqqA9s1qHNeglbG2j7UBf4C92NpdQXqJzs00MXb2gMh7IWIQwigL61nQtS2ZJKkWMTJJpE6TPiqGYiMEpBSjazUOcNzu28/X03iuPUVNgEzWbKe1DvqIOr7keI2QCnOlC2PkWIx2oNQnBZWgQsvffpdakemj7YC/MTIoyywIDAQAB", diff --git a/lib/browser/browser_bridge.dart b/lib/browser/browser_bridge.dart index 30e3cac0c..83ec8beba 100644 --- a/lib/browser/browser_bridge.dart +++ b/lib/browser/browser_bridge.dart @@ -40,6 +40,11 @@ class BrowserBridge extends ChangeNotifier { /// user's browsers, as Settings → Browser turns it on or off. Unset: on. static const settingKey = 'browser.enabled'; + /// settings.json's `browser.preferred`: the browser the agents use, by + /// the path of its executable ([BrowserConnection.executable]). Unset: + /// the last connected. + static const preferredKey = 'browser.preferred'; + /// Sets [enabled] from [read] now and whenever [changes] notifies. void follow(Listenable changes, Object? Function() read) { void update() => enabled = read() != false; @@ -47,6 +52,27 @@ class BrowserBridge extends ChangeNotifier { changes.addListener(update); } + /// Sets [preferred] from [read] now and whenever [changes] notifies. + void followPreferred(Listenable changes, Object? Function() read) { + void update() => preferred = switch (read()) { + final String path when path.trim().isNotEmpty => path.trim(), + _ => null, + }; + update(); + changes.addListener(update); + } + + /// The path of the browser chosen in Settings → Browser; null for none + /// chosen, where the last connected is used. + String? get preferred => _preferred; + String? _preferred; + + set preferred(String? value) { + if (_preferred == value) return; + _preferred = value; + notifyListeners(); + } + /// Where the host finds the app: the same folder for both, the user's /// temporary one ([socketFolder] in a test). static String get socketPath => p.join(_folder, 'baocode-browser.sock'); @@ -154,6 +180,38 @@ class BrowserBridge extends ChangeNotifier { if (connection.browser != null && connection.compatible) connection, ]; + /// The browser the agents use: [preferred]'s while it is connected, the + /// last connected otherwise (none chosen, or the one chosen closed); + /// null when none is. + BrowserConnection? get active { + final browsers = this.browsers; + if (browsers.isEmpty) return null; + if (chosen case final chosen?) return chosen; + return browsers.first; + } + + /// The browser chosen in Settings → Browser ([preferred]), while it is + /// connected. + BrowserConnection? get chosen { + final path = _preferred; + if (path == null) return null; + for (final browser in browsers) { + if (_samePath(browser.executable, path)) return browser; + } + return null; + } + + /// Whether [browser] is the one the agents use now. + bool isActive(BrowserConnection browser) => identical(active, browser); + + /// Whether [a] and [b] name the same executable: the same path, whatever + /// the slashes or the case. + static bool _samePath(String? a, String? b) { + if (a == null || b == null || a.isEmpty || b.isEmpty) return false; + String plain(String path) => path.replaceAll('\\', '/').toLowerCase(); + return plain(a) == plain(b); + } + /// The browsers whose extension is connected but speaks another /// [protocol]: one of them, or BaoCode, has to be updated. List get mismatched => [ @@ -531,6 +589,54 @@ class BrowserConnection { /// (its "Allow access to file URLs"): null for one from before it said. bool? fileAccess; + /// The browser's executable, as its host said: the folder tells a browser + /// that borrows another's name (Cent Browser's extension says Google + /// Chrome). Null for one from before the host said. + String? executable; + + /// The browser's engine and its version, as the extension said: + /// `Chromium 116.0.5845.188` under the browsers here. + String? engine; + + /// The browser's name: its executable's where that says one (Cent + /// Browser's chrome.exe is not Chrome's), the extension's brand + /// otherwise. + String get displayName => _nameOf(executable) ?? browser ?? 'Browser'; + + /// The browsers whose executable says their name, which the extension + /// may not (Cent Browser's, Google Chrome's): a part of the path, and + /// the name. + static const _names = [ + ('centbrowser', 'Cent Browser'), + ('brave', 'Brave'), + ('vivaldi', 'Vivaldi'), + ('microsoft edge', 'Microsoft Edge'), + ('microsoft/edge', 'Microsoft Edge'), + ('msedge', 'Microsoft Edge'), + ('google chrome', 'Google Chrome'), + ('google/chrome', 'Google Chrome'), + ('google-chrome', 'Google Chrome'), + ('chromium', 'Chromium'), + ('arc.app', 'Arc'), + ('opera', 'Opera'), + ('qqbrowser', 'QQ Browser'), + ('360se', '360 Browser'), + ('360chrome', '360 Browser'), + ('sogou', 'Sogou Explorer'), + ('yandex', 'Yandex'), + ('whale', 'Naver Whale'), + ('ucbrowser', 'UC Browser'), + ]; + + static String? _nameOf(String? path) { + if (path == null || path.isEmpty) return null; + final lower = path.replaceAll('\\', '/').toLowerCase(); + for (final (part, name) in _names) { + if (lower.contains(part)) return name; + } + return null; + } + /// 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 ' @@ -681,16 +787,24 @@ class BrowserConnection { } switch (message['type']) { case 'hello' when message['origin'] != null: - // The host's: who started it. + // The host's: who started it, and the browser it runs in. origin = message['origin'] as String?; final allowed = BrowserBridge.extensionIds.any( (id) => origin == 'chrome-extension://$id/', ); if (!allowed) _close(); + if (message['path'] case final String path + when path.trim().isNotEmpty) { + executable = path.trim(); + } case 'hello': browser = message['browser'] as String? ?? 'Browser'; version = message['version'] as String?; fileAccess = message['fileAccess'] as bool?; + if (message['engine'] case final String engine + when engine.trim().isNotEmpty) { + this.engine = engine.trim(); + } protocol = (message['protocol'] as num?)?.toInt() ?? 1; capabilities = { for (final capability in message['capabilities'] as List? ?? []) diff --git a/lib/browser/browser_history.dart b/lib/browser/browser_history.dart index 9d63e56f7..ca709ed5c 100644 --- a/lib/browser/browser_history.dart +++ b/lib/browser/browser_history.dart @@ -662,11 +662,11 @@ final _historyTool = ClaudeSdkTool( } return true; }); - final browsers = BrowserBridge.instance.browsers; + final browser = BrowserBridge.instance.active; BrowserTab? live(Object? tab) { final id = int.tryParse('$tab'); - if (id == null || browsers.isEmpty) return null; - final open = BrowserTab(browsers.first, id); + if (id == null || browser == null) return null; + final open = BrowserTab(browser, id); return BrowserRecords.instance.watching(open) ? open : null; } diff --git a/lib/browser/browser_tools.dart b/lib/browser/browser_tools.dart index ec1d6488a..b1f59a12f 100644 --- a/lib/browser/browser_tools.dart +++ b/lib/browser/browser_tools.dart @@ -149,10 +149,10 @@ abstract final class BrowserTools { } static Future _watch(int tabId) async { - final browsers = BrowserBridge.instance.browsers; - if (browsers.isEmpty) return; + final browser = BrowserBridge.instance.active; + if (browser == null) return; try { - await BrowserRecords.instance.watch(BrowserTab(browsers.first, tabId)); + await BrowserRecords.instance.watch(BrowserTab(browser, tabId)); } on Object { // Not shared, or gone: the tool says so. } @@ -219,11 +219,11 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea final browser = _browser(); final tabs = await browser.request('tabs.list') as List? ?? const []; if (tabs.isEmpty) { - return 'No tab is shared with BaoCode in ${browser.browser}. ' + return 'No tab is shared with BaoCode in ${browser.displayName}. ' 'Open one with browser_open.'; } return [ - '${browser.browser}:', + '${browser.displayName}:', for (final tab in tabs.cast()) _describeTab(tab), ].join('\n'); }, @@ -337,11 +337,12 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea ), ]; - /// The browser to use: the last connected. + /// The browser to use: the one chosen in Settings → Browser, or the last + /// connected when none is (see [BrowserBridge.active]). static BrowserConnection _browser() { final bridge = BrowserBridge.instance; - final browsers = bridge.browsers; - if (browsers.isNotEmpty) return browsers.first; + final browser = bridge.active; + if (browser != null) return browser; if (bridge.otherApp) { throw StateError( 'Another BaoCode is connected to the browser: quit it first.', @@ -350,10 +351,10 @@ Do not use the browser tools to scrape or bulk-collect data from government, hea if (bridge.mismatched case [final browser, ...]) { throw StateError( browser.protocol < BrowserBridge.protocol - ? "BaoCode's extension in ${browser.browser} is too old for " + ? "BaoCode's extension in ${browser.displayName} is too old for " 'this BaoCode: the user needs to update it (Settings → ' 'Browser says how).' - : "BaoCode's extension in ${browser.browser} is newer than " + : "BaoCode's extension in ${browser.displayName} is newer than " 'this BaoCode: the user needs to update BaoCode.', ); } diff --git a/lib/browser/browser_welcome.dart b/lib/browser/browser_welcome.dart index 4f46acbe3..889862bfd 100644 --- a/lib/browser/browser_welcome.dart +++ b/lib/browser/browser_welcome.dart @@ -101,7 +101,7 @@ class _BrowserWelcomeState extends State Widget _build(BuildContext context) { final l10n = context.l10n; final bridge = widget.bridge; - final connected = bridge.browsers.firstOrNull; + final connected = bridge.active; final lines = [ ( const Icon(Codicons.lock, size: 15), @@ -122,7 +122,7 @@ class _BrowserWelcomeState extends State final String title; final String text; if (connected != null) { - title = l10n.browserWelcomeConnected(connected.browser ?? ''); + title = l10n.browserWelcomeConnected(connected.displayName); text = l10n.browserWelcomeTry; } else if (!bridge.enabled) { title = l10n.browserWelcomeInstallTitle; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b7ba25503..261df310c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -7367,6 +7367,7 @@ "browserSettingsEnabled": "Let Agents Use the Browser", "browserSettingsEnabledDescription": "When off, agents have no browser tools and the extension disconnects.", "browserSettingsStatus": "Status", + "browserSettingsStatusDescription": "Agents use the browser marked In Use; choose another to switch.", "browserSettingsNotInstalled": "No browser has connected yet", "browserSettingsNotInstalledDescription": "Install the extension either way below, then open the browser: it connects automatically.", "browserSettingsNotRunning": "No browser connected", @@ -7379,6 +7380,11 @@ "@browserSettingsIncompatible": {"description": "A browser connected whose extension BaoCode cannot use: one too old, or newer than the app.", "placeholders": {"browser": {"type": "String"}}}, "browserSettingsExtensionVersion": "Extension {version}", "@browserSettingsExtensionVersion": {"description": "The version of BaoCode's extension in a connected browser.", "placeholders": {"version": {"type": "String"}}}, + "browserSettingsUse": "Use This Browser", + "browserSettingsUsing": "In Use", + "browserSettingsChosenMissing": "The browser chosen is not connected", + "browserSettingsChosenMissingDescription": "{path}: agents use {browser} until it connects again.", + "@browserSettingsChosenMissingDescription": {"description": "Under browserSettingsChosenMissing: the chosen browser's executable, and the connected one used meanwhile.", "placeholders": {"path": {"type": "String"}, "browser": {"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", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index fe039c6c0..2f4993261 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -16747,6 +16747,12 @@ abstract class AppLocalizations { /// **'Status'** String get browserSettingsStatus; + /// No description provided for @browserSettingsStatusDescription. + /// + /// In en, this message translates to: + /// **'Agents use the browser marked In Use; choose another to switch.'** + String get browserSettingsStatusDescription; + /// No description provided for @browserSettingsNotInstalled. /// /// In en, this message translates to: @@ -16801,6 +16807,30 @@ abstract class AppLocalizations { /// **'Extension {version}'** String browserSettingsExtensionVersion(String version); + /// No description provided for @browserSettingsUse. + /// + /// In en, this message translates to: + /// **'Use This Browser'** + String get browserSettingsUse; + + /// No description provided for @browserSettingsUsing. + /// + /// In en, this message translates to: + /// **'In Use'** + String get browserSettingsUsing; + + /// No description provided for @browserSettingsChosenMissing. + /// + /// In en, this message translates to: + /// **'The browser chosen is not connected'** + String get browserSettingsChosenMissing; + + /// Under browserSettingsChosenMissing: the chosen browser's executable, and the connected one used meanwhile. + /// + /// In en, this message translates to: + /// **'{path}: agents use {browser} until it connects again.'** + String browserSettingsChosenMissingDescription(String path, String browser); + /// No description provided for @browserSettingsExtensionOld. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 6ccb7e026..40b2fb0b1 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -10267,6 +10267,10 @@ class AppLocalizationsEn extends AppLocalizations { @override String get browserSettingsStatus => 'Status'; + @override + String get browserSettingsStatusDescription => + 'Agents use the browser marked In Use; choose another to switch.'; + @override String get browserSettingsNotInstalled => 'No browser has connected yet'; @@ -10304,6 +10308,21 @@ class AppLocalizationsEn extends AppLocalizations { return 'Extension $version'; } + @override + String get browserSettingsUse => 'Use This Browser'; + + @override + String get browserSettingsUsing => 'In Use'; + + @override + String get browserSettingsChosenMissing => + 'The browser chosen is not connected'; + + @override + String browserSettingsChosenMissingDescription(String path, String browser) { + return '$path: agents use $browser until it connects again.'; + } + @override String get 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.'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 8a8290bca..3ccb5627d 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -9717,6 +9717,10 @@ class AppLocalizationsZh extends AppLocalizations { @override String get browserSettingsStatus => '状态'; + @override + String get browserSettingsStatusDescription => + 'agent 使用标着「使用中」的浏览器;选另一个即可切换。'; + @override String get browserSettingsNotInstalled => '还没有浏览器连接过'; @@ -9753,6 +9757,20 @@ class AppLocalizationsZh extends AppLocalizations { return '扩展版本 $version'; } + @override + String get browserSettingsUse => '使用这个浏览器'; + + @override + String get browserSettingsUsing => '使用中'; + + @override + String get browserSettingsChosenMissing => '所选的浏览器没有连接'; + + @override + String browserSettingsChosenMissingDescription(String path, String browser) { + return '$path:它重新连上之前,agent 先用 $browser。'; + } + @override String get browserSettingsExtensionOld => '扩展版本太旧,需要更新。商店版会自动更新,也可以在 chrome://extensions 里点「更新」;手动安装的请重新下载 zip,覆盖原来的文件夹后点刷新。'; diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 4702f8d24..22f50794e 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2781,6 +2781,7 @@ "browserSettingsEnabled": "允许 agent 使用浏览器", "browserSettingsEnabledDescription": "关闭后 agent 不再有浏览器工具,扩展也会断开连接。", "browserSettingsStatus": "状态", + "browserSettingsStatusDescription": "agent 使用标着「使用中」的浏览器;选另一个即可切换。", "browserSettingsNotInstalled": "还没有浏览器连接过", "browserSettingsNotInstalledDescription": "用下方任一方式安装扩展,之后打开浏览器就会自动连接。", "browserSettingsNotRunning": "浏览器未连接", @@ -2790,6 +2791,10 @@ "browserSettingsConnected": "{browser} 已连接", "browserSettingsIncompatible": "{browser} 的扩展版本不匹配", "browserSettingsExtensionVersion": "扩展版本 {version}", + "browserSettingsUse": "使用这个浏览器", + "browserSettingsUsing": "使用中", + "browserSettingsChosenMissing": "所选的浏览器没有连接", + "browserSettingsChosenMissingDescription": "{path}:它重新连上之前,agent 先用 {browser}。", "browserSettingsExtensionOld": "扩展版本太旧,需要更新。商店版会自动更新,也可以在 chrome://extensions 里点「更新」;手动安装的请重新下载 zip,覆盖原来的文件夹后点刷新。", "browserSettingsAppOld": "扩展比当前的 BaoCode 新,请更新 BaoCode。", "browserSettingsNoFileAccess": "没有开文件访问权限", diff --git a/lib/main.dart b/lib/main.dart index 2e0a755a6..7ecf289dd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -627,11 +627,14 @@ void followSettingsFiles(SettingsFiles files) { files.settings, () => files.settings[SidebarTimes.settingKey], ); - // Settings → Browser: whether the agents may use the user's browsers. - BrowserBridge.instance.follow( - files.settings, - () => files.settings[BrowserBridge.settingKey], - ); + // Settings → Browser: whether the agents may use the user's browsers, + // and which one they use. + BrowserBridge.instance + ..follow(files.settings, () => files.settings[BrowserBridge.settingKey]) + ..followPreferred( + files.settings, + () => files.settings[BrowserBridge.preferredKey], + ); // Settings → Browser: whether the history keeps bodies and steps too. BrowserHistory.instance.follow( files.settings, diff --git a/lib/settings/pages/browser_page.dart b/lib/settings/pages/browser_page.dart index c3ce370d1..73cfbb0de 100644 --- a/lib/settings/pages/browser_page.dart +++ b/lib/settings/pages/browser_page.dart @@ -82,6 +82,23 @@ class BrowserSettingsPage extends StatelessWidget { ); } + /// Has the agents use [browser] from now on, and keeps that in + /// settings.json ([BrowserBridge.preferredKey]). + void _use(BrowserConnection browser) { + final path = browser.executable; + if (path == null) return; + bridge.preferred = path; + final settings = this.settings; + if (settings == null) return; + unawaited( + settings.update(BrowserBridge.preferredKey, path).catchError(( + Object error, + ) { + debugPrint('${BrowserBridge.preferredKey} not kept: $error'); + }), + ); + } + @override Widget build(BuildContext context) => ListenableBuilder( listenable: Listenable.merge([bridge, kept]), @@ -113,9 +130,27 @@ class BrowserSettingsPage extends StatelessWidget { if (bridge.enabled) SettingsGroup( title: l10n.browserSettingsStatus, + description: l10n.browserSettingsStatusDescription, children: [ - for (final (label, description) in status(l10n, bridge)) - SettingsRow(label: label, description: description), + for (final (label, description, browser) in status( + l10n, + bridge, + )) + SettingsRow( + label: label, + description: description, + trailing: browser == null || browser.executable == null + ? null + : IdeButton( + label: bridge.isActive(browser) + ? l10n.browserSettingsUsing + : l10n.browserSettingsUse, + secondary: true, + onPressed: bridge.isActive(browser) + ? null + : () => _use(browser), + ), + ), ], ), if (bridge.enabled) @@ -188,14 +223,15 @@ class BrowserSettingsPage extends StatelessWidget { ); } - /// What the status group says, a row each: the browsers connected and + /// What the status group says, a row each: the browsers connected (each + /// with which it is, to choose it), the one chosen but not connected, /// those whose extension speaks another protocol, or why there is none. @visibleForTesting - static List<(String, String?)> status( + static List<(String, String?, BrowserConnection?)> status( AppLocalizations l10n, BrowserBridge bridge, ) { - if (bridge.otherApp) return [(l10n.browserOtherApp, null)]; + if (bridge.otherApp) return [(l10n.browserOtherApp, null, null)]; final browsers = bridge.browsers; final mismatched = bridge.mismatched; if (browsers.isEmpty && mismatched.isEmpty) { @@ -204,39 +240,64 @@ class BrowserSettingsPage extends StatelessWidget { ? ( l10n.browserSettingsNotRunning, l10n.browserSettingsNotRunningDescription, + null, ) : ( l10n.browserSettingsNotInstalled, l10n.browserSettingsNotInstalledDescription, + null, ), if (bridge.sandboxedBrowsers) ( l10n.browserSettingsSandboxed, l10n.browserSettingsSandboxedDescription, + null, ), ]; } return [ for (final browser in browsers) ( - l10n.browserSettingsConnected(browser.browser ?? ''), - l10n.browserSettingsExtensionVersion(browser.version ?? '?'), + l10n.browserSettingsConnected(browser.displayName), + _details(browser, l10n), + browser, + ), + if (bridge.preferred case final path? + when bridge.chosen == null && bridge.active != null) + ( + l10n.browserSettingsChosenMissing, + l10n.browserSettingsChosenMissingDescription( + path, + bridge.active!.displayName, + ), + null, ), for (final browser in browsers) if (browser.fileAccess == false) ( l10n.browserSettingsNoFileAccess, - l10n.browserSettingsNoFileAccessDescription, + '${browser.displayName}: ' + '${l10n.browserSettingsNoFileAccessDescription}', + null, ), for (final browser in mismatched) ( - l10n.browserSettingsIncompatible(browser.browser ?? ''), + l10n.browserSettingsIncompatible(browser.displayName), browser.protocol < BrowserBridge.protocol ? l10n.browserSettingsExtensionOld : l10n.browserSettingsAppOld, + null, ), ]; } + + /// A connected browser's row under its name: its engine, its executable + /// and its extension's version, ` · ` between. + static String _details(BrowserConnection browser, AppLocalizations l10n) => [ + ?browser.engine, + ?browser.executable, + l10n.browserSettingsExtensionVersion(browser.version ?? '?'), + ].join(' · '); } /// Said above every settings page while the debugging history is over diff --git a/macos/BrowserBridge/build_host.sh b/macos/BrowserBridge/build_host.sh index 1753efd16..3b72c2e5f 100755 --- a/macos/BrowserBridge/build_host.sh +++ b/macos/BrowserBridge/build_host.sh @@ -7,7 +7,7 @@ out="$TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH/baocode-browser-host" arch_flags="" for arch in $ARCHS; do arch_flags="$arch_flags -arch $arch"; done xcrun clang -O2 -Wall -Wextra $arch_flags \ - -mmacosx-version-min="$MACOSX_DEPLOYMENT_TARGET" -o "$out" "$src" + -mmacosx-version-min="$MACOSX_DEPLOYMENT_TARGET" -o "$out" "$src" -lproc identity="${EXPANDED_CODE_SIGN_IDENTITY:--}" options="" if [ "$ENABLE_HARDENED_RUNTIME" = "YES" ]; then options="--options runtime"; fi diff --git a/macos/BrowserBridge/host.c b/macos/BrowserBridge/host.c index 422c5de66..1d5714d52 100644 --- a/macos/BrowserBridge/host.c +++ b/macos/BrowserBridge/host.c @@ -30,6 +30,10 @@ #include #include +#ifdef __APPLE__ +#include +#endif + #define MAX_MESSAGE (64 * 1024 * 1024) static pthread_mutex_t out_lock = PTHREAD_MUTEX_INITIALIZER; @@ -92,6 +96,36 @@ static void tell_browser(int connected) { to_browser(text, (uint32_t)strlen(text)); } +// The browser's executable, as the process that started this one runs it: +// the path says which browser it is (a fork's chrome is not Chrome's). "" +// when it is not to be had. +static void browser_path(char* buffer, size_t size) { + buffer[0] = '\0'; +#ifdef __APPLE__ + if (proc_pidpath(getppid(), buffer, (uint32_t)size) <= 0) buffer[0] = '\0'; +#else + char link[64]; + snprintf(link, sizeof link, "/proc/%d/exe", (int)getppid()); + const ssize_t n = readlink(link, buffer, size - 1); + if (n <= 0) { + buffer[0] = '\0'; + return; + } + buffer[n] = '\0'; +#endif +} + +// [text] as it goes in JSON: its quotes and backslashes escaped (a path +// has no control characters in it). +static void escape_json(const char* text, char* out, size_t size) { + size_t j = 0; + for (const char* p = text; *p && j + 3 < size; p++) { + if (*p == '"' || *p == '\\') out[j++] = '\\'; + out[j++] = *p; + } + out[j] = '\0'; +} + // As BrowserBridge.socketPath finds it. static int socket_path(char* path, size_t size) { const char* dir = NULL; @@ -151,10 +185,16 @@ static void* from_bao(void* unused) { sleep(1); continue; } - // Who it is: the extension's origin, as the browser gave it. - char hello[512]; + // Who it is: the extension's origin, as the browser gave it; and the + // browser's own executable, which tells one from another. + char path[1024]; + char escaped[2048]; + browser_path(path, sizeof path); + escape_json(path, escaped, sizeof escaped); + char hello[4096]; int n = snprintf(hello, sizeof hello, - "{\"type\":\"hello\",\"origin\":\"%s\"}", origin); + "{\"type\":\"hello\",\"origin\":\"%s\",\"path\":\"%s\"}", + origin, escaped); if (n <= 0 || n >= (int)sizeof hello || write_message(fd, hello, (uint32_t)n) != 0) { close(fd); diff --git a/test/browser/browser_bridge_test.dart b/test/browser/browser_bridge_test.dart index 216f7f583..44cda3220 100644 --- a/test/browser/browser_bridge_test.dart +++ b/test/browser/browser_bridge_test.dart @@ -54,7 +54,11 @@ void main() { /// origin, then the extension's. Over loopback, as host.cpp is: at the /// port the bridge's file says, the token in its hello ([token] instead, /// when given). - Future connect(Map hello, {String? token}) async { + Future connect( + Map hello, { + String? token, + String? path, + }) async { final Socket socket; String? said; if (BrowserBridge.loopback) { @@ -78,6 +82,7 @@ void main() { send(socket, { 'type': 'hello', 'origin': 'chrome-extension://${BrowserBridge.extensionIds.first}/', + 'path': ?path, 'token': ?said, }); send(socket, {'type': 'hello', ...hello}); @@ -118,10 +123,12 @@ void main() { ( l10n.browserSettingsConnected('Google Chrome'), l10n.browserSettingsExtensionVersion('0.1.0'), + bridge.browsers.single, ), ( l10n.browserSettingsIncompatible('Microsoft Edge'), l10n.browserSettingsAppOld, + null, ), ]); }, skip: Platform.isWindows); @@ -142,11 +149,78 @@ void main() { BrowserSettingsPage.status(l10n, bridge), contains(( l10n.browserSettingsNoFileAccess, - l10n.browserSettingsNoFileAccessDescription, + 'Google Chrome: ${l10n.browserSettingsNoFileAccessDescription}', + null, )), ); }, skip: Platform.isWindows); + test( + 'a browser says which it is, and the one chosen is the one used', + () async { + addTearDown(() => bridge.preferred = null); + await bridge.start(); + const chromePath = + r'C:\Program Files\Google\Chrome\Application\chrome.exe'; + const centPath = r'E:\soft_ware\cent\CentBrowser\Application\chrome.exe'; + final chrome = await connect({ + 'browser': 'Google Chrome', + 'version': '0.2.1', + 'engine': 'Chromium 157.0.8103.52', + }, path: chromePath); + addTearDown(chrome.destroy); + final cent = await connect({ + 'browser': 'Google Chrome', + 'version': '0.2.1', + 'engine': 'Chromium 116.0.5845.188', + }, path: centPath); + addTearDown(cent.destroy); + await until(() => bridge.browsers.length == 2); + + // The path says which browser a borrowed name hides: Cent Browser's + // extension says Google Chrome too. + final byPath = { + for (final browser in bridge.browsers) browser.executable: browser, + }; + expect(byPath[chromePath]?.displayName, 'Google Chrome'); + expect(byPath[centPath]?.displayName, 'Cent Browser'); + expect(byPath[centPath]?.engine, 'Chromium 116.0.5845.188'); + + // None chosen: the last connected, as before. + expect(bridge.active, bridge.browsers.first); + + // Chosen: that one, while it is connected. + bridge.preferred = centPath; + expect(bridge.active, byPath[centPath]); + expect(bridge.isActive(byPath[centPath]!), isTrue); + expect(bridge.isActive(byPath[chromePath]!), isFalse); + + // The same path, whatever the slashes or the case. + bridge.preferred = + r'e:/SOFT_ware/CENT/CentBrowser/Application/chrome.exe'; + expect(bridge.active, byPath[centPath]); + + // Chosen but not connected: the last connected meantime, and the + // settings say so. + bridge.preferred = r'C:\nowhere\chrome.exe'; + expect(bridge.chosen, isNull); + expect(bridge.active, bridge.browsers.first); + final l10n = AppLocalizationsEn(); + expect( + BrowserSettingsPage.status(l10n, bridge), + contains(( + l10n.browserSettingsChosenMissing, + l10n.browserSettingsChosenMissingDescription( + r'C:\nowhere\chrome.exe', + bridge.browsers.first.displayName, + ), + null, + )), + ); + }, + skip: Platform.isWindows, + ); + test('a big answer, in many chunks, is read whole', () async { await bridge.start(); final host = await connect({ @@ -189,6 +263,7 @@ void main() { final sandboxed = ( l10n.browserSettingsSandboxed, l10n.browserSettingsSandboxedDescription, + null, ); expect(bridge.sandboxedBrowsers, isFalse); expect( diff --git a/windows/BrowserBridge/CMakeLists.txt b/windows/BrowserBridge/CMakeLists.txt index 5a847d675..6f193b4df 100644 --- a/windows/BrowserBridge/CMakeLists.txt +++ b/windows/BrowserBridge/CMakeLists.txt @@ -9,5 +9,5 @@ add_executable(baocode-browser-host "host.cpp") apply_standard_settings(baocode-browser-host) target_compile_options(baocode-browser-host PRIVATE /utf-8) target_compile_definitions(baocode-browser-host PRIVATE - "NOMINMAX" "WIN32_LEAN_AND_MEAN") + "NOMINMAX" "WIN32_LEAN_AND_MEAN" "_WIN32_WINNT=0x0600") target_link_libraries(baocode-browser-host PRIVATE "ws2_32.lib") diff --git a/windows/BrowserBridge/host.cpp b/windows/BrowserBridge/host.cpp index d05264d96..31864d2a0 100644 --- a/windows/BrowserBridge/host.cpp +++ b/windows/BrowserBridge/host.cpp @@ -20,11 +20,13 @@ #include #include #include +#include #include #include #include #include +#include #define MAX_MESSAGE (64 * 1024 * 1024) @@ -112,6 +114,67 @@ static void tell_browser(bool connected) { to_browser(text, static_cast(strlen(text))); } +// The parent of [pid], as the processes' snapshot has it; 0 when none. +static DWORD parent_of(HANDLE snapshot, DWORD pid) { + PROCESSENTRY32 entry = {}; + entry.dwSize = sizeof entry; + for (BOOL found = Process32First(snapshot, &entry); found; + found = Process32Next(snapshot, &entry)) { + if (entry.th32ProcessID == pid) return entry.th32ParentProcessID; + } + return 0; +} + +// [pid]'s executable, in [wide] (a path), [length] its characters. +static bool image_path(DWORD pid, wchar_t* wide, DWORD* length) { + HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!process) return false; + const BOOL ok = QueryFullProcessImageNameW(process, 0, wide, length); + CloseHandle(process); + return ok != FALSE && *length > 0; +} + +// The browser's executable, as the process that started this one runs it: +// the folder says which browser it is (a fork's chrome.exe is not +// Chrome's). Windows starts the host through cmd.exe, whose parent is the +// browser: the chain is walked up to it. "" when it is not to be had. +static void browser_path(char* buffer, size_t size) { + buffer[0] = 0; + HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (snapshot == INVALID_HANDLE_VALUE) return; + DWORD pid = GetCurrentProcessId(); + wchar_t wide[1024]; + for (int up = 0; up < 4; up++) { + pid = parent_of(snapshot, pid); + if (pid == 0) break; + DWORD length = static_cast(sizeof wide / sizeof wide[0]); + if (!image_path(pid, wide, &length)) break; + const wchar_t* name = wcsrchr(wide, L'\\'); + name = name ? name + 1 : wide; + if (_wcsicmp(name, L"cmd.exe") == 0 || + _wcsicmp(name, L"conhost.exe") == 0) { + continue; + } + const int n = WideCharToMultiByte(CP_UTF8, 0, wide, static_cast(length), + buffer, static_cast(size - 1), + nullptr, nullptr); + if (n > 0) buffer[n] = 0; + break; + } + CloseHandle(snapshot); +} + +// [text] as it goes in JSON: its quotes and backslashes escaped (a path +// has no control characters in it). +static void escape_json(const char* text, char* out, size_t size) { + size_t j = 0; + for (const char* p = text; *p && j + 3 < size; p++) { + if (*p == '"' || *p == '\\') out[j++] = '\\'; + out[j++] = *p; + } + out[j] = 0; +} + // BaoCode's port and token, from its file: false while there is none // (BaoCode is not running) or it is not whole yet. static bool find_bao(unsigned* port, char* token, size_t size) { @@ -173,13 +236,18 @@ static DWORD WINAPI from_bao(void*) { Sleep(1000); continue; } - // Who it is: the extension's origin, as the browser gave it, and the - // token, which says the host is one the user started. - char hello[640]; + // Who it is: the extension's origin, as the browser gave it; the + // token, which says the host is one the user started; and the + // browser's own executable, which tells one from another. + char path[1024]; + char escaped[2048]; + browser_path(path, sizeof path); + escape_json(path, escaped, sizeof escaped); + char hello[4096]; const int n = snprintf(hello, sizeof hello, "{\"type\":\"hello\",\"origin\":\"%s\"," - "\"token\":\"%s\"}", - origin, token); + "\"token\":\"%s\",\"path\":\"%s\"}", + origin, token, escaped); if (n <= 0 || n >= static_cast(sizeof hello) || !send_message(fd, hello, static_cast(n))) { closesocket(fd);