File size: 1,834 Bytes
4551c7e
221aef6
4551c7e
 
 
2b65d87
c7254fd
 
5e47bf4
dbf311b
4551c7e
2b65d87
 
 
4551c7e
7597a9d
80971ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7597a9d
c1a7224
 
80971ae
68e73f6
 
5e47bf4
13a47fe
 
5e47bf4
4551c7e
221aef6
13a47fe
2b65d87
 
68e73f6
 
4551c7e
c1a7224
 
 
4551c7e
 
7c9d1d2
c7254fd
4551c7e
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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"));