dsh-chrome-bridge 1.13.0 → 1.15.0

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/client.js CHANGED
@@ -40,7 +40,7 @@ window.__ModuleLoader__.load({
40
40
  connected: '已连接',
41
41
  paused: '已暂停',
42
42
  disconnected: '未连接',
43
- unsupported: '目前只支持 macOS',
43
+ unsupported: '目前只支持 macOS、Windows、Linux',
44
44
  summaryOn: '已连接 · 正在控制 %n 个标签页',
45
45
  summaryIdle: '已连接,没有在控制的标签页',
46
46
  summaryOff: '还没连上 Chrome,点开看怎么装',
@@ -70,6 +70,7 @@ window.__ModuleLoader__.load({
70
70
  openInstall: '帮我打开安装页',
71
71
  installOpened: '已在 Chrome 里打开扩展页',
72
72
  pathCopied: ',文件夹路径也复制好了(文件框里按 ⌘⇧G 再 ⌘V)',
73
+ pathCopiedWin: ',文件夹路径也复制好了(粘进文件框顶上的地址栏、回车)',
73
74
  plugin: '插件 v%v',
74
75
  guide: '使用说明',
75
76
  failed: '操作没成功:%e',
@@ -81,7 +82,7 @@ window.__ModuleLoader__.load({
81
82
  connected: 'Connected',
82
83
  paused: 'Paused',
83
84
  disconnected: 'Not connected',
84
- unsupported: 'macOS only for now',
85
+ unsupported: 'Supports macOS, Windows and Linux only',
85
86
  summaryOn: 'Connected · controlling %n tab(s)',
86
87
  summaryIdle: 'Connected, no tabs under control',
87
88
  summaryOff: 'Not connected to Chrome yet — open for setup steps',
@@ -111,6 +112,7 @@ window.__ModuleLoader__.load({
111
112
  openInstall: 'Open the install page for me',
112
113
  installOpened: 'Opened the extensions page in Chrome',
113
114
  pathCopied: '; the folder path is on the clipboard (⌘⇧G then ⌘V in the file picker)',
115
+ pathCopiedWin: '; the folder path is on the clipboard (paste it into the file picker\'s address bar)',
114
116
  plugin: 'Plugin v%v',
115
117
  guide: 'Guide',
116
118
  failed: 'That did not work: %e',
@@ -206,7 +208,7 @@ window.__ModuleLoader__.load({
206
208
 
207
209
  function phaseOf(s) {
208
210
  if (!s) return 'checking'
209
- if (s.platform && s.platform !== 'darwin') return 'unsupported'
211
+ if (s.platform && !['darwin', 'win32', 'linux'].includes(s.platform)) return 'unsupported'
210
212
  if (!s.connected) return 'off'
211
213
  return s.paused ? 'paused' : 'on'
212
214
  }
@@ -274,7 +276,7 @@ window.__ModuleLoader__.load({
274
276
  h('li', null, t('setupStep3'))),
275
277
  state.store ? null : h('p', { className: 'dcb-hint' }, t('setupStoreAlt'))),
276
278
  state.store ? null : h(Btn, { primary: true, disabled: busy, onClick: () => run({ action: 'install', via: 'store' }, t('storeOpened')) }, t('openStore')),
277
- h(Btn, { primary: !!state.store, disabled: busy, onClick: () => run({ action: 'install' }, (s) => t('installOpened') + (s.assist && s.assist.clipboard ? t('pathCopied') : '')) }, t('openInstall')))) : null
279
+ h(Btn, { primary: !!state.store, disabled: busy, onClick: () => run({ action: 'install' }, (s) => t('installOpened') + (s.assist && s.assist.clipboard ? t(state.platform === 'win32' ? 'pathCopiedWin' : 'pathCopied') : '')) }, t('openInstall')))) : null
278
280
 
279
281
  const switches = state && state.connected ? h('div', { className: 'dcb-card' },
280
282
  h('div', { className: 'dcb-row' },
package/download.js ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * 下载文件(browser_download):带着用户在 Chrome 里的登录状态,把链接指向的文件存到本机。
3
+ *
4
+ * 只用宿主已有的 eval / cdp op —— 不改扩展,不加扩展权限(加权限得重新过商店审核,用户还要再点一次同意)。
5
+ *
6
+ * 两条路,先走第一条:
7
+ * ① 页面里 fetch(credentials: include):和用户点链接一样走 Chrome 的网络(登录、代理、证书都一样),
8
+ * 文件先留在页面里,再分块用 base64 读回来写盘。blob: / data: 链接只能走这条
9
+ * ② 跨站被 CORS / CSP 拦了:插件自己下,Cookie 用 CDP 的 Network.getCookies 按网址取(每一跳重定向都重取)
10
+ */
11
+
12
+ import fs from 'node:fs'
13
+ import os from 'node:os'
14
+ import path from 'node:path'
15
+ import crypto from 'node:crypto'
16
+ import { refElementJs } from './refs.js'
17
+
18
+ const CHUNK = 2 * 1024 * 1024 // 页面里每次读回 2MB(base64 后约 2.7MB)
19
+ const PAGE_MAX = 300 * 1024 * 1024 // 页面里最多暂存这么大,再大走插件直接下
20
+ const TIMEOUT_MS = 10 * 60 * 1000
21
+
22
+ const EXT = {
23
+ 'application/pdf': '.pdf', 'text/csv': '.csv', 'application/zip': '.zip', 'application/json': '.json',
24
+ 'text/plain': '.txt', 'text/html': '.html', 'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif',
25
+ 'image/webp': '.webp', 'image/svg+xml': '.svg', 'video/mp4': '.mp4', 'audio/mpeg': '.mp3',
26
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
27
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
28
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx',
29
+ 'application/vnd.ms-excel': '.xls', 'application/msword': '.doc',
30
+ }
31
+
32
+ /** Content-Disposition 里的文件名:filename*=UTF-8''… 优先,再 filename="…" */
33
+ export function dispositionName(header) {
34
+ const h = String(header || '')
35
+ const star = /filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(h)
36
+ if (star) { try { return decodeURIComponent(star[2].trim().replace(/^"|"$/g, '')) } catch {} }
37
+ const plain = /filename\s*=\s*("((?:[^"\\]|\\.)*)"|[^;]+)/i.exec(h)
38
+ if (plain) return (plain[2] !== undefined ? plain[2].replace(/\\(.)/g, '$1') : plain[1]).trim()
39
+ return ''
40
+ }
41
+
42
+ /** 文件名能安全落盘:去掉路径分隔符、控制字符、开头的点(不做成隐藏文件),太长截断 */
43
+ export function safeName(name) {
44
+ let n = String(name || '').replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').replace(/^[.\s]+/, '').trim()
45
+ if (n.length > 180) {
46
+ const ext = path.extname(n).slice(0, 12)
47
+ n = n.slice(0, 180 - ext.length) + ext
48
+ }
49
+ return n
50
+ }
51
+
52
+ /** 起名:给的名字 > 服务器给的 > 链接的 download 属性 > 网址最后一段;没扩展名就按类型补 */
53
+ export function pickName({ filename, disposition, suggested, url, type }) {
54
+ let fromUrl = ''
55
+ try {
56
+ const u = new URL(url)
57
+ if (u.protocol === 'http:' || u.protocol === 'https:') fromUrl = decodeURIComponent(u.pathname.split('/').pop() || '')
58
+ } catch {}
59
+ let n = safeName(filename) || safeName(dispositionName(disposition)) || safeName(suggested) || safeName(fromUrl) || 'download'
60
+ const ext = EXT[String(type || '').split(';')[0].trim().toLowerCase()]
61
+ if (!path.extname(n) && ext) n += ext
62
+ return n
63
+ }
64
+
65
+ /** 不覆盖已有文件:重名就加「 (1)」「 (2)」… */
66
+ export function uniquePath(dir, name) {
67
+ const ext = path.extname(name)
68
+ const base = name.slice(0, name.length - ext.length)
69
+ for (let i = 0; i < 1000; i++) {
70
+ const p = path.join(dir, i ? `${base} (${i})${ext}` : name)
71
+ if (!fs.existsSync(p)) return p
72
+ }
73
+ throw new Error(`${dir} 里同名文件太多了:${name}`)
74
+ }
75
+
76
+ export function humanSize(n) {
77
+ if (n < 1024) return `${n} B`
78
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
79
+ return `${(n / 1024 / 1024).toFixed(1)} MB`
80
+ }
81
+
82
+ /** 默认存到「下载」文件夹(Windows、Mac、Linux 都是家目录下的 Downloads) */
83
+ export function downloadsDir() {
84
+ return path.join(os.homedir(), 'Downloads')
85
+ }
86
+
87
+ /** 在页面里:要下载的是哪个网址(编号 / 选择器指的链接,或直接给的网址,相对地址按页面算) */
88
+ const TARGET_JS = ({ ref, selector, url }) => `(() => {
89
+ const el = ${ref !== undefined && ref !== null ? refElementJs(ref) : selector ? `document.querySelector(${JSON.stringify(selector)})` : 'null'};
90
+ ${(ref !== undefined && ref !== null) || selector ? "if (!el) return { error: 'gone' };" : ''}
91
+ const raw = el ? (el.getAttribute('href') || el.getAttribute('src') || el.currentSrc || el.getAttribute('data') || '') : ${JSON.stringify(url || '')};
92
+ if (!raw) return { error: 'nohref', tag: el ? el.tagName.toLowerCase() : '' };
93
+ const base = el ? el.ownerDocument.baseURI : document.baseURI;
94
+ let abs;
95
+ try { abs = new URL(raw, base).href; } catch { return { error: 'badurl', raw }; }
96
+ return { url: abs, page: location.href, ua: navigator.userAgent, lang: navigator.language,
97
+ suggested: (el && el.getAttribute('download')) || '' };
98
+ })()`
99
+
100
+ /** 在页面里:fetch 下来先放在 window.__dshDl[id],回大小和头 */
101
+ const FETCH_JS = (id, url) => `(async () => {
102
+ try {
103
+ const r = await fetch(${JSON.stringify(url)}, { credentials: 'include' });
104
+ if (!r.ok) return { status: r.status };
105
+ const len = Number(r.headers.get('content-length')) || 0;
106
+ if (len > ${PAGE_MAX}) return { tooBig: true };
107
+ const buf = new Uint8Array(await r.arrayBuffer());
108
+ if (buf.length > ${PAGE_MAX}) return { tooBig: true };
109
+ (window.__dshDl || (window.__dshDl = {}))[${JSON.stringify(id)}] = buf;
110
+ return { size: buf.length, type: r.headers.get('content-type') || '', disposition: r.headers.get('content-disposition') || '', finalUrl: r.url };
111
+ } catch (e) {
112
+ return { failed: String(e && e.message || e) };
113
+ }
114
+ })()`
115
+
116
+ const CHUNK_JS = (id, offset) => `(() => {
117
+ const b = window.__dshDl && window.__dshDl[${JSON.stringify(id)}];
118
+ if (!b) return null;
119
+ const part = b.subarray(${offset}, ${offset + CHUNK});
120
+ let s = '';
121
+ for (let i = 0; i < part.length; i += 0x8000) s += String.fromCharCode.apply(null, part.subarray(i, i + 0x8000));
122
+ return btoa(s);
123
+ })()`
124
+
125
+ const DROP_JS = (id) => `(() => { if (window.__dshDl) delete window.__dshDl[${JSON.stringify(id)}]; return true; })()`
126
+
127
+ /** ① 页面里取:成功回 { size, type, disposition, finalUrl };被拦了回 null(换第二条路) */
128
+ async function viaPage(call, tabId, url, file) {
129
+ const id = crypto.randomUUID()
130
+ const r = (await call('eval', { tabId, expression: FETCH_JS(id, url), awaitPromise: true, userGesture: false }, TIMEOUT_MS)).value || {}
131
+ if (r.status) throw new Error(`下载失败:服务器回 HTTP ${r.status}`)
132
+ if (r.failed || r.tooBig) return null
133
+ try {
134
+ const fd = fs.openSync(file, 'w')
135
+ try {
136
+ for (let off = 0; off < r.size; off += CHUNK) {
137
+ const b64 = (await call('eval', { tabId, expression: CHUNK_JS(id, off), userGesture: false })).value
138
+ if (typeof b64 !== 'string') throw new Error('页面跳走了,下载中断')
139
+ fs.writeSync(fd, Buffer.from(b64, 'base64'))
140
+ }
141
+ } finally {
142
+ fs.closeSync(fd)
143
+ }
144
+ } finally {
145
+ call('eval', { tabId, expression: DROP_JS(id), userGesture: false }).catch(() => {})
146
+ }
147
+ return r
148
+ }
149
+
150
+ /** ② 插件自己下,带上 Chrome 里这个网址的 Cookie(重定向每一跳都按新网址取) */
151
+ async function viaNode(call, tabId, target, file, fetchImpl = globalThis.fetch) {
152
+ const ctl = new AbortController()
153
+ const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS)
154
+ try {
155
+ let url = target.url
156
+ let referer = target.page
157
+ for (let hop = 0; hop < 10; hop++) {
158
+ let cookie = ''
159
+ try {
160
+ const r = await call('cdp', { tabId, method: 'Network.getCookies', params: { urls: [url] } })
161
+ cookie = ((r.result && r.result.cookies) || []).map((c) => `${c.name}=${c.value}`).join('; ')
162
+ } catch {}
163
+ const res = await fetchImpl(url, {
164
+ redirect: 'manual',
165
+ signal: ctl.signal,
166
+ headers: {
167
+ 'user-agent': target.ua || 'Mozilla/5.0',
168
+ 'accept-language': target.lang || 'en',
169
+ accept: '*/*',
170
+ ...(referer ? { referer } : {}),
171
+ ...(cookie ? { cookie } : {}),
172
+ },
173
+ })
174
+ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
175
+ referer = url
176
+ url = new URL(res.headers.get('location'), url).href
177
+ continue
178
+ }
179
+ if (!res.ok || !res.body) throw new Error(`下载失败:服务器回 HTTP ${res.status}`)
180
+ const out = fs.createWriteStream(file)
181
+ let size = 0
182
+ try {
183
+ for await (const chunk of res.body) {
184
+ size += chunk.length
185
+ if (!out.write(chunk)) await new Promise((r) => out.once('drain', r))
186
+ }
187
+ } finally {
188
+ await new Promise((r) => out.end(r))
189
+ }
190
+ return { size, type: res.headers.get('content-type') || '', disposition: res.headers.get('content-disposition') || '', finalUrl: url }
191
+ }
192
+ throw new Error('下载失败:重定向太多次')
193
+ } finally {
194
+ clearTimeout(timer)
195
+ }
196
+ }
197
+
198
+ /**
199
+ * @returns {{ file, size, type, via }}
200
+ * @param opts.dir 存到哪个文件夹(调用方已经定好)
201
+ */
202
+ export async function download(call, tabId, { url, ref, selector, filename, dir }, deps = {}) {
203
+ if ((ref === undefined || ref === null) && !selector && !url) throw new Error('要给出 url、ref 或 selector 之一')
204
+ const target = (await call('eval', { tabId, expression: TARGET_JS({ ref, selector, url }), userGesture: false })).value
205
+ if (!target) throw new Error('页面没回应(可能刚跳转,重试一次)')
206
+ if (target.error === 'gone') throw new Error(ref !== undefined && ref !== null ? `编号 ${ref} 已失效——重新 browser_read what=snapshot` : `没找到元素: ${selector}`)
207
+ if (target.error === 'nohref') throw new Error(`这个 ${target.tag} 元素没有链接地址(href / src)。是按钮的话,先 browser_click 它,看会不会打开下载链接`)
208
+ if (target.error === 'badurl') throw new Error(`网址不对:${target.raw}`)
209
+ const proto = new URL(target.url).protocol
210
+ if (!['http:', 'https:', 'blob:', 'data:'].includes(proto)) throw new Error(`不支持这种网址:${proto}`)
211
+
212
+ fs.mkdirSync(dir, { recursive: true })
213
+ const part = path.join(dir, `.dsh-download-${crypto.randomUUID()}.part`)
214
+ try {
215
+ let via = 'page'
216
+ let meta = await viaPage(call, tabId, target.url, part)
217
+ if (!meta) {
218
+ if (proto === 'blob:' || proto === 'data:') throw new Error('页面里读不出这个文件(blob 链接可能已经失效:重新点一次生成它的按钮再试)')
219
+ via = 'direct'
220
+ meta = await viaNode(call, tabId, target, part, deps.fetch)
221
+ }
222
+ const name = pickName({ filename, disposition: meta.disposition, suggested: target.suggested, url: meta.finalUrl || target.url, type: meta.type })
223
+ const file = uniquePath(dir, name)
224
+ fs.renameSync(part, file)
225
+ return { file, size: meta.size, type: meta.type, via }
226
+ } finally {
227
+ try { fs.rmSync(part, { force: true }) } catch {}
228
+ }
229
+ }
package/index.js CHANGED
@@ -18,11 +18,12 @@ import { fileURLToPath } from 'node:url'
18
18
  import { AsyncLocalStorage } from 'node:async_hooks'
19
19
  import { installImageGuard } from './image-guard.js'
20
20
  import { ensureInstalled, installHint, assistInstall, paths, extensionId } from './setup.js'
21
- import { snapshot, locate, focusShadow, elementBox } from './refs.js'
21
+ import { snapshot, locate, focusShadow, elementBox, selectInPage, frameTexts } from './refs.js'
22
22
  import { consoleLog, networkLog, responseBody, clearLogs } from './devtools.js'
23
23
  import { historyNav, waitUntil } from './nav.js'
24
24
  import { PANEL_ROUTE, panelHandler } from './panel.js'
25
25
  import { drag } from './drag.js'
26
+ import { download, downloadsDir, humanSize } from './download.js'
26
27
 
27
28
  /**
28
29
  * 这里刻意不 import 任何外部包——不碰 `@deepseek-ai/dsh-tools`。
@@ -35,18 +36,29 @@ import { drag } from './drag.js'
35
36
  */
36
37
 
37
38
  // socket / token / 日志都在只有当前用户进得去的 /tmp/dsh-bridge-<uid>/(和宿主、cb 同一个约定):
38
- // /tmp 人人可写,固定文件名会被别的用户抢先占位,或者用软链接把写入引到别处
39
+ // /tmp 人人可写,固定文件名会被别的用户抢先占位,或者用软链接把写入引到别处。
40
+ // Windows:目录是 %TEMP%\dsh-bridge(本来就只属于当前用户);没有 Unix socket,宿主每次起一个
41
+ // 随机名字的命名管道,名字写在 token 文件第二行
42
+ const WIN = process.platform === 'win32'
39
43
  const UID = typeof process.getuid === 'function' ? process.getuid() : null
40
- const DIR = process.env.DSH_BRIDGE_DIR || `/tmp/dsh-bridge-${UID ?? 'user'}`
41
- const SOCK = process.env.DSH_BRIDGE_SOCK || path.join(DIR, 'dsh-bridge.sock')
44
+ const DIR = process.env.DSH_BRIDGE_DIR || (WIN ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${UID ?? 'user'}`)
42
45
  const TOKEN_FILE = process.env.DSH_BRIDGE_TOKEN || path.join(DIR, 'dsh-bridge.token')
46
+ const FIXED_SOCK = process.env.DSH_BRIDGE_SOCK || (WIN ? null : path.join(DIR, 'dsh-bridge.sock'))
47
+
48
+ function tokenLines() {
49
+ try { return fs.readFileSync(TOKEN_FILE, 'utf8').split('\n').map((l) => l.trim()) } catch { return [] }
50
+ }
51
+ /** 宿主在听的地址(Windows 上每次启动都换) */
52
+ function hostSock() { return FIXED_SOCK || tokenLines()[1] || null }
53
+ /** 宿主起没起:socket 文件在不在;Windows 看 token 文件里有没有管道名(宿主退出时会删掉) */
54
+ function hostUp() { const s = hostSock(); return Boolean(s) && (WIN || fs.existsSync(s)) }
43
55
  const TRACE = path.join(DIR, 'plugin.log')
44
56
  const { O_WRONLY, O_CREAT, O_APPEND, O_NOFOLLOW } = fs.constants
45
57
 
46
58
  /** 目录必须是自己的真目录(不是软链接)、别人进不去:不然连上的可能是别人摆的假宿主 */
47
59
  function checkDir(dir) {
48
60
  const st = fs.lstatSync(dir)
49
- if (!st.isDirectory() || (UID !== null && st.uid !== UID) || (st.mode & 0o077)) {
61
+ if (!st.isDirectory() || (!WIN && ((UID !== null && st.uid !== UID) || (st.mode & 0o077)))) {
50
62
  throw new Error(`${dir} 不是只属于当前用户的目录,拒绝使用`)
51
63
  }
52
64
  }
@@ -137,6 +149,7 @@ function hintOf(name, a = {}) {
137
149
  return `${a.gone ? '等消失 ' : ''}${a.text ? `「${short(a.text, 20)}」` : a.url ? `网址 ${short(a.url, 30)}` : short(a.selector, 30)}`
138
150
  case 'browser_dialog': return a.action || ''
139
151
  case 'browser_drag': return `${el('from')} → ${el('to')}`
152
+ case 'browser_download': return a.ref !== undefined && a.ref !== null ? `[${a.ref}]` : short(a.selector || a.url || '', 50)
140
153
  case 'browser_devtools': return [a.action, a.level && a.level !== 'all' ? a.level : '', a.filter ? `「${short(a.filter, 16)}」` : ''].filter(Boolean).join(' ')
141
154
  default: return ''
142
155
  }
@@ -180,11 +193,11 @@ function firstAid() {
180
193
  if (aided) return ''
181
194
  aided = true
182
195
  try {
183
- if (fs.existsSync(SOCK)) return ''
196
+ if (hostUp()) return ''
184
197
  const r = assistInstall()
185
198
  const notes = []
186
199
  if (r.opened) notes.push(`我已经帮你把 chrome://extensions 打开(后台标签页)${r.store ? ',看一眼 DSH Bridge 是不是启用着' : ''}`)
187
- if (r.clipboard) notes.push('扩展文件夹的路径已经复制到剪贴板(文件框里 ⌘⇧G 再 ⌘V 回车就到)')
200
+ if (r.clipboard) notes.push(`扩展文件夹的路径已经复制到剪贴板(${WIN ? '粘进文件框顶上的地址栏、回车' : '文件框里 ⌘⇧G 再 ⌘V 回车'}就到)`)
188
201
  return notes.length ? `\n(${notes.join(';')})` : ''
189
202
  } catch {
190
203
  return ''
@@ -199,12 +212,12 @@ const HINT = () => installHint() + firstAid()
199
212
  /** 一次请求一个连接,协议是换行分隔的 JSON(和 cb CLI 完全一致)。 */
200
213
  function call(op, args = {}, timeoutMs = 60000) {
201
214
  return new Promise((resolve, reject) => {
202
- if (!fs.existsSync(SOCK)) {
203
- return reject(new Error(`浏览器桥没在跑(找不到 ${SOCK}):Chrome 没开,或扩展还没加载。\n${HINT()}`))
215
+ const SOCK = hostSock()
216
+ if (!hostUp()) {
217
+ return reject(new Error(`浏览器桥没在跑(找不到 ${SOCK || TOKEN_FILE}):Chrome 没开,或扩展还没加载。\n${HINT()}`))
204
218
  }
205
- try { checkDir(path.dirname(SOCK)) } catch (e) { return reject(e) }
206
- let token = null
207
- try { token = fs.readFileSync(TOKEN_FILE, 'utf8').trim() } catch {}
219
+ try { checkDir(WIN ? DIR : path.dirname(SOCK)) } catch (e) { return reject(e) }
220
+ const token = tokenLines()[0] || null
208
221
  const id = crypto.randomUUID()
209
222
  const sock = net.connect(SOCK)
210
223
  let acc = ''
@@ -293,6 +306,7 @@ async function emulateFocus(tabId) {
293
306
  * 只发 reload,不发别的。
294
307
  */
295
308
  function nudgeLegacyHost() {
309
+ if (WIN) return
296
310
  try {
297
311
  const legacy = '/tmp/dsh-bridge.sock'
298
312
  const tokenFile = '/tmp/dsh-bridge.token'
@@ -316,7 +330,7 @@ function nudgeLegacyHost() {
316
330
  * reload 只会白白掐断宿主一下;而商店版本号常常落后本地,不跳过就会每次启动都重载。
317
331
  */
318
332
  async function refreshExtension() {
319
- if (!fs.existsSync(SOCK)) {
333
+ if (!hostUp()) {
320
334
  if (!process.env.DSH_BRIDGE_SOCK) nudgeLegacyHost()
321
335
  return
322
336
  }
@@ -450,7 +464,7 @@ export function apply(ctx, config) {
450
464
  sub.effect(() => sub.webServer.register({
451
465
  kind: 'exact',
452
466
  path: PANEL_ROUTE,
453
- handler: panelHandler({ call, sock: SOCK, origin: () => sub.webServer.getOrigin(), trace }),
467
+ handler: panelHandler({ call, sock: hostUp, origin: () => sub.webServer.getOrigin(), trace }),
454
468
  }), 'chrome-bridge: settings panel route')
455
469
  trace(`设置页路由已挂上 ${PANEL_ROUTE}`)
456
470
  })
@@ -533,7 +547,7 @@ export function apply(ctx, config) {
533
547
  name: 'browser_read',
534
548
  description:
535
549
  '读页面内容。what=snapshot 列出页面上能点/能填的元素,每个带编号 [N]——要操作页面时先调它,' +
536
- '之后 browser_click / browser_input 直接传 ref=N,比猜选择器稳;' +
550
+ '之后 browser_click / browser_input 直接传 ref=N,比猜选择器稳(同源 iframe 里的元素也会列出、也能按编号操作);' +
537
551
  'text 取可见文字(抓内容首选);html 取外层 HTML;' +
538
552
  'attr 取某个属性;info 取标题/URL/视口,并会告诉你有没有 alert 弹窗挡着(挡着的话先调 browser_dialog)。',
539
553
  parameters: {
@@ -554,7 +568,16 @@ export function apply(ctx, config) {
554
568
  }
555
569
  case 'text': {
556
570
  const r = await call('text', { tabId, selector: args.selector || undefined, limit })
557
- return { text: clip(r.text, limit) || '(页面没有可见文字)' }
571
+ let text = r.text || ''
572
+ // 整页读时把同源 iframe 里的字接在后面(innerText 不含框架内容);跨站的给一行提示
573
+ if (!args.selector) {
574
+ for (const f of await frameTexts(call, tabId).catch(() => [])) {
575
+ text += f.cross
576
+ ? `\n\n[iframe] ${f.src}(跨站框架,读不到里面的字:browser_screenshot 看)`
577
+ : f.text ? `\n\n[iframe] ${f.src}\n${f.text}` : ''
578
+ }
579
+ }
580
+ return { text: clip(text.trim(), limit) || '(页面没有可见文字)' }
558
581
  }
559
582
  case 'html': {
560
583
  const r = await call('html', { tabId, selector: args.selector || 'body', limit })
@@ -607,7 +630,7 @@ export function apply(ctx, config) {
607
630
  const r = await call('clickEl', { tabId, selector: el.selector, ...withCursor() })
608
631
  return { text: `已点击 [${args.ref}] ${r.target.tag}「${r.target.text}」@ (${r.x}, ${r.y})` }
609
632
  }
610
- // shadow DOM 里的元素(选择器够不着),或者要双击:按坐标点
633
+ // shadow DOM / iframe 里的元素(选择器够不着),或者要双击:按坐标点
611
634
  const r = await call('click', { tabId, x: el.x, y: el.y, clickCount: count, ...withCursor() })
612
635
  return { text: `已点击 [${args.ref}] ${el.tag}「${el.text}」@ (${r.x}, ${r.y})${count > 1 ? ` ×${count}` : ''}` }
613
636
  }
@@ -655,14 +678,14 @@ export function apply(ctx, config) {
655
678
  async execute(args, exec) {
656
679
  const tabId = await resolveTab(args.tab)
657
680
  if (args.action !== 'scroll') await emulateFocus(tabId)
658
- // 有编号就先把它换成选择器;shadow DOM 里的元素换不成,下面各自按坐标/页内处理
681
+ // 有编号就先把它换成选择器;shadow DOM / iframe 里的元素换不成,下面各自按坐标/页内处理
659
682
  const hasRef = args.ref !== undefined && args.ref !== null &&
660
683
  ['type', 'select', 'upload', 'focus', 'hover'].includes(args.action)
661
684
  const el = hasRef ? await locate(call, tabId, args.ref) : null
662
685
  const selector = el ? el.selector : args.selector
663
686
  const target = hasRef ? `[${args.ref}]` : args.selector
664
687
  const noShadow = (what) => {
665
- if (el && el.shadow) throw new Error(`编号 ${args.ref} 在 shadow DOM 里,${what} 暂时不支持按编号——改用 browser_eval`)
688
+ if (el && el.shadow) throw new Error(`编号 ${args.ref} 在 shadow DOM 或 iframe 里,${what} 暂时不支持按编号——改用 browser_eval`)
666
689
  }
667
690
  switch (args.action) {
668
691
  case 'type': {
@@ -683,7 +706,10 @@ export function apply(ctx, config) {
683
706
  case 'select': {
684
707
  if (!selector && !el) throw new Error('action=select 需要 ref 或 selector')
685
708
  if (args.value === undefined) throw new Error('action=select 需要 value')
686
- noShadow('select')
709
+ if (el && el.shadow) {
710
+ const r = await selectInPage(call, tabId, args.ref, args.value)
711
+ return { text: `已选择「${r.label}」(${r.value})` }
712
+ }
687
713
  const r = await call('select', { tabId, selector, value: args.value })
688
714
  return { text: `已选择「${r.label}」(${r.value})` }
689
715
  }
@@ -800,9 +826,15 @@ export function apply(ctx, config) {
800
826
  // 自己取框再直接截:扩展的 shot(selector) 取框只等 rAF,后台标签页里会卡满 15 秒
801
827
  const box = await elementBox(call, tabId, { ref: hasRef ? args.ref : undefined, selector: args.selector })
802
828
  if (!box || box.width < 1 || box.height < 1) throw new Error('这个元素没有大小(可能被隐藏了),截不了')
803
- const shot = await call('cdp', {
829
+ const capture = () => call('cdp', {
804
830
  tabId, method: 'Page.captureScreenshot', params: { format, clip: { ...box, scale: 1 } },
805
831
  }, 90000)
832
+ // Edge 无头偶尔第一次带 clip 的截图一直不回(之后的都正常):15 秒没回就再截一次,先发的那个结果不要了
833
+ const first = capture()
834
+ first.catch(() => {})
835
+ let timer
836
+ const late = new Promise((r) => { timer = setTimeout(r, 15000, null) })
837
+ const shot = (await Promise.race([first, late]).finally(() => clearTimeout(timer))) || (await capture())
806
838
  const t = (await call('tabs')).find((x) => x.id === tabId)
807
839
  r = { data: shot.result.data, format, url: t && t.url, title: t && t.title }
808
840
  } else {
@@ -967,6 +999,46 @@ export function apply(ctx, config) {
967
999
  },
968
1000
  }),
969
1001
 
1002
+ // ── 下载 ────────────────────────────────────────────────────────────────
1003
+ defineTool({
1004
+ name: 'browser_download',
1005
+ description:
1006
+ '把链接指向的文件(发票、报表、PDF、图片……)下载到本机,带着用户在 Chrome 里的登录状态。' +
1007
+ '给 ref(snapshot 里的链接编号)、selector 或 url 三选一;相对地址按页面算,blob: / data: 链接也行。' +
1008
+ '默认存进「下载」文件夹,to=workdir 存进会话工作目录;同名不覆盖,自动加 (1)。' +
1009
+ '下载按钮不是链接(点了才生成文件)的话:先 browser_click 它,再用 browser_devtools action=network 找到文件网址,交给这里。',
1010
+ parameters: {
1011
+ ref: { type: 'integer', description: REF_DESC },
1012
+ selector: { type: 'string', description: 'CSS 选择器(指向 a / img / video / source 等带地址的元素)' },
1013
+ url: { type: 'string', description: '要下载的网址,可以是相对地址' },
1014
+ tab: { type: 'string', description: TAB_DESC },
1015
+ filename: { type: 'string', description: '存成什么名字;省略时用服务器给的名字或网址里的名字' },
1016
+ to: { type: 'string', enum: ['downloads', 'workdir'], description: 'downloads(默认)存进「下载」文件夹;workdir 存进会话工作目录' },
1017
+ },
1018
+ output: textOutput,
1019
+ presentCall: present('Download file'),
1020
+ async execute(args, exec) {
1021
+ const tabId = await resolveTab(args.tab)
1022
+ let dir = downloadsDir()
1023
+ if (args.to === 'workdir') {
1024
+ dir = sessionCwd(exec)
1025
+ if (!dir) throw new Error('拿不到会话工作目录,去掉 to=workdir 存进「下载」文件夹')
1026
+ }
1027
+ const r = await download(call, tabId, {
1028
+ url: args.url || undefined,
1029
+ ref: args.ref ?? undefined,
1030
+ selector: args.selector || undefined,
1031
+ filename: args.filename || undefined,
1032
+ dir,
1033
+ })
1034
+ const type = (r.type || '').split(';')[0].trim()
1035
+ const warn = /^text\/html/i.test(type)
1036
+ ? '\n⚠️ 下到的是网页(text/html),多半是登录页或「下载即将开始」的中转页,不是文件本身:打开看看,或者换成真正的文件链接'
1037
+ : ''
1038
+ return { text: `已下载:${r.file}(${humanSize(r.size)}${type ? `,${type}` : ''})${warn}` }
1039
+ },
1040
+ }),
1041
+
970
1042
  // ── 调试:控制台 / 网络 ──────────────────────────────────────────────────
971
1043
  defineTool({
972
1044
  name: 'browser_devtools',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-chrome-bridge",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "description": "DSH plugin: native browser_* tools that drive the Chrome you are already using — over native messaging + CDP. No WebSocket, no port, no Connect button. The native host and the MV3 extension ship inside this package and are installed automatically on first load; the only manual step left is picking ~/dsh-bridge-extension once at chrome://extensions (Chrome ≥137 has no programmatic extension install). Until then browser_* tools fail loudly with those exact steps.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,6 +38,7 @@
38
38
  "devtools.js",
39
39
  "nav.js",
40
40
  "drag.js",
41
+ "download.js",
41
42
  "panel.js",
42
43
  "cordis.patch.yml",
43
44
  "client.js",
package/panel.js CHANGED
@@ -25,7 +25,7 @@ const LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i
25
25
  /**
26
26
  * 当前状态。连不上时也要答得出「差哪一步」,所以安装情况单独给。
27
27
  * @param call - socket 调用(index.js 的 call)
28
- * @param sock - socket 路径;文件都不在就是宿主没起(= 扩展没在 Chrome 里跑)
28
+ * @param sock - 宿主在不在的判断函数(或 socket 路径);不在就是宿主没起(= 扩展没在 Chrome 里跑)
29
29
  */
30
30
  export async function panelState(call, sock) {
31
31
  const inst = installState()
@@ -36,7 +36,7 @@ export async function panelState(call, sock) {
36
36
  extDir: paths().extDir,
37
37
  connected: false,
38
38
  }
39
- if (!fs.existsSync(sock)) return base
39
+ if (!(typeof sock === 'function' ? sock() : fs.existsSync(sock))) return base
40
40
  let ver
41
41
  try {
42
42
  ver = await call('version', {}, 3000)
@@ -87,7 +87,7 @@ function readJson(req, limit = 4096) {
87
87
 
88
88
  /**
89
89
  * @param deps.call - socket 调用
90
- * @param deps.sock - socket 路径
90
+ * @param deps.sock - 宿主在不在的判断函数(或 socket 路径)
91
91
  * @param deps.origin - DSH 网页端自己的 origin(webServer.getOrigin)
92
92
  * @param deps.trace - 日志
93
93
  */
package/refs.js CHANGED
@@ -8,8 +8,9 @@
8
8
  * 编号怎么记:
9
9
  * · 元素上打 data-dsh-ref="N" → 编号本身就是选择器 [data-dsh-ref="N"],
10
10
  * 现成的 clickEl / type / select / upload / hover / shot 全都直接能用
11
- * · 开放 shadow root 里的元素 document.querySelector 够不着,另记一份 WeakRef
12
- * 在 window.__dshSnap.shadow,动作时退回按坐标操作
11
+ * · 开放 shadow root 里的元素、同源 iframe 里的元素 document.querySelector 够不着,另记一份 WeakRef
12
+ * 在 window.__dshSnap.shadow,动作时退回按坐标操作(框架里的坐标加上框架在页面上的位置)
13
+ * · 跨站的 iframe 读不到里面(浏览器不让),只列一行提示
13
14
  * · 同一个元素再快照沿用旧编号(模型手里的旧编号继续有效);页面跳转后全部失效
14
15
  */
15
16
 
@@ -32,7 +33,9 @@ const SNAPSHOT_JS = (scope, maxItems) => `(() => {
32
33
  const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'META', 'LINK']);
33
34
  const FORM = new Set(['INPUT', 'SELECT', 'TEXTAREA']);
34
35
 
35
- const cursorOf = (el) => { try { return getComputedStyle(el).cursor } catch { return '' } };
36
+ // 框架里的元素按它自己那一页算样式
37
+ const css = (el) => (el.ownerDocument.defaultView || window).getComputedStyle(el);
38
+ const cursorOf = (el) => { try { return css(el).cursor } catch { return '' } };
36
39
  const shown = (el, st) => {
37
40
  const r = el.getBoundingClientRect();
38
41
  if (r.width < 1 || r.height < 1) return false;
@@ -109,7 +112,7 @@ const SNAPSHOT_JS = (scope, maxItems) => `(() => {
109
112
  const h = el.getAttribute('href');
110
113
  if (!h || h.startsWith('javascript:')) return '';
111
114
  try {
112
- const u = new URL(h, location.href);
115
+ const u = new URL(h, el.baseURI);
113
116
  return u.origin === location.origin ? (u.pathname + u.search + u.hash) : (u.host + u.pathname);
114
117
  } catch { return h; }
115
118
  };
@@ -154,15 +157,25 @@ const SNAPSHOT_JS = (scope, maxItems) => `(() => {
154
157
  const lines = [];
155
158
  let count = 0, more = 0, scanned = 0;
156
159
  const MAX = ${Number(maxItems) || 300};
157
- const walk = (parent) => {
160
+ const walk = (parent, depth = 0) => {
158
161
  for (const el of parent.children) {
159
162
  if (++scanned > 30000) return;
160
163
  if (SKIP.has(el.tagName) || el.id === '__dsh_cursor__') continue;
161
164
  let st;
162
- try { st = getComputedStyle(el); } catch { continue; }
165
+ try { st = css(el); } catch { continue; }
163
166
  if (st.display === 'none') continue;
164
167
  if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
165
- if (shown(el, st)) lines.push('[iframe] ' + cut(el.getAttribute('src') || el.getAttribute('title') || '', 80) + '(框架里的内容没展开)');
168
+ if (!shown(el, st)) continue;
169
+ const label = '[iframe] ' + cut(el.getAttribute('src') || el.getAttribute('title') || el.getAttribute('name') || '', 80);
170
+ let doc = null;
171
+ try { doc = el.contentDocument; } catch {}
172
+ if (doc && doc.body && depth < 5) {
173
+ lines.push(label + ' ↓');
174
+ walk(doc.body, depth + 1);
175
+ lines.push('[/iframe]');
176
+ } else {
177
+ lines.push(label + '(跨站框架,读不到里面:browser_screenshot 看,按坐标 x/y 点)');
178
+ }
166
179
  continue;
167
180
  }
168
181
  const hm = /^H([1-3])$/.exec(el.tagName);
@@ -179,8 +192,8 @@ const SNAPSHOT_JS = (scope, maxItems) => `(() => {
179
192
  }
180
193
  }
181
194
  if (el.tagName === 'SELECT' || el.tagName === 'svg') continue;
182
- walk(el);
183
- if (el.shadowRoot) walk(el.shadowRoot);
195
+ walk(el, depth);
196
+ if (el.shadowRoot) walk(el.shadowRoot, depth);
184
197
  }
185
198
  };
186
199
  walk(root);
@@ -198,7 +211,8 @@ const LOCATE_JS = (ref, wantPoint) => `(async () => {
198
211
  el = w && w.deref();
199
212
  shadow = true;
200
213
  }
201
- if (!el || !el.isConnected) return { gone: true };
214
+ // 框架跳转过的话,旧元素还「连着」它那份已经作废的文档:defaultView 没了就算失效
215
+ if (!el || !el.isConnected || !el.ownerDocument.defaultView) return { gone: true };
202
216
  // 密码框的 value 绝不拿出来(会进工具结果、上光标名牌)
203
217
  const out = { shadow, selector: shadow ? null : sel, tag: el.tagName.toLowerCase(),
204
218
  text: (el.innerText || (el.type === 'password' ? '' : el.value) || el.getAttribute('aria-label') || '').replace(/\\s+/g, ' ').trim().slice(0, 60) };
@@ -206,20 +220,33 @@ const LOCATE_JS = (ref, wantPoint) => `(async () => {
206
220
  return { ...out, ...(await ${BOX_FN}(el)) };
207
221
  })()`
208
222
 
209
- /** 页内函数:滚进视口,给出中点和框。后台标签页会暂停 rAF,所以定时器兜底(和扩展里 __dsh_point 同一个坑)。 */
223
+ /**
224
+ * 页内函数:滚进视口,给出中点和框(整页视口坐标)。后台标签页会暂停 rAF,所以定时器兜底(和扩展里 __dsh_point 同一个坑)。
225
+ * 同源 iframe 里的元素:先由外到里把每层框架滚进视口,坐标再加上每层框架内容区在外层的位置(框 + 边框 + 内边距)。
226
+ */
210
227
  const BOX_FN = `(async (el) => {
228
+ const frames = [];
229
+ for (let w = el.ownerDocument.defaultView; w && w !== window && w.frameElement; w = w.parent) frames.push(w.frameElement);
230
+ for (let i = frames.length - 1; i >= 0; i--) frames[i].scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
211
231
  el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
212
232
  await new Promise((res) => { requestAnimationFrame(() => requestAnimationFrame(res)); setTimeout(res, 120); });
213
233
  const r = el.getBoundingClientRect();
214
- return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2),
215
- box: { x: r.left, y: r.top, width: r.width, height: r.height } };
234
+ let left = r.left, top = r.top;
235
+ for (const f of frames) {
236
+ const fr = f.getBoundingClientRect();
237
+ const fs = f.ownerDocument.defaultView.getComputedStyle(f);
238
+ left += fr.left + f.clientLeft + (parseFloat(fs.paddingLeft) || 0);
239
+ top += fr.top + f.clientTop + (parseFloat(fs.paddingTop) || 0);
240
+ }
241
+ return { x: Math.round(left + r.width / 2), y: Math.round(top + r.height / 2),
242
+ box: { x: left, y: top, width: r.width, height: r.height } };
216
243
  })`
217
244
 
218
- /** 页内表达式:编号 → 元素(找不到是 null)。普通元素按属性找,shadow 里的查 WeakRef 表。 */
245
+ /** 页内表达式:编号 → 元素(找不到是 null)。普通元素按属性找,shadow / 框架里的查 WeakRef 表。 */
219
246
  export const refElementJs = (ref) => `(document.querySelector(${JSON.stringify(`[${ATTR}="${Number(ref)}"]`)}) || (() => {
220
247
  const w = window.__dshSnap && window.__dshSnap.shadow.get(${Number(ref)});
221
248
  const el = w && w.deref();
222
- return el && el.isConnected ? el : null;
249
+ return el && el.isConnected && el.ownerDocument.defaultView ? el : null;
223
250
  })())`
224
251
 
225
252
  const goneError = (ref) =>
@@ -289,7 +316,7 @@ export async function focusShadow(call, tabId, ref) {
289
316
  expression: `(() => {
290
317
  const w = window.__dshSnap && window.__dshSnap.shadow.get(${n});
291
318
  const el = w && w.deref();
292
- if (!el || !el.isConnected) return null;
319
+ if (!el || !el.isConnected || !el.ownerDocument.defaultView) return null;
293
320
  el.focus();
294
321
  return el.getRootNode().activeElement === el;
295
322
  })()`,
@@ -297,3 +324,55 @@ export async function focusShadow(call, tabId, ref) {
297
324
  if (r.value === null) throw goneError(n)
298
325
  if (!r.value) throw new Error(`编号 ${n} 聚焦失败(元素可能不可聚焦)`)
299
326
  }
327
+
328
+ /** shadow DOM / 框架里的下拉框:直接在页面里选(扩展的 select 只认 document.querySelector 找得到的)。 */
329
+ export async function selectInPage(call, tabId, ref, value) {
330
+ const n = Number(ref)
331
+ const r = await call('eval', {
332
+ tabId,
333
+ expression: `(() => {
334
+ const el = ${refElementJs(n)};
335
+ if (!el) return null;
336
+ if (el.tagName !== 'SELECT') return { ok: false, why: '不是 <select> 元素' };
337
+ const v = ${JSON.stringify(String(value))};
338
+ const opts = [...el.options];
339
+ const hit = opts.find((o) => o.value === v) || opts.find((o) => (o.textContent || '').trim() === v);
340
+ if (!hit) return { ok: false, why: '没有这个选项', options: opts.map((o) => o.value).slice(0, 20) };
341
+ el.value = hit.value;
342
+ el.dispatchEvent(new Event('input', { bubbles: true }));
343
+ el.dispatchEvent(new Event('change', { bubbles: true }));
344
+ return { ok: true, value: hit.value, label: (hit.textContent || '').trim() };
345
+ })()`,
346
+ userGesture: false,
347
+ })
348
+ const v = r.value
349
+ if (v === null) throw goneError(n)
350
+ if (!v.ok) throw new Error(`选择失败:${v.why}${v.options ? '(可选值:' + v.options.join(', ') + ')' : ''}`)
351
+ return v
352
+ }
353
+
354
+ /** 同源 iframe 里的可见文字(document.body.innerText 不含框架内容);跨站的只给一行提示。 */
355
+ export async function frameTexts(call, tabId) {
356
+ const r = await call('eval', {
357
+ tabId,
358
+ expression: `(() => {
359
+ const out = [];
360
+ const walk = (doc, depth) => {
361
+ for (const f of doc.querySelectorAll('iframe, frame')) {
362
+ const b = f.getBoundingClientRect();
363
+ if (b.width < 2 || b.height < 2) continue;
364
+ const src = (f.getAttribute('src') || f.getAttribute('title') || f.getAttribute('name') || '').slice(0, 120);
365
+ let d = null;
366
+ try { d = f.contentDocument; } catch {}
367
+ if (!d || !d.body) { out.push({ src, cross: true }); continue; }
368
+ out.push({ src, text: (d.body.innerText || '').trim() });
369
+ if (depth < 4) walk(d, depth + 1);
370
+ }
371
+ };
372
+ walk(document, 0);
373
+ return out.slice(0, 30);
374
+ })()`,
375
+ userGesture: false,
376
+ })
377
+ return Array.isArray(r.value) ? r.value : []
378
+ }
package/setup.js CHANGED
@@ -22,7 +22,7 @@ import fs from 'node:fs'
22
22
  import os from 'node:os'
23
23
  import path from 'node:path'
24
24
  import crypto from 'node:crypto'
25
- import { execFileSync } from 'node:child_process'
25
+ import { execFileSync, spawn } from 'node:child_process'
26
26
  import { fileURLToPath } from 'node:url'
27
27
 
28
28
  export const HOST_NAME = 'com.dsh.bridge'
@@ -44,16 +44,34 @@ export function vendorDir() {
44
44
  return path.join(path.dirname(fileURLToPath(import.meta.url)), 'vendor')
45
45
  }
46
46
 
47
- /** 所有落盘位置。home 可覆盖,方便测试。 */
48
- export function paths(home = os.homedir()) {
47
+ /** 支持的系统。Windows 的原生宿主注册走注册表,其余两家是固定目录里的 JSON。 */
48
+ export const PLATFORMS = ['darwin', 'win32', 'linux']
49
+
50
+ /** Windows 上 Chrome(和 Edge,它也能装 Chrome 应用商店的扩展)找原生宿主的注册表项 */
51
+ export const REG_KEYS = [
52
+ `HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\${HOST_NAME}`,
53
+ `HKCU\\Software\\Microsoft\\Edge\\NativeMessagingHosts\\${HOST_NAME}`,
54
+ ]
55
+
56
+ /** 所有落盘位置。home、platform 可覆盖,方便测试。 */
57
+ export function paths(home = os.homedir(), platform = process.platform) {
58
+ const win = platform === 'win32'
49
59
  const bridge = path.join(home, '.dsh/chrome-bridge')
50
60
  const extDir = path.join(home, EXT_DIR_NAME)
51
- const chromeDir = path.join(home, 'Library/Application Support/Google/Chrome')
52
- const nmDir = path.join(chromeDir, 'NativeMessagingHosts')
61
+ const hostDir = path.join(bridge, 'host')
62
+ const chromeDir = win
63
+ ? path.join(process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'Google', 'Chrome', 'User Data')
64
+ : platform === 'linux'
65
+ ? path.join(home, '.config/google-chrome')
66
+ : path.join(home, 'Library/Application Support/Google/Chrome')
67
+ // Windows 的注册文件放哪都行(注册表指过去),就放在宿主旁边
68
+ const nmDir = win ? bridge : path.join(chromeDir, 'NativeMessagingHosts')
53
69
  return {
54
70
  home,
55
71
  bridge,
56
- hostDir: path.join(bridge, 'host'),
72
+ hostDir,
73
+ // Chrome 拉起宿主用的脚本:Windows 是装的时候现写的 run.bat,其余是自带的 run.sh
74
+ launcher: path.join(hostDir, win ? 'run.bat' : 'run.sh'),
57
75
  extDir,
58
76
  chromeDir,
59
77
  nmDir,
@@ -129,6 +147,45 @@ export function storeExtension(home = os.homedir()) {
129
147
  return null
130
148
  }
131
149
 
150
+ /**
151
+ * Windows 注册表里某一项的默认值;读不到回 null。
152
+ * 用 reg export 导出成 UTF-16 文件再读:reg query 的输出按控制台代码页编码,DSH 桌面版里没有控制台,中文路径会变成问号。
153
+ */
154
+ export function regValue(key) {
155
+ const file = path.join(os.tmpdir(), `dsh-bridge-reg-${process.pid}.reg`)
156
+ try {
157
+ execFileSync('reg', ['export', key, file, '/y'], { stdio: 'ignore', windowsHide: true })
158
+ return parseRegExport(fs.readFileSync(file, 'utf16le'))
159
+ } catch { return null } finally {
160
+ try { fs.rmSync(file, { force: true }) } catch {}
161
+ }
162
+ }
163
+
164
+ /** reg export 导出的文本里取默认值(@="…",反斜杠和引号是转义过的) */
165
+ export function parseRegExport(text) {
166
+ const m = /^@="((?:[^"\\]|\\.)*)"/m.exec(text)
167
+ return m ? m[1].replace(/\\(.)/g, '$1') : null
168
+ }
169
+
170
+ /**
171
+ * Windows 的宿主启动脚本。Chrome 用 cmd 跑它,stdout 就是 native messaging 管道,所以脚本自己一个字都不能往外打。
172
+ * node 用 DSH 自己的(桌面版是 Electron,要 ELECTRON_RUN_AS_NODE),没了再找 PATH 里的;DSH 升级换了路径,
173
+ * 插件下次加载会重写这个文件。路径可能带中文,先把代码页切到 UTF-8 再读后面的行。
174
+ */
175
+ export function winLauncher(execPath = process.execPath, electron = Boolean(process.versions.electron)) {
176
+ return [
177
+ '@echo off',
178
+ 'chcp 65001 >nul',
179
+ 'setlocal',
180
+ ...(electron ? ['set ELECTRON_RUN_AS_NODE=1'] : []),
181
+ `set "N=${execPath}"`,
182
+ 'if defined DSH_BRIDGE_NODE set "N=%DSH_BRIDGE_NODE%"',
183
+ 'if not exist "%N%" for %%I in (node.exe) do set "N=%%~$PATH:I"',
184
+ '"%N%" "%~dp0host.js" %*',
185
+ '',
186
+ ].join('\r\n')
187
+ }
188
+
132
189
  /** 装好了没有(只看落盘结果,不管 Chrome 有没有加载扩展)。 */
133
190
  export function installState(home = os.homedir()) {
134
191
  const p = paths(home)
@@ -138,8 +195,8 @@ export function installState(home = os.homedir()) {
138
195
  ...p,
139
196
  extId,
140
197
  extensionCopied: !!extId,
141
- hostCopied: fs.existsSync(path.join(p.hostDir, 'run.sh')),
142
- registered: fs.existsSync(p.nmFile),
198
+ hostCopied: fs.existsSync(p.launcher),
199
+ registered: fs.existsSync(p.nmFile) && (process.platform !== 'win32' || regValue(REG_KEYS[0]) !== null),
143
200
  vendor: fs.existsSync(vendorDir()),
144
201
  store: storeExtension(home),
145
202
  }
@@ -160,9 +217,10 @@ export function ensureInstalled(options = {}) {
160
217
  const p = paths(home)
161
218
  const out = { ok: false, changed: false, home, vendor, ...p }
162
219
 
220
+ const win = process.platform === 'win32'
163
221
  try {
164
- if (process.platform !== 'darwin') {
165
- return { ...out, reason: 'macOS only(native messaging 路径是 macOS 专有)' }
222
+ if (!PLATFORMS.includes(process.platform)) {
223
+ return { ...out, reason: `浏览器桥暂不支持 ${process.platform}(只支持 macOS、Windows、Linux)` }
166
224
  }
167
225
  const vExt = path.join(vendor, 'extension')
168
226
  const vHost = path.join(vendor, 'host')
@@ -178,22 +236,32 @@ export function ensureInstalled(options = {}) {
178
236
  const nmBody = `${JSON.stringify({
179
237
  name: HOST_NAME,
180
238
  description: 'dsh-chrome-bridge native host (local browser control)',
181
- path: path.join(p.hostDir, 'run.sh'),
239
+ path: p.launcher,
182
240
  type: 'stdio',
183
241
  allowed_origins: [extId, ...STORE_EXT_IDS].map((id) => `chrome-extension://${id}/`),
184
242
  }, null, 2)}\n`
185
243
 
186
244
  let nmPrev = null
187
245
  try { nmPrev = fs.readFileSync(p.nmFile, 'utf8') } catch {}
188
- const upToDate = prev === stamp && nmPrev === nmBody && allPresent(vExt, p.extDir) && allPresent(vHost, p.hostDir)
246
+ const launcherBody = win ? winLauncher() : null
247
+ let launcherPrev = null
248
+ if (win) try { launcherPrev = fs.readFileSync(p.launcher, 'utf8') } catch {}
249
+ const winOk = !win || (launcherPrev === launcherBody && REG_KEYS.every((k) => regValue(k) === p.nmFile))
250
+ const upToDate = prev === stamp && nmPrev === nmBody && winOk && allPresent(vExt, p.extDir) && allPresent(vHost, p.hostDir)
189
251
  if (!upToDate) {
190
252
  fs.mkdirSync(p.extDir, { recursive: true })
191
253
  fs.cpSync(vExt, p.extDir, { recursive: true, force: true })
192
254
  fs.mkdirSync(p.hostDir, { recursive: true })
193
255
  fs.cpSync(vHost, p.hostDir, { recursive: true, force: true })
194
- fs.chmodSync(path.join(p.hostDir, 'run.sh'), 0o755)
256
+ if (win) fs.writeFileSync(p.launcher, launcherBody)
257
+ else fs.chmodSync(p.launcher, 0o755)
195
258
  fs.mkdirSync(p.nmDir, { recursive: true })
196
259
  fs.writeFileSync(p.nmFile, nmBody)
260
+ if (win) {
261
+ for (const k of REG_KEYS) {
262
+ execFileSync('reg', ['add', k, '/ve', '/t', 'REG_SZ', '/d', p.nmFile, '/f'], { stdio: 'ignore', windowsHide: true })
263
+ }
264
+ }
197
265
  fs.writeFileSync(p.stampFile, `${stamp}\n`)
198
266
  out.changed = true
199
267
  }
@@ -201,13 +269,18 @@ export function ensureInstalled(options = {}) {
201
269
  // ── 可选件:cb CLI、页内光标脚本 —— 失败只是少个便利,不该让安装失败 ──
202
270
  // 刻意不动 ~/.dsh/skills:那是全局 agent 行为,装了插件就有原生 browser_* 工具,不需要它。
203
271
  try {
204
- copyFile(path.join(vendor, 'cb'), p.cb, 0o755)
205
- fs.mkdirSync(path.dirname(p.cbLink), { recursive: true })
206
- // ~/.local/bin/cb 可能是用户自己的另一个 cb:只在还没有时建链接;指向我们的链接本来就对,
207
- // 别的东西(用户自己的文件 / 指向别处的链接)一律不碰
208
- let cur = null
209
- try { cur = fs.lstatSync(p.cbLink) } catch {}
210
- if (!cur) fs.symlinkSync(p.cb, p.cbLink)
272
+ copyFile(path.join(vendor, 'cb'), p.cb, win ? undefined : 0o755)
273
+ if (win) {
274
+ // Windows 没有 shebang:旁边放个 cb.cmd(用 PATH 里的 node),也不去建 ~/.local/bin 的软链接
275
+ fs.writeFileSync(`${p.cb}.cmd`, '@echo off\r\nnode "%~dp0cb" %*\r\n')
276
+ } else {
277
+ fs.mkdirSync(path.dirname(p.cbLink), { recursive: true })
278
+ // ~/.local/bin/cb 可能是用户自己的另一个 cb:只在还没有时建链接;指向我们的链接本来就对,
279
+ // 别的东西(用户自己的文件 / 指向别处的链接)一律不碰
280
+ let cur = null
281
+ try { cur = fs.lstatSync(p.cbLink) } catch {}
282
+ if (!cur) fs.symlinkSync(p.cb, p.cbLink)
283
+ }
211
284
  } catch {}
212
285
  try {
213
286
  copyFile(path.join(vendor, 'in-page-cursor.js'), p.cursorFile)
@@ -228,15 +301,15 @@ export function ensureInstalled(options = {}) {
228
301
  export function installHint(home = os.homedir()) {
229
302
  const s = installState(home)
230
303
  if (!s.vendor) return '插件包里没有自带宿主:请重新用 release tarball 安装本插件(README 的 Install 一节)。'
231
- if (process.platform !== 'darwin') {
232
- return '浏览器桥只支持 macOS:native messaging 的注册路径是 macOS 专有的,其他系统上装不了宿主(插件本身不会静默失败)。'
304
+ if (!PLATFORMS.includes(process.platform)) {
305
+ return `浏览器桥暂不支持 ${process.platform}(只支持 macOS、Windows、Linux)。`
233
306
  }
234
307
  if (!s.hostCopied || !s.registered) {
235
308
  return [
236
309
  '宿主或 native messaging 注册没写成功(多半是权限问题):',
237
310
  `宿主目录 ${s.hostDir}${s.hostCopied ? ' ✅' : ' ❌'}`,
238
- `注册文件 ${s.nmFile}${s.registered ? ' ✅' : ' ❌'}`,
239
- '可以手动跑一次:./bridge setup(源码仓库里),或者用源码的 install.sh。',
311
+ `注册${process.platform === 'win32' ? '(注册表 + 文件)' : '文件'} ${s.nmFile}${s.registered ? ' ✅' : ' ❌'}`,
312
+ '重启一次 DSH 会再试一遍;还不行就在 GitHub 提 issue。',
240
313
  ].join('\n')
241
314
  }
242
315
  if (s.store) {
@@ -255,15 +328,49 @@ export function installHint(home = os.homedir()) {
255
328
  '· 或者加载已解压的扩展:',
256
329
  ' 1. Chrome 打开 chrome://extensions',
257
330
  ' 2. 右上角打开「开发者模式」',
258
- ' 3. 点「加载已解压的扩展程序」,在文件框里按 ⌘⇧G、粘贴、回车,选这个文件夹:',
331
+ ` 3. 点「加载已解压的扩展程序」,${PASTE_TIP[process.platform] || PASTE_TIP.darwin},选这个文件夹:`,
259
332
  ` ${s.extDir}`,
260
333
  '装好后回到这里重试;宿主和 native 注册已经自动装好了,不用再跑任何脚本。',
261
334
  ].join('\n')
262
335
  }
263
336
 
337
+ /** 文件框里怎么直接粘路径 */
338
+ const PASTE_TIP = {
339
+ darwin: '在文件框里按 ⌘⇧G、粘贴、回车',
340
+ win32: '把路径粘进文件框顶上的地址栏、回车',
341
+ linux: '在文件框里按 Ctrl+L、粘贴、回车',
342
+ }
343
+
264
344
  /** Chrome 在不在跑(决定要不要顺手把设置页打开)。 */
265
345
  function chromeRunning() {
266
- try { execFileSync('/usr/bin/pgrep', ['-x', 'Google Chrome'], { stdio: 'ignore' }); return true } catch { return false }
346
+ try {
347
+ if (process.platform === 'win32') {
348
+ const out = execFileSync('tasklist', ['/FI', 'IMAGENAME eq chrome.exe', '/NH'], { encoding: 'utf8', windowsHide: true })
349
+ return /chrome\.exe/i.test(out)
350
+ }
351
+ execFileSync('/usr/bin/pgrep', ['-x', process.platform === 'linux' ? 'chrome' : 'Google Chrome'], { stdio: 'ignore' })
352
+ return true
353
+ } catch { return false }
354
+ }
355
+
356
+ /** Windows / Linux 上 Chrome 的可执行文件(打开网址用);找不到回 null */
357
+ function chromeBin() {
358
+ const c = process.platform === 'win32'
359
+ ? [process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA].filter(Boolean)
360
+ .map((d) => path.join(d, 'Google', 'Chrome', 'Application', 'chrome.exe'))
361
+ : ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/opt/google/chrome/chrome']
362
+ return c.find((f) => fs.existsSync(f)) || null
363
+ }
364
+
365
+ /** 用 Chrome 打开一个网址(macOS 可以不抢前台) */
366
+ function openInChrome(url, { background = false } = {}) {
367
+ if (process.platform === 'darwin') {
368
+ execFileSync('/usr/bin/open', [...(background ? ['-g'] : []), '-a', 'Google Chrome', url])
369
+ return
370
+ }
371
+ const bin = chromeBin()
372
+ if (!bin) throw new Error('找不到 Chrome')
373
+ spawn(bin, [url], { detached: true, stdio: 'ignore', windowsHide: false }).unref()
267
374
  }
268
375
 
269
376
  /**
@@ -281,20 +388,23 @@ export function assistInstall(home = os.homedir(), { viaStore = false } = {}) {
281
388
  const out = { clipboard: false, opened: false, chromeRunning: chromeRunning(), store: !!store }
282
389
  if (viaStore) {
283
390
  try {
284
- execFileSync('/usr/bin/open', ['-a', 'Google Chrome', STORE_URL])
391
+ openInChrome(STORE_URL)
285
392
  out.opened = true
286
393
  } catch {}
287
394
  return out
288
395
  }
289
- if (!store) {
396
+ // 剪贴板:macOS 用 pbcopy,Windows 用 clip(Linux 不一定有 xclip,就不塞了)
397
+ if (!store && process.platform !== 'linux') {
290
398
  try {
291
- execFileSync('/usr/bin/pbcopy', [], { input: `${p.extDir}\n` })
399
+ if (process.platform === 'win32') execFileSync('clip', [], { input: p.extDir, windowsHide: true })
400
+ else execFileSync('/usr/bin/pbcopy', [], { input: `${p.extDir}\n` })
292
401
  out.clipboard = true
293
402
  } catch {}
294
403
  }
295
- if (out.chromeRunning) {
404
+ // 只有 macOS 能在后台开标签页;别的系统会把 Chrome 拉到前台,就不主动开了
405
+ if (out.chromeRunning && process.platform === 'darwin') {
296
406
  try {
297
- execFileSync('/usr/bin/open', ['-g', '-a', 'Google Chrome', 'chrome://extensions'])
407
+ openInChrome('chrome://extensions', { background: true })
298
408
  out.opened = true
299
409
  } catch {}
300
410
  }
package/vendor/cb CHANGED
@@ -41,16 +41,25 @@ import fs from 'node:fs'
41
41
  import path from 'node:path'
42
42
  import os from 'node:os'
43
43
  import crypto from 'node:crypto'
44
+ import { fileURLToPath } from 'node:url'
44
45
 
45
- // 和宿主同一个约定:只有当前用户进得去的 /tmp/dsh-bridge-<uid>/
46
- const DIR = process.env.DSH_BRIDGE_DIR || `/tmp/dsh-bridge-${process.getuid()}`
47
- const SOCK = process.env.DSH_BRIDGE_SOCK || path.join(DIR, 'dsh-bridge.sock')
46
+ // 和宿主同一个约定:只有当前用户进得去的 /tmp/dsh-bridge-<uid>/(Windows:%TEMP%\dsh-bridge)
47
+ const WIN = process.platform === 'win32'
48
+ const DIR = process.env.DSH_BRIDGE_DIR || (WIN ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${process.getuid()}`)
48
49
  const TOKEN_FILE = process.env.DSH_BRIDGE_TOKEN || path.join(DIR, 'dsh-bridge.token')
50
+ const FIXED_SOCK = process.env.DSH_BRIDGE_SOCK || (WIN ? null : path.join(DIR, 'dsh-bridge.sock'))
51
+
52
+ /** token 文件:第一行 token;Windows 上第二行是宿主这次起的命名管道 */
53
+ function tokenLines() {
54
+ try { return fs.readFileSync(TOKEN_FILE, 'utf8').split('\n').map((l) => l.trim()) } catch { return [] }
55
+ }
56
+ function hostSock() { return FIXED_SOCK || tokenLines()[1] || null }
57
+ function hostUp() { const s = hostSock(); return Boolean(s) && (WIN || fs.existsSync(s)) }
49
58
 
50
59
  /** socket 所在目录必须是自己的、别人进不去:不然连上的可能是别人摆的假宿主(会把要打的字、要跑的 JS 都交出去) */
51
60
  function checkDir(dir) {
52
61
  const st = fs.lstatSync(dir)
53
- if (!st.isDirectory() || st.uid !== process.getuid() || (st.mode & 0o077)) {
62
+ if (!st.isDirectory() || (!WIN && (st.uid !== process.getuid() || (st.mode & 0o077)))) {
54
63
  throw new Error(`${dir} 不是只属于当前用户的目录,拒绝连接`)
55
64
  }
56
65
  }
@@ -76,7 +85,7 @@ function die(msg) {
76
85
  }
77
86
 
78
87
  function readToken() {
79
- try { return fs.readFileSync(TOKEN_FILE, 'utf8').trim() } catch { return null }
88
+ return tokenLines()[0] || null
80
89
  }
81
90
 
82
91
  // 换目录之前的宿主只在这儿听:升级后 Chrome 没重启,它就还活着
@@ -89,6 +98,7 @@ const LEGACY_TOKEN = '/tmp/dsh-bridge.token'
89
98
  */
90
99
  function nudgeLegacyHost() {
91
100
  return new Promise((resolve) => {
101
+ if (WIN) return resolve(false)
92
102
  try {
93
103
  const st = fs.lstatSync(LEGACY_SOCK)
94
104
  const tk = fs.lstatSync(LEGACY_TOKEN)
@@ -108,19 +118,20 @@ function nudgeLegacyHost() {
108
118
  }
109
119
 
110
120
  async function call(op, args = {}, timeoutMs = 60000) {
111
- if (!fs.existsSync(SOCK) && !process.env.DSH_BRIDGE_SOCK && await nudgeLegacyHost()) {
121
+ if (!hostUp() && !process.env.DSH_BRIDGE_SOCK && await nudgeLegacyHost()) {
112
122
  // 扩展重载 + 新宿主起来一般一两秒;最多等 10 秒
113
- for (let i = 0; i < 40 && !fs.existsSync(SOCK); i++) await new Promise((r) => setTimeout(r, 250))
114
- if (op === 'reload' && fs.existsSync(SOCK)) return { reloading: true } // 刚才那下就是重载,不用再来一次
123
+ for (let i = 0; i < 40 && !hostUp(); i++) await new Promise((r) => setTimeout(r, 250))
124
+ if (op === 'reload' && hostUp()) return { reloading: true } // 刚才那下就是重载,不用再来一次
115
125
  }
116
126
  return new Promise((resolve, reject) => {
117
- if (!fs.existsSync(SOCK)) {
118
- if (fs.existsSync(LEGACY_SOCK)) {
127
+ const SOCK = hostSock()
128
+ if (!hostUp()) {
129
+ if (!WIN && fs.existsSync(LEGACY_SOCK)) {
119
130
  return reject(new Error(`宿主没在跑(找不到 ${SOCK})。老版宿主还占着 ${LEGACY_SOCK}、叫不醒:重启一次 Chrome`))
120
131
  }
121
- return reject(new Error(`宿主没在跑(找不到 ${SOCK})。Chrome 开着吗?扩展装了吗?`))
132
+ return reject(new Error(`宿主没在跑(找不到 ${SOCK || TOKEN_FILE})。Chrome 开着吗?扩展装了吗?`))
122
133
  }
123
- try { checkDir(path.dirname(SOCK)) } catch (e) { return reject(e) }
134
+ try { checkDir(WIN ? DIR : path.dirname(SOCK)) } catch (e) { return reject(e) }
124
135
  const token = readToken()
125
136
  const id = crypto.randomUUID()
126
137
  const sock = net.connect(SOCK)
@@ -156,7 +167,7 @@ function cursorScript() {
156
167
  const cands = [
157
168
  process.env.DSH_CURSOR_JS,
158
169
  path.join(os.homedir(), '.dsh/chrome-cursor/in-page-cursor.js'),
159
- path.join(path.dirname(new URL(import.meta.url).pathname), '../scratch/in-page-cursor.js'),
170
+ path.join(path.dirname(fileURLToPath(import.meta.url)), '../scratch/in-page-cursor.js'),
160
171
  ].filter(Boolean)
161
172
  for (const p of cands) {
162
173
  try { return fs.readFileSync(p, 'utf8') } catch {}
@@ -182,7 +193,7 @@ const USAGE = `cb <命令> [参数] 用 cb help 看完整用法`
182
193
 
183
194
  async function main() {
184
195
  if (!cmd || cmd === 'help' || flags.help) {
185
- console.log(fs.readFileSync(new URL(import.meta.url).pathname, 'utf8').split('*/')[0].replace(/^\/\*\*?/, '').replace(/^ \* ?/gm, '').trim())
196
+ console.log(fs.readFileSync(fileURLToPath(import.meta.url), 'utf8').split('*/')[0].replace(/^\/\*\*?/, '').replace(/^ \* ?/gm, '').trim())
186
197
  return
187
198
  }
188
199
 
@@ -313,7 +324,7 @@ async function main() {
313
324
  case 'record': {
314
325
  const tabId = await resolveTab(rest[0])
315
326
  const ms = Number(flags.ms || 5000)
316
- const dir = String(flags.out || `/tmp/dsh-frames-${Date.now()}`)
327
+ const dir = String(flags.out || path.join(WIN ? os.tmpdir() : '/tmp', `dsh-frames-${Date.now()}`))
317
328
  fs.mkdirSync(dir, { recursive: true })
318
329
  const r = await call('screencast', {
319
330
  tabId, durationMs: ms, maxWidth: Number(flags.width || 900), quality: Number(flags.quality || 70),
@@ -390,7 +401,7 @@ async function main() {
390
401
  full: !!flags.full,
391
402
  selector: flags.sel || undefined,
392
403
  }, 90000)
393
- const file = String(flags.out || `/tmp/dsh-shot-${Date.now()}.${format === 'jpeg' ? 'jpg' : 'png'}`)
404
+ const file = String(flags.out || path.join(WIN ? os.tmpdir() : '/tmp', `dsh-shot-${Date.now()}.${format === 'jpeg' ? 'jpg' : 'png'}`))
394
405
  fs.writeFileSync(file, Buffer.from(r.data, 'base64'))
395
406
  out(file, { file, format, url: r.url, title: r.title, bytes: fs.statSync(file).size, full: r.full, clip: r.clip })
396
407
  return
@@ -4,7 +4,8 @@
4
4
  *
5
5
  * 两条腿:
6
6
  * 1. stdin/stdout ← native messaging 协议(4 字节 LE 长度前缀 + JSON)→ Chrome 扩展
7
- * 2. /tmp/dsh-bridge-<uid>/dsh-bridge.sock ← 换行分隔 JSON → DSH 的 `cb` CLI
7
+ * 2. /tmp/dsh-bridge-<uid>/dsh-bridge.sock ← 换行分隔 JSON → DSH 插件和 `cb` CLI
8
+ * (Windows 没有 Unix socket:每次起一个随机名字的命名管道,名字写在 token 文件第二行)
8
9
  *
9
10
  * 由 Chrome 拉起(扩展 connectNative 时)。stdin 关闭 = Chrome 没了 = 退出。
10
11
  * 调试时可以手动跑:node host.js --standalone
@@ -12,13 +13,17 @@
12
13
 
13
14
  import net from 'node:net'
14
15
  import fs from 'node:fs'
16
+ import os from 'node:os'
15
17
  import path from 'node:path'
16
18
  import crypto from 'node:crypto'
17
19
 
18
20
  // socket / token / 日志都放进只有当前用户进得去的目录(0700):/tmp 人人可写,
19
21
  // 固定文件名会被别的用户抢先占位、或者用软链接把我们的写入引到别处。插件和 cb 用同一个约定。
20
- const DIR = process.env.DSH_BRIDGE_DIR || `/tmp/dsh-bridge-${process.getuid()}`
21
- const SOCK = process.env.DSH_BRIDGE_SOCK || path.join(DIR, 'dsh-bridge.sock')
22
+ // Windows 上 %TEMP% 本来就是每个用户自己的目录
23
+ const WIN = process.platform === 'win32'
24
+ const DIR = process.env.DSH_BRIDGE_DIR || (WIN ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${process.getuid()}`)
25
+ const SOCK = process.env.DSH_BRIDGE_SOCK ||
26
+ (WIN ? `\\\\.\\pipe\\dsh-bridge-${crypto.randomBytes(12).toString('hex')}` : path.join(DIR, 'dsh-bridge.sock'))
22
27
  const TOKEN_FILE = process.env.DSH_BRIDGE_TOKEN || path.join(DIR, 'dsh-bridge.token')
23
28
  const LOG_FILE = process.env.DSH_BRIDGE_LOG || path.join(DIR, 'dsh-bridge.log')
24
29
  const TIMEOUT_MS = Number(process.env.DSH_BRIDGE_TIMEOUT_MS || 45000)
@@ -32,12 +37,12 @@ const TOKEN = crypto.randomBytes(24).toString('hex')
32
37
  function privateDir(dir) {
33
38
  try { fs.mkdirSync(dir, { mode: 0o700 }) } catch (e) { if (e.code !== 'EEXIST') throw e }
34
39
  const st = fs.lstatSync(dir)
35
- if (!st.isDirectory() || st.uid !== process.getuid()) throw new Error(`${dir} 不是当前用户自己的目录,拒绝使用`)
36
- if (st.mode & 0o077) fs.chmodSync(dir, 0o700)
40
+ if (!st.isDirectory() || (!WIN && st.uid !== process.getuid())) throw new Error(`${dir} 不是当前用户自己的目录,拒绝使用`)
41
+ if (!WIN && (st.mode & 0o077)) fs.chmodSync(dir, 0o700)
37
42
  }
38
43
 
39
44
  try {
40
- for (const d of new Set([SOCK, TOKEN_FILE, LOG_FILE].map((f) => path.dirname(f)))) privateDir(d)
45
+ for (const d of new Set([...(WIN ? [] : [SOCK]), TOKEN_FILE, LOG_FILE].map((f) => path.dirname(f)))) privateDir(d)
41
46
  } catch (e) {
42
47
  process.stderr.write(`dsh-bridge: ${e.message}\n`) // Chrome 会把宿主的 stderr 记进它自己的日志
43
48
  process.exit(1)
@@ -57,7 +62,7 @@ function writeToken() {
57
62
  const tmp = `${TOKEN_FILE}.${process.pid}.tmp`
58
63
  try { fs.unlinkSync(tmp) } catch {}
59
64
  const fd = fs.openSync(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)
60
- try { fs.writeSync(fd, TOKEN + '\n') } finally { fs.closeSync(fd) }
65
+ try { fs.writeSync(fd, TOKEN + '\n' + (WIN ? SOCK + '\n' : '')) } finally { fs.closeSync(fd) }
61
66
  fs.renameSync(tmp, TOKEN_FILE)
62
67
  }
63
68
 
@@ -186,7 +191,7 @@ function handleLine(sock, line) {
186
191
 
187
192
  function startServer() {
188
193
  try {
189
- if (fs.existsSync(SOCK)) {
194
+ if (!WIN && fs.existsSync(SOCK)) {
190
195
  // 探测一下是不是活着的旧实例;活着也让路(接管),否则清掉陈旧文件
191
196
  try {
192
197
  const probe = net.connect(SOCK)
@@ -215,8 +220,10 @@ function startServer() {
215
220
  server.on('error', (e) => { log('socket 服务出错:', String(e)); shutdown(1) })
216
221
  server.listen(SOCK, () => {
217
222
  listening = true
218
- fs.chmodSync(SOCK, 0o600)
219
- try { const st = fs.lstatSync(SOCK); ownSock = { dev: st.dev, ino: st.ino } } catch {}
223
+ if (!WIN) {
224
+ fs.chmodSync(SOCK, 0o600)
225
+ try { const st = fs.lstatSync(SOCK); ownSock = { dev: st.dev, ino: st.ino } } catch {}
226
+ }
220
227
  try { writeToken() } catch (e) { log('写 token 失败:', String(e)); shutdown(1) }
221
228
  log(`监听 ${SOCK}(pid ${process.pid}, standalone=${STANDALONE})`)
222
229
  })
@@ -231,8 +238,13 @@ function shutdown(code) {
231
238
  // 不调 server.close():Node 关 Unix socket 服务时会按路径无条件 unlink(实测),
232
239
  // 正好会删掉后来接管的新宿主的 socket。反正马上退出,fd 由系统回收。
233
240
  try {
234
- const st = fs.lstatSync(SOCK)
235
- if (ownSock && st.dev === ownSock.dev && st.ino === ownSock.ino) fs.unlinkSync(SOCK)
241
+ if (WIN) {
242
+ // 命名管道随进程消失;token 文件还指着自己的管道就删掉,免得客户端连一个不存在的管道
243
+ if (fs.readFileSync(TOKEN_FILE, 'utf8').split('\n')[1] === SOCK) fs.unlinkSync(TOKEN_FILE)
244
+ } else {
245
+ const st = fs.lstatSync(SOCK)
246
+ if (ownSock && st.dev === ownSock.dev && st.ino === ownSock.ino) fs.unlinkSync(SOCK)
247
+ }
236
248
  } catch {}
237
249
  process.exit(code)
238
250
  }
@@ -12,12 +12,12 @@ whenToUse: 任务要在"用户已经登录的那个浏览器"里做事情,或
12
12
 
13
13
  ## 首选:`browser_*` 原生工具
14
14
 
15
- 装了 Chrome Bridge 插件就有这 9 个工具,比走 shell 快、也不用引号转义:
15
+ 装了 Chrome Bridge 插件就有这 12 个工具,比走 shell 快、也不用引号转义:
16
16
 
17
17
  | 工具 | 用途 |
18
18
  |---|---|
19
19
  | `browser_tabs` | 列 / 找 / 开 / 关 / 切标签页(**先拿 tabId**) |
20
- | `browser_read` | **`what=snapshot` 给能点/能填的元素编号 [N]**(要操作页面先调它);`text` 读可见文字;`html` / `attr` / `info`(info 会告诉你有没有弹窗挡着) |
20
+ | `browser_read` | **`what=snapshot` 给能点/能填的元素编号 [N]**(要操作页面先调它;同源 iframe 里的元素也在里面,夹在 `[iframe] … ↓` 和 `[/iframe]` 之间);`text` 读可见文字;`html` / `attr` / `info`(info 会告诉你有没有弹窗挡着) |
21
21
  | `browser_click` | 按 `ref`(编号,最稳)/ `selector` / `text` / 坐标点(真实鼠标事件) |
22
22
  | `browser_input` | `type` / `key` / `select` / `upload` / `focus` / `hover` / `scroll` |
23
23
  | `browser_nav` | `go` 跳转 / `back` 后退 / `forward` 前进 / `reload` 刷新,都等加载完 |
@@ -26,6 +26,7 @@ whenToUse: 任务要在"用户已经登录的那个浏览器"里做事情,或
26
26
  | `browser_wait` | 等 `selector` 元素 / `text` 文字 / `url` 网址出现;`gone=true` 等它消失(加载圈) |
27
27
  | `browser_dialog` | 放行 alert / confirm / prompt |
28
28
  | `browser_drag` | 拖拽:起点终点各用 `ref` / `selector` / `text` / 坐标;放置区一般没编号,用 `toText` |
29
+ | `browser_download` | 下载文件:`ref` / `selector` / `url` 三选一,带用户的登录状态;默认存「下载」文件夹,`to=workdir` 存会话工作目录。下载按钮不是链接时,先点它,再从 `browser_devtools network` 里找文件网址 |
29
30
  | `browser_devtools` | `console` 控制台 + JS 报错(`level=error` 只看报错)/ `network` 请求列表(`reload=true` 抓整页加载)/ `response` 看某个请求的返回内容 / `clear` |
30
31
 
31
32
  ## 备用:`cb` 命令行
@@ -66,6 +67,7 @@ cb cdp <tab> <方法> '{...}' # 原始 CDP 逃生口
66
67
  7. **页面不对劲(点了没反应、数据没出来、白屏)先查 `browser_devtools`**:`console level=error` 看报错,
67
68
  `network` 看接口是不是 4xx/5xx,再 `response` 看返回内容——别靠猜。
68
69
  8. 等异步内容用 `browser_wait`(等文字 / 网址 / 加载圈消失),别干等。
70
+ 9. **要文件就用 `browser_download`**,别去点浏览器的下载(存到哪、叫什么你都拿不到)。快照里写着「跨站框架」的 iframe 读不到里面:截图看,按坐标点。
69
71
 
70
72
  ## 什么时候别用它
71
73