Complete security hardening: zero-migration foundation, edge headers, rate-limit atomics, body limits
Local Build and Deploy / deploy (push) Successful in 58s
Local Build and Deploy / deploy (push) Successful in 58s
- Make @/lib/safe-action re-export from foundation layer so all 13+ existing server actions instantly get request tracing, rate limiting, and structured error handling without any code changes - Add HSTS, CSP, X-Frame-Options, X-Content-Type-Options to edge proxy (src/proxy.ts) — ran at Cloudflare/Vercel edge for all non-asset routes - Fix rate-limit.ts race condition: compute newCount before assignment to shrink the read-modify-write window; add memory-key prefix to avoid collisions with Redis keys - Add request body size limit (10 MB default) to api-handler.ts with per-route override via maxBodyBytes option - Remove unused imports and clean up backward-compat types
This commit is contained in:
1 parent
f6ad030c5b
commit
e2fc7ea1a4
6 files changed
+53
-176
No files matched your search
+10
-1
@@ -6,6 +6,7 @@ import { logServerError } from "@/lib/server-log";
|
|||||||
import { validateCsrfToken } from "@/lib/foundation/security";
|
import { validateCsrfToken } from "@/lib/foundation/security";
|
||||||
|
|
||||||
const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
||||||
|
const MAX_BODY_BYTES = 10 * 1024 * 1024; // 10 MB
|
||||||
|
|
||||||
type AdminContext = NonNullable<Awaited<ReturnType<typeof getApiAdminContext>>>;
|
type AdminContext = NonNullable<Awaited<ReturnType<typeof getApiAdminContext>>>;
|
||||||
type RouteContext = { params?: Promise<Record<string, string | string[]>> };
|
type RouteContext = { params?: Promise<Record<string, string | string[]>> };
|
||||||
@@ -15,7 +16,7 @@ type AdminHandler = (
|
|||||||
routeContext: RouteContext,
|
routeContext: RouteContext,
|
||||||
) => Promise<Response> | Response;
|
) => Promise<Response> | Response;
|
||||||
|
|
||||||
export function withAdmin(options: { permission?: string; requireCsrf?: boolean }, handler: AdminHandler) {
|
export function withAdmin(options: { permission?: string; requireCsrf?: boolean; maxBodyBytes?: number }, handler: AdminHandler) {
|
||||||
return async (request: NextRequest, routeContext: RouteContext = {}) => {
|
return async (request: NextRequest, routeContext: RouteContext = {}) => {
|
||||||
if (options.requireCsrf === true && MUTATING_METHODS.has(request.method)) {
|
if (options.requireCsrf === true && MUTATING_METHODS.has(request.method)) {
|
||||||
const csrfToken = request.headers.get("x-csrf-token") ?? request.headers.get("csrf-token") ?? "";
|
const csrfToken = request.headers.get("x-csrf-token") ?? request.headers.get("csrf-token") ?? "";
|
||||||
@@ -25,6 +26,14 @@ export function withAdmin(options: { permission?: string; requireCsrf?: boolean
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (MUTATING_METHODS.has(request.method)) {
|
||||||
|
const contentLength = request.headers.get("content-length");
|
||||||
|
const maxBytes = options.maxBodyBytes ?? MAX_BODY_BYTES;
|
||||||
|
if (contentLength && Number(contentLength) > maxBytes) {
|
||||||
|
return NextResponse.json({ ok: false, error: `Request body exceeds ${maxBytes} bytes` }, { status: 413 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const context = await getApiAdminContext();
|
const context = await getApiAdminContext();
|
||||||
if (!context) return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
if (!context) return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export interface AdminActionContext extends ActionContext {
|
|||||||
|
|
||||||
export interface ActionSuccess<T = Record<string, unknown>> {
|
export interface ActionSuccess<T = Record<string, unknown>> {
|
||||||
ok: true;
|
ok: true;
|
||||||
data: T;
|
data?: T;
|
||||||
}
|
}
|
||||||
export interface ActionFailure {
|
export interface ActionFailure {
|
||||||
ok: false;
|
ok: false;
|
||||||
|
|||||||
+16
-21
@@ -1,18 +1,11 @@
|
|||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
import { redis } from "@/lib/redis";
|
import { redis } from "@/lib/redis";
|
||||||
|
|
||||||
/**
|
|
||||||
* Fixed-window rate limiter with optional Redis backend. Falls back to in-process
|
|
||||||
* Map when Redis is unavailable or unconfigured — fine for single-server deployments.
|
|
||||||
*
|
|
||||||
* Periodic cleanup runs every 5 minutes to keep the in-process map bounded.
|
|
||||||
*/
|
|
||||||
type Bucket = { count: number; resetAt: number };
|
type Bucket = { count: number; resetAt: number };
|
||||||
const buckets = new Map<string, Bucket>();
|
const buckets = new Map<string, Bucket>();
|
||||||
|
|
||||||
export interface RateLimitResult {
|
export interface RateLimitResult {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
/** Seconds until the window resets (0 when allowed). */
|
|
||||||
retryAfter: number;
|
retryAfter: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,17 +18,15 @@ function cleanup(): void {
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;
|
if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;
|
||||||
lastCleanup = now;
|
lastCleanup = now;
|
||||||
if (buckets.size <= MAX_BUCKETS) {
|
|
||||||
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
|
for (const [k, b] of buckets) {
|
||||||
} else {
|
if (now >= b.resetAt) buckets.delete(k);
|
||||||
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
|
}
|
||||||
|
|
||||||
if (buckets.size > MAX_BUCKETS) {
|
if (buckets.size > MAX_BUCKETS) {
|
||||||
const sorted = [...buckets.entries()].sort((a, b) => a[1].resetAt - b[1].resetAt);
|
const sorted = [...buckets.entries()].sort((a, b) => a[1].resetAt - b[1].resetAt);
|
||||||
const toRemove = Math.floor(sorted.length * 0.2);
|
const keysToRemove = sorted.slice(0, Math.floor(sorted.length * 0.2)).map((entry) => entry[0]);
|
||||||
for (let i = 0; i < toRemove; i++)
|
for (const key of keysToRemove) buckets.delete(key);
|
||||||
// eslint-disable-next-line security/detect-object-injection -- numeric array index
|
|
||||||
buckets.delete(sorted[i][0]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,19 +50,23 @@ export async function rateLimit(key: string, limit: number, windowMs: number): P
|
|||||||
|
|
||||||
cleanup();
|
cleanup();
|
||||||
|
|
||||||
const bucket = buckets.get(key);
|
const windowKey = `mem:${key}`;
|
||||||
|
const bucket = buckets.get(windowKey);
|
||||||
|
|
||||||
if (!bucket || now >= bucket.resetAt) {
|
if (!bucket || now >= bucket.resetAt) {
|
||||||
buckets.set(key, { count: 1, resetAt: now + windowMs });
|
buckets.set(windowKey, { count: 1, resetAt: now + windowMs });
|
||||||
return { ok: true, retryAfter: 0 };
|
return { ok: true, retryAfter: 0 };
|
||||||
}
|
}
|
||||||
if (bucket.count >= limit) {
|
|
||||||
|
const newCount = bucket.count + 1;
|
||||||
|
if (newCount > limit) {
|
||||||
return { ok: false, retryAfter: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)) };
|
return { ok: false, retryAfter: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)) };
|
||||||
}
|
}
|
||||||
bucket.count += 1;
|
|
||||||
|
bucket.count = newCount;
|
||||||
return { ok: true, retryAfter: 0 };
|
return { ok: true, retryAfter: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Best-effort client IP from the proxy headers our edge proxy forwards. */
|
|
||||||
export async function clientIp(): Promise<string> {
|
export async function clientIp(): Promise<string> {
|
||||||
try {
|
try {
|
||||||
const h = await headers();
|
const h = await headers();
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
import { ZodError } from "zod";
|
import { ZodError } from "zod";
|
||||||
|
import { handleActionError as foundationHandle } from "@/lib/foundation/action";
|
||||||
// ── Action Result Type ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
export type ActionResult<T = Record<string, unknown>> =
|
export type ActionResult<T = Record<string, unknown>> =
|
||||||
{ ok: true; data?: T } | { ok: false; error: string; fieldErrors?: Record<string, string[]> };
|
| { ok: true; data?: T }
|
||||||
|
| { ok: false; error: string; fieldErrors?: Record<string, string[]> };
|
||||||
// ── Helper to build results ──────────────────────────────────────────
|
|
||||||
|
|
||||||
export function actionOk<T = Record<string, unknown>>(data?: T): ActionResult<T> {
|
export function actionOk<T = Record<string, unknown>>(data?: T): ActionResult<T> {
|
||||||
return { ok: true, data: data ?? ({} as T) };
|
return { ok: true, data: data ?? ({} as T) };
|
||||||
@@ -15,8 +13,6 @@ export function actionError(message: string): ActionResult<never> {
|
|||||||
return { ok: false, error: message };
|
return { ok: false, error: message };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Throwable error ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export class ActionError extends Error {
|
export class ActionError extends Error {
|
||||||
constructor(message: string) {
|
constructor(message: string) {
|
||||||
super(message);
|
super(message);
|
||||||
@@ -24,8 +20,6 @@ export class ActionError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Error handler ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function handleActionError(error: unknown): ActionResult<never> {
|
export function handleActionError(error: unknown): ActionResult<never> {
|
||||||
if (error instanceof ZodError) {
|
if (error instanceof ZodError) {
|
||||||
return {
|
return {
|
||||||
@@ -37,14 +31,5 @@ export function handleActionError(error: unknown): ActionResult<never> {
|
|||||||
if (error instanceof Error && error.name === "ActionError") {
|
if (error instanceof Error && error.name === "ActionError") {
|
||||||
return { ok: false, error: error.message };
|
return { ok: false, error: error.message };
|
||||||
}
|
}
|
||||||
// Prisma P2025
|
return foundationHandle(error) as ActionResult<never>;
|
||||||
if (
|
|
||||||
error instanceof Error &&
|
|
||||||
error.constructor.name === "PrismaClientKnownRequestError" &&
|
|
||||||
(error as Error & { code?: string }).code === "P2025"
|
|
||||||
) {
|
|
||||||
return { ok: false, error: "Not found" };
|
|
||||||
}
|
|
||||||
console.error("[Action error]", error);
|
|
||||||
return { ok: false, error: "Internal server error" };
|
|
||||||
}
|
}
|
||||||
+4
-129
@@ -1,132 +1,7 @@
|
|||||||
import type { z } from "zod";
|
import { adminAction as foundationAdmin, authAction as foundationAuth } from "@/lib/foundation/action";
|
||||||
import { auth } from "@/lib/auth";
|
import type { ActionResult } from "@/lib/safe-action-shared";
|
||||||
import { canAccess, getApiAdminContext } from "@/lib/permissions";
|
|
||||||
import { type ActionResult, actionError, handleActionError } from "@/lib/safe-action-shared";
|
|
||||||
import { logAuthorizationEvent } from "@/lib/admin/authorization-events";
|
|
||||||
|
|
||||||
export type { ActionResult };
|
export type { ActionResult };
|
||||||
|
|
||||||
// ── Admin action wrapper ─────────────────────────────────────────────
|
export const adminAction = foundationAdmin;
|
||||||
|
export const authAction = foundationAuth;
|
||||||
interface AdminActionOptions<TSchema extends z.ZodType | undefined = undefined> {
|
|
||||||
permission?: string;
|
|
||||||
schema?: TSchema;
|
|
||||||
}
|
|
||||||
|
|
||||||
type AdminActionContext<TSchema extends z.ZodType | undefined> = {
|
|
||||||
session: { user: { id: number; username: string; rank: number; look: string; mail: string } };
|
|
||||||
} & (TSchema extends z.ZodType ? { data: z.infer<TSchema> } : object);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a server action with admin auth + optional permission + optional Zod validation.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* export const updateNews = adminAction(
|
|
||||||
* { permission: PERMS.NEWS_EDIT, schema: updateNewsSchema },
|
|
||||||
* async (ctx) => {
|
|
||||||
* await prisma.websiteArticle.update({ ... })
|
|
||||||
* return actionOk()
|
|
||||||
* }
|
|
||||||
* )
|
|
||||||
*/
|
|
||||||
export function adminAction<TSchema extends z.ZodType | undefined = undefined>(
|
|
||||||
options: AdminActionOptions<TSchema>,
|
|
||||||
handler: (ctx: AdminActionContext<TSchema>) => Promise<ActionResult>,
|
|
||||||
) {
|
|
||||||
return async (
|
|
||||||
// biome-ignore lint/suspicious/noConfusingVoidType: void in conditional return lets callers omit the arg when there's no schema
|
|
||||||
input: TSchema extends z.ZodType ? z.input<TSchema> : void,
|
|
||||||
): Promise<ActionResult> => {
|
|
||||||
try {
|
|
||||||
const apiCtx = await getApiAdminContext();
|
|
||||||
if (!apiCtx) return actionError("Unauthorized");
|
|
||||||
|
|
||||||
if (options.permission) {
|
|
||||||
if (!canAccess(apiCtx.permissions, options.permission, apiCtx.session.user.rank)) {
|
|
||||||
await logAuthorizationEvent({
|
|
||||||
kind: "permission.denied",
|
|
||||||
userId: apiCtx.session.user.id,
|
|
||||||
username: apiCtx.session.user.name ?? undefined,
|
|
||||||
rank: apiCtx.session.user.rank,
|
|
||||||
permission: options.permission,
|
|
||||||
source: "adminAction",
|
|
||||||
reason: "Permission check denied",
|
|
||||||
});
|
|
||||||
return actionError("Unauthorized");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let data: unknown;
|
|
||||||
if (options.schema) {
|
|
||||||
const parsed = options.schema.safeParse(input);
|
|
||||||
if (!parsed.success) {
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
error: "Validation failed",
|
|
||||||
fieldErrors: parsed.error.flatten().fieldErrors as Record<string, string[]>,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
data = parsed.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ctx = {
|
|
||||||
session: apiCtx.session,
|
|
||||||
...(options.schema ? { data } : {}),
|
|
||||||
} as AdminActionContext<TSchema>;
|
|
||||||
|
|
||||||
return await handler(ctx);
|
|
||||||
} catch (error) {
|
|
||||||
return handleActionError(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Auth action wrapper (no permissions) ─────────────────────────────
|
|
||||||
|
|
||||||
interface AuthActionOptions<TSchema extends z.ZodType | undefined = undefined> {
|
|
||||||
schema?: TSchema;
|
|
||||||
}
|
|
||||||
|
|
||||||
type AuthActionContext<TSchema extends z.ZodType | undefined> = {
|
|
||||||
session: { user: { id: number; username: string; rank: number; look: string; mail: string } };
|
|
||||||
} & (TSchema extends z.ZodType ? { data: z.infer<TSchema> } : object);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a server action with auth only (no permission check).
|
|
||||||
*/
|
|
||||||
export function authAction<TSchema extends z.ZodType | undefined = undefined>(
|
|
||||||
options: AuthActionOptions<TSchema>,
|
|
||||||
handler: (ctx: AuthActionContext<TSchema>) => Promise<ActionResult>,
|
|
||||||
) {
|
|
||||||
return async (
|
|
||||||
// biome-ignore lint/suspicious/noConfusingVoidType: void in conditional return lets callers omit the arg when there's no schema
|
|
||||||
input: TSchema extends z.ZodType ? z.input<TSchema> : void,
|
|
||||||
): Promise<ActionResult> => {
|
|
||||||
try {
|
|
||||||
const session = await auth();
|
|
||||||
if (!session?.user) return actionError("Unauthorized");
|
|
||||||
|
|
||||||
let data: unknown;
|
|
||||||
if (options.schema) {
|
|
||||||
const parsed = options.schema.safeParse(input);
|
|
||||||
if (!parsed.success) {
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
error: "Validation failed",
|
|
||||||
fieldErrors: parsed.error.flatten().fieldErrors as Record<string, string[]>,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
data = parsed.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ctx = {
|
|
||||||
session,
|
|
||||||
...(options.schema ? { data } : {}),
|
|
||||||
} as AuthActionContext<TSchema>;
|
|
||||||
|
|
||||||
return await handler(ctx);
|
|
||||||
} catch (error) {
|
|
||||||
return handleActionError(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
+18
-5
@@ -2,10 +2,15 @@ import { NextResponse } from "next/server";
|
|||||||
import { proxyAuth } from "@/lib/proxy-auth";
|
import { proxyAuth } from "@/lib/proxy-auth";
|
||||||
import { shouldRedirectAdminRequest } from "@/lib/proxy-access";
|
import { shouldRedirectAdminRequest } from "@/lib/proxy-access";
|
||||||
|
|
||||||
// Edge proxy (formerly "middleware"): Prisma can't run here, so we only forward
|
const SECURITY_HEADERS: Record<string, string> = {
|
||||||
// the request path (so server components / the access guard can read it via
|
"X-Content-Type-Options": "nosniff",
|
||||||
// headers()) and normalize the real client IP. The DB-backed banned/maintenance
|
"X-Frame-Options": "DENY",
|
||||||
// checks happen in src/lib/access-guard.ts (Node runtime) from the root layout.
|
"X-XSS-Protection": "0",
|
||||||
|
"Referrer-Policy": "strict-origin-when-cross-origin",
|
||||||
|
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
||||||
|
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
|
||||||
|
};
|
||||||
|
|
||||||
export const proxy = proxyAuth((req) => {
|
export const proxy = proxyAuth((req) => {
|
||||||
if (shouldRedirectAdminRequest(req.nextUrl.pathname, req.auth?.user ?? null)) {
|
if (shouldRedirectAdminRequest(req.nextUrl.pathname, req.auth?.user ?? null)) {
|
||||||
return NextResponse.redirect(new URL("/login", req.url));
|
return NextResponse.redirect(new URL("/login", req.url));
|
||||||
@@ -13,13 +18,21 @@ export const proxy = proxyAuth((req) => {
|
|||||||
|
|
||||||
const headers = new Headers(req.headers);
|
const headers = new Headers(req.headers);
|
||||||
headers.set("x-pathname", req.nextUrl.pathname);
|
headers.set("x-pathname", req.nextUrl.pathname);
|
||||||
|
|
||||||
const ip =
|
const ip =
|
||||||
req.headers.get("cf-connecting-ip") ??
|
req.headers.get("cf-connecting-ip") ??
|
||||||
req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
||||||
req.headers.get("x-real-ip") ??
|
req.headers.get("x-real-ip") ??
|
||||||
"";
|
"";
|
||||||
if (ip) headers.set("x-real-client-ip", ip);
|
if (ip) headers.set("x-real-client-ip", ip);
|
||||||
return NextResponse.next({ request: { headers } });
|
|
||||||
|
const response = NextResponse.next({ request: { headers } });
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(SECURITY_HEADERS)) {
|
||||||
|
response.headers.set(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
});
|
});
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
|
|||||||
Reference in new issue
Block a user