dsh-chrome-bridge 1.20.0 → 2.0.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.
Files changed (88) hide show
  1. package/README.en.md +6 -2
  2. package/README.md +6 -2
  3. package/client.js +110 -29
  4. package/core/ext.js +119 -0
  5. package/core/hosts.js +277 -0
  6. package/core/locale.js +8 -0
  7. package/core/receipt.js +56 -0
  8. package/core/session.js +157 -0
  9. package/core/shots.js +56 -0
  10. package/core/tooldef.js +142 -0
  11. package/core/transport.js +212 -0
  12. package/core/upload.js +59 -0
  13. package/devtools.js +18 -8
  14. package/download.js +879 -60
  15. package/drag.js +38 -20
  16. package/features/frames.js +58 -0
  17. package/features/gif.js +203 -0
  18. package/features/index.js +1 -0
  19. package/features/mock-har.js +85 -0
  20. package/features/record.js +225 -0
  21. package/i18n/en.js +168 -16
  22. package/i18n/ru.js +168 -16
  23. package/i18n/zh.js +168 -16
  24. package/image-guard.js +13 -6
  25. package/index.js +17 -1155
  26. package/locale/ru.json +7 -0
  27. package/nav.js +43 -5
  28. package/package.json +8 -1
  29. package/panel.js +10 -1
  30. package/refs.js +275 -230
  31. package/setup.js +214 -46
  32. package/tools/click.js +58 -0
  33. package/tools/devtools.js +61 -0
  34. package/tools/dialog.js +22 -0
  35. package/tools/download.js +50 -0
  36. package/tools/drag.js +61 -0
  37. package/tools/eval.js +22 -0
  38. package/tools/fill.js +77 -0
  39. package/tools/handoff.js +40 -0
  40. package/tools/index.js +38 -0
  41. package/tools/input.js +147 -0
  42. package/tools/nav.js +57 -0
  43. package/tools/read.js +87 -0
  44. package/tools/record.js +120 -0
  45. package/tools/screenshot.js +223 -0
  46. package/tools/tabs.js +131 -0
  47. package/tools/wait.js +56 -0
  48. package/vendor/cb +616 -35
  49. package/vendor/extension/_locales/en/messages.json +3 -0
  50. package/vendor/extension/_locales/ru/messages.json +3 -0
  51. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  53. package/vendor/extension/background.js +2 -1969
  54. package/vendor/extension/confirm.css +148 -0
  55. package/vendor/extension/confirm.html +49 -0
  56. package/vendor/extension/confirm.js +188 -0
  57. package/vendor/extension/in-page-cursor.js +599 -0
  58. package/vendor/extension/manifest.json +11 -2
  59. package/vendor/extension/popup.css +99 -5
  60. package/vendor/extension/popup.html +28 -2
  61. package/vendor/extension/popup.js +430 -45
  62. package/vendor/extension/sw/boot.js +111 -0
  63. package/vendor/extension/sw/cdp.js +411 -0
  64. package/vendor/extension/sw/chooser.js +192 -0
  65. package/vendor/extension/sw/confirm.js +608 -0
  66. package/vendor/extension/sw/cursor.js +241 -0
  67. package/vendor/extension/sw/dispatch.js +129 -0
  68. package/vendor/extension/sw/download.js +279 -0
  69. package/vendor/extension/sw/fetch-hub.js +224 -0
  70. package/vendor/extension/sw/frames.js +651 -0
  71. package/vendor/extension/sw/imaging.js +361 -0
  72. package/vendor/extension/sw/native.js +111 -0
  73. package/vendor/extension/sw/net-tools.js +525 -0
  74. package/vendor/extension/sw/ops.js +829 -0
  75. package/vendor/extension/sw/popup-api.js +303 -0
  76. package/vendor/extension/sw/profile.js +166 -0
  77. package/vendor/extension/sw/record.js +494 -0
  78. package/vendor/extension/sw/state.js +161 -0
  79. package/vendor/extension/sw/tabui.js +219 -0
  80. package/vendor/extension/sw/util.js +166 -0
  81. package/vendor/extension/sw/welcome.js +26 -0
  82. package/vendor/extension/sw/windows.js +94 -0
  83. package/vendor/extension/welcome.css +189 -0
  84. package/vendor/extension/welcome.html +70 -0
  85. package/vendor/extension/welcome.js +157 -0
  86. package/vendor/host/host.js +476 -71
  87. package/vendor/in-page-cursor.js +309 -37
  88. package/vendor/skill/SKILL.md +34 -16
@@ -0,0 +1,241 @@
1
+ import { evaluate, send } from './cdp.js'
2
+ import { withChooser } from './chooser.js'
3
+ import { S } from './state.js'
4
+ import { CURSOR_ICON, CURSOR_TAB_TITLE, IDLE_ICON, labels, setTabFavicon } from './tabui.js'
5
+ import { log, sleep, timeLeft, within } from './util.js'
6
+
7
+ async function injectCursor(tabId) {
8
+ if (S.paused || !S.showCursor) return false
9
+ const id = Number(tabId)
10
+ if (!S.cursorReady.has(id)) {
11
+ await chrome.scripting.executeScript({ target: { tabId: id }, world: 'MAIN', files: ['in-page-cursor.js'] })
12
+ const p = S.cursorPos.get(id)
13
+ if (p) await evaluate(tabId, `window.__dshCursor.pos() || window.__dshCursor.place(${p.x}, ${p.y})`).catch(() => {})
14
+ S.cursorReady.add(id)
15
+ // 语义:标签页上出现小鼠标 = 这个页面里真的有一只鼠标(页内光标已就位)
16
+ await markCursor(tabId, true)
17
+ }
18
+ return true
19
+ }
20
+
21
+ /**
22
+ * 调页内光标。cursorReady 可能已经过期(页面刚跳走、loadEventFired 还没到;或者页面里还是旧版光标),
23
+ * 所以表达式里先探一下 v4 以上光标在不在,不在就重注一次再来。光标装不上返回 undefined。
24
+ */
25
+ async function cursorDo(tabId, expr, deadline) {
26
+ const id = Number(tabId)
27
+ const NONE = '__dsh_no_cursor__'
28
+ const probe = `((window.__dshCursor && window.__dshCursor.version >= 4) ? (${expr}) : ${JSON.stringify(NONE)})`
29
+ if (!S.cursorReady.has(id) && !(await injectCursor(tabId))) return undefined
30
+ let r = await evaluate(tabId, probe, false, deadline && timeLeft(deadline))
31
+ if (r === NONE) {
32
+ S.cursorReady.delete(id)
33
+ if (!(await injectCursor(tabId))) return undefined
34
+ r = await evaluate(tabId, probe, false, deadline && timeLeft(deadline))
35
+ }
36
+ return r === NONE ? undefined : r
37
+ }
38
+
39
+ /** 光标滑到 (x, y),可顺带亮出名牌文字。返回滑行时长 ms;光标装不上返回 null(不影响真实操作)。 */
40
+ async function cursorMove(tabId, x, y, opts = {}) {
41
+ const px = Math.round(Number(x))
42
+ const py = Math.round(Number(y))
43
+ const mo = { straight: !!opts.straight }
44
+ if (opts.duration != null) mo.duration = Math.max(0, Math.round(Number(opts.duration)))
45
+ const say = opts.label ? `c.label(${JSON.stringify(String(opts.label).slice(0, 80))});` : ''
46
+ try {
47
+ const d = await cursorDo(tabId, `(() => { const c = window.__dshCursor; ${say} return c.move(${px}, ${py}, ${JSON.stringify(mo)}) })()`, opts.deadline)
48
+ if (d === undefined) return null
49
+ S.cursorPos.set(Number(tabId), { x: px, y: py })
50
+ return Number(d) || 0
51
+ } catch { return null }
52
+ }
53
+
54
+ /** 光标的其它表情(click / down / up / label / scroll):只在光标已经在页面里时做,出错不管 */
55
+ async function cursorFx(tabId, expr, deadline) {
56
+ if (!S.cursorReady.has(Number(tabId))) return undefined
57
+ try { return await cursorDo(tabId, expr, deadline) } catch { return undefined }
58
+ }
59
+
60
+ /** 等光标飞到位:人眼先看到"要点这儿",再发真实事件 */
61
+ const settle = (d) => sleep(Math.min(700, Math.max(120, d || 0)) + 40)
62
+
63
+ /** 用 scripting 在 MAIN world 收掉页内光标(不依赖 CDP,调试器已断开时也能收)。 */
64
+ async function hidePageCursor(tabId) {
65
+ try {
66
+ await chrome.scripting.executeScript({
67
+ target: { tabId: Number(tabId) },
68
+ world: 'MAIN',
69
+ func: () => { try { window.__dshCursor && window.__dshCursor.hide() } catch {} },
70
+ })
71
+ } catch {}
72
+ }
73
+
74
+ /** 标签上的小鼠标只跟"页内光标在不在":在 → 亮;hide / 导航 / 松手 → 灭。 */
75
+ async function markCursor(tabId, on) {
76
+ const id = Number(tabId)
77
+ try {
78
+ await chrome.action.setIcon({ tabId: id, path: on ? CURSOR_ICON : IDLE_ICON })
79
+ await chrome.action.setTitle({ tabId: id, title: on ? CURSOR_TAB_TITLE[S.UI_LANG] : '' })
80
+ } catch {}
81
+ await setTabFavicon(id, on)
82
+ }
83
+
84
+ async function installInputListener(tabId) {
85
+ try {
86
+ await chrome.scripting.executeScript({ target: { tabId, allFrames: true }, world: 'ISOLATED', injectImmediately: true, func: () => {
87
+ if (globalThis.__dshInputInstalled) return
88
+ globalThis.__dshInputInstalled = true
89
+ let last = -Infinity
90
+ const onInput = ev => {
91
+ if (ev.isTrusted !== true || performance.now() - last < 200) return
92
+ last = performance.now()
93
+ chrome.runtime.sendMessage({ bridgeEvent: 'userInput', type: ev.type }).catch(() => {})
94
+ }
95
+ for (const type of ['pointerdown', 'keydown']) window.addEventListener(type, onInput, { capture: true, passive: true })
96
+ } })
97
+ } catch (e) { log('无法监听页内输入:', String(e)) }
98
+ }
99
+
100
+ async function mountHandoff({ tabId, id, reason }) {
101
+ try {
102
+ await chrome.scripting.executeScript({ target: { tabId }, world: 'ISOLATED', injectImmediately: true,
103
+ args: [{ id, reason, title: labels[S.UI_LANG].handoff, doneLabel: labels[S.UI_LANG].done }],
104
+ func: ({ id, reason, title, doneLabel }) => {
105
+ const prev = globalThis.__dshHandoff
106
+ if (prev?.id === id && prev.host.isConnected) return
107
+ prev?.host.remove()
108
+ const host = document.createElement('div')
109
+ host.id = 'dsh-handoff'
110
+ host.setAttribute('popover', 'manual')
111
+ host.style.cssText = 'position:fixed;inset:12px 0 auto;margin:0 auto;width:max-content;max-width:94vw;padding:0;border:0;background:transparent;pointer-events:none;z-index:2147483647;color-scheme:light dark'
112
+ const root = host.attachShadow({ mode: 'closed' })
113
+ const bar = document.createElement('div')
114
+ bar.style.cssText = 'pointer-events:auto;display:flex;align-items:center;gap:12px;padding:12px 16px;border:1px solid GrayText;border-radius:12px;background:Canvas;color:CanvasText;font:14px/1.4 system-ui'
115
+ const label = document.createElement('span')
116
+ label.textContent = reason ? title + ' · ' + reason : title
117
+ const button = document.createElement('button')
118
+ button.textContent = doneLabel
119
+ button.addEventListener('click', ev => {
120
+ if (!ev.isTrusted) return
121
+ ev.stopPropagation()
122
+ host.remove()
123
+ chrome.runtime.sendMessage({ bridgeEvent: 'handoffDone', id }).catch(() => {})
124
+ })
125
+ bar.append(label, button)
126
+ root.append(bar)
127
+ document.documentElement.append(host)
128
+ globalThis.__dshHandoff = { id, host }
129
+ host.showPopover?.()
130
+ },
131
+ })
132
+ } catch (e) { log('页内交接提示不可用:', String(e)) }
133
+ }
134
+
135
+ function refreshControls(tabId) {
136
+ if (S.attached.has(tabId)) void installInputListener(tabId)
137
+ if (S.activeHandoff?.tabId === tabId && !S.activeHandoff.settled) void mountHandoff(S.activeHandoff)
138
+ }
139
+
140
+ function beginAgentInput(tabId, ms = 1500) { S.agentInputUntil.set(Number(tabId), Date.now() + ms) }
141
+ function endAgentInput(tabId, graceMs = 150) {
142
+ if (S.attached.has(Number(tabId))) S.agentInputUntil.set(Number(tabId), Date.now() + graceMs)
143
+ else S.agentInputUntil.delete(Number(tabId))
144
+ }
145
+ async function agentInput(tabId, action) {
146
+ beginAgentInput(tabId)
147
+ try { return await action() }
148
+ finally { endAgentInput(tabId) }
149
+ }
150
+
151
+ async function clickPoint(tabId, x, y, opts = {}) {
152
+ const n = Number(opts.clickCount || 1)
153
+ const button = opts.button || 'left'
154
+ const budget = () => opts.deadline && timeLeft(opts.deadline)
155
+ const base = { x: Math.round(x), y: Math.round(y), button, clickCount: n }
156
+
157
+ // 先让光标飞过去,人眼看得见,再发真实点击
158
+ if (opts.cursor && S.showCursor) {
159
+ const d = await cursorMove(tabId, base.x, base.y, { label: opts.cursor.label, deadline: opts.deadline })
160
+ if (d !== null) {
161
+ await (opts.deadline ? within(settle(d), budget(), '等待光标超时') : settle(d))
162
+ await cursorFx(tabId, `(window.__dshCursor.click(${base.x}, ${base.y}, ${n}), 1)`, opts.deadline)
163
+ }
164
+ }
165
+
166
+ return agentInput(tabId, async () => {
167
+ if (typeof opts.check === 'function') opts.check()
168
+ await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mouseMoved', buttons: 0 }, budget())
169
+ await new Promise(r => setTimeout(r, 12))
170
+ return withChooser(tabId, opts.chooser, async () => {
171
+ if (typeof opts.check === 'function') opts.check()
172
+ await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mousePressed', buttons: ({ left: 1, right: 2, middle: 4, back: 8, forward: 16 })[button] || 1 }, budget())
173
+ await new Promise(r => setTimeout(r, 24))
174
+ await send(tabId, 'Input.dispatchMouseEvent', { ...base, type: 'mouseReleased', buttons: 0 }, opts.deadline ? Math.max(1, opts.deadline - Date.now()) : undefined)
175
+ return { x: base.x, y: base.y, button }
176
+ })
177
+ })
178
+ }
179
+
180
+ const MODS = { alt: 1, ctrl: 2, meta: 4, shift: 8 }
181
+ const NAMED_KEYS = {
182
+ enter: ['Enter', 'Enter', 13, '\r'], tab: ['Tab', 'Tab', 9], escape: ['Escape', 'Escape', 27],
183
+ esc: ['Escape', 'Escape', 27], backspace: ['Backspace', 'Backspace', 8],
184
+ delete: ['Delete', 'Delete', 46], arrowup: ['ArrowUp', 'ArrowUp', 38], arrowdown: ['ArrowDown', 'ArrowDown', 40],
185
+ arrowleft: ['ArrowLeft', 'ArrowLeft', 37], arrowright: ['ArrowRight', 'ArrowRight', 39],
186
+ home: ['Home', 'Home', 36], end: ['End', 'End', 35], pageup: ['PageUp', 'PageUp', 33],
187
+ pagedown: ['PageDown', 'PageDown', 34], space: [' ', 'Space', 32, ' '],
188
+ }
189
+
190
+ async function pressKey(tabId, spec) {
191
+ const parts = String(spec).split('+').map(s => s.trim()).filter(Boolean)
192
+ const keyName = parts.pop()
193
+ let modifiers = 0
194
+ for (const p of parts) {
195
+ const m = MODS[p.toLowerCase()]
196
+ if (!m) throw new Error(`不认识修饰键: ${p}(可用 alt/ctrl/meta/shift)`)
197
+ modifiers |= m
198
+ }
199
+ const lower = keyName.toLowerCase()
200
+ let key, code, keyCode, text
201
+ if (NAMED_KEYS[lower]) {
202
+ ;[key, code, keyCode, text] = NAMED_KEYS[lower]
203
+ } else if (keyName.length === 1) {
204
+ key = keyName
205
+ keyCode = keyName.toUpperCase().charCodeAt(0)
206
+ code = /[a-z]/i.test(keyName) ? 'Key' + keyName.toUpperCase()
207
+ : /[0-9]/.test(keyName) ? 'Digit' + keyName
208
+ : ''
209
+ text = keyName
210
+ } else {
211
+ throw new Error(`不认识按键: ${keyName}`)
212
+ }
213
+ const suppressText = modifiers !== 0 || !text
214
+ const base = { key, code, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode, modifiers }
215
+ return agentInput(tabId, async () => {
216
+ await send(tabId, 'Input.dispatchKeyEvent', {
217
+ ...base, type: suppressText ? 'rawKeyDown' : 'keyDown',
218
+ ...(suppressText ? {} : { text, unmodifiedText: text }),
219
+ })
220
+ await new Promise(r => setTimeout(r, 12))
221
+ await send(tabId, 'Input.dispatchKeyEvent', { ...base, type: 'keyUp' })
222
+ return { key: spec, modifiers }
223
+ })
224
+ }
225
+
226
+ async function unmountHandoff(tabId, id) {
227
+ try {
228
+ await chrome.scripting.executeScript({ target: { tabId }, world: 'ISOLATED', injectImmediately: true, args: [id], func: id => {
229
+ if (globalThis.__dshHandoff?.id === id) {
230
+ globalThis.__dshHandoff.host.remove()
231
+ delete globalThis.__dshHandoff
232
+ }
233
+ } })
234
+ } catch {}
235
+ }
236
+
237
+ export {
238
+ injectCursor, cursorDo, cursorMove, cursorFx, settle, hidePageCursor, markCursor,
239
+ installInputListener, mountHandoff, refreshControls, beginAgentInput, endAgentInput,
240
+ agentInput, clickPoint, MODS, NAMED_KEYS, pressKey, unmountHandoff,
241
+ }
@@ -0,0 +1,129 @@
1
+ import { hasProtectedSites, isUrlAllowed } from './confirm.js'
2
+ import { post } from './native.js'
3
+ import { getOps } from './ops.js'
4
+ import {
5
+ HANDOFF_LOCKED, OPEN_TRACKED, OWN_PAGE_OK, PAUSED_MSG, PAUSE_ALLOWED, QUEUED, S, TAKEOVER_OPS,
6
+ } from './state.js'
7
+ import { clientKey, friendly, isExtUrl, sleep, subscribe, timeLeft, track } from './util.js'
8
+
9
+ function addPreHook(fn) { return subscribe(S.preHooks, fn) }
10
+
11
+ function enqueue(id, run) {
12
+ const previous = S.tabQueues.get(id) || Promise.resolve()
13
+ const next = previous.then(run, run)
14
+ S.tabQueues.set(id, next)
15
+ return next.finally(() => { if (S.tabQueues.get(id) === next) S.tabQueues.delete(id) })
16
+ }
17
+
18
+ async function trackOpened(id, run) {
19
+ const created = []
20
+ const listener = t => { if (t.openerTabId === id) created.push(t) }
21
+ S.tabCreated.add(listener)
22
+ try {
23
+ const result = await run()
24
+ await sleep(80)
25
+ if (created.length) result.openedTabs = await Promise.all(created.map(async t => {
26
+ const tab = await chrome.tabs.get(t.id).catch(() => t)
27
+ const url = tab.url || tab.pendingUrl || ''
28
+ if (url && hasProtectedSites() && !isUrlAllowed(t.id, url)) {
29
+ let origin = ''
30
+ try { origin = new URL(url).origin } catch {}
31
+ return { id: t.id, url: origin, title: '' }
32
+ }
33
+ return { id: t.id, url, title: tab.title || '' }
34
+ }))
35
+ return result
36
+ } finally { S.tabCreated.delete(listener) }
37
+ }
38
+
39
+ async function handle(msg) {
40
+ if (!msg) return
41
+ if (msg.hostPong) { S.hostInfo = { ...msg, at: Date.now() }; return }
42
+ if (!msg.op) return
43
+ const { id, op, client } = msg
44
+ const args = { ...msg.args }
45
+ const t0 = Date.now()
46
+ // 两笔时间分开算:整次请求(DSH 那头等多久)从收到起算;操作自己的执行预算(nav 30 秒、waitFor 15 秒……)
47
+ // 从前置闸门(受保护网站确认)放行之后才开始算 —— 用户想一想再点放行,不该把操作本身的时间吃光
48
+ const hostBudget = Number.isFinite(msg.timeoutMs) ? Math.max(1000, msg.timeoutMs - 1500) : undefined
49
+ const hostDeadline = hostBudget !== undefined ? t0 + hostBudget : undefined
50
+ const requested = Number.isFinite(args.timeoutMs) ? args.timeoutMs : undefined
51
+ delete args.timeoutMs
52
+ /** 整次请求还剩多久(没带就 undefined) */
53
+ const hostLeft = () => (hostDeadline !== undefined ? Math.max(0, hostDeadline - Date.now()) : undefined)
54
+ /** 执行预算:操作自己要的(至少 1 秒、至多 10 分钟)和整次请求还剩的取小;整次请求已经过时限了就是 0 */
55
+ const execBudget = (left) => {
56
+ if (op === 'nav') return Math.min(requested ?? 30000, left ?? 30000)
57
+ const own = requested !== undefined ? Math.max(1000, Math.min(600000, requested)) : undefined
58
+ if (left === undefined) return own
59
+ return Math.min(own ?? 600000, left)
60
+ }
61
+ // 前置闸门看到的是「整次请求」的时限:用户点放行时整次请求都已经超时了,就报 CONFIRM_LATE、不再补做
62
+ const overall = hostBudget ?? execBudget(undefined)
63
+ if (overall !== undefined) args.timeoutMs = overall
64
+ try {
65
+ const ops = getOps()
66
+ if (!Object.hasOwn(ops, op)) throw new Error(`未知操作: ${op}`)
67
+ const fn = ops[op]
68
+ await S.startupReady
69
+ const tabId = Number(args.tabId)
70
+ const rawInput = op === 'cdp' && typeof args.method === 'string' && args.method.startsWith('Input.')
71
+ const checkHandoff = () => {
72
+ if (args.tabId != null && S.activeHandoff?.tabId === tabId &&
73
+ (HANDOFF_LOCKED.has(op) || (op === 'network' && args.reload)))
74
+ throw new Error('正在等待用户完成交接,请等用户点「我已完成」后再继续操作')
75
+ }
76
+ checkHandoff()
77
+ const run = async () => {
78
+ // 排队等过的时间也算在整次里;排到时整次请求已经过了时限(DSH 那头早走了):别再弹确认窗、也别再做
79
+ if (hostDeadline !== undefined) args.timeoutMs = timeLeft(hostDeadline)
80
+ for (const hook of S.preHooks) await hook({ op, args, client })
81
+ // 闸门放行了:执行预算从这里起算(同时不超过整次请求还剩的)
82
+ const budget = execBudget(hostLeft())
83
+ if (budget === undefined) delete args.timeoutMs
84
+ else args.timeoutMs = budget
85
+ const tExec = Date.now()
86
+ if (!OWN_PAGE_OK.has(op) && await touchesOwnPage(op, args)) throw new Error('扩展页面(chrome-extension://)不能被自动化操作')
87
+ if (S.paused && !PAUSE_ALLOWED.has(op)) throw new Error(PAUSED_MSG)
88
+ checkHandoff()
89
+ if (args.force === true) S.userTakeover.delete(tabId)
90
+ if (TAKEOVER_OPS.has(op) || rawInput) {
91
+ const user = S.userTakeover.get(tabId)
92
+ if (user && Date.now() - user.at <= 12000) throw new Error(`USER_ACTIVE ${user.type}`)
93
+ }
94
+ if (args.timeoutMs !== undefined) args.timeoutMs = timeLeft(tExec + args.timeoutMs)
95
+ if (Number.isInteger(tabId)) S.tabSessions.set(tabId, clientKey(client))
96
+ return OPEN_TRACKED.has(op) ? trackOpened(tabId, () => fn(args)) : fn(args)
97
+ }
98
+ const result = await (QUEUED.has(op) || rawInput ? enqueue(tabId, run) : run())
99
+ post({ id, ok: true, result })
100
+ track(client, op, args, result, null, Date.now() - t0)
101
+ } catch (e) {
102
+ const err = friendly(e).message
103
+ post({ id, ok: false, error: err })
104
+ track(client, op, args, null, err, Date.now() - t0)
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 扩展页面任何时候(不只是暂停时)都不让碰:弹窗页 popup.html 要是被当成标签页打开、再往里跑脚本,
110
+ * 就能 chrome.runtime.sendMessage 自己把「暂停」解除。打开、跳转过去、CDP 参数里带它、对它所在的
111
+ * 标签页做任何事(注入 / 截图 / 输入)都算。
112
+ */
113
+ async function touchesOwnPage(op, args) {
114
+ if ((op === 'open' || op === 'nav') && isExtUrl(args.url)) return true
115
+ // CDP 只看网址类参数(Page.navigate、Target.createTarget 的 url 之类),不扫表达式等别的文本
116
+ const p = op === 'cdp' && args.params
117
+ if (p && typeof p === 'object' && Object.keys(p).some((k) => /url$/i.test(k) && isExtUrl(p[k]))) return true
118
+ if (args.tabId == null) return false
119
+ try {
120
+ const t = await chrome.tabs.get(Number(args.tabId))
121
+ return isExtUrl(t.url) || isExtUrl(t.pendingUrl)
122
+ } catch {
123
+ return false
124
+ }
125
+ }
126
+
127
+ export {
128
+ addPreHook, enqueue, trackOpened, handle, touchesOwnPage,
129
+ }
@@ -0,0 +1,279 @@
1
+ import { ensure, evaluate, onCdpEvent } from './cdp.js'
2
+ import { isUrlAllowed } from './confirm.js'
3
+ import { clickPoint } from './cursor.js'
4
+ import { registerFetchConsumer } from './fetch-hub.js'
5
+ import { getOps } from './ops.js'
6
+ import { PAUSED_MSG, S } from './state.js'
7
+ import { checkPath, localHostname, sleep, timeLeft, within } from './util.js'
8
+
9
+ async function clickAndDownload({ tabId, selector, x, y, downloadDir, timeoutMs = 60000 }) {
10
+ if (downloadDir !== undefined && downloadDir !== null) checkPath(downloadDir, true)
11
+ if (!selector && ![x, y].every(Number.isFinite)) throw new Error('下载需要 selector 或坐标')
12
+ const deadline = Date.now() + timeoutMs
13
+ const id = Number(tabId)
14
+ await within(ensure(id), timeLeft(deadline), '等待调试器超时')
15
+ while (S.activeDownload) await within(S.activeDownload.cleaned, timeLeft(deadline), '等待下载超时')
16
+ if (S.paused) throw new Error(PAUSED_MSG)
17
+ let cleanup, interrupt, aborted = false
18
+ const cleaned = new Promise(r => { cleanup = r })
19
+ const interrupted = new Promise(r => { interrupt = () => { aborted = true; r() } })
20
+ const check = () => {
21
+ if (aborted || S.paused) throw new Error('下载已中止')
22
+ return timeLeft(deadline)
23
+ }
24
+ const dlId = crypto.randomUUID()
25
+ const MAX_FETCH_BYTES = 45 * 1024 * 1024
26
+ const headerVal = (headers, name) => {
27
+ const target = name.toLowerCase()
28
+ const hit = (headers || []).find((h) => String(h.name || '').toLowerCase() === target)
29
+ return hit ? String(hit.value || '') : ''
30
+ }
31
+ const isFileMime = (ct) => /^(application\/(pdf|zip|octet-stream|gzip|x-gzip|x-tar|msword|vnd\.|x-excel|x-msdownload)|text\/csv|audio\/|video\/|image\/)/i.test(String(ct || '').split(';')[0].trim())
32
+
33
+ let unregisterFetch, stopTracking
34
+ const redirects = new Map()
35
+ const redirectKey = (src, kind, id) => JSON.stringify([src.sessionId, kind, id])
36
+ function rememberRedirect(key, urls) {
37
+ redirects.set(key, urls)
38
+ if (redirects.size > 512) redirects.delete(redirects.keys().next().value)
39
+ }
40
+ let pageHost
41
+ let pageUrl = ''
42
+ let keepPageData = false
43
+ let watchingClick = false
44
+ let settled = false
45
+ let resolveCapture, rejectCapture
46
+ const captured = new Promise((res, rej) => { resolveCapture = res; rejectCapture = rej })
47
+ captured.catch(() => {}) // A paused response may reject before the click command returns.
48
+ const failCapture = (err) => { if (!settled) { settled = true; rejectCapture(err) } }
49
+
50
+ const onPaused = (event, _stage, src) => {
51
+ if (!watchingClick || settled) return
52
+ const status = Number(event.responseStatusCode || 0)
53
+ const networkKey = redirectKey(src, 'network', event.networkId)
54
+ const previousKey = redirectKey(src, 'fetch', event.redirectedRequestId)
55
+ const requestUrl = event.request?.url
56
+ const urls = new Set([...(redirects.get(networkKey) || []), ...(redirects.get(previousKey) || []), requestUrl])
57
+ if (status >= 300 && status < 400 && headerVal(event.responseHeaders, 'location')) {
58
+ rememberRedirect(redirectKey(src, 'fetch', event.requestId), urls)
59
+ if (event.networkId) rememberRedirect(networkKey, urls)
60
+ return
61
+ }
62
+ const disp = headerVal(event.responseHeaders, 'content-disposition')
63
+ const ctype = headerVal(event.responseHeaders, 'content-type')
64
+ const clen = Number(headerVal(event.responseHeaders, 'content-length') || 0)
65
+ const isAttachment = /^\s*attachment\b/i.test(disp)
66
+ const isDoc = !event.resourceType || event.resourceType === 'Document'
67
+ const want = status >= 200 && status < 300 && isDoc && (isAttachment || isFileMime(ctype))
68
+ if (!want) return
69
+ const denied = () => [...urls].some(url => !isUrlAllowed(id, url))
70
+ const denial = () => new Error('USER_DENIED_SENSITIVE')
71
+ const block = async finish => {
72
+ try { await finish('Fetch.failRequest', { errorReason: 'BlockedByClient' }) }
73
+ finally { rejectCapture(denial()) }
74
+ }
75
+ if (denied()) {
76
+ settled = true
77
+ return ({ finish }) => block(finish)
78
+ }
79
+ let url
80
+ try { url = new URL(requestUrl) } catch {}
81
+ const remoteIP = (event.networkId && S.netPending.get(id + '/' + event.networkId)?.remoteIP) || ''
82
+ const privateRemote = remoteIP && localHostname(remoteIP) && (!pageHost || !localHostname(pageHost))
83
+ if (!url || url.username || url.password || !['http:', 'https:'].includes(url.protocol) ||
84
+ (localHostname(url.hostname) && url.hostname !== pageHost) || privateRemote) {
85
+ failCapture(new Error('不允许抓取此来源的下载'))
86
+ return
87
+ }
88
+ settled = true
89
+ if (clen > MAX_FETCH_BYTES) {
90
+ return async ({ finish }) => {
91
+ try { await finish('Fetch.failRequest', { errorReason: 'Aborted' }) }
92
+ finally { rejectCapture(new Error('文件超过点击直抓上限(45MB)')) }
93
+ }
94
+ }
95
+ return async ({ getResponseBody, finish, signal }) => {
96
+ if (denied()) return block(finish)
97
+ let result
98
+ try {
99
+ const res = await getResponseBody()
100
+ signal.throwIfAborted()
101
+ if (denied()) throw denial()
102
+ const body = String((res && res.body) || '')
103
+ const base64Encoded = !!(res && res.base64Encoded)
104
+ const totalBytes = base64Encoded ? Math.floor(body.length * 3 / 4) - (body.endsWith('==') ? 2 : body.endsWith('=') ? 1 : 0)
105
+ : new TextEncoder().encode(body).byteLength
106
+ if (totalBytes > MAX_FETCH_BYTES) throw new Error('文件超过点击直抓上限(45MB)')
107
+ result = {
108
+ source: 'fetch',
109
+ url: (event.request && event.request.url) || '',
110
+ pageUrl,
111
+ remoteIP,
112
+ type: ctype,
113
+ disposition: disp,
114
+ suggestedFilename: '',
115
+ body,
116
+ base64Encoded,
117
+ totalBytes,
118
+ }
119
+ } catch (e) {
120
+ rejectCapture(e)
121
+ } finally {
122
+ if (!signal.aborted) await finish('Fetch.failRequest', { errorReason: 'Aborted' }).catch(() => {})
123
+ }
124
+ if (result) resolveCapture(result)
125
+ }
126
+ }
127
+
128
+ const HOOK_JS = `(() => {
129
+ if (window.__dshClickDlCleanup) try { window.__dshClickDlCleanup(true); } catch {}
130
+ const id = ${JSON.stringify(dlId)};
131
+ const state = { id, status: 'idle', url: '', filename: '', type: '', size: 0, error: '' };
132
+ window.__dshClickDl = state;
133
+ const origClick = HTMLAnchorElement.prototype.click;
134
+ const origDispatch = EventTarget.prototype.dispatchEvent;
135
+ const origRevoke = URL.revokeObjectURL;
136
+ const deferred = [];
137
+ const captureUrl = (url, filename) => {
138
+ if (state.status !== 'idle') return false;
139
+ state.status = 'loading';
140
+ state.url = url;
141
+ state.filename = filename || '';
142
+ (async () => {
143
+ try {
144
+ state.ctl = new AbortController();
145
+ const r = await fetch(url, { signal: state.ctl.signal });
146
+ if (!r.ok) throw new Error('HTTP ' + r.status);
147
+ const ab = await r.arrayBuffer();
148
+ if (state.ctl.signal.aborted) return;
149
+ const buf = new Uint8Array(ab);
150
+ (window.__dshDl || (window.__dshDl = Object.create(null)))[id] = {
151
+ buf, size: buf.byteLength, type: r.headers.get('content-type') || '', ctl: { abort() {} },
152
+ };
153
+ state.type = r.headers.get('content-type') || '';
154
+ state.size = buf.byteLength;
155
+ state.status = 'done';
156
+ } catch (e) {
157
+ state.error = String((e && e.message) || e);
158
+ state.status = 'error';
159
+ } finally {
160
+ for (const u of deferred.splice(0)) try { origRevoke.call(URL, u); } catch {}
161
+ }
162
+ })();
163
+ return true;
164
+ };
165
+ URL.revokeObjectURL = function (u) {
166
+ if (state.status === 'loading' && u === state.url) { deferred.push(u); return; }
167
+ return origRevoke.call(this, u);
168
+ };
169
+ HTMLAnchorElement.prototype.click = function () {
170
+ const href = String(this.getAttribute('href') || this.href || '');
171
+ if (/^(blob|data):/i.test(href) && captureUrl(href, this.getAttribute('download') || '')) return;
172
+ return origClick.apply(this, arguments);
173
+ };
174
+ EventTarget.prototype.dispatchEvent = function (ev) {
175
+ if (this instanceof HTMLAnchorElement && ev && ev.type === 'click' &&
176
+ /^(blob|data):/i.test(this.href) && captureUrl(this.href, this.download)) return false;
177
+ return origDispatch.apply(this, arguments);
178
+ };
179
+ const onClick = (ev) => {
180
+ const a = ev.target && ev.target.closest ? ev.target.closest('a[href]') : null;
181
+ if (!a) return;
182
+ const href = String(a.getAttribute('href') || a.href || '');
183
+ if (/^(blob|data):/i.test(href) && captureUrl(href, a.getAttribute('download') || '')) {
184
+ ev.preventDefault();
185
+ ev.stopPropagation();
186
+ }
187
+ };
188
+ document.addEventListener('click', onClick, true);
189
+ window.__dshClickDlCleanup = (dropData) => {
190
+ state.ctl?.abort();
191
+ if (dropData && window.__dshDl) delete window.__dshDl[id];
192
+ delete window.__dshClickDl;
193
+ EventTarget.prototype.dispatchEvent = origDispatch;
194
+ HTMLAnchorElement.prototype.click = origClick;
195
+ URL.revokeObjectURL = origRevoke;
196
+ document.removeEventListener('click', onClick, true);
197
+ for (const u of deferred.splice(0)) try { origRevoke.call(URL, u); } catch {}
198
+ delete window.__dshClickDlCleanup;
199
+ };
200
+ return true;
201
+ })()`
202
+
203
+ let pageHooked = false
204
+ S.activeDownload = { tabId: id, cleaned, interrupt }
205
+ try {
206
+ const page = new URL((await within(chrome.tabs.get(id), check(), '读取下载来源超时')).url)
207
+ pageUrl = page.href
208
+ pageHost = ['http:', 'https:'].includes(page.protocol) ? page.hostname : null
209
+ stopTracking = onCdpEvent((src, method, event) => {
210
+ if (src.tabId !== id || !watchingClick || settled || method !== 'Network.requestWillBeSent' || !event.redirectResponse?.url) return
211
+ const key = redirectKey(src, 'network', event.requestId)
212
+ rememberRedirect(key, new Set([...(redirects.get(key) || []), event.redirectResponse.url]))
213
+ })
214
+ unregisterFetch = registerFetchConsumer(id, {
215
+ id: dlId, priority: 10, patterns: [{ requestStage: 'Response' }], onPaused, timeoutMs: check(),
216
+ })
217
+ await within(unregisterFetch.ready, check(), 'Fetch setup timed out')
218
+ try { await evaluate(id, HOOK_JS, false, Math.min(5000, check())); pageHooked = true } catch {}
219
+ check()
220
+ watchingClick = true
221
+ if (selector) await getOps().clickEl({ tabId: id, selector }, { deadline, check })
222
+ else await clickPoint(id, x, y, { deadline, check })
223
+
224
+ let downloadStarted = false
225
+ const pollPage = (async () => {
226
+ if (!pageHooked) return new Promise(() => {})
227
+ const startLimit = Date.now() + Math.min(15000, check())
228
+ while (!settled && !aborted && !S.paused) {
229
+ let st = null
230
+ try { st = await evaluate(id, 'window.__dshClickDl || null', false, Math.min(3000, check())) } catch { return new Promise(() => {}) }
231
+ if (st && st.id === dlId) {
232
+ if (st.status === 'loading') downloadStarted = true
233
+ if (st.status === 'done') {
234
+ return { source: 'page', dlId, url: st.url, type: st.type, suggestedFilename: st.filename, size: st.size }
235
+ }
236
+ if (st.status === 'error') throw new Error(st.error || '页面导出读取失败')
237
+ }
238
+ if (!downloadStarted && Date.now() >= startLimit) throw new Error('等待下载开始超时')
239
+ await sleep(120)
240
+ }
241
+ return new Promise(() => {})
242
+ })()
243
+
244
+ const startGuard = new Promise((_, rej) => {
245
+ const ms = Math.min(15000, check())
246
+ const t = setTimeout(() => { if (!settled && !downloadStarted) rej(new Error('等待下载开始超时')) }, ms)
247
+ captured.then(() => clearTimeout(t), () => clearTimeout(t))
248
+ pollPage.then(() => clearTimeout(t), () => clearTimeout(t))
249
+ interrupted.then(() => clearTimeout(t))
250
+ })
251
+
252
+ const result = await within(
253
+ Promise.race([captured, pollPage, startGuard, interrupted.then(() => { throw new Error('下载已中止') })]),
254
+ Math.min(timeoutMs, check()),
255
+ '等待下载完成超时',
256
+ )
257
+ check()
258
+ keepPageData = result.source === 'page'
259
+ return result
260
+ } finally {
261
+ settled = true
262
+ stopTracking?.()
263
+ try {
264
+ if (unregisterFetch) await within(unregisterFetch(), 2000, '关闭拦截超时')
265
+ } catch {}
266
+ try {
267
+ await within(chrome.scripting.executeScript({ target: { tabId: id }, world: 'MAIN', injectImmediately: true,
268
+ args: [dlId, !keepPageData], func: (id, dropData) => {
269
+ if (window.__dshClickDl?.id === id) window.__dshClickDlCleanup?.(dropData)
270
+ } }), 1500, '清理下载超时')
271
+ } catch {}
272
+ S.activeDownload = null
273
+ cleanup()
274
+ }
275
+ }
276
+
277
+ export {
278
+ clickAndDownload,
279
+ }