@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/visual-page.mjs
ADDED
|
@@ -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,238 @@
|
|
|
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
|
+
export function previewFinish(service, ws, keepPageIds) {
|
|
13
|
+
const digest = finishDigest(keepPageIds);
|
|
14
|
+
for (const id of keepPageIds) service.tab(ws, id);
|
|
15
|
+
const keptPageIds = [], closedPageIds = [];
|
|
16
|
+
for (const tab of ws.pages.values())
|
|
17
|
+
(keepPageIds.includes(tab.id) || !tab.createdByAgent ? keptPageIds : closedPageIds).push(tab.id);
|
|
18
|
+
const previewId = createHash('sha256').update(JSON.stringify([ws.id, ws.generation, digest, keptPageIds, closedPageIds])).digest('hex');
|
|
19
|
+
return {previewId, keptPageIds, closedPageIds};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function stopOperations(ws, controlTransferred = false) {
|
|
23
|
+
ws.uploads?.clear();
|
|
24
|
+
ws.control.abort();
|
|
25
|
+
for (const job of ws.jobs) {
|
|
26
|
+
if (controlTransferred) job.controlTransferred = true;
|
|
27
|
+
job.cancel = true;
|
|
28
|
+
job.controller?.abort();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function finish(service, ws, {operationId, keepPageIds, controlGeneration, previewId}, trusted = false) {
|
|
33
|
+
stringParam(operationId, 160);
|
|
34
|
+
const digest = finishDigest(keepPageIds);
|
|
35
|
+
const past = service.store.get(ws.owner, ws.id, operationId);
|
|
36
|
+
if (past) {
|
|
37
|
+
if (past.digest !== digest) fail('operation_id_conflict');
|
|
38
|
+
return ws.finishing?.operationId === operationId ? ws.finishing.promise : past.receipt;
|
|
39
|
+
}
|
|
40
|
+
if (controlGeneration !== undefined && controlGeneration !== ws.generation) fail('stale_control');
|
|
41
|
+
if (ws.finishing) fail('workspace_finishing');
|
|
42
|
+
if (previewId !== undefined && (ws.pending || ws.inputPending || ws.popupTasks.size ||
|
|
43
|
+
previewFinish(service, ws, keepPageIds).previewId !== previewId)) fail('finish_preview_changed');
|
|
44
|
+
if (!trusted || ws.mode !== 'human') service.requireControl(ws, ws.generation);
|
|
45
|
+
for (const id of keepPageIds) service.tab(ws, id);
|
|
46
|
+
ws.offer?.revoke();
|
|
47
|
+
const keep = new Set(keepPageIds);
|
|
48
|
+
const receipt = { operationId, state:'running', phase:'running', totalSteps:ws.pages.size, completedSteps:0, keptPageIds:[], closedPageIds:[] };
|
|
49
|
+
service.store.save(ws.owner, ws.id, digest, receipt);
|
|
50
|
+
const pending = { operationId };
|
|
51
|
+
ws.finishing = pending;
|
|
52
|
+
for (const tab of ws.pages.values()) discardDialog(tab);
|
|
53
|
+
ws.generation = randomUUID();
|
|
54
|
+
stopOperations(ws);
|
|
55
|
+
pending.promise = (async () => {
|
|
56
|
+
await Promise.allSettled([ws.tail, ws.inputTail,...ws.popupTasks]);
|
|
57
|
+
try {
|
|
58
|
+
await ws.downloads.close();
|
|
59
|
+
const tabs = [...ws.pages.values()];
|
|
60
|
+
if (ws.onPage) ws.context.off('page', ws.onPage);
|
|
61
|
+
if (!service.sharedContext && tabs.some(tab => keep.has(tab.id) || !tab.createdByAgent))
|
|
62
|
+
await ws.networkRelease?.();
|
|
63
|
+
for (const tab of tabs) {
|
|
64
|
+
service.store.save(ws.owner, ws.id, digest, receipt, true);
|
|
65
|
+
if (keep.has(tab.id) || !tab.createdByAgent) {
|
|
66
|
+
await releaseInput(tab);
|
|
67
|
+
await service.setInputGuard?.(ws, tab, false);
|
|
68
|
+
await service.releaseTab?.(tab.page, ws.id, tab.id);
|
|
69
|
+
await tab.releasePopups?.();
|
|
70
|
+
await tab.networkRelease?.();
|
|
71
|
+
if (tab.networkSession) {
|
|
72
|
+
await tab.networkSession.send('Network.setBypassServiceWorker', {bypass:false});
|
|
73
|
+
await tab.networkSession.detach();
|
|
74
|
+
}
|
|
75
|
+
tab.unregister();
|
|
76
|
+
receipt.keptPageIds.push(tab.id);
|
|
77
|
+
} else {
|
|
78
|
+
await service.releaseTab?.(tab.page, ws.id, tab.id);
|
|
79
|
+
await tab.page.close();
|
|
80
|
+
receipt.closedPageIds.push(tab.id);
|
|
81
|
+
}
|
|
82
|
+
receipt.completedSteps++;
|
|
83
|
+
service.store.save(ws.owner, ws.id, digest, receipt);
|
|
84
|
+
}
|
|
85
|
+
if (!service.sharedContext && !receipt.keptPageIds.length) await ws.context.close();
|
|
86
|
+
ws.mode = 'closed';
|
|
87
|
+
ws.credentials.clear();
|
|
88
|
+
ws.credentialRequests.clear();
|
|
89
|
+
service.store.event(ws.owner, ws.id, 'control', ws.mode);
|
|
90
|
+
service.notify(ws);
|
|
91
|
+
service.workspaces.delete(ws.id);
|
|
92
|
+
receipt.state = 'completed';
|
|
93
|
+
receipt.phase = 'completed';
|
|
94
|
+
} catch {
|
|
95
|
+
// Some tabs may already have been released. Preserve their exact
|
|
96
|
+
// acknowledgements and require inspection before issuing a new finish.
|
|
97
|
+
receipt.state = 'outcome_unknown';
|
|
98
|
+
receipt.phase = 'outcome_unknown';
|
|
99
|
+
receipt.error = 'inspect_before_retry';
|
|
100
|
+
ws.mode = 'transferring';
|
|
101
|
+
try {
|
|
102
|
+
await setWorkspaceGuard(service, ws, false);
|
|
103
|
+
ws.mode = 'human';
|
|
104
|
+
} catch {
|
|
105
|
+
ws.unlockPending = true;
|
|
106
|
+
}
|
|
107
|
+
ws.generation = randomUUID();
|
|
108
|
+
service.notify(ws);
|
|
109
|
+
} finally {
|
|
110
|
+
service.store.save(ws.owner, ws.id, digest, receipt);
|
|
111
|
+
ws.finishing = null;
|
|
112
|
+
}
|
|
113
|
+
return { ...receipt };
|
|
114
|
+
})();
|
|
115
|
+
return pending.promise;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function handOff(service, ws, pageId, focus = true, expectedGeneration) {
|
|
119
|
+
if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
|
|
120
|
+
if (ws.returning) fail('control_transition');
|
|
121
|
+
if (ws.handoff) return ws.handoff;
|
|
122
|
+
if (ws.mode === 'human') return workspaceView(ws);
|
|
123
|
+
const tab = pageId ? service.tab(ws, pageId) : [...ws.pages.values()].at(-1);
|
|
124
|
+
ws.mode = 'transferring';
|
|
125
|
+
service.store.event(ws.owner, ws.id, 'control', ws.mode);
|
|
126
|
+
ws.credentialRequests.clear();
|
|
127
|
+
ws.generation = randomUUID();
|
|
128
|
+
stopOperations(ws, true);
|
|
129
|
+
service.notify(ws);
|
|
130
|
+
ws.handoff = (async () => {
|
|
131
|
+
await Promise.allSettled([ws.tail,...ws.popupTasks]);
|
|
132
|
+
for (const candidate of ws.pages.values()) clearRefs(candidate);
|
|
133
|
+
try {
|
|
134
|
+
await setWorkspaceGuard(service, ws, false);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
ws.unlockPending = true;
|
|
137
|
+
service.notify(ws);
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
ws.unlockPending = false;
|
|
141
|
+
if (ws.mode !== 'transferring') fail('workspace_closed');
|
|
142
|
+
ws.mode = 'human';
|
|
143
|
+
service.store.event(ws.owner, ws.id, 'control', ws.mode);
|
|
144
|
+
service.notify(ws);
|
|
145
|
+
if (focus && tab && !tab.dialog && !tab.page.isClosed())
|
|
146
|
+
await tab.page.bringToFront().catch(() => {});
|
|
147
|
+
await refreshControlGroups(service, ws);
|
|
148
|
+
return workspaceView(ws);
|
|
149
|
+
})().finally(() => { ws.handoff = null; });
|
|
150
|
+
return ws.handoff;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function setWorkspaceGuard(service, ws, enabled) {
|
|
154
|
+
if (!service.setInputGuard) return;
|
|
155
|
+
const results = await Promise.allSettled([...ws.pages.values()].map(async tab => {
|
|
156
|
+
try { await service.setInputGuard(ws, tab, enabled); }
|
|
157
|
+
catch (error) { if (!tab.page.isClosed()) throw error; }
|
|
158
|
+
}));
|
|
159
|
+
const failed = results.find(result => result.status === 'rejected');
|
|
160
|
+
if (failed) throw failed.reason;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function refreshControlGroups(service, ws) {
|
|
164
|
+
if (!service.groupTab) return;
|
|
165
|
+
await Promise.allSettled([...ws.pages.values()].filter(tab => !tab.dialog && !tab.page.isClosed())
|
|
166
|
+
.map(async tab => service.syncTab(ws, tab)));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function returnToAgent(service, ws, expectedGeneration) {
|
|
170
|
+
if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
|
|
171
|
+
if (ws.returning) return ws.returning;
|
|
172
|
+
if (ws.mode !== 'human') fail('not_in_human_control');
|
|
173
|
+
ws.mode = 'transferring';
|
|
174
|
+
service.store.event(ws.owner, ws.id, 'control', ws.mode);
|
|
175
|
+
ws.generation = randomUUID();
|
|
176
|
+
service.notify(ws);
|
|
177
|
+
ws.returning = (async () => {
|
|
178
|
+
try {
|
|
179
|
+
await ws.inputTail;
|
|
180
|
+
await Promise.all([...ws.pages.values()].map(releaseInput));
|
|
181
|
+
ws.guardLost = false;
|
|
182
|
+
await setWorkspaceGuard(service, ws, true);
|
|
183
|
+
if (ws.guardLost) fail('input_guard_unavailable');
|
|
184
|
+
} catch (error) {
|
|
185
|
+
try { await setWorkspaceGuard(service, ws, false); }
|
|
186
|
+
catch (rollbackError) {
|
|
187
|
+
ws.unlockPending = true;
|
|
188
|
+
service.notify(ws);
|
|
189
|
+
throw rollbackError;
|
|
190
|
+
}
|
|
191
|
+
if (ws.mode === 'transferring') {
|
|
192
|
+
ws.mode = 'human';
|
|
193
|
+
service.store.event(ws.owner, ws.id, 'control', ws.mode);
|
|
194
|
+
service.notify(ws);
|
|
195
|
+
}
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
if (ws.mode !== 'transferring') fail('workspace_closed');
|
|
199
|
+
// Returning control acknowledges that the user handled the visible site
|
|
200
|
+
// verification. A later navigation or response can raise it again.
|
|
201
|
+
ws.securityChallenge = null;
|
|
202
|
+
ws.control = new AbortController();
|
|
203
|
+
ws.mode = 'agent';
|
|
204
|
+
service.store.event(ws.owner, ws.id, 'control', ws.mode);
|
|
205
|
+
service.notify(ws);
|
|
206
|
+
await refreshControlGroups(service, ws);
|
|
207
|
+
return workspaceView(ws);
|
|
208
|
+
})().finally(() => { ws.returning = null; });
|
|
209
|
+
return ws.returning;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export async function close(service, ws) {
|
|
213
|
+
ws.offer?.revoke();
|
|
214
|
+
for (const tab of ws.pages.values()) discardDialog(tab);
|
|
215
|
+
ws.mode = 'closed';
|
|
216
|
+
service.store.event(ws.owner, ws.id, 'control', ws.mode);
|
|
217
|
+
stopOperations(ws);
|
|
218
|
+
service.notify(ws);
|
|
219
|
+
ws.credentials.clear();
|
|
220
|
+
await ws.downloads?.close();
|
|
221
|
+
if (service.sharedContext) {
|
|
222
|
+
await Promise.allSettled([ws.tail, ws.inputTail,...ws.popupTasks]);
|
|
223
|
+
await Promise.all([...ws.pages.values()].map(async tab => {
|
|
224
|
+
const {page, id} = tab;
|
|
225
|
+
if (ws.singleTab) {
|
|
226
|
+
await releaseInput(tab);
|
|
227
|
+
await service.setInputGuard?.(ws, tab, false);
|
|
228
|
+
try { await service.releaseTab?.(page, ws.id, id); }
|
|
229
|
+
finally { tab.unregister(); }
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (!page.isClosed() && service.releaseTab) await service.releaseTab(page,ws.id,id).catch(() => {});
|
|
233
|
+
await page.close().catch(() => {});
|
|
234
|
+
}));
|
|
235
|
+
} else await ws.context.close();
|
|
236
|
+
service.workspaces.delete(ws.id);
|
|
237
|
+
await Promise.allSettled([ws.tail, ws.inputTail,...ws.popupTasks]);
|
|
238
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
ownership:ws.singleTab ? 'user' : tab.createdByAgent ? 'agent' : 'user',
|
|
76
|
+
syncState:!tab.extensionSync ? 'not_required' : tab.syncedGeneration === ws.generation ? 'synced' : 'sync_pending',
|
|
77
|
+
syncRevision:tab.syncRevision || 0, lastSyncedAt:tab.lastSyncedAt || null,
|
|
78
|
+
title: origin ? redact(ws, tab.title) : '' };
|
|
79
|
+
});
|
|
80
|
+
const pending = [...ws.jobs];
|
|
81
|
+
const queued = pending.filter(job => job.receipt.state === 'queued');
|
|
82
|
+
const running = pending.filter(job => job.receipt.state === 'running');
|
|
83
|
+
const currentJob = running[0] || queued[0];
|
|
84
|
+
const current = operationView(currentJob);
|
|
85
|
+
if (currentJob?.pageId && ws.pages.has(currentJob.pageId)) current.pageId = currentJob.pageId;
|
|
86
|
+
const request = ws.credentialRequests.values().next().value;
|
|
87
|
+
const recent = operationView(ws.recent);
|
|
88
|
+
let phase = 'idle';
|
|
89
|
+
if (ws.securityChallenge) phase = 'needs_human_verification';
|
|
90
|
+
else if (current) phase = current.state;
|
|
91
|
+
else if (request) phase = 'needs_credential';
|
|
92
|
+
else if (recent && recent.error !== 'credential_required') phase = recent.state;
|
|
93
|
+
return { workspaceId: ws.id, profileId: serviceProfileId, name: ws.name, agentName: ws.agentName, mode: ws.mode, controlGeneration: ws.generation, pages,
|
|
94
|
+
pageAvailability:pages.length ? 'managed' : current?.kind === 'openPage' ? 'sync_pending' : ws.everRegistered ? 'closed' : 'unregistered',
|
|
95
|
+
scope:ws.singleTab ? 'single_tab' : 'workspace',
|
|
96
|
+
nextAction:pages.length ? (ws.mode === 'agent' ? 'reattachPage' : 'wait_for_agent_control') : current?.kind === 'openPage' ? 'wait_for_sync' : 'request_tab_selection',
|
|
97
|
+
...(ws.accountAlias && {accountAlias:ws.accountAlias}),
|
|
98
|
+
...(includeCredentialRequest && {pendingDialogs: [...ws.pages.values()].flatMap(tab=>tab.dialog ? [tab.dialog.info] : [])}),
|
|
99
|
+
...(includeCredentialRequest && { blockedOrigins: [...ws.blockedOrigins.values()] }),
|
|
100
|
+
...(ws.mode === 'transferring' && ws.unlockPending && {unlockPending:true}),
|
|
101
|
+
security: { inputGuard: ws.inputGuardMode || 'unavailable' },
|
|
102
|
+
activity: { phase, queued: queued.length, needsCredential: !!request,
|
|
103
|
+
needsHumanVerification: !!ws.securityChallenge,
|
|
104
|
+
...(ws.securityChallenge && { securityChallenge: { ...ws.securityChallenge } }), current, recent,
|
|
105
|
+
running: running.map(job => ({ ...operationView(job), ...(ws.pages.has(job.pageId) && {pageId:job.pageId}) })),
|
|
106
|
+
credentialRequest: request && includeCredentialRequest ? { ...request } : null } };
|
|
107
|
+
}
|