← back to Fentucci Viewer

server.js

17 lines

const http=require("http"),fs=require("fs"),path=require("path");
const ROOT=path.join(__dirname,"public");
const USER="admin",PASS="DW2024!";
const MIME={".html":"text/html",".json":"application/json",".js":"text/javascript",".css":"text/css"};
const srv=http.createServer((req,res)=>{
  const auth=(req.headers.authorization||"").split(" ")[1]||"";
  const [u,p]=Buffer.from(auth,"base64").toString().split(":");
  if(u!==USER||p!==PASS){res.writeHead(401,{"WWW-Authenticate":'Basic realm="Fentucci"'});return res.end("auth required");}
  let f=decodeURIComponent((req.url.split("?")[0]));
  if(f==="/"||f==="")f="/index.html";
  const fp=path.join(ROOT,path.normalize(f).replace(/^(\.\.[\/\\])+/,""));
  if(!fp.startsWith(ROOT)||!fs.existsSync(fp)){res.writeHead(404);return res.end("not found");}
  res.writeHead(200,{"Content-Type":MIME[path.extname(fp)]||"application/octet-stream"});
  fs.createReadStream(fp).pipe(res);
});
srv.listen(process.env.PORT||9827,"127.0.0.1",()=>console.log("FENTUCCI-VIEWER-PORT="+srv.address().port));