dsh-shared-browser 0.0.0-stage → 0.6.7
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/LICENSE +21 -0
- package/README.md +132 -2
- package/README.zh.md +127 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +10 -0
- package/index.js +825 -0
- package/lib/bridge.mjs +372 -0
- package/lib/client.cjs +2712 -0
- package/lib/external.mjs +641 -0
- package/locale/en.json +9 -0
- package/locale/zh.json +9 -0
- package/package.json +78 -3
package/lib/external.mjs
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-shared-browser — external Chromium channel.
|
|
3
|
+
*
|
|
4
|
+
* The built-in `<webview>` is locked down by the desktop shell (no persistent
|
|
5
|
+
* partition, no downloads, no DevTools, Electron UA), which makes real sites
|
|
6
|
+
* such as Cloudflare-protected ones unusable. This module drives the user's own
|
|
7
|
+
* Edge/Chrome through the Chrome DevTools Protocol instead: real fingerprints,
|
|
8
|
+
* a persistent profile, extensions, downloads and DevTools, and no change to
|
|
9
|
+
* DSH itself.
|
|
10
|
+
*
|
|
11
|
+
* Everything here is plain HTTP + WebSocket to 127.0.0.1, so the Host process
|
|
12
|
+
* needs no extra dependency.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { spawn } from 'node:child_process'
|
|
16
|
+
import { existsSync } from 'node:fs'
|
|
17
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
|
18
|
+
import { homedir } from 'node:os'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
|
|
21
|
+
const LAUNCH_TIMEOUT_MS = 20000
|
|
22
|
+
const COMMAND_TIMEOUT_MS = 20000
|
|
23
|
+
|
|
24
|
+
/** Absolute profile root for the external browsers. */
|
|
25
|
+
export function profileRoot() {
|
|
26
|
+
return join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'shared-browser', 'profiles')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Candidate browser binaries, most preferred first. */
|
|
30
|
+
export function detectBrowsers() {
|
|
31
|
+
const found = []
|
|
32
|
+
const push = (id, name, path) => {
|
|
33
|
+
if (path !== undefined && existsSync(path) === true && found.some(entry => entry.path === path) === false) {
|
|
34
|
+
found.push({ id, name, path })
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (process.platform === 'win32') {
|
|
38
|
+
const pf = process.env['ProgramFiles'] ?? 'C:\\Program Files'
|
|
39
|
+
const pf86 = process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)'
|
|
40
|
+
const local = process.env['LOCALAPPDATA'] ?? join(homedir(), 'AppData', 'Local')
|
|
41
|
+
push('msedge', 'Microsoft Edge', join(pf86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'))
|
|
42
|
+
push('msedge', 'Microsoft Edge', join(pf, 'Microsoft', 'Edge', 'Application', 'msedge.exe'))
|
|
43
|
+
push('chrome', 'Google Chrome', join(pf, 'Google', 'Chrome', 'Application', 'chrome.exe'))
|
|
44
|
+
push('chrome', 'Google Chrome', join(pf86, 'Google', 'Chrome', 'Application', 'chrome.exe'))
|
|
45
|
+
push('chrome', 'Google Chrome', join(local, 'Google', 'Chrome', 'Application', 'chrome.exe'))
|
|
46
|
+
} else if (process.platform === 'darwin') {
|
|
47
|
+
push('chrome', 'Google Chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
|
|
48
|
+
push('msedge', 'Microsoft Edge', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge')
|
|
49
|
+
push('chrome', 'Chromium', '/Applications/Chromium.app/Contents/MacOS/Chromium')
|
|
50
|
+
} else {
|
|
51
|
+
for (const [id, name, path] of [
|
|
52
|
+
['chrome', 'Google Chrome', '/usr/bin/google-chrome'],
|
|
53
|
+
['chrome', 'Chromium', '/usr/bin/chromium'],
|
|
54
|
+
['chrome', 'Chromium', '/usr/bin/chromium-browser'],
|
|
55
|
+
['msedge', 'Microsoft Edge', '/usr/bin/microsoft-edge'],
|
|
56
|
+
]) {
|
|
57
|
+
push(id, name, path)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return found
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Minimal CDP page session over the global WebSocket. */
|
|
64
|
+
class PageSession {
|
|
65
|
+
constructor(webSocketUrl, onEvent) {
|
|
66
|
+
this.url = webSocketUrl
|
|
67
|
+
this.onEvent = onEvent
|
|
68
|
+
this.nextId = 1
|
|
69
|
+
this.pending = new Map()
|
|
70
|
+
this.socket = null
|
|
71
|
+
this.ready = null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async connect() {
|
|
75
|
+
if (this.ready !== null) return this.ready
|
|
76
|
+
this.ready = new Promise((resolve, reject) => {
|
|
77
|
+
const socket = new WebSocket(this.url)
|
|
78
|
+
this.socket = socket
|
|
79
|
+
socket.addEventListener('open', () => resolve(), { once: true })
|
|
80
|
+
socket.addEventListener('error', () => reject(new Error('CDP 连接失败')), { once: true })
|
|
81
|
+
socket.addEventListener('message', (event) => this.handle(event.data))
|
|
82
|
+
socket.addEventListener('close', () => {
|
|
83
|
+
for (const [, entry] of this.pending) entry.reject(new Error('CDP 连接已断开'))
|
|
84
|
+
this.pending.clear()
|
|
85
|
+
this.ready = null
|
|
86
|
+
})
|
|
87
|
+
})
|
|
88
|
+
return this.ready
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
handle(data) {
|
|
92
|
+
let message
|
|
93
|
+
try {
|
|
94
|
+
message = JSON.parse(String(data))
|
|
95
|
+
} catch {
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
if (message.id !== undefined) {
|
|
99
|
+
const entry = this.pending.get(message.id)
|
|
100
|
+
if (entry === undefined) return
|
|
101
|
+
this.pending.delete(message.id)
|
|
102
|
+
if (message.error !== undefined) entry.reject(new Error(message.error.message ?? 'CDP 错误'))
|
|
103
|
+
else entry.resolve(message.result)
|
|
104
|
+
return
|
|
105
|
+
}
|
|
106
|
+
if (typeof message.method === 'string' && typeof this.onEvent === 'function') {
|
|
107
|
+
this.onEvent(message.method, message.params ?? {})
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
send(method, params = {}, timeoutMs = COMMAND_TIMEOUT_MS) {
|
|
112
|
+
const id = this.nextId++
|
|
113
|
+
return new Promise((resolve, reject) => {
|
|
114
|
+
const timer = setTimeout(() => {
|
|
115
|
+
this.pending.delete(id)
|
|
116
|
+
reject(new Error(`CDP 命令超时: ${method}`))
|
|
117
|
+
}, timeoutMs)
|
|
118
|
+
this.pending.set(id, {
|
|
119
|
+
resolve: (value) => { clearTimeout(timer); resolve(value) },
|
|
120
|
+
reject: (error) => { clearTimeout(timer); reject(error) },
|
|
121
|
+
})
|
|
122
|
+
try {
|
|
123
|
+
this.socket.send(JSON.stringify({ id, method, params }))
|
|
124
|
+
} catch (error) {
|
|
125
|
+
clearTimeout(timer)
|
|
126
|
+
this.pending.delete(id)
|
|
127
|
+
reject(error)
|
|
128
|
+
}
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async evaluate(expression, awaitPromise = true) {
|
|
133
|
+
const result = await this.send('Runtime.evaluate', {
|
|
134
|
+
expression,
|
|
135
|
+
awaitPromise,
|
|
136
|
+
returnByValue: true,
|
|
137
|
+
userGesture: true,
|
|
138
|
+
})
|
|
139
|
+
if (result.exceptionDetails !== undefined) {
|
|
140
|
+
const text = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text ?? '脚本执行失败'
|
|
141
|
+
throw new Error(String(text).split('\n')[0])
|
|
142
|
+
}
|
|
143
|
+
return result.result?.value
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
close() {
|
|
147
|
+
try { this.socket?.close() } catch { /* already gone */ }
|
|
148
|
+
this.ready = null
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** One launched Chromium and the page sessions attached to it. */
|
|
153
|
+
export class ExternalBrowser {
|
|
154
|
+
constructor(log = () => {}) {
|
|
155
|
+
this.log = log
|
|
156
|
+
this.process = null
|
|
157
|
+
this.port = 0
|
|
158
|
+
this.browser = null
|
|
159
|
+
this.profileDir = ''
|
|
160
|
+
this.sessions = new Map()
|
|
161
|
+
this.zoom = new Map()
|
|
162
|
+
this.consoleLog = []
|
|
163
|
+
this.networkLog = []
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
get running() {
|
|
167
|
+
return this.port !== 0 && this.process !== null && this.process.exitCode === null
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Launch the browser once and wait for its DevTools port file. */
|
|
171
|
+
async ensure(options = {}) {
|
|
172
|
+
if (this.running === true) {
|
|
173
|
+
const url = typeof options.url === 'string' && options.url !== '' ? options.url : null
|
|
174
|
+
try {
|
|
175
|
+
if (url !== null) {
|
|
176
|
+
const tabs = await this.listTabs()
|
|
177
|
+
const wanted = url.replace(/\/+$/, '')
|
|
178
|
+
const already = tabs.find(entry => String(entry.url ?? '').replace(/\/+$/, '') === wanted)
|
|
179
|
+
if (already === undefined) await this.waitReady(await this.openTab(url))
|
|
180
|
+
}
|
|
181
|
+
return this.summary()
|
|
182
|
+
} catch {
|
|
183
|
+
/* The window went away between calls: fall through and relaunch. */
|
|
184
|
+
this.running = false
|
|
185
|
+
this.port = null
|
|
186
|
+
for (const [, session] of this.sessions) session.close()
|
|
187
|
+
this.sessions.clear()
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const candidates = detectBrowsers()
|
|
191
|
+
if (candidates.length === 0) throw new Error('没有找到 Edge 或 Chrome,无法使用外部通道。')
|
|
192
|
+
const wanted = typeof options.browser === 'string' && options.browser !== ''
|
|
193
|
+
? candidates.find(entry => entry.id === options.browser || entry.path === options.browser)
|
|
194
|
+
: undefined
|
|
195
|
+
const pick = wanted ?? candidates[0]
|
|
196
|
+
const profileDir = options.profileDir ?? join(profileRoot(), pick.id)
|
|
197
|
+
await mkdir(profileDir, { recursive: true })
|
|
198
|
+
const portFile = join(profileDir, 'DevToolsActivePort')
|
|
199
|
+
await rm(portFile, { force: true }).catch(() => {})
|
|
200
|
+
const args = [
|
|
201
|
+
'--remote-debugging-port=0',
|
|
202
|
+
`--user-data-dir=${profileDir}`,
|
|
203
|
+
'--no-first-run',
|
|
204
|
+
'--no-default-browser-check',
|
|
205
|
+
'--disable-features=Translate,MediaRouter',
|
|
206
|
+
'--window-size=1200,860',
|
|
207
|
+
options.url ?? 'about:blank',
|
|
208
|
+
]
|
|
209
|
+
const child = spawn(pick.path, args, { detached: true, stdio: 'ignore' })
|
|
210
|
+
child.unref()
|
|
211
|
+
this.process = child
|
|
212
|
+
this.browser = pick
|
|
213
|
+
this.profileDir = profileDir
|
|
214
|
+
const deadline = Date.now() + LAUNCH_TIMEOUT_MS
|
|
215
|
+
while (Date.now() < deadline) {
|
|
216
|
+
if (existsSync(portFile) === true) {
|
|
217
|
+
const content = await readFile(portFile, 'utf8').catch(() => '')
|
|
218
|
+
const port = Number.parseInt(String(content).split('\n')[0] ?? '', 10)
|
|
219
|
+
if (Number.isFinite(port) && port > 0) {
|
|
220
|
+
this.port = port
|
|
221
|
+
this.log(`external: ${pick.name} on port ${port}`)
|
|
222
|
+
/* First launch also has to paint the page: wait so callers see a title. */
|
|
223
|
+
if (typeof options.url === 'string' && options.url !== '') await this.waitTab(options.url).catch(() => null)
|
|
224
|
+
return this.summary()
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
await new Promise(resolve => setTimeout(resolve, 250))
|
|
228
|
+
}
|
|
229
|
+
throw new Error(`外部浏览器启动超时:${pick.name}`)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
summary() {
|
|
233
|
+
return {
|
|
234
|
+
running: this.running,
|
|
235
|
+
browser: this.browser === null ? null : { id: this.browser.id, name: this.browser.name, path: this.browser.path },
|
|
236
|
+
port: this.port,
|
|
237
|
+
profileDir: this.profileDir,
|
|
238
|
+
candidates: detectBrowsers().map(entry => ({ id: entry.id, name: entry.name })),
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async http(path, method = 'GET') {
|
|
243
|
+
if (this.running === false) throw new Error('外部浏览器没有运行。')
|
|
244
|
+
const response = await fetch(`http://127.0.0.1:${this.port}${path}`, { method })
|
|
245
|
+
if (response.ok === false) throw new Error(`CDP HTTP ${response.status}`)
|
|
246
|
+
const text = await response.text()
|
|
247
|
+
return text === '' ? null : JSON.parse(text)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async listTabs() {
|
|
251
|
+
const targets = await this.http('/json/list')
|
|
252
|
+
return (targets ?? []).filter(target => target.type === 'page')
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async openTab(url) {
|
|
256
|
+
const target = await this.http(`/json/new?${encodeURIComponent(url)}`, 'PUT')
|
|
257
|
+
if (target?.id === undefined) throw new Error('无法新建外部页签。')
|
|
258
|
+
return target.id
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async closeTab(targetId) {
|
|
262
|
+
await this.http(`/json/close/${encodeURIComponent(targetId)}`).catch(() => {})
|
|
263
|
+
const session = this.sessions.get(targetId)
|
|
264
|
+
if (session !== undefined) {
|
|
265
|
+
session.close()
|
|
266
|
+
this.sessions.delete(targetId)
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Attach to one external page and enable the domains we read. */
|
|
271
|
+
async session(targetId) {
|
|
272
|
+
const existing = this.sessions.get(targetId)
|
|
273
|
+
if (existing !== undefined) {
|
|
274
|
+
await existing.connect()
|
|
275
|
+
return existing
|
|
276
|
+
}
|
|
277
|
+
const targets = await this.listTabs()
|
|
278
|
+
const target = targets.find(entry => entry.id === targetId)
|
|
279
|
+
if (target === undefined) throw new Error('外部页签不存在。')
|
|
280
|
+
const session = new PageSession(target.webSocketDebuggerUrl, (method, params) => this.onEvent(targetId, method, params))
|
|
281
|
+
await session.connect()
|
|
282
|
+
await session.send('Runtime.enable').catch(() => {})
|
|
283
|
+
await session.send('Page.enable').catch(() => {})
|
|
284
|
+
await session.send('Network.enable').catch(() => {})
|
|
285
|
+
this.sessions.set(targetId, session)
|
|
286
|
+
return session
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
onEvent(targetId, method, params) {
|
|
290
|
+
if (method === 'Runtime.consoleAPICalled') {
|
|
291
|
+
const level = params.type === 'error' ? 'error' : params.type === 'warning' ? 'warning' : 'info'
|
|
292
|
+
const text = (params.args ?? []).map(arg => arg.value ?? arg.description ?? '').join(' ')
|
|
293
|
+
this.consoleLog.push({ level, text, ts: params.timestamp ?? Date.now(), tabId: targetId })
|
|
294
|
+
if (this.consoleLog.length > 2000) this.consoleLog.shift()
|
|
295
|
+
return
|
|
296
|
+
}
|
|
297
|
+
if (method === 'Log.entryAdded') {
|
|
298
|
+
const entry = params.entry ?? {}
|
|
299
|
+
this.consoleLog.push({ level: entry.level ?? 'info', text: entry.text ?? '', ts: entry.timestamp ?? Date.now(), tabId: targetId })
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
if (method === 'Network.responseReceived') {
|
|
303
|
+
const response = params.response ?? {}
|
|
304
|
+
this.networkLog.push({
|
|
305
|
+
method: response.requestHeadersText ?? 'GET',
|
|
306
|
+
url: response.url ?? '',
|
|
307
|
+
status: response.status ?? 0,
|
|
308
|
+
ok: Number(response.status ?? 0) < 400,
|
|
309
|
+
ms: Math.round(params.timestamp ?? 0),
|
|
310
|
+
tabId: targetId,
|
|
311
|
+
})
|
|
312
|
+
if (this.networkLog.length > 600) this.networkLog.shift()
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Resolve a target id from a tool tab id such as `ext:ABCD`. */
|
|
317
|
+
static targetOf(tabId) {
|
|
318
|
+
const raw = String(tabId ?? '')
|
|
319
|
+
return raw.startsWith('ext:') ? raw.slice(4) : null
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Wait until a freshly opened page is ready to answer evaluations. */
|
|
323
|
+
async waitReady(id, timeoutMs = 8000) {
|
|
324
|
+
const session = await this.session(id).catch(() => null)
|
|
325
|
+
if (session === null) return
|
|
326
|
+
const deadline = Date.now() + timeoutMs
|
|
327
|
+
while (Date.now() < deadline) {
|
|
328
|
+
const state = await session.evaluate('document.readyState').catch(() => '')
|
|
329
|
+
if (state === 'complete' || state === 'interactive') return
|
|
330
|
+
await new Promise(resolve => setTimeout(resolve, 250))
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Describe the element a comment should attach to. */
|
|
335
|
+
async describe(session, args) {
|
|
336
|
+
const selector = typeof args.selector === 'string' && args.selector !== '' ? args.selector : null
|
|
337
|
+
const ref = typeof args.ref === 'string' && args.ref !== '' ? args.ref : null
|
|
338
|
+
const expression = `(() => {
|
|
339
|
+
const selector = ${JSON.stringify(selector)}
|
|
340
|
+
const ref = ${JSON.stringify(ref)}
|
|
341
|
+
const element = selector !== null ? document.querySelector(selector) : (ref !== null ? document.querySelector('[data-dsb-ref="' + ref + '"]') : null)
|
|
342
|
+
if (element === null) return null
|
|
343
|
+
const rect = element.getBoundingClientRect()
|
|
344
|
+
return {
|
|
345
|
+
selector: selector ?? '[data-dsb-ref="' + ref + '"]',
|
|
346
|
+
tag: element.tagName.toLowerCase(),
|
|
347
|
+
name: String(element.getAttribute('aria-label') ?? element.getAttribute('name') ?? '').slice(0, 120),
|
|
348
|
+
text: String(element.innerText ?? element.textContent ?? '').trim().slice(0, 300),
|
|
349
|
+
rect: { x: Math.round(rect.left), y: Math.round(rect.top), width: Math.round(rect.width), height: Math.round(rect.height) },
|
|
350
|
+
}
|
|
351
|
+
})()`
|
|
352
|
+
return await session.evaluate(expression).catch(() => null)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Capture a rectangular region of the page as a data URL. */
|
|
356
|
+
async captureClip(session, rect) {
|
|
357
|
+
const width = Math.max(1, Math.round(rect.width))
|
|
358
|
+
const height = Math.max(1, Math.round(rect.height))
|
|
359
|
+
const shot = await session.send('Page.captureScreenshot', {
|
|
360
|
+
format: 'png',
|
|
361
|
+
clip: { x: Math.max(0, Math.round(rect.x)), y: Math.max(0, Math.round(rect.y)), width, height, scale: 1 },
|
|
362
|
+
captureBeyondViewport: true,
|
|
363
|
+
})
|
|
364
|
+
return `data:image/png;base64,${shot.data}`
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Wait until the requested address shows up with a title. */
|
|
368
|
+
async waitTab(url, timeoutMs = 15000) {
|
|
369
|
+
const wanted = String(url ?? '').replace(/\/+$/, '')
|
|
370
|
+
if (wanted === '') return null
|
|
371
|
+
const deadline = Date.now() + timeoutMs
|
|
372
|
+
while (Date.now() < deadline) {
|
|
373
|
+
const tabs = await this.listTabs().catch(() => [])
|
|
374
|
+
const hit = tabs.find(entry => String(entry.url ?? '').replace(/\/+$/, '') === wanted && String(entry.title ?? '') !== '')
|
|
375
|
+
if (hit !== undefined) return hit
|
|
376
|
+
await new Promise(resolve => setTimeout(resolve, 400))
|
|
377
|
+
}
|
|
378
|
+
return null
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
async command(op, args = {}, tabId) {
|
|
382
|
+
const targetId = ExternalBrowser.targetOf(tabId) ?? (await this.activeTarget(args))
|
|
383
|
+
switch (op) {
|
|
384
|
+
case 'open': {
|
|
385
|
+
const id = await this.openTab(String(args.url ?? 'about:blank'))
|
|
386
|
+
await this.waitReady(id)
|
|
387
|
+
return { tabId: `ext:${id}`, url: String(args.url ?? '') }
|
|
388
|
+
}
|
|
389
|
+
case 'tabs': {
|
|
390
|
+
const tabs = (await this.listTabs()).map(target => ({
|
|
391
|
+
id: `ext:${target.id}`,
|
|
392
|
+
url: target.url,
|
|
393
|
+
title: target.title,
|
|
394
|
+
loading: false,
|
|
395
|
+
visible: true,
|
|
396
|
+
}))
|
|
397
|
+
return { tabs }
|
|
398
|
+
}
|
|
399
|
+
case 'navigate': {
|
|
400
|
+
const session = await this.session(targetId)
|
|
401
|
+
await session.send('Page.navigate', { url: String(args.url ?? '') })
|
|
402
|
+
return { url: String(args.url ?? '') }
|
|
403
|
+
}
|
|
404
|
+
case 'zoom': {
|
|
405
|
+
const session = await this.session(targetId)
|
|
406
|
+
const action = String(args.action ?? 'reset')
|
|
407
|
+
const steps = [0.5, 0.67, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3]
|
|
408
|
+
const current = this.zoom.get(targetId) ?? 1
|
|
409
|
+
let next = current
|
|
410
|
+
if (action === 'reset') next = 1
|
|
411
|
+
else if (action === 'in') next = steps.find(step => step > current + 0.001) ?? steps[steps.length - 1]
|
|
412
|
+
else if (action === 'out') next = [...steps].reverse().find(step => step < current - 0.001) ?? steps[0]
|
|
413
|
+
else if (action === 'set') next = Math.min(5, Math.max(0.25, Number(args.factor ?? 1)))
|
|
414
|
+
this.zoom.set(targetId, next)
|
|
415
|
+
await session.send('Emulation.setPageScaleFactor', { pageScaleFactor: next })
|
|
416
|
+
return { zoom: next }
|
|
417
|
+
}
|
|
418
|
+
case 'find': {
|
|
419
|
+
const session = await this.session(targetId)
|
|
420
|
+
const action = String(args.action ?? 'find')
|
|
421
|
+
const wanted = String(args.text ?? '')
|
|
422
|
+
if (action === 'stop' || wanted === '') {
|
|
423
|
+
await session.evaluate('window.getSelection().removeAllRanges()').catch(() => {})
|
|
424
|
+
return { count: 0, found: false }
|
|
425
|
+
}
|
|
426
|
+
const probe = "(() => { var t = " + JSON.stringify(wanted.toLowerCase()) + "; var n = 0; var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); var node; while ((node = walker.nextNode())) { var value = String(node.nodeValue || '').toLowerCase(); var at = value.indexOf(t); while (at !== -1) { n += 1; at = value.indexOf(t, at + t.length) } } return n })()"
|
|
427
|
+
const count = await session.evaluate(probe).catch(() => 0)
|
|
428
|
+
await session.evaluate('window.find(' + JSON.stringify(wanted) + ', false, false, true)').catch(() => {})
|
|
429
|
+
return { count: Number(count) || 0, found: Number(count) > 0, text: wanted }
|
|
430
|
+
}
|
|
431
|
+
case 'comment': {
|
|
432
|
+
const session = await this.session(targetId)
|
|
433
|
+
const target = await this.describe(session, args)
|
|
434
|
+
if (target === null) throw new Error('未找到要评论的元素:先选取元素或传入 selector。')
|
|
435
|
+
const clip = await this.captureClip(session, target.rect).catch(() => null)
|
|
436
|
+
return {
|
|
437
|
+
id: `ext-${Date.now()}`,
|
|
438
|
+
tabId: `ext:${targetId}`,
|
|
439
|
+
url: await session.evaluate('location.href').catch(() => ''),
|
|
440
|
+
title: await session.evaluate('document.title').catch(() => ''),
|
|
441
|
+
selector: target.selector,
|
|
442
|
+
ref: null,
|
|
443
|
+
tag: target.tag,
|
|
444
|
+
name: target.name,
|
|
445
|
+
text: target.text,
|
|
446
|
+
note: String(args.note ?? ''),
|
|
447
|
+
rect: target.rect,
|
|
448
|
+
screenshot: clip,
|
|
449
|
+
ts: Date.now(),
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
case 'text': {
|
|
453
|
+
const session = await this.session(targetId)
|
|
454
|
+
const text = await session.evaluate('document.body === null ? "" : document.body.innerText')
|
|
455
|
+
return { text: String(text ?? '') }
|
|
456
|
+
}
|
|
457
|
+
case 'snapshot': {
|
|
458
|
+
const session = await this.session(targetId)
|
|
459
|
+
return await snapshot(session)
|
|
460
|
+
}
|
|
461
|
+
case 'evaluate': {
|
|
462
|
+
const session = await this.session(targetId)
|
|
463
|
+
const value = await session.evaluate(String(args.expression ?? 'undefined'))
|
|
464
|
+
return { value: value ?? null }
|
|
465
|
+
}
|
|
466
|
+
case 'screenshot': {
|
|
467
|
+
const session = await this.session(targetId)
|
|
468
|
+
const shot = await session.send('Page.captureScreenshot', { format: 'png' })
|
|
469
|
+
return { mime: 'image/png', dataUrl: `data:image/png;base64,${shot.data}` }
|
|
470
|
+
}
|
|
471
|
+
case 'regionScreenshot': {
|
|
472
|
+
const session = await this.session(targetId)
|
|
473
|
+
const clip = {
|
|
474
|
+
x: Number(args.x ?? 0),
|
|
475
|
+
y: Number(args.y ?? 0),
|
|
476
|
+
width: Math.max(1, Number(args.width ?? 1)),
|
|
477
|
+
height: Math.max(1, Number(args.height ?? 1)),
|
|
478
|
+
scale: 1,
|
|
479
|
+
}
|
|
480
|
+
const shot = await session.send('Page.captureScreenshot', { format: 'png', clip })
|
|
481
|
+
return { mime: 'image/png', dataUrl: `data:image/png;base64,${shot.data}`, clip }
|
|
482
|
+
}
|
|
483
|
+
case 'click': {
|
|
484
|
+
const session = await this.session(targetId)
|
|
485
|
+
const rect = await elementRect(session, args)
|
|
486
|
+
const x = rect.x + rect.width / 2
|
|
487
|
+
const y = rect.y + rect.height / 2
|
|
488
|
+
await session.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
|
|
489
|
+
await session.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 })
|
|
490
|
+
await session.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 })
|
|
491
|
+
return { clicked: true, x: Math.round(x), y: Math.round(y) }
|
|
492
|
+
}
|
|
493
|
+
case 'type': {
|
|
494
|
+
const session = await this.session(targetId)
|
|
495
|
+
const selector = args.selector === undefined ? null : String(args.selector)
|
|
496
|
+
await session.evaluate(focusSnippet(args))
|
|
497
|
+
await session.send('Input.insertText', { text: String(args.text ?? '') })
|
|
498
|
+
return { typed: String(args.text ?? '').length, selector }
|
|
499
|
+
}
|
|
500
|
+
case 'press': {
|
|
501
|
+
const session = await this.session(targetId)
|
|
502
|
+
await session.send('Input.dispatchKeyEvent', { type: 'keyDown', key: String(args.key ?? 'Enter'), code: String(args.code ?? '') })
|
|
503
|
+
await session.send('Input.dispatchKeyEvent', { type: 'keyUp', key: String(args.key ?? 'Enter'), code: String(args.code ?? '') })
|
|
504
|
+
return { pressed: String(args.key ?? 'Enter') }
|
|
505
|
+
}
|
|
506
|
+
case 'console':
|
|
507
|
+
return { entries: this.consoleLog.slice(-200) }
|
|
508
|
+
case 'network':
|
|
509
|
+
return { entries: this.networkLog.slice(-200) }
|
|
510
|
+
case 'close': {
|
|
511
|
+
if (targetId !== null) await this.closeTab(targetId)
|
|
512
|
+
return { closed: targetId }
|
|
513
|
+
}
|
|
514
|
+
default:
|
|
515
|
+
throw new Error(`外部通道不支持该操作: ${op}`)
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async activeTarget(args) {
|
|
520
|
+
const explicit = args.tabId === undefined ? null : ExternalBrowser.targetOf(args.tabId)
|
|
521
|
+
if (explicit !== null) return explicit
|
|
522
|
+
const tabs = await this.listTabs()
|
|
523
|
+
if (tabs.length === 0) throw new Error('外部浏览器没有页签。')
|
|
524
|
+
return tabs[tabs.length - 1].id
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** Forward one pointer/key event from the sidebar mirror. */
|
|
528
|
+
async input(tabId, event = {}) {
|
|
529
|
+
const targetId = ExternalBrowser.targetOf(tabId) ?? (await this.activeTarget({}))
|
|
530
|
+
const session = await this.session(targetId)
|
|
531
|
+
const kind = event.kind
|
|
532
|
+
if (kind === 'mouse') {
|
|
533
|
+
const type = event.type === 'down' ? 'mousePressed' : event.type === 'up' ? 'mouseReleased' : 'mouseMoved'
|
|
534
|
+
await session.send('Input.dispatchMouseEvent', {
|
|
535
|
+
type,
|
|
536
|
+
x: Number(event.x ?? 0),
|
|
537
|
+
y: Number(event.y ?? 0),
|
|
538
|
+
button: event.button ?? 'left',
|
|
539
|
+
clickCount: type === 'mouseMoved' ? 0 : Number(event.clickCount ?? 1),
|
|
540
|
+
})
|
|
541
|
+
return { sent: type }
|
|
542
|
+
}
|
|
543
|
+
if (kind === 'wheel') {
|
|
544
|
+
await session.send('Input.dispatchMouseEvent', {
|
|
545
|
+
type: 'mouseWheel',
|
|
546
|
+
x: Number(event.x ?? 0),
|
|
547
|
+
y: Number(event.y ?? 0),
|
|
548
|
+
deltaX: Number(event.deltaX ?? 0),
|
|
549
|
+
deltaY: Number(event.deltaY ?? 0),
|
|
550
|
+
})
|
|
551
|
+
return { sent: 'wheel' }
|
|
552
|
+
}
|
|
553
|
+
if (kind === 'key') {
|
|
554
|
+
if (typeof event.text === 'string' && event.text !== '') {
|
|
555
|
+
await session.send('Input.insertText', { text: event.text })
|
|
556
|
+
return { sent: 'text' }
|
|
557
|
+
}
|
|
558
|
+
const key = String(event.key ?? '')
|
|
559
|
+
const code = String(event.code ?? '')
|
|
560
|
+
await session.send('Input.dispatchKeyEvent', { type: 'keyDown', key, code })
|
|
561
|
+
await session.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code })
|
|
562
|
+
return { sent: 'key' }
|
|
563
|
+
}
|
|
564
|
+
return { sent: 'ignored' }
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
async shutdown(kill = false) {
|
|
568
|
+
for (const [, session] of this.sessions) session.close()
|
|
569
|
+
this.sessions.clear()
|
|
570
|
+
if (kill === true) {
|
|
571
|
+
try { this.process?.kill() } catch { /* already gone */ }
|
|
572
|
+
}
|
|
573
|
+
this.port = 0
|
|
574
|
+
this.process = null
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** `document.querySelector` helper shared by click/type. */
|
|
579
|
+
function targetSnippet(args) {
|
|
580
|
+
const selector = args.selector === undefined ? null : JSON.stringify(String(args.selector))
|
|
581
|
+
const ref = args.ref === undefined ? null : JSON.stringify(String(args.ref))
|
|
582
|
+
return `(() => {
|
|
583
|
+
if (${selector} !== null) return document.querySelector(${selector})
|
|
584
|
+
if (${ref} !== null) return document.querySelector('[data-dsb-ref="' + ${ref} + '"]')
|
|
585
|
+
return document.body
|
|
586
|
+
})()`
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
async function elementRect(session, args) {
|
|
590
|
+
const rect = await session.evaluate(`(() => {
|
|
591
|
+
const element = ${targetSnippet(args)}
|
|
592
|
+
if (element === null) return null
|
|
593
|
+
const box = element.getBoundingClientRect()
|
|
594
|
+
return { x: box.x, y: box.y, width: box.width, height: box.height }
|
|
595
|
+
})()`)
|
|
596
|
+
if (rect === null || rect === undefined) throw new Error('未找到要操作的元素。')
|
|
597
|
+
return rect
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function focusSnippet(args) {
|
|
601
|
+
return `(() => {
|
|
602
|
+
const element = ${targetSnippet(args)}
|
|
603
|
+
if (element === null) return false
|
|
604
|
+
element.focus()
|
|
605
|
+
if ('value' in element && element.value !== undefined) {
|
|
606
|
+
element.value = ''
|
|
607
|
+
element.dispatchEvent(new Event('input', { bubbles: true }))
|
|
608
|
+
}
|
|
609
|
+
return true
|
|
610
|
+
})()`
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** Accessible-ish tree with stable refs, mirroring the built-in channel. */
|
|
614
|
+
async function snapshot(session) {
|
|
615
|
+
const value = await session.evaluate(`(() => {
|
|
616
|
+
let index = 0
|
|
617
|
+
const lines = []
|
|
618
|
+
const walk = (node, depth) => {
|
|
619
|
+
if (node === null || node.nodeType !== 1) return
|
|
620
|
+
const tag = node.tagName.toLowerCase()
|
|
621
|
+
if (['script', 'style', 'noscript', 'template'].includes(tag) === true) return
|
|
622
|
+
const box = node.getBoundingClientRect()
|
|
623
|
+
if (box.width < 1 || box.height < 1) return
|
|
624
|
+
const label = (node.innerText || node.getAttribute('aria-label') || node.getAttribute('placeholder') || '').trim().split('\\n')[0].slice(0, 80)
|
|
625
|
+
index += 1
|
|
626
|
+
node.setAttribute('data-dsb-ref', 'e' + index)
|
|
627
|
+
lines.push('e' + index + ' <' + tag + '>' + (label === '' ? '' : ' "' + label + '"'))
|
|
628
|
+
for (const child of node.children) walk(child, depth + 1)
|
|
629
|
+
}
|
|
630
|
+
if (document.body !== null) walk(document.body, 0)
|
|
631
|
+
return { url: location.href, title: document.title, lines: lines.slice(0, 400) }
|
|
632
|
+
})()`)
|
|
633
|
+
const lines = Array.isArray(value?.lines) ? value.lines : []
|
|
634
|
+
return { url: value?.url ?? '', title: value?.title ?? '', text: lines.join('\\n'), lineCount: lines.length }
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Write a small marker file so the UI can show which browser is in use. */
|
|
638
|
+
export async function writeState(file, state) {
|
|
639
|
+
await mkdir(join(file, '..'), { recursive: true })
|
|
640
|
+
await writeFile(file, JSON.stringify(state, null, 2), 'utf8')
|
|
641
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Shared browser",
|
|
4
|
+
"description": "Turns the DSH Browser tab (right sidebar → Browser) into a desktop browser shared with the agent: back/forward/reload, zoom, find in page, device emulation, history, bookmarks, screenshots, region screenshots, element picking, agent-readable element comments, console/network capture, a DevTools panel (F12), and one-click hand-off of screenshots, elements and logs to the chat draft. The agent drives the very same tab through the bb_* tools (bb_status, bb_open, bb_snapshot, bb_click, …); when a real fingerprint or persistent login is needed the same address can be opened in the local Edge/Chrome over CDP (external channel, ext: tabs) with a live mirror in the sidebar. On Cloudflare-style verification walls the tools tell the agent to stop and leave the check to the user instead of trying to bypass it. The in-app tab still runs in the shell sandbox guest: site permissions, downloads and popups stay denied, and the native DevTools window cannot open in a packaged shell, so the plugin ships its own console/elements/network panel. Disabling the bundle restores the built-in Browser tab and leaves nothing behind."
|
|
5
|
+
},
|
|
6
|
+
"browser": {
|
|
7
|
+
"label": "Browser"
|
|
8
|
+
}
|
|
9
|
+
}
|
package/locale/zh.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "共享浏览器",
|
|
4
|
+
"description": "把 DSH 的 Browser 页签(右侧栏 → 浏览器)变成与 Agent 共享的桌面浏览器:前进/后退/刷新、缩放、页内查找、设备仿真、历史记录、收藏夹、截图、区域截图、元素选取、Agent 可读的元素评论、控制台/网络采集、开发者工具面板(F12),以及把截图、元素和日志添加到聊天。Agent 通过 bb_* 工具(bb_status、bb_open、bb_snapshot、bb_click……)驱动你正在看的同一个页签;需要真实指纹或持久登录时,可以把同一地址交给本机的 Edge/Chrome(外部通道,ext: 页签),侧栏提供实时镜面。遇到 Cloudflare 一类人机验证时,工具会提示 Agent 停手、交给用户完成,而不是尝试绕过。内置页签仍运行在桌面壳自带的沙箱 guest 中:站点权限、下载和弹窗保持拒绝,原生 DevTools 窗口因打包壳禁用而不会打开——插件改为提供自己的控制台/元素/网络面板。关闭该 bundle 即恢复原生 Browser 页签,不残留改动。"
|
|
5
|
+
},
|
|
6
|
+
"browser": {
|
|
7
|
+
"label": "浏览器"
|
|
8
|
+
}
|
|
9
|
+
}
|