@lordesteph/openvegas-selected-tab 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.
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # OpenVegas selected-tab preview
2
+ The visual pointer adapts the quadratic flight, distance scaling and smoothstep timing from Farza's MIT-licensed [public Clicky overlay](https://github.com/farzaa/clicky/blob/e71105ce091d71dff4d89cf5d8d37ea1df460961/leanring-buddy/OverlayWindow.swift). The pointer stays inside the selected document and honors reduced motion. See `extension/LICENSE-Clicky.txt`. This is not the private HeyClicky product. No upstream analytics, hosted services, audio, keys, or branded media are included.
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ Ordinary search and the default isolated browser do not use this connector or extension. This preview lets the terminal ask for visible text or one click inside a single Chrome document. No OpenClaw, browser debugger, customer API key or browser-wide site access. Only text and labels you approve are returned to Codex and may be sent to its model.
5
+
6
+ For a local preview, export the extension into a new directory with the package's `--extension PATH` command. Load that directory in Chrome's extension developer UI only if you are testing this source. Do not turn on developer mode on a managed or customer machine to bypass policy. Add the connector to a trusted project's Codex MCP configuration with `--stdio` and prompt approval; leave the isolated browser as the default. No settings are written for you.
7
+
8
+ Ask Codex to start selected-tab sharing. Copy the session code from the local pairing page, switch to the exact tab you intend to share, then click the OpenVegas extension icon. Paste the code there, never into chat. Keep the small approval window open. Approve a read to share the preview and its controls, then approve or refuse each requested click. Closing the approval window or stopping the connector ends sharing; a new document requires a new grant. A click can change your account on that site: do not approve a purchase or destructive action you do not intend. No password entry, form submission tools, other tabs or frames.
package/cli.mjs ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ import {createInterface} from 'node:readline';
3
+ import {fileURLToPath} from 'node:url';
4
+ import {cp,mkdir} from 'node:fs/promises';
5
+ import {resolve} from 'node:path';
6
+ import {spawn} from 'node:child_process';
7
+ import {newSession} from './session.mjs';
8
+
9
+ const path=fileURLToPath(new URL('./extension/',import.meta.url));
10
+ const none={type:'object',properties:{},additionalProperties:false};
11
+ const tools=[
12
+ {name:'start',description:'Only on an explicit request to share a signed-in tab. Opens a local pairing screen. Ordinary web search and isolated browsing do not use this.',inputSchema:none},
13
+ {name:'read',description:'Ask the owner to preview and send bounded visible text and control references from the selected document.',inputSchema:none},
14
+ {name:'click',description:'Ask the owner to approve one click on a visible control from the latest approved read. Never retry a click automatically.',inputSchema:{type:'object',properties:{ref:{type:'string'}},required:['ref'],additionalProperties:false}},
15
+ {name:'stop',description:'End the selected-tab session.',inputSchema:none},
16
+ ];
17
+ function openLocal(url){
18
+ const [bin,...args]=process.platform==='darwin'?['/usr/bin/open',url]:process.platform==='win32'?['rundll32.exe','url.dll,FileProtocolHandler',url]:['xdg-open',url];
19
+ return new Promise((ok,bad)=>{const p=spawn(bin,args,{stdio:'ignore',shell:false});p.once('error',bad);p.once('exit',n=>n===0?ok():bad(Error('Unable to open the local pairing page.')));});
20
+ }
21
+ async function serve(){
22
+ let session,starting=false,initialized=false,requests=new Map();
23
+ const send=x=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\n');
24
+ const output=(value,isError=false)=>({content:[{type:'text',text:typeof value==='string'?value:JSON.stringify(value)}],isError});
25
+ async function call(name,args){
26
+ if(!tools.some(t=>t.name===name)||Object.keys(args).some(k=>name!=='click'||k!=='ref'))throw Error('Unsupported tab request.');
27
+ if(name==='start'){
28
+ if(starting || (session&&!session.closed))throw Error('Sharing is already pending or active. Stop it first.');
29
+ starting=true;
30
+ try{session=await newSession();await openLocal(session.invitation.url);}
31
+ catch(e){session?.close();throw e;}finally{starting=false;}
32
+ return 'Local pairing page opened. Ask the user to click the extension on their chosen tab and enter the session code there, not in chat.';
33
+ }
34
+ if(name==='stop'){session?.close();return 'Sharing stopped.';}
35
+ if(!session?.connected)throw Error('No shared tab. The user must connect the selected document.');
36
+ return session.request(name,args.ref);
37
+ }
38
+ const input=createInterface({input:process.stdin,crlfDelay:Infinity});
39
+ input.on('line',async line=>{
40
+ let m;
41
+ try{m=JSON.parse(line);}catch{return send({id:null,error:{code:-32700,message:'Invalid JSON.'}});}
42
+ if(!m||m.jsonrpc!=='2.0')return;
43
+ if(m.method==='notifications/cancelled'){if(requests.has(m.params?.requestId))session?.close();return;}
44
+ if(m.id==null)return;
45
+ try{
46
+ let result;
47
+ if(m.method==='initialize'){initialized=true;const versions=['2025-11-25','2025-06-18','2025-03-26','2024-11-05'];result={protocolVersion:versions.includes(m.params?.protocolVersion)?m.params.protocolVersion:versions[0],capabilities:{tools:{}},serverInfo:{name:'openvegas-selected-tab',version:'0.1.0'}};}
48
+ else if(!initialized)throw Error();
49
+ else if(m.method==='ping')result={};
50
+ else if(m.method==='tools/list')result={tools};
51
+ else if(m.method==='tools/call'){
52
+ requests.set(m.id,true);
53
+ try{result=output(await call(m.params.name,m.params.arguments??{}));}
54
+ catch(e){result=output(e.message||'Tab operation did not complete.',true);}
55
+ finally{requests.delete(m.id);}
56
+ }else return send({id:m.id,error:{code:-32601,message:'Unknown method.'}});
57
+ send({id:m.id,result});
58
+ }catch{send({id:m.id,error:{code:-32602,message:'Invalid request.'}});}
59
+ });
60
+ input.on('close',()=>session?.close());process.once('SIGTERM',()=>{session?.close();process.exit(0);});
61
+ }
62
+ const [cmd,dest,...extra]=process.argv.slice(2);
63
+ if(cmd==='--stdio'&&!dest)await serve();
64
+ else if(cmd==='--extension'&&dest&&!extra.length){
65
+ const target=resolve(dest);await mkdir(target,{mode:0o700});
66
+ try{await cp(path,target,{recursive:true,force:false,errorOnExist:true});}catch(e){throw e;}
67
+ console.log('Extension copied into '+target+'. No Chrome or Codex settings were changed.');
68
+ }else if(cmd==='--check'&&!dest){
69
+ const s=await newSession();s.close();console.log('Selected-tab connector available; no Chrome access requested.');
70
+ }else{
71
+ console.log('OpenVegas selected tab (optional)\n --extension NEW_DIRECTORY Export the extension for a local preview\n --stdio Run the optional Codex MCP connector\n --check Check the local connector without opening Chrome');
72
+ if(cmd)process.exitCode=2;
73
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Farza
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,10 @@
1
+ chrome.action.onClicked.addListener(async tab => {
2
+ if (!Number.isInteger(tab.id) || tab.incognito || !Number.isInteger(tab.windowId)) return;
3
+ try {
4
+ // Capture the document identity at the actual toolbar gesture, not at terminal request time.
5
+ const [r] = await chrome.scripting.executeScript({target:{tabId:tab.id,frameIds:[0]},func:()=>location.origin});
6
+ if (r.frameId !== 0 || !r.documentId || (!r.result.startsWith('https://') && !/^http:\/\/127\.0\.0\.1:\d+$/.test(r.result))) return;
7
+ const pin = new URLSearchParams({tab:String(tab.id),win:String(tab.windowId),doc:r.documentId});
8
+ await chrome.windows.create({url:chrome.runtime.getURL('popup.html')+'#'+pin, type:'popup',width:430,height:600});
9
+ } catch { /* Internal pages and closed tabs cannot be shared. */ }
10
+ });
@@ -0,0 +1,12 @@
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "OpenVegas: Share this tab",
4
+ "version": "0.1.0",
5
+ "description": "Review and approve terminal requests for the one Chrome document you choose.",
6
+ "permissions": ["activeTab", "scripting"],
7
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtK8oBA4rE325VXznEbpLEfoP9rcYYO0gAZwpCmNARz8aRjbtlW+KxBmUbVcTwgjJMgm4TAme7dOv4fDs+NZKoWKvtKzlGhlpCc9APGXnogFYvRduRrMl28kKusx6KFrenYtVoHZJbDVJFvWpWl7c7kfGcUHV//jGuUSBn+lwnIa5walZ1nsRihHJ0IKCPhwzpuCeEhZ3YpxysmeB7kzljtiguD0qp6k1SY0rEW6kV4MtLc6Yrc2bzbVWa7RFR7JHWIN84oeXPocKDwjQAUxe+jDSj7jQWBRKWCfS7FXsdWqVxRSFZzyd8ld1acy5gdwYmG7lgfxgNPlwdzo2p4ZNQQIDAQAB",
8
+ "action": {"default_title": "Share only this tab"},
9
+ "background": {"service_worker": "launch.js"},
10
+ "commands": {"_execute_action": {"suggested_key":{"default":"Alt+Shift+Y"}}},
11
+ "content_security_policy": {"extension_pages": "script-src 'self'; object-src 'none'; connect-src http://127.0.0.1:*"}
12
+ }
@@ -0,0 +1,82 @@
1
+ // Chrome serializes this function into the top document's isolated world.
2
+ // No caller-supplied script, selector, URL, tab ID, form value, or frame ID.
3
+ export function pageOperation(op, ref) {
4
+ const slot = "__openVegasSelectedControls";
5
+ const state = globalThis[slot] ??= { refs: new Map() };
6
+ if (op === "clear") { state.clearPoint?.(); return {cleared:true}; }
7
+ const visible = el => {
8
+ if (el.closest("[hidden],[inert],[aria-hidden=true],[contenteditable]:not([contenteditable=false])")) return false;
9
+ const r = el.getBoundingClientRect();
10
+ if (r.width <= 0 || r.height <= 0 || r.right <= 0 || r.bottom <= 0 || r.left >= innerWidth || r.top >= innerHeight) return false;
11
+ const s = getComputedStyle(el);
12
+ if (s.visibility !== "visible" || Number(s.opacity) === 0) return false;
13
+ const hit = document.elementFromPoint((Math.max(0,r.left)+Math.min(innerWidth,r.right))/2,(Math.max(0,r.top)+Math.min(innerHeight,r.bottom))/2);
14
+ return hit && el.contains(hit);
15
+ };
16
+ const label = el => (el.innerText || el.getAttribute("aria-label") || "").replace(/\s+/g," ").trim().slice(0,100);
17
+ const eligible = el => {
18
+ if (!el.isConnected || el.matches(":disabled,[aria-disabled=true]") || !visible(el)) return false;
19
+ if (el.localName === "button") return !el.form || el.type === "button";
20
+ if (el.localName !== "a" || el.hasAttribute("download")) return false;
21
+ try { const u = new URL(el.href); return u.origin === location.origin && !u.username && !u.password && (!el.target || el.target === "_self"); } catch { return false; }
22
+ };
23
+ if (op === "probe") return {origin:location.origin};
24
+ if (op === "read") {
25
+ state.refs.clear();
26
+ const controls = [];
27
+ for (const el of document.querySelectorAll("button,a[href]")) {
28
+ if (controls.length >= 24) break;
29
+ if (!eligible(el) || !label(el)) continue;
30
+ const id = crypto.randomUUID();
31
+ state.refs.set(id,{el,label:label(el),href:el.localName === "a" ? el.href : null});
32
+ controls.push({ref:id,label:label(el)});
33
+ }
34
+ const text = [];
35
+ let size = 0;
36
+ for (const el of document.querySelectorAll("h1,h2,h3,p,li,td,th")) {
37
+ if (size >= 2400) break;
38
+ if (!visible(el) || el.querySelector("input,textarea,select,[contenteditable],form")) continue;
39
+ const line = (el.innerText || "").trim().slice(0,2400-size);
40
+ if (line) {text.push(line);size+=line.length+1;}
41
+ }
42
+ return {title:document.title.slice(0,160),text:text.join("\n"),controls};
43
+ }
44
+ const item = state.refs.get(ref);
45
+ if (!item || !eligible(item.el) || label(item.el)!==item.label || (item.href !== null && item.el.href!==item.href))
46
+ throw Error("Control changed. Request a new view.");
47
+ if (op === "describe" || op === "point") {
48
+ state.clearPoint?.();
49
+ const box=item.el.getBoundingClientRect();
50
+ const x=Math.max(1,Math.min(innerWidth-14,box.left+box.width/2));
51
+ const y=Math.max(1,Math.min(innerHeight-14,box.top+box.height/2));
52
+ const badge=document.createElement('span');
53
+ badge.setAttribute('aria-hidden','true');badge.dataset.openvegasPoint='true';
54
+ badge.style.cssText='all:initial;position:fixed;top:0;left:0;z-index:2147483647;pointer-events:none;color:#168bfc;text-shadow:0 1px 2px #111;font:bold 18px sans-serif;white-space:nowrap';
55
+ badge.textContent='\u2196 OpenVegas';
56
+ document.documentElement.append(badge);
57
+ const dx=Math.min(140,Math.max(0,innerWidth-x-28)),dy=Math.min(85,Math.max(0,innerHeight-y-22));
58
+ const distance=Math.hypot(dx,dy),height=Math.min(distance*.2,80);
59
+ // Port of Clicky's distance-scaled, smoothstep quadratic flight, in viewport coordinates.
60
+ // Only the visual marker moves. The physical mouse and the user's focus do not.
61
+ const frames=Array.from({length:25},(_,i)=>{
62
+ const u=i/24,t=u*u*(3-2*u),k=1-t;
63
+ return {transform:'translate('+(x+k*dx)+'px,'+(y+k*dy-2*k*t*height)+'px) scale('+(1+.3*Math.sin(Math.PI*u))+')'};
64
+ });
65
+ badge.style.transform='translate('+x+'px,'+y+'px)';
66
+ if(!matchMedia('(prefers-reduced-motion: reduce)').matches)
67
+ badge.animate(frames,{duration:1000*Math.min(1.4,Math.max(.6,distance/800))});
68
+ const outline=item.el.animate([{outline:'3px solid #168bfc'},{outline:'3px solid #168bfc'}],{duration:6500});
69
+ let timer;
70
+ const remove=()=>{clearTimeout(timer);badge.remove();outline.cancel();
71
+ removeEventListener('scroll',remove,true);removeEventListener('resize',remove);removeEventListener('pagehide',remove);
72
+ if(state.clearPoint===remove)state.clearPoint=null;};
73
+ state.clearPoint=remove;timer=setTimeout(remove,6500);
74
+ addEventListener('scroll',remove,true);addEventListener('resize',remove);addEventListener('pagehide',remove);
75
+ return {kind:item.el.localName,label:item.label, destination:item.href ? new URL(item.href).origin+new URL(item.href).pathname : null};
76
+ }
77
+ if (op !== "click") throw Error("Unknown action.");
78
+ state.clearPoint?.();
79
+ state.refs.clear();
80
+ item.el.click();
81
+ return {clicked:true};
82
+ }
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en"><meta charset="utf-8"><title>OpenVegas | Share this tab</title>
3
+ <style>
4
+ :root{color-scheme:light dark;font:14px/1.45 ui-sans-serif,sans-serif}body{width:345px;margin:17px}
5
+ h1{font-size:19px;margin:0}label,p,pre{display:block;margin:10px 0}input{width:96%}pre{max-height:210px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere}
6
+ button{padding:5px 10px}button[hidden],label[hidden]{display:none}
7
+ </style>
8
+ <h1>Share only this tab</h1>
9
+ <p>OpenVegas can request visible text or a click. You approve each request here. Approved text goes into your Codex chat. Closing this popup ends sharing.</p>
10
+ <label id="pair">Session code from your terminal <input id="code" type="password" autocomplete="off" spellcheck="false"></label>
11
+ <button id="connect">Share this document</button>
12
+ <p role="status" id="status"></p><pre id="preview"></pre>
13
+ <button id="approve" hidden>Approve once</button> <button id="deny" hidden>Decline</button> <button id="stop" hidden>Stop sharing</button>
14
+ <script src="popup.js" type="module"></script></html>
@@ -0,0 +1,74 @@
1
+ import {pageOperation} from './page.js';
2
+ const $ = id => document.getElementById(id);
3
+ const pin=new URLSearchParams(location.hash.slice(1));
4
+ history.replaceState(null,'','popup.html');
5
+ const tabId=Number(pin.get('tab')), winId=Number(pin.get('win')), docId=pin.get('doc');
6
+ let base, key, origin, pending, preview, running=false, busy=false;
7
+ const show=(id,v)=>$(id).hidden=!v;
8
+ async function post(path,data={},bearer=key){
9
+ const res=await fetch(base+path,{method:'POST',credentials:'omit',redirect:'error',cache:'no-store',headers:{Authorization:'Bearer '+bearer,'Content-Type':'application/json'},body:JSON.stringify(data),signal:AbortSignal.timeout(3500)});
10
+ if(!res.ok)throw Error('The local session ended.');return res.json();
11
+ }
12
+ async function inTab(op,ref){
13
+ if(!docId||!tabId||!winId)throw Error('No toolbar gesture.');
14
+ const [current]=await chrome.tabs.query({active:true,windowId:winId});
15
+ if(!current||current.id!==tabId||current.incognito)throw Error('Selected tab is no longer active.');
16
+ const target={tabId,documentIds:[docId]};
17
+ const [r]=await chrome.scripting.executeScript({target,func:pageOperation,args:[op,ref||null]});
18
+ if(!r||r.frameId!==0||!r.documentId||(docId&&r.documentId!==docId)||!r.result)throw Error('Selected document changed.');
19
+ return r.result;
20
+ }
21
+ function clear(){pending=null;preview=null;show('approve',false);show('deny',false);$('preview').textContent='';}
22
+ function stop(msg){const was=running;running=false;clear();if(was)inTab('clear').catch(()=>{});
23
+ if(was)post('/stop').catch(()=>{});key=null;
24
+ $('status').textContent=msg;show('stop',false);show('connect',false);show('pair',false);}
25
+ async function poll(){
26
+ if(!running)return;
27
+ try{
28
+ const msg=await post('/next');
29
+ if(!running)return;
30
+ if(!busy&&(!msg.id||pending?.id!==msg.id)){
31
+ clear();
32
+ if(msg.id){
33
+ if(!['read','click'].includes(msg.op))throw Error();
34
+ pending=msg;preview=await inTab(msg.op==='read'?'read':'describe',msg.ref);
35
+ $('preview').textContent=msg.op==='read'?[preview.title,preview.text,...preview.controls.map(c=>c.label)].join('\n'):[preview.kind+': '+preview.label,preview.destination].filter(Boolean).join('\n');
36
+ $('status').textContent=msg.op==='read'?'Review the text and controls to send to your model:':'Allow one click on '+origin+'? A click can change the site.';
37
+ $('approve').textContent=msg.op==='read'?'Send this preview':'Click once';
38
+ show('approve',true);show('deny',true);
39
+ }else $('status').textContent='Sharing '+origin+'. Waiting for a terminal request.';
40
+ }
41
+ }catch{stop('Stopped. The selected document or terminal is no longer available.');}
42
+ if(running)setTimeout(poll,500);
43
+ }
44
+ $('connect').onclick=async()=>{
45
+ $('connect').disabled=true;
46
+ try{
47
+ const m=/^(\d{1,5}):([0-9a-f]{48})$/.exec($('code').value.trim());
48
+ if(!m||+m[1]>65535||!+m[1])throw Error();
49
+ origin=(await inTab('probe')).origin;
50
+ if(!/^https:\/\//.test(origin)&&!/^http:\/\/127\.0\.0\.1:\d+$/.test(origin))throw Error();
51
+ base='http://127.0.0.1:'+m[1];key=(await post('/pair',{},m[2])).key;running=true;
52
+ $('code').value='';show('connect',false);show('pair',false);show('stop',true);
53
+ $('status').textContent='Sharing '+origin;poll();
54
+ }catch{$('status').textContent='Could not share. Use a regular HTTPS tab and a fresh session code.';$('connect').disabled=false;}
55
+ };
56
+ async function answer(yes){
57
+ if(busy||!pending)return;busy=true;
58
+ const msg=pending;show('approve',false);show('deny',false);
59
+ try{
60
+ let result;
61
+ if(yes){
62
+ await inTab('probe');
63
+ await post('/claim',{id:msg.id});
64
+ if(!running||pending?.id!==msg.id)throw Error('Request expired.');
65
+ result=msg.op==='click'?await inTab('click',msg.ref):preview;
66
+ }
67
+ if(!yes)await inTab('clear').catch(()=>{});
68
+ await post('/result',{id:msg.id,approved:yes,result});clear();
69
+ }catch{stop('Stopped. If a click was requested, check the page; do not repeat it automatically.');}
70
+ finally{busy=false;}
71
+ }
72
+ $('approve').onclick=()=>answer(true);$('deny').onclick=()=>answer(false);
73
+ $('stop').onclick=()=>stop('Sharing stopped.');
74
+ addEventListener('pagehide',()=>{if(running)fetch(base+'/stop',{method:'POST',keepalive:true,credentials:'omit',redirect:'error',headers:{Authorization:'Bearer '+key,'Content-Type':'application/json'},body:'{}'}).catch(()=>{});});
package/package.json CHANGED
@@ -1,6 +1,10 @@
1
1
  {
2
2
  "name": "@lordesteph/openvegas-selected-tab",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Optional, user-approved single-tab Chrome connector for OpenVegas Codex",
6
+ "bin": {"openvegas-selected-tab":"cli.mjs"},
7
+ "engines": {"node": ">=20"},
8
+ "files": ["cli.mjs", "session.mjs", "extension/", "README.md"],
9
+ "license": "UNLICENSED"
10
+ }
package/session.mjs ADDED
@@ -0,0 +1,90 @@
1
+ import {createServer} from 'node:http';
2
+ import {randomBytes,randomUUID} from 'node:crypto';
3
+
4
+ export const EXT = 'chrome-extension://bdnfjobbhfnpagojakoamomofjhgmpdo';
5
+ const makeKey = () => randomBytes(24).toString('hex');
6
+ const info = '<!doctype html><meta charset=utf-8><title>OpenVegas tab sharing</title><h1>Share one Chrome tab</h1><p>Copy the session code below. On the tab you intend to share, click the OpenVegas extension and paste it there. Do not send it to chat.</p><code id=c></code><p>Leave the extension popup open while using your terminal. Closing the popup stops sharing.</p><script src="/show.js"></script>';
7
+
8
+ export async function newSession() {
9
+ let pair = makeKey(), key = '', pending, last = 0, host, closed = false;
10
+ const approvedRefs = new Set();
11
+ const endOp = (err,result) => {
12
+ if (!pending) return;
13
+ const p=pending; pending=undefined; clearTimeout(p.timer);
14
+ if (err) p.reject(Error(err)); else p.resolve(result);
15
+ };
16
+ const close = () => {
17
+ if (closed) return;
18
+ closed=true; pair='';key='';approvedRefs.clear();endOp('Tab sharing ended.');clearInterval(clock);
19
+ server.close();server.closeAllConnections();
20
+ };
21
+ const server=createServer(async(req,res)=>{
22
+ const send=(n,v={})=>{res.writeHead(n,{'Content-Type':'application/json'});res.end(JSON.stringify(v));};
23
+ res.setHeader('Cache-Control','no-store');res.setHeader('Referrer-Policy','no-referrer');
24
+ res.setHeader('X-Content-Type-Options','nosniff');
25
+ if (req.headers.host!==host || closed) return send(403);
26
+ if(req.method==='GET' && ['/setup','/show.js'].includes(req.url)){
27
+ res.setHeader('Content-Security-Policy',"default-src 'none'; script-src 'self'; frame-ancestors 'none'; base-uri 'none'");
28
+ res.setHeader('Content-Type',req.url==='/setup'?'text/html; charset=utf-8':'text/javascript');
29
+ res.end(req.url==='/setup'?info:"const v=location.hash.slice(1);history.replaceState(null,'','/setup');document.getElementById('c').textContent=v;");return;
30
+ }
31
+ if(req.headers.origin!==EXT)return send(403);
32
+ res.setHeader('Access-Control-Allow-Origin',EXT);
33
+ if(req.method==='OPTIONS'){
34
+ res.setHeader('Access-Control-Allow-Methods','POST');
35
+ res.setHeader('Access-Control-Allow-Headers','authorization,content-type');
36
+ res.setHeader('Access-Control-Allow-Private-Network','true');
37
+ return send(200);
38
+ }
39
+ if(req.method!=='POST' || !/^application\/json(?:;|$)/.test(req.headers['content-type']||''))return send(405);
40
+ const expected=req.url==='/pair'?pair:key;
41
+ if (!expected || req.headers.authorization!=='Bearer '+expected) return send(403);
42
+ let data;
43
+ try{
44
+ let size=0;const chunks=[];
45
+ for await(const b of req){size+=b.length;if(size>24576)return send(413);chunks.push(b);}
46
+ data=JSON.parse(Buffer.concat(chunks).toString());
47
+ }catch{return send(400);}
48
+ if(closed || (req.url==='/pair'?pair:key)!==expected)return send(403);
49
+ if(req.url==='/pair'){
50
+ pair='';key=makeKey();last=Date.now();return send(200,{key});
51
+ }
52
+ if(req.url==='/next'){last=Date.now();return send(200,pending?{id:pending.id,op:pending.op,ref:pending.ref}:{});}
53
+ if(req.url==='/claim'){
54
+ if(!pending||data.id!==pending.id||pending.claimed)return send(409);
55
+ pending.claimed=true;return send(200);
56
+ }
57
+ if(req.url==='/stop'){send(200);close();return;}
58
+ if(req.url!=='/result'||!pending||data.id!==pending.id)return send(409);
59
+ if(data.approved!==true){endOp('User declined or the selected document changed.');return send(200);}
60
+ if(!pending.claimed)return send(409);
61
+ const v=data.result;
62
+ const isText=x=>typeof x==='string';
63
+ const uuid=x=>typeof x==='string'&&/^[0-9a-f-]{36}$/.test(x);
64
+ const ok = pending.op==='read'
65
+ ? v && isText(v.title)&&v.title.length<=160 && isText(v.text)&&v.text.length<=2400 &&
66
+ Array.isArray(v.controls)&&v.controls.length<=24&&v.controls.every(c=>c&&uuid(c.ref)&&isText(c.label)&&c.label.length<=100)
67
+ : v?.clicked===true;
68
+ if(!ok){endOp('Invalid extension result.');return send(400);}
69
+ if(pending.op==='read')for(const c of v.controls)approvedRefs.add(c.ref);
70
+ endOp(null,pending.op==='read'?{title:v.title,text:v.text,controls:v.controls.map(({ref,label})=>({ref,label}))}:{clicked:true});
71
+ send(200);
72
+ });
73
+ server.requestTimeout=10000;server.headersTimeout=8000;server.maxHeadersCount=20;
74
+ await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
75
+ const port=server.address().port;host='127.0.0.1:'+port;
76
+ const start=Date.now();
77
+ const clock=setInterval(()=>{if(Date.now()-start>300000 || (key&&Date.now()-last>10000))close();},1000);clock.unref();
78
+ return {
79
+ get invitation(){if(!pair||closed)throw Error('No pending invitation.');return {code:port+':'+pair,url:'http://'+host+'/setup#'+port+':'+pair};},
80
+ get connected(){return !!key&&!closed;},get closed(){return closed;},close,
81
+ request(op,ref){
82
+ if(!key||closed)throw Error('No selected tab. Start sharing and connect the extension first.');
83
+ if(!['read','click'].includes(op)||(op==='click'&&!/^[0-9a-f-]{36}$/.test(ref||'')))throw Error('Invalid tab operation.');
84
+ if(pending)throw Error('A request is already pending.');
85
+ if(op==='click'&&!approvedRefs.has(ref))throw Error('Use a control from the latest approved view.');
86
+ approvedRefs.clear();
87
+ return new Promise((resolve,reject)=>{pending={id:randomUUID(),op,ref,resolve,reject,timer:setTimeout(()=>endOp('Approval timed out; do not retry a click automatically.'),60000)};});
88
+ }
89
+ };
90
+ }