import "server-only"; import { AppError, authenticateWorker, forbidden, getEnv } from "@autoscholar/core"; import type { computeWorkers } from "@autoscholar/db"; import { db } from "./db"; import { ipInCidrs, sourceIp, viaPublicProxy } from "./ip"; /** * Internal worker API guard: rejects anything that came through the public tunnel (Caddy adds X-Forwarded-*), * optionally enforces the private CIDR allow-list, checks the protocol version, then the worker bearer token. */ export async function requireWorker(req: Request): Promise { const env = getEnv(); if (viaPublicProxy(req)) throw forbidden("internal API is not reachable through the public gateway"); const ip = sourceIp(req); if (!ip || !ipInCidrs(ip, env.INTERNAL_API_ALLOWED_CIDRS)) throw forbidden(`source network not allowed (${ip ?? "unknown"})`); const pv = req.headers.get("x-protocol-version"); if (pv && pv !== "1") throw new AppError("protocol_mismatch", `unsupported worker protocol ${pv}`, 426); const auth = req.headers.get("authorization"); const bearer = auth?.startsWith("Bearer ") ? auth.slice(7) : null; return authenticateWorker(db(), bearer); } export function assertInternalNetwork(req: Request): void { const env = getEnv(); if (viaPublicProxy(req)) throw forbidden("internal API is not reachable through the public gateway"); const ip = sourceIp(req); if (!ip || !ipInCidrs(ip, env.INTERNAL_API_ALLOWED_CIDRS)) throw forbidden(`source network not allowed (${ip ?? "unknown"})`); }