const express = require("express"); const { CaptchaGenerator } = require("captcha-canvas"); const fs = require("fs"); const os = require("os"); const path = require("path"); const crypto = require("crypto"); const app = express(); app.set('json spaces', 4) const tempDir = os.tmpdir(); function generateRandomHex(length) { return crypto.randomBytes(length).toString("hex"); } const rand = (length) => [...Array(length)].map(() => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(Math.random() * 62)]).join(''); const deleteOldFiles = (folderPath, maxAgeMinutes = 10) => { setInterval(() => { fs.readdir(folderPath, (err, files) => { if (err) return; const now = Date.now(), maxAgeMs = maxAgeMinutes * 60 * 1000; files.forEach(file => { const filePath = path.join(folderPath, file); fs.stat(filePath, (err, stats) => { if (!err && now - stats.mtimeMs > maxAgeMs) fs.unlink(filePath, () => {}); }); }); }); }, 60000); }; const exp = (minutes) => Date.now() - minutes * 60 * 1000; deleteOldFiles(tempDir, 5) app.use("/tmp", express.static(tempDir)); app.all("/", async (req, res) => { const captcha = new CaptchaGenerator({ height: 200, width: 600 }) .setCaptcha({ text: rand(6) }) const fileName = `temp_${generateRandomHex(8)}.png`; const filePath = path.join(tempDir, fileName); const buffer = await captcha.generateSync() fs.writeFile(filePath, buffer, (err) => { if (err) return res.status(500).json({ error: "Failed to save captcha" }); res.json({ expired: `${exp(5)} mins.`, text: captcha.text, image: `https://${req.hostname}/tmp/${fileName}` }); }); }); app.listen(7860, () => console.log("Server running on port 7860"));