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
@@ -0,0 +1,292 @@
1
+ import { areAllFramesAllowed, hasProtectedSites, isUrlAllowed, loadProtectedSites, matchesProtectedSite } from './confirm.js'
2
+ import { evaluate } from './cdp.js'
3
+ import { isSensitiveField } from './frames.js'
4
+ import { S } from './state.js'
5
+ import { isExtUrl, timeLeft } from './util.js'
6
+
7
+ export function originOf(url) {
8
+ try { return new URL(url).origin } catch { return '' }
9
+ }
10
+
11
+ export function isOpaqueOrigin(origin) {
12
+ return !origin || origin === 'null'
13
+ }
14
+
15
+ export function hashUrl(url) {
16
+ const s = String(url || '')
17
+ let h1 = 0x811c9dc5, h2 = 0x9e3779b9
18
+ for (let i = 0; i < s.length; i++) {
19
+ const c = s.charCodeAt(i)
20
+ h1 = Math.imul(h1 ^ c, 0x01000193)
21
+ h2 = Math.imul(h2 ^ c, 0x85ebca6b)
22
+ }
23
+ return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0')
24
+ }
25
+
26
+ // Metadata is inspected outside the document. Protected titles, paths, dialogs and live regions never enter a receipt.
27
+ export async function pageAccess(id, { autoObserve = false, expectedOrigin, expectedUrl, frames = true } = {}) {
28
+ let tab
29
+ try { tab = await chrome.tabs.get(id) } catch (error) {
30
+ if (autoObserve) return { url: '', title: '', reason: 'protected' }
31
+ throw error
32
+ }
33
+ const pendingUrl = tab.pendingUrl || ''
34
+ const committedUrl = tab.url || ''
35
+ const url = pendingUrl || committedUrl
36
+ const urls = [pendingUrl, committedUrl, S.tabUrl.get(id)].filter(Boolean)
37
+ let protectedSite = urls.some(isExtUrl)
38
+ if (!protectedSite && hasProtectedSites()) {
39
+ protectedSite = !await loadProtectedSites() || !urls.length ||
40
+ urls.some(u => !isUrlAllowed(id, u) || (autoObserve && matchesProtectedSite(u))) ||
41
+ (frames && !await areAllFramesAllowed(id, autoObserve))
42
+ }
43
+ if (protectedSite) return { url: originOf(urls.find(u => isExtUrl(u) || !isUrlAllowed(id, u) || (autoObserve && matchesProtectedSite(u))) || url), committedUrl: '', committedSameOrigin: false, title: '', reason: 'protected' }
44
+ const urlOrigin = originOf(url)
45
+ const committedOrigin = originOf(committedUrl)
46
+ const committedSameOrigin = Boolean(committedUrl) && (!pendingUrl || (!isOpaqueOrigin(committedOrigin) && committedOrigin === urlOrigin) || committedUrl === url)
47
+ const originMismatch = expectedOrigin !== undefined && (isOpaqueOrigin(expectedOrigin)
48
+ ? (!expectedUrl || url !== expectedUrl || (Boolean(committedUrl) && committedUrl !== expectedUrl))
49
+ : (isOpaqueOrigin(urlOrigin) || expectedOrigin !== urlOrigin || (Boolean(committedUrl) && committedOrigin !== expectedOrigin)))
50
+ if (originMismatch) {
51
+ return { url: urlOrigin, committedUrl, committedSameOrigin, title: '', reason: 'origin_changed' }
52
+ }
53
+ return {
54
+ url,
55
+ committedUrl,
56
+ committedSameOrigin,
57
+ title: committedSameOrigin ? (tab.title || '') : '',
58
+ ...(committedSameOrigin && S.dialogs.has(id) && { reason: 'dialog' }),
59
+ }
60
+ }
61
+
62
+ function liveRegions(masked) {
63
+ const secrets = new Set()
64
+ const collectSecrets = (root) => {
65
+ for (const el of root.querySelectorAll('*')) {
66
+ if (secrets.size >= 50) return
67
+ if (el.shadowRoot) collectSecrets(el.shadowRoot)
68
+ if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
69
+ try { if (el.contentDocument?.body) collectSecrets(el.contentDocument) } catch {}
70
+ }
71
+ if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && !el.isContentEditable) continue
72
+ const view = el.ownerDocument?.defaultView || window
73
+ if (masked(el, view.getComputedStyle(el), true)) {
74
+ const value = el.isContentEditable ? el.innerText : el.value
75
+ if (value && String(value).length >= 4) secrets.add(String(value).slice(0, 512))
76
+ }
77
+ }
78
+ }
79
+ collectSecrets(document)
80
+ const selfOrigin = typeof self !== 'undefined' && typeof self.origin === 'string' ? self.origin : location.origin
81
+ const live = []
82
+ const regions = document.querySelectorAll('[role="alert"],[role="status"],[aria-live="polite"],[aria-live="assertive"]')
83
+ if (!regions.length) return { live, secrets: [...secrets], selfOrigin }
84
+ const escRe = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
85
+ const enc = typeof TextEncoder === 'function' ? new TextEncoder() : null
86
+ const buildRegex = (secret) => {
87
+ if (!enc || secret.length > 256) return null
88
+ let pat = ''
89
+ for (const ch of secret) {
90
+ if (ch === ' ') { pat += '(?: |%20|\\+)'; continue }
91
+ if (/^[a-zA-Z0-9]$/.test(ch)) { pat += ch; continue }
92
+ let pct = ''
93
+ for (const b of enc.encode(ch)) {
94
+ const h = b.toString(16).padStart(2, '0')
95
+ pct += '%' + h.replace(/[a-f]/g, c => '[' + c + c.toUpperCase() + ']')
96
+ }
97
+ pat += '(?:' + escRe(ch) + '|' + pct + ')'
98
+ }
99
+ return new RegExp(pat, 'g')
100
+ }
101
+ const rules = [...secrets].sort((a, b) => b.length - a.length).map(value => {
102
+ const re = buildRegex(value)
103
+ if (re) return { value, re, extras: [] }
104
+ const extras = new Set()
105
+ try {
106
+ const e1 = encodeURIComponent(value)
107
+ if (e1 && e1 !== value) { extras.add(e1); if (e1.includes('%20')) extras.add(e1.replace(/%20/g, '+')) }
108
+ const e2 = typeof URLSearchParams === 'function' ? new URLSearchParams([['x', value]]).toString().slice(2) : ''
109
+ if (e2 && e2 !== value) { extras.add(e2); if (e2.includes('+')) extras.add(e2.replace(/\+/g, '%20')) }
110
+ } catch {}
111
+ return { value, re: null, extras: [...extras].map(v => new RegExp(escRe(v), 'gi')) }
112
+ })
113
+ for (const el of regions) {
114
+ const st = getComputedStyle(el)
115
+ if (!el.getClientRects().length || st.visibility !== 'visible' || st.opacity === '0') continue
116
+ if ([el, ...el.querySelectorAll('input,textarea,[contenteditable]')].some(node => masked(node, getComputedStyle(node), true))) continue
117
+ let safe = el.innerText || ''
118
+ for (const { value, re, extras } of rules) {
119
+ if (re) safe = safe.replace(re, '••••')
120
+ else {
121
+ safe = safe.replaceAll(value, '••••')
122
+ for (const x of extras) safe = safe.replace(x, '••••')
123
+ }
124
+ }
125
+ const normText = safe.replace(/\s+/g, ' ').trim()
126
+ const text = normText.length > 16384 ? '__DSH_TOO_LONG__' : normText
127
+ if (text && !live.includes(text)) live.push(text)
128
+ if (live.length >= 30) break
129
+ }
130
+ return { live, secrets: [...secrets], selfOrigin }
131
+ }
132
+
133
+ export async function receiptState(id, deadline, guard, _secrets = [], beforeOrigin, beforeUrl) {
134
+ const accessOpts = beforeOrigin !== undefined
135
+ ? { expectedOrigin: beforeOrigin, ...(isOpaqueOrigin(beforeOrigin) && beforeUrl ? { expectedUrl: beforeUrl } : {}) }
136
+ : {}
137
+ const page = await pageAccess(id, accessOpts)
138
+ if (page.reason) return { ...page, selfOrigin: '', navGeneration: S.mainNavGeneration.get(Number(id)) || 0, live: [], secrets: [] }
139
+ const expected = originOf(page.url)
140
+ const opaque = isOpaqueOrigin(expected)
141
+ const originCheck = opaque ? `location.href === ${JSON.stringify(page.url)}` : `location.origin === ${JSON.stringify(expected)}`
142
+ // Never serialize cached SW secrets into any page world; SW redacts complete fields before truncation.
143
+ const expression = `${originCheck} ? { docToken: (globalThis.performance?.timeOrigin ?? (window.__dshDocToken ||= Math.random().toString(36).slice(2))), ...(${liveRegions})(${isSensitiveField}) } : null`
144
+ let state
145
+ try { state = await evaluate(id, expression, false, Math.min(1200, timeLeft(deadline)), guard) }
146
+ catch { guard?.() }
147
+ const after = await pageAccess(id, accessOpts)
148
+ if (after.reason === 'protected' || after.reason === 'origin_changed') {
149
+ return { ...after, selfOrigin: '', navGeneration: S.mainNavGeneration.get(Number(id)) || 0, live: [], secrets: [] }
150
+ }
151
+ const valid = !after.reason && page.url === after.url && state && typeof state === 'object'
152
+ const selfOrigin = valid && typeof state.selfOrigin === 'string' ? state.selfOrigin : ''
153
+ const foundSecrets = valid && Array.isArray(state.secrets) ? state.secrets : []
154
+ if (isOpaqueOrigin(selfOrigin) || opaque) {
155
+ S.recentSecrets.delete(Number(id))
156
+ } else if (foundSecrets.length && !after.reason) {
157
+ rememberSecrets(id, selfOrigin, foundSecrets)
158
+ }
159
+ return {
160
+ ...after,
161
+ selfOrigin,
162
+ navGeneration: S.mainNavGeneration.get(Number(id)) || 0,
163
+ docToken: valid ? state.docToken : undefined,
164
+ live: valid && Array.isArray(state.live) ? state.live : [],
165
+ secrets: foundSecrets,
166
+ }
167
+ }
168
+
169
+ const SECRET_TTL_MS = 15_000
170
+
171
+ export function rememberSecrets(tabId, origin, secrets) {
172
+ const id = Number(tabId)
173
+ if (isOpaqueOrigin(origin)) {
174
+ S.recentSecrets.delete(id)
175
+ return
176
+ }
177
+ if (!Array.isArray(secrets) || !secrets.length) return
178
+ const now = Date.now()
179
+ const prev = S.recentSecrets.get(id)
180
+ const values = prev && prev.origin === origin && prev.expiresAt > now ? prev.values : new Set()
181
+ for (const v of secrets) {
182
+ if (typeof v === 'string' && v.length >= 4 && values.size < 50) values.add(v.slice(0, 512))
183
+ }
184
+ if (values.size) S.recentSecrets.set(id, { origin, expiresAt: now + SECRET_TTL_MS, values })
185
+ }
186
+
187
+ export function getRecentSecrets(tabId, origin) {
188
+ const id = Number(tabId)
189
+ if (isOpaqueOrigin(origin)) return []
190
+ const entry = S.recentSecrets.get(id)
191
+ if (!entry) return []
192
+ if (entry.expiresAt <= Date.now() || entry.origin !== origin) {
193
+ S.recentSecrets.delete(id)
194
+ return []
195
+ }
196
+ return [...entry.values]
197
+ }
198
+
199
+ export function makeSecretRedactor(secrets, minLen = 4) {
200
+ const ordered = [...new Set((secrets || []).filter(v => typeof v === 'string' && v.length >= minLen))].sort((a, b) => b.length - a.length)
201
+ if (!ordered.length) return text => String(text ?? '')
202
+ const escRe = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
203
+ const enc = new TextEncoder()
204
+ const rules = ordered.map(value => {
205
+ if (value.length <= 256) {
206
+ let pat = ''
207
+ for (const ch of value) {
208
+ if (ch === ' ') { pat += '(?: |%20|\\+)'; continue }
209
+ if (/^[a-zA-Z0-9]$/.test(ch)) { pat += ch; continue }
210
+ let pct = ''
211
+ for (const b of enc.encode(ch)) {
212
+ const h = b.toString(16).padStart(2, '0')
213
+ pct += '%' + h.replace(/[a-f]/g, c => '[' + c + c.toUpperCase() + ']')
214
+ }
215
+ pat += '(?:' + escRe(ch) + '|' + pct + ')'
216
+ }
217
+ return { value, re: new RegExp(pat, 'g'), extras: [] }
218
+ }
219
+ const extras = new Set()
220
+ try {
221
+ const e1 = encodeURIComponent(value)
222
+ if (e1 && e1 !== value) { extras.add(e1); if (e1.includes('%20')) extras.add(e1.replace(/%20/g, '+')) }
223
+ const e2 = new URLSearchParams([['x', value]]).toString().slice(2)
224
+ if (e2 && e2 !== value) { extras.add(e2); if (e2.includes('+')) extras.add(e2.replace(/\+/g, '%20')) }
225
+ } catch {}
226
+ return { value, re: null, extras: [...extras].map(v => new RegExp(escRe(v), 'gi')) }
227
+ })
228
+ return text => {
229
+ let out = String(text ?? '')
230
+ for (const { value, re, extras } of rules) {
231
+ if (re) out = out.replace(re, '••••')
232
+ else {
233
+ out = out.replaceAll(value, '••••')
234
+ for (const x of extras) out = out.replace(x, '••••')
235
+ }
236
+ }
237
+ return out
238
+ }
239
+ }
240
+
241
+ export function receiptOf(id, before, after, openedTabs, secrets = [], allowOriginChange = false) {
242
+ const protectedSite = after.reason === 'protected'
243
+ const originReason = after.reason === 'origin_changed'
244
+ const liveUpdate = after.live?.find(line => before.live && !before.live.includes(line)) || null
245
+ const beforeOrigin = originOf(before?.url)
246
+ const afterOrigin = originOf(after?.url)
247
+ const effBeforeOrigin = before?.selfOrigin !== undefined ? before.selfOrigin : beforeOrigin
248
+ const effAfterOrigin = after?.selfOrigin !== undefined ? after.selfOrigin : afterOrigin
249
+ const cacheOpaque = isOpaqueOrigin(afterOrigin) || isOpaqueOrigin(beforeOrigin) || isOpaqueOrigin(effAfterOrigin) || isOpaqueOrigin(effBeforeOrigin)
250
+ const hardOpaque = isOpaqueOrigin(afterOrigin) || isOpaqueOrigin(beforeOrigin) || after?.selfOrigin === 'null' || before?.selfOrigin === 'null'
251
+ const unverifiedOrigin = isOpaqueOrigin(effAfterOrigin) || isOpaqueOrigin(effBeforeOrigin)
252
+ const sameOrigin = !originReason && !cacheOpaque && effBeforeOrigin === effAfterOrigin && beforeOrigin === afterOrigin
253
+ const prior = sameOrigin ? getRecentSecrets(id, effAfterOrigin) : []
254
+ // Never store or reuse cached secrets when the actual security origin is opaque or unverified (e.g. dialog early return / sandboxed HTTPS).
255
+ if (protectedSite || originReason || isOpaqueOrigin(afterOrigin) || isOpaqueOrigin(effAfterOrigin)) {
256
+ S.recentSecrets.delete(Number(id))
257
+ } else if (sameOrigin) {
258
+ const sameOriginSecrets = [...(secrets || []), ...(before?.secrets || []), ...(after?.secrets || []), ...prior]
259
+ if (sameOriginSecrets.length) rememberSecrets(id, effAfterOrigin, sameOriginSecrets)
260
+ } else {
261
+ S.recentSecrets.delete(Number(id))
262
+ if (after?.secrets?.length) rememberSecrets(id, effAfterOrigin, after.secrets)
263
+ }
264
+ const allSecrets = [...(secrets || []), ...(before?.secrets || []), ...(after?.secrets || []), ...prior]
265
+ const redactMeta = makeSecretRedactor(allSecrets, 6)
266
+ const redactText = makeSecretRedactor(allSecrets, 4)
267
+ const committedOrigin = after.committedUrl ? originOf(after.committedUrl) : ''
268
+ const committedMatches = after.committedSameOrigin !== undefined
269
+ ? Boolean(after.committedSameOrigin)
270
+ : after.committedUrl !== undefined
271
+ ? (Boolean(after.committedUrl) && (!isOpaqueOrigin(committedOrigin) ? committedOrigin === afterOrigin : after.committedUrl === after.url))
272
+ : true
273
+ const navGenChanged = before?.navGeneration != null && after?.navGeneration != null && before.navGeneration !== after.navGeneration
274
+ const sameUrlReload = (before.docToken != null && after.docToken != null && before.docToken !== after.docToken) || navGenChanged
275
+ const originChanged = protectedSite || originReason || (hardOpaque
276
+ ? (Boolean(before?.url) && (before.url !== after.url || sameUrlReload))
277
+ : (beforeOrigin !== afterOrigin || (unverifiedOrigin && sameUrlReload) || (before?.selfOrigin && after?.selfOrigin && before.selfOrigin !== after.selfOrigin)))
278
+ const hideDest = protectedSite || originReason || (!allowOriginChange && originChanged)
279
+ const dialog = !hideDest && committedMatches && S.dialogs.get(id)
280
+ const safeLive = hideDest || !committedMatches || !liveUpdate
281
+ ? null
282
+ : liveUpdate === '__DSH_TOO_LONG__'
283
+ ? (allSecrets.length ? '••••' : null)
284
+ : redactText(liveUpdate).slice(0, 120)
285
+ return { beforeUrl: redactMeta(before.url), beforeTitle: redactMeta(before.title), url: hideDest ? (isOpaqueOrigin(afterOrigin) ? '' : afterOrigin) : redactMeta(after.url), title: hideDest || !committedMatches ? '' : redactMeta(after.title),
286
+ documentToken: after.docToken, urlHash: after.url ? hashUrl(after.url) : '',
287
+ navigated: before.url !== after.url || sameUrlReload, originChanged,
288
+ protectedSite, pendingDialog: dialog ? { type: dialog.type, message: redactText(dialog.message || ''), at: dialog.at } : null,
289
+ liveUpdate: safeLive,
290
+ controlEpoch: S.controlEpoch.get(id) || 0, navGeneration: S.mainNavGeneration.get(id) || 0,
291
+ ...(openedTabs?.length && { openedTabs: openedTabs.map(t => ({ ...t, url: redactMeta(t.url), title: redactMeta(t.title || '') })) }) }
292
+ }
@@ -10,10 +10,12 @@ import { CURSOR_FAVICON } from './tabui.js'
10
10
  import { controlledCount, isExtUrl, log, updateBadge } from './util.js'
11
11
 
12
12
  function restorePrefs() {
13
- S.prefsReady = chrome.storage.local.get(['paused', 'pauseReason', 'showCursor', 'ownWindow']).then((v) => {
13
+ S.prefsReady = chrome.storage.local.get(['paused', 'pauseReason', 'showCursor', 'cursorPace', 'lastCursorPace', 'ownWindow']).then((v) => {
14
14
  S.paused = !!(v && v.paused)
15
15
  S.pauseReason = S.paused ? v.pauseReason || null : null
16
- S.showCursor = !(v && v.showCursor === false)
16
+ S.cursorPace = ['fast', 'smooth', 'off'].includes(v?.cursorPace) ? v.cursorPace : v?.showCursor === false ? 'off' : 'fast'
17
+ S.lastCursorPace = S.cursorPace === 'off' ? (v?.lastCursorPace === 'smooth' ? 'smooth' : 'fast') : S.cursorPace
18
+ S.showCursor = S.cursorPace !== 'off'
17
19
  S.ownWindow = !(v && v.ownWindow === false)
18
20
  updateBadge()
19
21
  }).catch(() => {})
@@ -118,7 +120,7 @@ async function buildState() {
118
120
  host: S.hostInfo,
119
121
  idleMs: DETACH_IDLE_MS,
120
122
  attachedCount: controlledCount(),
121
- showCursor: S.showCursor,
123
+ showCursor: S.showCursor, cursorPace: S.cursorPace,
122
124
  ownWindow: S.ownWindow,
123
125
  protectedSites,
124
126
  activeTabHost,
@@ -133,6 +135,7 @@ async function buildState() {
133
135
  }
134
136
 
135
137
  async function releaseTab(tabId) {
138
+ S.releasing.add(Number(tabId))
136
139
  bumpControlEpoch(tabId)
137
140
  revokeTabGrants(tabId) // 用户放开 = 解绑:受保护网站的放行跟着作废
138
141
  await getOps().detach({ tabId })
@@ -188,8 +191,25 @@ async function setPaused(on, where) {
188
191
  }
189
192
 
190
193
  async function setShowCursor(on, where) {
191
- S.showCursor = !!on
192
- await chrome.storage.local.set({ showCursor: S.showCursor })
194
+ return queueCursorPace(() => on ? S.lastCursorPace : 'off', where)
195
+ }
196
+
197
+ async function setCursorPace(pace, where) {
198
+ if (!['off', 'fast', 'smooth'].includes(pace)) throw new Error('Invalid cursorPace')
199
+ return queueCursorPace(() => pace, where)
200
+ }
201
+
202
+ function queueCursorPace(select, where) {
203
+ const run = () => saveCursorPace(select(), where)
204
+ const job = S.cursorPrefsWrite.then(run, run)
205
+ S.cursorPrefsWrite = job.catch(() => {})
206
+ return job
207
+ }
208
+
209
+ async function saveCursorPace(pace, where) {
210
+ const prefs = { cursorPace: pace, showCursor: pace !== 'off', lastCursorPace: pace === 'off' ? S.lastCursorPace : pace }
211
+ await chrome.storage.local.set(prefs)
212
+ Object.assign(S, prefs)
193
213
  log(`${S.showCursor ? '打开' : '关掉'}了页内光标(${where})`)
194
214
  if (!S.showCursor) {
195
215
  for (const id of [...S.cursorReady]) {
@@ -277,7 +297,8 @@ function handleRuntimeMessage(msg, sender, sendResponse) {
277
297
  await setPaused(!!msg.on, '弹窗')
278
298
  return buildState()
279
299
  case 'cursor':
280
- await setShowCursor(!!msg.on, '弹窗')
300
+ if (msg.cursorPace !== undefined) await setCursorPace(msg.cursorPace, '弹窗')
301
+ else await setShowCursor(!!msg.on, '弹窗')
281
302
  return buildState()
282
303
  case 'window':
283
304
  await setOwnWindow(!!msg.on, '弹窗')
@@ -310,5 +331,5 @@ function handleRuntimeMessage(msg, sender, sendResponse) {
310
331
 
311
332
  export {
312
333
  restorePrefs, buildState, releaseTab, diagnostics, releaseAllTabs, setPaused, setShowCursor,
313
- setOwnWindow, setProfileLabel, handleRuntimeMessage,
334
+ setOwnWindow, setCursorPace, setProfileLabel, handleRuntimeMessage,
314
335
  }
@@ -0,0 +1,251 @@
1
+ import { evaluate } from './cdp.js'
2
+ import { getOps } from './ops.js'
3
+ import { formatRedactedRow, isSensitiveField, scanPage } from './frames.js'
4
+ import { getRecentSecrets, isOpaqueOrigin, makeSecretRedactor, originOf, pageAccess } from './page-access.js'
5
+ import { S } from './state.js'
6
+ import { areAllFramesAllowed, hasProtectedSites } from './confirm.js'
7
+ import { RELEASED_MSG } from './cursor.js'
8
+ import { timeLeft } from './util.js'
9
+
10
+ function rowKeys(rows) {
11
+ const seen = new Map()
12
+ return rows.map(row => {
13
+ const key = row.ref != null ? 'ref:' + row.ref : row.key || JSON.stringify([row.framePath, row.crossPath, row.line])
14
+ const n = seen.get(key) || 0
15
+ seen.set(key, n + 1)
16
+ return key + ':' + n
17
+ })
18
+ }
19
+
20
+ function diffRows(previous, next, keysForRows = rowKeys) {
21
+ const oldKeys = keysForRows(previous), keys = keysForRows(next)
22
+ const old = new Map(oldKeys.map((key, i) => [key, previous[i]]))
23
+ const current = new Set(keys)
24
+ const surviving = oldKeys.filter(key => current.has(key))
25
+ let index = 0
26
+ const out = []
27
+ for (const [i, key] of keys.entries()) {
28
+ const row = next[i], prior = old.get(key)
29
+ const moved = prior && surviving[index++] !== key
30
+ if (!prior || moved || row.line !== prior.line) out.push({ ...row, line: (prior ? '[~] ' : '[+] ') + (row.line || '') })
31
+ old.delete(key)
32
+ }
33
+ for (const row of old.values()) out.push({ ...(row.raw && { raw: row.raw }), ref: row.ref, line: '[-] ' + (row.line || '') })
34
+ return out
35
+ }
36
+
37
+ function sliceRows(rows, args, cursor) {
38
+ const limit = Math.min(2000, Math.max(1, Math.trunc(args.limit) || 300))
39
+ const maxChars = Math.min(65536, Math.max(1, Math.trunc(args.maxChars) || 8000))
40
+ const maxLine = args.mode === 'page' ? Math.min(120, maxChars) : maxChars
41
+ const page = []
42
+ let chars = 0
43
+ for (const row of rows.slice(cursor, cursor + limit)) {
44
+ const length = Math.min(maxLine, (row.line || '').length) + Number(page.length > 0)
45
+ if (page.length && chars + length > maxChars) break
46
+ page.push({ ...(row.ref !== undefined && { ref: row.ref }), ...(row.crossPath && { crossPath: row.crossPath }), ...(row.framePath && { framePath: row.framePath }), ...(args.swRedact && row.raw && { raw: row.raw }),
47
+ line: row.line == null ? null : row.line.slice(0, maxLine) })
48
+ chars += length
49
+ }
50
+ const nextCursor = cursor + page.length, more = Math.max(0, rows.length - nextCursor)
51
+ return { page, more, nextCursor }
52
+ }
53
+
54
+ // Serialized once per document. Scans stay local, including the baseline for diffs.
55
+ function installScanner(scan, rowKeys, diffRows, sliceRows, maskField) {
56
+ const cache = new Map()
57
+ window.__dshScan = { version: 3, read(args, cached = false) {
58
+ const { selector, scope = 'all', query = '', mode = 'interactive', diff, autoObserve } = args
59
+ const cursor = Math.max(0, Math.trunc(args.cursor) || 0)
60
+ const key = JSON.stringify([selector || '', scope, query, mode])
61
+ const swKey = Boolean(args.swRedact)
62
+ let state = cache.get(key)
63
+ const switchingToSwRedact = Boolean(swKey && state && !state.swKey)
64
+ if (!state || (!cursor && !cached) || switchingToSwRedact) {
65
+ const next = scan(selector, scope, query, null, { mode, maskField, ...(swKey ? { swRedact: true } : {}) })
66
+ if (next.error) return next
67
+ if (!state || switchingToSwRedact || state.url !== next.url || state.documentId !== next.documentId) {
68
+ state = { snapshotId: crypto.randomUUID?.() || Array.from(crypto.getRandomValues(new Uint32Array(4))).join('-'), revision: 0, rows: [], previous: null }
69
+ }
70
+ const changed = !state.revision || state.swKey !== swKey || state.title !== next.title || state.count !== next.count ||
71
+ state.outside !== next.outside || state.capped !== next.capped || state.rows.length !== next.rows.length ||
72
+ next.rows.some((r, i) => r.line !== state.rows[i].line || r.ref !== state.rows[i].ref || String(r.crossPath) !== String(state.rows[i].crossPath))
73
+ if (changed) {
74
+ state.previous = { revision: state.revision, rows: state.rows }
75
+ Object.assign(state, next, { swKey, revision: state.revision + 1, paths: next.rows.filter(r => r.crossPath).map(r => r.crossPath) })
76
+ }
77
+ cache.delete(key)
78
+ cache.set(key, state)
79
+ if (cache.size > 8) cache.delete(cache.keys().next().value)
80
+ }
81
+ let rows = state.rows, diffMode = 'full'
82
+ if (diff && cursor && state.diffPage) {
83
+ rows = state.diffPage.rows
84
+ diffMode = state.diffPage.mode
85
+ } else if (diff && args.prevSnapshotId === state.snapshotId) {
86
+ if (args.prevRevision === state.revision) { rows = []; diffMode = 'unchanged' }
87
+ else if (args.prevRevision === state.previous?.revision) { rows = diffRows(state.previous.rows, rows, rowKeys); diffMode = 'diff' }
88
+ }
89
+ const { page, more, nextCursor } = sliceRows(rows, args, cursor)
90
+ if (!cursor) state.diffPage = diff && more ? { rows, mode: diffMode } : null
91
+ const { snapshotId, revision, documentId, url, title, count, outside, capped, selfOrigin, rawTitle, rawUrl } = state
92
+ return { snapshotId, revision, documentId, url, title, count, outside, capped, diffMode, selfOrigin,
93
+ ...(swKey && { rawTitle, rawUrl }),
94
+ paths: !autoObserve ? state.paths : undefined, unchanged: diffMode === 'unchanged', lines: page.map(r => r.line).filter(Boolean),
95
+ ...((!autoObserve || swKey) && { rows: page }),
96
+ nextCursor, more, totalRows: rows.length }
97
+ } }
98
+ }
99
+
100
+ export async function snapshotScan({ tabId, timeoutMs = 15000, controlEpoch, ...args }) {
101
+ const id = Number(tabId), deadline = Date.now() + timeoutMs
102
+ const auto = args.autoObserve === true
103
+ const startEpoch = Number.isInteger(controlEpoch) ? controlEpoch : (S.controlEpoch.get(id) || 0)
104
+ const startReleaseAll = S.releaseAllEpoch
105
+ const skip = info => ({ skipped: true, reason: info.reason, url: info.url || '', title: info.title || '' })
106
+ const released = () => S.paused || S.releasing.has(id) || S.releaseAllEpoch !== startReleaseAll || (S.controlEpoch.get(id) || 0) !== startEpoch || (auto && !S.attached.has(id))
107
+ if (auto && released()) return skip({ reason: 'detached' })
108
+ const guard = () => { if (released()) throw new Error(RELEASED_MSG) }
109
+ const access = { autoObserve: auto, expectedOrigin: args.expectedOrigin }
110
+ const page = await pageAccess(id, access)
111
+ if (page.reason) {
112
+ if (auto) return skip(page)
113
+ throw new Error(page.reason === 'protected' ? 'USER_DENIED_SENSITIVE' : page.reason)
114
+ }
115
+ if (auto && released()) return skip({ reason: 'detached' })
116
+ const origin = originOf(page.url)
117
+ const opaque = isOpaqueOrigin(origin)
118
+ const recent = getRecentSecrets(id, origin)
119
+ // Never pass cached secrets into any page world; request untrimmed raw fields and redact in SW.
120
+ const scanArgs = recent.length ? { ...args, swRedact: true } : args
121
+ const check = opaque ? `location.href === ${JSON.stringify(page.url)}` : `location.origin === ${JSON.stringify(origin)}`
122
+ const read = `window.__dshScan.read(${JSON.stringify(scanArgs)})`
123
+ const miss = 'DSH_SCANNER_MISSING'
124
+ let result
125
+ try {
126
+ result = await evaluate(id, `${check} && (window.__dshScan?.version === 3 ? ${read} : '${miss}')`, false, timeLeft(deadline), guard)
127
+ if (result === miss) {
128
+ result = await evaluate(id, `${check} && ((${installScanner})(${scanPage}, ${rowKeys}, ${diffRows}, ${sliceRows}, ${isSensitiveField}), ${read})`, false, timeLeft(deadline), guard)
129
+ }
130
+ if (!auto && (result?.paths?.length || S.frameSnapshots.has(result?.snapshotId)) && getOps().frameSnapshot) {
131
+ result = await withFrames(id, scanArgs, result, check, deadline, guard)
132
+ }
133
+ } catch (error) {
134
+ if (auto && released()) return skip({ reason: 'detached' })
135
+ throw error
136
+ }
137
+ if (result) delete result.paths
138
+ if (auto && released()) return skip({ reason: 'detached' })
139
+ const genBeforeAfter = S.frameGeneration.get(id)
140
+ const after = await pageAccess(id, { ...access, expectedOrigin: origin, ...(opaque ? { expectedUrl: page.url } : {}) })
141
+ if (!after.reason && hasProtectedSites() && genBeforeAfter !== S.frameGeneration.get(id)) {
142
+ if (!await areAllFramesAllowed(id, auto)) {
143
+ after.reason = 'protected'
144
+ after.url = originOf(after.url)
145
+ after.title = ''
146
+ }
147
+ }
148
+ if (after.reason || result === false) {
149
+ if (auto) return skip(after.reason ? after : { ...after, title: '', reason: 'origin_changed' })
150
+ throw new Error(after.reason === 'protected' ? 'USER_DENIED_SENSITIVE' : '页面已变化')
151
+ }
152
+ const selfOrigin = typeof result?.selfOrigin === 'string' ? result.selfOrigin : ''
153
+ const sandboxedOpaque = result && typeof result === 'object' && 'selfOrigin' in result && isOpaqueOrigin(selfOrigin)
154
+ if (sandboxedOpaque) S.recentSecrets.delete(id)
155
+ const postRecent = sandboxedOpaque ? [] : [...new Set([...recent, ...getRecentSecrets(id, origin)])]
156
+ if (result && typeof result === 'object') {
157
+ if (postRecent.length) {
158
+ const redactText = makeSecretRedactor(postRecent, 4)
159
+ const redactMeta = makeSecretRedactor(postRecent, 6)
160
+ const redactUrl = (u) => {
161
+ const s = String(u ?? '')
162
+ try {
163
+ const p = new URL(s)
164
+ if (p.origin && p.origin !== 'null') return p.origin + redactText(p.pathname + p.search + p.hash)
165
+ } catch {}
166
+ if (s.startsWith('/')) return redactText(s)
167
+ return redactMeta(s)
168
+ }
169
+ if (result.rawUrl !== undefined) result.url = (result.rawUrl && result.rawUrl.tooLong) ? origin : redactUrl(result.rawUrl)
170
+ else if (typeof result.url === 'string') result.url = redactUrl(result.url)
171
+ if (result.rawTitle !== undefined) result.title = (result.rawTitle && result.rawTitle.tooLong) ? '••••' : redactMeta(result.rawTitle)
172
+ else if (typeof result.title === 'string') result.title = redactMeta(result.title)
173
+ if (Array.isArray(result.rows)) {
174
+ result.rows = result.rows.map(r => r ? formatRedactedRow(r, redactText, redactUrl, args.mode, true) : r)
175
+ result.lines = result.rows.map(r => r?.line).filter(Boolean)
176
+ } else if (Array.isArray(result.lines)) {
177
+ result.lines = result.lines.map(redactText)
178
+ }
179
+ } else if (Array.isArray(result.rows)) {
180
+ result.rows = result.rows.map(r => {
181
+ if (!r || !r.raw) return r
182
+ const { raw: _raw, ...rest } = r
183
+ return rest
184
+ })
185
+ }
186
+ delete result.rawTitle
187
+ delete result.rawUrl
188
+ delete result.selfOrigin
189
+ if (auto) delete result.rows
190
+ }
191
+ return result
192
+ }
193
+
194
+ // Keep cross-origin content exclusively in the worker. Only the main document's rows
195
+ // are cached in its page world. Unresolved crossPath markers keep the legacy merge contract.
196
+ async function withFrames(id, args, main, check, deadline, guard) {
197
+ const key = main.snapshotId
198
+ let state = S.frameSnapshots.get(key)
199
+ const cursor = Math.max(0, Math.trunc(args.cursor) || 0)
200
+ if (!state || !cursor) {
201
+ let mainRows = state?.mainRows
202
+ if (!mainRows || state.mainRevision !== main.revision) {
203
+ mainRows = []
204
+ let offset = 0
205
+ do {
206
+ const pageArgs = { ...args, diff: false, limit: 2000, maxChars: 65536, cursor: offset }
207
+ const data = await evaluate(id, `${check} && window.__dshScan?.read(${JSON.stringify(pageArgs)}, true)`, false, timeLeft(deadline), guard)
208
+ if (data?.snapshotId !== key || data.revision !== main.revision) throw new Error('快照已变化,请重试')
209
+ mainRows.push(...data.rows)
210
+ offset = data.more ? data.nextCursor : 0
211
+ } while (offset)
212
+ }
213
+ const groups = main.paths.length ? (await getOps().frameSnapshot({ tabId: id, mode: args.mode, scope: args.scope, query: args.query,
214
+ paths: main.paths, timeoutMs: timeLeft(deadline) })).groups : []
215
+ const paths = new Map()
216
+ let count = main.count, outside = main.outside, capped = main.capped
217
+ for (const group of groups) {
218
+ const path = group.path.join('.')
219
+ if (!paths.has(path)) paths.set(path, [])
220
+ paths.get(path).push(...group.rows.map(row => ({ ...row, framePath: group.path })))
221
+ count += group.count
222
+ outside += group.outside
223
+ capped ||= group.capped
224
+ }
225
+ const rows = mainRows.flatMap(row => paths.get(row.crossPath?.join('.')) || [row])
226
+ const changed = !state || state.mainRevision !== main.revision || state.count !== count ||
227
+ state.outside !== outside || state.capped !== capped || state.rows.length !== rows.length ||
228
+ rows.some((r, i) => r.ref !== state.rows[i].ref || r.line !== state.rows[i].line || String(r.framePath) !== String(state.rows[i].framePath))
229
+ if (changed) {
230
+ // A worker restart or eviction creates a new baseline, so an old revision can never match.
231
+ state = { tabId: id, snapshotId: state?.snapshotId || crypto.randomUUID(), rows, mainRows, mainRevision: main.revision, count, outside, capped,
232
+ revision: (state?.revision || 0) + 1, previous: state && { revision: state.revision, rows: state.rows } }
233
+ }
234
+ S.frameSnapshots.delete(key)
235
+ S.frameSnapshots.set(key, state)
236
+ if (S.frameSnapshots.size > 4) S.frameSnapshots.delete(S.frameSnapshots.keys().next().value)
237
+ state.page = state.rows
238
+ state.mode = 'full'
239
+ if (args.diff && args.prevSnapshotId === state.snapshotId) {
240
+ if (args.prevRevision === state.revision) { state.page = []; state.mode = 'unchanged' }
241
+ else if (state.previous && args.prevRevision === state.previous.revision) {
242
+ state.page = diffRows(state.previous.rows, state.rows)
243
+ state.mode = 'diff'
244
+ }
245
+ }
246
+ }
247
+ const { page, nextCursor, more } = sliceRows(state.page, args, cursor)
248
+ return { ...main, rows: page, lines: page.map(r => r.line).filter(Boolean), count: state.count,
249
+ outside: state.outside, capped: state.capped, snapshotId: state.snapshotId, revision: state.revision, diffMode: state.mode,
250
+ unchanged: state.mode === 'unchanged', more, nextCursor, totalRows: state.page.length }
251
+ }