browserpilot-cdp 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
 
7
7
  // ../protocol/dist/constants.js
8
- var BROWSERPILOT_VERSION = "1.2.0";
8
+ var BROWSERPILOT_VERSION = "1.2.1";
9
9
  var DEFAULT_DAEMON_HOST = "127.0.0.1";
10
10
  var DEFAULT_DAEMON_PORT = 19888;
11
11
  var NATIVE_HOST_NAME = "com.browserpilot.bridge";
@@ -29,6 +29,23 @@ var BLOCKED_PROFILE_WIDE_CDP_COMMANDS = /* @__PURE__ */ new Set([
29
29
  "Network.clearBrowserCookies",
30
30
  "Network.clearBrowserCache"
31
31
  ]);
32
+ var RESTRICTED_URL_PREFIXES = [
33
+ "chrome://",
34
+ "chrome-extension://",
35
+ "chrome-untrusted://",
36
+ "devtools://",
37
+ "edge://",
38
+ "brave://",
39
+ "about:blank#blocked",
40
+ "https://chrome.google.com/webstore",
41
+ "https://chromewebstore.google.com"
42
+ ];
43
+ function isRestrictedUrl(url) {
44
+ if (!url)
45
+ return false;
46
+ const lower = url.toLowerCase();
47
+ return RESTRICTED_URL_PREFIXES.some((prefix) => lower.startsWith(prefix));
48
+ }
32
49
  function isBlockedProfileWideCommand(method) {
33
50
  return BLOCKED_PROFILE_WIDE_CDP_COMMANDS.has(method);
34
51
  }
@@ -4698,6 +4715,9 @@ var SessionManager = class {
4698
4715
  getTransport() {
4699
4716
  return this.transport;
4700
4717
  }
4718
+ getAttachedTabCount() {
4719
+ return this.tabs.size;
4720
+ }
4701
4721
  async getOrAttachTab(tabId, options) {
4702
4722
  await this.transport.attachTab(tabId, options);
4703
4723
  let tab = this.tabs.get(tabId);
@@ -4751,7 +4771,8 @@ var SessionManager = class {
4751
4771
  session.activeTabId = void 0;
4752
4772
  }
4753
4773
  const allTabs = await this.listTabs();
4754
- const candidate = allTabs.find((t) => t.active && !t.url.startsWith("chrome://")) ?? allTabs.find((t) => !t.url.startsWith("chrome://"));
4774
+ const attachable = allTabs.filter((t) => !isRestrictedUrl(t.url));
4775
+ const candidate = attachable.find((t) => t.active && /^https?:\/\//i.test(t.url)) ?? attachable.find((t) => t.active) ?? attachable.find((t) => /^https?:\/\//i.test(t.url)) ?? attachable[0];
4755
4776
  if (candidate) {
4756
4777
  const tab = await this.getOrAttachTab(candidate.tabId, groupOpts);
4757
4778
  if (session)
@@ -4994,6 +5015,16 @@ ${code}
4994
5015
  function textResult(text, meta) {
4995
5016
  return { content: [{ type: "text", text }], meta };
4996
5017
  }
5018
+ function normalizeNavigationUrl(raw) {
5019
+ const trimmed = (raw ?? "").trim();
5020
+ if (!trimmed) return "about:blank";
5021
+ if (/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(trimmed)) {
5022
+ return `http://${trimmed}`;
5023
+ }
5024
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) return trimmed;
5025
+ if (/^(about|data|file|javascript|mailto|blob|view-source):/i.test(trimmed)) return trimmed;
5026
+ return `https://${trimmed}`;
5027
+ }
4997
5028
  function formatFeedbackSuffix(fb) {
4998
5029
  const parts = [`URL: ${fb.url}`];
4999
5030
  if (fb.newConsoleErrors.length > 0) {
@@ -5721,15 +5752,23 @@ async function executeTool(ctx, name, args = {}) {
5721
5752
  return textResult(formatted || "(no tabs open)", { tabs });
5722
5753
  }
5723
5754
  case "browser_open_tab": {
5755
+ const targetUrl = normalizeNavigationUrl(args.url);
5724
5756
  const tab = await manager.openTab({
5725
- url: args.url,
5757
+ url: targetUrl,
5726
5758
  active: args.active,
5727
5759
  tabGroup: args.tabGroup,
5728
5760
  tabGroupColor: args.tabGroupColor
5729
5761
  });
5730
5762
  if (sessionId) manager.getOrCreateSession(sessionId).activeTabId = tab.tabId;
5731
- const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: String(args.url ?? "about:blank"), title: "" }));
5732
- return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}`, { tabId: tab.tabId, ...meta });
5763
+ if (/^https?:\/\//i.test(targetUrl)) {
5764
+ await waitForPageLoad(tab.session, { timeoutMs: 6e3, idleMs: 200 }).catch(() => {
5765
+ });
5766
+ }
5767
+ const meta = await tab.page.getUrlAndTitle().catch(() => ({ url: targetUrl, title: "" }));
5768
+ return textResult(`Opened and attached tab [${tab.tabId}]: ${meta.url}${meta.title ? ` ("${meta.title}")` : ""}`, {
5769
+ tabId: tab.tabId,
5770
+ ...meta
5771
+ });
5733
5772
  }
5734
5773
  case "browser_close_tab": {
5735
5774
  await manager.closeTab(Number(args.tabId));
@@ -5752,8 +5791,9 @@ async function executeTool(ctx, name, args = {}) {
5752
5791
  }
5753
5792
  case "browser_navigate": {
5754
5793
  const tab = await resolveTab();
5794
+ const targetUrl = normalizeNavigationUrl(String(args.url));
5755
5795
  const { result, feedback } = await tab.runWithFeedback(
5756
- () => tab.page.navigate(String(args.url), {
5796
+ () => tab.page.navigate(targetUrl, {
5757
5797
  waitUntil: args.waitUntil ?? "domcontentloaded",
5758
5798
  timeoutMs: args.timeoutMs
5759
5799
  })
@@ -6517,6 +6557,15 @@ var BrowserPilotDaemon = class {
6517
6557
  };
6518
6558
  this.backends.set(clientId, { info, transport, manager });
6519
6559
  this.primaryClientId = clientId;
6560
+ if (ws.readyState === ws.OPEN) {
6561
+ ws.send(
6562
+ JSON.stringify({
6563
+ type: "event",
6564
+ event: "bridge.ready",
6565
+ params: { version: BROWSERPILOT_VERSION, clientId }
6566
+ })
6567
+ );
6568
+ }
6520
6569
  ws.on("close", () => {
6521
6570
  manager.dispose();
6522
6571
  this.backends.delete(clientId);
@@ -6559,7 +6608,10 @@ var BrowserPilotDaemon = class {
6559
6608
  return info;
6560
6609
  }
6561
6610
  listClients() {
6562
- return Array.from(this.backends.values()).map((b) => b.info);
6611
+ return Array.from(this.backends.values()).map((b) => ({
6612
+ ...b.info,
6613
+ attachedTabCount: b.manager.getAttachedTabCount()
6614
+ }));
6563
6615
  }
6564
6616
  getManager(clientId) {
6565
6617
  const targetId = clientId ?? this.primaryClientId;
@@ -6592,6 +6644,7 @@ var BrowserPilotDaemon = class {
6592
6644
  this.sendJson(res, 200, {
6593
6645
  ok: true,
6594
6646
  version: BROWSERPILOT_VERSION,
6647
+ pid: process.pid,
6595
6648
  uptimeMs: Date.now() - this.startedAt,
6596
6649
  clients: this.listClients()
6597
6650
  });
@@ -6805,14 +6858,27 @@ async function startMcpServer(options = {}) {
6805
6858
  };
6806
6859
  result = await executeTool(ctx, name, args);
6807
6860
  } else {
6808
- if (!daemonClient) {
6809
- daemonClient = await DaemonClient.connectOrStart({
6810
- host: options.daemonHost,
6811
- port: options.daemonPort,
6812
- token: options.daemonToken
6813
- });
6861
+ const ensureDaemon = async () => {
6862
+ if (!daemonClient) {
6863
+ daemonClient = await DaemonClient.connectOrStart({
6864
+ host: options.daemonHost,
6865
+ port: options.daemonPort,
6866
+ token: options.daemonToken
6867
+ });
6868
+ }
6869
+ return daemonClient;
6870
+ };
6871
+ try {
6872
+ result = await (await ensureDaemon()).callTool(name, args);
6873
+ } catch (err) {
6874
+ const msg = err instanceof Error ? err.message : String(err);
6875
+ if (/fetch failed|ECONNREFUSED|ECONNRESET|socket|Unauthorized/i.test(msg)) {
6876
+ daemonClient = null;
6877
+ result = await (await ensureDaemon()).callTool(name, args);
6878
+ } else {
6879
+ throw err;
6880
+ }
6814
6881
  }
6815
- result = await daemonClient.callTool(name, args);
6816
6882
  }
6817
6883
  return {
6818
6884
  isError: result.isError,
@@ -6829,6 +6895,7 @@ async function startMcpServer(options = {}) {
6829
6895
  }
6830
6896
 
6831
6897
  // src/native-install.ts
6898
+ import crypto3 from "node:crypto";
6832
6899
  import fs5 from "node:fs/promises";
6833
6900
  import os4 from "node:os";
6834
6901
  import path6 from "node:path";
@@ -6839,31 +6906,178 @@ function getNativeMessagingHostDirs(platform = process.platform) {
6839
6906
  if (platform === "darwin") {
6840
6907
  const appSupport = path6.join(home, "Library", "Application Support");
6841
6908
  return [
6842
- { name: "Google Chrome", dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts") },
6843
- { name: "Google Chrome Canary", dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts") },
6844
- { name: "Google Chrome for Testing", dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts") },
6845
- { name: "Chromium", dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts") },
6846
- { name: "Brave", dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts") },
6847
- { name: "Microsoft Edge", dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts") },
6848
- { name: "Arc", dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts") }
6909
+ {
6910
+ name: "Google Chrome",
6911
+ userDataDir: path6.join(appSupport, "Google", "Chrome"),
6912
+ dir: path6.join(appSupport, "Google", "Chrome", "NativeMessagingHosts")
6913
+ },
6914
+ {
6915
+ name: "Google Chrome Canary",
6916
+ userDataDir: path6.join(appSupport, "Google", "Chrome Canary"),
6917
+ dir: path6.join(appSupport, "Google", "Chrome Canary", "NativeMessagingHosts")
6918
+ },
6919
+ {
6920
+ name: "Google Chrome for Testing",
6921
+ userDataDir: path6.join(appSupport, "Google", "Chrome for Testing"),
6922
+ dir: path6.join(appSupport, "Google", "Chrome for Testing", "NativeMessagingHosts")
6923
+ },
6924
+ {
6925
+ name: "Chromium",
6926
+ userDataDir: path6.join(appSupport, "Chromium"),
6927
+ dir: path6.join(appSupport, "Chromium", "NativeMessagingHosts")
6928
+ },
6929
+ {
6930
+ name: "Brave",
6931
+ userDataDir: path6.join(appSupport, "BraveSoftware", "Brave-Browser"),
6932
+ dir: path6.join(appSupport, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6933
+ },
6934
+ {
6935
+ name: "Microsoft Edge",
6936
+ userDataDir: path6.join(appSupport, "Microsoft Edge"),
6937
+ dir: path6.join(appSupport, "Microsoft Edge", "NativeMessagingHosts")
6938
+ },
6939
+ {
6940
+ name: "Arc",
6941
+ userDataDir: path6.join(appSupport, "Arc", "User Data"),
6942
+ dir: path6.join(appSupport, "Arc", "User Data", "NativeMessagingHosts")
6943
+ }
6849
6944
  ];
6850
6945
  }
6851
6946
  if (platform === "linux") {
6852
6947
  const config = path6.join(home, ".config");
6853
6948
  return [
6854
- { name: "Google Chrome", dir: path6.join(config, "google-chrome", "NativeMessagingHosts") },
6855
- { name: "Chromium", dir: path6.join(config, "chromium", "NativeMessagingHosts") },
6856
- { name: "Brave", dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts") },
6857
- { name: "Microsoft Edge", dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts") }
6949
+ {
6950
+ name: "Google Chrome",
6951
+ userDataDir: path6.join(config, "google-chrome"),
6952
+ dir: path6.join(config, "google-chrome", "NativeMessagingHosts")
6953
+ },
6954
+ {
6955
+ name: "Chromium",
6956
+ userDataDir: path6.join(config, "chromium"),
6957
+ dir: path6.join(config, "chromium", "NativeMessagingHosts")
6958
+ },
6959
+ {
6960
+ name: "Brave",
6961
+ userDataDir: path6.join(config, "BraveSoftware", "Brave-Browser"),
6962
+ dir: path6.join(config, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts")
6963
+ },
6964
+ {
6965
+ name: "Microsoft Edge",
6966
+ userDataDir: path6.join(config, "microsoft-edge"),
6967
+ dir: path6.join(config, "microsoft-edge", "NativeMessagingHosts")
6968
+ }
6858
6969
  ];
6859
6970
  }
6860
6971
  return [];
6861
6972
  }
6973
+ function computeChromeExtensionId(unpackedDir) {
6974
+ const normalized = path6.resolve(unpackedDir);
6975
+ const hash = crypto3.createHash("sha256").update(normalized, "utf8").digest("hex").slice(0, 32);
6976
+ return hash.replace(/[0-9a-f]/g, (ch) => String.fromCharCode(97 + Number.parseInt(ch, 16)));
6977
+ }
6978
+ function getStableExtensionDir() {
6979
+ return path6.join(getBrowserPilotHomeDir(), "extension");
6980
+ }
6981
+ async function syncExtensionToHome(sourceExtDir, options = {}) {
6982
+ const destDir = getStableExtensionDir();
6983
+ let version = null;
6984
+ try {
6985
+ const manifestRaw = await fs5.readFile(path6.join(sourceExtDir, "manifest.json"), "utf8");
6986
+ const manifest = JSON.parse(manifestRaw);
6987
+ version = manifest.version ?? null;
6988
+ } catch {
6989
+ }
6990
+ let synced = false;
6991
+ if (!options.dryRun) {
6992
+ await ensureBrowserPilotHome();
6993
+ const resolvedSrc = await fs5.realpath(sourceExtDir).catch(() => path6.resolve(sourceExtDir));
6994
+ const resolvedDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
6995
+ if (resolvedSrc !== resolvedDest) {
6996
+ await fs5.rm(destDir, { recursive: true, force: true });
6997
+ await fs5.cp(sourceExtDir, destDir, { recursive: true });
6998
+ synced = true;
6999
+ }
7000
+ }
7001
+ const realDest = await fs5.realpath(destDir).catch(() => path6.resolve(destDir));
7002
+ return {
7003
+ extensionDir: realDest,
7004
+ extensionId: computeChromeExtensionId(realDest),
7005
+ version,
7006
+ synced
7007
+ };
7008
+ }
7009
+ async function discoverInstalledExtensionIds(platform = process.platform) {
7010
+ const found = [];
7011
+ const seen = /* @__PURE__ */ new Set();
7012
+ for (const target of getNativeMessagingHostDirs(platform)) {
7013
+ let entries;
7014
+ try {
7015
+ entries = await fs5.readdir(target.userDataDir);
7016
+ } catch {
7017
+ continue;
7018
+ }
7019
+ const profiles = entries.filter((e) => e === "Default" || e.startsWith("Profile "));
7020
+ for (const profile of profiles) {
7021
+ for (const fileName of ["Secure Preferences", "Preferences"]) {
7022
+ const prefPath = path6.join(target.userDataDir, profile, fileName);
7023
+ let parsed;
7024
+ try {
7025
+ parsed = JSON.parse(await fs5.readFile(prefPath, "utf8"));
7026
+ } catch {
7027
+ continue;
7028
+ }
7029
+ const settings = parsed.extensions?.settings;
7030
+ if (!settings || typeof settings !== "object") continue;
7031
+ for (const [extId, meta] of Object.entries(settings)) {
7032
+ if (!meta || !/^[a-p]{32}$/.test(extId)) continue;
7033
+ const manifestName = meta.manifest?.name || "";
7034
+ const extPath = meta.path || "";
7035
+ let isBrowserPilot = /^browserpilot$/i.test(manifestName) || /browserpilot/i.test(extPath);
7036
+ if (!isBrowserPilot && meta.location === 4 && extPath) {
7037
+ try {
7038
+ const m = JSON.parse(await fs5.readFile(path6.join(extPath, "manifest.json"), "utf8"));
7039
+ if (/^browserpilot$/i.test(m.name || "")) isBrowserPilot = true;
7040
+ } catch {
7041
+ }
7042
+ }
7043
+ if (isBrowserPilot && !seen.has(extId)) {
7044
+ seen.add(extId);
7045
+ found.push({ browser: target.name, profile, extensionId: extId, path: extPath || void 0 });
7046
+ }
7047
+ }
7048
+ }
7049
+ }
7050
+ }
7051
+ return found;
7052
+ }
7053
+ async function readInstalledNativeHosts(platform = process.platform) {
7054
+ const results = [];
7055
+ for (const target of getNativeMessagingHostDirs(platform)) {
7056
+ const mp = path6.join(target.dir, `${NATIVE_HOST_NAME}.json`);
7057
+ try {
7058
+ const parsed = JSON.parse(await fs5.readFile(mp, "utf8"));
7059
+ results.push({
7060
+ browser: target.name,
7061
+ installed: true,
7062
+ path: mp,
7063
+ allowedOrigins: Array.isArray(parsed.allowed_origins) ? parsed.allowed_origins : [],
7064
+ wrapperPath: parsed.path
7065
+ });
7066
+ } catch {
7067
+ results.push({ browser: target.name, installed: false, path: mp, allowedOrigins: [] });
7068
+ }
7069
+ }
7070
+ return results;
7071
+ }
6862
7072
  async function installNativeHost(options) {
6863
7073
  const nativeHostJs = path6.resolve(__dirname2, "native-host.js");
6864
7074
  const binDir = path6.join(getBrowserPilotHomeDir(), "bin");
6865
7075
  const wrapperPath = path6.join(binDir, "browserpilot-native-host");
6866
- const allowedOrigins = options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id : `chrome-extension://${id}/`);
7076
+ const allowedOrigins = Array.from(
7077
+ new Set(
7078
+ options.extensionIds.map((id) => id.trim()).filter(Boolean).map((id) => id.startsWith("chrome-extension://") ? id.endsWith("/") ? id : `${id}/` : `chrome-extension://${id}/`)
7079
+ )
7080
+ );
6867
7081
  const manifestJson = {
6868
7082
  name: NATIVE_HOST_NAME,
6869
7083
  description: "BrowserPilot Zero-Click Browser Control & DevTools Bridge",
@@ -6951,17 +7165,23 @@ export {
6951
7165
  BrowserPilotDaemon,
6952
7166
  DaemonClient,
6953
7167
  TOOL_DEFINITIONS,
7168
+ computeChromeExtensionId,
7169
+ discoverInstalledExtensionIds,
6954
7170
  ensureBrowserPilotHome,
6955
7171
  executeTool,
6956
7172
  getBrowserPilotHomeDir,
6957
7173
  getDaemonConfigPath,
6958
7174
  getDaemonLogPath,
6959
7175
  getNativeMessagingHostDirs,
7176
+ getStableExtensionDir,
6960
7177
  installNativeHost,
6961
7178
  isDaemonReachable,
6962
7179
  loadOrCreateDaemonConfig,
7180
+ normalizeNavigationUrl,
6963
7181
  readDaemonConfig,
7182
+ readInstalledNativeHosts,
6964
7183
  startMcpServer,
7184
+ syncExtensionToHome,
6965
7185
  writeDaemonRuntimeInfo
6966
7186
  };
6967
7187
  //# sourceMappingURL=index.js.map