var express = require("express"); var formidable = require("formidable"); var serveIndex = require("serve-index"); var randomipa = require("random-ip"); var path = require("path"); var fs = require("fs"); const BASE_BLOCK = process.env.BASE_BLOCK || "2607:5600:c6:203::/64", BASE_IPA = BASE_BLOCK.split('/')[0], BASE_PREFIX = BASE_BLOCK.split('/')[1]; const FILES_DIR = "files"; const AUTH_TOKEN = fs.readFileSync("auth.txt", "utf8").trim(); var app = express(); app.use((req, res, next)=>{ console.log(`[${new Date().toLocaleString()}]`, '📥', req.socket.remoteAddress, `"${req.method} ${req.url} HTTP/${req.httpVersion}"`, JSON.stringify(req.headers)); res.on("finish", () => { console.log(`[${new Date().toLocaleString()}]`, '📤', res.statusCode, res.statusMessage, JSON.stringify(res.getHeaders())); }); next(); }); app.post("/upload", (req, res, next) => { if (req.headers.authentication != AUTH_TOKEN) return res.status(403).send("Unauthorized"); var form = new formidable.IncomingForm({ maxFileSize: 2**30, // 1 GiB maxFields: 1, uploadDir: "tmp" }); form.parse(req, function(err, fields, files) { if (err) return next(err); var file = files.file; if (!file) return res.sendStatus(400); do { var ipv6 = randomipa(BASE_IPA, BASE_PREFIX); var filedir = path.join(FILES_DIR, `[${ipv6}]`); } while ( fs.existsSync(filedir) && !console.log("oof") ); try { fs.mkdirSync(filedir); fs.renameSync(file.path, path.join(filedir, file.name)); } catch(e) { return next(e); } require("child_process").execSync(`ip addr add ${ipv6} dev eth0`); fs.appendFileSync("@reboot.sh", `ip addr add ${ipv6} dev eth0\n`); // :lul: res.send(`http://[${ipv6}]/`); }); }); app.get("*", function(req, res, next){ let filecode = req.headers.host; let webroot = path.join(FILES_DIR, filecode); let webrootdirlist = fs.readdirSync(webroot); if (webrootdirlist.length > 1) { req.url = path.join(filecode, req.url); next(); } else if (webrootdirlist.length == 1) { res.sendFile(webrootdirlist[0], { root: path.join(process.cwd(), webroot), headers: {"Content-Disposition": `filename=${webrootdirlist[0]}`} }); } else { res.sendStatus(204); } }); app.get("*", express.static(FILES_DIR), serveIndex(FILES_DIR, {icons: true})); app.use(function (error, req, res, next) { res.status(error.code == "ENOENT" ? 404 : console.error(error.stack) || 500).send(error.toString()); }); app.listen(process.env.PORT || 80, process.env.ADDRESS || "::");