import express, { Router } from "express"; import { cleanMessage, recordPing, type PingKind } from "../services/heartbeats.js"; import { rateLimit } from "../utils/rateLimit.js"; import { asyncHandler } from "../utils/asyncHandler.js"; /** * The address a job calls: /api/heartbeat/, /api/heartbeat//start, /api/heartbeat//fail. No session and no sign-in — the * token is the whole of the access, and all it allows is to say "I'm alive". Mounted ahead of the browser-only middleware (a script isn't a * browser and has no cookie), so it answers GET, HEAD, POST and PUT alike: whatever `curl` or `wget` happens to send. * * It answers a token that doesn't exist, and a path that isn't one of the three, in the same two words, and is limited per address. */ export const heartbeatPingRouter = Router(); const limiter = rateLimit({ windowMs: 60_000, max: 120, message: "Too many requests. Wait a minute." }); // Whatever a script sends as the body ("3.2 GB copied") is a note; it is cut down to a line. const body = express.text({ type: () => true, limit: "100kb" }); const KINDS: Record = { "": "ok", ok: "ok", start: "start", fail: "fail" }; heartbeatPingRouter.all("/:token/:kind?", limiter, body, asyncHandler(async (req, res) => { res.setHeader("Cache-Control", "no-store"); res.setHeader("X-Robots-Tag", "noindex, nofollow"); if (!["GET", "HEAD", "POST", "PUT"].includes(req.method)) return res.status(405).type("text/plain").send("Method not allowed"); const kind = KINDS[(req.params.kind ?? "").toLowerCase()]; if (!kind) return res.status(404).type("text/plain").send("Not found"); const fromQuery = typeof req.query.msg === "string" ? req.query.msg : null; const message = cleanMessage(fromQuery ?? (typeof req.body === "string" ? req.body : null)); const heartbeat = await recordPing(req.params.token, kind, message); if (!heartbeat) return res.status(404).type("text/plain").send("Not found"); res.type("text/plain").send("OK"); }));