File size: 14,489 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 | import { readdirSync } from 'fs'
import { stat } from 'fs/promises'
import { homedir, platform, tmpdir, userInfo } from 'os'
import { join } from 'path'
import { normalizeNameForMCP } from '../../services/mcp/normalization.js'
import { logForDebugging } from '../debug.js'
import { isFsInaccessible } from '../errors.js'
import { execFileNoThrow } from '../execFileNoThrow.js'
import { getPlatform } from '../platform.js'
import { which } from '../which.js'
export const CLAUDE_IN_CHROME_MCP_SERVER_NAME = 'claude-in-chrome'
// Re-export ChromiumBrowser type for setup.ts
export type { ChromiumBrowser } from './setupPortable.js'
// Import for local use
import type { ChromiumBrowser } from './setupPortable.js'
type BrowserConfig = {
name: string
macos: {
appName: string
dataPath: string[]
nativeMessagingPath: string[]
}
linux: {
binaries: string[]
dataPath: string[]
nativeMessagingPath: string[]
}
windows: {
dataPath: string[]
registryKey: string
useRoaming?: boolean // Opera uses Roaming instead of Local
}
}
export const CHROMIUM_BROWSERS: Record<ChromiumBrowser, BrowserConfig> = {
chrome: {
name: 'Google Chrome',
macos: {
appName: 'Google Chrome',
dataPath: ['Library', 'Application Support', 'Google', 'Chrome'],
nativeMessagingPath: [
'Library',
'Application Support',
'Google',
'Chrome',
'NativeMessagingHosts',
],
},
linux: {
binaries: ['google-chrome', 'google-chrome-stable'],
dataPath: ['.config', 'google-chrome'],
nativeMessagingPath: ['.config', 'google-chrome', 'NativeMessagingHosts'],
},
windows: {
dataPath: ['Google', 'Chrome', 'User Data'],
registryKey: 'HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts',
},
},
brave: {
name: 'Brave',
macos: {
appName: 'Brave Browser',
dataPath: [
'Library',
'Application Support',
'BraveSoftware',
'Brave-Browser',
],
nativeMessagingPath: [
'Library',
'Application Support',
'BraveSoftware',
'Brave-Browser',
'NativeMessagingHosts',
],
},
linux: {
binaries: ['brave-browser', 'brave'],
dataPath: ['.config', 'BraveSoftware', 'Brave-Browser'],
nativeMessagingPath: [
'.config',
'BraveSoftware',
'Brave-Browser',
'NativeMessagingHosts',
],
},
windows: {
dataPath: ['BraveSoftware', 'Brave-Browser', 'User Data'],
registryKey:
'HKCU\\Software\\BraveSoftware\\Brave-Browser\\NativeMessagingHosts',
},
},
arc: {
name: 'Arc',
macos: {
appName: 'Arc',
dataPath: ['Library', 'Application Support', 'Arc', 'User Data'],
nativeMessagingPath: [
'Library',
'Application Support',
'Arc',
'User Data',
'NativeMessagingHosts',
],
},
linux: {
// Arc is not available on Linux
binaries: [],
dataPath: [],
nativeMessagingPath: [],
},
windows: {
// Arc Windows is Chromium-based
dataPath: ['Arc', 'User Data'],
registryKey: 'HKCU\\Software\\ArcBrowser\\Arc\\NativeMessagingHosts',
},
},
chromium: {
name: 'Chromium',
macos: {
appName: 'Chromium',
dataPath: ['Library', 'Application Support', 'Chromium'],
nativeMessagingPath: [
'Library',
'Application Support',
'Chromium',
'NativeMessagingHosts',
],
},
linux: {
binaries: ['chromium', 'chromium-browser'],
dataPath: ['.config', 'chromium'],
nativeMessagingPath: ['.config', 'chromium', 'NativeMessagingHosts'],
},
windows: {
dataPath: ['Chromium', 'User Data'],
registryKey: 'HKCU\\Software\\Chromium\\NativeMessagingHosts',
},
},
edge: {
name: 'Microsoft Edge',
macos: {
appName: 'Microsoft Edge',
dataPath: ['Library', 'Application Support', 'Microsoft Edge'],
nativeMessagingPath: [
'Library',
'Application Support',
'Microsoft Edge',
'NativeMessagingHosts',
],
},
linux: {
binaries: ['microsoft-edge', 'microsoft-edge-stable'],
dataPath: ['.config', 'microsoft-edge'],
nativeMessagingPath: [
'.config',
'microsoft-edge',
'NativeMessagingHosts',
],
},
windows: {
dataPath: ['Microsoft', 'Edge', 'User Data'],
registryKey: 'HKCU\\Software\\Microsoft\\Edge\\NativeMessagingHosts',
},
},
vivaldi: {
name: 'Vivaldi',
macos: {
appName: 'Vivaldi',
dataPath: ['Library', 'Application Support', 'Vivaldi'],
nativeMessagingPath: [
'Library',
'Application Support',
'Vivaldi',
'NativeMessagingHosts',
],
},
linux: {
binaries: ['vivaldi', 'vivaldi-stable'],
dataPath: ['.config', 'vivaldi'],
nativeMessagingPath: ['.config', 'vivaldi', 'NativeMessagingHosts'],
},
windows: {
dataPath: ['Vivaldi', 'User Data'],
registryKey: 'HKCU\\Software\\Vivaldi\\NativeMessagingHosts',
},
},
opera: {
name: 'Opera',
macos: {
appName: 'Opera',
dataPath: ['Library', 'Application Support', 'com.operasoftware.Opera'],
nativeMessagingPath: [
'Library',
'Application Support',
'com.operasoftware.Opera',
'NativeMessagingHosts',
],
},
linux: {
binaries: ['opera'],
dataPath: ['.config', 'opera'],
nativeMessagingPath: ['.config', 'opera', 'NativeMessagingHosts'],
},
windows: {
dataPath: ['Opera Software', 'Opera Stable'],
registryKey:
'HKCU\\Software\\Opera Software\\Opera Stable\\NativeMessagingHosts',
useRoaming: true, // Opera uses Roaming AppData, not Local
},
},
}
// Priority order for browser detection (most common first)
export const BROWSER_DETECTION_ORDER: ChromiumBrowser[] = [
'chrome',
'brave',
'arc',
'edge',
'chromium',
'vivaldi',
'opera',
]
/**
* Get all browser data paths to check for extension installation
*/
export function getAllBrowserDataPaths(): {
browser: ChromiumBrowser
path: string
}[] {
const platform = getPlatform()
const home = homedir()
const paths: { browser: ChromiumBrowser; path: string }[] = []
for (const browserId of BROWSER_DETECTION_ORDER) {
const config = CHROMIUM_BROWSERS[browserId]
let dataPath: string[] | undefined
switch (platform) {
case 'macos':
dataPath = config.macos.dataPath
break
case 'linux':
case 'wsl':
dataPath = config.linux.dataPath
break
case 'windows': {
if (config.windows.dataPath.length > 0) {
const appDataBase = config.windows.useRoaming
? join(home, 'AppData', 'Roaming')
: join(home, 'AppData', 'Local')
paths.push({
browser: browserId,
path: join(appDataBase, ...config.windows.dataPath),
})
}
continue
}
}
if (dataPath && dataPath.length > 0) {
paths.push({
browser: browserId,
path: join(home, ...dataPath),
})
}
}
return paths
}
/**
* Get native messaging host directories for all supported browsers
*/
export function getAllNativeMessagingHostsDirs(): {
browser: ChromiumBrowser
path: string
}[] {
const platform = getPlatform()
const home = homedir()
const paths: { browser: ChromiumBrowser; path: string }[] = []
for (const browserId of BROWSER_DETECTION_ORDER) {
const config = CHROMIUM_BROWSERS[browserId]
switch (platform) {
case 'macos':
if (config.macos.nativeMessagingPath.length > 0) {
paths.push({
browser: browserId,
path: join(home, ...config.macos.nativeMessagingPath),
})
}
break
case 'linux':
case 'wsl':
if (config.linux.nativeMessagingPath.length > 0) {
paths.push({
browser: browserId,
path: join(home, ...config.linux.nativeMessagingPath),
})
}
break
case 'windows':
// Windows uses registry, not file paths for native messaging
// We'll use a common location for the manifest file
break
}
}
return paths
}
/**
* Get Windows registry keys for all supported browsers
*/
export function getAllWindowsRegistryKeys(): {
browser: ChromiumBrowser
key: string
}[] {
const keys: { browser: ChromiumBrowser; key: string }[] = []
for (const browserId of BROWSER_DETECTION_ORDER) {
const config = CHROMIUM_BROWSERS[browserId]
if (config.windows.registryKey) {
keys.push({
browser: browserId,
key: config.windows.registryKey,
})
}
}
return keys
}
/**
* Detect which browser to use for opening URLs
* Returns the first available browser, or null if none found
*/
export async function detectAvailableBrowser(): Promise<ChromiumBrowser | null> {
const platform = getPlatform()
for (const browserId of BROWSER_DETECTION_ORDER) {
const config = CHROMIUM_BROWSERS[browserId]
switch (platform) {
case 'macos': {
// Check if the .app bundle (a directory) exists
const appPath = `/Applications/${config.macos.appName}.app`
try {
const stats = await stat(appPath)
if (stats.isDirectory()) {
logForDebugging(
`[Claude in Chrome] Detected browser: ${config.name}`,
)
return browserId
}
} catch (e) {
if (!isFsInaccessible(e)) throw e
// App not found, continue checking
}
break
}
case 'wsl':
case 'linux': {
// Check if any binary exists
for (const binary of config.linux.binaries) {
if (await which(binary).catch(() => null)) {
logForDebugging(
`[Claude in Chrome] Detected browser: ${config.name}`,
)
return browserId
}
}
break
}
case 'windows': {
// Check if data path exists (indicates browser is installed)
const home = homedir()
if (config.windows.dataPath.length > 0) {
const appDataBase = config.windows.useRoaming
? join(home, 'AppData', 'Roaming')
: join(home, 'AppData', 'Local')
const dataPath = join(appDataBase, ...config.windows.dataPath)
try {
const stats = await stat(dataPath)
if (stats.isDirectory()) {
logForDebugging(
`[Claude in Chrome] Detected browser: ${config.name}`,
)
return browserId
}
} catch (e) {
if (!isFsInaccessible(e)) throw e
// Browser not found, continue checking
}
}
break
}
}
}
return null
}
export function isClaudeInChromeMCPServer(name: string): boolean {
return normalizeNameForMCP(name) === CLAUDE_IN_CHROME_MCP_SERVER_NAME
}
const MAX_TRACKED_TABS = 200
const trackedTabIds = new Set<number>()
export function trackClaudeInChromeTabId(tabId: number): void {
if (trackedTabIds.size >= MAX_TRACKED_TABS && !trackedTabIds.has(tabId)) {
trackedTabIds.clear()
}
trackedTabIds.add(tabId)
}
export function isTrackedClaudeInChromeTabId(tabId: number): boolean {
return trackedTabIds.has(tabId)
}
export async function openInChrome(url: string): Promise<boolean> {
const currentPlatform = getPlatform()
// Detect the best available browser
const browser = await detectAvailableBrowser()
if (!browser) {
logForDebugging('[Claude in Chrome] No compatible browser found')
return false
}
const config = CHROMIUM_BROWSERS[browser]
switch (currentPlatform) {
case 'macos': {
const { code } = await execFileNoThrow('open', [
'-a',
config.macos.appName,
url,
])
return code === 0
}
case 'windows': {
// Use rundll32 to avoid cmd.exe metacharacter issues with URLs containing & | > <
const { code } = await execFileNoThrow('rundll32', ['url,OpenURL', url])
return code === 0
}
case 'wsl':
case 'linux': {
for (const binary of config.linux.binaries) {
const { code } = await execFileNoThrow(binary, [url])
if (code === 0) {
return true
}
}
return false
}
default:
return false
}
}
/**
* Get the socket directory path (Unix only)
*/
export function getSocketDir(): string {
return `/tmp/claude-mcp-browser-bridge-${getUsername()}`
}
/**
* Get the socket path (Unix) or pipe name (Windows)
*/
export function getSecureSocketPath(): string {
if (platform() === 'win32') {
return `\\\\.\\pipe\\${getSocketName()}`
}
return join(getSocketDir(), `${process.pid}.sock`)
}
/**
* Get all socket paths including PID-based sockets in the directory
* and legacy fallback paths
*/
export function getAllSocketPaths(): string[] {
// Windows uses named pipes, not Unix sockets
if (platform() === 'win32') {
return [`\\\\.\\pipe\\${getSocketName()}`]
}
const paths: string[] = []
const socketDir = getSocketDir()
// Scan for *.sock files in the socket directory
try {
// eslint-disable-next-line custom-rules/no-sync-fs -- ClaudeForChromeContext.getSocketPaths (external @ant/claude-for-chrome-mcp) requires a sync () => string[] callback
const files = readdirSync(socketDir)
for (const file of files) {
if (file.endsWith('.sock')) {
paths.push(join(socketDir, file))
}
}
} catch {
// Directory may not exist yet
}
// Legacy fallback paths
const legacyName = `claude-mcp-browser-bridge-${getUsername()}`
const legacyTmpdir = join(tmpdir(), legacyName)
const legacyTmp = `/tmp/${legacyName}`
if (!paths.includes(legacyTmpdir)) {
paths.push(legacyTmpdir)
}
if (legacyTmpdir !== legacyTmp && !paths.includes(legacyTmp)) {
paths.push(legacyTmp)
}
return paths
}
function getSocketName(): string {
// NOTE: This must match the one used in the Claude in Chrome MCP
return `claude-mcp-browser-bridge-${getUsername()}`
}
function getUsername(): string {
try {
return userInfo().username || 'default'
} catch {
return process.env.USER || process.env.USERNAME || 'default'
}
}
|