Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
31 lines (30 loc) · 8.35 KB
/
Copy pathserver.js
File metadata and controls
31 lines (30 loc) · 8.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import http from 'node:http';
import {chromium} from 'playwright';
import {readFile} from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
import {randomUUID,createHash} from 'node:crypto';
import {discover,scan,validURL,createSession,confirmSession,closeSession,sessions,LIMITS} from './src/scanner.js';
const PORT=Number(process.env.PORT||4193),jobs=new Map(),root=fileURLToPath(new URL('.',import.meta.url));
const buildFiles=['server.js','src/scanner.js','src/authentication.js','app.js','index.html','styles.css','theme.js','lens-tokens.css','brand/linklens-logo-v2.png','assets/fonts/geist-latin.woff2','package.json'];
async function fingerprint(){const hash=createHash('sha256');for(const file of buildFiles)hash.update(await readFile(root+file));return hash.digest('hex').slice(0,12)}
const BUILD_ID=await fingerprint(),VERSION=JSON.parse(await readFile(root+'package.json','utf8')).version;
const publicFiles=['index.html','app.js','styles.css','theme.js','lens-tokens.css','brand/linklens-logo-v2.png','assets/fonts/geist-latin.woff2'];
const staticFiles=new Map(await Promise.all(publicFiles.map(async file=>[file,/\.(png|woff2)$/.test(file)?await readFile(root+file):(await readFile(root+file,'utf8')).replaceAll('__LINKLENSE_BUILD_ID__',BUILD_ID)])));
function json(res,status,value){res.writeHead(status,{'Content-Type':'application/json','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});res.end(JSON.stringify(value))}
async function body(req){let b='';for await(const chunk of req){b+=chunk;if(b.length>20000000)throw Error('Request too large.')}try{return JSON.parse(b||'{}')}catch{throw Error('Invalid JSON request.')}}
function target(raw){const url=validURL(raw),u=new URL(url);if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)&&u.port===String(PORT))throw Error('Choose a target website, not the LinkLense workspace.');return url;}
const server=http.createServer(async(req,res)=>{try{const host=req.headers.host||'';if(![`127.0.0.1:${PORT}`,`localhost:${PORT}`].includes(host))return json(res,403,{error:'Local connections only.'});const u=new URL(req.url,`http://${host}`);if(req.headers.origin&&!['http://127.0.0.1:'+PORT,'http://localhost:'+PORT].includes(req.headers.origin))return json(res,403,{error:'Cross-origin access denied.'});if(u.pathname.startsWith('/api/')&&!['GET','HEAD'].includes(req.method)&&req.headers['x-linklense']!=='1')return json(res,403,{error:'Missing local request header.'});
if(u.pathname==='/api/pdf'&&req.method==='POST'){const data=await body(req);if(typeof data.html!=='string')throw Error('Report HTML is required.');const browser=await chromium.launch({headless:true});try{const context=await browser.newContext({javaScriptEnabled:false});await context.route('**/*',route=>route.abort());const page=await context.newPage();await page.setContent(data.html,{waitUntil:'domcontentloaded',timeout:20000});const pdf=await page.pdf({format:'A4',printBackground:true,margin:{top:'15mm',bottom:'15mm',left:'10mm',right:'10mm'}});res.writeHead(200,{'Content-Type':'application/pdf','Content-Disposition':'attachment; filename="linklense-report.pdf"'});res.end(pdf);}finally{await browser.close()}return;}
if(u.pathname==='/api/health')return json(res,200,{ok:true,version:VERSION,buildId:BUILD_ID,restartRequired:await fingerprint()!==BUILD_ID,limits:LIMITS});
if(u.pathname.startsWith('/api/')&&req.headers['x-linklense-build']&&req.headers['x-linklense-build']!==BUILD_ID)return json(res,409,{error:'The running LinkLense version changed. Refresh this page before continuing.'});
if(['/api/jobs','/api/sessions'].includes(u.pathname)&&req.method==='POST'&&await fingerprint()!==BUILD_ID)return json(res,409,{error:'LinkLense files were updated, but this server is still running the old scanner. Restart LinkLense and refresh this page before starting an audit.'});
if(u.pathname==='/api/sessions'&&req.method==='POST'){const data=await body(req);return json(res,201,await createSession(target(data.url)))}
const sessionMatch=u.pathname.match(/^\/api\/sessions\/([\w-]+)(\/confirm)?$/);if(sessionMatch){if(req.method==='DELETE'){await closeSession(sessionMatch[1]);return json(res,200,{ok:true})}if(req.method==='POST'&&sessionMatch[2])return json(res,200,await confirmSession(sessionMatch[1],await body(req)));return json(res,405,{error:'Unsupported method.'})}
if(u.pathname==='/api/jobs'&&req.method==='POST'){const data=await body(req);data.url=target(data.url);data.viewports??=['Desktop','Mobile'];if(!Array.isArray(data.viewports)||!data.viewports.length||data.viewports.length>2||data.viewports.some(v=>!['Desktop','Mobile'].includes(v))||new Set(data.viewports).size!==data.viewports.length)throw Error('Select Desktop Web App, Mobile Web App, or both.');if(!['discover','scan'].includes(data.kind))throw Error('Unknown job type.');if(data.requestId){if(!/^[a-f0-9-]{36}$/i.test(data.requestId))throw Error('Invalid request identity.');const existing=jobs.get(data.requestId);if(existing){if(existing.requestKey!==JSON.stringify([data.kind,data.url,data.sessionId||null,data.scope||'',data.viewports,data.pages?.map(target)||null]))throw Error('This request identity belongs to a different audit.');return json(res,200,{id:existing.id});}}if([...jobs.values()].filter(j=>j.status==='running').length>=2)return json(res,429,{error:'Two browser jobs are already running. Wait or cancel one.'});if(data.kind==='scan'){if(!Array.isArray(data.pages)||!data.pages.length||data.pages.length>LIMITS.pages)throw Error(`Choose between 1 and ${LIMITS.pages} pages.`);data.pages=data.pages.map(target);if(data.pages.some(p=>new URL(p).origin!==new URL(data.url).origin))throw Error('All pages must belong to the target website.');}if(data.sessionId&&!sessions.has(data.sessionId))throw Error('Sign-in session expired. Please sign in again.');for(const[id,j]of jobs)if(j.status!=='running'&&jobs.size>=20)jobs.delete(id);const controller=new AbortController();const job={id:data.requestId||randomUUID(),requestKey:JSON.stringify([data.kind,data.url,data.sessionId||null,data.scope||'',data.viewports,data.pages?.map(target)||null]),status:'running',gaps:[],progress:{message:'Starting browser…',done:0,total:0},signal:controller.signal,controller};jobs.set(job.id,job);json(res,202,{id:job.id});(async()=>{try{const result=await(data.kind==='discover'?discover:scan)(data,job);if(!job.signal.aborted){job.result={...result,buildId:BUILD_ID,version:VERSION};job.status='complete'}}catch(e){if(!job.signal.aborted){job.error=e.message;job.status='error'}}finally{if(job.signal.aborted)job.status='cancelled';}})();return;}
const m=u.pathname.match(/^\/api\/jobs\/([\w-]+)$/);if(m){const job=jobs.get(m[1]);if(!job)return json(res,404,{error:'This job expired. Start again.'});if(req.method==='DELETE'){job.controller.abort();job.status='cancelled';await job.browser?.close().catch(()=>{});return json(res,200,{ok:true})}if(req.method==='GET')return json(res,200,{id:job.id,status:job.status,progress:job.progress,error:job.error,...(job.status==='complete'?{result:job.result}:{})});}
const files=Object.fromEntries([['/','index.html'],...publicFiles.map(file=>['/'+file,file])]);if(!files[u.pathname]||req.method!=='GET')return json(res,404,{error:'Not found.'});const file=files[u.pathname];res.writeHead(200,{'Content-Type':file.endsWith('.js')?'text/javascript':file.endsWith('.css')?'text/css':file.endsWith('.png')?'image/png':file.endsWith('.woff2')?'font/woff2':'text/html','Cache-Control':'no-cache','X-Content-Type-Options':'nosniff','Content-Security-Policy':"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"});res.end(staticFiles.get(file));
}catch(e){json(res,400,{error:e.message||'Request failed.'})}});
server.on('error',error=>{if(error.code==='EADDRINUSE')console.error(`Port ${PORT} is already in use. The older LinkLense server may still be running. Stop that server, restart this version, and verify the build ID in the app.`);else console.error(error.message);process.exitCode=1;});
server.listen(PORT,'127.0.0.1',()=>console.log(`LinkLense ${VERSION} (${BUILD_ID}) running at http://127.0.0.1:${PORT}`));
async function shutdown(){for(const j of jobs.values())if(j.status==='running'){j.controller.abort();await j.browser?.close().catch(()=>{})}for(const id of sessions.keys())await closeSession(id);server.close(()=>process.exit(0));}process.on('SIGTERM',shutdown);process.on('SIGINT',shutdown);
export {server};