@seekskyworld/open-browser 0.0.0-stage → 0.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 (109) hide show
  1. package/CONTRIBUTING.md +15 -0
  2. 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
  3. package/Docs/THIRD-PARTY-NOTICES.md +12 -0
  4. package/Docs/open-browser-api.d.ts +273 -0
  5. 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
  6. 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
  7. 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
  8. 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 +36 -0
  9. package/LICENSE +200 -0
  10. package/README.md +150 -2
  11. package/README.zh-CN.md +155 -0
  12. package/SECURITY.md +9 -0
  13. package/access-registry.mjs +151 -0
  14. package/action-execution.mjs +374 -0
  15. package/activity-notifier.mjs +34 -0
  16. package/api-contract.mjs +122 -0
  17. package/browser-extension/icons/open-browser-128.png +0 -0
  18. package/browser-extension/icons/open-browser-16.png +0 -0
  19. package/browser-extension/icons/open-browser-32.png +0 -0
  20. package/browser-extension/icons/open-browser-48.png +0 -0
  21. package/browser-extension/icons/open-browser-wordmark.png +0 -0
  22. package/browser-extension/manifest.json +38 -0
  23. package/browser-extension/newtab.css +20 -0
  24. package/browser-extension/newtab.html +19 -0
  25. package/browser-extension/newtab.js +123 -0
  26. package/browser-extension/phase-labels.js +9 -0
  27. package/browser-extension/popup.css +19 -0
  28. package/browser-extension/popup.html +46 -0
  29. package/browser-extension/popup.js +324 -0
  30. package/browser-extension/tab-action.js +137 -0
  31. package/browser-extension/worker.js +188 -0
  32. package/browser-extension/workspace-title.js +15 -0
  33. package/capability-matrix.mjs +21 -0
  34. package/chromium-host.mjs +149 -0
  35. package/chromium-shell.mjs +150 -0
  36. package/cli.mjs +83 -0
  37. package/contract-validation.mjs +27 -0
  38. package/control.mjs +107 -0
  39. package/desktop/Info.plist +13 -0
  40. package/desktop/Launcher.m +117 -0
  41. package/desktop/OBControlBar.h +7 -0
  42. package/desktop/OBControlBar.m +213 -0
  43. package/desktop/OBPageView.h +6 -0
  44. package/desktop/OBPageView.m +348 -0
  45. package/desktop/WorkspacePanel.h +16 -0
  46. package/desktop/WorkspacePanel.m +915 -0
  47. package/desktop/archive-release.py +129 -0
  48. package/desktop/brand-keychain.py +95 -0
  49. package/desktop/brand-locales.py +93 -0
  50. package/desktop/brand-macos-icons.py +24 -0
  51. package/desktop/brand-windows-icons.mjs +48 -0
  52. package/desktop/build-macos.mjs +96 -0
  53. package/desktop/build-portable.mjs +95 -0
  54. package/desktop/build.mjs +5 -0
  55. package/desktop/create-shortcut.ps1 +9 -0
  56. package/desktop/generate-icons.py +39 -0
  57. package/desktop/icons/open-browser.icns +0 -0
  58. package/desktop/icons/open-browser.ico +0 -0
  59. package/desktop/install-menu-entry.mjs +24 -0
  60. package/desktop/package-assets.mjs +34 -0
  61. package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
  62. package/desktop/portable-archive.py +22 -0
  63. package/desktop/sign.mjs +33 -0
  64. package/desktop/smoke-portable.mjs +65 -0
  65. package/desktop/start.mjs +12 -0
  66. package/desktop/verify-upgrade.mjs +74 -0
  67. package/desktop/verify-version.mjs +12 -0
  68. package/desktop-page.mjs +211 -0
  69. package/diagnostics.mjs +28 -0
  70. package/downloads.mjs +110 -0
  71. package/engine-service.mjs +1002 -0
  72. package/hosted/README.md +74 -0
  73. package/hosted/cli.mjs +17 -0
  74. package/hosted/directory.mjs +261 -0
  75. package/hosted/init.mjs +37 -0
  76. package/hosted/server.mjs +129 -0
  77. package/managed-popup.mjs +54 -0
  78. package/mcp.mjs +43 -0
  79. package/network-policy.mjs +107 -0
  80. package/output-store.mjs +96 -0
  81. package/package.json +57 -4
  82. package/page-activity.mjs +121 -0
  83. package/page-dialogs.mjs +53 -0
  84. package/page-observation.mjs +280 -0
  85. package/paths.mjs +20 -0
  86. package/privacy-config.mjs +95 -0
  87. package/receipt-store.mjs +191 -0
  88. package/runtime.mjs +44 -0
  89. package/scheduler.mjs +70 -0
  90. package/sdk.mjs +176 -0
  91. package/service.mjs +271 -0
  92. package/site-workflow.mjs +115 -0
  93. package/skills/open-browser/SKILL.md +86 -0
  94. package/skills/open-browser/scripts/bootstrap.mjs +134 -0
  95. package/skills/open-browser/scripts/open-browser +21 -0
  96. package/skills/open-browser/scripts/open-browser.cmd +9 -0
  97. package/skills/open-browser/workflows/login-export.json +10 -0
  98. package/skills/open-browser/workflows/upload-verify.json +8 -0
  99. package/studio/demo-site.mjs +111 -0
  100. package/studio/demo.css +1 -0
  101. package/studio/index.html +66 -0
  102. package/studio/index.mjs +57 -0
  103. package/studio/native-demo.mjs +124 -0
  104. package/studio/studio.css +119 -0
  105. package/studio/studio.js +438 -0
  106. package/uploads.mjs +63 -0
  107. package/visual-page.mjs +306 -0
  108. package/workspace-lifecycle.mjs +170 -0
  109. package/workspace-state.mjs +95 -0
@@ -0,0 +1,438 @@
1
+ 'use strict';
2
+ const $ = id => document.getElementById(id);
3
+ const state = { access: '', config: {}, workspaces: [], workspace: '', page: '', detail: null, demoRetry: null, demoOperations: new Set(), refreshId: 0, entered: false };
4
+ const active = () => state.workspaces.find(w => w.workspaceId === state.workspace);
5
+ const currentPage = () => active()?.pages.find(p => p.pageId === state.page);
6
+ const timestamp = () => new Date().toLocaleTimeString('zh-CN', { hour12: false });
7
+ const labels = { agent: 'Agent 控制', human: '用户控制', transferring: '交接中' };
8
+ const groups = [
9
+ { id: 'attention', title: '待处理' }, { id: 'running', title: 'Agent 运行' },
10
+ { id: 'human', title: '人工接管' }, { id: 'idle', title: '待命' },
11
+ ];
12
+ const phases = { idle: '等待指令', queued: '已排队', running: '执行中', needs_credential: '等待凭据',
13
+ completed: '已完成', failed: '执行失败', cancelled: '已取消', outcome_unknown: '结果待核对' };
14
+ const kinds = { openPage: '打开页面', observe: '观察页面', act: '页面操作' };
15
+ const stepKinds = { click: '点击', fill: '填写', fillCredential: '填写凭据' };
16
+ const errorText = {
17
+ credential_required: '请补充缺少的凭据', wrong_password: '站点拒绝了账号或密码,请更新后再试。',
18
+ pairing_failed: '管理入口已使用,请从 open-browser 重新打开控制台。',
19
+ unauthorized: '管理入口已失效,请重新打开控制台。',
20
+ origin_not_allowed: '新页面超出了当前工作区授权站点,请另建工作区。',
21
+ login_form_changed: '登录表单已变化,请读取页面后再试。',
22
+ human_control: '当前为用户控制,请先交回 Agent。',
23
+ };
24
+
25
+ async function post(route, payload) {
26
+ const headers = { 'Content-Type': 'application/json' };
27
+ if (state.access) headers.Authorization = 'Bearer ' + state.access;
28
+ const response = await fetch(route, { method: 'POST', headers, body: JSON.stringify(payload) });
29
+ const data = await response.json();
30
+ if (!response.ok) throw new Error(data.error || 'request_failed');
31
+ return data;
32
+ }
33
+ async function call(method, params = {}) {
34
+ return (await post('/call', { method, params })).result;
35
+ }
36
+ function log(message) {
37
+ const list = $('activity');
38
+ list.querySelector('.empty')?.remove();
39
+ const row = document.createElement('li');
40
+ const time = document.createElement('time');
41
+ time.textContent = timestamp();
42
+ row.append(time, document.createTextNode(message));
43
+ list.prepend(row);
44
+ while (list.children.length > 20) list.lastElementChild.remove();
45
+ $('activity-count').textContent = list.children.length + ' 条';
46
+ }
47
+ function notify(message) {
48
+ $('notice').textContent = message;
49
+ $('notice').hidden = !message;
50
+ }
51
+ function clearObservation() {
52
+ $('snapshot').textContent = '暂无观察结果';
53
+ $('observed-at').textContent = '';
54
+ }
55
+ function choose(workspaceId) {
56
+ state.workspace = workspaceId;
57
+ state.page = '';
58
+ state.detail = null;
59
+ state.entered = true;
60
+ state.refreshId++;
61
+ sessionStorage.setItem('open-browser.selection', workspaceId);
62
+ clearSensitiveInputs();
63
+ clearObservation();
64
+ notify('');
65
+ paint();
66
+ }
67
+ function clearSensitiveInputs() {
68
+ $('password').value = '';
69
+ $('bind-value').value = '';
70
+ $('credential-settings').open = false;
71
+ $('demo-secret').textContent = '';
72
+ $('demo-details').open = false;
73
+ $('reveal').textContent = '显示密码';
74
+ }
75
+ function groupOf(w) {
76
+ if (w.mode === 'human' || w.mode === 'transferring') return 'human';
77
+ const a = w.activity || {};
78
+ if (a.needsCredential || a.phase === 'failed' || a.phase === 'outcome_unknown') return 'attention';
79
+ if (a.current || a.queued || a.phase === 'running' || a.phase === 'queued') return 'running';
80
+ return 'idle';
81
+ }
82
+ function describe(operation) {
83
+ if (!operation) return '';
84
+ const kind = kinds[operation.kind] || '操作';
85
+ const status = operation.error === 'credential_required' ? '缺少凭据' :
86
+ phases[operation.state] || operation.state;
87
+ if (operation.state === 'running' && operation.stepKind) {
88
+ return stepKinds[operation.stepKind] + ' · ' + operation.completedSteps + '/' + operation.totalSteps;
89
+ }
90
+ return [kind, status].filter(Boolean).join(' · ');
91
+ }
92
+ function shortState(w) {
93
+ if (w.mode !== 'agent') return labels[w.mode];
94
+ const a = w.activity || {};
95
+ if (a.needsCredential) return '等待凭据';
96
+ return describe(a.current) || phases[a.phase] || '等待指令';
97
+ }
98
+ function paintRail() {
99
+ const byGroup = new Map(groups.map(g => [g.id, []]));
100
+ for (const w of state.workspaces) byGroup.get(groupOf(w)).push(w);
101
+ const view = groups.map(g => ({ ...g, items: byGroup.get(g.id).map(w => ({
102
+ id: w.workspaceId, name: w.name || '工作区', status: shortState(w),
103
+ pages: w.pages.length, selected: w.workspaceId === state.workspace,
104
+ })) }));
105
+ const rail = $('workspaces');
106
+ const signature = JSON.stringify(view);
107
+ if (rail.dataset.view !== signature) {
108
+ const focused = document.activeElement?.dataset.workspaceId;
109
+ const blocks = view.map(group => {
110
+ const block = document.createElement('div');
111
+ block.className = 'group';
112
+ block.dataset.group = group.id;
113
+ block.dataset.empty = String(!group.items.length);
114
+ block.setAttribute('role', 'group');
115
+ block.setAttribute('aria-label', group.title);
116
+ const header = document.createElement('div');
117
+ header.className = 'group-header';
118
+ const title = document.createElement('h3');
119
+ title.textContent = group.title;
120
+ const count = document.createElement('span');
121
+ count.className = 'group-total';
122
+ count.textContent = group.items.length;
123
+ header.append(title, count);
124
+ block.append(header);
125
+ for (const row of group.items) {
126
+ const item = document.createElement('button');
127
+ item.type = 'button';
128
+ item.className = row.selected ? 'ws active' : 'ws';
129
+ item.dataset.workspaceId = row.id;
130
+ if (row.selected) item.setAttribute('aria-current', 'true');
131
+ const name = document.createElement('b');
132
+ name.textContent = row.name;
133
+ const status = document.createElement('small');
134
+ status.textContent = row.status + ' · ' + row.pages + ' 页';
135
+ item.append(name, status);
136
+ item.onclick = () => { if (state.workspace !== row.id) { choose(row.id); sync(); } };
137
+ block.append(item);
138
+ }
139
+ return block;
140
+ });
141
+ rail.replaceChildren(...blocks);
142
+ rail.dataset.view = signature;
143
+ if (focused) Array.from(rail.querySelectorAll('button')).find(el => el.dataset.workspaceId === focused)?.focus({ preventScroll: true });
144
+ }
145
+ $('rail-empty').hidden = state.workspaces.length > 0;
146
+ $('count').textContent = state.workspaces.length;
147
+ }
148
+ function credentialRequest() {
149
+ const w = active();
150
+ if (!w || w.mode !== 'agent') return null;
151
+ const request = state.detail?.activity?.credentialRequest;
152
+ if (request) return { ...request, workspaceId: w.workspaceId };
153
+ if (state.demoRetry?.workspaceId === w.workspaceId && w.pages.some(p => p.pageId === state.demoRetry.pageId)) return state.demoRetry;
154
+ return null;
155
+ }
156
+ function paintCredential() {
157
+ const request = credentialRequest();
158
+ const panel = $('credential-view');
159
+ const key = request ? JSON.stringify([request.workspaceId, request.operationId, request.credentialRef]) : '';
160
+ if (panel.dataset.request !== key) $('password').value = '';
161
+ panel.dataset.request = key;
162
+ panel.hidden = !request;
163
+ if (!request) return;
164
+ const demoPassword = request.origin === new URL(state.config.demoUrl).origin && request.credentialRef === 'demo.password';
165
+ const canContinue = state.demoOperations.has(request.operationId);
166
+ $('credential-title').textContent = demoPassword ? '需要补充密码' : '需要补充凭据';
167
+ $('credential-ref').textContent = request.credentialRef;
168
+ $('credential-origin').textContent = request.origin;
169
+ $('credential-label').textContent = demoPassword ? '密码' : '凭据值';
170
+ $('insert-password').hidden = !demoPassword;
171
+ $('submit-credential').textContent = canContinue ? '补充并继续' : '绑定凭据';
172
+ }
173
+ function paint() {
174
+ paintRail();
175
+ const w = active();
176
+ $('new-view').hidden = Boolean(w);
177
+ $('active-view').hidden = !w;
178
+ if (!w) return;
179
+ $('workspace-name').textContent = w.name || '工作区';
180
+ $('wid').title = w.workspaceId;
181
+ $('mode').textContent = labels[w.mode] || w.mode;
182
+ const a = w.activity || {};
183
+ $('work-state').textContent = w.mode === 'human' ? '自动化已暂停' :
184
+ w.mode === 'transferring' ? '正在交接' : a.needsCredential ? '等待补充凭据' :
185
+ describe(a.current) || '等待指令';
186
+ if (w.mode === 'agent' && a.queued > 0) $('work-state').textContent += ' · 排队 ' + a.queued;
187
+ $('result-text').textContent = describe(a.recent) || '暂无已结束操作';
188
+ $('take').hidden = w.mode !== 'agent' || !w.pages.length;
189
+ $('give').hidden = w.mode !== 'human';
190
+ $('view-controlled').hidden = w.mode !== 'human' || !w.pages.length;
191
+ $('page-form').hidden = w.mode !== 'agent';
192
+ $('close-workspace').hidden = w.mode !== 'agent';
193
+ const pages = $('pages');
194
+ const pageOptions = JSON.stringify(w.pages.map(p => [p.pageId, p.origin]));
195
+ if (pages.dataset.options !== pageOptions) {
196
+ pages.replaceChildren(...w.pages.map((page, i) => {
197
+ const option = document.createElement('option');
198
+ option.value = page.pageId;
199
+ option.textContent = (i + 1) + ' · ' + page.origin;
200
+ return option;
201
+ }));
202
+ pages.dataset.options = pageOptions;
203
+ }
204
+ if (!w.pages.some(p => p.pageId === state.page)) {
205
+ const fallback = w.pages.at(-1)?.pageId || '';
206
+ if (state.page !== fallback) clearObservation();
207
+ state.page = fallback;
208
+ }
209
+ if (pages.value !== state.page) pages.value = state.page;
210
+ $('wid').textContent = [currentPage()?.origin, w.pages.length + ' 个页面'].filter(Boolean).join(' · ');
211
+ const isDemo = currentPage()?.origin === new URL(state.config.demoUrl).origin;
212
+ $('login-action').hidden = !isDemo || w.mode !== 'agent';
213
+ $('demo-details').hidden = !isDemo;
214
+ $('credential-settings').hidden = !state.page || w.mode !== 'agent';
215
+ $('observe').hidden = !state.page || w.mode !== 'agent';
216
+ paintCredential();
217
+ if (w.mode !== 'agent') {
218
+ clearObservation();
219
+ clearSensitiveInputs();
220
+ }
221
+ }
222
+ function setConnected(connected) {
223
+ $('connection-status').dataset.connected = String(connected);
224
+ $('connection').textContent = connected ? '本机服务已连接' : '服务已断开';
225
+ }
226
+ async function refresh() {
227
+ const sequence = ++state.refreshId;
228
+ const selected = state.workspace;
229
+ const rows = await call('listWorkspaces');
230
+ if (sequence !== state.refreshId) return;
231
+ const w = rows.find(row => row.workspaceId === selected);
232
+ let detail = null;
233
+ if (w?.activity?.needsCredential) {
234
+ detail = await call('getWorkspace', { workspaceId: selected });
235
+ if (sequence !== state.refreshId) return;
236
+ }
237
+ state.workspaces = rows.map(row => row.workspaceId === detail?.workspaceId ? detail : row);
238
+ state.detail = detail;
239
+ if (selected && !w) choose('');
240
+ else paint();
241
+ setConnected(true);
242
+ }
243
+ async function sync() {
244
+ try { await refresh(); } catch { setConnected(false); }
245
+ }
246
+ function command(id, fn, event = 'click') {
247
+ $(id).addEventListener(event, async e => {
248
+ e.preventDefault();
249
+ const button = event === 'submit' ? e.submitter || $(id).querySelector('button') : $(id);
250
+ if (button.disabled) return;
251
+ button.disabled = true;
252
+ notify('');
253
+ try { await fn(); }
254
+ catch (err) {
255
+ const msg = errorText[err.message] || '操作未完成(' + err.message + ')';
256
+ notify(msg);
257
+ log(msg);
258
+ } finally {
259
+ button.disabled = false;
260
+ await sync();
261
+ }
262
+ });
263
+ }
264
+ async function create(name, url) {
265
+ const { workspaceId } = await call('createWorkspace', { name, allowedOrigins: [new URL(url).origin] });
266
+ let page;
267
+ try { page = await call('openPage', { workspaceId, url }); }
268
+ catch (error) {
269
+ await call('closeWorkspace', { workspaceId }).catch(() => {});
270
+ throw error;
271
+ }
272
+ state.workspaces = await call('listWorkspaces');
273
+ choose(workspaceId);
274
+ state.page = page.pageId;
275
+ paint();
276
+ log('已打开「' + name + '」');
277
+ return { workspaceId, pageId: page.pageId };
278
+ }
279
+ async function observe(page, method = 'observe') {
280
+ const snap = await call(method, page);
281
+ if (state.workspace === page.workspaceId && state.page === page.pageId) {
282
+ $('snapshot').textContent = snap.text || (snap.elements || []).map(e => e.role + ' ' + e.name).join('\n') || '当前页无可见文本';
283
+ $('observed-at').textContent = timestamp();
284
+ }
285
+ return snap;
286
+ }
287
+ async function putCredential(page, credentialRef, value) {
288
+ await call('setCredential', { workspaceId: page.workspaceId, origin: new URL(state.config.demoUrl).origin, credentialRef, value });
289
+ }
290
+ async function runLogin(page) {
291
+ const snap = await observe(page);
292
+ const authenticated = observation => observation.text.includes('我的账号') &&
293
+ observation.elements.some(e => e.role === 'button' && e.name === '退出登录');
294
+ if (authenticated(snap)) {
295
+ state.demoRetry = null;
296
+ log('已读取受保护的账号页面');
297
+ return;
298
+ }
299
+ const find = (role, name) => snap.elements.find(element => element.role === role && element.name === name)?.ref;
300
+ const username = find('textbox', '账号');
301
+ const password = find('textbox', '密码');
302
+ const submit = find('button', '登录');
303
+ if (!username || !password || !submit) throw new Error('login_form_changed');
304
+ const request = {
305
+ workspaceId: page.workspaceId, pageId: page.pageId, documentId: snap.documentId,
306
+ controlGeneration: snap.controlGeneration, operationId: crypto.randomUUID(), actions: [
307
+ { kind: 'fillCredential', ref: username, credentialRef: 'demo.username' },
308
+ { kind: 'fillCredential', ref: password, credentialRef: 'demo.password' },
309
+ { kind: 'click', ref: submit },
310
+ ],
311
+ };
312
+ let receipt = await call('act', request);
313
+ state.demoOperations.add(request.operationId);
314
+ const deadline = Date.now() + 35000;
315
+ while (['running', 'queued'].includes(receipt.state)) {
316
+ if (Date.now() > deadline) throw new Error('operation_pending');
317
+ await new Promise(resolve => setTimeout(resolve, 100));
318
+ receipt = await call('getOperation', { workspaceId: page.workspaceId, operationId: request.operationId });
319
+ }
320
+ if (receipt.error === 'credential_required' && receipt.credentialRef === 'demo.password') {
321
+ log('任务等待补充密码');
322
+ return;
323
+ }
324
+ if (receipt.state !== 'completed') throw new Error(receipt.error || receipt.state);
325
+ const after = await observe(page);
326
+ if (after.text.includes('账号或密码不正确')) {
327
+ state.demoRetry = { ...page, operationId: request.operationId, credentialRef: 'demo.password', origin: new URL(state.config.demoUrl).origin };
328
+ paint();
329
+ throw new Error('wrong_password');
330
+ }
331
+ if (!authenticated(after))
332
+ throw new Error('account_page_unconfirmed');
333
+ state.demoRetry = null;
334
+ log('登录成功,已读取受保护的账号页面');
335
+ }
336
+ async function demo(withPassword) {
337
+ const page = await create(withPassword ? '自动登录' : '凭据补充', state.config.demoUrl);
338
+ await putCredential(page, 'demo.username', state.config.username);
339
+ if (withPassword) await putCredential(page, 'demo.password', (await post('/demo-password', {})).password);
340
+ await runLogin(page);
341
+ }
342
+ function pageHandle() {
343
+ return { workspaceId: state.workspace, pageId: state.page };
344
+ }
345
+
346
+ command('show-new', () => choose(''));
347
+ command('new-form', () => create($('name').value.trim() || '我的工作区', $('url').value), 'submit');
348
+ command('demo', () => demo(true));
349
+ command('missing', () => demo(false));
350
+ command('observe', async () => { await observe(pageHandle(), 'previewPage'); log('已读取当前页面'); });
351
+ command('login-action', () => runLogin(pageHandle()));
352
+ command('insert-password', async () => { $('password').value = (await post('/demo-password', {})).password; });
353
+ command('credential-form', async () => {
354
+ const req = credentialRequest();
355
+ if (!req) throw new Error('credential_request_expired');
356
+ const secret = $('password').value;
357
+ $('password').value = '';
358
+ const latest = await call('getWorkspace', { workspaceId: req.workspaceId });
359
+ const pending = latest.activity.credentialRequest || state.demoRetry;
360
+ if (latest.mode !== 'agent' || !pending || req.operationId !== pending.operationId ||
361
+ req.origin !== pending.origin || req.credentialRef !== pending.credentialRef) {
362
+ throw new Error('credential_request_expired');
363
+ }
364
+ if (latest.activity.credentialRequest) await call('resolveCredential', { ...req, value: secret });
365
+ else if (req === state.demoRetry) await call('setCredential', { ...req, value: secret });
366
+ else throw new Error('credential_request_expired');
367
+ if (state.demoOperations.has(req.operationId)) {
368
+ state.demoRetry = null;
369
+ await runLogin({ workspaceId: req.workspaceId, pageId: req.pageId });
370
+ } else log('已绑定缺少的凭据;调用方可重新观察并提交剩余操作');
371
+ }, 'submit');
372
+ command('bind-form', async () => {
373
+ const page = currentPage();
374
+ const value = $('bind-value').value;
375
+ $('bind-value').value = '';
376
+ await call('setCredential', { workspaceId: state.workspace, origin: page.origin, credentialRef: $('bind-id').value, value });
377
+ $('credential-settings').open = false;
378
+ log('已为当前工作区绑定站点凭据');
379
+ }, 'submit');
380
+ command('take', async () => {
381
+ await call('takeControl', pageHandle());
382
+ clearObservation();
383
+ log('已由用户控制当前工作区');
384
+ });
385
+ command('give', async () => {
386
+ await call('returnToAgent', { workspaceId: state.workspace });
387
+ clearObservation();
388
+ log('已交回 Agent,页面需要重新观察');
389
+ });
390
+ command('view-controlled', async () => {
391
+ await call('showPage', pageHandle());
392
+ log('已显示接管页面');
393
+ });
394
+ command('close-workspace', async () => {
395
+ await call('closeWorkspace', { workspaceId: state.workspace });
396
+ if (state.demoRetry?.workspaceId === state.workspace) state.demoRetry = null;
397
+ choose('');
398
+ log('工作区已关闭');
399
+ });
400
+ command('page-form', async () => {
401
+ const page = await call('openPage', { workspaceId: state.workspace, url: $('address').value });
402
+ state.page = page.pageId;
403
+ $('address').value = '';
404
+ clearObservation();
405
+ log('已打开新页面');
406
+ }, 'submit');
407
+ command('reveal', async () => {
408
+ const showing = Boolean($('demo-secret').textContent);
409
+ $('demo-secret').textContent = showing ? '' : (await post('/demo-password', {})).password;
410
+ $('reveal').textContent = showing ? '显示密码' : '隐藏密码';
411
+ });
412
+ $('pages').onchange = () => { state.page = $('pages').value; clearObservation(); paint(); };
413
+
414
+ (async () => {
415
+ const key = location.hash.slice(1);
416
+ if (key) {
417
+ history.replaceState(null, '', location.pathname);
418
+ state.access = (await post('/pair', { key })).access;
419
+ sessionStorage.setItem('open-browser.studio', state.access);
420
+ } else state.access = sessionStorage.getItem('open-browser.studio') || '';
421
+ state.config = await post('/config', {});
422
+ $('demo-user').textContent = state.config.username;
423
+ $('url').value = state.config.demoUrl;
424
+ state.workspace = sessionStorage.getItem('open-browser.selection') || '';
425
+ await refresh();
426
+ if (!state.workspace && !sessionStorage.getItem('open-browser.selection') &&
427
+ state.workspaces.length && !state.entered) {
428
+ const first = groups.flatMap(g => state.workspaces.filter(w => groupOf(w) === g.id))[0];
429
+ choose(first.workspaceId);
430
+ await refresh();
431
+ }
432
+ setInterval(() => { if (!document.hidden) sync(); }, 900);
433
+ document.addEventListener('visibilitychange', () => { if (!document.hidden) sync(); });
434
+ })().catch(error => {
435
+ $('connection').textContent = '未连接';
436
+ notify(errorText[error.message] || '无法连接本机控制台,请重新启动 open-browser。');
437
+ document.querySelectorAll('button,input,select').forEach(el => el.disabled = true);
438
+ });
package/uploads.mjs ADDED
@@ -0,0 +1,63 @@
1
+ import {randomUUID} from 'node:crypto';
2
+
3
+ const maxFileBytes = 8 * 1024 * 1024;
4
+ function fail(code) { throw Object.assign(new Error(code), {code}); }
5
+
6
+ // Only the trusted desktop can supply the chosen file bytes. Grants never contain a path.
7
+ export class UploadGrants {
8
+ constructor() { this.entries = new Map(); }
9
+ remove(id) {
10
+ const entry=this.entries.get(id);
11
+ if (entry) { clearTimeout(entry.timer); this.entries.delete(id); }
12
+ }
13
+ clear() { for (const id of this.entries.keys()) this.remove(id); }
14
+ list() { return [...this.entries.values()].map(entry=>entry.info); }
15
+ grant(ws,tab,params) {
16
+ const {name,mimeType='',data,origin,documentId,controlGeneration} = params;
17
+ if (ws.mode !== 'agent' || ws.generation !== controlGeneration || tab.documentId !== documentId)
18
+ fail('stale_control');
19
+ if (!ws.origins.has(origin) || URL.parse(tab.page.url())?.origin !== origin) fail('origin_denied');
20
+ if (typeof data !== 'string' || data.length > 4*Math.ceil(maxFileBytes/3) ||
21
+ typeof name !== 'string' || !name.length || name.length>180 || /[\/\\\p{Cc}]/u.test(name) ||
22
+ name === '.' || name === '..' || typeof mimeType !== 'string' || mimeType.length>128) fail('invalid_file');
23
+ const buffer=Buffer.from(data,'base64');
24
+ if (buffer.length > maxFileBytes || buffer.toString('base64') !== data) fail('invalid_file');
25
+ if (this.entries.size>=4 || this.list().reduce((n,e)=>n+e.size,buffer.length)>2*maxFileBytes) fail('file_budget');
26
+ const fileId=randomUUID(), expiresAt=Date.now()+300_000;
27
+ const info={fileId,pageId:tab.id,documentId,controlGeneration,origin,name,size:buffer.length,expiresAt};
28
+ const timer=setTimeout(()=>this.remove(fileId),300_000).unref();
29
+ this.entries.set(fileId,{info,payload:{name,mimeType,buffer},timer});
30
+ return info;
31
+ }
32
+ get(ws,tab,id) {
33
+ const entry=this.entries.get(id);
34
+ if (!entry || entry.info.expiresAt<=Date.now() || entry.info.controlGeneration!==ws.generation ||
35
+ entry.info.pageId!==tab.id || entry.info.documentId!==tab.documentId || !ws.origins.has(entry.info.origin) ||
36
+ entry.info.origin!==URL.parse(tab.page.url())?.origin || ws.mode!=='agent') fail('file_grant_invalid');
37
+ return entry;
38
+ }
39
+ }
40
+
41
+ export async function chooseGrantedFile(ws,tab,el,id,beforeDispatch,check) {
42
+ ws.uploads.get(ws,tab,id);
43
+ // Register the chooser before dispatch. Many pages create a detached input during click.
44
+ let receive, timer;
45
+ const chosen=new Promise((resolve,reject)=>{
46
+ receive=resolve;
47
+ timer=setTimeout(()=>reject(Object.assign(new Error('file_chooser_timeout'),{code:'file_chooser_timeout'})),5000);
48
+ tab.page.once('filechooser',receive);
49
+ });
50
+ try {
51
+ beforeDispatch();
52
+ const [chooser]=await Promise.all([chosen,el.click({timeout:5000})]);
53
+ const frame=await chooser.element().ownerFrame();
54
+ if (frame!==tab.page.mainFrame()) fail('file_origin_mismatch');
55
+ check();
56
+ const {payload}=ws.uploads.get(ws,tab,id);
57
+ ws.uploads.remove(id);
58
+ await chooser.setFiles(payload,{timeout:5000});
59
+ } finally {
60
+ clearTimeout(timer);
61
+ tab.page.off('filechooser',receive);
62
+ }
63
+ }