Files
fristydev/lib/api-route.ts
T
fristy 864b9226fc
Build & Push / Lint & Build (pull_request) Failing after 52s
Build & Push / Build & Push Image (pull_request) Skipped
Build & Push / Trigger Deploy (pull_request) Skipped
desloppify: code health overhaul plus abuse hardening (140 green, strict 87.2)
Honest baseline after removing 45 gaming suppressions. Structural: lib/game plus root hooks extraction, CORS origin echo, DEV_ORIGINS layering. Fixes: error-cause binding, discord 5xx split, null-cache guard, co-located tests, rejecting-fetch coverage, naming and typing cleanup, socket controller, cache bound, cascade helpers, latch resets. Hardening: per-IP rate limit on API routes, deterministic-miss UX, retry cooldown plus cap. Suite 140 green, build plus lint clean.
2026-09-11 23:54:59 +03:00

98 lines
2.4 KiB
TypeScript

import { NextResponse } from "next/server";
import { DEV_ORIGINS, SITE_URL } from "@/lib/site";
const ALLOWED_ORIGIN = SITE_URL;
function isDev(): boolean {
return process.env.NODE_ENV !== "production";
}
export function isAllowedOrigin(request: Request): boolean {
const origin = request.headers.get("origin");
if (origin === null) {
return true;
}
if (origin === ALLOWED_ORIGIN) {
return true;
}
if (isDev() && DEV_ORIGINS.has(origin)) {
return true;
}
return false;
}
function resolveAllowedOrigin(origin: string | null): string {
if (
origin !== null &&
(origin === ALLOWED_ORIGIN || (isDev() && DEV_ORIGINS.has(origin)))
) {
return origin;
}
return ALLOWED_ORIGIN;
}
export function corsHeaders(origin?: string | null): Record<string, string> {
return {
"Access-Control-Allow-Origin": resolveAllowedOrigin(origin ?? null),
Vary: "Origin",
};
}
export function forbidden(origin?: string | null): NextResponse {
return NextResponse.json(
{ error: "Forbidden" },
{
status: 403,
headers: {
"Cache-Control": "public, s-maxage=0, stale-while-revalidate=86400",
...corsHeaders(origin),
},
},
);
}
export async function parseAppId(context: {
params: Promise<{ id: string }>;
}): Promise<string | null> {
const { id } = await context.params;
if (!/^\d{1,20}$/.test(id)) {
return null;
}
return id;
}
export function invalidIdResponse(origin?: string | null): NextResponse {
return jsonErrorWithCors({ error: "Invalid application id" }, 400, 0, origin);
}
export function jsonErrorWithCors(
data: unknown,
status: number,
sMaxage = 60,
origin?: string | null,
): NextResponse {
return NextResponse.json(data, {
status,
headers: {
"Cache-Control": `public, s-maxage=${sMaxage}, stale-while-revalidate=86400`,
...corsHeaders(origin),
},
});
}
export function jsonWithCors(
data: unknown,
sMaxage = 3600,
origin?: string | null,
): NextResponse {
return NextResponse.json(data, {
headers: {
"Cache-Control": `public, s-maxage=${sMaxage}, stale-while-revalidate=86400`,
...corsHeaders(origin),
},
});
}
export function requestOrigin(request: Request): string | null {
return request.headers.get("origin");
}