refactor(gateway): dedupe json endpoint prelude

This commit is contained in:
Peter Steinberger
2026-02-15 13:24:33 +00:00
parent 052d988add
commit 9e2233da7f
4 changed files with 195 additions and 90 deletions

View File

@@ -0,0 +1,45 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import type { AuthRateLimiter } from "./auth-rate-limit.js";
import type { ResolvedGatewayAuth } from "./auth.js";
import { authorizeGatewayBearerRequestOrReply } from "./http-auth-helpers.js";
import { readJsonBodyOrError, sendMethodNotAllowed } from "./http-common.js";
export async function handleGatewayPostJsonEndpoint(
req: IncomingMessage,
res: ServerResponse,
opts: {
pathname: string;
auth: ResolvedGatewayAuth;
maxBodyBytes: number;
trustedProxies?: string[];
rateLimiter?: AuthRateLimiter;
},
): Promise<false | { body: unknown } | undefined> {
const url = new URL(req.url ?? "/", `http://${req.headers.host || "localhost"}`);
if (url.pathname !== opts.pathname) {
return false;
}
if (req.method !== "POST") {
sendMethodNotAllowed(res);
return undefined;
}
const authorized = await authorizeGatewayBearerRequestOrReply({
req,
res,
auth: opts.auth,
trustedProxies: opts.trustedProxies,
rateLimiter: opts.rateLimiter,
});
if (!authorized) {
return undefined;
}
const body = await readJsonBodyOrError(req, res, opts.maxBodyBytes);
if (body === undefined) {
return undefined;
}
return { body };
}