Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions src/browser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class BrowserManager extends EventEmitter {
return true;
}

async launch({ executablePath, headless, profileDir, isolated, projectDir, proxy, embed }) {
async launch({ executablePath, headless, profileDir, isolated, projectDir, proxy, embed, dock }) {
if (executablePath) await requireNormalExecutable(executablePath);
await this.close();
this.projectDir = projectDir;
Expand All @@ -93,6 +93,9 @@ class BrowserManager extends EventEmitter {
this.headless = !!headless;
const vw = this.fit?.width || 1366, vh = this.fit?.height || 850;
if (headless) args.push(`--window-size=${vw},${vh}`);
// 伪嵌入:先放到屏幕外,等宿主用 CDP 把窗口停靠到面板矩形,避免闪一下。
this.dock = !!dock && !headless;
if (this.dock) args.push('--window-position=-32000,-32000', `--window-size=${vw},${vh}`, '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding');
// Windows 嵌入模式:窗口先放到屏幕外(不闪现),等 Rust 侧 SetParent 进主窗口后再显示;
// 被遮挡/隐藏的会话也要持续渲染(回落 screencast 时仍有画面)
this.embed = !!embed && !headless; this.embedFailed = false; this.chromePid = null;
Expand Down Expand Up @@ -139,7 +142,7 @@ class BrowserManager extends EventEmitter {
status() {
return {
running: this.running, cdpPort: this.cdpPort, capturePaused: this.net.paused,
embed: this.embedActive, chromePid: this.embedActive ? this.chromePid : null,
embed: this.embedActive, dock: !!(this.dock && this.running), chromePid: this.embedActive ? this.chromePid : null,
pages: this.pages.map((p, i) => ({ index: i, url: safe(() => p.url()), active: p === this.activePage })),
};
}
Expand Down Expand Up @@ -299,6 +302,24 @@ class BrowserManager extends EventEmitter {

clearRequests() { this.requests = []; this._dirty.clear(); this.emit('requests-cleared'); }

// 伪嵌入:CDP Browser 域移动/缩放/最小化真实窗口,不需要辅助功能权限。
async dockWindow({ left, top, width, height, hidden } = {}) {
if (!this.context) throw Error('浏览器尚未启动');
const browser = this.context.browser();
if (!browser) throw Error('当前配置不支持窗口停靠');
const session = await browser.newBrowserCDPSession();
try {
const { targetInfos } = await session.send('Target.getTargets');
const page = targetInfos.find(target => target.type === 'page');
if (!page) throw Error('没有可停靠的页面');
const { windowId } = await session.send('Browser.getWindowForTarget', { targetId: page.targetId });
const bounds = hidden
? { windowState: 'minimized' }
: { windowState: 'normal', left: Math.round(left), top: Math.round(top), width: Math.round(width), height: Math.round(height) };
await session.send('Browser.setWindowBounds', { windowId, bounds });
return { ok: true, windowId };
} finally { await session.detach().catch(() => {}); }
}
async close() {
try { await this.injector.disarm?.(); } catch {}
this.injector.resetContext();
Expand Down
72 changes: 58 additions & 14 deletions src/kernels.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,23 @@ export function repositoryName(value = 'CloakHQ/cloakbrowser') {
if (!/^[\w.-]+\/[\w.-]+$/.test(v) || v.includes('..')) throw new Error('填写 GitHub 仓库 owner/repo');
return v;
}
export function chooseAsset(release, { asset, platform = process.platform, arch = process.arch } = {}) {
const all = (release.assets || []).filter(a => /\.(zip|tar\.gz)$/i.test(a.name));
if (asset) { const a = all.find(a => a.name === asset); if (!a) throw new Error('未找到 Release 文件:' + asset); return a; }
export function archiveAssets(release) {
return ((release || {}).assets || []).filter(a => /\.(zip|tar\.gz)$/i.test(a.name));
}
// 返回与当前平台/架构匹配的唯一文件;不匹配时返回 null(用于跨 Release 查找)。
export function matchAsset(release, { asset, platform = process.platform, arch = process.arch } = {}) {
const all = archiveAssets(release);
if (asset) return all.find(a => a.name === asset) || null;
const platforms = platform === 'win32' ? /windows|win(?:32|64|-)/i : platform === 'darwin' ? /darwin|mac/i : /linux/i;
const arches = arch === 'arm64' ? /arm64|aarch64/i : /x64|amd64|win64|x86_64/i;
const found = all.filter(a => platforms.test(a.name) && arches.test(a.name));
if (found.length !== 1) throw new Error('请指定当前系统的 Release 文件名。可选:' + all.map(a => a.name).join(', '));
return found[0];
return found.length === 1 ? found[0] : null;
}
export function chooseAsset(release, options = {}) {
const target = matchAsset(release, options);
if (target) return target;
if (options.asset) throw new Error('未找到 Release 文件:' + options.asset);
throw new Error('请指定当前系统的 Release 文件名。可选:' + archiveAssets(release).map(a => a.name).join(', '));
}
async function response(url, fetcher, ms = 20000) {
const r = await fetcher(url, { signal: AbortSignal.timeout(ms), headers: { 'User-Agent': 'WebDecryptHub', Accept: 'application/vnd.github+json' } });
Expand Down Expand Up @@ -54,18 +63,39 @@ export async function probeKernel(userData, executablePath) {
return { ok: true, title, path: executablePath };
} catch (e) {
const message = String(e.message).replace(/\x1b\[[0-9;]*m/g, ''), code = message.match(/exitCode=(\d+)|spawn (\w+)/);
return { ok: false, error: '内核启动检查失败:' + (code ? code[0] : message.split('\n')[0]).slice(0, 500) + '。可以继续使用系统 Chrome / Edge,或更换自定义内核。' };
return { ok: false, error: '内核启动检查失败:' + (code ? code[0] : message.split('\n')[0]).slice(0, 500) + '。可以重新下载内核后再试。' };
} finally { await browser.close(); resolveIn(root, path.relative(root, directory)); try { fs.rmSync(directory, { recursive: true, force: true }); } catch {} }
}
export async function extractKernel(archive, dir) {
if (archive.endsWith('.zip')) return extractZip(archive, { dir });
const tar = await import('tar'); let bytes = 0, entries = 0;
const tar = await import('tar'); let bytes = 0, entries = 0, problem = ''; const links = [];
// tar 的 filter 抛错会冒成未捕获异常(旧实现会直接带栈退出);这里跳过该条目并留到解压后统一报错。
await tar.x({ file: archive, cwd: dir, strict: true, preservePaths: false, filter(name, entry) {
resolveIn(dir, name);
if (++entries > 100000 || (bytes += entry.size || 0) > 2 * MAX || entry.size > 512e6) throw new Error('内核解压超过限制');
if (!['File', 'Directory', 'OldFile'].includes(entry.type)) throw new Error('内核包含链接或特殊文件');
return true;
if (problem) return false;
try {
resolveIn(dir, name);
if (++entries > 100000 || (bytes += entry.size || 0) > 2 * MAX || entry.size > 512e6) { problem = '内核解压超过限制'; return false; }
// macOS 的 .app 必须保留框架内部的相对符号链接;只接受解码后仍落在目录内的链接,
// 解压完成后再用 realpath 复核一次,防止链式链接逃逸。
if (entry.type === 'SymbolicLink') {
const target = String(entry.linkpath || '');
if (!target || path.isAbsolute(target)) { problem = '内核包含指向目录外的链接'; return false; }
resolveIn(dir, path.join(path.dirname(name), target));
links.push(name);
return true;
}
if (!['File', 'Directory', 'OldFile'].includes(entry.type)) { problem = '内核包含链接或特殊文件'; return false; }
return true;
} catch (error) { problem = error.message; return false; }
} });
if (problem) throw new Error(problem);
if (!links.length) return;
const root = fs.realpathSync(dir);
for (const name of links) {
let resolved;
try { resolved = fs.realpathSync(path.resolve(dir, name)); } catch { throw new Error('内核链接无法解析:' + name); }
if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new Error('内核链接指向目录外:' + name);
}
}
function findExecutable(dir, requested) {
if (requested) { const f = resolveIn(dir, requested); if (!fs.statSync(f).isFile()) throw new Error('指定的浏览器程序不存在'); return f; }
Expand All @@ -74,15 +104,29 @@ function findExecutable(dir, requested) {
if (!files.length) throw new Error('压缩包内未找到 Chromium 程序,请指定包内可执行文件路径');
return resolveIn(dir, files[0]);
}
// 官方把不同平台的构建分散在多个 Release(新版本可能只发布 Linux/Windows)。按新到旧找到第一个
// 真正含当前平台文件的版本,避免 macOS 停留在最新 Release 的 Linux/Windows 包上直接失败。
export function selectRelease(releases, options = {}) {
for (const candidate of releases) {
const asset = matchAsset(candidate, options);
if (asset) return { release: candidate, asset };
}
if (options.asset) throw new Error('未找到 Release 文件:' + options.asset);
const names = [...new Set(releases.flatMap(r => archiveAssets(r).map(a => a.name)))];
throw new Error(names.length
? '没有找到支持当前系统的内核文件,请指定 Release 文件名。可选:' + names.join(', ')
: '没有找到可下载的浏览器 Release,请填写版本标签');
}
export async function downloadGithub(userData, options = {}, progress = () => {}, fetcher = fetch) {
await requireNormalHost();
const repository = repositoryName(options.repository), cloak = repository.toLowerCase() === 'cloakhq/cloakbrowser', kind = cloak ? 'cloak' : 'github';
progress({ phase: 'metadata', source: 'GitHub', got: 0, total: 0 });
const api = 'https://api.github.com/repos/' + repository + '/releases';
const data = JSON.parse((await small(api + (options.tag ? '/tags/' + encodeURIComponent(options.tag) : '?per_page=30'), fetcher)).toString());
const release = Array.isArray(data) ? data.find(r => !r.draft && !r.prerelease && (!cloak || /^chromium-v/.test(r.tag_name)) && (r.assets || []).some(a => /\.(zip|tar\.gz)$/.test(a.name))) : data;
if (!release?.tag_name) throw new Error('没有找到可下载的浏览器 Release,请填写版本标签');
const asset = chooseAsset(release, options);
const list = Array.isArray(data)
? data.filter(r => !r.draft && !r.prerelease && (!cloak || /^chromium-v/.test(String(r.tag_name))))
: [data];
const { release, asset } = selectRelease(list, options);
const url = String(asset.browser_download_url || '');
if (!url.toLowerCase().startsWith(('https://github.com/' + repository + '/releases/download/').toLowerCase())) throw new Error('只接受该仓库的 GitHub Release 下载地址');
let expected = options.sha256 || String(asset.digest || '').replace(/^sha256:/, ''), signed = false;
Expand Down
5 changes: 4 additions & 1 deletion src/service.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class WebRuntime {
needChrome: true,
error:
config.kernel === 'cloak'
? 'CloakBrowser 尚未安装。运行 wdh kernel install cloak,或选择系统 Chrome / Edge。'
? 'CloakBrowser 尚未安装。运行 wdh kernel install cloak,或在桌面插件页下载内核。'
: '所选浏览器未安装或路径无效。',
};
await this.mcp.stop();
Expand All @@ -74,6 +74,7 @@ export class WebRuntime {
projectDir: this.dataDir,
proxy: config.proxy,
embed: this.desktop && config.embed,
dock: this.desktop && config.dock,
});
if (config.antiDebug) {
this.browser.injector.antiDebug = true;
Expand Down Expand Up @@ -180,6 +181,8 @@ export class WebRuntime {
};
case 'launch':
return this.launch(args);
case 'dock':
return this.browser.dockWindow(args);
case 'close':
await this.mcp.stop();
await this.browser.close();
Expand Down
43 changes: 43 additions & 0 deletions test/kernels-extract.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// 内核解压:macOS .app 需要保留内部相对链接,但不能让链接逃出解压目录。
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as tar from 'tar';
import { extractKernel } from '../src/kernels.mjs';

const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'wdh-kernel-'));

async function pack(work, entries) {
const src = path.join(work, 'src'), archive = path.join(work, 'kernel.tar.gz');
fs.mkdirSync(src, { recursive: true });
await tar.c({ gzip: true, file: archive, cwd: src }, entries);
const out = path.join(work, 'out'); fs.mkdirSync(out);
return { archive, out, src };
}

test('extractKernel: 保留 .app 内部的相对符号链接', async () => {
const work = tmp(), src = path.join(work, 'src');
fs.mkdirSync(path.join(src, 'Chromium.app/Contents/MacOS'), { recursive: true });
fs.writeFileSync(path.join(src, 'Chromium.app/Contents/MacOS/Chromium'), 'bin');
fs.symlinkSync('MacOS', path.join(src, 'Chromium.app/Contents/Current'));
const archive = path.join(work, 'kernel.tar.gz');
await tar.c({ gzip: true, file: archive, cwd: src }, ['Chromium.app']);
const out = path.join(work, 'out'); fs.mkdirSync(out);
await extractKernel(archive, out);
assert.equal(fs.readFileSync(path.join(out, 'Chromium.app/Contents/Current/Chromium'), 'utf8'), 'bin');
});

test('extractKernel: 拒绝绝对路径和越界的符号链接', async () => {
for (const [name, target] of [['abs', '/etc/passwd'], ['up', '../../etc'], ['sub/up', '../../../tmp']]) {
const work = tmp(), src = path.join(work, 'src');
fs.mkdirSync(path.dirname(path.join(src, name)), { recursive: true });
fs.writeFileSync(path.join(src, 'a.txt'), 'x');
fs.symlinkSync(target, path.join(src, name));
const archive = path.join(work, 'kernel.tar.gz');
await tar.c({ gzip: true, file: archive, cwd: src }, [...new Set(['a.txt', name.split('/')[0]])]);
const out = path.join(work, 'out'); fs.mkdirSync(out);
await assert.rejects(extractKernel(archive, out), /内核包含指向目录外的链接|内核链接指向目录外|内核链接无法解析|路径越界/, name + ' -> ' + target);
}
});
40 changes: 40 additions & 0 deletions test/kernels-release.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// 内核 Release 选择:官方把不同平台的构建放在不同 Release,必须按平台找到真正可用的那一个。
import test from 'node:test';
import assert from 'node:assert/strict';
import { matchAsset, selectRelease } from '../src/kernels.mjs';

const asset = (name) => ({ name, browser_download_url: 'https://github.com/CloakHQ/cloakbrowser/releases/download/t/' + name, size: 1 });
const release = (tag, names) => ({ tag_name: tag, assets: names.map(asset) });

const newest = release('chromium-v155.0.8059.39.2-pro', []); // 只有 SHA256SUMS,无平台包
const linuxOnly = release('chromium-v146.0.7680.177.5', ['cloakbrowser-linux-x64.tar.gz', 'cloakbrowser-windows-x64.zip']);
const mac = release('chromium-v145.0.7632.109.2', ['cloakbrowser-darwin-arm64.tar.gz', 'cloakbrowser-darwin-x64.tar.gz', 'cloakbrowser-linux-x64.tar.gz']);

test('selectRelease: macOS arm64 跳过只有 Linux/Windows 的新版本', () => {
const { release: picked, asset: file } = selectRelease([newest, linuxOnly, mac], { platform: 'darwin', arch: 'arm64' });
assert.equal(picked.tag_name, mac.tag_name);
assert.equal(file.name, 'cloakbrowser-darwin-arm64.tar.gz');
});

test('selectRelease: Windows 命中最新且有平台包的版本', () => {
const { release: picked, asset: file } = selectRelease([newest, linuxOnly, mac], { platform: 'win32', arch: 'x64' });
assert.equal(picked.tag_name, linuxOnly.tag_name);
assert.equal(file.name, 'cloakbrowser-windows-x64.zip');
});

test('selectRelease: 指定文件名时只在该文件存在的 Release 上生效', () => {
const { release: picked } = selectRelease([newest, linuxOnly, mac], { asset: 'cloakbrowser-darwin-x64.tar.gz' });
assert.equal(picked.tag_name, mac.tag_name);
assert.throws(() => selectRelease([newest, linuxOnly], { asset: 'cloakbrowser-darwin-x64.tar.gz' }), /未找到 Release 文件/);
});

test('selectRelease: 没有平台匹配时列出可选文件名,而不是抛平台错误', () => {
assert.throws(() => selectRelease([linuxOnly], { platform: 'darwin', arch: 'arm64' }), /没有找到支持当前系统的内核文件.*cloakbrowser-windows-x64\.zip/);
assert.throws(() => selectRelease([newest], { platform: 'darwin', arch: 'arm64' }), /没有找到可下载的浏览器 Release/);
});

test('matchAsset: 同名平台包在同一个 Release 中不唯一时返回 null', () => {
const ambiguous = release('chromium-v1', ['cloakbrowser-linux-x64.tar.gz', 'cloakbrowser-linux-x64-legacy.tar.gz']);
assert.equal(matchAsset(ambiguous, { platform: 'linux', arch: 'x64' }), null);
assert.equal(matchAsset(ambiguous, { asset: 'cloakbrowser-linux-x64.tar.gz' }).name, 'cloakbrowser-linux-x64.tar.gz');
});
Loading