spb/autoscholar
Public
1import "server-only";2import { AppError, authenticateWorker, forbidden, getEnv } from "@autoscholar/core";3import type { computeWorkers } from "@autoscholar/db";4import { db } from "./db";5import { ipInCidrs, sourceIp, viaPublicProxy } from "./ip";67/**8 * Internal worker API guard: rejects anything that came through the public tunnel (Caddy adds X-Forwarded-*),9 * optionally enforces the private CIDR allow-list, checks the protocol version, then the worker bearer token.10 */11export async function requireWorker(req: Request): Promise<typeof computeWorkers.$inferSelect> {12 const env = getEnv();13 if (viaPublicProxy(req)) throw forbidden("internal API is not reachable through the public gateway");14 const ip = sourceIp(req);15 if (!ip || !ipInCidrs(ip, env.INTERNAL_API_ALLOWED_CIDRS))16 throw forbidden(`source network not allowed (${ip ?? "unknown"})`);17 const pv = req.headers.get("x-protocol-version");18 if (pv && pv !== "1") throw new AppError("protocol_mismatch", `unsupported worker protocol ${pv}`, 426);19 const auth = req.headers.get("authorization");20 const bearer = auth?.startsWith("Bearer ") ? auth.slice(7) : null;21 return authenticateWorker(db(), bearer);22}2324export function assertInternalNetwork(req: Request): void {25 const env = getEnv();26 if (viaPublicProxy(req)) throw forbidden("internal API is not reachable through the public gateway");27 const ip = sourceIp(req);28 if (!ip || !ipInCidrs(ip, env.INTERNAL_API_ALLOWED_CIDRS))29 throw forbidden(`source network not allowed (${ip ?? "unknown"})`);30}31