64 lines
1.6 KiB
TypeScript
64 lines
1.6 KiB
TypeScript
import { Hono } from "hono";
|
|
import type { Env } from "./env";
|
|
import type { InternalSession } from "./internal-context";
|
|
import { withInternalSession } from "./internal-context";
|
|
import { resolveRoute } from "./route-policy";
|
|
|
|
const app = new Hono<{ Bindings: Env }>();
|
|
|
|
async function verifySession(request: Request, env: Env): Promise<InternalSession | null> {
|
|
const sessionUrl = new URL("/internal/session", request.url);
|
|
const sessionRequest = new Request(sessionUrl, {
|
|
method: "GET",
|
|
headers: request.headers,
|
|
});
|
|
sessionRequest.headers.set("x-internal-auth-secret", env.INTERNAL_AUTH_SECRET);
|
|
|
|
const response = await env.AUTH.fetch(sessionRequest);
|
|
if (!response.ok) return null;
|
|
|
|
const session = (await response.json()) as InternalSession;
|
|
return session.authenticated ? session : null;
|
|
}
|
|
|
|
app.all("*", async (c) => {
|
|
const target = resolveRoute(c.req.raw, c.env);
|
|
|
|
if (target.kind === "gateway-health") {
|
|
return c.json({
|
|
ok: true,
|
|
service: "cfw-gateway",
|
|
});
|
|
}
|
|
|
|
if (target.kind === "auth") {
|
|
return c.env.AUTH.fetch(c.req.raw);
|
|
}
|
|
|
|
const session = await verifySession(c.req.raw, c.env);
|
|
if (!session) {
|
|
return c.json({ error: "unauthorized" }, 401);
|
|
}
|
|
|
|
const request = withInternalSession(c.req.raw, session);
|
|
|
|
if (!c.env.DISPATCHER) {
|
|
return c.json({
|
|
ok: true,
|
|
routedTo: target.workerName,
|
|
userId: session.userId,
|
|
});
|
|
}
|
|
|
|
const worker = c.env.DISPATCHER.get(target.workerName, {}, {
|
|
limits: {
|
|
cpuMs: 20,
|
|
subRequests: 20,
|
|
},
|
|
});
|
|
|
|
return worker.fetch(request);
|
|
});
|
|
|
|
export default app;
|