const fs = require('node:fs'); const path = require('node:path'); const https = require('node:https'); const crypto = require('node:crypto'); const {execFile} = require('node:child_process'); const pty = require('./runtime/node_modules/node-pty'); const {terminalTarget,attachCommand,parseSessions,sessionListCommand} = require('./workspace.cjs'); const {WebSocketServer} = require('./runtime/node_modules/ws'); const root = __dirname, run = path.join(root, '.private'); const config = JSON.parse(fs.readFileSync(path.join(run, 'config.json'))); const sshArgs = ['-S', config.controlPath, '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=4', config.target]; const sessions = new Map(), attempts = new Map(); const expectedOrigin = `https://${config.bind}:${config.port}`; function sameOrigin(req) { return req.headers.host === new URL(expectedOrigin).host && req.headers.origin === expectedOrigin; } const clients = new Set(), events = []; let clientNumber = 0, statusCache, statusAt = 0, pendingStatus; function diagnostic(event, fields={}) { events.push({at:new Date().toISOString(),event,...fields}); if(events.length>100)events.shift(); fs.writeFileSync(path.join(run,'connection-events.json'),JSON.stringify(events),{mode:0o600}); } const files = { '/': ['public/device.html','text/html'], '/device':['public/device.html','text/html'], '/classic':['public/index.html','text/html'], '/device.css':['public/device.css','text/css'], '/device.js':['public/device.js','application/javascript'], '/device-input.js':['public/device-input.js','application/javascript'], '/app.js':['public/app.js','application/javascript'], '/xterm.js':['runtime/node_modules/@xterm/xterm/lib/xterm.js','application/javascript'], '/xterm.css':['runtime/node_modules/@xterm/xterm/css/xterm.css','text/css'] }; function authorized(req) { const token = /(?:^|; )session=([a-f0-9]+)/.exec(req.headers.cookie || '')?.[1]; return sessions.get(token) > Date.now(); } function reply(res, code, text, type='text/plain') { res.writeHead(code, {'Content-Type':type, 'Cache-Control':'no-store', 'X-Content-Type-Options':'nosniff', 'Referrer-Policy':'same-origin'});res.end(text); } function telemetry() { if (statusCache && Date.now()-statusAt < 30000) return Promise.resolve(statusCache); if (pendingStatus) return pendingStatus; pendingStatus = new Promise(resolve => { execFile('/usr/bin/ssh', [...sshArgs, 'n810-pocket-status --section all'], {timeout:10000,maxBuffer:16384}, (err,out) => { statusCache = err ? 'N810 SSH unavailable; status not current.' : out; statusAt=Date.now();pendingStatus=null;resolve(statusCache); }); }); return pendingStatus; } function remote(command){ return new Promise((resolve,reject)=>execFile('/usr/bin/ssh',[...sshArgs,command],{timeout:10000,maxBuffer:16384},(err,out)=>err?reject(err):resolve(out))); } async function workspaceSessions(){return parseSessions(await remote(sessionListCommand()));} let creatingView=false; const server = https.createServer({key:fs.readFileSync(path.join(run,'key.pem')),cert:fs.readFileSync(path.join(run,'cert.pem'))}, async (req,res) => { if (req.headers.host !== new URL(expectedOrigin).host) return reply(res,403,'Host rejected'); if (req.url==='/login' && req.method==='POST') { if (!sameOrigin(req)) { fs.writeFileSync(path.join(run,'last-origin-rejection.json'),JSON.stringify({origin:req.headers.origin||null,host:req.headers.host,fetchSite:req.headers['sec-fetch-site']||null,expectedOrigin}),{mode:0o600}); return reply(res,403,'Origin rejected. Open the original phone terminal URL and reload the login page.'); } const ip=req.socket.remoteAddress, a=attempts.get(ip)||{start:Date.now(),n:0}; if(Date.now()-a.start>60000){a.start=Date.now();a.n=0;} attempts.set(ip,a); if(++a.n>5) return reply(res,429,'Wait a minute before trying again.'); let body='';for await(const chunk of req){body+=chunk;if(body.length>1024)return reply(res,413,'Too large');} const password=new URLSearchParams(body).get('password')||''; const hash=x=>crypto.createHash('sha256').update(x).digest(); if(!crypto.timingSafeEqual(hash(password),hash(config.password)))return reply(res,401,'Incorrect password.'); const token=crypto.randomBytes(32).toString('hex');sessions.set(token,Date.now()+8*3600000); res.writeHead(303,{'Location':'/','Set-Cookie':`session=${token}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=28800`});return res.end(); } if(['/session','/sessions','/new-view'].includes(req.url)&&!authorized(req))return reply(res,401,JSON.stringify({authenticated:false}),'application/json'); if(!authorized(req)) return reply(res,200,'