A Cloudflare Worker which works in conjunction with https://github.com/indexxing/bsky-alt-text
1import { Context, Next } from "hono";
2import { Env, Variables } from "../types";
3
4export async function authMiddleware(
5 c: Context<{ Bindings: Env; Variables: Variables }>,
6 next: Next,
7) {
8 if (!c.env.AUTH_TOKEN) {
9 return c.json({
10 success: false,
11 error: "Authentication token is not specified in worker secrets.",
12 }, 500);
13 }
14
15 const authToken = c.req.header("Authorization");
16
17 if (!authToken || !authToken.startsWith("Bearer ")) {
18 return c.json(
19 {
20 success: false,
21 error:
22 "Authentication token missing or malformed. Expected 'Bearer <token>'.",
23 },
24 401,
25 {
26 "WWW-Authenticate": "Bearer",
27 },
28 );
29 }
30
31 const token = authToken.split(" ")[1];
32 if (token !== c.env.AUTH_TOKEN) {
33 return c.json({
34 success: false,
35 error: "Authentication token provided is invalid.",
36 }, 401);
37 }
38
39 await next();
40}