@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,306 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { PNG } from 'pngjs';
3
+
4
+ const maxPixels = 2_400_000;
5
+ const frameLifetime = 8000;
6
+ export const visualActions = Object.freeze(['click','hover','drag','scroll','key','tap','text']);
7
+ const fail = code => { throw Object.assign(new Error(code), {code}); };
8
+ const hash = value => createHash('sha256').update(value).digest('hex');
9
+ const finite = Number.isFinite;
10
+ const inRect = (x,y,r) => x >= r.x && y >= r.y && x < r.x+r.width && y < r.y+r.height;
11
+
12
+ function rectangle(rect,viewport) {
13
+ if (!rect || !['x','y','width','height'].every(k => Number.isSafeInteger(rect[k])) ||
14
+ rect.x<0 || rect.y<0 || rect.width<1 || rect.height<1 || rect.x+rect.width>viewport.width ||
15
+ rect.y+rect.height>viewport.height || rect.width*rect.height>maxPixels) fail('invalid_visual_region');
16
+ return {x:rect.x,y:rect.y,width:rect.width,height:rect.height};
17
+ }
18
+
19
+ // Use the browser's DOM/layout snapshot, including closed shadow trees. The
20
+ // page's DOM prototypes cannot redefine these node IDs or layout coordinates.
21
+ async function isolatedContext(session) {
22
+ const {frameTree}=await session.send('Page.getFrameTree');
23
+ const {executionContextId}=await session.send('Page.createIsolatedWorld',{
24
+ frameId:frameTree.frame.id,worldName:'open-browser-visual'});
25
+ return executionContextId;
26
+ }
27
+
28
+ async function measure(session, contextId, guarded=false) {
29
+ const {cssVisualViewport:v}=await session.send('Page.getLayoutMetrics');
30
+ const viewport={width:Math.floor(v.clientWidth),height:Math.floor(v.clientHeight),scrollX:v.pageX,scrollY:v.pageY,
31
+ scale:v.scale,zoom:v.zoom || 1,offsetX:v.offsetX,offsetY:v.offsetY,deviceScaleFactor:(await session.send('Runtime.evaluate',{expression:'window.devicePixelRatio',contextId})).result.value};
32
+ if (![viewport.scale,viewport.zoom,viewport.deviceScaleFactor].every(n=>finite(n)&&n>0)) fail('unsupported_visual_zoom');
33
+ const {documents,strings} = await session.send('DOMSnapshot.captureSnapshot',{
34
+ computedStyles:['visibility','filter','-webkit-box-reflect','backdrop-filter','opacity'],includePaintOrder:true });
35
+ const doc = documents[0];
36
+ if (!doc || doc.nodes.nodeName.length > 30000 || doc.layout.nodeIndex.length > 18000) fail('visual_layout_limit');
37
+ const sensitive = new Set(), shadowHosts = new Set();
38
+ for (const node of doc.nodes.shadowRootType?.index || []) {
39
+ // Built-in controls have UA shadow trees, and custom closed shadow hosts
40
+ // may contain private controls. Mask the entire host.
41
+ shadowHosts.add(doc.nodes.parentIndex[node]);
42
+ }
43
+ for(let i=0;i<doc.nodes.nodeName.length;i++) {
44
+ const tag = strings[doc.nodes.nodeName[i]];
45
+ const values = doc.nodes.attributes[i] || [];
46
+ let privateNode = ['INPUT','TEXTAREA','SELECT','IFRAME','FRAME','OBJECT','EMBED'].includes(tag) || shadowHosts.has(i);
47
+ for(let a=0;a<values.length;a+=2) {
48
+ const name=strings[values[a]], value=strings[values[a+1]];
49
+ if(name==='data-open-browser-private' || (name==='contenteditable' && value!=='false') ||
50
+ (name==='autocomplete' && /^(cc-|one-time-code)/.test(value))) privateNode=true;
51
+ }
52
+ if(privateNode || sensitive.has(doc.nodes.parentIndex[i])) sensitive.add(i);
53
+ }
54
+ const masks=[],layout=[],hiddenNodes=new Set();
55
+ let complexPaint=false;
56
+ for(let j=0;j<doc.layout.nodeIndex.length;j++) {
57
+ const node = doc.layout.nodeIndex[j], b = doc.layout.bounds[j];
58
+ const [visibility,filter,reflection,backdrop,opacity] = doc.layout.styles[j].map(k=>strings[k]);
59
+ if(opacity==='0') hiddenNodes.add(node);
60
+ layout.push([doc.nodes.backendNodeId[node],b,doc.layout.paintOrders[j],visibility]);
61
+ if ([filter,reflection,backdrop].some(v=>v && v!=='none')) complexPaint=true;
62
+ if(sensitive.has(node)) masks.push({x:b[0]/viewport.zoom-viewport.scrollX-2,y:b[1]/viewport.zoom-viewport.scrollY-2,
63
+ width:b[2]/viewport.zoom+4,height:b[3]/viewport.zoom+4});
64
+ }
65
+ if(guarded) {
66
+ for(const node of doc.layout.nodeIndex) {
67
+ if(!sensitive.has(node)) continue;
68
+ let parent=node;
69
+ while(parent>=0 && !hiddenNodes.has(parent)) parent=doc.nodes.parentIndex[parent];
70
+ if(parent<0) fail('visual_redaction_unavailable');
71
+ }
72
+ }
73
+ if(masks.length && complexPaint) fail('visual_redaction_unavailable');
74
+ const protectedNodes=new Set([...sensitive].map(i=>doc.nodes.backendNodeId[i]));
75
+ const hosts=[...new Set([...shadowHosts].map(i=>strings[doc.nodes.nodeName[i]].toLowerCase()))];
76
+ return {viewport,masks,protectedNodes,hosts,signature:hash(JSON.stringify([viewport,layout,masks]))};
77
+ }
78
+
79
+ // Read the current compositor surface. CDP's screenshot clip can temporarily
80
+ // change the visual viewport and reset a user's pinch zoom. Crop the surface
81
+ // locally and expose exactly one sample for each requested CSS pixel.
82
+ async function capturePixels(session,clip,v) {
83
+ const ratio=v.deviceScaleFactor*v.scale;
84
+ const width=Math.round(v.width*ratio),height=Math.round(v.height*ratio);
85
+ if (width*height>16_000_000) fail('visual_frame_too_large');
86
+ const {data}=await session.send('Page.captureScreenshot',{format:'png',fromSurface:true,captureBeyondViewport:false});
87
+ const raw=Buffer.from(data,'base64');
88
+ if(raw.length<24 || raw.readUInt32BE(16)*raw.readUInt32BE(20)>16_000_000) fail('visual_frame_too_large');
89
+ const source=PNG.sync.read(raw);
90
+ // Metrics are rounded down to whole CSS pixels. Permit the browser's
91
+ // fractional last pixel but reject geometry that does not match this frame.
92
+ if(Math.abs(source.width-width)>Math.ceil(ratio) || Math.abs(source.height-height)>Math.ceil(ratio))
93
+ fail('visual_geometry_changed');
94
+ const image=new PNG({width:clip.width,height:clip.height});
95
+ const input=new Uint32Array(source.data.buffer,source.data.byteOffset,source.data.length/4);
96
+ const output=new Uint32Array(image.data.buffer,image.data.byteOffset,image.data.length/4);
97
+ for(let y=0;y<image.height;y++) {
98
+ const sy=Math.min(source.height-1,Math.floor((clip.y+y+0.5)*ratio));
99
+ for(let x=0;x<image.width;x++) {
100
+ const sx=Math.min(source.width-1,Math.floor((clip.x+x+0.5)*ratio));
101
+ output[y*image.width+x]=input[sy*source.width+sx];
102
+ }
103
+ }
104
+ return image;
105
+ }
106
+
107
+ function redactImage(png,clip,masks) {
108
+ for(const m of masks) {
109
+ const left=Math.max(0,Math.floor(m.x-clip.x)), right=Math.min(png.width,Math.ceil(m.x+m.width-clip.x));
110
+ const top=Math.max(0,Math.floor(m.y-clip.y)), bottom=Math.min(png.height,Math.ceil(m.y+m.height-clip.y));
111
+ for(let y=top;y<bottom;y++) for(let x=left;x<right;x++) png.data.writeUInt32BE(0x000000ff,(y*png.width+x)*4);
112
+ }
113
+ const clean = PNG.sync.write(png);
114
+ if(clean.length>3*1024*1024) fail('visual_frame_too_large');
115
+ return clean;
116
+ }
117
+
118
+ // Suppress private paint in the renderer as well as blacking out its known
119
+ // bounds. A moving control, overflowing glyph, or frame cannot paint its
120
+ // visible content between the two layout measurements. The isolated world
121
+ // keeps the stylesheet and DOM access independent of page JS prototypes.
122
+ async function maskedCapture(session,contextId,clip,initial) {
123
+ const selectors=['input','textarea','select','iframe','frame','object','embed','[data-open-browser-private]',
124
+ '[contenteditable]:not([contenteditable="false" i])','[autocomplete*="cc-" i]','[autocomplete*="one-time-code" i]'];
125
+ for(const host of initial.hosts) {
126
+ if(!/^[a-z][a-z0-9-]*$/.test(host)) fail('visual_redaction_unavailable');
127
+ selectors.push(host);
128
+ }
129
+ const scope=':is('+selectors.join(',')+')';
130
+ const rule=scope+', '+scope+' *, '+scope+'::before, '+scope+'::after {opacity:0!important;transition:none!important}';
131
+ const {result}=await session.send('Runtime.evaluate',{contextId,expression:`(() => {
132
+ const sheet=new CSSStyleSheet();sheet.replaceSync(${JSON.stringify(rule)});
133
+ document.adoptedStyleSheets=[...document.adoptedStyleSheets,sheet];return sheet;
134
+ })()`});
135
+ if(!result.objectId) fail('visual_redaction_unavailable');
136
+ try {
137
+ const before=await measure(session,contextId,true);
138
+ if(before.signature!==initial.signature) fail('stale_visual_frame');
139
+ const data=await capturePixels(session,clip,before.viewport);
140
+ const after=await measure(session,contextId,true);
141
+ if(before.signature!==after.signature) fail('stale_visual_frame');
142
+ return redactImage(data,clip,before.masks);
143
+ } finally {
144
+ await session.send('Runtime.callFunctionOn',{objectId:result.objectId,
145
+ functionDeclaration:'function(){ document.adoptedStyleSheets=document.adoptedStyleSheets.filter(sheet=>sheet!==this) }'})
146
+ .catch(()=>{});
147
+ }
148
+ }
149
+
150
+ export function validateVisualAction(action) {
151
+ const types={click:[],hover:[],tap:[],drag:['toX','toY'],scroll:['deltaX','deltaY'],key:['keys'],text:['text']};
152
+ if(!action || !Object.hasOwn(types,action.type) || !finite(action.x) || !finite(action.y) ||
153
+ Object.keys(action).some(k=>!['type','x','y',...types[action.type]].includes(k))) fail('invalid_visual_action');
154
+ if(action.type==='drag' && ![action.toX,action.toY].every(finite)) fail('invalid_visual_action');
155
+ if(action.type==='scroll' && ![action.deltaX,action.deltaY].every(v=>finite(v)&&Math.abs(v)<=1600)) fail('invalid_visual_action');
156
+ if(action.type==='key' && (!Array.isArray(action.keys) || !action.keys.length || action.keys.length>3 ||
157
+ !action.keys.every((k,i)=>typeof k==='string' && (i<action.keys.length-1 ? /^(Control|Shift|Alt|Meta)$/.test(k) :
158
+ /^(Tab|Enter|Escape|Space|Backspace|Delete|ArrowLeft|ArrowRight|ArrowUp|ArrowDown|Home|End|[a-z0-9])$/.test(k))))) fail('invalid_visual_action');
159
+ if(action.type==='text' && (typeof action.text!=='string'||!action.text.length||action.text.length>2048)) fail('invalid_visual_action');
160
+ }
161
+
162
+ export class VisualPages {
163
+ permissions = new WeakMap();
164
+ frames = new WeakMap();
165
+ active = 0;
166
+ enabled = process.env.OPEN_BROWSER_DISABLE_VISUAL !== '1';
167
+
168
+ revokeActor(ws, principalId) {
169
+ const grants=this.permissions.get(ws);
170
+ if(!grants) return;
171
+ for(const key of grants.keys()) if(JSON.parse(key)[0]===principalId) grants.delete(key);
172
+ }
173
+
174
+ permission(ws, {principalId,origin,allow}) {
175
+ const u=URL.parse(origin);
176
+ if(typeof principalId!=='string'||!principalId||principalId.length>160||typeof allow!=='boolean'||
177
+ !u||!['http:','https:'].includes(u.protocol)||u.origin!==origin||!ws.origins.has(origin)) fail('invalid_pixel_permission');
178
+ let grants=this.permissions.get(ws);
179
+ if(!grants){ grants=new Map(); this.permissions.set(ws,grants); }
180
+ const key=JSON.stringify([principalId,origin]);
181
+ if(allow) grants.set(key,randomUUID()); else grants.delete(key);
182
+ return {principalId,origin,allow};
183
+ }
184
+
185
+ authority(ws,tab,actor,mode) {
186
+ if(!this.enabled) fail('visual_disabled');
187
+ if(ws.mode!==mode || ws.finishing) fail('stale_control');
188
+ if(ws.pages.get(tab.id)!==tab || tab.page.isClosed()) fail('page_not_found');
189
+ const url=URL.parse(tab.page.url());
190
+ if(!url || !['http:','https:'].includes(url.protocol)||url.username||url.password||!ws.origins.has(url.origin)) fail('origin_denied');
191
+ const grant=this.permissions.get(ws)?.get(JSON.stringify([actor,url.origin]));
192
+ if(!grant) fail('pixel_permission_required');
193
+ return {origin:url.origin,grant,documentId:tab.documentId,controlGeneration:ws.generation};
194
+ }
195
+
196
+ async capture(ws,tab,actor,params,mode) {
197
+ const auth=this.authority(ws,tab,actor,mode);
198
+ if(params.ref!==undefined && params.region!==undefined) fail('invalid_visual_region');
199
+ if(tab.visualBusy || this.active>=3 || Date.now()-(tab.visualCaptureAt||0)<150) fail('frame_busy');
200
+ tab.visualCaptureAt=Date.now(); tab.visualBusy=true; this.active++;
201
+ let session;
202
+ try {
203
+ session=await tab.page.context().newCDPSession(tab.page);
204
+ const contextId=await isolatedContext(session);
205
+ const initial=await measure(session,contextId);
206
+ const v=initial.viewport;
207
+ let region=params.region;
208
+ if(params.ref!==undefined) {
209
+ const handle=tab.refs.get(params.ref);
210
+ const bounds=await handle?.boundingBox();
211
+ if(!bounds) fail('stale_ref');
212
+ region={x:Math.floor(bounds.x-v.offsetX),y:Math.floor(bounds.y-v.offsetY),width:Math.ceil(bounds.width),height:Math.ceil(bounds.height)};
213
+ }
214
+ const clip=rectangle(region ?? {x:0,y:0,width:v.width,height:v.height},v);
215
+ const pixels=await maskedCapture(session,contextId,clip,initial);
216
+ const final=await measure(session,contextId);
217
+ const current=this.authority(ws,tab,actor,mode);
218
+ if(JSON.stringify(auth)!==JSON.stringify(current)||initial.signature!==final.signature) fail('stale_visual_frame');
219
+ await session.detach();session=null;
220
+ if(JSON.stringify(auth)!==JSON.stringify(this.authority(ws,tab,actor,mode))) fail('stale_visual_frame');
221
+ ws.lastVisualCapture={pageId:tab.id,principalId:actor,origin:auth.origin,clip,at:Date.now()};
222
+ const frameId=randomUUID();
223
+ this.frames.set(tab,{...auth,actor,mode,clip,frameId,expires:Date.now()+frameLifetime,signature:initial.signature,
224
+ // Retain only a digest, so changed paint on canvas is detected without saving its pixels.
225
+ pixelDigest:hash(pixels)});
226
+ return {workspaceId:ws.id,pageId:tab.id,frameId,documentId:auth.documentId,controlGeneration:auth.controlGeneration,
227
+ origin:auth.origin,mimeType:'image/png',data:pixels.toString('base64'),clip,viewport:{width:v.width,height:v.height},
228
+ pixelWidth:clip.width,pixelHeight:clip.height,scale:v.scale,zoom:v.zoom,deviceScaleFactor:v.deviceScaleFactor};
229
+ } finally { if(session) await session.detach().catch(()=>{}); tab.visualBusy=false; this.active--; }
230
+ }
231
+
232
+ async input(ws,tab,actor,params,mode,dispatch=()=>{}) {
233
+ const auth=this.authority(ws,tab,actor,mode);
234
+ const frame=this.frames.get(tab);
235
+ const check=()=>{
236
+ const live=this.authority(ws,tab,actor,mode);
237
+ if(!frame||frame.actor!==actor||frame.mode!==mode||live.grant!==frame.grant||live.origin!==frame.origin||
238
+ frame.frameId!==params.frameId||frame.expires<Date.now()||tab.documentId!==params.documentId||
239
+ auth.documentId!==frame.documentId||ws.generation!==params.controlGeneration||auth.controlGeneration!==frame.controlGeneration)
240
+ fail('stale_visual_frame');
241
+ };
242
+ check(); validateVisualAction(params.action);
243
+ if(tab.visualBusy || this.active>=3) fail('frame_busy');
244
+ tab.visualBusy=true;this.active++;
245
+ this.frames.delete(tab);
246
+ let session;
247
+ const {page}=tab, action=params.action;
248
+ const held=[];
249
+ let button=false,touch=false;
250
+ try {
251
+ session=await page.context().newCDPSession(page);
252
+ const executionContextId=await isolatedContext(session);
253
+ const layout=await measure(session,executionContextId);
254
+ if(layout.signature!==frame.signature) fail('stale_visual_frame');
255
+ const pixels=await maskedCapture(session,executionContextId,frame.clip,layout);
256
+ if(hash(pixels)!==frame.pixelDigest || (await measure(session,executionContextId)).signature!==layout.signature)
257
+ fail('stale_visual_frame');
258
+ async function point(x,y,verifyFocus=false) {
259
+ check();
260
+ if(!inRect(x,y,frame.clip) || layout.masks.some(m=>inRect(x,y,m))) fail('visual_target_denied');
261
+ const hitX=x+layout.viewport.offsetX,hitY=y+layout.viewport.offsetY;
262
+ const expression=`(() => {
263
+ const node=document.elementFromPoint(${hitX},${hitY});
264
+ if(!node || node.closest('input, textarea, select, iframe, frame, object, embed, [data-open-browser-private], [contenteditable]:not([contenteditable="false" i]), [inert], [disabled], [aria-disabled="true"]')) return null;
265
+ const active=document.activeElement;
266
+ if(${verifyFocus} && (!active || active===document.body || (active!==node && !active.contains(node)))) return null;
267
+ return node;
268
+ })()`;
269
+ const {result}=await session.send('Runtime.evaluate',{expression,contextId:executionContextId});
270
+ if(!result.objectId) fail('visual_target_denied');
271
+ const {node}=await session.send('DOM.describeNode',{objectId:result.objectId});
272
+ if(!node.backendNodeId || layout.protectedNodes.has(node.backendNodeId)) fail('visual_target_denied');
273
+ check();
274
+ }
275
+ await point(action.x,action.y,['key','text'].includes(action.type));
276
+ if(action.type==='drag') for(let i=1;i<=12;i++) await point(action.x+(action.toX-action.x)*i/12,action.y+(action.toY-action.y)*i/12);
277
+ check(); dispatch();
278
+ if(action.type==='tap') {
279
+ await session.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:action.x,y:action.y}]});
280
+ touch=true;check();await session.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});touch=false;
281
+ } else if(action.type==='key') {
282
+ for(const key of action.keys){check();await page.keyboard.down(key);held.push(key);}
283
+ } else if(action.type==='text') await page.keyboard.insertText(action.text);
284
+ else {
285
+ await page.mouse.move(action.x,action.y);
286
+ await point(action.x,action.y);
287
+ if(action.type==='scroll') await page.mouse.wheel(action.deltaX,action.deltaY);
288
+ if(['click','drag'].includes(action.type)) {
289
+ await page.mouse.down();button=true;
290
+ if(action.type==='drag') for(let i=1;i<=12;i++) {
291
+ const x=action.x+(action.toX-action.x)*i/12,y=action.y+(action.toY-action.y)*i/12;
292
+ await point(x,y);await page.mouse.move(x,y);
293
+ }
294
+ check();await page.mouse.up();button=false;
295
+ }
296
+ }
297
+ return {accepted:true};
298
+ } finally {
299
+ for(const key of held.reverse()) await page.keyboard.up(key).catch(()=>{});
300
+ if(button){await page.mouse.move(-1,-1).catch(()=>{});await page.mouse.up().catch(()=>{});}
301
+ if(touch) await session.send('Input.dispatchTouchEvent',{type:'touchCancel',touchPoints:[]}).catch(()=>{});
302
+ if(session) await session.detach().catch(()=>{});
303
+ tab.visualBusy=false;this.active--;
304
+ }
305
+ }
306
+ }
@@ -0,0 +1,170 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { discardDialog } from './page-dialogs.mjs';
3
+ import { releaseInput } from './desktop-page.mjs';
4
+ import { clearRefs, fail, stringParam, workspaceView } from './workspace-state.mjs';
5
+
6
+ export function finishDigest(keepPageIds) {
7
+ if (!Array.isArray(keepPageIds) || keepPageIds.some(id => typeof id !== 'string') ||
8
+ new Set(keepPageIds).size !== keepPageIds.length) fail('invalid_params');
9
+ return createHash('sha256').update(JSON.stringify(['finish', [...keepPageIds].sort()])).digest('hex');
10
+ }
11
+
12
+ function stopOperations(ws, controlTransferred = false) {
13
+ ws.uploads?.clear();
14
+ ws.control.abort();
15
+ for (const job of ws.jobs) {
16
+ if (controlTransferred) job.controlTransferred = true;
17
+ job.cancel = true;
18
+ job.controller?.abort();
19
+ }
20
+ }
21
+
22
+ export async function finish(service, ws, {operationId, keepPageIds, controlGeneration}, trusted = false) {
23
+ stringParam(operationId, 160);
24
+ const digest = finishDigest(keepPageIds);
25
+ const past = service.store.get(ws.owner, ws.id, operationId);
26
+ if (past) {
27
+ if (past.digest !== digest) fail('operation_id_conflict');
28
+ return ws.finishing?.operationId === operationId ? ws.finishing.promise : past.receipt;
29
+ }
30
+ if (controlGeneration !== undefined && controlGeneration !== ws.generation) fail('stale_control');
31
+ if (ws.finishing) fail('workspace_finishing');
32
+ if (!trusted || ws.mode !== 'human') service.requireControl(ws, ws.generation);
33
+ for (const id of keepPageIds) service.tab(ws, id);
34
+ const keep = new Set(keepPageIds);
35
+ const receipt = { operationId, state:'running', phase:'running', totalSteps:ws.pages.size, completedSteps:0, keptPageIds:[], closedPageIds:[] };
36
+ service.store.save(ws.owner, ws.id, digest, receipt);
37
+ const pending = { operationId };
38
+ ws.finishing = pending;
39
+ for (const tab of ws.pages.values()) discardDialog(tab);
40
+ ws.generation = randomUUID();
41
+ stopOperations(ws);
42
+ pending.promise = (async () => {
43
+ await Promise.allSettled([ws.tail, ws.inputTail,...ws.popupTasks]);
44
+ try {
45
+ await ws.downloads.close();
46
+ const tabs = [...ws.pages.values()];
47
+ if (ws.onPage) ws.context.off('page', ws.onPage);
48
+ if (!service.sharedContext && tabs.some(tab => keep.has(tab.id) || !tab.createdByAgent))
49
+ await ws.networkRelease?.();
50
+ for (const tab of tabs) {
51
+ service.store.save(ws.owner, ws.id, digest, receipt, true);
52
+ if (keep.has(tab.id) || !tab.createdByAgent) {
53
+ await releaseInput(tab);
54
+ await service.releaseTab?.(tab.page, ws.id, tab.id);
55
+ await tab.releasePopups?.();
56
+ await tab.networkRelease?.();
57
+ if (tab.networkSession) {
58
+ await tab.networkSession.send('Network.setBypassServiceWorker', {bypass:false});
59
+ await tab.networkSession.detach();
60
+ }
61
+ tab.unregister();
62
+ receipt.keptPageIds.push(tab.id);
63
+ } else {
64
+ await service.releaseTab?.(tab.page, ws.id, tab.id);
65
+ await tab.page.close();
66
+ receipt.closedPageIds.push(tab.id);
67
+ }
68
+ receipt.completedSteps++;
69
+ service.store.save(ws.owner, ws.id, digest, receipt);
70
+ }
71
+ if (!service.sharedContext && !receipt.keptPageIds.length) await ws.context.close();
72
+ ws.mode = 'closed';
73
+ ws.credentials.clear();
74
+ ws.credentialRequests.clear();
75
+ service.store.event(ws.owner, ws.id, 'control', ws.mode);
76
+ service.notify(ws);
77
+ service.workspaces.delete(ws.id);
78
+ receipt.state = 'completed';
79
+ receipt.phase = 'completed';
80
+ } catch {
81
+ // Some tabs may already have been released. Preserve their exact
82
+ // acknowledgements and require inspection before issuing a new finish.
83
+ receipt.state = 'outcome_unknown';
84
+ receipt.phase = 'outcome_unknown';
85
+ receipt.error = 'inspect_before_retry';
86
+ ws.mode = 'human';
87
+ ws.generation = randomUUID();
88
+ service.notify(ws);
89
+ } finally {
90
+ service.store.save(ws.owner, ws.id, digest, receipt);
91
+ ws.finishing = null;
92
+ }
93
+ return { ...receipt };
94
+ })();
95
+ return pending.promise;
96
+ }
97
+
98
+ export async function handOff(service, ws, pageId, focus = true, expectedGeneration) {
99
+ if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
100
+ if (ws.returning) fail('control_transition');
101
+ if (ws.handoff) return ws.handoff;
102
+ if (ws.mode === 'human') return workspaceView(ws);
103
+ const tab = pageId ? service.tab(ws, pageId) : [...ws.pages.values()].at(-1);
104
+ ws.mode = 'transferring';
105
+ service.store.event(ws.owner, ws.id, 'control', ws.mode);
106
+ ws.credentialRequests.clear();
107
+ ws.generation = randomUUID();
108
+ stopOperations(ws, true);
109
+ service.notify(ws);
110
+ ws.handoff = (async () => {
111
+ await Promise.allSettled([ws.tail,...ws.popupTasks]);
112
+ for (const candidate of ws.pages.values()) clearRefs(candidate);
113
+ if (ws.mode !== 'transferring') fail('workspace_closed');
114
+ ws.mode = 'human';
115
+ service.store.event(ws.owner, ws.id, 'control', ws.mode);
116
+ service.notify(ws);
117
+ if (focus && tab && !tab.dialog && !tab.page.isClosed())
118
+ await tab.page.bringToFront().catch(() => {});
119
+ await refreshControlGroups(service, ws);
120
+ return workspaceView(ws);
121
+ })().finally(() => { ws.handoff = null; });
122
+ return ws.handoff;
123
+ }
124
+
125
+ async function refreshControlGroups(service, ws) {
126
+ if (!service.groupTab) return;
127
+ await Promise.allSettled([...ws.pages.values()].filter(tab => !tab.dialog && !tab.page.isClosed())
128
+ .map(async tab => service.groupTab(tab.page, ws.id, ws.name, ws.mode, ws.agentName, tab.id)));
129
+ }
130
+
131
+ export async function returnToAgent(service, ws, expectedGeneration) {
132
+ if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
133
+ if (ws.returning) return ws.returning;
134
+ if (ws.mode !== 'human') fail('not_in_human_control');
135
+ ws.mode = 'transferring';
136
+ service.store.event(ws.owner, ws.id, 'control', ws.mode);
137
+ ws.generation = randomUUID();
138
+ service.notify(ws);
139
+ ws.returning = (async () => {
140
+ await ws.inputTail;
141
+ await Promise.all([...ws.pages.values()].map(releaseInput));
142
+ if (ws.mode !== 'transferring') fail('workspace_closed');
143
+ ws.control = new AbortController();
144
+ ws.mode = 'agent';
145
+ service.store.event(ws.owner, ws.id, 'control', ws.mode);
146
+ service.notify(ws);
147
+ await refreshControlGroups(service, ws);
148
+ return workspaceView(ws);
149
+ })().finally(() => { ws.returning = null; });
150
+ return ws.returning;
151
+ }
152
+
153
+ export async function close(service, ws) {
154
+ for (const tab of ws.pages.values()) discardDialog(tab);
155
+ ws.mode = 'closed';
156
+ service.store.event(ws.owner, ws.id, 'control', ws.mode);
157
+ stopOperations(ws);
158
+ service.notify(ws);
159
+ ws.credentials.clear();
160
+ await ws.downloads?.close();
161
+ if (service.sharedContext) {
162
+ await Promise.allSettled([ws.tail, ws.inputTail,...ws.popupTasks]);
163
+ await Promise.all([...ws.pages.values()].map(async ({page,id}) => {
164
+ if (!page.isClosed() && service.releaseTab) await service.releaseTab(page,ws.id,id).catch(() => {});
165
+ await page.close().catch(() => {});
166
+ }));
167
+ } else await ws.context.close();
168
+ service.workspaces.delete(ws.id);
169
+ await Promise.allSettled([ws.tail, ws.inputTail,...ws.popupTasks]);
170
+ }
@@ -0,0 +1,95 @@
1
+ import { profileId as serviceProfileId } from './paths.mjs';
2
+ import { redactSensitiveText } from './privacy-config.mjs';
3
+
4
+ export class ServiceError extends Error {
5
+ constructor(code) {
6
+ super(code);
7
+ this.code = code;
8
+ }
9
+ }
10
+
11
+ export function fail(code) { throw new ServiceError(code); }
12
+
13
+ export function webOrigin(value) {
14
+ let url;
15
+ try { url = new URL(value); } catch { fail('invalid_url'); }
16
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) fail('invalid_url');
17
+ return url.origin;
18
+ }
19
+
20
+ export function allowedPageOrigin(ws, tab) {
21
+ const url = URL.parse(tab.page.url());
22
+ if (url && ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password &&
23
+ ws.origins.has(url.origin)) return url.origin;
24
+ return null;
25
+ }
26
+
27
+ export function requirePageOrigin(ws, tab) {
28
+ return allowedPageOrigin(ws, tab) || fail('origin_denied');
29
+ }
30
+
31
+ export function publicError(error) {
32
+ if (error instanceof ServiceError) return error.code;
33
+ return error.name === 'TimeoutError' ? 'timeout' : 'browser_action_failed';
34
+ }
35
+
36
+ export function stringParam(value, max) {
37
+ if (typeof value !== 'string' || !value.length || value.length > max) fail('invalid_params');
38
+ return value;
39
+ }
40
+
41
+
42
+ export function redact(ws, text) {
43
+ return redactSensitiveText(text, ws.credentials.values());
44
+ }
45
+
46
+ export function clearFrameRefs(tab) {
47
+ for(const entry of tab.frameRefs.values()) void entry.handle.dispose().catch(()=>{});
48
+ tab.frameRefs.clear();
49
+ }
50
+
51
+ export function clearRefs(tab) {
52
+ clearFrameRefs(tab);
53
+ tab.cursors.clear();
54
+ for (const handle of tab.refs.values()) void handle.dispose().catch(() => {});
55
+ tab.refs.clear();
56
+ tab.strictLocator=undefined;
57
+ void tab.observedNodes?.dispose().catch(() => {});
58
+ tab.observedNodes = undefined;
59
+ }
60
+
61
+ function operationView(job) {
62
+ if (!job) return null;
63
+ const { state, phase, completedSteps, error } = job.receipt;
64
+ return { kind: job.kind, state, completedSteps, totalSteps: job.totalSteps,
65
+ ...(phase && {phase}),
66
+ ...(job.stepKind && state === 'running' && {dispatchState: job.dispatched ? 'dispatched' : 'waiting'}),
67
+ ...(job.stepKind && { stepKind: job.stepKind }), ...(error && { error }) };
68
+ }
69
+
70
+ export function workspaceView(ws, includeCredentialRequest = false) {
71
+ const pages = [...ws.pages.values()].map(tab => {
72
+ const origin = allowedPageOrigin(ws, tab);
73
+ return { workspaceId: ws.id, pageId: tab.id, documentId:tab.documentId, origin: origin || 'null',
74
+ ...(tab.openerPageId && {openerPageId:tab.openerPageId,openedByOperationId:tab.openedByOperationId}),
75
+ title: origin ? redact(ws, tab.title) : '' };
76
+ });
77
+ const pending = [...ws.jobs];
78
+ const queued = pending.filter(job => job.receipt.state === 'queued');
79
+ const running = pending.filter(job => job.receipt.state === 'running');
80
+ const currentJob = running[0] || queued[0];
81
+ const current = operationView(currentJob);
82
+ if (currentJob?.pageId && ws.pages.has(currentJob.pageId)) current.pageId = currentJob.pageId;
83
+ const request = ws.credentialRequests.values().next().value;
84
+ const recent = operationView(ws.recent);
85
+ let phase = 'idle';
86
+ if (current) phase = current.state;
87
+ else if (request) phase = 'needs_credential';
88
+ else if (recent && recent.error !== 'credential_required') phase = recent.state;
89
+ return { workspaceId: ws.id, profileId: serviceProfileId, name: ws.name, agentName: ws.agentName, mode: ws.mode, controlGeneration: ws.generation, pages,
90
+ ...(includeCredentialRequest && {pendingDialogs: [...ws.pages.values()].flatMap(tab=>tab.dialog ? [tab.dialog.info] : [])}),
91
+ ...(includeCredentialRequest && { blockedOrigins: [...ws.blockedOrigins.values()] }),
92
+ activity: { phase, queued: queued.length, needsCredential: !!request, current, recent,
93
+ running: running.map(job => ({ ...operationView(job), ...(ws.pages.has(job.pageId) && {pageId:job.pageId}) })),
94
+ credentialRequest: request && includeCredentialRequest ? { ...request } : null } };
95
+ }