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
@@ -4,6 +4,11 @@ import { registerOps } from './ops.js'
4
4
  import { HANDOFF_LOCKED, PAUSED_MSG, QUEUED, S, TAKEOVER_OPS } from './state.js'
5
5
  import { timeLeft } from './util.js'
6
6
 
7
+ export function sensitiveValue(text) {
8
+ return /^\d{4,}$/.test(text) || /(?:\d\s*){6}|(?:bearer\s+|sk[-_]|gh[pousr]_|eyJ|AKIA)[\w./+=-]{6,}/i.test(text) ||
9
+ (text.match(/[\w+/-]{24,}/g) || []).some(word => /[a-z]/i.test(word) && /\d/.test(word))
10
+ }
11
+
7
12
  // Standalone helper serialized by refs.js locate() and ops.js type().
8
13
  export function isSensitiveField(el, style, frame) {
9
14
  if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && !el.isContentEditable) return false;
@@ -49,8 +54,8 @@ export function isSensitiveField(el, style, frame) {
49
54
  }
50
55
 
51
56
  // Serialized by Chrome for isolated frames and by refs.js for the main snapshot.
52
- export function scanPage(selector, scope, query, frame) {
53
- const sensitive = (el, style) => {
57
+ export function scanPage(selector, scope, query, frame, options) {
58
+ const sensitive = options?.maskField || ((el, style) => {
54
59
  if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && !el.isContentEditable) return false;
55
60
  const value = String(el.isContentEditable ? el.innerText || '' : el.value || '');
56
61
  const doc = el.ownerDocument || (typeof document !== 'undefined' ? document : null);
@@ -91,31 +96,89 @@ export function scanPage(selector, scope, query, frame) {
91
96
  /(?:^|\s)(?:one-time-code|cc-number|cc-csc)(?:\s|$)/i.test(fields) ||
92
97
  (/(?:^|[\s_-])code(?:$|[\s_-])/i.test(fields) && (Boolean(frame) || /^[a-z0-9]{4,10}$/i.test(value.trim()))) ||
93
98
  /(?:\d[\s-]?){11}\d/.test(value);
94
- };
99
+ });
95
100
  if (scope === 'mask') return sensitive(selector, query);
96
101
  // innerText on an ancestor can include a masked editable child's contents.
97
102
  // Redact before query matching or truncation as well as before returning text.
98
- function redactWithin(root) {
103
+ function redactWithin(root, minLen = 4) {
99
104
  const hiddenValues = new Set();
105
+ for (const extra of (options?.extraSecrets || [])) {
106
+ if (typeof extra === 'string' && extra.length >= minLen) hiddenValues.add(extra.slice(0, 512));
107
+ }
100
108
  function collectSecrets(root) {
101
109
  for (const el of root.querySelectorAll('*')) {
102
110
  if (el.shadowRoot) collectSecrets(el.shadowRoot);
111
+ if (options && !frame && (el.tagName === 'IFRAME' || el.tagName === 'FRAME')) {
112
+ try { if (el.contentDocument?.body) collectSecrets(el.contentDocument); } catch {}
113
+ }
103
114
  if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && !el.isContentEditable) continue;
104
115
  if (!sensitive(el, getComputedStyle(el))) continue;
105
116
  const values = [el.value, el.innerText, el.tagName === 'TEXTAREA' && el.defaultValue];
106
- for (const value of values) if (value) hiddenValues.add(String(value));
117
+ for (const value of values) {
118
+ const s = value ? String(value) : '';
119
+ if (s.length >= minLen) hiddenValues.add(s);
120
+ }
107
121
  }
108
122
  }
109
123
  collectSecrets(root);
110
124
  if (root.shadowRoot) collectSecrets(root.shadowRoot);
125
+ const escRe = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
126
+ const enc = typeof TextEncoder === 'function' ? new TextEncoder() : null;
127
+ const buildRegex = (secret) => {
128
+ if (!enc || secret.length > 256) return null;
129
+ let pat = '';
130
+ for (const ch of secret) {
131
+ if (ch === ' ') { pat += '(?: |%20|\\+)'; continue; }
132
+ if (/^[a-zA-Z0-9]$/.test(ch)) { pat += ch; continue; }
133
+ let pct = '';
134
+ for (const b of enc.encode(ch)) {
135
+ const h = b.toString(16).padStart(2, '0');
136
+ pct += '%' + h.replace(/[a-f]/g, c => '[' + c + c.toUpperCase() + ']');
137
+ }
138
+ pat += '(?:' + escRe(ch) + '|' + pct + ')';
139
+ }
140
+ return new RegExp(pat, 'g');
141
+ };
111
142
  const secrets = [...hiddenValues].sort((a, b) => b.length - a.length);
143
+ const rules = secrets.map(secret => {
144
+ const re = buildRegex(secret);
145
+ if (re) return { secret, re, extras: [] };
146
+ const extras = new Set();
147
+ try {
148
+ const e1 = encodeURIComponent(secret);
149
+ if (e1 && e1 !== secret) { extras.add(e1); if (e1.includes('%20')) extras.add(e1.replace(/%20/g, '+')); }
150
+ const e2 = new URLSearchParams([['x', secret]]).toString().slice(2);
151
+ if (e2 && e2 !== secret) { extras.add(e2); if (e2.includes('+')) extras.add(e2.replace(/\+/g, '%20')); }
152
+ } catch {}
153
+ return { secret, re: null, extras: [...extras].map(v => new RegExp(escRe(v), 'gi')) };
154
+ });
112
155
  return text => {
113
- for (const secret of secrets) text = text.replaceAll(secret, '••••');
114
- return text;
156
+ let out = String(text ?? '');
157
+ for (const { secret, re, extras } of rules) {
158
+ if (re) out = out.replace(re, '••••');
159
+ else {
160
+ out = out.replaceAll(secret, '••••');
161
+ for (const x of extras) out = out.replace(x, '••••');
162
+ }
163
+ }
164
+ return out;
115
165
  };
116
166
  }
117
- const redact = frame ? redactWithin(document) : text => text;
118
- if (scope === 'frameText') return redact(document.body?.innerText || '').trim().slice(0, 16000);
167
+ const redact = frame || options ? redactWithin(document, 4) : text => text;
168
+ const redactMeta = frame || options ? redactWithin(document, 6) : text => text;
169
+ const redactUrlParts = (raw) => {
170
+ const s = String(raw ?? '');
171
+ try {
172
+ const u = new URL(s, document.baseURI || location.href);
173
+ if (u.origin && u.origin !== 'null') return u.origin + redact(u.pathname + u.search + u.hash);
174
+ } catch {}
175
+ return redactMeta(s);
176
+ };
177
+ if (scope === 'frameText') {
178
+ const rawText = redact(document.body?.innerText || '').trim();
179
+ const rawSrc = redactUrlParts(location.href);
180
+ return { text: rawText.slice(0, 65536), textOverCap: rawText.length > 65536, src: rawSrc.slice(0, 16384), srcTooLong: rawSrc.length > 16384 };
181
+ }
119
182
  const key = frame ? '__dshFrameSnap' : '__dshSnap';
120
183
  const S = window[key] ||= { next: 1, shadow: new Map(), ids: new WeakMap() };
121
184
  if (frame) S.label = el => {
@@ -221,6 +284,36 @@ export function scanPage(selector, scope, query, frame) {
221
284
  return u.origin === location.origin ? (u.pathname + u.search + u.hash) : (u.host + u.pathname);
222
285
  } catch { return h; }
223
286
  };
287
+ const swRedact = Boolean(options?.swRedact);
288
+ const rawVal = (s) => { const str = String(s ?? ''); return str.length > 16384 ? { tooLong: true } : str; };
289
+ const stateObj = (el, role, masked) => {
290
+ const out = [];
291
+ const tag = el.tagName;
292
+ if (tag === 'INPUT' && ['checkbox', 'radio'].includes(el.type)) { if (el.checked) out.push('已勾选'); }
293
+ else if (el.getAttribute('aria-checked') === 'true') out.push('已勾选');
294
+ if (el.getAttribute('aria-selected') === 'true') out.push('已选中');
295
+ const ex = el.getAttribute('aria-expanded');
296
+ if (ex === 'true') out.push('已展开'); else if (ex === 'false') out.push('已收起');
297
+ if (el.disabled || el.getAttribute('aria-disabled') === 'true') out.push('不可用');
298
+ if (el.readOnly) out.push('只读');
299
+ const obj = { out };
300
+ if (tag === 'SELECT') {
301
+ const o = el.selectedOptions && el.selectedOptions[0];
302
+ obj.selText = rawVal(norm(o ? o.textContent : ''));
303
+ obj.optCount = el.options.length;
304
+ } else if (masked) {
305
+ if (el.isContentEditable ? norm(el.innerText) : el.value) obj.maskedVal = true;
306
+ } else if ((tag === 'INPUT' && !['checkbox', 'radio', 'button', 'submit', 'reset', 'image', 'file'].includes(el.type)) || tag === 'TEXTAREA') {
307
+ if (el.value) obj.val = rawVal(norm(el.value));
308
+ } else if (role === 'textbox' && el.isContentEditable) {
309
+ const t = norm(el.innerText);
310
+ if (t) obj.val = rawVal(t);
311
+ }
312
+ const ph = el.getAttribute('placeholder');
313
+ if (ph && !el.value) obj.ph = rawVal(norm(ph));
314
+ if (tag === 'A') { const rawH = hrefOf(el); const h = rawH ? (rawH.startsWith('/') ? redact(rawH) : redactMeta(rawH)) : ''; if (h) obj.href = rawVal(h); }
315
+ return obj;
316
+ };
224
317
  const stateOf = (el, role, masked) => {
225
318
  const out = [];
226
319
  const tag = el.tagName;
@@ -245,7 +338,7 @@ export function scanPage(selector, scope, query, frame) {
245
338
  }
246
339
  const ph = el.getAttribute('placeholder');
247
340
  if (ph && !el.value) extra += ' 提示' + q(cut(norm(ph), 40));
248
- if (tag === 'A') { const h = hrefOf(el); if (h) extra += ' → ' + cut(h, 70); }
341
+ if (tag === 'A') { const rawH = hrefOf(el); const h = rawH ? (rawH.startsWith('/') ? redact(rawH) : redactMeta(rawH)) : ''; if (h) extra += ' → ' + cut(h, 70); }
249
342
  return extra + (out.length ? ' (' + out.join(',') + ')' : '');
250
343
  };
251
344
 
@@ -314,9 +407,17 @@ export function scanPage(selector, scope, query, frame) {
314
407
  };
315
408
 
316
409
  const rows = [];
410
+ const pageMode = options?.mode === 'page';
411
+ const textTags = /^(P|LI|DT|DD|TD|TH|OUTPUT|FIGCAPTION|BLOCKQUOTE|H[4-6])$/;
412
+ const nodeId = el => {
413
+ S.rowIds ||= new WeakMap();
414
+ if (!S.rowIds.has(el)) S.rowIds.set(el, S.nextRowId = (S.nextRowId || 0) + 1);
415
+ return S.rowIds.get(el);
416
+ };
417
+
317
418
  let count = 0, outside = 0, scanned = 0, capped = false;
318
419
  const scanLimit = 30000;
319
- const walk = (el, depth = 0, path = []) => {
420
+ const walk = (el, depth = 0, path = [], captureText = false) => {
320
421
  if (scanned >= scanLimit || SKIP.has(el.tagName) || el.id === '__dsh_cursor__') return;
321
422
  scanned++;
322
423
  let st;
@@ -324,7 +425,9 @@ export function scanPage(selector, scope, query, frame) {
324
425
  if (st.display === 'none') return;
325
426
  if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
326
427
  if (frame || !shown(el, st)) return;
327
- const label = '[iframe] ' + cut(el.getAttribute('src') || el.getAttribute('title') || el.getAttribute('name') || '', 80);
428
+ const rawIframeAttr = el.getAttribute('src') || el.getAttribute('title') || el.getAttribute('name') || '';
429
+ const safeIframeAttr = redactUrlParts(rawIframeAttr);
430
+ const label = '[iframe] ' + cut(safeIframeAttr, 80);
328
431
  const context = !query && (!viewport || inViewport(el));
329
432
  const parent = el.ownerDocument.defaultView;
330
433
  const index = Array.prototype.indexOf.call(parent.frames || [], el.contentWindow);
@@ -332,11 +435,19 @@ export function scanPage(selector, scope, query, frame) {
332
435
  let doc = null;
333
436
  try { doc = el.contentDocument; } catch {}
334
437
  if (doc?.body && doc.defaultView?.origin === parent.origin && depth < 5) {
335
- if (context) rows.push({ line: label + ' ↓' });
438
+ if (context) rows.push({
439
+ line: label + ' ↓',
440
+ ...(swRedact && { raw: { kind: 'iframe', val: rawVal(safeIframeAttr), suffix: ' ↓' } }),
441
+ });
336
442
  walk(doc.body, depth + 1, childPath);
337
443
  if (context) rows.push({ line: '[/iframe]' });
338
444
  } else {
339
- rows.push({ crossPath: childPath, line: context ? label + '(跨站框架,读不到里面:browser_screenshot 看,按坐标 x/y 点)' : null });
445
+ const suffix = '(跨站框架,读不到里面:browser_screenshot 看,按坐标 x/y 点)';
446
+ rows.push({
447
+ crossPath: childPath,
448
+ line: context ? label + suffix : null,
449
+ ...(context && swRedact && { raw: { kind: 'iframe', val: rawVal(safeIframeAttr), suffix } }),
450
+ });
340
451
  }
341
452
  return;
342
453
  }
@@ -345,9 +456,39 @@ export function scanPage(selector, scope, query, frame) {
345
456
  const heading = /^H([1-3])$/.exec(el.tagName);
346
457
  if (heading && !masked && !query && (!viewport || inViewport(el))) {
347
458
  const title = norm(el.innerText);
348
- if (title) rows.push({ line: '#'.repeat(Number(heading[1])) + ' ' + cut(title, 80) });
459
+ if (title) rows.push({
460
+ line: '#'.repeat(Number(heading[1])) + ' ' + cut(title, 80),
461
+ ...(swRedact && { raw: { kind: 'h', level: Number(heading[1]), title: rawVal(title) } }),
462
+ });
349
463
  }
350
- if (interactive(el, st)) {
464
+ const clickable = interactive(el, st);
465
+ const semantic = textTags.test(el.tagName);
466
+ const metric = pageMode && !el.children.length && /^(SPAN|DIV|STRONG|B)$/.test(el.tagName) && /[0-9¥¥$€£₽%]/.test(el.innerText || '');
467
+ const readable = pageMode && !clickable && !heading && !masked &&
468
+ !el.closest?.('a,button,[contenteditable="true"]') && (!viewport || inViewport(el));
469
+ const hasInteractiveDescendant = (node) => {
470
+ if (node.shadowRoot && hasInteractiveDescendant(node.shadowRoot)) return true;
471
+ for (const c of node.querySelectorAll('*')) {
472
+ let cs; try { cs = css(c); } catch { cs = null; }
473
+ if (cs && shown(c, cs) && interactive(c, cs)) return true;
474
+ if (c.shadowRoot && hasInteractiveDescendant(c.shadowRoot)) return true;
475
+ }
476
+ return false;
477
+ };
478
+ const mixed = readable && (semantic || captureText) && (el.children.length || el.shadowRoot) &&
479
+ (Boolean(el.querySelector?.('a,button,input,select,textarea,[role],p,li,dt,dd,td,th,output,figcaption,blockquote')) || hasInteractiveDescendant(el));
480
+ if (readable && (semantic || captureText || metric) && !mixed) {
481
+ const text = norm(el.innerText);
482
+ if (text && (!query || text.toLowerCase().includes(query))) {
483
+ rows.push({
484
+ key: 'text:' + nodeId(el), line: cut(text, 120),
485
+ ...(swRedact && { raw: { kind: 't', text: rawVal(text) } }),
486
+ });
487
+ }
488
+ return;
489
+ }
490
+ captureText = readable && (semantic || captureText);
491
+ if (clickable) {
351
492
  const role = roleOf(el);
352
493
  const name = nameOf(el, masked);
353
494
  const state = stateOf(el, role, masked);
@@ -358,7 +499,12 @@ export function scanPage(selector, scope, query, frame) {
358
499
  const ref = assign(el);
359
500
  if (ref === null) capped = true;
360
501
  else {
361
- rows.push({ ref, line: '[' + ref + '] ' + role + (name ? ' ' + q(cut(name, 80)) : '') + state });
502
+ const list = pageMode && role === 'link' && (el.closest?.('ul,ol,nav,[role=list]') || el.parentElement);
503
+ rows.push({
504
+ ...(list && { linkGroup: nodeId(list) }), ref,
505
+ line: '[' + ref + '] ' + role + (name ? ' ' + q(cut(name, 80)) : '') + state,
506
+ ...(swRedact && { raw: { kind: 'el', role, name: rawVal(name), st: stateObj(el, role, masked) } }),
507
+ });
362
508
  count++;
363
509
  }
364
510
  }
@@ -366,11 +512,39 @@ export function scanPage(selector, scope, query, frame) {
366
512
  }
367
513
  }
368
514
  if (el.tagName === 'SELECT' || el.tagName === 'svg' || (masked && el.isContentEditable)) return;
369
- for (const child of el.children) walk(child, depth, path);
515
+ if (captureText && el.childNodes) {
516
+ for (const node of el.childNodes) {
517
+ if (node.nodeType === 1) walk(node, depth, path, true);
518
+ else if (node.nodeType === 3) {
519
+ const text = norm(node.nodeValue);
520
+ if (text && (!query || text.toLowerCase().includes(query)))
521
+ rows.push({
522
+ key: 'text:' + nodeId(node), line: cut(text, 120),
523
+ ...(swRedact && { raw: { kind: 't', text: rawVal(text) } }),
524
+ });
525
+ }
526
+ }
527
+ } else for (const child of el.children) walk(child, depth, path);
370
528
  if (el.shadowRoot) for (const child of el.shadowRoot.children) walk(child, depth, path);
371
529
  };
372
530
  walk(root);
373
- return { rows, count, outside, capped: capped || scanned >= scanLimit, title: document.title, url: location.href, documentId: S.documentId ||= Math.random().toString(36).slice(2) };
531
+ if (pageMode) {
532
+ for (let i = 0; i < rows.length;) {
533
+ let end = i + 1;
534
+ while (rows[i].linkGroup && end < rows.length && rows[end].linkGroup === rows[i].linkGroup) end++;
535
+ if (end - i > 3) rows.splice(i + 2, end - i - 2, { key: 'links:' + rows[i].ref, line: '…另有 ' + (end - i - 2) + ' 个同类项' });
536
+ i += Math.min(end - i, 3);
537
+ }
538
+ for (const row of rows) if (row.line) row.line = cut(row.line, 120);
539
+ }
540
+ return {
541
+ rows, count, outside, capped: capped || scanned >= scanLimit,
542
+ title: options ? redactMeta(document.title) : document.title,
543
+ url: options ? redactUrlParts(location.href) : location.href,
544
+ selfOrigin: typeof self !== 'undefined' && typeof self.origin === 'string' ? self.origin : location.origin,
545
+ ...(swRedact && { rawTitle: rawVal(redactMeta(document.title)), rawUrl: rawVal(redactUrlParts(location.href)) }),
546
+ documentId: S.documentId ||= Math.random().toString(36).slice(2),
547
+ };
374
548
  }
375
549
 
376
550
  // Cross-origin WindowProxy exposes indexed child windows. This associates an
@@ -393,11 +567,17 @@ function frameInfo(scrollChild = null, metadataOnly = false, point = null) {
393
567
  }
394
568
  return hit
395
569
  }
396
- if (point) {
570
+ if (point && !point.map) {
397
571
  const frame = window.frames[point.child]
398
572
  return Boolean(frame && hitAt(point.x, point.y)?.contentWindow === frame)
399
573
  }
574
+ if (point?.map && Array.isArray(point.expectedPath)) {
575
+ if (info.path.length !== point.expectedPath.length || info.path.some((v, idx) => v !== point.expectedPath[idx])) {
576
+ return { ok: false }
577
+ }
578
+ }
400
579
  const children = {}
580
+ let mapped = null
401
581
  function scale(el, rect, style) {
402
582
  // offsetWidth rounds to integral CSS pixels. Preserve fractional sizes
403
583
  // before applying zoom or an axis-aligned transform.
@@ -413,10 +593,11 @@ function frameInfo(scrollChild = null, metadataOnly = false, point = null) {
413
593
  }
414
594
  function owners(root) {
415
595
  for (const el of root.querySelectorAll('*')) {
416
- if (el.shadowRoot) owners(el.shadowRoot)
596
+ if (el.shadowRoot) { owners(el.shadowRoot); if (mapped) return }
417
597
  if (!['IFRAME', 'FRAME'].includes(el.tagName)) continue
418
598
  const i = Array.prototype.indexOf.call(window.frames, el.contentWindow)
419
599
  if (i < 0) continue
600
+ if (point?.map && i !== point.child) continue
420
601
  if (i === scrollChild) el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
421
602
  const r = el.getBoundingClientRect(), st = getComputedStyle(el)
422
603
  if (!r.width || !r.height || st.visibility === 'hidden' || Number(st.opacity) === 0) continue
@@ -445,40 +626,120 @@ function frameInfo(scrollChild = null, metadataOnly = false, point = null) {
445
626
  const [sx, sy] = scale(el, r, st)
446
627
  const visibleLeft = Math.max(left, r.left), visibleRight = Math.min(right, r.right)
447
628
  const visibleTop = Math.max(top, r.top), visibleBottom = Math.min(bottom, r.bottom)
629
+ const bx = r.left + sx * (el.clientLeft + (parseFloat(st.paddingLeft) || 0))
630
+ const by = r.top + sy * (el.clientTop + (parseFloat(st.paddingTop) || 0))
631
+ if (point?.map) {
632
+ const px = Number(point.x), py = Number(point.y)
633
+ const hit = aligned && Number.isFinite(px) && Number.isFinite(py) &&
634
+ px >= 0 && px <= innerWidth && py >= 0 && py <= innerHeight &&
635
+ px >= visibleLeft && px <= visibleRight && py >= visibleTop && py <= visibleBottom &&
636
+ sx > 0 && sy > 0 && Number.isFinite(sx) && Number.isFinite(sy)
637
+ ? hitAt(px, py) : null
638
+ mapped = hit && hit.contentWindow === window.frames[point.child]
639
+ ? { ok: true, x: (px - bx) / sx, y: (py - by) / sy }
640
+ : { ok: false }
641
+ return
642
+ }
448
643
  if (aligned && visibleRight > visibleLeft && visibleBottom > visibleTop) {
449
644
  const x = (visibleLeft + visibleRight) / 2, y = (visibleTop + visibleBottom) / 2
450
645
  const hit = hitAt(x, y)
451
646
  aligned = hit === el || el.contains(hit)
452
647
  } else aligned = false
453
- children[i] = { x: r.left + sx * (el.clientLeft + (parseFloat(st.paddingLeft) || 0)),
454
- y: r.top + sy * (el.clientTop + (parseFloat(st.paddingTop) || 0)), sx, sy,
455
- left, top, right, bottom, aligned }
648
+ children[i] = { x: bx, y: by, sx, sy, left, top, right, bottom, aligned }
456
649
  }
457
650
  }
458
651
  if (window.length) owners(document)
652
+ if (point?.map) return mapped || { ok: false }
459
653
  return { ...info, children }
460
654
  }
461
655
 
462
- async function frameAction(local, action, args) {
656
+ export async function frameAction(local, action, args, mainElement) {
463
657
  const store = window.__dshFrameSnap
464
- const el = store?.refs.get(local)?.deref()
465
- if (!el?.isConnected || el.ownerDocument !== document || store.ids.get(el) !== local) return null
658
+ const el = mainElement || store?.refs.get(local)?.deref()
659
+ if (!el?.isConnected || (!mainElement && (el.ownerDocument !== document || store.ids.get(el) !== local))) return null
466
660
  if (action === 'locate') {
467
- el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
661
+ if (!args?.verifyHit && !args?.verifyPoint) el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
468
662
  const r = el.getBoundingClientRect()
663
+ if (r.width < 1 || r.height < 1) return null
469
664
  return { tag: el.tagName.toLowerCase(), text: store.label(el),
470
665
  draggable: Boolean(el.closest && el.closest('[draggable="true"]')),
471
666
  box: { x: r.left, y: r.top, width: r.width, height: r.height } }
472
667
  }
668
+ if (action === 'verifyPoint') {
669
+ if (Array.isArray(args?.expectedPath)) {
670
+ const livePath = []
671
+ for (let w = window; w !== w.top; w = w.parent) {
672
+ if (!w?.parent?.frames) return false
673
+ const index = Array.prototype.indexOf.call(w.parent.frames, w)
674
+ if (index < 0) return false
675
+ livePath.unshift(index)
676
+ }
677
+ if (livePath.length !== args.expectedPath.length || livePath.some((v, i) => v !== args.expectedPath[i])) return false
678
+ }
679
+ const r = el.getBoundingClientRect()
680
+ if (r.width < 1 || r.height < 1) return false
681
+ const cx = Number(args.x), cy = Number(args.y)
682
+ if (!Number.isFinite(cx) || !Number.isFinite(cy)) return false
683
+ if (typeof innerWidth === 'number' && (cx < 0 || cx > innerWidth)) return false
684
+ if (typeof innerHeight === 'number' && (cy < 0 || cy > innerHeight)) return false
685
+ if (cx < r.left || cx > r.right || cy < r.top || cy > r.bottom) return false
686
+ const visibleInClip = (node) => {
687
+ let anc = node.parentElement || (node.getRootNode && node.getRootNode().host) || null
688
+ const clipRe = /hidden|clip|auto|scroll/
689
+ while (anc && anc !== document.body && anc !== document.documentElement) {
690
+ const as = typeof getComputedStyle === 'function' ? getComputedStyle(anc) : null
691
+ const ox = clipRe.test(as?.overflowX || as?.overflow || '')
692
+ const oy = clipRe.test(as?.overflowY || as?.overflow || '')
693
+ if ((ox || oy) && typeof anc.getBoundingClientRect === 'function') {
694
+ const ar = anc.getBoundingClientRect()
695
+ if (ox && (ar.width <= 0 || cx < ar.left || cx > ar.right)) return false
696
+ if (oy && (ar.height <= 0 || cy < ar.top || cy > ar.bottom)) return false
697
+ }
698
+ anc = anc.parentElement || (anc.getRootNode && anc.getRootNode().host) || null
699
+ }
700
+ return true
701
+ }
702
+ if (!visibleInClip(el)) return false
703
+ if (typeof document.elementFromPoint !== 'function') return true
704
+ let hit = document.elementFromPoint(cx, cy)
705
+ while (hit?.shadowRoot && typeof hit.shadowRoot.elementFromPoint === 'function') {
706
+ const inner = hit.shadowRoot.elementFromPoint(cx, cy)
707
+ if (!inner || inner === hit) break
708
+ hit = inner
709
+ }
710
+ if (!hit) return false
711
+ const inside = (node, anc) => {
712
+ while (node) {
713
+ if (anc && typeof anc.contains === 'function' && anc.contains(node)) return true
714
+ if (node === anc) return true
715
+ node = node.getRootNode ? node.getRootNode().host : null
716
+ }
717
+ return false
718
+ }
719
+ if (inside(hit, el)) return true
720
+ const clickableAnc = (node) => {
721
+ if (!node || node === document.body || node === document.documentElement) return false
722
+ const tag = node.tagName
723
+ if (tag === 'A' || tag === 'BUTTON' || tag === 'LABEL' || tag === 'SUMMARY') return true
724
+ const role = typeof node.getAttribute === 'function' ? (node.getAttribute('role') || '') : ''
725
+ if (/^(button|link|tab|menuitem|option|checkbox|radio|switch)$/i.test(role)) return true
726
+ if (typeof node.onclick === 'function' || (typeof node.getAttribute === 'function' && (node.getAttribute('onclick') || node.getAttribute('tabindex') != null))) return true
727
+ const hs = typeof getComputedStyle === 'function' ? getComputedStyle(node) : null
728
+ return hs?.cursor === 'pointer'
729
+ }
730
+ const st = typeof getComputedStyle === 'function' ? getComputedStyle(el) : null
731
+ return st?.pointerEvents === 'none' && inside(el, hit) && clickableAnc(hit)
732
+ }
473
733
  if (action === 'scroll') {
474
734
  const dx = Number.isFinite(Number(args.dx)) ? Number(args.dx) : 0
475
735
  const dy = Number.isFinite(Number(args.dy)) ? Number(args.dy) : 600
736
+ const view = el.ownerDocument?.defaultView || window
476
737
  const scrollable = (n) => {
477
738
  if (!n || n.nodeType !== 1) return false
478
739
  const canY = n.scrollHeight > n.clientHeight + 1
479
740
  const canX = n.scrollWidth > n.clientWidth + 1
480
741
  if (!canY && !canX) return false
481
- const st = getComputedStyle(n)
742
+ const st = view.getComputedStyle(n)
482
743
  if (!st || (st.overflowY === undefined && st.overflowX === undefined)) return n === el
483
744
  return (canY && /auto|scroll|overlay/.test(st.overflowY)) || (canX && /auto|scroll|overlay/.test(st.overflowX))
484
745
  }
@@ -487,7 +748,7 @@ async function frameAction(local, action, args) {
487
748
  if (!scrollable(target)) {
488
749
  let cur = parentOf(el)
489
750
  while (cur && !scrollable(cur)) cur = parentOf(cur)
490
- target = cur || document.scrollingElement || document.documentElement || el
751
+ target = cur || el.ownerDocument?.scrollingElement || el.ownerDocument?.documentElement || el
491
752
  }
492
753
  target.scrollBy({ left: dx, top: dy, behavior: 'instant' })
493
754
  return { scrollTop: Math.round(target.scrollTop), scrollHeight: target.scrollHeight }
@@ -514,20 +775,21 @@ async function frameAction(local, action, args) {
514
775
  [...el.options].find(o => o.textContent.trim() === args.value)
515
776
  if (!option) return 'noOption'
516
777
  if (option.disabled || option.parentElement?.disabled) return 'disabled'
517
- proto = HTMLSelectElement.prototype
778
+ proto = (el.ownerDocument.defaultView.HTMLSelectElement || HTMLSelectElement).prototype
518
779
  value = option.value
519
780
  } else {
520
781
  if (action !== 'fill' || el.readOnly || el.getAttribute('aria-readonly') === 'true') return 'wrong'
521
- if (el.tagName === 'TEXTAREA') proto = HTMLTextAreaElement.prototype
522
- else if (el.tagName === 'INPUT' && /^(text|search|email|tel|password|url|number)$/.test(el.type)) proto = HTMLInputElement.prototype
782
+ if (el.tagName === 'TEXTAREA') proto = (el.ownerDocument.defaultView.HTMLTextAreaElement || HTMLTextAreaElement).prototype
783
+ else if (el.tagName === 'INPUT' && /^(text|search|email|tel|password|url|number)$/.test(el.type)) proto = (el.ownerDocument.defaultView.HTMLInputElement || HTMLInputElement).prototype
523
784
  else return 'wrong'
524
785
  el.focus()
525
786
  if (!el.isConnected || el.getRootNode().activeElement !== el) return 'wrong'
526
787
  value = String(args.value ?? '')
527
788
  }
528
789
  Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, value)
529
- el.dispatchEvent(new Event('input', { bubbles: true, composed: true }))
530
- el.dispatchEvent(new Event('change', { bubbles: true }))
790
+ const FieldEvent = el.ownerDocument.defaultView.Event || Event
791
+ el.dispatchEvent(new FieldEvent('input', { bubbles: true, composed: true }))
792
+ el.dispatchEvent(new FieldEvent('change', { bubbles: true }))
531
793
  await Promise.resolve()
532
794
  if (!el.isConnected || el.value !== value) return 'rejected'
533
795
  return option ? { value, label: option.textContent.trim() } : 'ok'
@@ -626,7 +888,7 @@ function frameGate(tabId, op, timeoutMs) {
626
888
  }
627
889
  }
628
890
 
629
- async function collect({ tabId, paths, scope, query = '', timeoutMs }, textOnly) {
891
+ async function collect({ tabId, paths, scope, query = '', mode, extraSecrets, timeoutMs }, textOnly) {
630
892
  tabId = Number(tabId)
631
893
  const allow = frameGate(tabId, textOnly ? 'frameTexts' : 'frameSnapshot', timeoutMs)
632
894
  let slots = tabSlots.get(tabId)
@@ -642,6 +904,133 @@ async function collect({ tabId, paths, scope, query = '', timeoutMs }, textOnly)
642
904
  }
643
905
  return a.path.length - b.path.length
644
906
  })
907
+ let mainSecrets = []
908
+ let mainMetaRedactor = null
909
+ let mainTextRedactor = null
910
+ let mainSecretsFailed = false
911
+ const mainFrame = frames.get('')
912
+ const mainOrigin = mainFrame?.origin && mainFrame.origin !== 'null' ? mainFrame.origin : ''
913
+ const cachedEntry = S.recentSecrets.get(tabId)
914
+ const cachedRecent = (mainOrigin && cachedEntry && cachedEntry.origin === mainOrigin && cachedEntry.expiresAt > Date.now())
915
+ ? [...cachedEntry.values] : []
916
+ if (mainFrame) {
917
+ const probedSecrets = await inDocument(tabId, frames.get(''), () => {
918
+ // Self-contained JSON-only scripting call mirroring isSensitiveField (no function in executeScript args).
919
+ const isMasked = (el) => {
920
+ if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && !el.isContentEditable) return false
921
+ const st = (el.ownerDocument?.defaultView || window).getComputedStyle(el)
922
+ const value = String(el.isContentEditable ? el.innerText || '' : el.value || '')
923
+ const doc = el.ownerDocument || (typeof document !== 'undefined' ? document : null)
924
+ const root = typeof el.getRootNode === 'function' ? el.getRootNode() : null
925
+ const getById = (id) => (root && typeof root.getElementById === 'function' && root.getElementById(id)) ||
926
+ (doc && typeof doc.getElementById === 'function' && doc.getElementById(id)) || null
927
+ const labelParts = []
928
+ if (el.labels && el.labels.length) {
929
+ for (const l of el.labels) labelParts.push((l && (l.innerText || l.textContent)) || '')
930
+ } else {
931
+ const id = el.id || (typeof el.getAttribute === 'function' ? el.getAttribute('id') || '' : '')
932
+ const qRoot = (root && typeof root.querySelectorAll === 'function' ? root : null) ||
933
+ (doc && typeof doc.querySelectorAll === 'function' ? doc : null)
934
+ if (id && qRoot) {
935
+ try {
936
+ const esc = typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(id) : String(id).replace(/["\\]/g, '\\$&')
937
+ for (const l of qRoot.querySelectorAll(`label[for="${esc}"]`)) labelParts.push(l.innerText || l.textContent || '')
938
+ } catch {}
939
+ }
940
+ const wrap = typeof el.closest === 'function' ? el.closest('label') : null
941
+ if (wrap) labelParts.push(wrap.innerText || wrap.textContent || '')
942
+ }
943
+ const by = typeof el.getAttribute === 'function' ? el.getAttribute('aria-labelledby') || '' : ''
944
+ if (by) {
945
+ for (const refId of by.trim().split(/\s+/)) {
946
+ const n = refId && getById(refId)
947
+ if (n) labelParts.push(n.innerText || n.textContent || '')
948
+ }
949
+ }
950
+ const ga = (attr) => (typeof el.getAttribute === 'function' ? el.getAttribute(attr) || '' : '')
951
+ const fields = [
952
+ ...['name', 'id', 'autocomplete', 'aria-label', 'placeholder', 'title'].map(ga),
953
+ ...labelParts,
954
+ ].join(' ')
955
+ return ['password', 'tel'].includes(el.type) ||
956
+ (st?.webkitTextSecurity && st.webkitTextSecurity !== 'none') ||
957
+ (/^numeric$/i.test(ga('inputmode')) && !!value) ||
958
+ /(?:^|[\s_-])pin(?:$|[\s_-])|otp|passcode|verif|2fa|mfa|sms[_-]?code|auth[_-]?code|cvv|cvc|card|secret|token|api[_-]?key|pwd|pass(?:word|wd)?|验证码|校验码|动态码|安全码|口令|密码|密钥|银行卡|卡号|令牌|парол|код\s*(?:подтвержд|доступа|безопасн|проверк)|смс[- ]?код|пин[- ]?код|секрет|токен|номер\s*карт/i.test(fields) ||
959
+ /(?:^|\s)(?:one-time-code|cc-number|cc-csc)(?:\s|$)/i.test(fields) ||
960
+ (/(?:^|[\s_-])code(?:$|[\s_-])/i.test(fields) && true) ||
961
+ /(?:\d[\s-]?){11}\d/.test(value)
962
+ }
963
+ const out = new Set()
964
+ const walk = (root) => {
965
+ for (const el of root.querySelectorAll('*')) {
966
+ if (out.size >= 50) return
967
+ if (el.shadowRoot) walk(el.shadowRoot)
968
+ if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
969
+ try { if (el.contentDocument?.body) walk(el.contentDocument) } catch {}
970
+ }
971
+ if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && !el.isContentEditable) continue
972
+ if (!isMasked(el)) continue
973
+ for (const v of [el.value, el.innerText, el.tagName === 'TEXTAREA' && el.defaultValue]) {
974
+ const s = v ? String(v) : ''
975
+ if (s.length >= 4) out.add(s.slice(0, 512))
976
+ }
977
+ }
978
+ }
979
+ walk(document)
980
+ return [...out].sort((a, b) => b.length - a.length)
981
+ }, []).catch(() => null)
982
+ if (!Array.isArray(probedSecrets)) mainSecretsFailed = true
983
+ else {
984
+ mainSecrets = [...new Set([...probedSecrets, ...cachedRecent])].sort((a, b) => b.length - a.length)
985
+ if (mainSecrets.length && mainOrigin) {
986
+ const prev = S.recentSecrets.get(tabId)
987
+ const values = prev && prev.origin === mainOrigin && prev.expiresAt > Date.now() ? prev.values : new Set()
988
+ for (const v of mainSecrets) if (typeof v === 'string' && v.length >= 4 && values.size < 50) values.add(v.slice(0, 512))
989
+ if (values.size) S.recentSecrets.set(tabId, { origin: mainOrigin, expiresAt: Date.now() + 15_000, values })
990
+ }
991
+ if (mainSecrets.length) {
992
+ const escRe = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
993
+ const enc = new TextEncoder()
994
+ const buildRedactor = (minLen) => {
995
+ const rules = mainSecrets.filter(s => s.length >= minLen).map(secret => {
996
+ if (secret.length <= 256) {
997
+ let pat = ''
998
+ for (const ch of secret) {
999
+ if (ch === ' ') { pat += '(?: |%20|\\+)'; continue }
1000
+ if (/^[a-zA-Z0-9]$/.test(ch)) { pat += ch; continue }
1001
+ let pct = ''
1002
+ for (const b of enc.encode(ch)) {
1003
+ const h = b.toString(16).padStart(2, '0')
1004
+ pct += '%' + h.replace(/[a-f]/g, c => '[' + c + c.toUpperCase() + ']')
1005
+ }
1006
+ pat += '(?:' + escRe(ch) + '|' + pct + ')'
1007
+ }
1008
+ return { secret, re: new RegExp(pat, 'g'), extras: [] }
1009
+ }
1010
+ const extras = new Set()
1011
+ try {
1012
+ const e1 = encodeURIComponent(secret)
1013
+ if (e1 && e1 !== secret) { extras.add(e1); if (e1.includes('%20')) extras.add(e1.replace(/%20/g, '+')) }
1014
+ const e2 = new URLSearchParams([['x', secret]]).toString().slice(2)
1015
+ if (e2 && e2 !== secret) { extras.add(e2); if (e2.includes('+')) extras.add(e2.replace(/\+/g, '%20')) }
1016
+ } catch {}
1017
+ return { secret, re: null, extras: [...extras].map(v => new RegExp(escRe(v), 'gi')) }
1018
+ })
1019
+ if (!rules.length) return null
1020
+ return (text) => {
1021
+ let out = String(text ?? '')
1022
+ for (const { secret, re, extras } of rules) {
1023
+ if (re) out = out.replace(re, '••••')
1024
+ else { out = out.replaceAll(secret, '••••'); for (const x of extras) out = out.replace(x, '••••') }
1025
+ }
1026
+ return out
1027
+ }
1028
+ }
1029
+ mainMetaRedactor = buildRedactor(6)
1030
+ mainTextRedactor = buildRedactor(4)
1031
+ }
1032
+ }
1033
+ }
645
1034
  for (const f of ordered) {
646
1035
  if (!f.frameId || f.href.startsWith('chrome-extension:')) continue
647
1036
  const root = paths?.find(p => p.length <= f.path.length && p.every((n, i) => n === f.path[i]))
@@ -651,20 +1040,56 @@ async function collect({ tabId, paths, scope, query = '', timeoutMs }, textOnly)
651
1040
  if (!g) continue
652
1041
  const path = root || f.path
653
1042
  if (textOnly) {
654
- const text = await inDocument(tabId, f, scanPage, [null, 'frameText', '', {}])
655
- if (text != null) groups.push({ path, src: f.href.slice(0, 120), text })
1043
+ const res = await inDocument(tabId, f, scanPage, [null, 'frameText', '', {}])
1044
+ let text = typeof res === 'string' ? res : res?.text
1045
+ const originOnly = (() => { try { const o = new URL(f.href).origin; return o && o !== 'null' ? o : '' } catch { return '' } })()
1046
+ if (mainSecretsFailed) {
1047
+ if (originOnly) groups.push({ path, src: originOnly.slice(0, 120), text: '' })
1048
+ if (groups.length === 30) break
1049
+ continue
1050
+ }
1051
+ let src = typeof res === 'object' && res?.src ? res.src : f.href
1052
+ if (mainTextRedactor) {
1053
+ if (res?.srcTooLong) {
1054
+ src = originOnly
1055
+ } else {
1056
+ try {
1057
+ const u = new URL(src)
1058
+ src = u.origin && u.origin !== 'null' ? u.origin + mainTextRedactor(u.pathname + u.search + u.hash) : (mainMetaRedactor ? mainMetaRedactor(src) : src)
1059
+ } catch {
1060
+ if (mainMetaRedactor) src = mainMetaRedactor(src)
1061
+ }
1062
+ }
1063
+ if (text != null) {
1064
+ text = mainTextRedactor(text)
1065
+ if (res?.textOverCap && text.length > 16000) text = text.slice(0, Math.min(text.length - 4096, 16000))
1066
+ }
1067
+ }
1068
+ if (text != null) groups.push({ path, src: src.slice(0, 120), text: text.slice(0, 16000) })
656
1069
  if (groups.length === 30) break
657
1070
  continue
658
1071
  }
659
- const data = await inDocument(tabId, f, scanPage, [null, scope || 'all', query, { clip: g.clip }])
1072
+ if (mainSecretsFailed) continue
1073
+ const frameOpts = { ...(mode === 'page' && { mode }), swRedact: true }
1074
+ const data = await inDocument(tabId, f, scanPage, [null, scope || 'all', query, { clip: g.clip }, frameOpts])
660
1075
  if (!data?.rows) continue
661
1076
  let slot = [...slots].find(([, entry]) => entry.documentId === f.documentId)?.[0]
662
1077
  if (!slot) slot = await reserveSlot()
663
1078
  slots.set(slot, { frameId: f.frameId, documentId: f.documentId, href: f.href, origin: f.origin })
1079
+ const red = (s) => (mainTextRedactor ? mainTextRedactor(s) : String(s ?? ''))
1080
+ const redUrl = (u) => {
1081
+ if (!mainTextRedactor && !mainMetaRedactor) return String(u ?? '')
1082
+ const s = String(u ?? '')
1083
+ try {
1084
+ const parsed = new URL(s)
1085
+ if (parsed.origin && parsed.origin !== 'null') return parsed.origin + (mainTextRedactor ? mainTextRedactor(parsed.pathname + parsed.search + parsed.hash) : s.slice(parsed.origin.length))
1086
+ } catch {}
1087
+ if (s.startsWith('/')) return mainTextRedactor ? mainTextRedactor(s) : s
1088
+ return mainTextRedactor ? mainTextRedactor(s) : (mainMetaRedactor ? mainMetaRedactor(s) : s)
1089
+ }
664
1090
  const rows = data.rows.map(row => {
665
- if (row.ref == null) return row
666
- const ref = slot * 10000 + row.ref
667
- return { ref, line: '[' + ref + ']' + row.line.slice(row.line.indexOf(']') + 1) }
1091
+ const ref = row.ref != null ? slot * 10000 + row.ref : undefined
1092
+ return formatRedactedRow({ ...row, ...(ref != null && { ref }) }, red, redUrl, mode, Boolean(mainTextRedactor))
668
1093
  })
669
1094
  groups.push({ path, rows, count: data.count, outside: data.outside, capped: data.capped })
670
1095
  }
@@ -698,15 +1123,35 @@ async function act({ tabId, ref, timeoutMs, ...args }, action) {
698
1123
  const result = await apply()
699
1124
  return result == null ? { gone: true } : { result }
700
1125
  }
701
- for (let depth = 0; depth < frame.path.length; depth++) {
702
- const parent = frames.get(frame.path.slice(0, depth).join('.'))
703
- if (!parent || !await inDocument(tabId, parent, frameInfo, [frame.path[depth]])) return { gone: true }
1126
+ if (!args?.verifyHit && !args?.verifyPoint) {
1127
+ for (let depth = 0; depth < frame.path.length; depth++) {
1128
+ const parent = frames.get(frame.path.slice(0, depth).join('.'))
1129
+ if (!parent || !await inDocument(tabId, parent, frameInfo, [frame.path[depth]])) return { gone: true }
1130
+ }
704
1131
  }
705
1132
  const target = await apply()
706
1133
  if (!target) return { gone: true }
707
1134
  frames = await tree(tabId)
708
1135
  if (frames.get(frame.path.join('.'))?.documentId !== frame.documentId) return { gone: true }
709
1136
  await allow(frames, frame.path, entry)
1137
+ const vp = args?.verifyPoint
1138
+ if (vp && Number.isFinite(vp.x) && Number.isFinite(vp.y)) {
1139
+ // Atomically verify hit-test + live geometry and inverse-map at each ancestor layer in one call.
1140
+ let px = Number(vp.x), py = Number(vp.y)
1141
+ for (let i = 0; i < frame.path.length; i++) {
1142
+ const parent = frames.get(frame.path.slice(0, i).join('.'))
1143
+ const child = frame.path[i]
1144
+ if (!parent) return { gone: true, reason: 'moved' }
1145
+ const mapped = await inDocument(tabId, parent, frameInfo, [null, false, { child, x: px, y: py, map: true, expectedPath: frame.path.slice(0, i) }])
1146
+ if (!mapped?.ok || !Number.isFinite(mapped.x) || !Number.isFinite(mapped.y)) return { gone: true, reason: 'moved' }
1147
+ px = mapped.x
1148
+ py = mapped.y
1149
+ }
1150
+ const childHitOk = tabSlots.get(tabId)?.get(slot) === entry
1151
+ ? await inDocument(tabId, entry, frameAction, [ref % 10000, 'verifyPoint', { x: px, y: py, expectedPath: frame.path }]) : false
1152
+ if (!childHitOk) return { gone: true, reason: 'moved' }
1153
+ return { ...target, x: vp.x, y: vp.y, shadow: true, crossFrame: true, frameId: frame.frameId, documentId: frame.documentId }
1154
+ }
710
1155
  const g = await loadGeometry(tabId, frames, frame.path)
711
1156
  if (!g?.aligned) return { gone: true }
712
1157
  const r = target.box
@@ -714,7 +1159,14 @@ async function act({ tabId, ref, timeoutMs, ...args }, action) {
714
1159
  const left = Math.max(r.x, g.clip.left), right = Math.min(r.x + r.width, g.clip.right)
715
1160
  const top = Math.max(r.y, g.clip.top), bottom = Math.min(r.y + r.height, g.clip.bottom)
716
1161
  if (right <= left || bottom <= top) return { gone: true }
717
- let x = (left + right) / 2, y = (top + bottom) / 2
1162
+ const localX = (left + right) / 2, localY = (top + bottom) / 2
1163
+ let x = localX, y = localY
1164
+ // Verify the exact clipped hit point inside the target child document before checking parent overlays.
1165
+ if (args?.verifyHit) {
1166
+ const childHitOk = tabSlots.get(tabId)?.get(slot) === entry
1167
+ ? await inDocument(tabId, entry, frameAction, [ref % 10000, 'verifyPoint', { x: localX, y: localY, expectedPath: frame.path }]) : false
1168
+ if (!childHitOk) return { gone: true }
1169
+ }
718
1170
  // The iframe's center can be visible while an overlay covers the control.
719
1171
  for (let i = frame.path.length - 1; i >= 0; i--) {
720
1172
  const parent = frames.get(frame.path.slice(0, i).join('.'))
@@ -724,7 +1176,51 @@ async function act({ tabId, ref, timeoutMs, ...args }, action) {
724
1176
  y = bounds.y + y * bounds.sy
725
1177
  if (!await inDocument(tabId, parent, frameInfo, [null, false, { child, x, y }])) return { gone: true }
726
1178
  }
727
- return { ...target, box, x, y, shadow: true, crossFrame: true, frameId: frame.frameId }
1179
+ return { ...target, box, x, y, shadow: true, crossFrame: true, frameId: frame.frameId, documentId: frame.documentId }
1180
+ }
1181
+
1182
+ export function formatRedactedRow(row, red, redUrl, mode, hasSecrets) {
1183
+ const swCut = (s, n) => { const str = String(s ?? ''); return str.length > n ? str.slice(0, n - 1) + '…' : str }
1184
+ const swQ = (s) => JSON.stringify(String(s ?? ''))
1185
+ const safe = (v, isUrl = false) => {
1186
+ if (v && typeof v === 'object' && v.tooLong) return hasSecrets ? '••••' : ''
1187
+ return isUrl ? redUrl(v) : red(v)
1188
+ }
1189
+ const ref = row.ref
1190
+ let line
1191
+ if (row.raw) {
1192
+ const r = row.raw
1193
+ const prefix = typeof row.line === 'string' && /^\[[+~-]\] /.test(row.line) ? row.line.slice(0, 4) : ''
1194
+ if (r.kind === 'h') line = '#'.repeat(r.level) + ' ' + swCut(safe(r.title), 80)
1195
+ else if (r.kind === 't') line = swCut(safe(r.text), 120)
1196
+ else if (r.kind === 'iframe') line = '[iframe] ' + swCut(safe(r.val, true), 80) + (r.suffix || '')
1197
+ else {
1198
+ const st = r.st || {}
1199
+ let extra = ''
1200
+ if (st.selText !== undefined) extra = ' = ' + swQ(swCut(safe(st.selText), 40)) + '(' + st.optCount + ' 个选项)'
1201
+ else if (st.maskedVal) extra = ' = ••••'
1202
+ else if (st.val) extra = ' = ' + swQ(swCut(safe(st.val), 60))
1203
+ if (st.ph) extra += ' 提示' + swQ(swCut(safe(st.ph), 40))
1204
+ if (st.href) extra += ' → ' + swCut(safe(st.href, true), 70)
1205
+ if (st.out?.length) extra += ' (' + st.out.join(',') + ')'
1206
+ const name = r.name ? ' ' + swQ(swCut(safe(r.name), 80)) : ''
1207
+ line = '[' + ref + '] ' + r.role + name + extra
1208
+ }
1209
+ if (mode === 'page') line = swCut(line, 120)
1210
+ if (prefix) line = prefix + line
1211
+ } else {
1212
+ const rawLine = row.line == null ? null : String(row.line)
1213
+ if (rawLine == null) line = null
1214
+ else if (ref != null && rawLine.startsWith('[') && rawLine.includes(']')) line = '[' + ref + ']' + red(rawLine.slice(rawLine.indexOf(']') + 1))
1215
+ else line = red(rawLine)
1216
+ }
1217
+ return {
1218
+ ...(row.key && { key: row.key }),
1219
+ ...(ref != null && { ref }),
1220
+ ...(row.crossPath && { crossPath: row.crossPath }),
1221
+ ...(row.framePath && { framePath: row.framePath }),
1222
+ line,
1223
+ }
728
1224
  }
729
1225
 
730
1226
  export function initFrames() {