8a48765a46
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
304 lines
11 KiB
JavaScript
304 lines
11 KiB
JavaScript
// 有头 Chrome 焦点守卫:唯一页面、禁止新建 / 切换标签页、后台建页兜底、前台状态检测。
|
||
// 规则见 docs/ui/GLOBAL_UI_BASELINE.md 第 7.1 节。
|
||
|
||
import { contextOptions as sharedContextOptions } from './browser-environment.mjs';
|
||
import { prepareStaticCapture } from './browser-capture.mjs';
|
||
import { browserRuntime, browserStabilityArgs } from './playwright-runtime.mjs';
|
||
|
||
import { execFile } from 'node:child_process';
|
||
import { mkdtemp, rm } from 'node:fs/promises';
|
||
import os from 'node:os';
|
||
import path from 'node:path';
|
||
|
||
export const FOCUS_SAFE_ARGS = Object.freeze([
|
||
...browserStabilityArgs,
|
||
'--window-position=-32000,-32000',
|
||
]);
|
||
|
||
export const FOCUS_EVENTS = Object.freeze({
|
||
STARTUP: '启动焦点激活事件',
|
||
STARTUP_PERSIST: '启动焦点仍保持',
|
||
REACTIVATED: '二次焦点激活',
|
||
UNKNOWN: '无法确认后台状态',
|
||
EXTRA_PAGE: '意外新页面',
|
||
FORBIDDEN: '禁止的焦点操作',
|
||
BACKGROUND_TARGET: '后台创建页面',
|
||
});
|
||
|
||
export class FocusGuardError extends Error {
|
||
constructor(message) {
|
||
super(message);
|
||
this.name = 'FocusGuardError';
|
||
}
|
||
}
|
||
|
||
export function createFocusLog(sink = console.log) {
|
||
const entries = [];
|
||
return {
|
||
entries,
|
||
record(type, detail = {}) {
|
||
const entry = { time: new Date().toISOString(), type, ...detail };
|
||
entries.push(entry);
|
||
sink(`[focus] ${type} ${JSON.stringify(detail)}`);
|
||
return entry;
|
||
},
|
||
};
|
||
}
|
||
|
||
// 在页面内拦截 window.open 与 target 非 _self 的链接,避免应用自行打开新标签页。
|
||
export const BLOCK_POPUP_SCRIPT = `(() => {
|
||
if (window.__focusGuardBlockedOpens) return;
|
||
const blocked = [];
|
||
Object.defineProperty(window, '__focusGuardBlockedOpens', { value: blocked });
|
||
window.open = function (url) {
|
||
blocked.push(String(url ?? ''));
|
||
return null;
|
||
};
|
||
const intercept = (event) => {
|
||
const anchor = event.target && event.target.closest && event.target.closest('a[target]');
|
||
if (!anchor) return;
|
||
const target = String(anchor.getAttribute('target') || '').toLowerCase();
|
||
if (!target || target === '_self' || target === '_top' || target === '_parent') return;
|
||
event.preventDefault();
|
||
blocked.push(anchor.href);
|
||
};
|
||
document.addEventListener('click', intercept, true);
|
||
document.addEventListener('auxclick', intercept, true);
|
||
})();`;
|
||
|
||
export function installFocusGuards(context, page, log) {
|
||
const browser = context.browser?.();
|
||
const forbid = (api) => async () => {
|
||
log.record(FOCUS_EVENTS.FORBIDDEN, { api });
|
||
throw new FocusGuardError(
|
||
`${api} 被焦点约束禁止:只能在唯一页面内用 goto 导航`,
|
||
);
|
||
};
|
||
const original = {
|
||
newPage: context.newPage,
|
||
bringToFront: page.bringToFront,
|
||
browserNewPage: browser?.newPage,
|
||
browserNewContext: browser?.newContext,
|
||
};
|
||
context.newPage = forbid('context.newPage');
|
||
page.bringToFront = forbid('page.bringToFront');
|
||
if (browser) {
|
||
browser.newPage = forbid('browser.newPage');
|
||
browser.newContext = forbid('browser.newContext');
|
||
}
|
||
const onPage = async (extra) => {
|
||
if (extra === page) return;
|
||
log.record(FOCUS_EVENTS.EXTRA_PAGE, { url: extra.url() });
|
||
await extra.close().catch(() => {});
|
||
};
|
||
context.on('page', onPage);
|
||
return () => {
|
||
context.off('page', onPage);
|
||
context.newPage = original.newPage;
|
||
page.bringToFront = original.bringToFront;
|
||
if (browser) {
|
||
browser.newPage = original.browserNewPage;
|
||
browser.newContext = original.browserNewContext;
|
||
}
|
||
};
|
||
}
|
||
|
||
// 状态迁移:启动阶段的激活只记录;之后仅“后台 → 前台”视为二次激活。
|
||
export function classifyFocus({ phase, previous, current }) {
|
||
if (current === 'unknown')
|
||
return { event: FOCUS_EVENTS.UNKNOWN, fatal: true };
|
||
if (current !== 'foreground') return { event: null, fatal: false };
|
||
if (phase === 'startup') return { event: FOCUS_EVENTS.STARTUP, fatal: false };
|
||
if (previous === 'foreground')
|
||
return { event: FOCUS_EVENTS.STARTUP_PERSIST, fatal: false };
|
||
return { event: FOCUS_EVENTS.REACTIVATED, fatal: true };
|
||
}
|
||
|
||
const FOREGROUND_PS = `[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;
|
||
Add-Type -Namespace FocusGuard -Name User32 -MemberDefinition '[DllImport("user32.dll")] public static extern System.IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(System.IntPtr h, out uint p);'
|
||
$fg = 0; [void][FocusGuard.User32]::GetWindowThreadProcessId([FocusGuard.User32]::GetForegroundWindow(), [ref]$fg)
|
||
$dir = $env:FOCUS_GUARD_PROFILE
|
||
$ids = @()
|
||
if ($dir) { $ids = @(Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($dir) } | ForEach-Object { $_.ProcessId }) }
|
||
Write-Output ("$fg|" + ($ids -join ','))`;
|
||
|
||
export function parseForegroundOutput(output) {
|
||
const match = /^(\d+)\|([\d,]*)$/.exec(String(output).trim());
|
||
if (!match) return { state: 'unknown', reason: 'unparsable' };
|
||
const pids = match[2] ? match[2].split(',').map(Number) : [];
|
||
if (!pids.length) return { state: 'unknown', reason: 'no-browser-process' };
|
||
return {
|
||
state: pids.includes(Number(match[1])) ? 'foreground' : 'background',
|
||
foregroundPid: Number(match[1]),
|
||
browserPids: pids,
|
||
};
|
||
}
|
||
|
||
// 只读查询系统前台窗口所属进程,并与本次 profile 启动的 chrome.exe 比对;不调用任何激活 API。
|
||
export function probeOsForeground(profileDir) {
|
||
if (process.platform !== 'win32')
|
||
return Promise.resolve({
|
||
state: 'unknown',
|
||
reason: 'unsupported-platform',
|
||
});
|
||
const encoded = Buffer.from(FOREGROUND_PS, 'utf16le').toString('base64');
|
||
return new Promise((resolve) => {
|
||
execFile(
|
||
'powershell.exe',
|
||
['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
|
||
{
|
||
windowsHide: true,
|
||
timeout: 15000,
|
||
env: { ...process.env, FOCUS_GUARD_PROFILE: profileDir },
|
||
},
|
||
(error, stdout) =>
|
||
resolve(
|
||
error
|
||
? { state: 'unknown', reason: 'probe-failed' }
|
||
: parseForegroundOutput(stdout),
|
||
),
|
||
);
|
||
});
|
||
}
|
||
|
||
async function createBackgroundPage(context, log) {
|
||
const browser = context.browser();
|
||
if (!browser)
|
||
throw new FocusGuardError('无法获取 Browser,不能用 CDP 后台创建页面');
|
||
const session = await browser.newBrowserCDPSession();
|
||
try {
|
||
const pagePromise = context.waitForEvent('page', { timeout: 10000 });
|
||
await session.send('Target.createTarget', {
|
||
url: 'about:blank',
|
||
background: true,
|
||
newWindow: false,
|
||
});
|
||
const page = await pagePromise;
|
||
log.record(FOCUS_EVENTS.BACKGROUND_TARGET, { via: 'Target.createTarget' });
|
||
return page;
|
||
} finally {
|
||
await session.detach().catch(() => {});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 启动唯一页面的有头 Chrome。切换桌面 / 移动需关闭后重新启动(计为新的启动阶段)。
|
||
* 返回 { context, page, log, checkpoint, resetSession, blockedPopups, close }。
|
||
*/
|
||
export async function launchFocusSafe(options = {}) {
|
||
const runtime = browserRuntime({
|
||
...process.env,
|
||
...(options.headless === undefined
|
||
? {}
|
||
: { PW_HEADLESS: options.headless ? '1' : '0' }),
|
||
});
|
||
const {
|
||
chromium = (await import('@playwright/test')).chromium,
|
||
device = 'desktop',
|
||
colorScheme = 'light',
|
||
headless = runtime.headless,
|
||
blockPopups = true,
|
||
extraArgs = [],
|
||
contextOptions = {},
|
||
log = createFocusLog(),
|
||
} = options;
|
||
const deviceEnvironment = sharedContextOptions(device);
|
||
const profileDir = await mkdtemp(path.join(os.tmpdir(), 'monkey-pw-focus-'));
|
||
let context;
|
||
try {
|
||
context = await chromium.launchPersistentContext(profileDir, {
|
||
...deviceEnvironment,
|
||
locale: 'zh-CN',
|
||
timezoneId: 'Asia/Shanghai',
|
||
colorScheme,
|
||
reducedMotion: 'reduce',
|
||
serviceWorkers: 'block',
|
||
...contextOptions,
|
||
channel: 'chrome',
|
||
headless,
|
||
args: [...extraArgs, ...runtime.launchArgs],
|
||
});
|
||
} catch (error) {
|
||
await rm(profileDir, { recursive: true, force: true, maxRetries: 5 });
|
||
throw error;
|
||
}
|
||
if (blockPopups) await context.addInitScript(BLOCK_POPUP_SCRIPT);
|
||
const page = context.pages()[0] ?? (await createBackgroundPage(context, log));
|
||
const removeGuards = installFocusGuards(context, page, log);
|
||
const screenshot = page.screenshot.bind(page);
|
||
page.screenshot = async (options = {}) => {
|
||
await prepareStaticCapture(page);
|
||
return screenshot({ scale: 'css', ...options });
|
||
};
|
||
|
||
let previous = 'background';
|
||
let phase = 'startup';
|
||
async function checkpoint(label, { pauseOnUnknown = true } = {}) {
|
||
if (
|
||
log.entries.some((entry) =>
|
||
[FOCUS_EVENTS.FORBIDDEN, FOCUS_EVENTS.EXTRA_PAGE].includes(entry.type),
|
||
)
|
||
) {
|
||
throw new FocusGuardError(
|
||
`焦点守护发现禁止操作或意外新页面(${label}),已停止`,
|
||
);
|
||
}
|
||
let state;
|
||
let detail = {};
|
||
if (headless) state = 'background';
|
||
else {
|
||
const osProbe = await probeOsForeground(profileDir);
|
||
// Playwright 默认开启焦点模拟,document.hasFocus() 恒为 true,只作记录;以系统前台进程为准。
|
||
const pageFocus = await page
|
||
.evaluate(() => document.hasFocus())
|
||
.catch(() => null);
|
||
detail = {
|
||
os: osProbe.state,
|
||
reason: osProbe.reason,
|
||
foregroundPid: osProbe.foregroundPid,
|
||
documentHasFocus: pageFocus,
|
||
};
|
||
state = osProbe.state;
|
||
}
|
||
const verdict = classifyFocus({ phase, previous, current: state });
|
||
if (verdict.event) log.record(verdict.event, { label, ...detail });
|
||
phase = 'running';
|
||
if (state !== 'unknown') previous = state;
|
||
if (verdict.fatal && (state !== 'unknown' || pauseOnUnknown))
|
||
throw new FocusGuardError(`${verdict.event}(${label}),已暂停`);
|
||
return { state, ...detail };
|
||
}
|
||
|
||
async function resetSession(origins = []) {
|
||
await context.clearCookies();
|
||
const session = await context.newCDPSession(page);
|
||
try {
|
||
for (const origin of origins)
|
||
await session.send('Storage.clearDataForOrigin', {
|
||
origin,
|
||
storageTypes: 'all',
|
||
});
|
||
} finally {
|
||
await session.detach().catch(() => {});
|
||
}
|
||
await page.goto('about:blank');
|
||
}
|
||
|
||
const blockedPopups = () =>
|
||
page.evaluate(() => [...(window.__focusGuardBlockedOpens || [])]);
|
||
|
||
async function close() {
|
||
removeGuards();
|
||
await context.close().catch(() => {});
|
||
await rm(profileDir, { recursive: true, force: true, maxRetries: 5 });
|
||
}
|
||
|
||
try {
|
||
await checkpoint('launch');
|
||
} catch (error) {
|
||
await close();
|
||
throw error;
|
||
}
|
||
return { context, page, log, checkpoint, resetSession, blockedPopups, close };
|
||
}
|