Compare commits

...

12 Commits

Author SHA1 Message Date
mazyar bc21c711ee Update .drone.yml
continuous-integration/drone/push Build is passing
2026-06-20 09:14:55 +00:00
mazyar ca85d3142d Update .drone.yml
continuous-integration/drone/push Build is failing
2026-06-20 09:12:57 +00:00
AmirReza Jamali 85d1fbb20d Fix Lighthouse SEO metadata issues 2026-06-17 13:51:49 +03:30
AmirReza Jamali 635ca32b3a feat(metadata): Update page metadata and enhance video presentation
- Set metadataBase for consistent URL structure across pages
- Add Open Graph and Twitter metadata for improved social sharing
- Implement canonical links and robots directives for SEO optimization
- Replace static image with video previews for a more dynamic user experience
2026-04-16 11:01:38 +03:30
AmirReza Jamali 1bf3b91c12 feat(inquiries): Improve form submission validation and data sanitization
- Sanitize form data by trimming whitespace from string inputs
- Implement validation for required fields with user feedback for empty inputs
- Enhance error handling by displaying messages for invalid form fields
- Update API submission to use sanitized data while maintaining hcaptcha token integration
2026-04-15 18:34:27 +03:30
AmirReza Jamali 04545fc50e chore: Remove favicon and enhance global styles
- Delete unused favicon.ico file to clean up project assets
- Add smooth scrolling behavior to html element for improved user experience
- Refactor box-shadow property in Toastify styles for better readability
- Update button states in Contact Us and Inquiries forms to include hcaptchaToken validation
2026-04-13 14:25:25 +03:30
AmirReza Jamali e63d2d3156 feat(forms): Enhance form validation and submission handling
- Implement real-time validation with `isValid` state in Contact Us and Inquiries forms
- Add `trigger` function to validate forms before submission
- Disable submit button based on form validity and loading state
- Improve user experience by preventing submission of invalid forms
2026-04-13 13:02:49 +03:30
AmirReza Jamali 2229ffcd7a feat(input): Add autoComplete="off" to InputGroup and Textarea components for improved form security 2026-04-13 09:16:14 +03:30
AmirReza Jamali 8518c2c140 refactor(inquiries): Update form validation and error handling
- Change required fields in inquiries form to enforce mandatory input
- Enhance API error handler to provide user-friendly messages without exposing raw server text
- Improve test cases for API error handling to ensure accurate message mapping and validation
- Refactor error messages for clarity and consistency across the application
2026-04-13 08:37:22 +03:30
AmirReza Jamali 1ee57a4ec1 Add captcha in inquiries form 2026-04-12 11:12:44 +03:30
AmirReza Jamali 7b6cd4d965 feat(validation): Implement form validation and error handling utilities
- Add validation rules for form fields with XSS protection
- Create API error handler to parse and manage server validation errors
- Integrate validation rules into contact and inquiries forms
- Enhance error handling with user feedback for form submissions
- Introduce unit tests for validation and error handling functionalities
2026-02-08 13:35:07 +03:30
AmirReza Jamali 5fc6469752 chore(vscode): Remove empty VS Code settings file
- Delete empty .vscode/settings.json configuration file
- Reduce unnecessary project configuration clutter
- Allow team members to use their own VS Code preferences
2025-12-14 18:23:52 +03:30
31 changed files with 5430 additions and 172 deletions
+39 -24
View File
@@ -1,41 +1,56 @@
################################################################################
# web
################################################################################
kind: pipeline
type: docker
name: (landing) build form and push to artifactory
name: build-and-push-landing
steps:
- name: tag
image: alpine/git:2.40.1
environment:
GOOS: linux
GOARCH: amd64
CGO_ENABLED: 0
settings:
debug: true
commands:
- APP_VERSION=$(git rev-list HEAD --count --no-merges)-$DRONE_BRANCH
- echo "APP Version tags $APP_VERSION"
- echo -n "$APP_VERSION" >> .tags
- |
set -e
SHORT_SHA=$(echo "$DRONE_COMMIT_SHA" | cut -c1-8)
IMG_TAG="${DRONE_BUILD_NUMBER}-${DRONE_BRANCH}"
echo -n "$IMG_TAG,$SHORT_SHA" > .tags
echo "Image tags -> $IMG_TAG , $SHORT_SHA"
- name: build landing
image: plugins/docker
settings:
# build_args:
# - BUILD_APP=scraper
username: cicd
registry: git.opplens.se
repo: git.opplens.se/mazyar/landing
username:
from_secret: registry_username
password:
from_secret: REGISTRY_PASSWORD
# dockerfile: Dockerfile-drone
repo: artifactory.ravanertebat.ir/tm/landing
registry: artifactory.ravanertebat.ir
from_secret: registry_password
- name: deploy-uat
image: appleboy/drone-ssh
settings:
host: 10.0.0.3
username: mazyar
port: 22
key:
from_secret: ssh_deploy_key
envs:
- DRONE_BUILD_NUMBER
- DRONE_BRANCH
script:
- set -e
- cd /data/tm-uat
- NEW_TAG="${DRONE_BUILD_NUMBER}-${DRONE_BRANCH}"
- echo "Deploying landing tag $NEW_TAG"
- sed -i "s/^LANDING_IMG_TAG=.*/LANDING_IMG_TAG=$NEW_TAG/" .env
- docker compose pull landing
- docker compose up -d landing
- docker image prune -f
when:
branch:
- dev
node:
tag: aecde-docker-runner
trigger:
branch:
- main
- develop
- uat
- dev
event:
- custom
- push
-1
View File
@@ -1 +0,0 @@
{}
+10 -6
View File
@@ -1,6 +1,5 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { headers } from "next/headers";
import Image from "next/image";
import Link from "next/link";
import { Suspense } from "react";
@@ -19,9 +18,17 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
metadataBase: new URL("https://opplenz.com"),
title: "Opp lens - AI-Powered Tender Management",
description:
"Democratizing Tender Access for SMEs with AI-Powered Tender Management.",
alternates: {
canonical: "/",
},
robots: {
index: true,
follow: true,
},
icons: {
icon: "/fav-icon.svg",
},
@@ -73,13 +80,11 @@ function ContactInfo({
);
}
export default async function RootLayout({
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const domain = (await headers()).get("host")?.replace("www.", "");
const contactInfo = [
{
icon: "/Message.svg",
@@ -120,7 +125,7 @@ export default async function RootLayout({
</Link>
</section>
<Suspense>
<NavigationBar host={domain ?? "opplens.com"} />
<NavigationBar />
</Suspense>
</header>
@@ -151,7 +156,6 @@ export default async function RootLayout({
alt="Opp lens logo"
width={180}
height={30}
priority
/>
<div>
<p className="text-black my-2">
+39 -5
View File
@@ -11,10 +11,24 @@ export const metadata: Metadata = {
openGraph: {
title: "Opp lens - AI-Powered Tender Management",
description: "Win more tenders automatically with our AI-powered platform",
url: "https://opplenz.com/",
type: "website",
locale: "en_US",
siteName: "Opp lens",
},
twitter: {
card: "summary_large_image",
title: "Opp lens - AI-Powered Tender Management",
description: "Win more tenders automatically with our AI-powered platform",
images: ["/images/opp-lens-mobile.jpg"],
},
alternates: {
canonical: "https://opplenz.com/",
},
robots: {
index: true,
follow: true,
},
icons: {
icon: "/fav-icon.svg",
},
@@ -60,7 +74,7 @@ export default function Home() {
</p>
</div>
</div>
<div className="mx-12 md:mx-52 lg:mx-28 -z-20 relative flex justify-center h-[650px] lg:h-[505px]">
<div className="mx-12 md:mx-52 lg:mx-28 -z-20 relative flex justify-center h-[650px] lg:h-[510px]">
<span className="opacity-0 lg:opacity-100">
<Image
src={"/dynamic-island.svg"}
@@ -79,14 +93,34 @@ export default function Home() {
className="absolute top-4 left-1/2 -translate-x-1/2"
/>
</span>
<Image
{/* <Image
className="-z-10 border-8 border-black rounded-4xl overflow-hidden h-full w-full"
src="/mobile.gif"
width={300}
height={920}
loading="lazy"
alt="phone"
/>
sizes="(max-width: 1024px) 60vw, 300px"
priority
alt="Opp lens application preview on a mobile phone"
/> */}
<div className="-z-10 border-8 border-black rounded-4xl overflow-hidden h-full w-full">
<video
className="max-h-full w-full object-cover"
autoPlay
loop
muted
playsInline
preload="auto"
aria-label="Opp lens application preview on a mobile phone">
<source
src="/mobile.webm"
type="video/webm"
/>
<source
src="/mobile.mp4"
type="video/mp4"
/>
</video>
</div>
</div>
</section>
<section className="flex flex-col gap-6 bg-gradient-to-b from-[#011132] to-[#012B80] text-white rounded-[56px] relative py-13 px-14 -mt-36 z-20 md:grid lg:grid-cols-3 lg:flex-row">
+10 -4
View File
@@ -4,9 +4,9 @@ import Image from "next/image";
import Link from "next/link";
import { ToastContainer, Zoom } from "react-toastify";
import "../../globals.css";
import { Suspense } from "react";
import GoogleAnalytics from "@/app/_components/GoogleAnalytics";
import "@/app/globals.css";
import { Suspense } from "react";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
@@ -18,8 +18,14 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
metadataBase: new URL("https://opplenz.com"),
title: "Page Not Found | Opp lens",
description:
"Opp lens helps SMEs find relevant tenders, automate document handling, and get real-time alerts for new opportunities.",
robots: {
index: false,
follow: true,
},
icons: {
icon: "/fav-icon.svg",
},
+1
View File
@@ -33,6 +33,7 @@ function InputGroup({
<div>
<div className="relative w-full my-3">
<input
autoComplete="off"
type={type}
className={`border ${
error
+1 -1
View File
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
const NavigationBar = ({ host }: { host: string }) => {
const NavigationBar = ({ host = "opplenz.com" }: { host?: string }) => {
const pathname = usePathname();
return (
+1
View File
@@ -29,6 +29,7 @@ function TextareaGroup({
<div>
<div className="relative w-full my-3">
<textarea
autoComplete="off"
className={`border ${
error
? "border-red-500"
+23 -62
View File
@@ -1,4 +1,6 @@
"use client";
import { handleApiError } from "@/lib/apiErrorHandler";
import { validationRules } from "@/lib/validation";
import api from "@/service/api";
import HCaptcha from "@hcaptcha/react-hcaptcha";
import { useRef, useState } from "react";
@@ -14,6 +16,9 @@ type TContactUsForm = {
phone: string;
message: string;
};
const FORM_FIELDS = ["full_name", "email", "phone", "message"];
interface IProps {
columnsPerRow?: 1 | 2 | 3 | 4;
buttonText?: string;
@@ -28,9 +33,11 @@ const ContactUsForm = ({
const {
register,
handleSubmit,
formState: { errors },
formState: { errors, isValid },
reset,
} = useForm<TContactUsForm>();
setError,
trigger,
} = useForm<TContactUsForm>({ mode: "onChange" });
const onCaptchaVerify = (token: string) => {
setHcaptchaToken(token);
@@ -41,6 +48,11 @@ const ContactUsForm = ({
};
const onSubmit = async (data: TContactUsForm) => {
const isFormValid = await trigger();
if (!isFormValid) {
return;
}
if (!hcaptchaToken) {
toast.error("Please complete the captcha verification");
return;
@@ -55,9 +67,7 @@ const ContactUsForm = ({
setHcaptchaToken(null);
captchaRef.current?.resetCaptcha();
} catch (error) {
console.log(error);
toast.error("Something went wrong");
throw error;
handleApiError(error, setError, toast.error, FORM_FIELDS);
} finally {
setIsLoading(() => false);
}
@@ -84,20 +94,7 @@ const ContactUsForm = ({
id="full_name"
label="Full Name"
register={register}
validation={{
required: {
message: "This field is required",
value: true,
},
minLength: {
value: 2,
message: "Please enter at least 2 characters",
},
maxLength: {
value: 100,
message: "Please enter at most 100 characters",
},
}}
validation={validationRules.fullName}
type="text"
error={errors.full_name?.message}
/>
@@ -105,16 +102,7 @@ const ContactUsForm = ({
id="email"
label="Email"
register={register}
validation={{
required: {
message: "This field is required",
value: true,
},
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: "Please enter a valid email address",
},
}}
validation={validationRules.email}
type="email"
error={errors.email?.message}
/>
@@ -122,24 +110,7 @@ const ContactUsForm = ({
id="phone"
label="Phone"
register={register}
validation={{
required: {
message: "This field is required",
value: true,
},
minLength: {
value: 10,
message: "Please enter at least 10 characters",
},
maxLength: {
value: 20,
message: "Please enter at most 20 characters",
},
pattern: {
value: /^[+\d]+$/,
message: "Please enter a valid phone number",
},
}}
validation={validationRules.phone}
type="text"
error={errors.phone?.message}
/>
@@ -148,20 +119,7 @@ const ContactUsForm = ({
label="Message"
register={register}
error={errors.message?.message}
validation={{
required: {
value: true,
message: "This field is required",
},
maxLength: {
value: 1000,
message: "Please enter at most 1000 characters",
},
minLength: {
value: 10,
message: "Please enter at least 10 characters",
},
}}
validation={validationRules.message}
/>
<div className={`${colSpanClass}`}>
<HCaptcha
@@ -172,7 +130,10 @@ const ContactUsForm = ({
/>
</div>
<div className={`${colSpanClass} flex justify-end`}>
<button className="bg-(--primary) cursor-pointer w-fit text-white rounded-full py-4 px-6 flex justify-center items-center text-center">
<button
type="submit"
disabled={!isValid || isLoading || !hcaptchaToken}
className="bg-(--primary) cursor-pointer w-fit text-white rounded-full py-4 px-6 flex justify-center items-center text-center disabled:opacity-60 disabled:cursor-not-allowed">
{isLoading ? <Loading /> : buttonText}
</button>
</div>
+176 -48
View File
@@ -1,8 +1,11 @@
"use client";
import { handleApiError } from "@/lib/apiErrorHandler";
import { sanitizeText } from "@/lib/sanitize";
import { createFieldValidation } from "@/lib/validation";
import api from "@/service/api";
import { CmsContact } from "@/types/TCms";
import { useState } from "react";
import HCaptcha from "@hcaptcha/react-hcaptcha";
import { useMemo, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";
import InputGroup from "../_components/InputGroup";
@@ -24,23 +27,108 @@ const InquiresForm = ({
contactData,
}: InquiresFormProps) => {
const [isLoading, setIsLoading] = useState(false);
const [hcaptchaToken, setHcaptchaToken] = useState<string | null>(null);
const captchaRef = useRef<HCaptcha>(null);
const {
register,
handleSubmit,
formState: { errors },
formState: { errors, isValid },
reset,
} = useForm<TInquiresForm>();
setError,
trigger,
} = useForm<TInquiresForm>({ mode: "onChange" });
const defaultFields = useMemo(
() => [
{
name: "full_name",
label: "Full Name",
placeholder: "",
required: true,
},
{
name: "company_name",
label: "Company Name",
placeholder: "",
required: true,
},
{
name: "work_email",
label: "Work Email",
placeholder: "",
required: true,
},
{
name: "phone_number",
label: "Phone Number",
placeholder: "",
required: true,
},
],
[],
);
const fields = contactData?.fields || defaultFields;
const formFieldNames = useMemo(() => fields.map((f) => f.name), [fields]);
const onCaptchaVerify = (token: string) => {
setHcaptchaToken(token);
};
const onCaptchaExpire = () => {
setHcaptchaToken(null);
};
const onSubmit = async (data: TInquiresForm) => {
const sanitizedData = Object.fromEntries(
Object.entries(data).map(([key, value]) => [
key,
typeof value === "string" ? value.trim() : value,
]),
) as TInquiresForm;
const requiredFields = fields.filter((field) => field.required);
let hasEmptyRequiredField = false;
requiredFields.forEach((field) => {
const value = sanitizedData[field.name];
if (!value) {
setError(field.name, {
type: "required",
message: `${field.label} is required`,
});
hasEmptyRequiredField = true;
}
});
if (hasEmptyRequiredField) {
toast.error("Please complete all required fields");
return;
}
const isFormValid = await trigger(formFieldNames);
if (!isFormValid) {
toast.error("Please correct invalid form fields");
return;
}
if (!hcaptchaToken) {
toast.error("Please complete the captcha verification");
return;
}
setIsLoading(true);
try {
const response = (await api.post("inquiries", { ...data })).data;
const response = (
await api.post("inquiries", {
...sanitizedData,
hcaptcha_token: hcaptchaToken,
})
).data;
toast.success(response.message);
reset();
setHcaptchaToken(null);
captchaRef.current?.resetCaptcha();
} catch (error) {
console.log(error);
toast.error("Something went wrong");
throw error;
handleApiError(error, setError, toast.error, formFieldNames);
} finally {
setIsLoading(false);
}
@@ -60,32 +148,77 @@ const InquiresForm = ({
4: "lg:col-span-4",
}[columnsPerRow];
const defaultFields = [
{ name: "full_name", label: "Full Name", placeholder: "", required: false },
{
name: "company_name",
label: "Company Name",
placeholder: "",
required: false,
},
{
name: "work_email",
label: "Work Email",
placeholder: "",
required: false,
},
{
name: "phone_number",
label: "Phone Number",
placeholder: "",
required: false,
},
];
const fields = contactData?.fields || defaultFields;
const submitText =
sanitizeText(contactData?.submit_button_text) || buttonText || "Submit";
/**
* Creates validation rules based on field type with XSS protection
*/
const getFieldValidation = (field: {
name: string;
label: string;
required?: boolean;
}) => {
const isEmailField =
field.name.includes("email") || field.name === "work_email";
const isPhoneField =
field.name.includes("phone") || field.name === "phone_number";
const isStrictTextField =
field.name === "full_name" || field.name === "company_name";
if (isPhoneField) {
return createFieldValidation(field.label, field.required, {
pattern: {
value: /^[+\d\s()-]+$/,
message:
"Please enter a valid phone number (digits, +, spaces, parentheses, and dashes only)",
},
minLength: field.required
? { value: 10, message: "Phone number must be at least 10 digits" }
: undefined,
maxLength: {
value: 20,
message: "Phone number must not exceed 20 characters",
},
});
}
if (isEmailField) {
return createFieldValidation(field.label, field.required, {
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: "Please enter a valid email address",
},
});
}
if (isStrictTextField) {
return createFieldValidation(field.label, field.required, {
minLength: field.required
? {
value: 2,
message: `${field.label} must be at least 2 characters`,
}
: undefined,
maxLength: {
value: 200,
message: `${field.label} must not exceed 200 characters`,
},
pattern: {
value: /^[\p{L}\p{M}\p{N}\s'.,()&/_-]+$/u,
message: `${field.label} may only include letters, numbers, spaces, and common punctuation (no HTML or code)`,
},
});
}
return createFieldValidation(field.label, field.required, {
maxLength: {
value: 200,
message: `${field.label} must not exceed 200 characters`,
},
});
};
return (
<form
className={`w-full px-4 lg:px-16 py-10 grid ${gridColsClass} gap-4`}
@@ -95,8 +228,6 @@ const InquiresForm = ({
field.name.includes("email") || field.name === "work_email"
? "email"
: "text";
const isPhoneField =
field.name.includes("phone") || field.name === "phone_number";
return (
<InputGroup
@@ -107,26 +238,23 @@ const InquiresForm = ({
register={register}
type={inputType}
error={errors[field.name]?.message}
validation={
isPhoneField
? {
pattern: {
value: /^[+\d]+$/,
message: "Please enter a valid phone number",
},
required: field.required
? "This field is required"
: undefined,
}
: field.required
? { required: "This field is required" }
: undefined
}
validation={getFieldValidation(field)}
/>
);
})}
<div className={`${colSpanClass}`}>
<HCaptcha
sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY || ""}
onVerify={onCaptchaVerify}
onExpire={onCaptchaExpire}
ref={captchaRef}
/>
</div>
<div className={`${colSpanClass} flex justify-end`}>
<button className="bg-(--primary) cursor-pointer w-fit text-white rounded-full py-4 px-6">
<button
type="submit"
disabled={!isValid || isLoading || !hcaptchaToken}
className="bg-(--primary) cursor-pointer inline-flex items-center justify-center min-h-14 w-fit text-white rounded-full py-4 px-6 disabled:opacity-60 disabled:cursor-not-allowed">
{isLoading ? <Loading /> : submitText}
</button>
</div>
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

+40
View File
@@ -0,0 +1,40 @@
import "./globals.css";
const description =
"Opp lens helps SMEs find relevant tenders, automate document handling, and get real-time alerts for new opportunities.";
export default function GlobalNotFound() {
return (
<html lang="en">
<head>
<title>Page Not Found | Opp lens</title>
<meta
name="description"
content={description}
/>
<meta
name="robots"
content="noindex, follow"
/>
<link
rel="icon"
href="/fav-icon.svg"
/>
</head>
<body>
<main className="min-h-screen px-6 py-16 flex flex-col items-center justify-center text-center">
<h1 className="text-3xl font-bold text-[#013280]">Page not found</h1>
<p className="mt-4 max-w-xl text-[#777]">
Sorry, the page you are looking for does not exist or has been
removed.
</p>
<a
href="/"
className="mt-8 rounded-full bg-(--primary) px-8 py-4 text-white">
Home
</a>
</main>
</body>
</html>
);
}
+6 -1
View File
@@ -9,6 +9,10 @@
body {
font-family: "Inter", sans-serif;
}
html {
scroll-behavior: smooth;
}
@theme {
--background: #171717;
--foreground: #ffffff;
@@ -31,7 +35,8 @@ body {
}
.dark .Toastify__toast {
box-shadow: 0 20px 25px -5px rgb(255 255 255 / 0.07),
box-shadow:
0 20px 25px -5px rgb(255 255 255 / 0.07),
0 8px 10px -6px rgb(255 255 255 / 0.05) !important;
}
+21 -2
View File
@@ -81,14 +81,33 @@ export default async function Home({ params }: IProps) {
height={22}
className="absolute top-4 left-1/2 -translate-x-1/2"
/>
<Image
<div className="-z-10 border-8 border-black rounded-4xl overflow-hidden h-full w-full">
<video
className="max-h-full w-full object-cover"
autoPlay
loop
muted
playsInline
preload="auto"
aria-label="Opp lens application preview on a mobile phone">
<source
src="/mobile.webm"
type="video/webm"
/>
<source
src="/mobile.mp4"
type="video/mp4"
/>
</video>
</div>
{/* <Image
className="-z-10 border-8 border-black rounded-4xl overflow-hidden h-full w-full"
src="/mobile.gif"
width={300}
height={920}
loading="lazy"
alt="phone"
/>
/> */}
</div>
</section>
<section className="text-left flex flex-col gap-6 bg-gradient-to-b from-[#011132] to-[#012B80] text-white rounded-[56px] relative p-6 lg:p-14 -mt-16 z-20 lg:ml-28 ">
+2 -2
View File
@@ -1,9 +1,9 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { ToastContainer, Zoom } from "react-toastify";
import "../globals.css";
import { Suspense } from "react";
import { ToastContainer, Zoom } from "react-toastify";
import GoogleAnalytics from "../_components/GoogleAnalytics";
import "../globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
+28 -7
View File
@@ -142,11 +142,11 @@ export default function Home() {
</p>
</hgroup>
<div className="flex justify-start text-white">
<button
type="button"
className="w-2/3 lg:w-fit capitalize bg-(--primary) rounded-4xl py-4 px-6">
<Link
href={"#footer"}
className="w-2/3 lg:w-fit capitalize bg-(--primary) rounded-4xl py-4 px-6 cursor-pointer">
Get early access
</button>
</Link>
</div>
</section>
<div className="m-auto w-xs lg:m-0 lg:w-auto -z-20 relative flex justify-center h-[650px] lg:h-[750px] lg:mr-28">
@@ -157,14 +157,33 @@ export default function Home() {
height={22}
className="absolute top-4 left-1/2 -translate-x-1/2"
/>
<Image
<div className="-z-10 border-8 border-black rounded-4xl overflow-hidden h-full w-full">
<video
className="max-h-full w-full object-cover"
autoPlay
loop
muted
playsInline
preload="auto"
aria-label="Opp lens application preview on a mobile phone">
<source
src="/mobile.webm"
type="video/webm"
/>
<source
src="/mobile.mp4"
type="video/mp4"
/>
</video>
</div>
{/* <Image
className="-z-10 border-8 border-black rounded-4xl overflow-hidden h-full w-full"
src="/mobile.gif"
width={300}
height={920}
loading="lazy"
alt="phone"
/>
/> */}
</div>
</section>
@@ -295,7 +314,9 @@ export default function Home() {
</div>
</section>
</main>
<footer className="relative h-full bg-[url('/footer-bg.svg')] bg-cover bg-no-repeat mt-96">
<footer
className="relative h-full bg-[url('/footer-bg.svg')] bg-cover bg-no-repeat mt-96"
id="footer">
<div
className="absolute w-full -top-[355px] lg:-top-72 h-[600px] z-[-10] bg-[url('/bottom-bg.svg')] bg-contain bg-no-repeat bg-right"
aria-hidden="true"
+13
View File
@@ -0,0 +1,13 @@
import type { MetadataRoute } from "next";
const siteUrl = "https://opplenz.com";
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: "*",
allow: "/",
},
sitemap: `${siteUrl}/sitemap.xml`,
};
}
+26
View File
@@ -0,0 +1,26 @@
import type { MetadataRoute } from "next";
const siteUrl = "https://opplenz.com";
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: siteUrl,
lastModified: new Date(),
changeFrequency: "weekly",
priority: 1,
},
{
url: `${siteUrl}/contact-us`,
lastModified: new Date(),
changeFrequency: "monthly",
priority: 0.7,
},
{
url: `${siteUrl}/marketing`,
lastModified: new Date(),
changeFrequency: "monthly",
priority: 0.6,
},
];
}
+2
View File
@@ -4,6 +4,8 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<meta name="description" content="Contact Opp lens to learn how AI-powered tender management helps SMEs find relevant tenders and win more opportunities.">
<link rel="canonical" href="https://opplenz.com/contact-us">
<link rel="icon" type="image/x-icon" href="assets/image/favicon.ico">
<title>Opplens</title>
<link rel="stylesheet" href="assets/css/style.css">
+2
View File
@@ -4,6 +4,8 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<meta name="description" content="Opp lens helps SMEs compete for public and private tenders with AI-powered discovery, preparation support, and opportunity alerts.">
<link rel="canonical" href="https://opplenz.com/email-marketing">
<link rel="icon" type="image/x-icon" href="assets/image/favicon.ico">
<title>Opplens</title>
<link rel="stylesheet" href="assets/css/style.css">
+2
View File
@@ -4,6 +4,8 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<meta name="description" content="Automated tender management platform for SMEs. Find tailored tenders, automate document handling, and get real-time alerts.">
<link rel="canonical" href="https://opplenz.com/">
<link rel="icon" type="image/x-icon" href="assets/image/favicon.ico">
<title>Opplens</title>
<link rel="stylesheet" href="assets/css/style.css">
+10
View File
@@ -0,0 +1,10 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["<rootDir>/lib"],
testMatch: ["**/__tests__/**/*.test.ts"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/$1",
},
};
+264
View File
@@ -0,0 +1,264 @@
import { AxiosError } from "axios";
import { handleApiError, parseApiError } from "../apiErrorHandler";
describe("API Error Handler", () => {
describe("parseApiError", () => {
it("should return default message for non-Error objects", () => {
const result = parseApiError("string error");
expect(result.generalMessage).toBe("Something went wrong. Please try again.");
expect(result.fieldErrors).toEqual({});
});
it("should handle network errors (no response)", () => {
const error = new Error("Network Error") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = undefined;
const result = parseApiError(error);
expect(result.generalMessage).toContain("Unable to connect");
});
it("should parse 400 errors with field-level errors", () => {
const error = new Error("Bad Request") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 400,
data: {
errors: {
email: "Invalid email format",
full_name: ["Name is too short", "Name contains invalid characters"],
},
},
statusText: "Bad Request",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.generalMessage).toContain("highlighted fields");
expect(result.fieldErrors.email).toMatch(/email/i);
expect(result.fieldErrors.full_name).toMatch(/name|short|character/i);
});
it("should map message-only 400 responses without exposing raw server text", () => {
const error = new Error("Bad Request") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 400,
data: {
message: "Custom validation error message",
},
statusText: "Bad Request",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.generalMessage).not.toContain("Custom validation");
expect(result.generalMessage.length).toBeGreaterThan(10);
});
it("should parse nested error object with field errors", () => {
const error = new Error("Bad Request") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 400,
data: {
error: {
code: "validation_failed",
errors: { work_email: "invalid_email" },
},
},
statusText: "Bad Request",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.fieldErrors.work_email).toMatch(/email/i);
});
it("should parse FastAPI-style detail arrays", () => {
const error = new Error("Unprocessable") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 422,
data: {
detail: [
{ loc: ["body", "phone_number"], msg: "value is not a valid phone" },
],
},
statusText: "Unprocessable Entity",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.fieldErrors.phone_number).toMatch(/phone/i);
});
it("should handle 401 unauthorized errors", () => {
const error = new Error("Unauthorized") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 401,
data: {},
statusText: "Unauthorized",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.generalMessage).toMatch(/Authentication|Sign in/i);
});
it("should handle 422 unprocessable entity errors", () => {
const error = new Error("Unprocessable Entity") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 422,
data: {
errors: {
phone: "invalid_phone",
},
},
statusText: "Unprocessable Entity",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.generalMessage).toContain("highlighted fields");
expect(result.fieldErrors.phone).toContain("phone number");
});
it("should handle 429 rate limit errors", () => {
const error = new Error("Too Many Requests") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 429,
data: {},
statusText: "Too Many Requests",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.generalMessage).toMatch(/many|wait/i);
});
it("should handle 500 server errors", () => {
const error = new Error("Internal Server Error") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 500,
data: {},
statusText: "Internal Server Error",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.generalMessage).toMatch(/server|try again/i);
});
it("should give a client-safe message for unlisted 4xx statuses with a body", () => {
const error = new Error("Nope") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 418,
data: { message: "I'm a teapot" },
statusText: "I'm a teapot",
headers: {},
config: {} as any,
};
const result = parseApiError(error);
expect(result.generalMessage).not.toContain("teapot");
expect(result.generalMessage.length).toBeGreaterThan(5);
});
});
describe("handleApiError", () => {
it("should call setError for each field error", () => {
const mockSetError = jest.fn();
const mockShowToast = jest.fn();
const error = new Error("Bad Request") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 400,
data: {
errors: {
email: "Invalid email",
phone: "Invalid phone",
},
},
statusText: "Bad Request",
headers: {},
config: {} as any,
};
handleApiError(error, mockSetError, mockShowToast, ["email", "phone"]);
expect(mockSetError).toHaveBeenCalledTimes(2);
expect(mockSetError).toHaveBeenCalledWith(
"email",
expect.objectContaining({ type: "server", message: expect.any(String) })
);
expect(mockSetError).toHaveBeenCalledWith(
"phone",
expect.objectContaining({ type: "server", message: expect.any(String) })
);
expect(mockShowToast).toHaveBeenCalledWith(expect.stringContaining("highlighted fields"));
});
it("should only set errors for fields in formFields list", () => {
const mockSetError = jest.fn();
const mockShowToast = jest.fn();
const error = new Error("Bad Request") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 400,
data: {
errors: {
email: "Invalid email",
unknown_field: "Unknown error",
},
},
statusText: "Bad Request",
headers: {},
config: {} as any,
};
handleApiError(error, mockSetError, mockShowToast, ["email"]);
expect(mockSetError).toHaveBeenCalledTimes(1);
expect(mockSetError).toHaveBeenCalledWith(
"email",
expect.objectContaining({ type: "server" })
);
});
it("should show general message when no field errors", () => {
const mockSetError = jest.fn();
const mockShowToast = jest.fn();
const error = new Error("Internal Server Error") as AxiosError;
error.isAxiosError = true;
(error as AxiosError).response = {
status: 500,
data: {},
statusText: "Internal Server Error",
headers: {},
config: {} as any,
};
handleApiError(error, mockSetError, mockShowToast, ["email"]);
expect(mockSetError).not.toHaveBeenCalled();
expect(mockShowToast).toHaveBeenCalledWith(expect.stringMatching(/server|try again/i));
});
});
});
+121
View File
@@ -0,0 +1,121 @@
import {
containsDangerousContent,
createFieldValidation,
createXSSValidator,
validationRules,
} from "../validation";
describe("Validation Functions", () => {
describe("containsDangerousContent", () => {
it("should detect script tags", () => {
expect(containsDangerousContent("<script>alert('XSS')</script>")).toBe(true);
expect(containsDangerousContent("<SCRIPT>alert('XSS')</SCRIPT>")).toBe(true);
});
it("should detect javascript: protocol", () => {
expect(containsDangerousContent("javascript:alert('XSS')")).toBe(true);
expect(containsDangerousContent("JAVASCRIPT:alert('XSS')")).toBe(true);
});
it("should detect event handlers", () => {
expect(containsDangerousContent("onclick=alert('XSS')")).toBe(true);
expect(containsDangerousContent("onerror=alert('XSS')")).toBe(true);
expect(containsDangerousContent("onload=alert('XSS')")).toBe(true);
});
it("should detect iframe tags", () => {
expect(containsDangerousContent("<iframe src='evil.com'>")).toBe(true);
});
it("should detect data: text/html", () => {
expect(containsDangerousContent("data: text/html,<script>")).toBe(true);
});
it("should return false for safe content", () => {
expect(containsDangerousContent("Hello World")).toBe(false);
expect(containsDangerousContent("john.doe@example.com")).toBe(false);
expect(containsDangerousContent("+1234567890")).toBe(false);
expect(containsDangerousContent("This is a normal message.")).toBe(false);
});
it("should handle empty or null input", () => {
expect(containsDangerousContent("")).toBe(false);
});
});
describe("createXSSValidator", () => {
it("should return error message for dangerous content", () => {
const validator = createXSSValidator("Full Name");
expect(validator("<script>alert('XSS')</script>")).toContain("Full Name");
expect(validator("<script>alert('XSS')</script>")).toContain("invalid");
});
it("should return true for safe content", () => {
const validator = createXSSValidator("Full Name");
expect(validator("John Doe")).toBe(true);
expect(validator("Jane Smith")).toBe(true);
});
});
describe("createFieldValidation", () => {
it("should create validation with XSS check", () => {
const validation = createFieldValidation("Email", true);
expect(validation).toHaveProperty("validate.noXSS");
expect(validation).toHaveProperty("required");
});
it("should include additional rules", () => {
const validation = createFieldValidation("Phone", false, {
pattern: { value: /^[+\d]+$/, message: "Invalid phone" },
});
expect(validation).toHaveProperty("pattern");
expect(validation).toHaveProperty("validate.noXSS");
});
});
describe("validationRules", () => {
describe("fullName rules", () => {
it("should have required validation", () => {
expect(validationRules.fullName.required.value).toBe(true);
});
it("should have min/max length", () => {
expect(validationRules.fullName.minLength.value).toBe(2);
expect(validationRules.fullName.maxLength.value).toBe(100);
});
it("should have XSS validation", () => {
expect(validationRules.fullName.validate.noXSS).toBeDefined();
});
});
describe("email rules", () => {
it("should have pattern validation", () => {
expect(validationRules.email.pattern.value).toBeDefined();
});
it("should have XSS validation", () => {
expect(validationRules.email.validate.noXSS).toBeDefined();
});
});
describe("phone rules", () => {
it("should have pattern validation for phone format", () => {
const pattern = validationRules.phone.pattern.value;
expect(pattern.test("+1234567890")).toBe(true);
expect(pattern.test("(123) 456-7890")).toBe(true);
expect(pattern.test("abc123")).toBe(false);
});
});
describe("message rules", () => {
it("should have XSS validation", () => {
expect(validationRules.message.validate.noXSS).toBeDefined();
});
it("should have max length of 1000", () => {
expect(validationRules.message.maxLength.value).toBe(1000);
});
});
});
});
+374
View File
@@ -0,0 +1,374 @@
/**
* API Error Handler Utility
* Parses server error responses and extracts field-level validation errors.
* Server text is mapped to safe, user-facing copy — raw messages are not echoed.
*/
import axios, { AxiosError } from "axios";
import { FieldValues, Path, UseFormSetError } from "react-hook-form";
/**
* Standard API error response structure (and common variants we normalize).
*/
export interface ApiErrorResponse {
message?: string;
errors?: Record<string, string | string[] | unknown> | unknown;
error?: string | ApiNestedError | Record<string, unknown>;
detail?: string | string[] | Record<string, string[] | unknown> | FastApiDetailItem[];
}
interface ApiNestedError {
message?: string;
code?: string;
errors?: Record<string, unknown>;
details?: Record<string, unknown>;
}
interface FastApiDetailItem {
loc?: unknown[];
msg?: string;
type?: string;
}
/**
* Parsed error result
*/
export interface ParsedApiError {
generalMessage: string;
fieldErrors: Record<string, string>;
}
const DEFAULT_GENERAL = "Something went wrong. Please try again.";
/** Shown under a field when the server flagged it but we do not expose its raw text. */
const GENERIC_FIELD_MESSAGE =
"This value could not be accepted. Check for typos and remove any HTML, scripts, or unusual symbols.";
const FIELD_NAME_MAP: Record<string, string> = {
fullName: "full_name",
full_name: "full_name",
email: "email",
phone: "phone",
phoneNumber: "phone_number",
phone_number: "phone_number",
message: "message",
companyName: "company_name",
company_name: "company_name",
workEmail: "work_email",
work_email: "work_email",
};
const ERROR_MESSAGES: Record<string, string> = {
invalid_input:
"That does not look like valid input. Use plain text only — no HTML or scripts.",
xss_detected:
"Invalid content was detected. Remove any HTML tags, scripts, or code-like text.",
validation_failed: "Please check this field and try again.",
required: "This field is required.",
invalid_email: "Please enter a valid email address.",
invalid_phone: "Please enter a valid phone number using digits and common phone symbols only.",
too_short: "This value is too short.",
too_long: "This value is too long.",
duplicate: "This value is already in use. Try a different one.",
duplicate_inquiry:
"You already have a pending inquiry with this email. Please wait for it to be processed.",
};
/**
* Maps a single server token or short code to a friendly message.
*/
function mapErrorCode(code: string): string | null {
const key = code.trim().toLowerCase().replace(/[\s-]+/g, "_");
if (ERROR_MESSAGES[key]) return ERROR_MESSAGES[key];
const aliases: Record<string, keyof typeof ERROR_MESSAGES> = {
invalid_email_format: "invalid_email",
email_invalid: "invalid_email",
invalid_email: "invalid_email",
invalid_phone_format: "invalid_phone",
invalid_phone: "invalid_phone",
phone_invalid: "invalid_phone",
xss: "xss_detected",
xss_detected: "xss_detected",
malicious_content: "xss_detected",
validation_error: "validation_failed",
validation_failed: "validation_failed",
duplicate_inquiry: "duplicate_inquiry",
duplicate: "duplicate",
};
const mappedKey = aliases[key];
return mappedKey ? ERROR_MESSAGES[mappedKey] : null;
}
/**
* Infers a safe message from server hint text without echoing the full string.
*/
function inferMessageFromHint(hint: string): string {
const h = hint.toLowerCase();
if (/(xss|script|html|tag|malicious|injection)/i.test(hint)) {
return ERROR_MESSAGES.xss_detected;
}
if (/email/.test(h)) return ERROR_MESSAGES.invalid_email;
if (/phone|tel|mobile/.test(h)) return ERROR_MESSAGES.invalid_phone;
if (/company|organization|organisation/.test(h)) {
return "Please use a valid company name (plain text, no HTML or scripts).";
}
if (/name|full/.test(h)) {
return "Please enter a valid name using letters and common characters only.";
}
if (/required|missing|empty/.test(h)) return ERROR_MESSAGES.required;
if (/long|length|exceed/.test(h)) return ERROR_MESSAGES.too_long;
if (/short|minimum/.test(h)) return ERROR_MESSAGES.too_short;
if (/duplicate|already|exist/.test(h)) return ERROR_MESSAGES.duplicate_inquiry;
return GENERIC_FIELD_MESSAGE;
}
function normalizeFieldName(fieldName: string): string {
return FIELD_NAME_MAP[fieldName] || fieldName;
}
function isPlainObject(v: unknown): v is Record<string, unknown> {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
/**
* Turns assorted server error values into a single user-safe string.
*/
function normalizeFieldErrorValue(value: unknown): string {
if (value === null || value === undefined) return GENERIC_FIELD_MESSAGE;
if (typeof value === "number" || typeof value === "boolean") {
return mapErrorCode(String(value)) ?? GENERIC_FIELD_MESSAGE;
}
if (typeof value === "string") {
const trimmed = value.trim();
if (!trimmed) return GENERIC_FIELD_MESSAGE;
const byCode = mapErrorCode(trimmed);
if (byCode) return byCode;
if (/^[a-z0-9_.]+$/i.test(trimmed) && trimmed.length <= 80) {
return mapErrorCode(trimmed.replace(/\./g, "_")) ?? GENERIC_FIELD_MESSAGE;
}
return inferMessageFromHint(trimmed);
}
if (Array.isArray(value)) {
const parts = value
.map((v) => normalizeFieldErrorValue(v))
.filter((s, i, arr) => s && arr.indexOf(s) === i);
return parts.length ? parts.join(" ") : GENERIC_FIELD_MESSAGE;
}
if (isPlainObject(value)) {
const msg =
typeof value.message === "string"
? value.message
: typeof value.msg === "string"
? value.msg
: typeof value.detail === "string"
? value.detail
: "";
if (msg) return inferMessageFromHint(msg);
}
return GENERIC_FIELD_MESSAGE;
}
function mergeFieldErrors(
target: Record<string, string>,
source: Record<string, string>
): void {
for (const [k, v] of Object.entries(source)) {
const key = normalizeFieldName(k);
target[key] = v;
}
}
function parseErrorsRecord(record: Record<string, unknown>): Record<string, string> {
const out: Record<string, string> = {};
for (const [field, err] of Object.entries(record)) {
out[field] = normalizeFieldErrorValue(err);
}
return out;
}
function parseFastApiDetailArray(items: FastApiDetailItem[]): Record<string, string> {
const out: Record<string, string> = {};
for (const item of items) {
if (!item || typeof item !== "object") continue;
const loc = Array.isArray(item.loc) ? item.loc : [];
const rawKey = loc.filter((x): x is string => typeof x === "string").pop();
const field = rawKey ? normalizeFieldName(rawKey) : "_form";
const hint = item.msg ?? item.type ?? "";
out[field] = hint ? inferMessageFromHint(String(hint)) : GENERIC_FIELD_MESSAGE;
}
return out;
}
function parseDetail(detail: unknown): Record<string, string> {
if (!detail) return {};
if (typeof detail === "string") {
return { _form: inferMessageFromHint(detail) };
}
if (Array.isArray(detail)) {
if (detail.length && typeof detail[0] === "object" && detail[0] !== null && "loc" in detail[0]) {
return parseFastApiDetailArray(detail as FastApiDetailItem[]);
}
return { _form: normalizeFieldErrorValue(detail) };
}
if (isPlainObject(detail)) {
return parseErrorsRecord(detail as Record<string, unknown>);
}
return {};
}
/**
* Walks common API shapes and collects field errors + optional form-level key.
*/
function extractFieldErrorsFromBody(data: unknown): {
fieldErrors: Record<string, string>;
formLevel?: string;
} {
const fieldErrors: Record<string, string> = {};
let formLevel: string | undefined;
if (!data) return { fieldErrors };
if (typeof data === "string") {
formLevel = inferMessageFromHint(data);
return { fieldErrors, formLevel };
}
if (!isPlainObject(data)) return { fieldErrors };
const d = data as Record<string, unknown>;
if (isPlainObject(d.errors)) {
mergeFieldErrors(fieldErrors, parseErrorsRecord(d.errors as Record<string, unknown>));
}
if (Array.isArray(d.errors)) {
mergeFieldErrors(fieldErrors, { _form: normalizeFieldErrorValue(d.errors) });
}
const detailParsed = parseDetail(d.detail);
mergeFieldErrors(fieldErrors, detailParsed);
if (detailParsed._form && !fieldErrors._form) {
fieldErrors._form = detailParsed._form;
}
const err = d.error;
if (typeof err === "string") {
formLevel = inferMessageFromHint(err);
} else if (isPlainObject(err)) {
const ne = err as ApiNestedError;
if (typeof ne.message === "string") {
formLevel = inferMessageFromHint(ne.message);
}
if (typeof ne.code === "string") {
const byCode = mapErrorCode(ne.code);
if (byCode) formLevel = byCode;
}
if (isPlainObject(ne.errors)) {
mergeFieldErrors(fieldErrors, parseErrorsRecord(ne.errors as Record<string, unknown>));
}
if (isPlainObject(ne.details)) {
mergeFieldErrors(fieldErrors, parseErrorsRecord(ne.details as Record<string, unknown>));
}
}
if (typeof d.message === "string" && !formLevel) {
formLevel = inferMessageFromHint(d.message);
}
return { fieldErrors, formLevel };
}
function getAxiosResponse(error: unknown): AxiosError<ApiErrorResponse>["response"] | undefined {
if (axios.isAxiosError(error)) {
return error.response;
}
if (error instanceof Error && "isAxiosError" in error && (error as AxiosError).isAxiosError) {
return (error as AxiosError<ApiErrorResponse>).response;
}
return undefined;
}
/**
* Parses API error response and extracts field-level errors
*/
export function parseApiError(error: unknown): ParsedApiError {
const result: ParsedApiError = {
generalMessage: DEFAULT_GENERAL,
fieldErrors: {},
};
const response = getAxiosResponse(error);
if (!response) {
if (error instanceof Error) {
result.generalMessage = "Unable to connect to the server. Check your connection and try again.";
}
return result;
}
const { status, data } = response;
const extracted = extractFieldErrorsFromBody(data);
Object.assign(result.fieldErrors, extracted.fieldErrors);
const validationSummary =
"Some information could not be accepted. Please review the highlighted fields below.";
if (status === 400 || status === 422) {
result.generalMessage = validationSummary;
if (extracted.formLevel && Object.keys(result.fieldErrors).length === 0) {
result.generalMessage = extracted.formLevel;
}
} else if (status === 401) {
result.generalMessage = "Authentication is required. Sign in and try again.";
} else if (status === 403) {
result.generalMessage = "You do not have permission to perform this action.";
} else if (status === 404) {
result.generalMessage = "The requested resource was not found.";
} else if (status === 409) {
result.generalMessage = ERROR_MESSAGES.duplicate_inquiry;
} else if (status === 429) {
result.generalMessage = "Too many attempts. Please wait a moment and try again.";
} else if (status >= 500) {
result.generalMessage = "The server had a problem. Please try again in a few minutes.";
} else if (status >= 400 && status < 500) {
result.generalMessage =
Object.keys(result.fieldErrors).length > 0
? validationSummary
: extracted.formLevel ?? "We could not complete this request. Please check your input and try again.";
}
if (result.fieldErrors._form) {
const formOnly = result.fieldErrors._form;
delete result.fieldErrors._form;
if (Object.keys(result.fieldErrors).length === 0) {
result.generalMessage = formOnly;
}
}
return result;
}
/**
* Handles API error and sets form field errors using react-hook-form
*/
export function handleApiError<T extends FieldValues>(
error: unknown,
setError: UseFormSetError<T>,
showToast: (message: string) => void,
formFields?: string[]
): void {
const parsedError = parseApiError(error);
let hasFieldErrors = false;
Object.entries(parsedError.fieldErrors).forEach(([field, message]) => {
if (!formFields || formFields.includes(field)) {
setError(field as Path<T>, {
type: "server",
message,
});
hasFieldErrors = true;
}
});
showToast(parsedError.generalMessage);
}
+154
View File
@@ -0,0 +1,154 @@
/**
* Validation utilities for form fields
* Detects potentially harmful content (XSS patterns) and provides validation rules
*/
// Patterns that indicate potentially malicious content
const DANGEROUS_PATTERNS = [
/<script[\s\S]*?>/i,
/<\/script>/i,
/javascript:/i,
/vbscript:/i,
/on\w+\s*=/i, // onclick=, onerror=, onload=, etc.
/<iframe[\s\S]*?>/i,
/<object[\s\S]*?>/i,
/<embed[\s\S]*?>/i,
/<link[\s\S]*?>/i,
/<meta[\s\S]*?>/i,
/data:\s*text\/html/i,
/expression\s*\(/i, // CSS expression
/url\s*\(\s*["']?\s*javascript:/i,
];
/**
* Checks if text contains potentially dangerous patterns (XSS)
* @param text - The text to check
* @returns true if dangerous patterns are found
*/
export function containsDangerousContent(text: string): boolean {
if (!text) return false;
return DANGEROUS_PATTERNS.some((pattern) => pattern.test(text));
}
/**
* Validation function for react-hook-form that checks for XSS patterns
* @param fieldName - The human-readable name of the field for error messages
* @returns Validation function for react-hook-form
*/
export function createXSSValidator(fieldName: string) {
return (value: string) => {
if (containsDangerousContent(value)) {
return `${fieldName} contains invalid characters or content. Please remove any special HTML tags or scripts.`;
}
return true;
};
}
/**
* Standard validation rules with XSS protection for common field types
*/
export const validationRules = {
fullName: {
required: {
value: true,
message: "Full name is required",
},
minLength: {
value: 2,
message: "Full name must be at least 2 characters",
},
maxLength: {
value: 100,
message: "Full name must not exceed 100 characters",
},
validate: {
noXSS: createXSSValidator("Full name"),
},
},
email: {
required: {
value: true,
message: "Email is required",
},
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: "Please enter a valid email address",
},
validate: {
noXSS: createXSSValidator("Email"),
},
},
phone: {
required: {
value: true,
message: "Phone number is required",
},
minLength: {
value: 10,
message: "Phone number must be at least 10 characters",
},
maxLength: {
value: 20,
message: "Phone number must not exceed 20 characters",
},
pattern: {
value: /^[+\d\s()-]+$/,
message: "Please enter a valid phone number (digits, +, spaces, parentheses, and dashes only)",
},
},
message: {
required: {
value: true,
message: "Message is required",
},
minLength: {
value: 10,
message: "Message must be at least 10 characters",
},
maxLength: {
value: 1000,
message: "Message must not exceed 1000 characters",
},
validate: {
noXSS: createXSSValidator("Message"),
},
},
companyName: {
maxLength: {
value: 200,
message: "Company name must not exceed 200 characters",
},
validate: {
noXSS: createXSSValidator("Company name"),
},
},
};
/**
* Creates validation rules for a field with optional XSS check
* @param fieldName - Human-readable field name
* @param isRequired - Whether the field is required
* @param additionalRules - Additional validation rules to merge
*/
export function createFieldValidation(
fieldName: string,
isRequired: boolean = false,
additionalRules: Record<string, unknown> = {}
) {
const rules: Record<string, unknown> = {
validate: {
noXSS: createXSSValidator(fieldName),
},
...additionalRules,
};
if (isRequired) {
rules.required = `${fieldName} is required`;
}
return rules;
}
+4 -1
View File
@@ -1,7 +1,10 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
experimental: {
globalNotFound: true,
},
htmlLimitedBots: /.*/,
};
export default nextConfig;
+4052 -4
View File
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -5,7 +5,9 @@
"scripts": {
"dev": "next dev --turbopack",
"build": "next build --turbopack",
"start": "next start"
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
},
"dependencies": {
"@hcaptcha/react-hcaptcha": "^1.16.0",
@@ -24,10 +26,13 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/jest": "^30.0.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"jest": "^30.2.0",
"tailwindcss": "^4",
"ts-jest": "^29.4.6",
"typescript": "^5"
}
}
BIN
View File
Binary file not shown.
Binary file not shown.