refactor: drop toast + over-engineered extras, add inline admin feedback
CI / quality (push) Waiting to run
CI / quality (push) Waiting to run
Phase 1 cleanup of the personal-site revamp. Backend/architecture untouched; changes are limited to removing unused complexity and restoring feedback. Removals - Toast system: delete react-hot-toast, Toaster, QueryToastBridge, lib/toast, the toggle/easter-egg calls, related i18n keys and the dependency. - Contact protection: remove Turnstile + per-IP rate limiting (lib/contact-guard, lib/contact-protection, admin screen, form widget, app-config wiring, nav entry, test). - Speculative specs: delete orders, products, downloads, project-inquiry. Inline feedback (replaces toast, no new deps) - Add lib/admin-feedback (withFlash/readFlash) and components/admin/admin-flash, rendered centrally by AdminDashboardShell. - Emit success/error messages for media, site-settings, portfolio, smtp, marquee and maintenance actions; pages read them via searchParams. - Contact form shows validation/delivery errors inline; success still redirects to /success. Docs - Fix stale paths in frontend-system-* (components/root -> components/admin, lib/root-navigation -> lib/admin-navigation, drop phantom src/) and remove contact-protection references from docs and CLAUDE.md. - Add docs/PHASE0_DIAGNOSIS.md (diagnosis report). Note: proxy.ts self-fetch kept intentionally; it also drives maintenance mode.
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
export type FlashMessages = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a redirect target that carries an inline success/error message via
|
||||
* query params. Consumed by <AdminFlash /> on the destination page (the
|
||||
* Post/Redirect/Get pattern). Replaces the removed toast transport.
|
||||
*/
|
||||
export function withFlash(pathname: string, flash: FlashMessages): string {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (flash.success) {
|
||||
params.set("success", flash.success);
|
||||
}
|
||||
|
||||
if (flash.error) {
|
||||
params.set("error", flash.error);
|
||||
}
|
||||
|
||||
const query = params.toString();
|
||||
|
||||
return query ? `${pathname}?${query}` : pathname;
|
||||
}
|
||||
|
||||
/** Read the flash messages from resolved searchParams. */
|
||||
export function readFlash(
|
||||
searchParams?: { success?: string; error?: string } | null,
|
||||
): FlashMessages {
|
||||
return {
|
||||
success: searchParams?.success,
|
||||
error: searchParams?.error,
|
||||
};
|
||||
}
|
||||
+1
-18
@@ -26,7 +26,6 @@ type AdminNavigationCopy = {
|
||||
localizationSettings?: string;
|
||||
marquee?: string;
|
||||
smtp?: string;
|
||||
contactProtection?: string;
|
||||
};
|
||||
|
||||
export type AdminNavItem = {
|
||||
@@ -41,7 +40,6 @@ export type AdminNavItem = {
|
||||
export function getAdminNavigation(
|
||||
copy: AdminNavigationCopy,
|
||||
active: "overview" | "maintenance" | "ui-kit" | "portfolio" | "media" | "site-settings" | "smtp" | "marquee",
|
||||
smtpChild?: "settings" | "contact-protection",
|
||||
portfolioChild?: "overview" | "projects" | "new-project" | "categories",
|
||||
siteSettingsChild?: "brand" | "localization",
|
||||
): AdminNavItem[] {
|
||||
@@ -101,22 +99,7 @@ export function getAdminNavigation(
|
||||
label: copy.smtp ?? "SMTP",
|
||||
href: getAdminAppPath("/smtp"),
|
||||
icon: Mail,
|
||||
active: active === "smtp" && !smtpChild,
|
||||
expanded: active === "smtp",
|
||||
children: [
|
||||
{
|
||||
label: copy.smtp ?? "SMTP",
|
||||
href: getAdminAppPath("/smtp"),
|
||||
icon: Mail,
|
||||
active: smtpChild === "settings" || (!smtpChild && active === "smtp"),
|
||||
},
|
||||
{
|
||||
label: copy.contactProtection ?? "Contact Protection",
|
||||
href: getAdminAppPath("/smtp/contact-protection"),
|
||||
icon: ShieldAlert,
|
||||
active: smtpChild === "contact-protection",
|
||||
},
|
||||
],
|
||||
active: active === "smtp",
|
||||
},
|
||||
{
|
||||
label: copy.portfolio,
|
||||
|
||||
@@ -24,16 +24,6 @@ export {
|
||||
type MailSettings,
|
||||
type MailSettingsFormValues,
|
||||
} from "./mail-settings";
|
||||
export {
|
||||
CONTACT_PROTECTION_SETTINGS_KEY,
|
||||
buildDefaultContactProtectionSettings,
|
||||
parseContactProtectionValue,
|
||||
toContactProtectionFormValues,
|
||||
toPublicContactProtectionSettings,
|
||||
type ContactProtectionSettings,
|
||||
type ContactProtectionFormValues,
|
||||
type PublicContactProtectionSettings,
|
||||
} from "./contact-protection";
|
||||
export {
|
||||
MARQUEE_SETTINGS_KEY,
|
||||
buildDefaultMarqueeSettings,
|
||||
@@ -67,16 +57,6 @@ import {
|
||||
type MailSettings,
|
||||
type MailSettingsFormValues,
|
||||
} from "./mail-settings";
|
||||
import {
|
||||
CONTACT_PROTECTION_SETTINGS_KEY,
|
||||
buildDefaultContactProtectionSettings,
|
||||
parseContactProtectionValue,
|
||||
toContactProtectionFormValues,
|
||||
toPublicContactProtectionSettings,
|
||||
type ContactProtectionSettings,
|
||||
type ContactProtectionFormValues,
|
||||
type PublicContactProtectionSettings,
|
||||
} from "./contact-protection";
|
||||
import {
|
||||
MARQUEE_SETTINGS_KEY,
|
||||
buildDefaultMarqueeSettings,
|
||||
@@ -179,46 +159,6 @@ export async function updateMailSettings(settings: MailSettings): Promise<void>
|
||||
});
|
||||
}
|
||||
|
||||
export async function getContactProtectionSettings(): Promise<ContactProtectionSettings> {
|
||||
try {
|
||||
const config = await prisma.appConfig.findUnique({
|
||||
where: { key: CONTACT_PROTECTION_SETTINGS_KEY },
|
||||
select: { value: true },
|
||||
});
|
||||
|
||||
return parseContactProtectionValue(config?.value);
|
||||
} catch {
|
||||
return buildDefaultContactProtectionSettings();
|
||||
}
|
||||
}
|
||||
|
||||
export async function getContactProtectionFormValues(): Promise<ContactProtectionFormValues> {
|
||||
const settings = await getContactProtectionSettings();
|
||||
|
||||
return toContactProtectionFormValues(settings);
|
||||
}
|
||||
|
||||
export async function getPublicContactProtectionSettings(): Promise<PublicContactProtectionSettings> {
|
||||
const settings = await getContactProtectionSettings();
|
||||
|
||||
return toPublicContactProtectionSettings(settings);
|
||||
}
|
||||
|
||||
export async function updateContactProtectionSettings(
|
||||
settings: ContactProtectionSettings,
|
||||
): Promise<void> {
|
||||
await prisma.appConfig.upsert({
|
||||
where: { key: CONTACT_PROTECTION_SETTINGS_KEY },
|
||||
update: {
|
||||
value: JSON.stringify(settings),
|
||||
},
|
||||
create: {
|
||||
key: CONTACT_PROTECTION_SETTINGS_KEY,
|
||||
value: JSON.stringify(settings),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMarqueeSettings(): Promise<MarqueeSettings> {
|
||||
try {
|
||||
const config = await prisma.appConfig.findUnique({
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
import { createHash } from "crypto";
|
||||
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import {
|
||||
CONTACT_RATE_LIMIT_KEY_PREFIX,
|
||||
type ContactProtectionSettings,
|
||||
} from "@/lib/contact-protection";
|
||||
|
||||
async function getClientIpFromHeaders() {
|
||||
const requestHeaders = await headers();
|
||||
const forwardedFor = requestHeaders.get("x-forwarded-for");
|
||||
|
||||
if (forwardedFor) {
|
||||
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
||||
}
|
||||
|
||||
return requestHeaders.get("x-real-ip")?.trim() || "unknown";
|
||||
}
|
||||
|
||||
function getRateLimitKey(ip: string, windowMinutes: number) {
|
||||
const windowMs = windowMinutes * 60 * 1000;
|
||||
const windowStart = Math.floor(Date.now() / windowMs) * windowMs;
|
||||
const ipHash = createHash("sha256").update(ip).digest("hex");
|
||||
|
||||
return `${CONTACT_RATE_LIMIT_KEY_PREFIX}:${ipHash}:${windowStart}`;
|
||||
}
|
||||
|
||||
function parseCount(rawValue: string | null | undefined) {
|
||||
if (!rawValue) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const parsed = Number.parseInt(rawValue, 10);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : 0;
|
||||
}
|
||||
|
||||
export async function enforceContactRateLimit(settings: ContactProtectionSettings) {
|
||||
if (!settings.rateLimit.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ip = await getClientIpFromHeaders();
|
||||
const key = getRateLimitKey(ip, settings.rateLimit.windowMinutes);
|
||||
|
||||
// Clean up stale rate limit entries (older than 2x the window) to prevent table bloat.
|
||||
const cutoffDate = new Date(Date.now() - settings.rateLimit.windowMinutes * 2 * 60 * 1000);
|
||||
await prisma.$executeRaw`
|
||||
DELETE FROM "AppConfig"
|
||||
WHERE key LIKE ${`${CONTACT_RATE_LIMIT_KEY_PREFIX}:%`}
|
||||
AND "updatedAt" < ${cutoffDate}
|
||||
`;
|
||||
|
||||
// Atomically insert or increment the counter for this IP + window.
|
||||
const result = await prisma.$queryRaw<Array<{ count: number }>>`
|
||||
INSERT INTO "AppConfig" (id, key, value, "createdAt", "updatedAt")
|
||||
VALUES (gen_random_uuid()::text, ${key}, '1', NOW(), NOW())
|
||||
ON CONFLICT (key) DO UPDATE
|
||||
SET value = (CAST("AppConfig".value AS INTEGER) + 1)::text,
|
||||
"updatedAt" = NOW()
|
||||
RETURNING CAST(value AS INTEGER) AS count
|
||||
`;
|
||||
|
||||
const count = result[0]?.count ?? 0;
|
||||
|
||||
if (count > settings.rateLimit.maxRequests) {
|
||||
throw new Error("Too many contact requests. Please try again later.");
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyTurnstileToken(
|
||||
settings: ContactProtectionSettings,
|
||||
token: string,
|
||||
) {
|
||||
if (!settings.turnstile.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!settings.turnstile.siteKey || !settings.turnstile.secretKey) {
|
||||
throw new Error("Turnstile is enabled but not fully configured.");
|
||||
}
|
||||
|
||||
if (!token.trim()) {
|
||||
throw new Error("Turnstile verification is required.");
|
||||
}
|
||||
|
||||
const body = new URLSearchParams();
|
||||
body.set("secret", settings.turnstile.secretKey);
|
||||
body.set("response", token);
|
||||
body.set("remoteip", await getClientIpFromHeaders());
|
||||
|
||||
const response = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Turnstile verification request failed.");
|
||||
}
|
||||
|
||||
const result = await response.json() as {
|
||||
success?: boolean;
|
||||
};
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error("Turnstile verification failed.");
|
||||
}
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
export const CONTACT_PROTECTION_SETTINGS_KEY = "contact_protection_settings";
|
||||
export const CONTACT_RATE_LIMIT_KEY_PREFIX = "contact_rate_limit";
|
||||
|
||||
export type ContactProtectionSettings = {
|
||||
turnstile: {
|
||||
enabled: boolean;
|
||||
siteKey: string;
|
||||
secretKey: string;
|
||||
};
|
||||
rateLimit: {
|
||||
enabled: boolean;
|
||||
maxRequests: number;
|
||||
windowMinutes: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type ContactProtectionFormValues = {
|
||||
turnstile: {
|
||||
enabled: boolean;
|
||||
siteKey: string;
|
||||
secretKey: string;
|
||||
hasSecretKey: boolean;
|
||||
};
|
||||
rateLimit: {
|
||||
enabled: boolean;
|
||||
maxRequests: number;
|
||||
windowMinutes: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type PublicContactProtectionSettings = {
|
||||
turnstile: {
|
||||
enabled: boolean;
|
||||
siteKey: string;
|
||||
};
|
||||
rateLimit: {
|
||||
enabled: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export function buildDefaultContactProtectionSettings(): ContactProtectionSettings {
|
||||
return {
|
||||
turnstile: {
|
||||
enabled: false,
|
||||
siteKey: "",
|
||||
secretKey: "",
|
||||
},
|
||||
rateLimit: {
|
||||
enabled: true,
|
||||
maxRequests: 5,
|
||||
windowMinutes: 10,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parsePositiveInt(value: unknown, fallback: number) {
|
||||
const parsed =
|
||||
typeof value === "number"
|
||||
? value
|
||||
: typeof value === "string"
|
||||
? Number.parseInt(value, 10)
|
||||
: fallback;
|
||||
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
|
||||
}
|
||||
|
||||
export function parseContactProtectionValue(
|
||||
rawValue: string | null | undefined,
|
||||
): ContactProtectionSettings {
|
||||
const defaults = buildDefaultContactProtectionSettings();
|
||||
|
||||
if (!rawValue) {
|
||||
return defaults;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawValue) as Record<string, unknown>;
|
||||
const turnstile = parsed.turnstile && typeof parsed.turnstile === "object"
|
||||
? (parsed.turnstile as Record<string, unknown>)
|
||||
: {};
|
||||
const rateLimit = parsed.rateLimit && typeof parsed.rateLimit === "object"
|
||||
? (parsed.rateLimit as Record<string, unknown>)
|
||||
: {};
|
||||
|
||||
return {
|
||||
turnstile: {
|
||||
enabled: Boolean(turnstile.enabled),
|
||||
siteKey: typeof turnstile.siteKey === "string" ? turnstile.siteKey.trim() : "",
|
||||
secretKey: typeof turnstile.secretKey === "string" ? turnstile.secretKey : "",
|
||||
},
|
||||
rateLimit: {
|
||||
enabled: rateLimit.enabled === undefined ? defaults.rateLimit.enabled : Boolean(rateLimit.enabled),
|
||||
maxRequests: parsePositiveInt(rateLimit.maxRequests, defaults.rateLimit.maxRequests),
|
||||
windowMinutes: parsePositiveInt(rateLimit.windowMinutes, defaults.rateLimit.windowMinutes),
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return defaults;
|
||||
}
|
||||
}
|
||||
|
||||
export function toContactProtectionFormValues(
|
||||
settings: ContactProtectionSettings,
|
||||
): ContactProtectionFormValues {
|
||||
return {
|
||||
turnstile: {
|
||||
enabled: settings.turnstile.enabled,
|
||||
siteKey: settings.turnstile.siteKey,
|
||||
secretKey: "",
|
||||
hasSecretKey: Boolean(settings.turnstile.secretKey),
|
||||
},
|
||||
rateLimit: {
|
||||
enabled: settings.rateLimit.enabled,
|
||||
maxRequests: settings.rateLimit.maxRequests,
|
||||
windowMinutes: settings.rateLimit.windowMinutes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function toPublicContactProtectionSettings(
|
||||
settings: ContactProtectionSettings,
|
||||
): PublicContactProtectionSettings {
|
||||
return {
|
||||
turnstile: {
|
||||
enabled: settings.turnstile.enabled && Boolean(settings.turnstile.siteKey),
|
||||
siteKey: settings.turnstile.siteKey,
|
||||
},
|
||||
rateLimit: {
|
||||
enabled: settings.rateLimit.enabled,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
toast as hotToast,
|
||||
type ToastOptions,
|
||||
type ToastPosition,
|
||||
} from "react-hot-toast";
|
||||
|
||||
import { FALLBACK_LOCALE, resolveLocale } from "@/lib/locale";
|
||||
|
||||
type ToastVariant = "default" | "success" | "error" | "loading";
|
||||
|
||||
type ToastMessage = string;
|
||||
|
||||
function getCurrentLocale() {
|
||||
if (typeof window === "undefined") {
|
||||
return FALLBACK_LOCALE;
|
||||
}
|
||||
|
||||
const pathname = window.location.pathname;
|
||||
const maybeLocale = pathname.split("/")[1] || FALLBACK_LOCALE;
|
||||
|
||||
return resolveLocale(maybeLocale, FALLBACK_LOCALE);
|
||||
}
|
||||
|
||||
function getToastPosition(isArabic: boolean): ToastPosition {
|
||||
return isArabic ? "top-right" : "top-left";
|
||||
}
|
||||
|
||||
function getToastOptions(): ToastOptions {
|
||||
const locale = getCurrentLocale();
|
||||
const isArabic = locale === "ar";
|
||||
|
||||
return {
|
||||
duration: 1800,
|
||||
position: getToastPosition(isArabic),
|
||||
};
|
||||
}
|
||||
|
||||
function showToast(message: ToastMessage, variant: ToastVariant = "default") {
|
||||
const options = getToastOptions();
|
||||
|
||||
if (variant === "success") {
|
||||
return hotToast.success(message, options);
|
||||
}
|
||||
|
||||
if (variant === "error") {
|
||||
return hotToast.error(message, options);
|
||||
}
|
||||
|
||||
if (variant === "loading") {
|
||||
return hotToast.loading(message, options);
|
||||
}
|
||||
|
||||
return hotToast(message, options);
|
||||
}
|
||||
|
||||
export const toast = Object.assign(
|
||||
(message: ToastMessage) => showToast(message, "default"),
|
||||
{
|
||||
success: (message: ToastMessage) => showToast(message, "success"),
|
||||
error: (message: ToastMessage) => showToast(message, "error"),
|
||||
loading: (message: ToastMessage) => showToast(message, "loading"),
|
||||
dismiss: hotToast.dismiss,
|
||||
remove: hotToast.remove,
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user