@seekskyworld/open-browser 0.0.0-stage → 0.2.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.
- package/CONTRIBUTING.md +15 -0
- package/Docs/Agent/346/265/217/350/247/210/345/231/250/346/200/273/344/275/223/346/236/266/346/236/204.md +58 -0
- package/Docs/THIRD-PARTY-NOTICES.md +12 -0
- package/Docs/open-browser-api.d.ts +291 -0
- package/Docs/open-browser/344/273/273/345/212/241/350/257/204/346/265/213/346/214/207/345/215/227.md +59 -0
- package/Docs/open-browser/351/232/220/347/247/201/344/270/216/345/274/200/346/272/220/345/256/241/350/256/241.md +37 -0
- package/Docs//346/216/247/345/210/266/345/217/260/345/210/206/347/273/204/344/270/216/346/216/245/347/256/241/346/226/271/346/241/210.md +31 -0
- package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +84 -0
- package/LICENSE +200 -0
- package/README.md +159 -2
- package/README.zh-CN.md +166 -0
- package/SECURITY.md +9 -0
- package/access-registry.mjs +156 -0
- package/action-execution.mjs +385 -0
- package/activity-notifier.mjs +34 -0
- package/api-contract.mjs +134 -0
- package/browser-extension/icons/open-browser-128.png +0 -0
- package/browser-extension/icons/open-browser-16.png +0 -0
- package/browser-extension/icons/open-browser-32.png +0 -0
- package/browser-extension/icons/open-browser-48.png +0 -0
- package/browser-extension/icons/open-browser-wordmark.png +0 -0
- package/browser-extension/manifest.json +35 -0
- package/browser-extension/newtab.css +26 -0
- package/browser-extension/newtab.html +19 -0
- package/browser-extension/newtab.js +174 -0
- package/browser-extension/phase-labels.js +9 -0
- package/browser-extension/popup.css +19 -0
- package/browser-extension/popup.html +56 -0
- package/browser-extension/popup.js +405 -0
- package/browser-extension/tab-action.js +138 -0
- package/browser-extension/worker.js +281 -0
- package/browser-extension/workspace-title.js +15 -0
- package/build-profile.mjs +23 -0
- package/capability-matrix.mjs +21 -0
- package/chromium-host.mjs +209 -0
- package/chromium-shell.mjs +179 -0
- package/cli.mjs +141 -0
- package/contract-validation.mjs +27 -0
- package/control.mjs +107 -0
- package/desktop/Info.plist +13 -0
- package/desktop/Launcher.m +117 -0
- package/desktop/OBControlBar.h +7 -0
- package/desktop/OBControlBar.m +217 -0
- package/desktop/OBPageView.h +6 -0
- package/desktop/OBPageView.m +348 -0
- package/desktop/WorkspacePanel.h +16 -0
- package/desktop/WorkspacePanel.m +916 -0
- package/desktop/archive-release.py +129 -0
- package/desktop/brand-keychain.py +111 -0
- package/desktop/brand-locales.py +93 -0
- package/desktop/brand-macos-icons.py +24 -0
- package/desktop/brand-windows-icons.mjs +48 -0
- package/desktop/build-macos.mjs +112 -0
- package/desktop/build-managed-input.mjs +37 -0
- package/desktop/build-portable.mjs +95 -0
- package/desktop/build-profile.mjs +6 -0
- package/desktop/build.mjs +13 -0
- package/desktop/create-shortcut.ps1 +9 -0
- package/desktop/generate-icons.py +39 -0
- package/desktop/icons/open-browser.icns +0 -0
- package/desktop/icons/open-browser.ico +0 -0
- package/desktop/install-menu-entry.mjs +24 -0
- package/desktop/macos-entitlements.plist +12 -0
- package/desktop/notarize-macos.mjs +145 -0
- package/desktop/package-assets.mjs +34 -0
- package/desktop/package-macos.mjs +54 -0
- package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
- package/desktop/patches/chromium-managed-input.patch +144 -0
- package/desktop/portable-archive.py +22 -0
- package/desktop/sign.mjs +77 -0
- package/desktop/smoke-portable.mjs +65 -0
- package/desktop/start-profile.mjs +5 -0
- package/desktop/start.mjs +34 -0
- package/desktop/verify-macos-release.mjs +61 -0
- package/desktop/verify-upgrade.mjs +74 -0
- package/desktop/verify-version.mjs +12 -0
- package/desktop-page.mjs +211 -0
- package/diagnostics.mjs +37 -0
- package/downloads.mjs +110 -0
- package/engine-service.mjs +1158 -0
- package/hosted/README.md +74 -0
- package/hosted/cli.mjs +17 -0
- package/hosted/directory.mjs +261 -0
- package/hosted/init.mjs +37 -0
- package/hosted/server.mjs +129 -0
- package/managed-input.mjs +138 -0
- package/managed-popup.mjs +54 -0
- package/mcp-http.mjs +84 -0
- package/mcp-server.mjs +41 -0
- package/mcp.mjs +5 -0
- package/network-policy.mjs +107 -0
- package/output-store.mjs +96 -0
- package/package.json +77 -4
- package/page-activity.mjs +188 -0
- package/page-dialogs.mjs +53 -0
- package/page-observation.mjs +318 -0
- package/paths.mjs +22 -0
- package/privacy-config.mjs +95 -0
- package/receipt-store.mjs +198 -0
- package/runtime.mjs +53 -0
- package/scheduler.mjs +70 -0
- package/sdk.mjs +193 -0
- package/service.mjs +290 -0
- package/site-workflow.mjs +115 -0
- package/skill-links.mjs +90 -0
- package/skills/open-browser/SKILL.macos.md +112 -0
- package/skills/open-browser/SKILL.md +107 -0
- package/skills/open-browser/SKILL.windows.md +112 -0
- package/skills/open-browser/scripts/bootstrap.mjs +213 -0
- package/skills/open-browser/scripts/open-browser +21 -0
- package/skills/open-browser/scripts/open-browser.cmd +9 -0
- package/skills/open-browser/workflows/login-export.json +10 -0
- package/skills/open-browser/workflows/upload-verify.json +8 -0
- package/studio/demo-site.mjs +111 -0
- package/studio/demo.css +1 -0
- package/studio/index.html +66 -0
- package/studio/index.mjs +57 -0
- package/studio/native-demo.mjs +124 -0
- package/studio/studio.css +119 -0
- package/studio/studio.js +438 -0
- package/tab-adoption.mjs +77 -0
- package/uploads.mjs +63 -0
- package/visual-page.mjs +306 -0
- package/workspace-lifecycle.mjs +238 -0
- package/workspace-state.mjs +107 -0
package/hosted/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# open-browser 托管工作节点
|
|
2
|
+
|
|
3
|
+
一个协调进程管理会话、节点选择、写租约和提交回执。工作节点通过现有 open-browser 服务启动专用无头 Chromium,每个工作区获得独立的 BrowserContext。桌面版与个人资料目录另行运行。本目录是可独立启动的 Unix 托管入口。
|
|
4
|
+
|
|
5
|
+
## 在一台机器上启动两个节点
|
|
6
|
+
|
|
7
|
+
在仓库根目录使用支持 `node:sqlite` 的 Node.js(本机验证版本 26.4),先安装项目依赖及项目专用 Chromium。以下命令初始化一个新目录。初始化器拒绝覆盖已有配置。
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm ci
|
|
11
|
+
npm run browser:install
|
|
12
|
+
export OPEN_BROWSER_HOSTED_DIR="$HOME/.open-browser/hosted"
|
|
13
|
+
node hosted/init.mjs "$OPEN_BROWSER_HOSTED_DIR"
|
|
14
|
+
OPEN_BROWSER_PROFILE=default OPEN_BROWSER_STATE_DIR="$OPEN_BROWSER_HOSTED_DIR/node-a" node service.mjs --headless &
|
|
15
|
+
worker_a=$!
|
|
16
|
+
OPEN_BROWSER_PROFILE=default OPEN_BROWSER_STATE_DIR="$OPEN_BROWSER_HOSTED_DIR/node-b" node service.mjs --headless &
|
|
17
|
+
worker_b=$!
|
|
18
|
+
node hosted/server.mjs "$OPEN_BROWSER_HOSTED_DIR" &
|
|
19
|
+
coordinator=$!
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
默认配置为两个租户各分配一个节点。如果一个租户允许使用多个节点,在相应节点的 `tenants` 数组加入该租户 ID,再重启协调器。创建会话时选择可用节点中会话数最少者,节点编号用于打破平局。已创建的会话固定在所选节点。
|
|
23
|
+
|
|
24
|
+
每个节点都使用专用 service 模式。协调器的输入是 `config.json` 中的 Unix socket 和节点令牌文件,示例使用同机的两个独立服务进程。多主机部署需要为每个节点提供经过认证的私有通道,并安全同步节点每次启动时轮换的令牌。此次验收覆盖同机双进程。单个 SQLite 协调目录支持一个活动协调器,数据库文件应置于本机文件系统。
|
|
25
|
+
|
|
26
|
+
## 使用租户 CLI
|
|
27
|
+
|
|
28
|
+
租户身份取自 Bearer 凭证。管理令牌、工作节点令牌和其他租户的令牌只由服务操作方保管。本机示例由同一操作系统用户运行,租户隔离在 API 层验证。生产客户端需要独立的系统账号或容器和经过访问控制的接入通道,以免客户端直接读取服务端目录中的密钥。
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
export OPEN_BROWSER_HOSTED_TOKEN_FILE="$OPEN_BROWSER_HOSTED_DIR/tenant-a.token"
|
|
32
|
+
node hosted/cli.mjs nodes
|
|
33
|
+
printf '%s\n' '{"sessionId":"demo","allowedOrigins":["https://example.org"]}' | node hosted/cli.mjs create
|
|
34
|
+
printf '%s\n' '{"sessionId":"demo"}' | node hosted/cli.mjs acquire
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
最后一个命令返回 `lease` 和毫秒时间戳 `expires`。将其返回的令牌代入以下输入。所有节点健康及操作回执都可用相同形式从 SDK 读取,协议为 HTTP POST 到 Unix socket 的 `/v1/call`,正文使用 `{"method":"…","params":{…}}`。CLI 采用同一 SDK 传输函数。
|
|
38
|
+
|
|
39
|
+
| 方法 | JSON 输入示例或说明 |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `nodes`、`sessions` | `{}`,列出本租户获准节点或会话 |
|
|
42
|
+
| `status`、`acquire` | `{"sessionId":"demo"}` |
|
|
43
|
+
| `renew`、`release` | `{"sessionId":"demo","lease":"…"}` |
|
|
44
|
+
| `openPage` | `{"sessionId":"demo","lease":"…","operationId":"p1","params":{"url":"https://example.org/"}}` |
|
|
45
|
+
| `observe` | `{"sessionId":"demo","lease":"…","pageId":"打开页回执中的 pageId"}`,可传 `name`、`limit`、`region`、`includeFrames` 或 `frameControls`。续读时仅附上 `cursor`。 |
|
|
46
|
+
| `act` | `{"sessionId":"demo","lease":"…","operationId":"a1","params":{"pageId":"…","documentId":"…","controlGeneration":"…","actions":[{"kind":"click","ref":"观察返回的 ref"}]}}` |
|
|
47
|
+
| `receipt` | `{"sessionId":"demo","operationId":"a1"}`,允许原持有者断线后按会话和操作 ID 核实 |
|
|
48
|
+
| `closeWorkspace` | `{"sessionId":"demo","lease":"…","operationId":"end"}` |
|
|
49
|
+
| `finishWorkspace` | `{"sessionId":"demo","lease":"…","operationId":"end","params":{"keepPageIds":[]}}`,交付已完成任务并关闭无头工作区 |
|
|
50
|
+
|
|
51
|
+
每个会话同时授予一份 30 秒写租约。观察会生成新的页面元素引用,因此也携带当前租约。持有者可续租,有未完成的写操作时继续查询回执,再释放或申请租约。操作号可在同一会话重用以查询同一请求。不同动作使用新的操作号。协调器重启后应重新申请租约。
|
|
52
|
+
|
|
53
|
+
协调器 SQLite 记录租户编号、会话和页面编号、节点、状态、操作类型、带密钥的请求摘要及核实决定。请在编号中使用随机或业务无关的值。页面正文经显式 `observe` 返回给已认证租户,协调器不将观察正文、动作参数、站点 Cookie 或截图写入该库。登录态留在节点的浏览器上下文,节点重启后需重新登录。工作节点另外保存原有的本地回执。
|
|
54
|
+
|
|
55
|
+
## 失联与人工核实
|
|
56
|
+
|
|
57
|
+
协调器每 750 毫秒并发探测各节点的授权能力接口,单次探测期限为 2 秒。失联或节点实例更换会使原会话进入 `review` 并撤销租约。已派发的操作固定在原节点,协调器不会在恢复时自动重发。协调器启动时,创建中或仍有操作待决的会话也会进入核实流程。
|
|
58
|
+
|
|
59
|
+
1. 恢复原节点的服务及状态目录,以便读取其本地回执。
|
|
60
|
+
2. 管理员从同一 CLI 调用 `review`,对照站点自身的订单、表单或其他结果。节点回执表示浏览器的执行进展,站点记录决定业务提交结果。
|
|
61
|
+
3. 以 `applied`、`not_applied` 或 `unknown` 记录人工判定。协调器先回收仍存活的工作区,再归档会话。若建工作区期间失联而不知道其标识,需要重启原节点以回收孤立上下文。后续任务使用新的会话编号。
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
export OPEN_BROWSER_HOSTED_TOKEN_FILE="$OPEN_BROWSER_HOSTED_DIR/admin.token"
|
|
65
|
+
printf '%s\n' '{"tenant":"tenant-a","sessionId":"demo"}' | node hosted/cli.mjs review
|
|
66
|
+
# 核对站点确认已经提交后执行
|
|
67
|
+
printf '%s\n' '{"tenant":"tenant-a","sessionId":"demo","decision":"applied"}' | node hosted/cli.mjs review
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
关闭手动启动的实例可执行 `kill "$coordinator" "$worker_a" "$worker_b"`。下次启动复用现有目录并从启动节点的命令开始。
|
|
71
|
+
|
|
72
|
+
## 真实故障演练
|
|
73
|
+
|
|
74
|
+
从仓库根目录执行 `node --test hosted/hosted.test.mjs`。测试在独立临时目录启动两个 Chromium 工作节点、协调器和自有 HTTP 站点。两个账号通过一次性登录票据获得 HttpOnly 会话。站点记录一次提交并延迟 HTTP 响应,测试随即强杀对应节点。另一个节点继续以自己的身份浏览。重启原节点后,管理员读取节点回执,对照站点提交次数并归档。测试还检查租约互斥、旧租约失效、跨租户回执隔离、协调器重启及本地元数据中无明文登录票据。结束后清理自建实例。
|
package/hosted/cli.mjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { localRequest } from '../sdk.mjs';
|
|
3
|
+
|
|
4
|
+
try {
|
|
5
|
+
const method = process.argv[2];
|
|
6
|
+
const home = process.env.OPEN_BROWSER_HOSTED_DIR;
|
|
7
|
+
const token = process.env.OPEN_BROWSER_HOSTED_TOKEN_FILE;
|
|
8
|
+
if (!method || !home || !token) throw new Error('请设置 OPEN_BROWSER_HOSTED_DIR 和 OPEN_BROWSER_HOSTED_TOKEN_FILE,然后指定方法。');
|
|
9
|
+
let input = '';
|
|
10
|
+
if (!process.stdin.isTTY) {
|
|
11
|
+
process.stdin.setEncoding('utf8');
|
|
12
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
13
|
+
}
|
|
14
|
+
const endpoint = method === 'review' ? '/v1/admin' : '/v1/call';
|
|
15
|
+
const result = await localRequest(path.join(home, 'control.sock'), token, endpoint, method, JSON.parse(input.trim() || '{}'));
|
|
16
|
+
console.log(JSON.stringify(result));
|
|
17
|
+
} catch (error) { console.error(error.code || error.message); process.exitCode = 1; }
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { request } from 'node:http';
|
|
5
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
6
|
+
import { OpenBrowserClient } from '../sdk.mjs';
|
|
7
|
+
|
|
8
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
9
|
+
const opaque = () => randomBytes(32).toString('hex');
|
|
10
|
+
const active = new Set(['queued','running']);
|
|
11
|
+
const terminal = new Set(['completed','failed','cancelled','outcome_unknown']);
|
|
12
|
+
const strings = /^[a-zA-Z0-9_-]{1,80}$/;
|
|
13
|
+
const rejectedBeforeDispatch = new Set(['invalid_params', 'invalid_url', 'invalid_actions', 'stale_control', 'stale_document',
|
|
14
|
+
'origin_denied', 'page_not_found', 'queue_full', 'operation_limit', 'workspace_under_user_control']);
|
|
15
|
+
const sessionKey = (tenant, sessionId) => hash(JSON.stringify([tenant, sessionId]));
|
|
16
|
+
const writeMethods = new Set(['openPage','act','finishWorkspace','closeWorkspace']);
|
|
17
|
+
function fail(code) { throw Object.assign(new Error(code), {code}); }
|
|
18
|
+
|
|
19
|
+
export class Directory {
|
|
20
|
+
constructor(home, config, digestKey) {
|
|
21
|
+
this.digestKey = digestKey;
|
|
22
|
+
this.db = new DatabaseSync(path.join(home,'directory.sqlite'));
|
|
23
|
+
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
|
|
24
|
+
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, public_id TEXT NOT NULL, tenant TEXT, node TEXT, incarnation TEXT,
|
|
25
|
+
workspace TEXT, create_digest TEXT, state TEXT NOT NULL, lease TEXT, expires INTEGER DEFAULT 0, pending TEXT, decision TEXT);
|
|
26
|
+
CREATE TABLE IF NOT EXISTS ops (session TEXT, id TEXT, method TEXT, digest TEXT, status TEXT, page TEXT,
|
|
27
|
+
PRIMARY KEY(session,id));`);
|
|
28
|
+
this.nodes = new Map();
|
|
29
|
+
for (const {id, socketPath, tokenPath, tenants} of config.nodes) {
|
|
30
|
+
if (!strings.test(id) || this.nodes.has(id) || !Array.isArray(tenants) || !tenants.length ||
|
|
31
|
+
tenants.some(t=>!strings.test(t)) || !path.isAbsolute(socketPath) || !path.isAbsolute(tokenPath))
|
|
32
|
+
fail('invalid_node_config');
|
|
33
|
+
this.nodes.set(id,{id, socketPath, tokenPath, tenants:new Set(tenants), api:new OpenBrowserClient({socketPath,tokenPath}), healthy:false});
|
|
34
|
+
}
|
|
35
|
+
this.db.exec("UPDATE sessions SET lease=NULL, expires=0; UPDATE sessions SET state='review' WHERE state='creating' OR (state='live' AND pending IS NOT NULL)");
|
|
36
|
+
this.stopped = false;
|
|
37
|
+
this.inFlight = new Set();
|
|
38
|
+
this.timer = setInterval(()=>{ void this.probeAll(); },750).unref();
|
|
39
|
+
}
|
|
40
|
+
one(sql,...args) { return this.db.prepare(sql).get(...args); }
|
|
41
|
+
change(sql,...args) { return this.db.prepare(sql).run(...args); }
|
|
42
|
+
async probe(node) {
|
|
43
|
+
if (node.probing || this.stopped) return;
|
|
44
|
+
node.probing = true;
|
|
45
|
+
let identity;
|
|
46
|
+
try {
|
|
47
|
+
const token = (await readFile(node.tokenPath, 'utf8')).trim();
|
|
48
|
+
if (!/^[0-9a-f]{64}$/.test(token)) fail('invalid_node_token');
|
|
49
|
+
await new Promise((resolve, reject) => {
|
|
50
|
+
const req = request({ socketPath: node.socketPath, method: 'POST', path: '/v1/call',
|
|
51
|
+
signal: AbortSignal.timeout(2000), headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }
|
|
52
|
+
}, res => {
|
|
53
|
+
res.on('error', reject);
|
|
54
|
+
res.on('end', () => res.statusCode === 200 ? resolve() : reject(new Error('health_check_failed')));
|
|
55
|
+
res.resume();
|
|
56
|
+
});
|
|
57
|
+
req.once('error', reject);
|
|
58
|
+
req.end(JSON.stringify({ method: 'capabilities', params: {} }));
|
|
59
|
+
});
|
|
60
|
+
identity = hash(token);
|
|
61
|
+
} catch { identity = null; }
|
|
62
|
+
finally { node.probing = false; }
|
|
63
|
+
if (this.stopped) return;
|
|
64
|
+
node.healthy = !!identity;
|
|
65
|
+
node.sampled = Date.now();
|
|
66
|
+
node.incarnation = identity;
|
|
67
|
+
this.change("UPDATE sessions SET state='review',lease=NULL,expires=0 WHERE node=? AND state IN ('live','creating') AND (incarnation!=? OR ? IS NULL)",
|
|
68
|
+
node.id, identity, identity);
|
|
69
|
+
}
|
|
70
|
+
probeAll() { return Promise.all([...this.nodes.values()].map(node => this.probe(node))); }
|
|
71
|
+
digest(value) { return createHmac('sha256', this.digestKey).update(JSON.stringify(value)).digest('hex'); }
|
|
72
|
+
healthy(node) { return node?.healthy && Date.now()-node.sampled < 5000; }
|
|
73
|
+
row(tenant,id) {
|
|
74
|
+
const row = this.one('SELECT * FROM sessions WHERE id=? AND tenant=?',id,tenant);
|
|
75
|
+
if (!row) fail('session_not_found');
|
|
76
|
+
return row;
|
|
77
|
+
}
|
|
78
|
+
view(row) {
|
|
79
|
+
return {sessionId:row.public_id,node:row.node,state:row.state,pendingOperationId:row.pending,
|
|
80
|
+
leaseExpiresAt:row.expires || null,decision:row.decision};
|
|
81
|
+
}
|
|
82
|
+
lock(row,token) {
|
|
83
|
+
if (row.state!=='live') fail(row.state==='review'?'review_required':'session_inactive');
|
|
84
|
+
if (typeof token!=='string' || row.lease!==hash(token) || row.expires<=Date.now()) fail('invalid_lease');
|
|
85
|
+
}
|
|
86
|
+
async create(tenant,{sessionId,allowedOrigins,resourceOrigins,name,agentName}) {
|
|
87
|
+
if (typeof sessionId!=='string' || !strings.test(sessionId)) fail('invalid_session_id');
|
|
88
|
+
if (typeof name !== 'string' || !name.trim()) fail('task_name_required');
|
|
89
|
+
const id = sessionKey(tenant, sessionId);
|
|
90
|
+
const existing=this.one('SELECT * FROM sessions WHERE id=?',id);
|
|
91
|
+
const digest = this.digest([allowedOrigins, resourceOrigins, name, agentName]);
|
|
92
|
+
if (existing) {
|
|
93
|
+
const own = this.row(tenant, id);
|
|
94
|
+
if (own.create_digest !== digest) fail('session_id_conflict');
|
|
95
|
+
return this.view(own);
|
|
96
|
+
}
|
|
97
|
+
const load = this.db.prepare("SELECT node,count(*) AS count FROM sessions WHERE state IN ('creating','live','review') GROUP BY node").all();
|
|
98
|
+
const counts = new Map(load.map(entry => [entry.node, entry.count]));
|
|
99
|
+
const candidates = [...this.nodes.values()].filter(node => this.healthy(node) && node.tenants.has(tenant));
|
|
100
|
+
candidates.sort((a, b) => (counts.get(a.id) || 0) - (counts.get(b.id) || 0) || a.id.localeCompare(b.id));
|
|
101
|
+
const node = candidates[0];
|
|
102
|
+
if (!node) fail('node_unavailable');
|
|
103
|
+
this.change("INSERT INTO sessions(id,public_id,tenant,node,incarnation,create_digest,state) VALUES(?,?,?,?,?,?,'creating')",id,sessionId,tenant,node.id,node.incarnation,digest);
|
|
104
|
+
this.inFlight.add(id);
|
|
105
|
+
try {
|
|
106
|
+
const ws=await node.api.createWorkspace({allowedOrigins,resourceOrigins,name,agentName});
|
|
107
|
+
this.change("UPDATE sessions SET workspace=?,state=CASE WHEN state='creating' THEN 'live' ELSE state END WHERE id=?",ws.workspaceId,id);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (['invalid_params', 'invalid_url', 'workspace_limit', 'task_name_required'].includes(error.code)) {
|
|
110
|
+
this.change("DELETE FROM sessions WHERE id=? AND state='creating'", id);
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
this.change("UPDATE sessions SET state='review' WHERE id=?", id);
|
|
114
|
+
} finally { this.inFlight.delete(id); }
|
|
115
|
+
return this.view(this.row(tenant,id));
|
|
116
|
+
}
|
|
117
|
+
async request(tenant,method,args) {
|
|
118
|
+
if(!args || typeof args!=='object' || Array.isArray(args)) fail('invalid_params');
|
|
119
|
+
if(method==='nodes') return [...this.nodes.values()].filter(n=>n.tenants.has(tenant)).map(n=>({id:n.id,healthy:!!this.healthy(n)}));
|
|
120
|
+
if(method==='sessions') return this.db.prepare('SELECT * FROM sessions WHERE tenant=? ORDER BY public_id').all(tenant).map(r=>this.view(r));
|
|
121
|
+
if(method==='create') return this.create(tenant,args);
|
|
122
|
+
if(typeof args.sessionId!=='string') fail('invalid_session_id');
|
|
123
|
+
const row=this.row(tenant,sessionKey(tenant,args.sessionId)), node=this.nodes.get(row.node);
|
|
124
|
+
if(method==='status') return this.view(row);
|
|
125
|
+
if(method==='receipt') return this.receipt(row,args.operationId);
|
|
126
|
+
if (row.state === 'review') fail('review_required');
|
|
127
|
+
if (!node?.tenants.has(tenant)) fail('node_unavailable');
|
|
128
|
+
if(!this.healthy(node)) fail('node_unavailable');
|
|
129
|
+
if(method==='acquire') {
|
|
130
|
+
if(row.state!=='live') fail('review_required');
|
|
131
|
+
if(row.pending || row.lease && row.expires>Date.now()) fail('lease_busy');
|
|
132
|
+
const token=opaque(), expires=Date.now()+30_000;
|
|
133
|
+
this.change('UPDATE sessions SET lease=?,expires=? WHERE id=?',hash(token),expires,row.id);
|
|
134
|
+
return {lease:token,expires};
|
|
135
|
+
}
|
|
136
|
+
this.lock(row,args.lease);
|
|
137
|
+
if(method==='renew') {
|
|
138
|
+
const expires=Date.now()+30_000;
|
|
139
|
+
this.change('UPDATE sessions SET expires=? WHERE id=?',expires,row.id);
|
|
140
|
+
return {expires};
|
|
141
|
+
}
|
|
142
|
+
if(method==='release') {
|
|
143
|
+
if(row.pending || this.inFlight.has(row.id)) fail('operation_pending');
|
|
144
|
+
this.change('UPDATE sessions SET lease=NULL,expires=0 WHERE id=?',row.id);
|
|
145
|
+
return {released:true};
|
|
146
|
+
}
|
|
147
|
+
if(method==='observe') {
|
|
148
|
+
const {cursor, name, limit, region, includeFrames, frameControls} = args;
|
|
149
|
+
const result=await node.api.observe({workspaceId:row.workspace,pageId:args.pageId,
|
|
150
|
+
cursor,name,limit,region,includeFrames,frameControls});
|
|
151
|
+
this.lock(this.row(tenant,row.id),args.lease);
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
if(!writeMethods.has(method)) fail('unknown_method');
|
|
155
|
+
const {operationId,params={}}=args;
|
|
156
|
+
if(typeof operationId!=='string'||!strings.test(operationId)||!params||typeof params!=='object'||Array.isArray(params)) fail('invalid_params');
|
|
157
|
+
if (method === 'finishWorkspace' && (!Array.isArray(params.keepPageIds) || params.keepPageIds.length)) fail('hosted_keep_unavailable');
|
|
158
|
+
const digest=this.digest([method,params]);
|
|
159
|
+
const old=this.one('SELECT * FROM ops WHERE session=? AND id=?',row.id,operationId);
|
|
160
|
+
if(old) {
|
|
161
|
+
if(old.digest!==digest) fail('operation_id_conflict');
|
|
162
|
+
return this.receipt(row,operationId);
|
|
163
|
+
}
|
|
164
|
+
if(row.pending || this.inFlight.has(row.id)) fail('operation_pending');
|
|
165
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
166
|
+
try {
|
|
167
|
+
this.change("INSERT INTO ops VALUES(?,?,?,?,'dispatched',NULL)",row.id,operationId,method,digest);
|
|
168
|
+
this.change('UPDATE sessions SET pending=? WHERE id=?',operationId,row.id);
|
|
169
|
+
this.db.exec('COMMIT');
|
|
170
|
+
} catch(error) { this.db.exec('ROLLBACK');throw error; }
|
|
171
|
+
this.inFlight.add(row.id);
|
|
172
|
+
try {
|
|
173
|
+
// Preserve the engine's stable invalid_actions error for an empty batch.
|
|
174
|
+
// The hosted envelope normally validates page metadata first, so provide
|
|
175
|
+
// inert identifiers only for this pre-dispatch validation case.
|
|
176
|
+
const forwarded = method === 'act' && Array.isArray(params.actions) && !params.actions.length
|
|
177
|
+
? {...params, pageId: params.pageId || 'invalid', documentId: params.documentId || 'invalid',
|
|
178
|
+
controlGeneration: params.controlGeneration || 'invalid'}
|
|
179
|
+
: params;
|
|
180
|
+
const result=await node.api.call(method,{...forwarded,workspaceId:row.workspace,
|
|
181
|
+
...(['act','finishWorkspace'].includes(method) && {operationId})});
|
|
182
|
+
const current=this.row(tenant,row.id);
|
|
183
|
+
if(current.state!=='live') return this.receipt(current,operationId);
|
|
184
|
+
const state=result.state || 'completed';
|
|
185
|
+
if(active.has(state)) {
|
|
186
|
+
this.change('UPDATE ops SET status=? WHERE session=? AND id=?',state,row.id,operationId);
|
|
187
|
+
} else {
|
|
188
|
+
this.settle(row,operationId,method,state,result.pageId);
|
|
189
|
+
}
|
|
190
|
+
return this.receipt(this.row(tenant,row.id),operationId);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
if (rejectedBeforeDispatch.has(error.code) && this.row(tenant,row.id).state === 'live') {
|
|
193
|
+
this.settle(row,operationId,method,'failed');
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
this.change("UPDATE sessions SET state='review',lease=NULL,expires=0 WHERE id=?",row.id);
|
|
197
|
+
return this.receipt(this.row(tenant,row.id),operationId);
|
|
198
|
+
} finally { this.inFlight.delete(row.id); }
|
|
199
|
+
}
|
|
200
|
+
settle(row,id,method,status,page) {
|
|
201
|
+
if(!terminal.has(status)) fail('invalid_receipt');
|
|
202
|
+
const next=status==='outcome_unknown'?'review':
|
|
203
|
+
status==='completed'&&['closeWorkspace','finishWorkspace'].includes(method)?'closed':'live';
|
|
204
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
205
|
+
try {
|
|
206
|
+
this.change('UPDATE ops SET status=?,page=? WHERE session=? AND id=?',status,page||null,row.id,id);
|
|
207
|
+
this.change("UPDATE sessions SET state=?,pending=?,lease=CASE WHEN ?='live' THEN lease ELSE NULL END,expires=CASE WHEN ?='live' THEN expires ELSE 0 END WHERE id=? AND state='live' AND pending=?",
|
|
208
|
+
next,next==='review'?id:null,next,next,row.id,id);
|
|
209
|
+
this.db.exec('COMMIT');
|
|
210
|
+
} catch(error) {this.db.exec('ROLLBACK');throw error;}
|
|
211
|
+
}
|
|
212
|
+
async receipt(row,id) {
|
|
213
|
+
if(typeof id!=='string') fail('invalid_operation_id');
|
|
214
|
+
const op=this.one('SELECT * FROM ops WHERE session=? AND id=?',row.id,id);
|
|
215
|
+
if(!op) fail('operation_not_found');
|
|
216
|
+
const node=this.nodes.get(row.node);
|
|
217
|
+
if(row.state==='live' && active.has(op.status) && this.healthy(node)) {
|
|
218
|
+
try {
|
|
219
|
+
const value=await node.api.getOperation(row.workspace,id);
|
|
220
|
+
if(terminal.has(value.state) && this.row(row.tenant,row.id).state==='live')
|
|
221
|
+
this.settle(row,id,op.method,value.state);
|
|
222
|
+
op.status=value.state;
|
|
223
|
+
} catch {
|
|
224
|
+
this.change("UPDATE sessions SET state='review',lease=NULL,expires=0 WHERE id=? AND pending=?",row.id,id);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const current = this.row(row.tenant,row.id);
|
|
228
|
+
const needsReview = current.pending === id && current.state === 'review';
|
|
229
|
+
const verified = current.pending === id && current.state === 'archived';
|
|
230
|
+
return {operationId:id, state:verified ? current.decision : needsReview ? 'review_required' : op.status,
|
|
231
|
+
pageId:op.page || undefined, session:this.view(current)};
|
|
232
|
+
}
|
|
233
|
+
async review({tenant,sessionId,decision}) {
|
|
234
|
+
if(typeof tenant!=='string'||typeof sessionId!=='string') fail('invalid_params');
|
|
235
|
+
const id = sessionKey(tenant, sessionId);
|
|
236
|
+
const row=this.row(tenant,id), node=this.nodes.get(row.node);
|
|
237
|
+
if(row.state!=='review' || this.inFlight.has(row.id)) fail('review_unavailable');
|
|
238
|
+
if(!decision) {
|
|
239
|
+
let nodeReceipt;
|
|
240
|
+
if(row.workspace && row.pending && this.healthy(node)) {
|
|
241
|
+
try {
|
|
242
|
+
const result=await node.api.getOperation(row.workspace,row.pending);
|
|
243
|
+
nodeReceipt={state:result.state,completedSteps:result.completedSteps};
|
|
244
|
+
} catch { /* Unavailable receipt leaves the review pending. */ }
|
|
245
|
+
}
|
|
246
|
+
return {session:this.view(row),workspaceId:row.workspace,nodeReceipt};
|
|
247
|
+
}
|
|
248
|
+
if(!['applied','not_applied','unknown'].includes(decision)) fail('invalid_decision');
|
|
249
|
+
if(!this.healthy(node)) fail('verify_node_before_archiving');
|
|
250
|
+
// Quiesce any surviving workspace before allowing a fresh session. A new
|
|
251
|
+
// worker has lost the old context; an application-level absence is expected.
|
|
252
|
+
if (!row.workspace && node.incarnation === row.incarnation) fail('restart_node_to_retire_unknown_workspace');
|
|
253
|
+
if(row.workspace) {
|
|
254
|
+
try { await node.api.closeWorkspace(row.workspace); }
|
|
255
|
+
catch(error) { if(error.code!=='workspace_not_found') throw error; }
|
|
256
|
+
}
|
|
257
|
+
this.change("UPDATE sessions SET state='archived',lease=NULL,expires=0,decision=? WHERE id=? AND state='review'",decision,row.id);
|
|
258
|
+
return this.view(this.row(tenant,row.id));
|
|
259
|
+
}
|
|
260
|
+
close() {this.stopped=true; clearInterval(this.timer); this.db.close();}
|
|
261
|
+
}
|
package/hosted/init.mjs
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
|
|
6
|
+
export async function initialize(directory) {
|
|
7
|
+
const home = path.resolve(directory);
|
|
8
|
+
if (Buffer.byteLength(path.join(home, 'node-a/open-browser.sock')) >= 100)
|
|
9
|
+
throw new Error('请选择较短的托管数据目录,以容纳 Unix socket 路径。');
|
|
10
|
+
await mkdir(path.dirname(home), { recursive: true });
|
|
11
|
+
await mkdir(home, { mode: 0o700 });
|
|
12
|
+
const token = async name => {
|
|
13
|
+
const file = path.join(home, name + '.token');
|
|
14
|
+
await writeFile(file, randomBytes(32).toString('hex') + '\n', { flag: 'wx', mode: 0o600 });
|
|
15
|
+
return file;
|
|
16
|
+
};
|
|
17
|
+
const adminTokenFile = await token('admin');
|
|
18
|
+
const digestKeyFile = await token('request-digest');
|
|
19
|
+
const tenants = [];
|
|
20
|
+
const nodes = [];
|
|
21
|
+
for (const suffix of ['a', 'b']) {
|
|
22
|
+
const tenant = 'tenant-' + suffix;
|
|
23
|
+
const id = 'node-' + suffix;
|
|
24
|
+
const state = path.join(home, id);
|
|
25
|
+
tenants.push({ id: tenant, tokenFile: await token(tenant) });
|
|
26
|
+
nodes.push({ id, tenants: [tenant], socketPath: path.join(state, 'open-browser.sock'),
|
|
27
|
+
tokenPath: path.join(state, 'open-browser.token') });
|
|
28
|
+
}
|
|
29
|
+
await writeFile(path.join(home, 'config.json'), JSON.stringify({ adminTokenFile, digestKeyFile, tenants, nodes }, null, 2) + '\n',
|
|
30
|
+
{ flag: 'wx', mode: 0o600 });
|
|
31
|
+
return home;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
35
|
+
try { console.log(await initialize(process.argv[2] || process.env.OPEN_BROWSER_HOSTED_DIR)); }
|
|
36
|
+
catch (error) { console.error(error.message); process.exitCode = 1; }
|
|
37
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { chmod, lstat, readFile, unlink } from 'node:fs/promises';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { Directory } from './directory.mjs';
|
|
9
|
+
|
|
10
|
+
async function credentials(config) {
|
|
11
|
+
const entries = [];
|
|
12
|
+
async function add(id, file) {
|
|
13
|
+
const token = (await readFile(file, 'utf8')).trim();
|
|
14
|
+
if (!/^[a-f0-9]{64}$/.test(token)) throw new Error('invalid_token_config');
|
|
15
|
+
const key = Buffer.from('Bearer ' + token);
|
|
16
|
+
if (entries.some(entry => entry.id === id || timingSafeEqual(entry.key, key))) throw new Error('duplicate_principal');
|
|
17
|
+
entries.push({id, key});
|
|
18
|
+
}
|
|
19
|
+
await add(null, config.adminTokenFile);
|
|
20
|
+
for (const {id, tokenFile} of config.tenants) {
|
|
21
|
+
if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{1,80}$/.test(id)) throw new Error('invalid_tenant');
|
|
22
|
+
await add(id, tokenFile);
|
|
23
|
+
}
|
|
24
|
+
if (!config.nodes.length || config.nodes.some(n => n.tenants.some(id => !entries.some(e => e.id === id))))
|
|
25
|
+
throw new Error('invalid_node_tenants');
|
|
26
|
+
return entries;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function reply(res, status, body) {
|
|
30
|
+
res.writeHead(status, {'content-type':'application/json', 'cache-control':'no-store'});
|
|
31
|
+
res.end(JSON.stringify(body));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function bind(server, socket) {
|
|
35
|
+
const info = await lstat(socket).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
36
|
+
if (info) {
|
|
37
|
+
if (!info.isSocket()) throw new Error('invalid_socket_path');
|
|
38
|
+
const live = await new Promise((resolve, reject) => {
|
|
39
|
+
const probe = net.connect(socket);
|
|
40
|
+
probe.once('connect', () => { probe.end(); resolve(true); });
|
|
41
|
+
probe.once('error', err => err.code === 'ECONNREFUSED' ? resolve(false) : reject(err));
|
|
42
|
+
});
|
|
43
|
+
if (live) throw new Error('coordinator_already_running');
|
|
44
|
+
await unlink(socket);
|
|
45
|
+
}
|
|
46
|
+
await new Promise((resolve, reject) => {
|
|
47
|
+
server.once('error', reject);
|
|
48
|
+
server.listen(socket, () => { server.removeListener('error', reject); resolve(); });
|
|
49
|
+
});
|
|
50
|
+
await chmod(socket, 0o600);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function startCoordinator(directory) {
|
|
54
|
+
const home = path.resolve(directory);
|
|
55
|
+
const info = await lstat(home);
|
|
56
|
+
if (!info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o077))
|
|
57
|
+
throw new Error('private_directory_required');
|
|
58
|
+
const config = JSON.parse(await readFile(path.join(home, 'config.json'), 'utf8'));
|
|
59
|
+
const principals = await credentials(config);
|
|
60
|
+
const digestKey = (await readFile(config.digestKeyFile, 'utf8')).trim();
|
|
61
|
+
if (!/^[0-9a-f]{64}$/.test(digestKey)) throw new Error('invalid_digest_key');
|
|
62
|
+
// The OS releases this exclusive database lock if the coordinator process dies.
|
|
63
|
+
const lock = new DatabaseSync(path.join(home, 'coordinator.lock.sqlite'), { timeout:0 });
|
|
64
|
+
let directoryAPI, server, closing = false;
|
|
65
|
+
const pending = new Set();
|
|
66
|
+
try {
|
|
67
|
+
lock.exec('BEGIN EXCLUSIVE');
|
|
68
|
+
server = http.createServer({ requestTimeout:20_000, headersTimeout:10_000 }, async (req, res) => {
|
|
69
|
+
const fail = (status, code) => reply(res, status, {error:{code}});
|
|
70
|
+
const admin = req.url === '/v1/admin';
|
|
71
|
+
if (req.method !== 'POST' || (!admin && req.url !== '/v1/call')) return fail(404, 'not_found');
|
|
72
|
+
const presented = Buffer.from(req.headers.authorization || '');
|
|
73
|
+
const principal = principals.find(({key}) => key.length === presented.length && timingSafeEqual(key, presented));
|
|
74
|
+
if (req.headers.origin !== undefined || !principal || admin !== (principal.id === null)) return fail(403, 'forbidden');
|
|
75
|
+
if (closing || !directoryAPI) return fail(503, 'not_ready');
|
|
76
|
+
try {
|
|
77
|
+
let size = 0;
|
|
78
|
+
const chunks = [];
|
|
79
|
+
for await (const chunk of req) {
|
|
80
|
+
size += chunk.length;
|
|
81
|
+
if (size > 256 * 1024) return fail(413, 'request_too_large');
|
|
82
|
+
chunks.push(chunk);
|
|
83
|
+
}
|
|
84
|
+
const frame = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
85
|
+
if (typeof frame?.method !== 'string') return fail(400, 'invalid_request');
|
|
86
|
+
const args = frame.params ?? {};
|
|
87
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) return fail(400, 'invalid_params');
|
|
88
|
+
if (admin && frame.method !== 'review') return fail(400, 'unknown_method');
|
|
89
|
+
if (closing) return fail(503, 'not_ready');
|
|
90
|
+
const call = admin ? directoryAPI.review(args) : directoryAPI.request(principal.id, frame.method, args);
|
|
91
|
+
pending.add(call);
|
|
92
|
+
try { reply(res, 200, {result:await call}); }
|
|
93
|
+
finally { pending.delete(call); }
|
|
94
|
+
} catch (error) {
|
|
95
|
+
const code = typeof error.code === 'string' && /^[a-z_]{1,64}$/i.test(error.code) ? error.code : 'invalid_request';
|
|
96
|
+
fail(400, code);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
await bind(server, path.join(home, 'control.sock'));
|
|
100
|
+
directoryAPI = new Directory(home, config, Buffer.from(digestKey, 'hex'));
|
|
101
|
+
await directoryAPI.probeAll();
|
|
102
|
+
let closed;
|
|
103
|
+
return {close() {
|
|
104
|
+
if (!closed) {
|
|
105
|
+
closing = true;
|
|
106
|
+
closed = (async () => {
|
|
107
|
+
await new Promise(resolve => server.close(resolve));
|
|
108
|
+
await Promise.allSettled([...pending]);
|
|
109
|
+
directoryAPI.close();
|
|
110
|
+
lock.close();
|
|
111
|
+
})();
|
|
112
|
+
}
|
|
113
|
+
return closed;
|
|
114
|
+
}};
|
|
115
|
+
} catch (error) {
|
|
116
|
+
if (server?.listening) await new Promise(resolve => server.close(resolve));
|
|
117
|
+
directoryAPI?.close();
|
|
118
|
+
lock.close();
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
124
|
+
try {
|
|
125
|
+
const coordinator = await startCoordinator(process.argv[2] || process.env.OPEN_BROWSER_HOSTED_DIR);
|
|
126
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { void coordinator.close(); });
|
|
127
|
+
console.log('open-browser hosted ready');
|
|
128
|
+
} catch (error) { console.error(error.message); process.exitCode = 1; }
|
|
129
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { ServiceError } from './workspace-state.mjs';
|
|
2
|
+
|
|
3
|
+
// The preferred guard is implemented inside Chromium. A stock Chromium build
|
|
4
|
+
// uses a page-level capture fallback, which blocks page input while allowing
|
|
5
|
+
// the service to open a short dispatch window for one Agent action. The
|
|
6
|
+
// fallback avoids keeping a CDP session attached after native support has been
|
|
7
|
+
// ruled out because the extension also uses chrome.debugger.
|
|
8
|
+
const fallbackSource = `(() => {
|
|
9
|
+
const key = '__openBrowserInputGuard';
|
|
10
|
+
const current = globalThis[key];
|
|
11
|
+
if (current) { current.enabled = true; return; }
|
|
12
|
+
const state = { enabled: true };
|
|
13
|
+
const block = event => {
|
|
14
|
+
if (!state.enabled) return;
|
|
15
|
+
event.preventDefault();
|
|
16
|
+
event.stopImmediatePropagation();
|
|
17
|
+
};
|
|
18
|
+
for (const type of ['click','dblclick','mousedown','mouseup','mousemove','mouseenter','mouseleave',
|
|
19
|
+
'pointerdown','pointerup','pointermove','pointercancel','wheel','touchstart','touchmove','touchend',
|
|
20
|
+
'contextmenu','keydown','keypress','keyup','beforeinput','input','change'])
|
|
21
|
+
document.addEventListener(type, block, true);
|
|
22
|
+
globalThis[key] = state;
|
|
23
|
+
})();`;
|
|
24
|
+
|
|
25
|
+
function fallbackExpression(enabled) {
|
|
26
|
+
return `globalThis.__openBrowserInputGuard && (globalThis.__openBrowserInputGuard.enabled = ${enabled ? 'true' : 'false'})`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function setFallbackState(page, enabled) {
|
|
30
|
+
await page.evaluate(fallbackExpression(enabled)).catch(() => {});
|
|
31
|
+
// Init scripts cannot be removed from a Playwright page. Append a small
|
|
32
|
+
// state update so a later navigation preserves the handoff decision.
|
|
33
|
+
await page.addInitScript({ content: fallbackExpression(enabled) }).catch(() => {});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function managedInput(context, onBlocked, { allowFallback = false, forceFallback = false } = {}) {
|
|
37
|
+
const sessions = new WeakMap();
|
|
38
|
+
const disconnectedSessions = new WeakSet();
|
|
39
|
+
|
|
40
|
+
async function setGuard(tab, enabled, onLost) {
|
|
41
|
+
const { page } = tab;
|
|
42
|
+
let entry = sessions.get(page);
|
|
43
|
+
if (page.isClosed()) return;
|
|
44
|
+
if (!enabled) {
|
|
45
|
+
if (!entry) return;
|
|
46
|
+
if (entry.mode === 'fallback') {
|
|
47
|
+
await setFallbackState(page, false);
|
|
48
|
+
sessions.delete(page);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
try { await entry.session.send('Input.setOpenBrowserInputGuard', { enabled: false }); }
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (!page.isClosed() && !disconnectedSessions.has(entry.session)) throw error;
|
|
54
|
+
}
|
|
55
|
+
sessions.delete(page);
|
|
56
|
+
try { await entry.session.detach(); }
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (!page.isClosed() && !disconnectedSessions.has(entry.session)) {
|
|
59
|
+
sessions.set(page, entry);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (entry) return;
|
|
66
|
+
if (forceFallback && allowFallback) {
|
|
67
|
+
try {
|
|
68
|
+
await page.addInitScript({ content: fallbackSource });
|
|
69
|
+
await page.evaluate(fallbackSource);
|
|
70
|
+
entry = { mode: 'fallback', depth: 0, transition: Promise.resolve() };
|
|
71
|
+
sessions.set(page, entry);
|
|
72
|
+
} catch (cause) {
|
|
73
|
+
if (!page.isClosed()) throw Object.assign(new ServiceError('input_guard_unavailable'), { cause });
|
|
74
|
+
}
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const session = await context.newCDPSession(page);
|
|
78
|
+
entry = { session, mode: 'native', depth: 0, transition: Promise.resolve() };
|
|
79
|
+
try {
|
|
80
|
+
session.once('close', () => {
|
|
81
|
+
disconnectedSessions.add(session);
|
|
82
|
+
if (sessions.get(page) !== entry) return;
|
|
83
|
+
sessions.delete(page);
|
|
84
|
+
if (!page.isClosed()) onLost?.();
|
|
85
|
+
});
|
|
86
|
+
session.on('Input.openBrowserInputBlocked', () => {
|
|
87
|
+
if (sessions.get(page) === entry) onBlocked(tab);
|
|
88
|
+
});
|
|
89
|
+
let timer;
|
|
90
|
+
try {
|
|
91
|
+
await Promise.race([
|
|
92
|
+
session.send('Input.setOpenBrowserInputGuard', { enabled: true }),
|
|
93
|
+
new Promise((_, reject) => {
|
|
94
|
+
timer = setTimeout(() => reject(Error('Input guard acknowledgement timed out')), 5000);
|
|
95
|
+
}),
|
|
96
|
+
]);
|
|
97
|
+
} finally { clearTimeout(timer); }
|
|
98
|
+
if (disconnectedSessions.has(session)) throw Error('input guard session closed');
|
|
99
|
+
sessions.set(page, entry);
|
|
100
|
+
} catch (cause) {
|
|
101
|
+
const unsupported = /wasn.t found|not found|unknown command/i.test(String(cause?.message));
|
|
102
|
+
await session.detach().catch(() => {});
|
|
103
|
+
if (!allowFallback || !unsupported) {
|
|
104
|
+
if (!page.isClosed()) throw Object.assign(new ServiceError('input_guard_unavailable'), { cause });
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
await page.addInitScript({ content: fallbackSource });
|
|
109
|
+
await page.evaluate(fallbackSource);
|
|
110
|
+
entry = { mode: 'fallback', depth: 0, transition: Promise.resolve() };
|
|
111
|
+
sessions.set(page, entry);
|
|
112
|
+
} catch (fallbackCause) {
|
|
113
|
+
if (!page.isClosed()) throw Object.assign(new ServiceError('input_guard_unavailable'), { cause: fallbackCause });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
setGuard.withAgentInput = async (tab, work) => {
|
|
119
|
+
const entry = sessions.get(tab.page);
|
|
120
|
+
if (!entry || entry.mode !== 'fallback') return work();
|
|
121
|
+
entry.depth++;
|
|
122
|
+
if (entry.depth === 1) {
|
|
123
|
+
entry.transition = entry.transition.then(() => setFallbackState(tab.page, false));
|
|
124
|
+
await entry.transition;
|
|
125
|
+
}
|
|
126
|
+
try { return await work(); }
|
|
127
|
+
finally {
|
|
128
|
+
entry.depth--;
|
|
129
|
+
if (entry.depth === 0) {
|
|
130
|
+
entry.transition = entry.transition.then(() => setFallbackState(tab.page, true));
|
|
131
|
+
await entry.transition.catch(() => {});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
setGuard.mode = tab => sessions.get(tab.page)?.mode || null;
|
|
137
|
+
return setGuard;
|
|
138
|
+
}
|