forked from nitrojs/nitro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcron-handler.ts
More file actions
31 lines (27 loc) · 1020 Bytes
/
Copy pathcron-handler.ts
File metadata and controls
31 lines (27 loc) · 1020 Bytes
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
import { timingSafeEqual } from "node:crypto";
import { defineHandler, HTTPError } from "nitro/h3";
import { runCronTasks } from "#nitro/runtime/task";
export default defineHandler(async (event) => {
// Validate CRON_SECRET if set - https://vercel.com/docs/cron-jobs/manage-cron-jobs#securing-cron-jobs
const cronSecret = process.env.CRON_SECRET;
if (cronSecret) {
const authHeader = event.req.headers.get("authorization") || "";
const expected = `Bearer ${cronSecret}`;
const a = Buffer.from(authHeader);
const b = Buffer.from(expected);
if (a.length !== b.length || !timingSafeEqual(a, b)) {
throw new HTTPError("Unauthorized", { status: 401 });
}
}
const cron = event.req.headers.get("x-vercel-cron-schedule");
if (!cron) {
throw new HTTPError("Missing x-vercel-cron-schedule header", { status: 400 });
}
const result = await runCronTasks(cron, {
context: {},
payload: {
scheduledTime: Date.now(),
},
});
return { cron, tasks: result };
});