webhelm 1.0.53 → 1.0.54
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/package.json
CHANGED
|
@@ -0,0 +1,55 @@
|
|
|
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
|
+
}
|
package/runtime/node-daemon.mjs
CHANGED
|
@@ -7,6 +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 { observeNetwork } from './network-observer.mjs';
|
|
10
11
|
import {createSiteKeepaliveScheduler} from './site-keepalive.mjs';
|
|
11
12
|
import { PlatformQueueRegistry } from './queue-registry.mjs';
|
|
12
13
|
import { idleUrlFromIdentity, sameIdleUrl, staleSession, withinDeadline, SessionDeadlineError, endedDesignSessions } from './session-lifecycle.mjs';
|
|
@@ -206,7 +207,7 @@ async function attach(s,targetId,b=null){b ||= await connectBrowser();const {ses
|
|
|
206
207
|
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}
|
|
207
208
|
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}
|
|
208
209
|
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));})}
|
|
209
|
-
function makeHelpers(s){
|
|
210
|
+
function makeHelpers(s, observers=null){
|
|
210
211
|
const h={
|
|
211
212
|
js:(expression,target_id)=>evaluate(s,expression,target_id||s.targetId),
|
|
212
213
|
cdp:(method,params={})=>cdp(s,method,params),
|
|
@@ -298,6 +299,18 @@ function makeHelpers(s){
|
|
|
298
299
|
if (!s.targets.has(tid)) throw Error('cannot activate a tab outside the active WebHelm session');
|
|
299
300
|
return cdp(s,'Target.activateTarget',{targetId:tid});
|
|
300
301
|
},
|
|
302
|
+
// Available only to Platform Actions; the runner always closes observers.
|
|
303
|
+
async observe_network(options){
|
|
304
|
+
if(!observers||observers.closed)throw Error('observe_network requires an active Platform Action');
|
|
305
|
+
const target=s.targetId, browser=await connectBrowser();
|
|
306
|
+
if(observers.closed||s.closing||s.poisoned||target!==s.targetId)throw Error('network observer target unavailable');
|
|
307
|
+
const attachment=sidFor(s,target);
|
|
308
|
+
await browser.send('Network.enable',{maxTotalBufferSize:16000000,maxResourceBufferSize:2000000,maxPostDataSize:32768},attachment);
|
|
309
|
+
if(observers.closed||s.closing||s.poisoned||target!==s.targetId)throw Error('network observer target unavailable');
|
|
310
|
+
const observer=observeNetwork(browser,attachment,options);
|
|
311
|
+
observers.items.add(observer);
|
|
312
|
+
return observer;
|
|
313
|
+
},
|
|
301
314
|
events(){const e=s.events.splice(0);return e},
|
|
302
315
|
async current_url(){return (await h.page_info()).url},
|
|
303
316
|
async title(){return (await h.page_info()).title}
|
|
@@ -306,7 +319,7 @@ function makeHelpers(s){
|
|
|
306
319
|
// A rejected async VM execution does not cancel browser operations it
|
|
307
320
|
// already started. Keep their tab ownership until those operations settle.
|
|
308
321
|
const effectHelpers=new Set(['js','cdp','goto_url','new_tab','close_tab','fill_input',
|
|
309
|
-
'click','capture_screenshot','snapshot','type_text','upload_file','switch_tab','activate_tab']);
|
|
322
|
+
'click','capture_screenshot','snapshot','type_text','upload_file','switch_tab','activate_tab','observe_network']);
|
|
310
323
|
for(const [name,helper] of Object.entries(h)){
|
|
311
324
|
if(typeof helper!=='function')continue;
|
|
312
325
|
h[name]=(...args)=>{
|
|
@@ -816,7 +829,8 @@ async function runPlatform(req) {
|
|
|
816
829
|
result=await session.mutex.run(async()=>{
|
|
817
830
|
if(session.poisoned||session.closing)throw Error('Session expired while waiting for platform action');
|
|
818
831
|
const logs=[];
|
|
819
|
-
const
|
|
832
|
+
const observers={closed:false,items:new Set()};
|
|
833
|
+
const helpers=makeHelpers(session,observers);
|
|
820
834
|
try {
|
|
821
835
|
const actionTimeoutMs=Math.max(50,Math.min(300000,Number(process.env.WEBHELM_PLATFORM_TIMEOUT_MS)||180000));
|
|
822
836
|
const value=await withinDeadline(Promise.resolve().then(()=>invokePlatformAction(platform,action,{
|
|
@@ -830,7 +844,7 @@ async function runPlatform(req) {
|
|
|
830
844
|
} catch(error) {
|
|
831
845
|
if(error instanceof SessionDeadlineError)session.poisoned=true;
|
|
832
846
|
return {ok:false,stdout:logs.join('\n').slice(-40000),stderr:'',error:`${error.name}: ${error.message}`};
|
|
833
|
-
}
|
|
847
|
+
} finally { observers.closed=true;for(const observer of observers.items)observer.close(); observers.items.clear(); }
|
|
834
848
|
});
|
|
835
849
|
} finally {
|
|
836
850
|
session.inFlight--;session.last_used_at=Date.now();
|