dsh-chrome-bridge 2.0.3 → 2.1.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 (49) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/core/ext.js +8 -1
  4. package/core/hosts.js +3 -4
  5. package/core/receipt.js +228 -31
  6. package/core/session.js +11 -14
  7. package/core/tooldef.js +10 -1
  8. package/core/transport.js +67 -17
  9. package/drag.js +10 -10
  10. package/features/frames.js +5 -2
  11. package/i18n/en.js +34 -7
  12. package/i18n/ru.js +34 -7
  13. package/i18n/zh.js +34 -7
  14. package/nav.js +103 -32
  15. package/package.json +1 -1
  16. package/refs.js +309 -73
  17. package/tools/batch.js +311 -0
  18. package/tools/click.js +37 -11
  19. package/tools/dialog.js +19 -2
  20. package/tools/drag.js +31 -5
  21. package/tools/fill.js +71 -22
  22. package/tools/index.js +3 -1
  23. package/tools/input.js +97 -36
  24. package/tools/nav.js +46 -23
  25. package/tools/read.js +2 -0
  26. package/tools/tabs.js +16 -2
  27. package/tools/wait.js +14 -6
  28. package/vendor/extension/in-page-cursor.js +1 -1
  29. package/vendor/extension/manifest.json +1 -1
  30. package/vendor/extension/popup.css +1 -0
  31. package/vendor/extension/popup.html +6 -3
  32. package/vendor/extension/popup.js +19 -13
  33. package/vendor/extension/sw/actions.js +573 -0
  34. package/vendor/extension/sw/boot.js +2 -1
  35. package/vendor/extension/sw/cdp.js +139 -11
  36. package/vendor/extension/sw/conditions.js +176 -0
  37. package/vendor/extension/sw/confirm.js +39 -7
  38. package/vendor/extension/sw/cursor.js +176 -14
  39. package/vendor/extension/sw/dispatch.js +6 -1
  40. package/vendor/extension/sw/frames.js +543 -47
  41. package/vendor/extension/sw/lifecycle.js +82 -0
  42. package/vendor/extension/sw/ops.js +801 -139
  43. package/vendor/extension/sw/page-access.js +292 -0
  44. package/vendor/extension/sw/popup-api.js +28 -7
  45. package/vendor/extension/sw/snapshot.js +251 -0
  46. package/vendor/extension/sw/state.js +16 -5
  47. package/vendor/extension/sw/tabui.js +9 -2
  48. package/vendor/in-page-cursor.js +1 -1
  49. package/vendor/skill/SKILL.md +8 -7
@@ -20,6 +20,9 @@ function rememberAttached(id) {
20
20
  }
21
21
 
22
22
  function forgetAttached(id, reason) {
23
+ S.mainDocuments.delete(id)
24
+ S.recentSecrets.delete(id)
25
+ for (const [key, snap] of S.frameSnapshots) if (snap.tabId === id) S.frameSnapshots.delete(key)
23
26
  if (S.attached.delete(id)) notify(S.tabDetached, id, reason)
24
27
  }
25
28
 
@@ -51,12 +54,24 @@ async function ensure(tabId) {
51
54
  try { await chrome.debugger.attach({ tabId: id }, CDP_VERSION) }
52
55
  catch (e) { if (!String(e.message || e).includes('Already attached')) throw e }
53
56
  try {
54
- for (const d of ['Page', 'DOM', 'Runtime', 'Network', 'Log']) {
57
+ const enable = async (method, params = {}, optional = false) => {
58
+ check()
59
+ try { await chrome.debugger.sendCommand({ tabId: id }, method, params) }
60
+ catch (error) { if (!optional) throw error }
55
61
  check()
56
- await chrome.debugger.sendCommand({ tabId: id }, d + '.enable', {})
57
62
  }
58
- check()
59
- await chrome.debugger.sendCommand({ tabId: id }, 'Emulation.setFocusEmulationEnabled', { enabled: true })
63
+ await Promise.all([
64
+ ...['Page', 'DOM', 'Runtime', 'Network', 'Log'].map(domain => enable(domain + '.enable')),
65
+ enable('Emulation.setFocusEmulationEnabled', { enabled: true }),
66
+ enable('Page.setLifecycleEventsEnabled', { enabled: true }, true),
67
+ chrome.debugger.sendCommand({ tabId: id }, 'Page.getFrameTree', {}).then((res) => {
68
+ const f = res?.frameTree?.frame
69
+ if (f?.id) {
70
+ S.mainDocuments.set(id, { id: f.id, loaderId: f.loaderId })
71
+ if (typeof f.url === 'string' && f.url) S.tabUrl.set(id, f.url)
72
+ }
73
+ }).catch(() => {}),
74
+ ])
60
75
  check()
61
76
  rememberAttached(id)
62
77
  await installInputListener(id)
@@ -100,7 +115,62 @@ async function send(tabId, method, params, timeoutMs = CDP_TIMEOUT_MS[method] ||
100
115
  let dispatchedOk = false
101
116
  try {
102
117
  if (method.startsWith('Input.')) {
103
- if (S.cursorReady.has(id) && (S.pageAgentUntil.get(id) || 0) < Date.now() + 400) {
118
+ const needCursorSync = S.cursorReady.has(id) && (S.pageAgentUntil.get(id) || 0) < Date.now() + 400
119
+ const docBinding = meta?.docBinding
120
+ if (docBinding) {
121
+ const bindErr = meta?.docBindingError || 'BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤'
122
+ const hashFn = `function(u){const s=String(u||'');let h1=0x811c9dc5,h2=0x9e3779b9;for(let i=0;i<s.length;i++){const c=s.charCodeAt(i);h1=Math.imul(h1^c,0x01000193);h2=Math.imul(h2^c,0x85ebca6b)}return (h1>>>0).toString(16).padStart(8,'0')+(h2>>>0).toString(16).padStart(8,'0')}`
123
+ const checkDocOnce = async (syncCursor) => {
124
+ const bindMs = Math.min(800, Math.max(50, timeLeft(deadline)))
125
+ let res
126
+ try {
127
+ res = await within(
128
+ chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
129
+ expression: `(() => {
130
+ const tok = globalThis.performance?.timeOrigin ?? (typeof window !== 'undefined' ? window.__dshDocToken : null);
131
+ const href = typeof location !== 'undefined' && location?.href ? location.href : '';
132
+ const hash = (${hashFn})(href);
133
+ const ok = ((typeof tok === 'number' && Number.isFinite(tok)) || (typeof tok === 'string' && tok.length > 0)) &&
134
+ (${docBinding.expectedDocToken != null ? `tok === ${JSON.stringify(docBinding.expectedDocToken)}` : 'true'}) &&
135
+ (${docBinding.expectedUrl ? `href === ${JSON.stringify(docBinding.expectedUrl)}` : 'true'}) &&
136
+ (${docBinding.expectedUrlHash ? `hash === ${JSON.stringify(docBinding.expectedUrlHash)}` : 'true'});
137
+ if (!ok) return { ok: false };
138
+ const synced = ${syncCursor ? 'Boolean(window.__dshCursor && window.__dshCursor.beginAgent && (window.__dshCursor.beginAgent(1500), true))' : 'false'};
139
+ return { ok: true, synced };
140
+ })()`,
141
+ returnByValue: true,
142
+ }),
143
+ bindMs,
144
+ 'BATCH_NAVIGATED 文档校验超时',
145
+ )
146
+ } catch {
147
+ throw new Error(bindErr)
148
+ }
149
+ if (res?.exceptionDetails || res?.result?.value?.ok !== true) {
150
+ throw new Error(bindErr)
151
+ }
152
+ if (res.result.value.synced) S.pageAgentUntil.set(id, Date.now() + 1500)
153
+ }
154
+ // Converge cross-frame guard and document-token check so no async gap remains before Input.*.
155
+ for (let tries = 0; tries < 3; tries++) {
156
+ if (typeof meta?.verifyFramesOnly === 'function') await meta.verifyFramesOnly()
157
+ if (S.paused) throw new Error(PAUSED_MSG)
158
+ if ((S.controlEpoch.get(id) || 0) !== epoch) throw new Error(RELEASED_MSG)
159
+ const genBeforeDoc = S.frameGeneration.get(id)
160
+ const listBeforeDoc = S.protectedListEpoch
161
+ await checkDocOnce(needCursorSync && tries === 0)
162
+ if (S.paused) throw new Error(PAUSED_MSG)
163
+ if ((S.controlEpoch.get(id) || 0) !== epoch) throw new Error(RELEASED_MSG)
164
+ if (typeof meta?.verifyFramesOnly === 'function' &&
165
+ (S.frameGeneration.get(id) !== genBeforeDoc || S.protectedListEpoch !== listBeforeDoc)) {
166
+ if (tries < 2) continue
167
+ throw new Error('USER_DENIED_SENSITIVE')
168
+ }
169
+ if (typeof check === 'function') check()
170
+ break
171
+ }
172
+ timeoutMs = timeLeft(deadline)
173
+ } else if (needCursorSync) {
104
174
  const syncMs = Math.min(500, Math.max(50, timeLeft(deadline)))
105
175
  let synced = false
106
176
  try {
@@ -194,12 +264,20 @@ function handleDetach(src, reason) {
194
264
  }
195
265
 
196
266
  function handleCdpEvent(src, method, params) {
197
- if (method === 'Page.loadEventFired') {
267
+ if (['Page.frameNavigated', 'Page.frameAttached', 'Page.frameDetached'].includes(method))
268
+ S.frameGeneration.set(src.tabId, (S.frameGeneration.get(src.tabId) || 0) + 1)
269
+ if (!src.sessionId) {
270
+ const phase = method === 'Page.lifecycleEvent' ? params.name : method === 'Page.domContentEventFired' ? 'DOMContentLoaded' : method === 'Page.loadEventFired' ? 'load' : null
271
+ if (phase) for (const entry of S.loadWaiters.get(src.tabId) || []) {
272
+ const frame = S.mainDocuments.get(src.tabId)
273
+ entry.observe(phase, params.frameId || frame?.id, params.loaderId || frame?.loaderId)
274
+ }
275
+ }
276
+ if (method === 'Page.loadEventFired' && !src.sessionId) {
198
277
  refreshControls(src.tabId)
199
278
  S.cursorReady.delete(src.tabId)
200
279
  S.pageAgentUntil.delete(src.tabId)
201
280
  markCursor(src.tabId, false).catch(() => {}) // 导航后页内光标没了,标签上的小鼠标跟着灭
202
- for (const entry of S.loadWaiters.get(src.tabId) || []) entry.finish(true)
203
281
  }
204
282
  if (method === 'Page.javascriptDialogOpening') {
205
283
  S.dialogs.set(src.tabId, { type: params.type, message: params.message, at: Date.now() })
@@ -223,11 +301,21 @@ function handleCdpEvent(src, method, params) {
223
301
  }
224
302
  if (method === 'Page.frameNavigated' && params.frame?.parentId && S.attached.has(src.tabId))
225
303
  void installInputListener(src.tabId)
226
- if (method === 'Page.frameNavigated' && params.frame && !params.frame.parentId) {
304
+ if (!src.sessionId && method === 'Page.frameNavigated' && params.frame && !params.frame.parentId) {
305
+ S.mainNavGeneration.set(src.tabId, (S.mainNavGeneration.get(src.tabId) || 0) + 1)
306
+ S.mainDocuments.set(src.tabId, { id: params.frame.id, loaderId: params.frame.loaderId })
307
+ for (const entry of S.loadWaiters.get(src.tabId) || []) entry.rebind?.(params.frame.id, params.frame.loaderId)
227
308
  if (typeof params.frame.url === 'string' && params.frame.url) S.tabUrl.set(src.tabId, params.frame.url)
228
309
  dropChooser(src.tabId) // 换页了,原来那个文件框也没了
229
310
  S.chooserSkip.delete(src.tabId)
230
311
  }
312
+ if (!src.sessionId && method === 'Page.navigatedWithinDocument') {
313
+ const main = S.mainDocuments.get(src.tabId)
314
+ if (main?.id && params.frameId && params.frameId === main.id) {
315
+ S.mainNavGeneration.set(src.tabId, (S.mainNavGeneration.get(src.tabId) || 0) + 1)
316
+ if (typeof params.url === 'string' && params.url) S.tabUrl.set(src.tabId, params.url)
317
+ }
318
+ }
231
319
  if (method === 'Network.requestWillBeSent') {
232
320
  // WebSocket/SSE 这类连接永不 finished,netPending 得有个上限(NET 有 400,它原来没有)
233
321
  if (S.netPending.size > NET_MAX) {
@@ -409,11 +497,51 @@ const __dsh_cover = (el, x, y) => {
409
497
  }
410
498
  return false;
411
499
  };
412
- if (!hit || inside(hit, el) || inside(el, hit)) return {};
500
+ if (!hit || inside(hit, el)) return {};
501
+ const visibleInClip = (node, px, py) => {
502
+ let anc = node.parentElement || node.getRootNode?.()?.host || null;
503
+ const clipRe = /hidden|clip|auto|scroll/;
504
+ while (anc && anc !== document.body && anc !== document.documentElement) {
505
+ const as = typeof getComputedStyle === 'function' ? getComputedStyle(anc) : null;
506
+ const cx = clipRe.test(as?.overflowX || as?.overflow || '');
507
+ const cy = clipRe.test(as?.overflowY || as?.overflow || '');
508
+ if ((cx || cy) && typeof anc.getBoundingClientRect === 'function') {
509
+ const ar = anc.getBoundingClientRect();
510
+ if (cx && (ar.width <= 0 || px < ar.left || px > ar.right)) return false;
511
+ if (cy && (ar.height <= 0 || py < ar.top || py > ar.bottom)) return false;
512
+ }
513
+ anc = anc.parentElement || anc.getRootNode?.()?.host || null;
514
+ }
515
+ return true;
516
+ };
517
+ const clickableAnc = (node) => {
518
+ if (!node || node === document.body || node === document.documentElement) return false;
519
+ const tag = node.tagName;
520
+ if (tag === 'A' || tag === 'BUTTON' || tag === 'LABEL' || tag === 'SUMMARY') return true;
521
+ const role = typeof node.getAttribute === 'function' ? (node.getAttribute('role') || '') : '';
522
+ if (/^(button|link|tab|menuitem|option|checkbox|radio|switch)$/i.test(role)) return true;
523
+ if (typeof node.onclick === 'function' || (typeof node.getAttribute === 'function' && (node.getAttribute('onclick') || node.getAttribute('tabindex') != null))) return true;
524
+ const hs = typeof getComputedStyle === 'function' ? getComputedStyle(node) : null;
525
+ return hs?.cursor === 'pointer';
526
+ };
527
+ if (inside(el, hit) && clickableAnc(hit) && visibleInClip(el, x, y)) {
528
+ const st = typeof getComputedStyle === 'function' ? getComputedStyle(el) : null;
529
+ if (st?.pointerEvents === 'none') return {};
530
+ }
413
531
  return { occluded: { tag: hit.tagName.toLowerCase(), text: __dsh_norm(hit.innerText).slice(0, 80),
414
532
  id: hit.id, className: hit.getAttribute('class') || '' } };
415
533
  };
416
534
  const __dsh_scroll_wait = (el) => {
535
+ const r = el.getBoundingClientRect(), view = el.ownerDocument?.defaultView || window;
536
+ if (r.top >= 0 && r.left >= 0 && r.bottom <= view.innerHeight && r.right <= view.innerWidth && r.width > 0 && r.height > 0) {
537
+ const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
538
+ const root = el.getRootNode?.();
539
+ const probe = typeof root?.elementFromPoint === 'function' ? root
540
+ : (typeof document?.elementFromPoint === 'function' ? document : null);
541
+ if (!probe) return;
542
+ const hit = probe.elementFromPoint(cx, cy);
543
+ if (hit === el || (hit && el.contains?.(hit))) return;
544
+ }
417
545
  el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
418
546
  return new Promise((res) => {
419
547
  let done = false;
@@ -438,8 +566,8 @@ const __dsh_point = async (el) => {
438
566
  };
439
567
  `
440
568
 
441
- async function pointOf(tabId, finderJs, deadline) {
442
- const pt = await evaluate(tabId, `(async () => { ${POINT_HELPER} ${finderJs} })()`, false, deadline && timeLeft(deadline))
569
+ async function pointOf(tabId, finderJs, deadline, check) {
570
+ const pt = await evaluate(tabId, `(async () => { ${POINT_HELPER} ${finderJs} })()`, false, deadline && timeLeft(deadline), check)
443
571
  if (!pt) throw new Error('没找到目标元素(可能不可见或文字不匹配)')
444
572
  if (pt.offscreen) throw new Error(`目标元素在视口外((${Math.round(pt.x)}, ${Math.round(pt.y)}) 超出 ${pt.vw}×${pt.vh}),请先滚动页面或容器`)
445
573
  return pt
@@ -0,0 +1,176 @@
1
+ import { ensure, evaluate } from './cdp.js'
2
+ import { makeClickGuard, RELEASED_MSG } from './cursor.js'
3
+ import { hashUrl, originOf, pageAccess, receiptOf, receiptState } from './page-access.js'
4
+ import { PAUSED_MSG, S } from './state.js'
5
+ import { sleep, within } from './util.js'
6
+
7
+ function observeCondition(args, maxMs, origin, token) {
8
+ if (location.origin !== origin) return null
9
+ const matches = () => {
10
+ if (args.phase) return document.readyState === 'complete' || (args.phase !== 'load' && document.readyState === 'interactive')
11
+ if (args.url !== undefined) return location.href.includes(args.url)
12
+ if (args.text !== undefined) return (document.body?.innerText || '').includes(args.text)
13
+ const el = document.querySelector(args.selector)
14
+ if (!el || args.visible === false) return !!el
15
+ const r = el.getBoundingClientRect(), st = getComputedStyle(el)
16
+ return r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none'
17
+ }
18
+ const hit = () => matches() !== !!args.gone
19
+ if (hit()) return true
20
+ return new Promise((resolve, reject) => {
21
+ let throttled = null
22
+ const observer = new MutationObserver(() => {
23
+ if (args.text !== undefined) {
24
+ if (!throttled) throttled = setTimeout(() => { throttled = null; check() }, 32)
25
+ return
26
+ }
27
+ check()
28
+ })
29
+ function finish(result, error) {
30
+ window.__dshWaits?.delete(token)
31
+ observer.disconnect()
32
+ clearTimeout(throttled)
33
+ clearInterval(tick)
34
+ clearTimeout(end)
35
+ if (error) reject(error)
36
+ else resolve(result)
37
+ }
38
+ function check() {
39
+ try { if (hit()) finish(true) } catch (error) { finish(false, error) }
40
+ }
41
+ const tick = setInterval(check, 64)
42
+ const end = setTimeout(() => finish(false), maxMs)
43
+ ;(window.__dshWaits ||= new Map()).set(token, () => finish(null))
44
+ observer.observe(document, { subtree: true, childList: true, characterData: true, attributes: true })
45
+ })
46
+ }
47
+
48
+ export async function waitCondition({ tabId, selector, text, url, gone, visible = true, timeoutMs = 15000, receipt = false, controlEpoch, noReattach = false, expectedUrl, expectedUrlHash, expectedDocToken, expectedNavGen: reqNavGen }, { phase, check } = {}) {
49
+ const id = Number(tabId), at = Date.now(), deadline = at + timeoutMs
50
+ const args = { selector, text, url, gone, visible, phase }
51
+ if (!phase && [selector, text, url].filter(x => typeof x === 'string' && x.length > 0).length !== 1)
52
+ throw new Error('Expected one selector, text or URL')
53
+ const batchBound = expectedDocToken != null || expectedUrl != null || expectedUrlHash != null || Number.isInteger(reqNavGen)
54
+ let expectedNavGen = Number.isInteger(reqNavGen) ? reqNavGen : undefined
55
+ const guard = makeClickGuard(id, undefined, () => {
56
+ if (S.releasing.has(id)) throw new Error(RELEASED_MSG)
57
+ if (Number.isInteger(controlEpoch) && (S.controlEpoch.get(id) || 0) !== controlEpoch) throw new Error(RELEASED_MSG)
58
+ if (expectedNavGen !== undefined && (S.mainNavGeneration.get(id) || 0) !== expectedNavGen) {
59
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
60
+ }
61
+ if (typeof check === 'function') check()
62
+ })
63
+ guard()
64
+ if (noReattach && !S.attached.has(id)) throw new Error(RELEASED_MSG)
65
+ await within(ensure(id), Math.max(1, timeoutMs), '等待调试器超时')
66
+ const seq = S.attachSeq.get(id)
67
+ const session = () => {
68
+ if (S.paused) throw new Error('PAUSED ' + PAUSED_MSG)
69
+ guard()
70
+ if (!S.attached.has(id) || S.attachSeq.get(id) !== seq) throw new Error('target_closed / ' + RELEASED_MSG)
71
+ }
72
+ const needBefore = receipt || batchBound
73
+ if (batchBound && expectedNavGen === undefined) expectedNavGen = S.mainNavGeneration.get(id) || 0
74
+ const before = needBefore && await receiptState(id, deadline, session)
75
+ if (batchBound) {
76
+ if (!before || before.reason || before.docToken == null ||
77
+ (S.mainNavGeneration.get(id) || 0) !== expectedNavGen ||
78
+ (expectedUrl && before.url !== expectedUrl) ||
79
+ (expectedUrlHash && hashUrl(before.url) !== expectedUrlHash) ||
80
+ (expectedDocToken != null && before.docToken !== expectedDocToken)) {
81
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
82
+ }
83
+ }
84
+ function cancelObserver(token) {
85
+ if (!S.attached.has(id) || S.attachSeq.get(id) !== seq) return
86
+ void chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
87
+ expression: `window.__dshWaits?.get(${JSON.stringify(token)})?.()`,
88
+ }).catch(() => {})
89
+ }
90
+ async function observe(page, remaining) {
91
+ const token = crypto.randomUUID(), generation = S.frameGeneration.get(id)
92
+ const expr = `(${observeCondition})(${JSON.stringify(args)},${remaining},${JSON.stringify(originOf(page.url))},${JSON.stringify(token)})`
93
+ let timer, settledInDocument = false
94
+ const signal = new Promise((resolve, reject) => {
95
+ timer = setInterval(() => {
96
+ try {
97
+ session()
98
+ if (S.frameGeneration.get(id) !== generation || S.dialogs.has(id)) resolve(null)
99
+ else if (Date.now() >= deadline) resolve(false)
100
+ } catch (error) { reject(error) }
101
+ }, 25)
102
+ })
103
+ try {
104
+ const result = evaluate(id, expr, false, remaining + 100, session).then(value => {
105
+ settledInDocument = true
106
+ return value
107
+ })
108
+ return await Promise.race([result, signal])
109
+ } catch (error) {
110
+ session()
111
+ if (!/context.*(?:destroyed|not found)|cannot find context|navigat|inspected target navigated/i.test(error.message)) throw error
112
+ return null
113
+ } finally {
114
+ clearInterval(timer)
115
+ if (!settledInDocument) cancelObserver(token)
116
+ }
117
+ }
118
+
119
+ while (Date.now() < deadline) {
120
+ session()
121
+ const page = await pageAccess(id)
122
+ if (page.reason === 'protected') throw new Error('USER_DENIED_SENSITIVE')
123
+ if (page.reason === 'dialog') break
124
+ const remaining = deadline - Date.now()
125
+ if (remaining <= 0) break
126
+ const matched = await observe(page, remaining)
127
+ session()
128
+ if (matched === false) break
129
+ if (!matched) { await sleep(16); continue }
130
+ const after = await pageAccess(id)
131
+ if (after.reason === 'protected') throw new Error('USER_DENIED_SENSITIVE')
132
+ if (after.reason || after.url !== page.url) continue
133
+ if (phase === 'idle') {
134
+ const idleStart = Date.now()
135
+ let quiet = false
136
+ while (Date.now() < deadline) {
137
+ session()
138
+ const busy = [...S.netPending.values()].some(r => r.tabId === id && !['EventSource', 'WebSocket'].includes(r.type))
139
+ if (!busy && Date.now() - Math.max(idleStart, S.netChanged.get(id) || 0) >= 500) {
140
+ quiet = true
141
+ break
142
+ }
143
+ await sleep(Math.min(25, Math.max(1, deadline - Date.now())))
144
+ }
145
+ if (!quiet) break
146
+ }
147
+ session()
148
+ const out = { matched: true, waitedMs: Date.now() - at }
149
+ if (before) {
150
+ const after = await receiptState(id, Math.max(Date.now() + 500, deadline), session, [], originOf(before.url), before.url)
151
+ session()
152
+ if (batchBound && (after.reason === 'origin_changed' || after.docToken == null ||
153
+ (expectedUrl && after.url !== expectedUrl) ||
154
+ (expectedUrlHash && hashUrl(after.url) !== expectedUrlHash) ||
155
+ (expectedDocToken != null && after.docToken !== expectedDocToken))) {
156
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
157
+ }
158
+ if (receipt) out.receipt = receiptOf(id, before, after)
159
+ }
160
+ return out
161
+ }
162
+ session()
163
+ const out = { matched: false, waitedMs: Date.now() - at }
164
+ if (before && (receipt || batchBound)) {
165
+ const after = await receiptState(id, Math.max(Date.now() + 500, deadline), session, [], originOf(before.url), before.url)
166
+ session()
167
+ if (batchBound && (after.reason === 'origin_changed' || after.docToken == null ||
168
+ (expectedUrl && after.url !== expectedUrl) ||
169
+ (expectedUrlHash && hashUrl(after.url) !== expectedUrlHash) ||
170
+ (expectedDocToken != null && after.docToken !== expectedDocToken))) {
171
+ throw new Error('BATCH_NAVIGATED 页面在步骤之间已变化或刷新,已停止后续步骤')
172
+ }
173
+ if (receipt) out.receipt = receiptOf(id, before, after)
174
+ }
175
+ return out
176
+ }
@@ -27,8 +27,9 @@ const NO_TAB = 0
27
27
  */
28
28
  const GATED_OPS = new Set([
29
29
  'click', 'clickEl', 'clickText', 'type', 'key', 'select', 'upload', 'focus', 'hover', 'scroll',
30
- 'nav', 'eval', 'cdp', 'clickAndDownload', 'dialog', 'open', 'info',
30
+ 'nav', 'historyNav', 'eval', 'cdp', 'clickAndDownload', 'dialog', 'open', 'info',
31
31
  'text', 'html', 'attr', 'shot', 'shotMarked', 'waitFor', 'network', 'networkIdle', 'console', 'screencast',
32
+ 'act', 'dragGesture', 'waitCondition', 'snapshotScan',
32
33
  'mockSet', 'harStart', 'harExport',
33
34
  'frameSnapshot', 'frameTexts', 'frameLocate', 'frameSetField', 'frameSelect',
34
35
  'recordStart', 'recordStop', 'recordClip',
@@ -46,6 +47,7 @@ function fresh() {
46
47
  writes: Promise.resolve(),
47
48
  /** tabId → Map(origin → 到期时刻) */
48
49
  grants: new Map(),
50
+ frameCache: new Map(),
49
51
  /** 确认 id → entry */
50
52
  pending: new Map(),
51
53
  /** `${tabId}|${origin}` → entry:同一处并发的请求共用一个确认窗 */
@@ -146,6 +148,7 @@ function restoreProtectedSites() {
146
148
  C.sites = sanitizeList(v && v.protectedSites)
147
149
  C.loaded = true
148
150
  C.loadFailed = false
151
+ S.protectedListEpoch = (S.protectedListEpoch || 0) + 1
149
152
  }, (e) => {
150
153
  if (C.ready !== job) return
151
154
  log('读受保护网站清单失败:', String((e && e.message) || e))
@@ -187,8 +190,9 @@ function serial(fn) {
187
190
  async function save(next) {
188
191
  const prev = C.sites
189
192
  C.sites = next // 先改内存:存储的 onChanged 回调一比就知道是我们自己写的
193
+ S.protectedListEpoch = (S.protectedListEpoch || 0) + 1
190
194
  try { await chrome.storage.local.set({ protectedSites: next }) }
191
- catch (e) { C.sites = prev; throw e }
195
+ catch (e) { C.sites = prev; S.protectedListEpoch = (S.protectedListEpoch || 0) + 1; throw e }
192
196
  }
193
197
 
194
198
  async function addProtectedSite(input) {
@@ -361,6 +365,7 @@ const DENY_WHY = {
361
365
  const deniedError = (r) => new Error(`USER_DENIED_SENSITIVE ${(DENY_WHY[r.reason] || DENY_WHY.denied).replace('%h', r.host || '')}`)
362
366
 
363
367
  const CROSS_FRAME_OPS = new Set([
368
+ 'act', 'dragGesture', 'waitCondition', 'snapshotScan',
364
369
  'shot', 'shotMarked', 'screencast', 'recordStart', 'recordClip',
365
370
  'frameSnapshot', 'frameTexts', 'frameLocate', 'frameSetField', 'frameSelect',
366
371
  ])
@@ -370,7 +375,7 @@ const isCrossFrameOp = (op, args = {}) =>
370
375
  const addOrigin = (set, url) => { const o = url ? originOf(url) : ''; if (o) set.add(o) }
371
376
 
372
377
  /** 标签页里所有子帧(含跨站 iframe)的网址;返回 { ok, urls },API 缺失 / 空结果 / 超时 / 报错一律 ok=false */
373
- async function frameUrls(tabId) {
378
+ async function probeFrameUrls(tabId) {
374
379
  if (!chrome.scripting?.executeScript) return { ok: false, urls: [] }
375
380
  let timer
376
381
  try {
@@ -387,14 +392,31 @@ async function frameUrls(tabId) {
387
392
  } finally { clearTimeout(timer) }
388
393
  }
389
394
 
395
+ async function frameUrls(tabId, fresh = false, attempt = 0) {
396
+ // Detached tabs have no CDP invalidation stream. Never reuse their observations.
397
+ if (!S.attached.has(tabId)) return probeFrameUrls(tabId)
398
+ const prior = C.frameCache.get(tabId)
399
+ if (!fresh && prior && prior.expires > Date.now()) return prior.promise
400
+ const entry = { expires: Date.now() + 1000 }
401
+ C.frameCache.set(tabId, entry)
402
+ entry.promise = probeFrameUrls(tabId).then(result => {
403
+ if (C.frameCache.get(tabId) !== entry) {
404
+ return attempt < 1 ? frameUrls(tabId, true, attempt + 1) : { ok: false, urls: [] }
405
+ }
406
+ if (!result.ok) C.frameCache.delete(tabId)
407
+ return result
408
+ })
409
+ return entry.promise
410
+ }
411
+
390
412
  /** 清单非空时检查该标签页全部框架(含跨进程 OOPIF)是否均允许访问;无法核实时 fail-closed 返回 false */
391
- async function areAllFramesAllowed(tabId) {
413
+ async function areAllFramesAllowed(tabId, autoObserve = false, fresh = false) {
392
414
  if (!hasProtectedSites()) return true
393
415
  const id = Number(tabId)
394
416
  if (!Number.isInteger(id)) return false
395
- const probed = await frameUrls(id)
417
+ const probed = await frameUrls(id, fresh)
396
418
  if (!probed.ok) return false
397
- return probed.urls.every((u) => isUrlAllowed(id, u))
419
+ return probed.urls.every(u => autoObserve ? !matchesProtectedSite(u) && isUrlAllowed(id, u) : isUrlAllowed(id, u))
398
420
  }
399
421
 
400
422
  /** 这个操作会碰到哪些网址:标签页现在的(和正在去的)地址、它的所有子帧,加上 nav / cdp / 新操作参数里指着的地址 */
@@ -442,7 +464,7 @@ async function recheck(tabId, pageOrigins, host, strict = true, op = '', args =
442
464
  throw deniedError({ reason: 'navigated', host })
443
465
  }
444
466
  if (strict && C.sites.length && isCrossFrameOp(op, args)) {
445
- const probed = await frameUrls(tabId)
467
+ const probed = await frameUrls(tabId, true)
446
468
  if (!probed.ok) throw new Error('USER_DENIED_SENSITIVE 放行后无法复核内嵌框架来源,本次操作已取消')
447
469
  for (const u of probed.urls) {
448
470
  if (matchesProtectedSite(u) && !hasGrant(tabId, originOf(u)))
@@ -460,6 +482,7 @@ async function gate({ op, args = {}, client } = {}) {
460
482
  // 每个请求前先把清单读到(读到过就是现成的,不花时间):后面的操作里 hasProtectedSites / isUrlAllowed 才准
461
483
  await loadProtectedSites()
462
484
  if (!GATED_OPS.has(op)) return
485
+ if (op === 'snapshotScan' && args.autoObserve === true) return // silent read is checked before and after scanning
463
486
  await ready()
464
487
  if (!C.sites.length || S.paused) return // 暂停了交给后面的暂停检查直接拒,不弹窗
465
488
  const tabId = args.tabId != null && args.tabId !== '' ? Number(args.tabId) : null
@@ -552,7 +575,10 @@ function resolveConfirmation({ id, nonce, allow } = {}, sender) {
552
575
 
553
576
  function onTabUpdated(tabId, change) {
554
577
  if (!change || !change.url) return
578
+ C.frameCache.delete(tabId)
555
579
  const now = originOf(change.url)
580
+ const prevSecret = S.recentSecrets.get(tabId)
581
+ if (prevSecret && prevSecret.origin !== now) S.recentSecrets.delete(tabId)
556
582
  const m = C.grants.get(tabId)
557
583
  if (m) for (const o of [...m.keys()]) if (o !== now) m.delete(o) // 离开了那个 origin:放行作废
558
584
  // 等确认期间换到了别的 origin:用户看到的那一页已经不在了,确认按拒绝收掉、关窗
@@ -562,6 +588,8 @@ function onTabUpdated(tabId, change) {
562
588
  }
563
589
 
564
590
  function onTabRemoved(tabId) {
591
+ C.frameCache.delete(tabId)
592
+ S.recentSecrets.delete(tabId)
565
593
  revokeTabGrants(tabId, 'tabClosed')
566
594
  }
567
595
 
@@ -571,6 +599,7 @@ function onWindowRemoved(windowId) {
571
599
 
572
600
  /** 调试器断开:空闲自动断开(idle)不算解绑,放行留着;别的(主动解绑、用户点掉调试提示条、标签页没了……)一律作废 */
573
601
  function onDebuggerDetached(tabId, reason) {
602
+ C.frameCache.delete(tabId)
574
603
  if (reason === 'idle') return
575
604
  revokeTabGrants(tabId, reason === 'target_closed' ? 'tabClosed' : 'detached')
576
605
  }
@@ -585,6 +614,9 @@ function initConfirm() {
585
614
  if (C.unhook) return
586
615
  restoreProtectedSites()
587
616
  C.unhook = subscribe(S.preHooks, gate)
617
+ C.listeners.push(subscribe(S.cdpEvents, (src, method) => {
618
+ if (['Page.frameAttached', 'Page.frameNavigated', 'Page.frameDetached', 'Page.navigatedWithinDocument'].includes(method)) C.frameCache.delete(src.tabId)
619
+ }))
588
620
  C.listeners.push(subscribe(S.tabDetached, onDebuggerDetached))
589
621
  listen(chrome.tabs && chrome.tabs.onUpdated, onTabUpdated)
590
622
  listen(chrome.tabs && chrome.tabs.onRemoved, onTabRemoved)