Enforce admin CSRF, harden catalog translate, use CMS hotel name for PayPal.
Local Build and Deploy / deploy (push) Successful in 1m38s
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:
1 parent
6b884ad25a
commit
2de3696993
18 files changed
+218
-62
No files matched your search
@@ -5,9 +5,11 @@ import { Prisma } from "@/generated/prisma/client";
|
|||||||
import { requirePermission } from "@/lib/admin/guard";
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { logAudit } from "@/lib/services/audit";
|
||||||
import { allocateCatalogItemId } from "@/lib/services/furni-import";
|
import { allocateCatalogItemId } from "@/lib/services/furni-import";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
import { rcon } from "@/lib/services/rcon";
|
||||||
import { logStaffActivity } from "@/lib/services/staff-activity";
|
import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||||
|
import { translateItemsSchema } from "@/lib/validators/catalog";
|
||||||
|
|
||||||
const CATALOG_ITEM_FIELDS = [
|
const CATALOG_ITEM_FIELDS = [
|
||||||
"pageId",
|
"pageId",
|
||||||
@@ -323,13 +325,19 @@ export async function updateCatalogItem({
|
|||||||
return { ok: true as const, data: {} };
|
return { ok: true as const, data: {} };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function translateCatalogItems({
|
export async function translateCatalogItems(input: {
|
||||||
items,
|
|
||||||
}: {
|
|
||||||
/** `id` is items_base.id (not catalog_items.id) */
|
/** `id` is items_base.id (not catalog_items.id) */
|
||||||
items: Array<{ id: number; publicName: string; description: string }>;
|
items: Array<{ id: number; publicName: string; description?: string }>;
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
|
const parsed = translateItemsSchema.safeParse(input);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return {
|
||||||
|
ok: false as const,
|
||||||
|
error: parsed.error.issues[0]?.message ?? "Invalid translate payload",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const { items } = parsed.data;
|
||||||
const { invalidateFurniDataCache } = await import(
|
const { invalidateFurniDataCache } = await import(
|
||||||
"@/lib/services/catalog-items-loader"
|
"@/lib/services/catalog-items-loader"
|
||||||
);
|
);
|
||||||
@@ -413,6 +421,17 @@ export async function translateCatalogItems({
|
|||||||
}
|
}
|
||||||
|
|
||||||
await rcon.updateCatalog();
|
await rcon.updateCatalog();
|
||||||
|
await logAudit({
|
||||||
|
userId: staff.id,
|
||||||
|
action: "items_base_translate",
|
||||||
|
target: "ItemsBase",
|
||||||
|
after: {
|
||||||
|
namesUpdated,
|
||||||
|
descriptionsUpdated,
|
||||||
|
furniDataUpdated: furniResult.updated > 0,
|
||||||
|
furniDataInserted: furniResult.inserted,
|
||||||
|
},
|
||||||
|
});
|
||||||
revalidatePath("/admin/catalog");
|
revalidatePath("/admin/catalog");
|
||||||
return {
|
return {
|
||||||
ok: true as const,
|
ok: true as const,
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { Badge } from "@/components/ui/badge";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
|
|
||||||
// ── Types ─────────────────────────────────────────────────────────────────────
|
// ── Types ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -62,7 +63,7 @@ async function runSseImport(
|
|||||||
onDone: (classname: string) => void,
|
onDone: (classname: string) => void,
|
||||||
onComplete: (succeeded: number, failed: number) => void,
|
onComplete: (succeeded: number, failed: number) => void,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const res = await fetch(url, {
|
const res = await adminFetch(url, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
@@ -202,7 +203,7 @@ function SourcesManager({
|
|||||||
async function handleSave(src: Partial<CloneSource>) {
|
async function handleSave(src: Partial<CloneSource>) {
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/clone", {
|
const res = await adminFetch("/api/admin/import/clone", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify(src),
|
body: JSON.stringify(src),
|
||||||
@@ -224,7 +225,7 @@ function SourcesManager({
|
|||||||
async function handleDelete(src: CloneSource) {
|
async function handleDelete(src: CloneSource) {
|
||||||
setDeletingId(src.id);
|
setDeletingId(src.id);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/import/clone?id=${encodeURIComponent(src.id)}`,
|
`/api/admin/import/clone?id=${encodeURIComponent(src.id)}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
@@ -417,7 +418,7 @@ function FurniGrid({ source }: FurniGridProps) {
|
|||||||
});
|
});
|
||||||
if (search) params.set("search", search);
|
if (search) params.set("search", search);
|
||||||
if (filterVal !== "all") params.set("filter", filterVal);
|
if (filterVal !== "all") params.set("filter", filterVal);
|
||||||
const res = await fetch(`/api/admin/import/clone?${params}`);
|
const res = await adminFetch(`/api/admin/import/clone?${params}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
setError(data.error || "Failed to load");
|
setError(data.error || "Failed to load");
|
||||||
@@ -535,7 +536,7 @@ function FurniGrid({ source }: FurniGridProps) {
|
|||||||
async function cloneAll() {
|
async function cloneAll() {
|
||||||
let names: string[] = [];
|
let names: string[] = [];
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/import/clone?source=${encodeURIComponent(source.id)}&action=clonable`,
|
`/api/admin/import/clone?source=${encodeURIComponent(source.id)}&action=clonable`,
|
||||||
);
|
);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
@@ -913,7 +914,7 @@ export function ImportCloneClient() {
|
|||||||
|
|
||||||
const fetchSources = useCallback(async () => {
|
const fetchSources = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/clone?action=sources");
|
const res = await adminFetch("/api/admin/import/clone?action=sources");
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
setSources(data.sources || []);
|
setSources(data.sources || []);
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { getAvatarUrl } from "@/lib/imager";
|
import { getAvatarUrl } from "@/lib/imager";
|
||||||
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
|
|
||||||
// ── Shared types ─────────────────────────────────────────────────────────────
|
// ── Shared types ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -50,7 +51,7 @@ async function runSseImport(
|
|||||||
onDone: (label: string) => void,
|
onDone: (label: string) => void,
|
||||||
onComplete: (succeeded: number, failed: number) => void,
|
onComplete: (succeeded: number, failed: number) => void,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const res = await fetch(url, {
|
const res = await adminFetch(url, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
@@ -155,7 +156,7 @@ function LibsView() {
|
|||||||
try {
|
try {
|
||||||
const params = new URLSearchParams({ page: String(pageNum) });
|
const params = new URLSearchParams({ page: String(pageNum) });
|
||||||
if (search) params.set("search", search);
|
if (search) params.set("search", search);
|
||||||
const res = await fetch(`/api/admin/import/clothing?${params}`);
|
const res = await adminFetch(`/api/admin/import/clothing?${params}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
setError(data.error || "Failed to load");
|
setError(data.error || "Failed to load");
|
||||||
@@ -251,7 +252,7 @@ function LibsView() {
|
|||||||
async function remove(p: FigureItem) {
|
async function remove(p: FigureItem) {
|
||||||
setBusyLib(p.lib);
|
setBusyLib(p.lib);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/import/clothing?lib=${encodeURIComponent(p.lib)}`,
|
`/api/admin/import/clothing?lib=${encodeURIComponent(p.lib)}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
@@ -532,7 +533,7 @@ function SetsView() {
|
|||||||
try {
|
try {
|
||||||
const params = new URLSearchParams({ page: String(pageNum) });
|
const params = new URLSearchParams({ page: String(pageNum) });
|
||||||
if (search) params.set("search", search);
|
if (search) params.set("search", search);
|
||||||
const res = await fetch(`/api/admin/import/clothing/sets?${params}`);
|
const res = await adminFetch(`/api/admin/import/clothing/sets?${params}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
setError(data.error || "Failed to load");
|
setError(data.error || "Failed to load");
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { Badge } from "@/components/ui/badge";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
|
|
||||||
interface EffectItem {
|
interface EffectItem {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -50,7 +51,7 @@ export function ImportEffectsClient() {
|
|||||||
try {
|
try {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (search) params.set("search", search);
|
if (search) params.set("search", search);
|
||||||
const res = await fetch(`/api/admin/import/effects?${params}`);
|
const res = await adminFetch(`/api/admin/import/effects?${params}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
setError(data.error || "Failed to load");
|
setError(data.error || "Failed to load");
|
||||||
@@ -101,7 +102,7 @@ export function ImportEffectsClient() {
|
|||||||
|
|
||||||
async function importViaSse(items: EffectItem[]) {
|
async function importViaSse(items: EffectItem[]) {
|
||||||
setBatchProgress({ done: 0, total: items.length });
|
setBatchProgress({ done: 0, total: items.length });
|
||||||
const res = await fetch("/api/admin/import/effects/batch", {
|
const res = await adminFetch("/api/admin/import/effects/batch", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ items, concurrency: 3 }),
|
body: JSON.stringify({ items, concurrency: 3 }),
|
||||||
@@ -167,7 +168,7 @@ export function ImportEffectsClient() {
|
|||||||
async function remove(e: EffectItem) {
|
async function remove(e: EffectItem) {
|
||||||
setBusyLib(e.lib);
|
setBusyLib(e.lib);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/import/effects?lib=${encodeURIComponent(e.lib)}`,
|
`/api/admin/import/effects?lib=${encodeURIComponent(e.lib)}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { NitroEditorDialog } from "./nitro-editor-dialog";
|
import { NitroEditorDialog } from "./nitro-editor-dialog";
|
||||||
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
|
|
||||||
interface FurniItem {
|
interface FurniItem {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -222,7 +223,7 @@ export function ImportFurniClient() {
|
|||||||
|
|
||||||
const fetchStats = useCallback(async () => {
|
const fetchStats = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/furni?action=stats");
|
const res = await adminFetch("/api/admin/import/furni?action=stats");
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
setStats({
|
setStats({
|
||||||
@@ -327,7 +328,7 @@ export function ImportFurniClient() {
|
|||||||
if (status === "missing-nitro") {
|
if (status === "missing-nitro") {
|
||||||
params.set("action", "missing-nitro");
|
params.set("action", "missing-nitro");
|
||||||
}
|
}
|
||||||
const res = await fetch(`/api/admin/import/furni?${params}`);
|
const res = await adminFetch(`/api/admin/import/furni?${params}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
setError(data.error || "Failed to load");
|
setError(data.error || "Failed to load");
|
||||||
@@ -417,7 +418,7 @@ export function ImportFurniClient() {
|
|||||||
async function doImport(item: FurniItem) {
|
async function doImport(item: FurniItem) {
|
||||||
setImportingId(item.classname);
|
setImportingId(item.classname);
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/furni", {
|
const res = await adminFetch("/api/admin/import/furni", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -483,7 +484,7 @@ export function ImportFurniClient() {
|
|||||||
setBatchProgress(new Map(initialProgress));
|
setBatchProgress(new Map(initialProgress));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/furni/batch", {
|
const res = await adminFetch("/api/admin/import/furni/batch", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -590,7 +591,7 @@ export function ImportFurniClient() {
|
|||||||
async function regenNitro(item: FurniItem) {
|
async function regenNitro(item: FurniItem) {
|
||||||
setRegeneratingNitro((prev) => new Set(prev).add(item.classname));
|
setRegeneratingNitro((prev) => new Set(prev).add(item.classname));
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/furni", {
|
const res = await adminFetch("/api/admin/import/furni", {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -640,7 +641,7 @@ export function ImportFurniClient() {
|
|||||||
setRegenProgress(new Map(initialProgress));
|
setRegenProgress(new Map(initialProgress));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/furni/batch-regen", {
|
const res = await adminFetch("/api/admin/import/furni/batch-regen", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -753,7 +754,7 @@ export function ImportFurniClient() {
|
|||||||
async function startReorganize() {
|
async function startReorganize() {
|
||||||
setReorganizing(true);
|
setReorganizing(true);
|
||||||
try {
|
try {
|
||||||
const previewRes = await fetch("/api/admin/import/furni?dryrun=1", {
|
const previewRes = await adminFetch("/api/admin/import/furni?dryrun=1", {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
});
|
});
|
||||||
const previewData = await previewRes.json();
|
const previewData = await previewRes.json();
|
||||||
@@ -779,7 +780,7 @@ export function ImportFurniClient() {
|
|||||||
setReorgPreview(null);
|
setReorgPreview(null);
|
||||||
setReorganizing(true);
|
setReorganizing(true);
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/furni", { method: "PUT" });
|
const res = await adminFetch("/api/admin/import/furni", { method: "PUT" });
|
||||||
const d = await res.json();
|
const d = await res.json();
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import { Label } from "@/components/ui/label";
|
|||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
|
|
||||||
interface NitroEditorDialogProps {
|
interface NitroEditorDialogProps {
|
||||||
classname: string;
|
classname: string;
|
||||||
@@ -121,7 +122,7 @@ export function NitroEditorDialog({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setJsonError(null);
|
setJsonError(null);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/import/furni/nitro-editor?classname=${encodeURIComponent(classname)}`,
|
`/api/admin/import/furni/nitro-editor?classname=${encodeURIComponent(classname)}`,
|
||||||
);
|
);
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -189,7 +190,7 @@ export function NitroEditorDialog({
|
|||||||
|
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/import/furni/nitro-editor", {
|
const res = await adminFetch("/api/admin/import/furni/nitro-editor", {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { Badge } from "@/components/ui/badge";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
|
|
||||||
interface PetItem {
|
interface PetItem {
|
||||||
lib: string;
|
lib: string;
|
||||||
@@ -57,7 +58,7 @@ export function ImportPetsClient() {
|
|||||||
try {
|
try {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (search) params.set("search", search);
|
if (search) params.set("search", search);
|
||||||
const res = await fetch(`/api/admin/import/pets?${params}`);
|
const res = await adminFetch(`/api/admin/import/pets?${params}`);
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
setError(data.error || "Failed to load");
|
setError(data.error || "Failed to load");
|
||||||
@@ -99,7 +100,7 @@ export function ImportPetsClient() {
|
|||||||
|
|
||||||
async function importViaSse(items: PetItem[]) {
|
async function importViaSse(items: PetItem[]) {
|
||||||
setBatchProgress({ done: 0, total: items.length });
|
setBatchProgress({ done: 0, total: items.length });
|
||||||
const res = await fetch("/api/admin/import/pets/batch", {
|
const res = await adminFetch("/api/admin/import/pets/batch", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ items, concurrency: 3 }),
|
body: JSON.stringify({ items, concurrency: 3 }),
|
||||||
@@ -161,7 +162,7 @@ export function ImportPetsClient() {
|
|||||||
async function remove(p: PetItem) {
|
async function remove(p: PetItem) {
|
||||||
setBusyLib(p.lib);
|
setBusyLib(p.lib);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/import/pets?lib=${encodeURIComponent(p.lib)}`,
|
`/api/admin/import/pets?lib=${encodeURIComponent(p.lib)}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
|
|||||||
+17
-12
@@ -11,6 +11,7 @@ import { LanguageSwitcher } from "@/components/language-switcher";
|
|||||||
import { ThemeSwitcher } from "@/components/theme-switcher";
|
import { ThemeSwitcher } from "@/components/theme-switcher";
|
||||||
import { requireStaff } from "@/lib/admin/guard";
|
import { requireStaff } from "@/lib/admin/guard";
|
||||||
import { ADMIN_NAV_GROUPS } from "@/lib/admin-nav";
|
import { ADMIN_NAV_GROUPS } from "@/lib/admin-nav";
|
||||||
|
import { setCsrfCookie } from "@/lib/foundation/security";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
@@ -22,6 +23,7 @@ export default async function AdminLayout({
|
|||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const staff = await requireStaff();
|
const staff = await requireStaff();
|
||||||
|
const csrfToken = await setCsrfCookie();
|
||||||
if (await siteSettings.getBool("force_staff_2fa", false)) {
|
if (await siteSettings.getBool("force_staff_2fa", false)) {
|
||||||
const u = await prisma.user
|
const u = await prisma.user
|
||||||
.findUnique({
|
.findUnique({
|
||||||
@@ -33,18 +35,21 @@ export default async function AdminLayout({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AdminMobileWrapper sidebar={<Sidebar staff={staff} />}>
|
<>
|
||||||
<div
|
<meta name="csrf-token" content={csrfToken} />
|
||||||
data-admin
|
<AdminMobileWrapper sidebar={<Sidebar staff={staff} />}>
|
||||||
className="flex flex-col min-w-0 p-5 lg:p-6 min-h-screen"
|
<div
|
||||||
style={{ backgroundColor: "var(--admin-canvas)" }}
|
data-admin
|
||||||
>
|
className="flex flex-col min-w-0 p-5 lg:p-6 min-h-screen"
|
||||||
<AdminTopbar staff={staff} />
|
style={{ backgroundColor: "var(--admin-canvas)" }}
|
||||||
<section className="admin-page flex-1">
|
>
|
||||||
<AdminHubChrome>{children}</AdminHubChrome>
|
<AdminTopbar staff={staff} />
|
||||||
</section>
|
<section className="admin-page flex-1">
|
||||||
</div>
|
<AdminHubChrome>{children}</AdminHubChrome>
|
||||||
</AdminMobileWrapper>
|
</section>
|
||||||
|
</div>
|
||||||
|
</AdminMobileWrapper>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ import { useServerAction } from "@/hooks/use-server-action";
|
|||||||
import { invalidateSongPickerCache } from "@/lib/client-cache/song-picker-cache";
|
import { invalidateSongPickerCache } from "@/lib/client-cache/song-picker-cache";
|
||||||
import { parseTraxChannels } from "@/lib/trax-format";
|
import { parseTraxChannels } from "@/lib/trax-format";
|
||||||
import { TraxPlayer } from "./trax-player";
|
import { TraxPlayer } from "./trax-player";
|
||||||
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
|
|
||||||
interface SoundtrackRow {
|
interface SoundtrackRow {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -434,7 +435,7 @@ function UploadDialog({
|
|||||||
fd.append("author", author.trim());
|
fd.append("author", author.trim());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/sounds/upload", {
|
const res = await adminFetch("/api/admin/sounds/upload", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: fd,
|
body: fd,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
} from "@/lib/services/paypal-topup";
|
} from "@/lib/services/paypal-topup";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
import { rcon } from "@/lib/services/rcon";
|
||||||
import { sendCurrency } from "@/lib/services/send-currency";
|
import { sendCurrency } from "@/lib/services/send-currency";
|
||||||
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
@@ -157,6 +158,9 @@ export async function POST(req: Request): Promise<Response> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const hotelName =
|
||||||
|
(await siteSettings.get("hotel_name", env.HOTEL_NAME)) ?? env.HOTEL_NAME;
|
||||||
|
|
||||||
if (result.status !== "COMPLETED") {
|
if (result.status !== "COMPLETED") {
|
||||||
// Record the non-completed attempt so support can trace it.
|
// Record the non-completed attempt so support can trace it.
|
||||||
try {
|
try {
|
||||||
@@ -164,7 +168,7 @@ export async function POST(req: Request): Promise<Response> {
|
|||||||
where: { userId, transactionId: orderId, status: "CREATED" },
|
where: { userId, transactionId: orderId, status: "CREATED" },
|
||||||
data: {
|
data: {
|
||||||
status: result.status,
|
status: result.status,
|
||||||
description: `${env.HOTEL_NAME} top-up (not completed)`,
|
description: `${hotelName} top-up (not completed)`,
|
||||||
amount: result.amount,
|
amount: result.amount,
|
||||||
currency: result.currency,
|
currency: result.currency,
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
@@ -189,7 +193,7 @@ export async function POST(req: Request): Promise<Response> {
|
|||||||
where: { userId, transactionId: orderId, status: "CREATED" },
|
where: { userId, transactionId: orderId, status: "CREATED" },
|
||||||
data: {
|
data: {
|
||||||
status: "CAPTURED_PENDING_CREDIT",
|
status: "CAPTURED_PENDING_CREDIT",
|
||||||
description: `${env.HOTEL_NAME} top-up: ${credits} credits`,
|
description: `${hotelName} top-up: ${credits} credits`,
|
||||||
amount: result.amount,
|
amount: result.amount,
|
||||||
currency: result.currency,
|
currency: result.currency,
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
PAYPAL_CURRENCY,
|
PAYPAL_CURRENCY,
|
||||||
} from "@/lib/services/paypal";
|
} from "@/lib/services/paypal";
|
||||||
import { recordCreatedTopup } from "@/lib/services/paypal-topup";
|
import { recordCreatedTopup } from "@/lib/services/paypal-topup";
|
||||||
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
@@ -68,10 +69,12 @@ export async function POST(req: Request): Promise<Response> {
|
|||||||
|
|
||||||
const credits = Math.floor(amount * creditsPerUnit());
|
const credits = Math.floor(amount * creditsPerUnit());
|
||||||
const base = env.APP_URL.replace(/\/+$/, "");
|
const base = env.APP_URL.replace(/\/+$/, "");
|
||||||
|
const hotelName =
|
||||||
|
(await siteSettings.get("hotel_name", env.HOTEL_NAME)) ?? env.HOTEL_NAME;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const order = await createOrder(amount, {
|
const order = await createOrder(amount, {
|
||||||
description: `${env.HOTEL_NAME} top-up: ${credits} credits`,
|
description: `${hotelName} top-up: ${credits} credits`,
|
||||||
returnUrl: `${base}/shop/topup?status=success`,
|
returnUrl: `${base}/shop/topup?status=success`,
|
||||||
cancelUrl: `${base}/shop/topup?status=cancel`,
|
cancelUrl: `${base}/shop/topup?status=cancel`,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ import {
|
|||||||
} from "@/components/ui/tooltip";
|
} from "@/components/ui/tooltip";
|
||||||
import { translateCaption } from "@/lib/catalog-translations";
|
import { translateCaption } from "@/lib/catalog-translations";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
|
|
||||||
/* ─── Types ──────────────────────────────────────────────── */
|
/* ─── Types ──────────────────────────────────────────────── */
|
||||||
|
|
||||||
@@ -211,7 +212,7 @@ export function CatalogTree({
|
|||||||
setSearching(true);
|
setSearching(true);
|
||||||
try {
|
try {
|
||||||
const catParam = catalogType === "bc" ? "&catalog=bc" : "";
|
const catParam = catalogType === "bc" ? "&catalog=bc" : "";
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/catalog/tree?search=${encodeURIComponent(searchQuery.trim())}${catParam}`,
|
`/api/admin/catalog/tree?search=${encodeURIComponent(searchQuery.trim())}${catParam}`,
|
||||||
);
|
);
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
@@ -237,7 +238,7 @@ export function CatalogTree({
|
|||||||
const handleToggleEnabled = useCallback(
|
const handleToggleEnabled = useCallback(
|
||||||
async (node: TreeNode) => {
|
async (node: TreeNode) => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/catalog/tree", {
|
const res = await adminFetch("/api/admin/catalog/tree", {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: `{"pageId":${node.id},"toggleField":"toggleEnabled"${catBody}}`,
|
body: `{"pageId":${node.id},"toggleField":"toggleEnabled"${catBody}}`,
|
||||||
@@ -257,7 +258,7 @@ export function CatalogTree({
|
|||||||
const handleToggleVisible = useCallback(
|
const handleToggleVisible = useCallback(
|
||||||
async (node: TreeNode) => {
|
async (node: TreeNode) => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/admin/catalog/tree", {
|
const res = await adminFetch("/api/admin/catalog/tree", {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: `{"pageId":${node.id},"toggleField":"toggleVisible"${catBody}}`,
|
body: `{"pageId":${node.id},"toggleField":"toggleVisible"${catBody}}`,
|
||||||
@@ -290,7 +291,7 @@ export function CatalogTree({
|
|||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/catalog/tree?pageId=${node.id}&mode=reparent${catParam}`,
|
`/api/admin/catalog/tree?pageId=${node.id}&mode=reparent${catParam}`,
|
||||||
{
|
{
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
@@ -571,7 +572,7 @@ function TreeItem({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const catParam = catalogType === "bc" ? "&catalog=bc" : "";
|
const catParam = catalogType === "bc" ? "&catalog=bc" : "";
|
||||||
const res = await fetch(
|
const res = await adminFetch(
|
||||||
`/api/admin/catalog/tree?parentId=${node.id}${catParam}`,
|
`/api/admin/catalog/tree?parentId=${node.id}${catParam}`,
|
||||||
);
|
);
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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",
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -25,7 +25,10 @@ export function withAdmin(
|
|||||||
handler: AdminHandler,
|
handler: AdminHandler,
|
||||||
) {
|
) {
|
||||||
return async (request: NextRequest, routeContext: RouteContext = {}) => {
|
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 =
|
const csrfToken =
|
||||||
request.headers.get("x-csrf-token") ??
|
request.headers.get("x-csrf-token") ??
|
||||||
request.headers.get("csrf-token") ??
|
request.headers.get("csrf-token") ??
|
||||||
|
|||||||
@@ -5,9 +5,15 @@ import { env } from "@/env";
|
|||||||
import type { IpAddress } from "./types";
|
import type { IpAddress } from "./types";
|
||||||
|
|
||||||
const CSRF_BYTES = 32;
|
const CSRF_BYTES = 32;
|
||||||
const CSRF_COOKIE = "__Host-csrf-token";
|
|
||||||
const CSRF_COOKIE_MAX_AGE = 86400; // 24h
|
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(
|
const ALLOWED_HOSTS: ReadonlySet<string> = new Set(
|
||||||
[
|
[
|
||||||
env.APP_URL ? new URL(env.APP_URL).host : "",
|
env.APP_URL ? new URL(env.APP_URL).host : "",
|
||||||
@@ -58,7 +64,7 @@ export function redirectSafe(
|
|||||||
redirect(safeRedirect(destination, fallback));
|
redirect(safeRedirect(destination, fallback));
|
||||||
}
|
}
|
||||||
|
|
||||||
function csrfCookieOpts(): {
|
function csrfCookieOpts(value: string): {
|
||||||
name: string;
|
name: string;
|
||||||
value: string;
|
value: string;
|
||||||
httpOnly: boolean;
|
httpOnly: boolean;
|
||||||
@@ -67,11 +73,12 @@ function csrfCookieOpts(): {
|
|||||||
path: string;
|
path: string;
|
||||||
maxAge: number;
|
maxAge: number;
|
||||||
} {
|
} {
|
||||||
|
const isProd = process.env.NODE_ENV === "production";
|
||||||
return {
|
return {
|
||||||
name: CSRF_COOKIE,
|
name: csrfCookieName(),
|
||||||
value: crypto.randomBytes(CSRF_BYTES).toString("hex"),
|
value,
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: true,
|
secure: isProd,
|
||||||
sameSite: "lax" as const,
|
sameSite: "lax" as const,
|
||||||
path: "/",
|
path: "/",
|
||||||
maxAge: CSRF_COOKIE_MAX_AGE,
|
maxAge: CSRF_COOKIE_MAX_AGE,
|
||||||
@@ -80,19 +87,21 @@ function csrfCookieOpts(): {
|
|||||||
|
|
||||||
export async function setCsrfCookie(): Promise<string> {
|
export async function setCsrfCookie(): Promise<string> {
|
||||||
const c = await cookies();
|
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)
|
if (existing?.value && existing.value.length === CSRF_BYTES * 2)
|
||||||
return existing.value;
|
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);
|
c.set(opts.name, opts.value, opts);
|
||||||
return opts.value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function validateCsrfToken(token: string): Promise<boolean> {
|
export async function validateCsrfToken(token: string): Promise<boolean> {
|
||||||
if (!token || token.length !== CSRF_BYTES * 2) return false;
|
if (!token || token.length !== CSRF_BYTES * 2) return false;
|
||||||
try {
|
try {
|
||||||
const c = await cookies();
|
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;
|
if (!stored || stored.length !== CSRF_BYTES * 2) return false;
|
||||||
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(stored));
|
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(stored));
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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>;
|
||||||
Reference in new issue
Block a user