webhelm 1.0.55 → 1.0.57
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/README.md +9 -0
- package/package.json +1 -1
- package/runtime/cli-help.mjs +5 -4
- package/runtime/extension/manifest.json +1 -1
- package/runtime/extension/service-worker.mjs +2 -1
- package/runtime/extension/workspace-manager.mjs +18 -0
- package/runtime/node-daemon.mjs +105 -32
- package/runtime/user-helpers.mjs +72 -0
- package/runtime/network-observer.mjs +0 -55
package/README.md
CHANGED
|
@@ -36,6 +36,15 @@ npx --yes webhelm@latest session stop SESSION_ID
|
|
|
36
36
|
Use `npx skills add lalalic/webhelm --skill webhelm` to install agent guidance.
|
|
37
37
|
The Extension is bundled with the npm Runtime and staged by WebHelm Daemon at `~/.local/webhelm/extension`. The Skill lives **in this repo** at `skills/webhelm/SKILL.md`. No Chrome Web Store publication or manual Extension installation is required.
|
|
38
38
|
|
|
39
|
+
### Browser helpers and local extensions
|
|
40
|
+
|
|
41
|
+
Use semantic built-in browser helpers for navigation, input, tab allocation,
|
|
42
|
+
file selection, frame evaluation and page initialization. Raw CDP is internal
|
|
43
|
+
to the Runtime. Reviewed local user helper modules can provide additional
|
|
44
|
+
diagnostics through a Runtime-enforced, current-tab broker. See
|
|
45
|
+
[Browser helper development](docs/browser-helpers.md) for the API, migration
|
|
46
|
+
table, policy boundary and test requirements.
|
|
47
|
+
|
|
39
48
|
### Automatic npm Runtime upgrades (macOS)
|
|
40
49
|
|
|
41
50
|
`webhelm setup` installs two independent LaunchAgents: the offline Chrome health
|
package/package.json
CHANGED
package/runtime/cli-help.mjs
CHANGED
|
@@ -245,11 +245,12 @@ Options:
|
|
|
245
245
|
|
|
246
246
|
The JavaScript context persists across exec calls. Browser helpers are async:
|
|
247
247
|
snapshot, page_info, goto_url, wait_for_load, wait_for_element,
|
|
248
|
-
fill_input, click, js,
|
|
249
|
-
switch_tab, close_tab, upload_file, type_text,
|
|
250
|
-
wait.
|
|
248
|
+
fill_input, click, js, new_tab, current_tab, list_tabs,
|
|
249
|
+
switch_tab, activate_tab, close_tab, upload_file, type_text, press_key,
|
|
250
|
+
add_init_script, list_frames, js_in_frame, capture_screenshot, events, wait.
|
|
251
251
|
Read 'snapshot()' before using element references and refresh after navigation.
|
|
252
|
-
|
|
252
|
+
Raw CDP is private; use the semantic helpers. Reviewed local helper modules
|
|
253
|
+
can be installed in ~/.local/webhelm/helpers/ (see Skill and developer docs).
|
|
253
254
|
Output: JSON with execution status and captured result/stdout.
|
|
254
255
|
|
|
255
256
|
Example:
|
|
@@ -138,7 +138,8 @@ chrome.webNavigation.onCreatedNavigationTarget.addListener((details) => {
|
|
|
138
138
|
|
|
139
139
|
chrome.tabs.onUpdated.addListener((_tabId, changeInfo, tab) => {
|
|
140
140
|
if (changeInfo.url || Object.prototype.hasOwnProperty.call(changeInfo, "groupId")) scheduleBadge();
|
|
141
|
-
if (!Object.prototype.hasOwnProperty.call(changeInfo, "groupId")
|
|
141
|
+
if (!Object.prototype.hasOwnProperty.call(changeInfo, "groupId") &&
|
|
142
|
+
!/^chrome:\/\/(?:newtab|new-tab-page)(?:[/?#]|$)/.test(changeInfo.url || "")) return;
|
|
142
143
|
manager.inheritWorkspaceForCreatedTab(tab).then(scheduleBadge).catch((error) => {
|
|
143
144
|
console.warn("WebHelm failed to reconcile tab group ownership", error);
|
|
144
145
|
});
|
|
@@ -372,6 +372,24 @@ export class WorkspaceManager {
|
|
|
372
372
|
const groups = await this.chrome.tabGroups.query({});
|
|
373
373
|
const groupsById = new Map(groups.map((candidate) => [candidate.id, candidate]));
|
|
374
374
|
|
|
375
|
+
// Chrome can give a browser-created New Tab an opener in the active
|
|
376
|
+
// managed group. A New Tab page is not a site-created child session.
|
|
377
|
+
// Use the latest snapshot because group and URL events can arrive separately.
|
|
378
|
+
tab = tabsById.get(tabId) || tab;
|
|
379
|
+
if (/^chrome:\/\/(?:newtab|new-tab-page)(?:[/?#]|$)/.test(this.tabUrl(tab))) {
|
|
380
|
+
if (this.isOwnedTab(tab) || this.designCompanionTabIds.has(tabId)) return null;
|
|
381
|
+
const group = groupsById.get(tab.groupId);
|
|
382
|
+
if (group?.title && (await this.configuredWorkspace(group.title)).entry) {
|
|
383
|
+
const current = await this.chrome.tabs.get(tabId);
|
|
384
|
+
if (current.groupId === group.id && !this.isOwnedTab(current) &&
|
|
385
|
+
!this.designCompanionTabIds.has(tabId)) {
|
|
386
|
+
await this.chrome.tabs.ungroup([tabId]);
|
|
387
|
+
return { workspace: group.title, groupId: group.id, tabId, releasedUnexpected: true };
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return null;
|
|
391
|
+
}
|
|
392
|
+
|
|
375
393
|
let ancestor = Number.isInteger(openerTabId) ? tabsById.get(openerTabId) : null;
|
|
376
394
|
const visited = new Set();
|
|
377
395
|
let inherited = null;
|
package/runtime/node-daemon.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import vm from 'node:vm';
|
|
|
7
7
|
import crypto from 'node:crypto';
|
|
8
8
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
9
9
|
import { invokePlatformAction } from './platforms.mjs';
|
|
10
|
-
import {
|
|
10
|
+
import { validateExtensionCommand, diagnosticEvent, loadUserHelpers } from './user-helpers.mjs';
|
|
11
11
|
import {createSiteKeepaliveScheduler} from './site-keepalive.mjs';
|
|
12
12
|
import { PlatformQueueRegistry } from './queue-registry.mjs';
|
|
13
13
|
import { idleUrlFromIdentity, sameIdleUrl, staleSession, withinDeadline, SessionDeadlineError, endedDesignSessions } from './session-lifecycle.mjs';
|
|
@@ -15,7 +15,7 @@ import { stopMatchingSessions } from './session-control.mjs';
|
|
|
15
15
|
import { ensureManagedChrome } from './chrome.mjs';
|
|
16
16
|
import { ensureExtensionLoaded } from './extension-manager.mjs';
|
|
17
17
|
import { createManagedChromeGuard } from './managed-chrome-guard.mjs';
|
|
18
|
-
import { PROFILE_DIR, RUNTIME_DIR, assertProfileConsistency } from './config-paths.mjs';
|
|
18
|
+
import { PROFILE_DIR, RUNTIME_DIR, LOCAL_ROOT, assertProfileConsistency } from './config-paths.mjs';
|
|
19
19
|
import { DemoCapture, requireMediaCommands } from './demo-capture.mjs';
|
|
20
20
|
import { DemoEngine } from './demo-engine.mjs';
|
|
21
21
|
|
|
@@ -205,15 +205,14 @@ const managedChromeGuard=createManagedChromeGuard(guardManagedChrome,{
|
|
|
205
205
|
});
|
|
206
206
|
|
|
207
207
|
function adoptPopup(info){if(info?.type!=='page'||!info.openerId)return;const owner=targets.get(info.openerId);if(owner){owner.targets.add(info.targetId);targets.set(info.targetId,owner)}}
|
|
208
|
-
async function attach(s,targetId,b=null){b ||= await connectBrowser();const {sessionId}=await b.send('Target.attachToTarget',{targetId,flatten:true});s.targets.add(targetId);s.attachments.set(targetId,sessionId);targets.set(targetId,s);for(const d of ['Page','DOM','Runtime','Network'])await b.send(`${d}.enable`,{},sessionId);for(const dispose of s.eventDisposers?.get(targetId)||[])dispose();const removers=[];for(const method of ['Page.loadEventFired','Page.domContentEventFired','Page.javascriptDialogOpening','Page.javascriptDialogClosed','Runtime.exceptionThrown','Network.requestWillBeSent','Network.responseReceived'])removers.push(b.on(method,(params,owner)=>{if(owner===sessionId){if(s.events.length>=500)s.events.shift();s.events.push({method,params
|
|
208
|
+
async function attach(s,targetId,b=null){b ||= await connectBrowser();const {sessionId}=await b.send('Target.attachToTarget',{targetId,flatten:true});s.targets.add(targetId);s.attachments.set(targetId,sessionId);targets.set(targetId,s);for(const d of ['Page','DOM','Runtime','Network'])await b.send(`${d}.enable`,{},sessionId);for(const dispose of s.eventDisposers?.get(targetId)||[])dispose();const removers=[];for(const method of ['Page.loadEventFired','Page.domContentEventFired','Page.javascriptDialogOpening','Page.javascriptDialogClosed','Runtime.exceptionThrown','Network.requestWillBeSent','Network.responseReceived','Network.loadingFailed','Network.loadingFinished'])removers.push(b.on(method,(params,owner)=>{if(owner===sessionId){if(s.events.length>=500)s.events.shift();const safe=diagnosticEvent(method,params);if(safe)s.events.push({method,params:safe,target_id:targetId})}}));s.eventDisposers?.set(targetId,removers);return sessionId}
|
|
209
209
|
function sidFor(s,targetId=s.targetId){const sid=s.attachments.get(targetId);if(!sid)throw new Error(`target ${targetId} is not attached to this session`);return sid}
|
|
210
210
|
async function evaluate(s,expression,targetId=s.targetId,awaitPromise=true){if(s.poisoned || s.closing)throw Error('Session execution expired or closing');if(!s.targets.has(targetId))throw Error('cannot evaluate a target outside the active WebHelm session');const b=await connectBrowser();if(s.poisoned || s.closing)throw Error('Session execution expired or closing');const r=await b.send('Runtime.evaluate',{expression,returnByValue:true,awaitPromise,userGesture:true},sidFor(s,targetId));if(r.exceptionDetails)throw new Error(r.exceptionDetails.exception?.description||r.exceptionDetails.text);return r.result?.value}
|
|
211
211
|
async function cdp(s,method,params={},targetId=s.targetId){if(s.poisoned || s.closing)throw Error('Session execution expired or closing');if(method==='Target.createTarget')throw Error('Target.createTarget is disabled; use new_tab(url)');if(method==='Target.attachToTarget'||method==='Target.detachFromTarget')throw Error('direct target attachment changes are disabled in WebHelm sessions');if(['Target.closeTarget','Target.activateTarget'].includes(method)&&!s.targets.has(params.targetId))throw Error('cannot operate on a tab outside the active WebHelm session');return connectBrowser().then(browser=>{if(s.poisoned || s.closing)throw Error('Session execution expired or closing');if(method.startsWith('Target.')||method.startsWith('Browser.')||method.startsWith('ServiceWorker.'))return browser.send(method,params);return browser.send(method,params,sidFor(s,targetId));})}
|
|
212
|
-
function makeHelpers(s
|
|
212
|
+
function makeHelpers(s){
|
|
213
213
|
const h={
|
|
214
214
|
js:(expression,target_id)=>evaluate(s,expression,target_id||s.targetId),
|
|
215
|
-
|
|
216
|
-
async goto_url(url){await cdp(s,'Page.navigate',{url});await h.wait_for_load();return h.page_info()},
|
|
215
|
+
async goto_url(url,{wait=true}={}){await cdp(s,'Page.navigate',{url});if(wait)await h.wait_for_load();return h.page_info()},
|
|
217
216
|
async current_tab(){const info=await cdp(s,'Target.getTargetInfo',{targetId:s.targetId});return info.targetInfo},
|
|
218
217
|
async new_tab(url='about:blank') {
|
|
219
218
|
const browser=await connectBrowser();
|
|
@@ -242,6 +241,7 @@ function makeHelpers(s, observers=null){
|
|
|
242
241
|
return leaseMutex(s.workspace).run(async()=>{
|
|
243
242
|
const browser=await connectBrowser();
|
|
244
243
|
if(s.poisoned || s.closing)throw Error('Session execution expired or closing');
|
|
244
|
+
await removeInitScripts(s,tid);
|
|
245
245
|
if(s.leasedTabs.has(tid))await navigateIdle(browser,s,tid,s.idleUrls.get(tid));
|
|
246
246
|
else await browser.send('Target.closeTarget',{targetId:tid}); // Popup without pool slot.
|
|
247
247
|
const attachment=s.attachments.get(tid);
|
|
@@ -277,13 +277,60 @@ function makeHelpers(s, observers=null){
|
|
|
277
277
|
async wait(seconds){return delay(seconds*1000)},
|
|
278
278
|
async sleep(milliseconds){return delay(milliseconds)},
|
|
279
279
|
async type_text(text){return cdp(s,'Input.insertText',{text:String(text)})},
|
|
280
|
-
async
|
|
281
|
-
|
|
280
|
+
async press_key(key){
|
|
281
|
+
const codes={Escape:27,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,Enter:13,Tab:9,Backspace:8,Delete:46};
|
|
282
|
+
if(!Object.hasOwn(codes,key))throw Error('unsupported key');
|
|
283
|
+
const p={key,code:key,windowsVirtualKeyCode:codes[key]};
|
|
284
|
+
await cdp(s,'Input.dispatchKeyEvent',{...p,type:'keyDown'});
|
|
285
|
+
await cdp(s,'Input.dispatchKeyEvent',{...p,type:'keyUp'});
|
|
286
|
+
},
|
|
287
|
+
async upload_file(selector, filename,{deep=false,sha256}={}){
|
|
288
|
+
const files=(Array.isArray(filename)?filename:[filename]).map(f=>path.resolve(f));
|
|
289
|
+
if(!files.length||files.some(f=>!fs.statSync(f).isFile()))throw Error('invalid upload files');
|
|
282
290
|
const root=await cdp(s,'DOM.getDocument',{depth:-1});
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
291
|
+
let {nodeId}=await cdp(s,'DOM.querySelector',{nodeId:root.root.nodeId,selector});
|
|
292
|
+
let searchId;
|
|
293
|
+
try {
|
|
294
|
+
if(!nodeId&&deep){
|
|
295
|
+
const search=await cdp(s,'DOM.performSearch',{query:selector});
|
|
296
|
+
searchId=search.searchId;
|
|
297
|
+
if(search.resultCount!==1)throw Error('file input search must match exactly one element');
|
|
298
|
+
const found=await cdp(s,'DOM.getSearchResults',{searchId,fromIndex:0,toIndex:1});
|
|
299
|
+
nodeId=found.nodeIds?.[0];
|
|
300
|
+
}
|
|
301
|
+
if(!nodeId)throw Error('upload input not found: '+selector);
|
|
302
|
+
if(sha256!==undefined){
|
|
303
|
+
if(files.length!==1||!/^([a-f0-9]{64})$/i.test(sha256))throw Error('invalid upload hash');
|
|
304
|
+
const observed=crypto.createHash('sha256').update(fs.readFileSync(files[0])).digest('hex');
|
|
305
|
+
if(observed!==sha256.toLowerCase())throw Error('upload_media_hash_mismatch');
|
|
306
|
+
}
|
|
307
|
+
await cdp(s,'DOM.setFileInputFiles',{nodeId,files});
|
|
308
|
+
return {uploaded:true};
|
|
309
|
+
} finally {if(searchId)await cdp(s,'DOM.discardSearchResults',{searchId}).catch(()=>{});}
|
|
310
|
+
},
|
|
311
|
+
async add_init_script(source){
|
|
312
|
+
const target=s.targetId;
|
|
313
|
+
const r=await cdp(s,'Page.addScriptToEvaluateOnNewDocument',{source:String(source)},target);
|
|
314
|
+
if(!r.identifier)throw Error('init script registration not confirmed');
|
|
315
|
+
if(!s.initScripts.has(target))s.initScripts.set(target,new Set());
|
|
316
|
+
s.initScripts.get(target).add(r.identifier);
|
|
317
|
+
return {registered:true};
|
|
318
|
+
},
|
|
319
|
+
async list_frames(){
|
|
320
|
+
const result=await cdp(s,'Page.getFrameTree');
|
|
321
|
+
const out=[];
|
|
322
|
+
const visit=t=>{if(t?.frame)out.push({id:t.frame.id,url:t.frame.url});for(const c of t?.childFrames||[])visit(c);};
|
|
323
|
+
visit(result.frameTree);
|
|
324
|
+
return out;
|
|
325
|
+
},
|
|
326
|
+
async js_in_frame(frameId,expression){
|
|
327
|
+
const target=s.targetId;
|
|
328
|
+
if(!(await h.list_frames()).some(f=>f.id===frameId)||target!==s.targetId)
|
|
329
|
+
throw Error('frame outside active Session target');
|
|
330
|
+
const world=await cdp(s,'Page.createIsolatedWorld',{frameId,worldName:'webhelm-frame'},target);
|
|
331
|
+
const r=await cdp(s,'Runtime.evaluate',{expression:String(expression),contextId:world.executionContextId,returnByValue:true,awaitPromise:true},target);
|
|
332
|
+
if(r.exceptionDetails)throw Error(r.exceptionDetails.text||'frame evaluation failed');
|
|
333
|
+
return r.result?.value;
|
|
287
334
|
},
|
|
288
335
|
async list_tabs(){
|
|
289
336
|
const {targetInfos=[]}=await connectBrowser().then(b=>b.send('Target.getTargets'));
|
|
@@ -301,27 +348,15 @@ function makeHelpers(s, observers=null){
|
|
|
301
348
|
if (!s.targets.has(tid)) throw Error('cannot activate a tab outside the active WebHelm session');
|
|
302
349
|
return cdp(s,'Target.activateTarget',{targetId:tid});
|
|
303
350
|
},
|
|
304
|
-
|
|
305
|
-
async observe_network(options){
|
|
306
|
-
if(!observers||observers.closed)throw Error('observe_network requires an active Platform Action');
|
|
307
|
-
const target=s.targetId, browser=await connectBrowser();
|
|
308
|
-
if(observers.closed||s.closing||s.poisoned||target!==s.targetId)throw Error('network observer target unavailable');
|
|
309
|
-
const attachment=sidFor(s,target);
|
|
310
|
-
await browser.send('Network.enable',{maxTotalBufferSize:16000000,maxResourceBufferSize:2000000,maxPostDataSize:32768},attachment);
|
|
311
|
-
if(observers.closed||s.closing||s.poisoned||target!==s.targetId)throw Error('network observer target unavailable');
|
|
312
|
-
const observer=observeNetwork(browser,attachment,options);
|
|
313
|
-
observers.items.add(observer);
|
|
314
|
-
return observer;
|
|
315
|
-
},
|
|
316
|
-
events(){const e=s.events.splice(0);return e},
|
|
351
|
+
events(){const e=s.events.filter(e=>e.target_id===s.targetId);s.events=s.events.filter(e=>e.target_id!==s.targetId);return e},
|
|
317
352
|
async current_url(){return (await h.page_info()).url},
|
|
318
353
|
async title(){return (await h.page_info()).title}
|
|
319
354
|
};
|
|
320
355
|
// Revoke even helper references retained by unresolved async VM scripts.
|
|
321
356
|
// A rejected async VM execution does not cancel browser operations it
|
|
322
357
|
// already started. Keep their tab ownership until those operations settle.
|
|
323
|
-
const effectHelpers=new Set(['js','
|
|
324
|
-
'click','capture_screenshot','snapshot','type_text','upload_file','switch_tab','activate_tab'
|
|
358
|
+
const effectHelpers=new Set(['js','goto_url','new_tab','close_tab','fill_input','press_key','add_init_script','list_frames','js_in_frame',
|
|
359
|
+
'click','capture_screenshot','snapshot','type_text','upload_file','switch_tab','activate_tab']);
|
|
325
360
|
for(const [name,helper] of Object.entries(h)){
|
|
326
361
|
if(typeof helper!=='function')continue;
|
|
327
362
|
h[name]=(...args)=>{
|
|
@@ -338,6 +373,44 @@ function makeHelpers(s, observers=null){
|
|
|
338
373
|
return h;
|
|
339
374
|
}
|
|
340
375
|
|
|
376
|
+
async function makeExtendedHelpers(s){
|
|
377
|
+
const h=makeHelpers(s);
|
|
378
|
+
const custom=await loadUserHelpers(path.join(LOCAL_ROOT,'helpers'),h,async(execute,args)=>{
|
|
379
|
+
if(s.poisoned||s.closing)throw Error('Session execution expired or closing');
|
|
380
|
+
const target=s.targetId;
|
|
381
|
+
let active=true;
|
|
382
|
+
const check=()=>{
|
|
383
|
+
if(!active||s.poisoned||s.closing||s.targetId!==target||!s.targets.has(target))
|
|
384
|
+
throw Error('user helper capability expired');
|
|
385
|
+
};
|
|
386
|
+
const broker=Object.freeze({
|
|
387
|
+
async cdp(method,params={}){
|
|
388
|
+
check();params=JSON.parse(JSON.stringify(params));validateExtensionCommand(method,params);
|
|
389
|
+
s.pendingEffects++;
|
|
390
|
+
try {
|
|
391
|
+
const result=await cdp(s,method,params,target);
|
|
392
|
+
check();return result;
|
|
393
|
+
} finally{s.pendingEffects--;}
|
|
394
|
+
},
|
|
395
|
+
events(){check();return h.events();},
|
|
396
|
+
});
|
|
397
|
+
s.pendingEffects++;
|
|
398
|
+
try{return await execute(broker,...args);}
|
|
399
|
+
finally{active=false;s.pendingEffects--;}
|
|
400
|
+
});
|
|
401
|
+
Object.assign(h,custom);
|
|
402
|
+
return h;
|
|
403
|
+
}
|
|
404
|
+
async function removeInitScripts(s,target){
|
|
405
|
+
const ids=s.initScripts?.get(target);
|
|
406
|
+
if(!ids)return;
|
|
407
|
+
// Cleanup uses the internal transport even while a Session is closing.
|
|
408
|
+
const browser=await connectBrowser();
|
|
409
|
+
for(const identifier of ids)
|
|
410
|
+
await browser.send('Page.removeScriptToEvaluateOnNewDocument',{identifier},sidFor(s,target));
|
|
411
|
+
s.initScripts.delete(target);
|
|
412
|
+
}
|
|
413
|
+
|
|
341
414
|
function demoTransport(s) {
|
|
342
415
|
return {
|
|
343
416
|
get viewport() { return s.demoViewport || { width: 0, height: 0 }; },
|
|
@@ -590,7 +663,7 @@ async function createSession(req={}) {
|
|
|
590
663
|
const sid=crypto.randomBytes(8).toString('hex');
|
|
591
664
|
const s={session_id:sid, workspace:req.workspace||await defaultWorkspaceName(), targetId:null,
|
|
592
665
|
rootTargetId:null, workspaceSupported:false,targets:new Set(), attachments:new Map(), eventDisposers:new Map(),
|
|
593
|
-
leasedTabs:new Map(), idleUrls:new Map(), mutex:new Mutex(), events:[], namespace:null,context:null,
|
|
666
|
+
leasedTabs:new Map(), idleUrls:new Map(), initScripts:new Map(), mutex:new Mutex(), events:[], namespace:null,context:null,
|
|
594
667
|
inFlight:0, pendingEffects:0, closing:false, poisoned:false, last_used_at:Date.now(), snapshotGeneration:0, snapshotTargetId:null};
|
|
595
668
|
let targetId,lease;
|
|
596
669
|
try {
|
|
@@ -608,7 +681,7 @@ async function createSession(req={}) {
|
|
|
608
681
|
await attach(s,targetId);
|
|
609
682
|
if(req.url && req.url!=='about:blank')await browser.send('Page.navigate',{url:req.url},sidFor(s,targetId));
|
|
610
683
|
else if (lease) await browser.send('Page.navigate',{url:'about:blank'},sidFor(s,targetId));
|
|
611
|
-
const h=
|
|
684
|
+
const h=await makeExtendedHelpers(s);
|
|
612
685
|
s.namespace={...h,helpers:h,session_id:sid};
|
|
613
686
|
s.context=vm.createContext(s.namespace);
|
|
614
687
|
sessions.set(sid,s);
|
|
@@ -775,6 +848,7 @@ async function closeSessionOwned(s){
|
|
|
775
848
|
const browser=await connectBrowser();
|
|
776
849
|
// Return managed tabs to their original Extension pool; keep their CDP targets.
|
|
777
850
|
for(const tid of [...s.targets]){
|
|
851
|
+
if(s.attachments.has(tid))await removeInitScripts(s,tid);
|
|
778
852
|
if(s.leasedTabs.has(tid)){
|
|
779
853
|
await navigateIdle(browser,s,tid,s.idleUrls.get(tid));
|
|
780
854
|
} else {
|
|
@@ -993,8 +1067,7 @@ async function runPlatform(req) {
|
|
|
993
1067
|
result=await session.mutex.run(async()=>{
|
|
994
1068
|
if(session.poisoned||session.closing)throw Error('Session expired while waiting for platform action');
|
|
995
1069
|
const logs=[];
|
|
996
|
-
const
|
|
997
|
-
const helpers=makeHelpers(session,observers);
|
|
1070
|
+
const helpers=await makeExtendedHelpers(session);
|
|
998
1071
|
try {
|
|
999
1072
|
const actionTimeoutMs=Math.max(50,Math.min(300000,Number(process.env.WEBHELM_PLATFORM_TIMEOUT_MS)||180000));
|
|
1000
1073
|
const value=await withinDeadline(Promise.resolve().then(()=>invokePlatformAction(platform,action,{
|
|
@@ -1008,7 +1081,7 @@ async function runPlatform(req) {
|
|
|
1008
1081
|
} catch(error) {
|
|
1009
1082
|
if(error instanceof SessionDeadlineError)session.poisoned=true;
|
|
1010
1083
|
return {ok:false,stdout:logs.join('\n').slice(-40000),stderr:'',error:`${error.name}: ${error.message}`};
|
|
1011
|
-
}
|
|
1084
|
+
}
|
|
1012
1085
|
});
|
|
1013
1086
|
} finally {
|
|
1014
1087
|
session.inFlight--;session.last_used_at=Date.now();
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {pathToFileURL} from 'node:url';
|
|
4
|
+
|
|
5
|
+
// The public extension broker is deliberately separate from the private
|
|
6
|
+
// Runtime CDP transport. Browser-wide or ownership-changing commands are
|
|
7
|
+
// forbidden even when Chrome would accept them on a page attachment.
|
|
8
|
+
const forbiddenDomains = new Set([
|
|
9
|
+
'Target','Browser','ServiceWorker','Storage','Fetch','Security','Extensions',
|
|
10
|
+
'SystemInfo','IO','Tracing','Debugger','Runtime','Input','Emulation','DOMStorage',
|
|
11
|
+
]);
|
|
12
|
+
const allowedMethods = new Set([
|
|
13
|
+
'Page.getLayoutMetrics','Page.getNavigationHistory','Performance.getMetrics',
|
|
14
|
+
'DOM.getDocument','DOM.describeNode','DOM.getBoxModel','DOM.getOuterHTML',
|
|
15
|
+
'DOM.querySelector','DOM.querySelectorAll','Accessibility.getFullAXTree',
|
|
16
|
+
]);
|
|
17
|
+
const forbiddenMethods = new Set([
|
|
18
|
+
'Page.navigate','Page.close','Page.bringToFront','Page.setWebLifecycleState',
|
|
19
|
+
'Page.addScriptToEvaluateOnNewDocument','Page.removeScriptToEvaluateOnNewDocument',
|
|
20
|
+
'DOM.setFileInputFiles','Network.getResponseBody','Network.getRequestPostData',
|
|
21
|
+
'Network.getCookies','Network.getAllCookies','Network.setCookie','Network.setCookies',
|
|
22
|
+
'Network.setExtraHTTPHeaders','Network.setBlockedURLs',
|
|
23
|
+
]);
|
|
24
|
+
export function validateExtensionCommand(method,params={}){
|
|
25
|
+
if(typeof method!=='string'||forbiddenDomains.has(method.split('.')[0])||
|
|
26
|
+
forbiddenMethods.has(method)||!allowedMethods.has(method))
|
|
27
|
+
throw Error('WebHelm extension CDP command prohibited');
|
|
28
|
+
if(!params||typeof params!=='object'||Array.isArray(params))
|
|
29
|
+
throw Error('CDP parameters must be an object');
|
|
30
|
+
for(const key of ['targetId','sessionId','browserContextId','objectId','backendNodeId','executionContextId','frameId'])
|
|
31
|
+
if(Object.hasOwn(params,key))throw Error('CDP target/context override prohibited');
|
|
32
|
+
return method;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Only bounded diagnostics, never headers, request payloads, bodies, full
|
|
36
|
+
// URLs or credentials. Request IDs are opaque and scoped by the Runtime.
|
|
37
|
+
export function diagnosticEvent(method,p={}){
|
|
38
|
+
const finite=v=>Number.isFinite(v)?v:undefined;
|
|
39
|
+
const str=v=>typeof v==='string'?v.slice(0,120):undefined;
|
|
40
|
+
if(method==='Network.requestWillBeSent')return {requestId:str(p.requestId),
|
|
41
|
+
type:str(p.type),method:str(p.request?.method),timestamp:finite(p.timestamp)};
|
|
42
|
+
if(method==='Network.responseReceived')return {requestId:str(p.requestId),
|
|
43
|
+
type:str(p.type),status:finite(p.response?.status),mimeType:str(p.response?.mimeType),timestamp:finite(p.timestamp)};
|
|
44
|
+
if(method==='Network.loadingFailed')return {requestId:str(p.requestId),
|
|
45
|
+
type:str(p.type),canceled:!!p.canceled,timestamp:finite(p.timestamp)};
|
|
46
|
+
if(method==='Network.loadingFinished')return {requestId:str(p.requestId),
|
|
47
|
+
encodedDataLength:finite(p.encodedDataLength),timestamp:finite(p.timestamp)};
|
|
48
|
+
if(method==='Page.loadEventFired'||method==='Page.domContentEventFired')
|
|
49
|
+
return {timestamp:finite(p.timestamp)};
|
|
50
|
+
if(method==='Runtime.exceptionThrown')return {timestamp:finite(p.timestamp)};
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// These are explicitly installed local, trusted JavaScript modules, not
|
|
55
|
+
// downloaded site scripts. Node modules themselves are not a security
|
|
56
|
+
// sandbox; the broker enforces WebHelm rules on all supplied capabilities.
|
|
57
|
+
export async function loadUserHelpers(dir,builtins,broker){
|
|
58
|
+
if(!fs.existsSync(dir))return {};
|
|
59
|
+
const result=Object.create(null);
|
|
60
|
+
for(const entry of fs.readdirSync(dir,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){
|
|
61
|
+
if(!entry.isFile()||!/^[_a-z][a-z0-9_-]*\.mjs$/.test(entry.name))continue;
|
|
62
|
+
const file=path.join(dir,entry.name), stat=fs.statSync(file);
|
|
63
|
+
const module=await import(pathToFileURL(file).href+'?mtime='+stat.mtimeMs+'-'+stat.size);
|
|
64
|
+
const def=module.default;
|
|
65
|
+
if(!def||!/^[_a-z][a-z0-9_]*$/.test(def.name)||typeof def.execute!=='function'||
|
|
66
|
+
typeof def.name!=='string'||def.name in builtins||def.name in result||
|
|
67
|
+
['__proto__','prototype','constructor','helpers','console','session_id','globalThis','process','require'].includes(def.name))
|
|
68
|
+
throw Error('Invalid or conflicting user helper: '+entry.name);
|
|
69
|
+
result[def.name]=(...args)=>broker(def.execute,args);
|
|
70
|
+
}
|
|
71
|
+
return result;
|
|
72
|
+
}
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
// Generic, bounded, per-CDP-session response observer. No platform-specific
|
|
2
|
-
// endpoints or identifiers here. Never persist request/response bodies.
|
|
3
|
-
export function observeNetwork(browser, sessionId, {url, method='POST'}={}) {
|
|
4
|
-
if(typeof url!=='string'||!/^https:\/\//.test(url)||typeof method!=='string')
|
|
5
|
-
throw new TypeError('observe_network requires an exact HTTPS URL and HTTP method');
|
|
6
|
-
const maxBytes=256*1024, records=new Map(), removers=[];
|
|
7
|
-
let armed=false,closed=false,overflow=false;
|
|
8
|
-
const on=(name,fn)=>removers.push(browser.on(name,(p,owner)=>{
|
|
9
|
-
if(!closed&&armed&&owner===sessionId){try{fn(p)}catch{}}
|
|
10
|
-
}));
|
|
11
|
-
const append=(rec,data,initial=false)=>{
|
|
12
|
-
if(closed||typeof data!=='string'||!data)return;
|
|
13
|
-
const bytes=Buffer.from(data,'base64');
|
|
14
|
-
if(rec.bytes+bytes.length>maxBytes){rec.truncated=true;return}
|
|
15
|
-
rec.bytes+=bytes.length;
|
|
16
|
-
if(initial)rec.chunks.unshift(bytes);else rec.chunks.push(bytes);
|
|
17
|
-
};
|
|
18
|
-
on('Network.requestWillBeSent',p=>{
|
|
19
|
-
if(records.has(p.requestId)){records.get(p.requestId).ambiguous=true;return}
|
|
20
|
-
if(p.request?.url!==url||p.request?.method!==method)return;
|
|
21
|
-
if(records.size>=4){overflow=true;return}
|
|
22
|
-
const rec={requestId:p.requestId,postData:typeof p.request.postData==='string'&&p.request.postData.length<=32768?p.request.postData:null,
|
|
23
|
-
status:null,mime:null,ambiguous:false,truncated:false,bytes:0,chunks:[],body:null};
|
|
24
|
-
records.set(p.requestId,rec);
|
|
25
|
-
if(rec.postData===null&&p.request.hasPostData)void browser.send('Network.getRequestPostData',{requestId:p.requestId},sessionId).then(r=>{
|
|
26
|
-
if(!closed&&typeof r.postData==='string'&&r.postData.length<=32768)rec.postData=r.postData;
|
|
27
|
-
}).catch(()=>{});
|
|
28
|
-
});
|
|
29
|
-
on('Network.responseReceived',p=>{
|
|
30
|
-
const rec=records.get(p.requestId);if(!rec)return;
|
|
31
|
-
rec.status=p.response?.status;rec.mime=p.response?.mimeType;
|
|
32
|
-
if(p.response?.url!==url){rec.ambiguous=true;return}
|
|
33
|
-
if(rec.status<200||rec.status>=300||!/(?:event-stream|ndjson)/i.test(rec.mime||''))return;
|
|
34
|
-
void browser.send('Network.streamResourceContent',{requestId:p.requestId},sessionId).then(r=>append(rec,r.bufferedData,true)).catch(()=>{});
|
|
35
|
-
});
|
|
36
|
-
on('Network.dataReceived',p=>{const rec=records.get(p.requestId);if(rec)append(rec,p.data)});
|
|
37
|
-
on('Network.loadingFinished',p=>{
|
|
38
|
-
const rec=records.get(p.requestId);
|
|
39
|
-
if(!rec||rec.status<200||rec.status>=300||!/(?:event-stream|ndjson)/i.test(rec.mime||''))return;
|
|
40
|
-
void browser.send('Network.getResponseBody',{requestId:p.requestId},sessionId).then(r=>{
|
|
41
|
-
if(closed||typeof r.body!=='string')return;
|
|
42
|
-
const bytes=Buffer.from(r.body,r.base64Encoded?'base64':'utf8');
|
|
43
|
-
if(bytes.length<=maxBytes)rec.body=bytes.toString('utf8');
|
|
44
|
-
}).catch(()=>{});
|
|
45
|
-
});
|
|
46
|
-
return {
|
|
47
|
-
arm(){if(closed)throw Error('network observer closed');if(armed)throw Error('network observer already armed');armed=true},
|
|
48
|
-
snapshot(){
|
|
49
|
-
if(closed)return {overflow:true,requests:[]};
|
|
50
|
-
return {overflow,requests:[...records.values()].map(r=>({request_id:r.requestId,post_data:r.postData,status:r.status,mime:r.mime,
|
|
51
|
-
ambiguous:r.ambiguous,truncated:r.truncated,body:r.body??Buffer.concat(r.chunks).toString('utf8')}))};
|
|
52
|
-
},
|
|
53
|
-
close(){if(closed)return;closed=true;for(const off of removers)off();records.clear()}
|
|
54
|
-
};
|
|
55
|
-
}
|