File size: 1,913 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
const express = require("express");
const helmet = require("helmet");
const { config } = require("./config/env");
const { timingSafeEqualText } = require("./security/auth");
const { listJobs, listEvents } = require("./queue/jobs");
const { snapshot } = require("./monitoring/metrics");
const { healthCheck } = require("./monitoring/health");
const { cleanupTemp, rotateCache } = require("./cache/rotation");

function createServer(bot, queue) {
  const app = express();
  app.use(helmet({ contentSecurityPolicy: false }));
  app.use(express.json({ limit: "2mb" }));

  app.get("/health", async (_req, res) => {
    res.json(await healthCheck());
  });

  app.post("/telegram/webhook", async (req, res) => {
    const workerSecret = req.header("x-worker-secret");
    if (config.server.workerSharedSecret && !timingSafeEqualText(workerSecret, config.server.workerSharedSecret)) {
      return res.status(401).json({ ok: false });
    }
    const telegramSecret = req.header("x-telegram-bot-api-secret-token");
    if (config.telegram.webhookSecret && !timingSafeEqualText(telegramSecret, config.telegram.webhookSecret)) {
      return res.status(401).json({ ok: false });
    }
    res.json({ ok: true });
    await bot.handleUpdate(req.body);
  });

  app.get("/api/status", async (_req, res) => {
    res.json(await snapshot());
  });

  app.get("/api/queue", (_req, res) => {
    res.json({ jobs: listJobs(100) });
  });

  app.get("/api/logs", (_req, res) => {
    res.json({ events: listEvents(200) });
  });

  app.post("/api/admin/pause", (_req, res) => {
    queue.pause();
    res.json({ ok: true });
  });

  app.post("/api/admin/resume", (_req, res) => {
    queue.resume();
    res.json({ ok: true });
  });

  app.post("/api/admin/cleanup", async (_req, res) => {
    await cleanupTemp();
    await rotateCache();
    res.json({ ok: true });
  });

  return app;
}

module.exports = { createServer };