Enforce admin CSRF, harden catalog translate, use CMS hotel name for PayPal.
Local Build and Deploy / deploy (push) Successful in 1m38s

Mutating withAdmin routes now require a double-submit CSRF token; translate is capped at 500 items with audit logging; PayPal descriptions prefer siteSettings hotel_name.

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
SimoandCursor committed 2026-07-18 19:38:42 +02:00
1 parent 6b884ad25a
commit 2de3696993
18 files changed
+218 -62

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
describe("admin CSRF wiring", () => {
it("defaults CSRF on for mutating withAdmin handlers", () => {
const source = readFileSync(
resolve(process.cwd(), "src/lib/api-handler.ts"),
"utf8",
);
expect(source).toContain("options.requireCsrf !== false");
});
it("issues a csrf meta tag from the admin layout", () => {
const source = readFileSync(
resolve(process.cwd(), "src/app/admin/layout.tsx"),
"utf8",
);
expect(source).toContain("setCsrfCookie");
expect(source).toContain('meta name="csrf-token"');
});
it("provides adminFetch helper that sets x-csrf-token", () => {
const source = readFileSync(
resolve(process.cwd(), "src/lib/admin-fetch.ts"),
"utf8",
);
expect(source).toContain("x-csrf-token");
expect(source).toContain("getCsrfToken");
});
});
+31
View File
@@ -0,0 +1,31 @@
const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
/** Read the CSRF token injected by the admin layout `<meta name="csrf-token">`. */
export function getCsrfToken(): string | null {
if (typeof document === "undefined") return null;
return (
document
.querySelector('meta[name="csrf-token"]')
?.getAttribute("content") ?? null
);
}
/**
* Same-origin fetch for admin APIs. Attaches `x-csrf-token` on mutating methods.
*/
export function adminFetch(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
const method = (init?.method ?? "GET").toUpperCase();
const headers = new Headers(init?.headers);
if (MUTATING.has(method)) {
const token = getCsrfToken();
if (token) headers.set("x-csrf-token", token);
}
return fetch(input, {
...init,
headers,
credentials: init?.credentials ?? "same-origin",
});
}
+4 -1
View File
@@ -25,7 +25,10 @@ export function withAdmin(
handler: AdminHandler,
) {
return async (request: NextRequest, routeContext: RouteContext = {}) => {
if (options.requireCsrf === true && MUTATING_METHODS.has(request.method)) {
// CSRF required for mutating admin APIs unless explicitly opted out.
const csrfRequired =
options.requireCsrf !== false && MUTATING_METHODS.has(request.method);
if (csrfRequired) {
const csrfToken =
request.headers.get("x-csrf-token") ??
request.headers.get("csrf-token") ??
+18 -9
View File
@@ -5,9 +5,15 @@ import { env } from "@/env";
import type { IpAddress } from "./types";
const CSRF_BYTES = 32;
const CSRF_COOKIE = "__Host-csrf-token";
const CSRF_COOKIE_MAX_AGE = 86400; // 24h
/** `__Host-` requires Secure; use a plain name on non-HTTPS local dev. */
function csrfCookieName(): string {
return process.env.NODE_ENV === "production"
? "__Host-csrf-token"
: "csrf-token";
}
const ALLOWED_HOSTS: ReadonlySet<string> = new Set(
[
env.APP_URL ? new URL(env.APP_URL).host : "",
@@ -58,7 +64,7 @@ export function redirectSafe(
redirect(safeRedirect(destination, fallback));
}
function csrfCookieOpts(): {
function csrfCookieOpts(value: string): {
name: string;
value: string;
httpOnly: boolean;
@@ -67,11 +73,12 @@ function csrfCookieOpts(): {
path: string;
maxAge: number;
} {
const isProd = process.env.NODE_ENV === "production";
return {
name: CSRF_COOKIE,
value: crypto.randomBytes(CSRF_BYTES).toString("hex"),
name: csrfCookieName(),
value,
httpOnly: true,
secure: true,
secure: isProd,
sameSite: "lax" as const,
path: "/",
maxAge: CSRF_COOKIE_MAX_AGE,
@@ -80,19 +87,21 @@ function csrfCookieOpts(): {
export async function setCsrfCookie(): Promise<string> {
const c = await cookies();
const existing = c.get(CSRF_COOKIE);
const name = csrfCookieName();
const existing = c.get(name);
if (existing?.value && existing.value.length === CSRF_BYTES * 2)
return existing.value;
const opts = csrfCookieOpts();
const value = crypto.randomBytes(CSRF_BYTES).toString("hex");
const opts = csrfCookieOpts(value);
c.set(opts.name, opts.value, opts);
return opts.value;
return value;
}
export async function validateCsrfToken(token: string): Promise<boolean> {
if (!token || token.length !== CSRF_BYTES * 2) return false;
try {
const c = await cookies();
const stored = c.get(CSRF_COOKIE)?.value;
const stored = c.get(csrfCookieName())?.value;
if (!stored || stored.length !== CSRF_BYTES * 2) return false;
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(stored));
} catch {
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { translateItemsSchema } from "@/lib/validators/catalog";
describe("translateItemsSchema", () => {
it("accepts a valid payload", () => {
const parsed = translateItemsSchema.safeParse({
items: [{ id: 1, publicName: "Chair", description: "A chair" }],
});
expect(parsed.success).toBe(true);
});
it("rejects more than 500 items", () => {
const items = Array.from({ length: 501 }, (_, i) => ({
id: i + 1,
publicName: `Item ${i + 1}`,
}));
const parsed = translateItemsSchema.safeParse({ items });
expect(parsed.success).toBe(false);
});
it("rejects oversized public names", () => {
const parsed = translateItemsSchema.safeParse({
items: [{ id: 1, publicName: "x".repeat(256) }],
});
expect(parsed.success).toBe(false);
});
});
+16
View File
@@ -0,0 +1,16 @@
import { z } from "zod";
export const translateItemsSchema = z.object({
items: z
.array(
z.object({
id: z.coerce.number().int().positive(),
publicName: z.string().min(1, "Name is required").max(255),
description: z.string().max(1000).optional().default(""),
}),
)
.min(1, "At least one item required")
.max(500),
});
export type TranslateItemsInput = z.infer<typeof translateItemsSchema>;