Add security headers and make the contact form actually submit
The contact section collected input and discarded it on submit. There is no backend contact endpoint and no mail provider, so the form opens the visitor's mail client with a prefilled Persian subject and body. Validation is client-side with inline Persian errors, an accessible alert summary, and focus moved to the first invalid field; a persistent hint states up front that nothing is stored on the server and shows the address to copy if no mail client is registered. Also add the response headers the site was missing: HSTS, nosniff, frame denial, a strict referrer policy, a restrictive permissions policy, and a CSP. The CSP still needs 'unsafe-inline' for scripts because nonces are not implemented yet; that is the next hardening step. poweredByHeader is off so the framework is not advertised.
This commit is contained in:
1 parent
cc7a5f2b7c
commit
6a56b27b01
3 files changed
+350
-47
No files matched your search
@@ -5,6 +5,7 @@ import withBundleAnalyzer from '@next/bundle-analyzer';
|
||||
const nextConfig = {
|
||||
output: 'standalone',
|
||||
reactStrictMode: false,
|
||||
poweredByHeader: false,
|
||||
turbopack: {},
|
||||
images: {
|
||||
remotePatterns: [
|
||||
@@ -40,6 +41,57 @@ const nextConfig = {
|
||||
},
|
||||
];
|
||||
},
|
||||
async headers() {
|
||||
// `upgrade-insecure-requests` is a CSP directive, not a header, so it lives inside
|
||||
// the policy value below. `connect-src` allows the production backend only; the dev
|
||||
// API runs on plain http://localhost:8000 (see .env.development), so that origin is
|
||||
// appended outside of production to keep `next dev` working.
|
||||
const connectSrc = ["'self'", 'https://backend.parsaaghayi.ir'];
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
connectSrc.push('http://localhost:8000', 'http://127.0.0.1:8000');
|
||||
}
|
||||
|
||||
// TODO follow-up: ship a nonce-based policy (`script-src 'nonce-<random>'` plus
|
||||
// `'strict-dynamic'`). `'unsafe-inline'` is still required for scripts because
|
||||
// Next.js emits inline bootstrap scripts (hydration payload, next-themes script)
|
||||
// and framer-motion/next-themes are not wired up to receive a nonce yet. The nonce
|
||||
// can be threaded through the root layout + middleware, which is what lets us drop
|
||||
// `'unsafe-inline'` from script-src.
|
||||
const contentSecurityPolicy = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'unsafe-inline'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: blob: https:",
|
||||
"font-src 'self' data:",
|
||||
`connect-src ${connectSrc.join(' ')}`,
|
||||
"media-src 'self' blob:",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"form-action 'self'",
|
||||
'upgrade-insecure-requests',
|
||||
].join('; ');
|
||||
|
||||
return [
|
||||
{
|
||||
source: '/:path*',
|
||||
headers: [
|
||||
{
|
||||
key: 'Strict-Transport-Security',
|
||||
value: 'max-age=63072000; includeSubDomains; preload',
|
||||
},
|
||||
{ key: 'X-Content-Type-Options', value: 'nosniff' },
|
||||
{ key: 'X-Frame-Options', value: 'DENY' },
|
||||
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
|
||||
{
|
||||
key: 'Permissions-Policy',
|
||||
value: 'camera=(), microphone=(), geolocation=(), interest-cohort=()',
|
||||
},
|
||||
{ key: 'Content-Security-Policy', value: contentSecurityPolicy },
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
webpack(config, { isServer }) {
|
||||
if (!isServer) {
|
||||
config.optimization.splitChunks = {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { motion } from "framer-motion";
|
||||
import { Send } from "lucide-react";
|
||||
import ContactForm from "./contactForm";
|
||||
|
||||
interface ContactProps {
|
||||
dict: {
|
||||
@@ -20,19 +19,6 @@ interface ContactProps {
|
||||
}
|
||||
|
||||
export default function Contact({ dict }: ContactProps) {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
// Simulate API call
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
setIsSubmitting(false);
|
||||
setSubmitted(true);
|
||||
setTimeout(() => setSubmitted(false), 5000);
|
||||
};
|
||||
|
||||
return (
|
||||
<section
|
||||
className="relative flex w-full max-w-[1200px] flex-col items-center py-20"
|
||||
@@ -66,38 +52,10 @@ export default function Contact({ dict }: ContactProps) {
|
||||
viewport={{ once: true }}
|
||||
className="w-full max-w-3xl p-8 md:p-12 rounded-3xl glass-panel shadow-2xl"
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col md:flex-row gap-4 items-start md:items-center">
|
||||
<div className="relative flex-grow w-full">
|
||||
<input
|
||||
type="email"
|
||||
required
|
||||
name="email"
|
||||
id="email"
|
||||
placeholder={dict.website.homePage.contact.placeholder}
|
||||
className="w-full px-6 py-4 rounded-2xl bg-background border border-border text-foreground placeholder:text-muted-foreground outline-none focus:ring-2 focus:ring-primary/50 transition-all duration-300"
|
||||
/>
|
||||
</div>
|
||||
<motion.button
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
disabled={isSubmitting}
|
||||
type="submit"
|
||||
className="relative w-full md:w-auto flex items-center justify-center gap-2 px-8 py-4 rounded-2xl bg-primary text-primary-foreground font-bold whitespace-nowrap transition-all duration-300 disabled:opacity-70 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
||||
) : submitted ? (
|
||||
<span className="flex items-center gap-2">
|
||||
Sent!
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span>{dict.website.homePage.contact.button}</span>
|
||||
<Send className="w-4 h-4" />
|
||||
</>
|
||||
)}
|
||||
</motion.button>
|
||||
</form>
|
||||
<ContactForm
|
||||
buttonLabel={dict.website.homePage.contact.button}
|
||||
emailPlaceholder={dict.website.homePage.contact.placeholder}
|
||||
/>
|
||||
</motion.div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ChangeEvent,
|
||||
FormEvent,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { AlertCircle, CheckCircle2, Mail, Send } from "lucide-react";
|
||||
|
||||
/**
|
||||
* Inbox that receives every message submitted through this form. It matches the address
|
||||
* already published in the Person JSON-LD of the website layout (`ceo@parsaaghayi.ir`).
|
||||
* Change it here (and only here) to move the contact form to a different mailbox.
|
||||
*/
|
||||
const CONTACT_FORM_RECIPIENT_EMAIL = "ceo@parsaaghayi.ir";
|
||||
|
||||
const SUBJECT_PREFIX = "پیام جدید از فرم تماس سایت";
|
||||
|
||||
/** Deliberately simple shape check; the mail app does the real validation. */
|
||||
const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||||
|
||||
type FieldName = "name" | "email" | "message";
|
||||
|
||||
type FormValues = Record<FieldName, string>;
|
||||
type FieldErrors = Partial<Record<FieldName, string>>;
|
||||
|
||||
const EMPTY_VALUES: FormValues = { name: "", email: "", message: "" };
|
||||
|
||||
const ERROR_MESSAGES = {
|
||||
nameRequired: "لطفاً نام خود را وارد کنید.",
|
||||
emailRequired: "لطفاً ایمیل خود را وارد کنید.",
|
||||
emailInvalid: "لطفاً یک ایمیل معتبر وارد کنید. مثال: name@example.com",
|
||||
messageRequired: "لطفاً متن پیام خود را بنویسید.",
|
||||
} as const;
|
||||
|
||||
function validate(values: FormValues): FieldErrors {
|
||||
const errors: FieldErrors = {};
|
||||
const name = values.name.trim();
|
||||
const email = values.email.trim();
|
||||
const message = values.message.trim();
|
||||
|
||||
if (!name) errors.name = ERROR_MESSAGES.nameRequired;
|
||||
if (!email) {
|
||||
errors.email = ERROR_MESSAGES.emailRequired;
|
||||
} else if (!EMAIL_SHAPE.test(email)) {
|
||||
errors.email = ERROR_MESSAGES.emailInvalid;
|
||||
}
|
||||
if (!message) errors.message = ERROR_MESSAGES.messageRequired;
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
interface ContactFormProps {
|
||||
buttonLabel: string;
|
||||
emailPlaceholder: string;
|
||||
}
|
||||
|
||||
export default function ContactForm({
|
||||
buttonLabel,
|
||||
emailPlaceholder,
|
||||
}: ContactFormProps) {
|
||||
const [values, setValues] = useState<FormValues>(EMPTY_VALUES);
|
||||
const [errors, setErrors] = useState<FieldErrors>({});
|
||||
const [mailClientOpened, setMailClientOpened] = useState(false);
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const focusFirstInvalidField = useRef(false);
|
||||
const uid = useId();
|
||||
const nameId = `${uid}-name`;
|
||||
const emailId = `${uid}-email`;
|
||||
const messageId = `${uid}-message`;
|
||||
const errorSummaryId = `${uid}-error-summary`;
|
||||
|
||||
const errorEntries = Object.entries(errors) as [FieldName, string][];
|
||||
|
||||
// Runs after a failed submit only, so typing in a field is never interrupted by a
|
||||
// focus jump while another field is still invalid.
|
||||
useEffect(() => {
|
||||
if (!focusFirstInvalidField.current) return;
|
||||
focusFirstInvalidField.current = false;
|
||||
formRef.current
|
||||
?.querySelector<HTMLElement>('[aria-invalid="true"]')
|
||||
?.focus();
|
||||
}, [errors]);
|
||||
|
||||
const handleChange =
|
||||
(field: FieldName) =>
|
||||
(event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
const { value } = event.target;
|
||||
setValues((previous) => ({ ...previous, [field]: value }));
|
||||
// Clear the message as soon as the visitor starts fixing the field.
|
||||
setErrors((previous) =>
|
||||
previous[field] ? { ...previous, [field]: undefined } : previous,
|
||||
);
|
||||
};
|
||||
|
||||
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
const trimmed: FormValues = {
|
||||
name: values.name.trim(),
|
||||
email: values.email.trim(),
|
||||
message: values.message.trim(),
|
||||
};
|
||||
|
||||
const nextErrors = validate(trimmed);
|
||||
|
||||
if (Object.keys(nextErrors).length > 0) {
|
||||
setMailClientOpened(false);
|
||||
// Ask for focus to move to the first field that needs fixing, so the announced
|
||||
// errors are actionable. Done in an effect because the `aria-invalid` flags are
|
||||
// only in the DOM after this state update is rendered.
|
||||
focusFirstInvalidField.current = true;
|
||||
setErrors(nextErrors);
|
||||
return;
|
||||
}
|
||||
|
||||
const subject = `${SUBJECT_PREFIX} — ${trimmed.name}`;
|
||||
const body = [
|
||||
`نام فرستنده: ${trimmed.name}`,
|
||||
`ایمیل فرستنده: ${trimmed.email}`,
|
||||
"",
|
||||
"متن پیام:",
|
||||
trimmed.message,
|
||||
].join("\n");
|
||||
|
||||
// There is no backend endpoint for contact submissions, so the form hands the draft
|
||||
// to the visitor's own mail client. Nothing is sent or stored by this site.
|
||||
window.location.href = `mailto:${CONTACT_FORM_RECIPIENT_EMAIL}?subject=${encodeURIComponent(
|
||||
subject,
|
||||
)}&body=${encodeURIComponent(body)}`;
|
||||
|
||||
setMailClientOpened(true);
|
||||
};
|
||||
|
||||
const inputClassName =
|
||||
"w-full px-5 py-3 rounded-2xl border bg-background text-foreground placeholder:text-muted-foreground outline-none transition-all duration-300 focus:ring-2 focus:ring-primary/50";
|
||||
const invalidInputClassName = "border-destructive focus:ring-destructive/50";
|
||||
|
||||
return (
|
||||
<form
|
||||
ref={formRef}
|
||||
dir="rtl"
|
||||
noValidate
|
||||
onSubmit={handleSubmit}
|
||||
className="flex flex-col gap-5"
|
||||
aria-describedby={errorEntries.length > 0 ? errorSummaryId : undefined}
|
||||
>
|
||||
<p className="flex items-start gap-2 text-sm text-muted-foreground">
|
||||
<Mail className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
|
||||
<span>
|
||||
سایتی برای ثبت پیام وجود ندارد؛ با زدن دکمه ارسال، برنامه ایمیل شما
|
||||
باز میشود و متن پیام در آن آماده میشود تا خودتان ارسالش کنید.
|
||||
</span>
|
||||
</p>
|
||||
|
||||
{errorEntries.length > 0 && (
|
||||
<div
|
||||
id={errorSummaryId}
|
||||
role="alert"
|
||||
className="flex flex-col gap-2 rounded-2xl border border-destructive bg-destructive/10 p-4 text-destructive"
|
||||
>
|
||||
<p className="flex items-center gap-2 font-bold">
|
||||
<AlertCircle className="h-5 w-5 shrink-0" aria-hidden="true" />
|
||||
لطفاً خطاهای فرم را برطرف کنید.
|
||||
</p>
|
||||
<ul className="list-disc space-y-1 pr-5 text-sm">
|
||||
{errorEntries.map(([field, message]) => (
|
||||
<li key={field}>{message}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-5 md:grid-cols-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
<label htmlFor={nameId} className="font-medium text-foreground">
|
||||
نام و نام خانوادگی <span aria-hidden="true">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id={nameId}
|
||||
name="name"
|
||||
value={values.name}
|
||||
onChange={handleChange("name")}
|
||||
autoComplete="name"
|
||||
placeholder="مثلاً: پارسا آقایی"
|
||||
aria-invalid={Boolean(errors.name)}
|
||||
aria-describedby={errors.name ? `${nameId}-error` : undefined}
|
||||
className={`${inputClassName} ${errors.name ? invalidInputClassName : "border-border"}`}
|
||||
/>
|
||||
{errors.name && (
|
||||
<p id={`${nameId}-error`} className="text-sm text-destructive">
|
||||
{errors.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<label htmlFor={emailId} className="font-medium text-foreground">
|
||||
ایمیل <span aria-hidden="true">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
id={emailId}
|
||||
name="email"
|
||||
value={values.email}
|
||||
onChange={handleChange("email")}
|
||||
autoComplete="email"
|
||||
placeholder={emailPlaceholder}
|
||||
aria-invalid={Boolean(errors.email)}
|
||||
aria-describedby={errors.email ? `${emailId}-error` : undefined}
|
||||
className={`${inputClassName} ${errors.email ? invalidInputClassName : "border-border"}`}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p id={`${emailId}-error`} className="text-sm text-destructive">
|
||||
{errors.email}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<label htmlFor={messageId} className="font-medium text-foreground">
|
||||
پیام <span aria-hidden="true">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
id={messageId}
|
||||
name="message"
|
||||
value={values.message}
|
||||
onChange={handleChange("message")}
|
||||
rows={5}
|
||||
placeholder="درخواست، پیشنهاد همکاری یا هر سؤالی دارید بنویسید..."
|
||||
aria-invalid={Boolean(errors.message)}
|
||||
aria-describedby={errors.message ? `${messageId}-error` : undefined}
|
||||
className={`${inputClassName} resize-y ${
|
||||
errors.message ? invalidInputClassName : "border-border"
|
||||
}`}
|
||||
/>
|
||||
{errors.message && (
|
||||
<p id={`${messageId}-error`} className="text-sm text-destructive">
|
||||
{errors.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
|
||||
<button
|
||||
type="submit"
|
||||
className="relative flex w-full items-center justify-center gap-2 whitespace-nowrap rounded-2xl bg-primary px-8 py-4 font-bold text-primary-foreground transition-all duration-300 hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background md:w-auto"
|
||||
>
|
||||
<span>{buttonLabel}</span>
|
||||
<Send className="h-4 w-4" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
<a
|
||||
href={`mailto:${CONTACT_FORM_RECIPIENT_EMAIL}`}
|
||||
dir="ltr"
|
||||
className="text-sm text-muted-foreground underline underline-offset-4 transition-colors hover:text-foreground"
|
||||
>
|
||||
{CONTACT_FORM_RECIPIENT_EMAIL}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={mailClientOpened ? undefined : "hidden"}
|
||||
>
|
||||
{mailClientOpened && (
|
||||
<p className="flex items-start gap-2 rounded-2xl border border-primary bg-primary/10 p-4 text-foreground">
|
||||
<CheckCircle2
|
||||
className="mt-0.5 h-5 w-5 shrink-0 text-primary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>
|
||||
پیام شما آماده شد. اگر برنامه ایمیل شما باز نشد، میتوانید آدرس
|
||||
<a
|
||||
href={`mailto:${CONTACT_FORM_RECIPIENT_EMAIL}`}
|
||||
className="mx-1 font-bold underline underline-offset-4"
|
||||
>
|
||||
{CONTACT_FORM_RECIPIENT_EMAIL}
|
||||
</a>
|
||||
را کپی کرده و پیام را دستی ارسال کنید.
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user