SPB Git

spb/autoscholar

Public
1.3 KB · 26 lines typescript
1import "server-only";2import { AppError, authenticateWorker, forbidden, getEnv } from "@autoscholar/core";3import type { computeWorkers } from "@autoscholar/db";4import { db } from "./db";5import { clientIp, ipInCidrs, 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 = clientIp(req);15  if (ip && !ipInCidrs(ip, env.INTERNAL_API_ALLOWED_CIDRS)) throw forbidden("source network not allowed");16  const pv = req.headers.get("x-protocol-version");17  if (pv && pv !== "1") throw new AppError("protocol_mismatch", `unsupported worker protocol ${pv}`, 426);18  const auth = req.headers.get("authorization");19  const bearer = auth?.startsWith("Bearer ") ? auth.slice(7) : null;20  return authenticateWorker(db(), bearer);21}2223export function assertInternalNetwork(req: Request): void {24  if (viaPublicProxy(req)) throw forbidden("internal API is not reachable through the public gateway");25}26
Files · e709d44366a0d3dc4c8b6b32ba43ac31859be02a
Menu

Theme