⚡ Bolt: Implement route lazy loading #23
@@ -1,3 +1,7 @@
|
|||||||
## 2024-05-24 - Accessible Input Validation
|
## 2024-05-24 - Accessible Input Validation
|
||||||
**Learning:** React 19 renders `aria-invalid={false}` as `aria-invalid="false"`, unlike older versions which might have omitted it. Explicitly handling this in tests is crucial. Also, ensuring DOM cleanup (`cleanup()`) in `afterEach` is vital when testing similar components with same labels across tests to avoid "finding the wrong element" false positives/negatives.
|
**Learning:** React 19 renders `aria-invalid={false}` as `aria-invalid="false"`, unlike older versions which might have omitted it. Explicitly handling this in tests is crucial. Also, ensuring DOM cleanup (`cleanup()`) in `afterEach` is vital when testing similar components with same labels across tests to avoid "finding the wrong element" false positives/negatives.
|
||||||
**Action:** Always include `afterEach(() => cleanup())` in `vitest` setup for DOM tests, and expect `aria-invalid="false"` (or explicitly handle `undefined` if omission is desired) when testing valid states in React 19.
|
**Action:** Always include `afterEach(() => cleanup())` in `vitest` setup for DOM tests, and expect `aria-invalid="false"` (or explicitly handle `undefined` if omission is desired) when testing valid states in React 19.
|
||||||
|
|
||||||
|
## 2024-05-24 - Accessible Loading Buttons
|
||||||
|
**Learning:** Replacing button text with a spinner destroys the accessible name.
|
||||||
|
**Action:** Use `aria-busy="true"`, keep children in DOM (visually hidden via opacity/class), and overlay spinner absolutely. Ensure wrapper element replicates flex layout (gap/alignment) to prevent layout shifts.
|
||||||
|
|||||||
@@ -5,3 +5,6 @@
|
|||||||
## 2025-01-26 - Missing Node Modules
|
## 2025-01-26 - Missing Node Modules
|
||||||
**Learning:** The environment might lack `node_modules` completely, preventing `npx vitest` or `pnpm exec tsc` from running even if dependencies are listed in `package.json`. Network restrictions may prevent `pnpm install`.
|
**Learning:** The environment might lack `node_modules` completely, preventing `npx vitest` or `pnpm exec tsc` from running even if dependencies are listed in `package.json`. Network restrictions may prevent `pnpm install`.
|
||||||
**Action:** When `node_modules` is missing and cannot be installed, rely on static analysis, careful code review, and verifying file contents manually. Do not assume tests can run.
|
**Action:** When `node_modules` is missing and cannot be installed, rely on static analysis, careful code review, and verifying file contents manually. Do not assume tests can run.
|
||||||
|
## 2024-05-22 - High-Frequency State Isolation
|
||||||
|
**Learning:** High-frequency state updates (like typing effects) in large parent components (`Hero`) trigger massive unnecessary re-renders of expensive sub-trees (`GradientBlinds`, `Button`).
|
||||||
|
**Action:** Isolate high-frequency state into small, leaf-node components (e.g., `TypedText`) and wrap them in `React.memo` if necessary, keeping the heavy parent static.
|
||||||
|
|||||||
6
.jules/palette.md
Normal file
6
.jules/palette.md
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
## 2025-02-18 - Missing Alerts for Dynamic Status
|
||||||
|
**Learning:** The application uses `framer-motion` for dynamic feedback messages but consistently lacks `role="alert"` and `aria-live` attributes, causing screen readers to miss critical status updates.
|
||||||
|
**Action:** When auditing forms, check all `motion.div/p` elements used for feedback and add `role="alert"` and `aria-live="polite"` (or "assertive" for errors).
|
||||||
|
## 2024-05-22 - Semantic Required Fields with Custom Validation
|
||||||
|
**Learning:** To combine custom validation UI with semantic `required` attributes (vital for a11y), add `noValidate` to the `<form>`. This prevents native browser bubbles while keeping the accessibility benefits.
|
||||||
|
**Action:** Use `noValidate` on forms when implementing custom validation but keep `required` attributes on inputs.
|
||||||
@@ -2,3 +2,18 @@
|
|||||||
**Vulnerability:** The application is served without standard security headers (CSP, X-Frame-Options, etc.), leaving it vulnerable to XSS, Clickjacking, and MIME sniffing.
|
**Vulnerability:** The application is served without standard security headers (CSP, X-Frame-Options, etc.), leaving it vulnerable to XSS, Clickjacking, and MIME sniffing.
|
||||||
**Learning:** Single Page Applications (SPAs) served via static hosting (like Firebase) rely on infrastructure configuration for security headers, which are often overlooked. Default configurations are rarely secure enough.
|
**Learning:** Single Page Applications (SPAs) served via static hosting (like Firebase) rely on infrastructure configuration for security headers, which are often overlooked. Default configurations are rarely secure enough.
|
||||||
**Prevention:** Always configure `firebase.json` (or equivalent) with strict security headers (CSP, X-Frame-Options, HSTS, etc.) at project setup.
|
**Prevention:** Always configure `firebase.json` (or equivalent) with strict security headers (CSP, X-Frame-Options, HSTS, etc.) at project setup.
|
||||||
|
|
||||||
|
## 2026-01-26 - Client-Side Rate Limiting for Serverless Forms
|
||||||
|
**Vulnerability:** Contact forms using client-side services (like EmailJS) without backend middleware are vulnerable to spam and quota exhaustion.
|
||||||
|
**Learning:** While true rate limiting requires a backend, client-side throttling via `localStorage` provides a necessary friction layer for legitimate users and simple bots, protecting external service quotas.
|
||||||
|
**Prevention:** Implement reusable rate-limit hooks for all public-facing form submissions in static/serverless applications.
|
||||||
|
|
||||||
|
## 2026-02-13 - State Leakage in Tests masking Security Failures
|
||||||
|
**Vulnerability:** Flaky tests caused by `localStorage` state leakage (e.g. rate limits persisting between tests) can prevent security features from being properly verified, leading to false negatives or untested paths.
|
||||||
|
**Learning:** Global state like `localStorage` must be explicitly cleared in `afterEach` blocks in test environments (jsdom). Failing to do so can cause subsequent tests to fail or behave unpredictably, especially for rate-limiting logic.
|
||||||
|
**Prevention:** Always include `localStorage.clear()` in `afterEach` (or `beforeEach`) when testing components that rely on local storage.
|
||||||
|
|
||||||
|
## 2026-02-13 - Strict Email Validation vs HTML5 Validation
|
||||||
|
**Vulnerability:** Standard email regexes and HTML5 validation are often too permissive, allowing XSS vectors (like `<script>`) in email fields if not properly sanitized/rejected.
|
||||||
|
**Learning:** While HTML5 browsers block some invalid emails, relying solely on them is insufficient for defense-in-depth. Application-level validation should explicitly reject dangerous characters (`<`, `>`) to prevent stored XSS or injection if the data is processed by less-secure backends.
|
||||||
|
**Prevention:** Implement strict, reusable validation functions (`isValidEmail`) that reject XSS vectors, and ensure tests verify this logic by bypassing browser validation if necessary.
|
||||||
|
|||||||
@@ -24,6 +24,14 @@
|
|||||||
"key": "X-Frame-Options",
|
"key": "X-Frame-Options",
|
||||||
"value": "DENY"
|
"value": "DENY"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "Strict-Transport-Security",
|
||||||
|
"value": "max-age=31536000; includeSubDomains"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "Permissions-Policy",
|
||||||
|
"value": "camera=(), microphone=(), geolocation=()"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"key": "Referrer-Policy",
|
"key": "Referrer-Policy",
|
||||||
"value": "strict-origin-when-cross-origin"
|
"value": "strict-origin-when-cross-origin"
|
||||||
|
|||||||
@@ -176,17 +176,11 @@ describe('GradientBlinds', () => {
|
|||||||
unmount();
|
unmount();
|
||||||
expect(removeEventListenerSpy).toHaveBeenCalledWith('pointermove', expect.any(Function));
|
expect(removeEventListenerSpy).toHaveBeenCalledWith('pointermove', expect.any(Function));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('minimizes getBoundingClientRect calls during pointer move', () => {
|
it('minimizes getBoundingClientRect calls during pointer move', () => {
|
||||||
const { unmount } = render(<GradientBlinds />);
|
const { unmount } = render(<GradientBlinds />);
|
||||||
|
|
||||||
// Spy on getBoundingClientRect
|
|
||||||
// Note: In jsdom, canvas is an HTMLCanvasElement which inherits from HTMLElement
|
|
||||||
const spy = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect');
|
const spy = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect');
|
||||||
|
|
||||||
// Trigger pointer move to clear any initial calls or verify baseline
|
|
||||||
// The initial render calls resize(), which calls getBoundingClientRect on container
|
|
||||||
|
|
||||||
// Clear spy history from initial render
|
|
||||||
spy.mockClear();
|
spy.mockClear();
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
@@ -198,9 +192,37 @@ describe('GradientBlinds', () => {
|
|||||||
window.dispatchEvent(event);
|
window.dispatchEvent(event);
|
||||||
});
|
});
|
||||||
|
|
||||||
// EXPECTATION: It should NOT be called because the listener shouldn't be attached (not visible)
|
|
||||||
expect(spy).not.toHaveBeenCalled();
|
expect(spy).not.toHaveBeenCalled();
|
||||||
|
|
||||||
unmount();
|
unmount();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('avoids expensive DOM reads (scrollX/Y) in pointermove handler when visible', () => {
|
||||||
|
const { unmount } = render(<GradientBlinds />);
|
||||||
|
|
||||||
|
// Spy on scrollX/scrollY getters
|
||||||
|
// Note: In jsdom, these are properties on window.
|
||||||
|
const scrollSpy = vi.spyOn(window, 'scrollX', 'get');
|
||||||
|
|
||||||
|
// Make visible to attach listener
|
||||||
|
act(() => {
|
||||||
|
if (ioCallback) {
|
||||||
|
ioCallback([{ isIntersecting: true } as IntersectionObserverEntry]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
scrollSpy.mockClear();
|
||||||
|
|
||||||
|
// Trigger pointer move
|
||||||
|
act(() => {
|
||||||
|
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 100, clientY: 100 }));
|
||||||
|
});
|
||||||
|
|
||||||
|
// With the optimization (moving to RAF loop), this should be 0.
|
||||||
|
// Without optimization, this will be > 0.
|
||||||
|
// Since we are mocking RAF and not running the loop, if it's in the loop, it won't be called.
|
||||||
|
expect(scrollSpy).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -64,6 +64,8 @@ const GradientBlinds: React.FC<GradientBlindsProps> = ({
|
|||||||
const geometryRef = useRef<Geometry | null>(null);
|
const geometryRef = useRef<Geometry | null>(null);
|
||||||
const rendererRef = useRef<Renderer | null>(null);
|
const rendererRef = useRef<Renderer | null>(null);
|
||||||
const mouseTargetRef = useRef<[number, number]>([0, 0]);
|
const mouseTargetRef = useRef<[number, number]>([0, 0]);
|
||||||
|
// Optimization: store raw pointer position (viewport coords) to decouple event handling from calculation
|
||||||
|
const pointerPosRef = useRef<{ x: number; y: number } | null>(null);
|
||||||
const lastTimeRef = useRef<number>(0);
|
const lastTimeRef = useRef<number>(0);
|
||||||
const firstResizeRef = useRef<boolean>(true);
|
const firstResizeRef = useRef<boolean>(true);
|
||||||
const rectRef = useRef<DOMRect | null>(null);
|
const rectRef = useRef<DOMRect | null>(null);
|
||||||
@@ -309,6 +311,15 @@ void main() {
|
|||||||
ro.observe(container);
|
ro.observe(container);
|
||||||
|
|
||||||
const onPointerMove = (e: PointerEvent) => {
|
const onPointerMove = (e: PointerEvent) => {
|
||||||
|
pointerPosRef.current = { x: e.clientX, y: e.clientY };
|
||||||
|
};
|
||||||
|
|
||||||
|
const loop = (t: number) => {
|
||||||
|
rafRef.current = requestAnimationFrame(loop);
|
||||||
|
uniforms.iTime.value = t * 0.001;
|
||||||
|
|
||||||
|
// Update target based on pointer position and scroll offset
|
||||||
|
if (pointerPosRef.current) {
|
||||||
const scale = (renderer as unknown as { dpr?: number }).dpr || 1;
|
const scale = (renderer as unknown as { dpr?: number }).dpr || 1;
|
||||||
let x, y;
|
let x, y;
|
||||||
|
|
||||||
@@ -317,23 +328,17 @@ void main() {
|
|||||||
const dy = window.scrollY - scrollPosRef.current.y;
|
const dy = window.scrollY - scrollPosRef.current.y;
|
||||||
const rectLeft = rectRef.current.left - dx;
|
const rectLeft = rectRef.current.left - dx;
|
||||||
const rectTop = rectRef.current.top - dy;
|
const rectTop = rectRef.current.top - dy;
|
||||||
x = (e.clientX - rectLeft) * scale;
|
x = (pointerPosRef.current.x - rectLeft) * scale;
|
||||||
y = (rectRef.current.height - (e.clientY - rectTop)) * scale;
|
y = (rectRef.current.height - (pointerPosRef.current.y - rectTop)) * scale;
|
||||||
} else {
|
} else {
|
||||||
|
// Fallback if rectRef missing
|
||||||
const rect = canvas.getBoundingClientRect();
|
const rect = canvas.getBoundingClientRect();
|
||||||
x = (e.clientX - rect.left) * scale;
|
x = (pointerPosRef.current.x - rect.left) * scale;
|
||||||
y = (rect.height - (e.clientY - rect.top)) * scale;
|
y = (rect.height - (pointerPosRef.current.y - rect.top)) * scale;
|
||||||
}
|
}
|
||||||
|
|
||||||
mouseTargetRef.current = [x, y];
|
mouseTargetRef.current = [x, y];
|
||||||
if (mouseDampening <= 0) {
|
|
||||||
uniforms.iMouse.value = [x, y];
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
const loop = (t: number) => {
|
|
||||||
rafRef.current = requestAnimationFrame(loop);
|
|
||||||
uniforms.iTime.value = t * 0.001;
|
|
||||||
if (mouseDampening > 0) {
|
if (mouseDampening > 0) {
|
||||||
if (!lastTimeRef.current) lastTimeRef.current = t;
|
if (!lastTimeRef.current) lastTimeRef.current = t;
|
||||||
const dt = (t - lastTimeRef.current) / 1000;
|
const dt = (t - lastTimeRef.current) / 1000;
|
||||||
@@ -346,6 +351,9 @@ void main() {
|
|||||||
cur[0] += (target[0] - cur[0]) * factor;
|
cur[0] += (target[0] - cur[0]) * factor;
|
||||||
cur[1] += (target[1] - cur[1]) * factor;
|
cur[1] += (target[1] - cur[1]) * factor;
|
||||||
} else {
|
} else {
|
||||||
|
if (pointerPosRef.current) {
|
||||||
|
uniforms.iMouse.value = mouseTargetRef.current;
|
||||||
|
}
|
||||||
lastTimeRef.current = t;
|
lastTimeRef.current = t;
|
||||||
}
|
}
|
||||||
if (!paused && programRef.current && meshRef.current) {
|
if (!paused && programRef.current && meshRef.current) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useEffect, useRef } from "react";
|
import { useState, useEffect, useRef, memo } from "react";
|
||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { motion } from "motion/react";
|
import { motion } from "motion/react";
|
||||||
import { useTranslation } from "../../i18n";
|
import { useTranslation } from "../../i18n";
|
||||||
@@ -9,6 +9,21 @@ import styles from "./Hero.module.css";
|
|||||||
|
|
||||||
const GRADIENT_COLORS = ["#26a269", "#8ff0a4"];
|
const GRADIENT_COLORS = ["#26a269", "#8ff0a4"];
|
||||||
|
|
||||||
|
interface TypedTextProps {
|
||||||
|
words: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const TypedText = memo(({ words }: TypedTextProps) => {
|
||||||
|
const { text } = useTypingEffect({
|
||||||
|
words,
|
||||||
|
typingSpeed: 80,
|
||||||
|
deletingSpeed: 40,
|
||||||
|
pauseDuration: 2500,
|
||||||
|
});
|
||||||
|
|
||||||
|
return <>{text}</>;
|
||||||
|
});
|
||||||
|
|
||||||
export function Hero() {
|
export function Hero() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [showScrollIndicator, setShowScrollIndicator] = useState(true);
|
const [showScrollIndicator, setShowScrollIndicator] = useState(true);
|
||||||
@@ -29,13 +44,6 @@ export function Hero() {
|
|||||||
return () => observer.disconnect();
|
return () => observer.disconnect();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const { text } = useTypingEffect({
|
|
||||||
words: t.hero.rotatingWords,
|
|
||||||
typingSpeed: 80,
|
|
||||||
deletingSpeed: 40,
|
|
||||||
pauseDuration: 2500,
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className={styles.hero}>
|
<section className={styles.hero}>
|
||||||
<div
|
<div
|
||||||
@@ -100,7 +108,7 @@ export function Hero() {
|
|||||||
>
|
>
|
||||||
<span>{t.hero.tagline}</span>
|
<span>{t.hero.tagline}</span>
|
||||||
<span className={styles.typed}>
|
<span className={styles.typed}>
|
||||||
{text}
|
<TypedText words={t.hero.rotatingWords} />
|
||||||
<span className={styles.cursor}>|</span>
|
<span className={styles.cursor}>|</span>
|
||||||
</span>
|
</span>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
.button {
|
.button {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
|
position: relative;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: var(--space-sm);
|
gap: var(--space-sm);
|
||||||
@@ -80,3 +81,23 @@
|
|||||||
transform: rotate(360deg);
|
transform: rotate(360deg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: var(--space-sm);
|
||||||
|
transition: opacity 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.contentHidden {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loaderWrapper {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { type ReactNode, type ButtonHTMLAttributes } from 'react';
|
|||||||
import { motion } from 'motion/react';
|
import { motion } from 'motion/react';
|
||||||
import styles from './Button.module.css';
|
import styles from './Button.module.css';
|
||||||
|
|
||||||
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
interface ButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onAnimationStart' | 'onDragStart' | 'onDragEnd' | 'onDrag'> {
|
||||||
variant?: 'primary' | 'secondary' | 'outline';
|
variant?: 'primary' | 'secondary' | 'outline';
|
||||||
size?: 'sm' | 'md' | 'lg';
|
size?: 'sm' | 'md' | 'lg';
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
@@ -24,14 +24,18 @@ export function Button({
|
|||||||
type={type}
|
type={type}
|
||||||
className={`${styles.button} ${styles[variant]} ${styles[size]} ${className || ''}`}
|
className={`${styles.button} ${styles[variant]} ${styles[size]} ${className || ''}`}
|
||||||
disabled={disabled || isLoading}
|
disabled={disabled || isLoading}
|
||||||
|
aria-busy={isLoading}
|
||||||
whileHover={{ scale: 1.02 }}
|
whileHover={{ scale: 1.02 }}
|
||||||
whileTap={{ scale: 0.98 }}
|
whileTap={{ scale: 0.98 }}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
<span className={`${styles.content} ${isLoading ? styles.contentHidden : ''}`}>
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
{isLoading && (
|
||||||
|
<span className={styles.loaderWrapper} aria-hidden="true">
|
||||||
<span className={styles.loader} />
|
<span className={styles.loader} />
|
||||||
) : (
|
</span>
|
||||||
children
|
|
||||||
)}
|
)}
|
||||||
</motion.button>
|
</motion.button>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -10,6 +10,11 @@
|
|||||||
color: var(--md-sys-color-on-surface);
|
color: var(--md-sys-color-on-surface);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.required {
|
||||||
|
color: var(--md-sys-color-error);
|
||||||
|
margin-left: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
.input {
|
.input {
|
||||||
padding: var(--space-md);
|
padding: var(--space-md);
|
||||||
font-family: var(--md-sys-typescale-body-font);
|
font-family: var(--md-sys-typescale-body-font);
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(
|
|||||||
<div className={`${styles.field} ${error ? styles.hasError : ''} ${className || ''}`}>
|
<div className={`${styles.field} ${error ? styles.hasError : ''} ${className || ''}`}>
|
||||||
<label htmlFor={inputId} className={styles.label}>
|
<label htmlFor={inputId} className={styles.label}>
|
||||||
{label}
|
{label}
|
||||||
|
{props.required && (
|
||||||
|
<span className={styles.required} aria-hidden="true">
|
||||||
|
*
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
ref={ref}
|
ref={ref}
|
||||||
@@ -46,6 +51,11 @@ export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
|
|||||||
<div className={`${styles.field} ${error ? styles.hasError : ''} ${className || ''}`}>
|
<div className={`${styles.field} ${error ? styles.hasError : ''} ${className || ''}`}>
|
||||||
<label htmlFor={inputId} className={styles.label}>
|
<label htmlFor={inputId} className={styles.label}>
|
||||||
{label}
|
{label}
|
||||||
|
{props.required && (
|
||||||
|
<span className={styles.required} aria-hidden="true">
|
||||||
|
*
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</label>
|
</label>
|
||||||
<textarea
|
<textarea
|
||||||
ref={ref}
|
ref={ref}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
import { render, screen, cleanup } from '@testing-library/react';
|
import { render, screen, cleanup } from '@testing-library/react';
|
||||||
import { describe, it, expect, afterEach } from 'vitest';
|
import { describe, it, expect, afterEach } from 'vitest';
|
||||||
import { Button } from '../Button';
|
import { Button } from '../Button';
|
||||||
import React from 'react';
|
|
||||||
|
|
||||||
describe('Button', () => {
|
describe('Button', () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -20,4 +19,13 @@ describe('Button', () => {
|
|||||||
const button = screen.getByTestId('custom-button');
|
const button = screen.getByTestId('custom-button');
|
||||||
expect(button).toBeTruthy();
|
expect(button).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('renders loading state correctly', () => {
|
||||||
|
render(<Button isLoading>Submit</Button>);
|
||||||
|
const button = screen.getByRole('button', { name: /submit/i }) as HTMLButtonElement;
|
||||||
|
expect(button.getAttribute('aria-busy')).toBe('true');
|
||||||
|
expect(button.disabled).toBe(true);
|
||||||
|
// Verify text is present (opacity: 0 doesn't remove from DOM)
|
||||||
|
expect(screen.getByText('Submit')).toBeTruthy();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -32,6 +32,19 @@ describe('Input', () => {
|
|||||||
expect(input.getAttribute('aria-invalid')).toBe('false');
|
expect(input.getAttribute('aria-invalid')).toBe('false');
|
||||||
expect(input.hasAttribute('aria-describedby')).toBe(false);
|
expect(input.hasAttribute('aria-describedby')).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('renders required asterisk when required prop is passed', () => {
|
||||||
|
render(<Input label="Required Input" required />);
|
||||||
|
|
||||||
|
// We search for the asterisk specifically
|
||||||
|
// Note: getByText('*') matches the content of the span
|
||||||
|
const asterisk = screen.getByText('*');
|
||||||
|
expect(asterisk).toBeTruthy();
|
||||||
|
expect(asterisk.getAttribute('aria-hidden')).toBe('true');
|
||||||
|
|
||||||
|
const input = screen.getByRole('textbox', { name: /Required Input/i });
|
||||||
|
expect(input.hasAttribute('required')).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Textarea', () => {
|
describe('Textarea', () => {
|
||||||
@@ -49,4 +62,15 @@ describe('Textarea', () => {
|
|||||||
expect(error.id).toBeDefined();
|
expect(error.id).toBeDefined();
|
||||||
expect(error.id).not.toBe('');
|
expect(error.id).not.toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('renders required asterisk when required prop is passed', () => {
|
||||||
|
render(<Textarea label="Required Textarea" required />);
|
||||||
|
|
||||||
|
const asterisk = screen.getByText('*');
|
||||||
|
expect(asterisk).toBeTruthy();
|
||||||
|
expect(asterisk.getAttribute('aria-hidden')).toBe('true');
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox', { name: /Required Textarea/i });
|
||||||
|
expect(textarea.hasAttribute('required')).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
export { useTypingEffect } from './useTypingEffect';
|
export { useTypingEffect } from './useTypingEffect';
|
||||||
|
export { useRateLimit } from './useRateLimit';
|
||||||
|
|||||||
64
src/hooks/useRateLimit.test.ts
Normal file
64
src/hooks/useRateLimit.test.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { renderHook, act } from '@testing-library/react';
|
||||||
|
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
||||||
|
import { useRateLimit } from './useRateLimit';
|
||||||
|
|
||||||
|
describe('useRateLimit', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
vi.useFakeTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should allow first attempt', () => {
|
||||||
|
const { result } = renderHook(() => useRateLimit('test-key', 1000));
|
||||||
|
|
||||||
|
let allowed: boolean = false;
|
||||||
|
act(() => {
|
||||||
|
allowed = result.current.checkRateLimit();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(allowed).toBe(true);
|
||||||
|
expect(result.current.remainingTime).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should block immediate second attempt', () => {
|
||||||
|
const { result } = renderHook(() => useRateLimit('test-key', 1000));
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.checkRateLimit();
|
||||||
|
});
|
||||||
|
|
||||||
|
let allowed: boolean = true;
|
||||||
|
act(() => {
|
||||||
|
allowed = result.current.checkRateLimit();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(allowed).toBe(false);
|
||||||
|
expect(result.current.remainingTime).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should allow attempt after cooldown', () => {
|
||||||
|
const { result } = renderHook(() => useRateLimit('test-key', 1000));
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.checkRateLimit();
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
vi.advanceTimersByTime(1100);
|
||||||
|
});
|
||||||
|
|
||||||
|
let allowed: boolean = false;
|
||||||
|
act(() => {
|
||||||
|
allowed = result.current.checkRateLimit();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(allowed).toBe(true);
|
||||||
|
expect(result.current.remainingTime).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
38
src/hooks/useRateLimit.ts
Normal file
38
src/hooks/useRateLimit.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
|
||||||
|
interface UseRateLimitReturn {
|
||||||
|
checkRateLimit: () => boolean;
|
||||||
|
remainingTime: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRateLimit(key: string, cooldownMs: number): UseRateLimitReturn {
|
||||||
|
const [remainingTime, setRemainingTime] = useState(0);
|
||||||
|
|
||||||
|
const checkRateLimit = useCallback(() => {
|
||||||
|
try {
|
||||||
|
const now = Date.now();
|
||||||
|
const lastAttempt = localStorage.getItem(key);
|
||||||
|
|
||||||
|
if (lastAttempt) {
|
||||||
|
const lastTime = parseInt(lastAttempt, 10);
|
||||||
|
const timePassed = now - lastTime;
|
||||||
|
|
||||||
|
if (timePassed < cooldownMs) {
|
||||||
|
const remaining = Math.ceil((cooldownMs - timePassed) / 1000);
|
||||||
|
setRemainingTime(remaining);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
localStorage.setItem(key, now.toString());
|
||||||
|
setRemainingTime(0);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('LocalStorage not available:', error);
|
||||||
|
// Fail safe: allow action if storage fails
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}, [key, cooldownMs]);
|
||||||
|
|
||||||
|
return { checkRateLimit, remainingTime };
|
||||||
|
}
|
||||||
@@ -96,6 +96,7 @@ export const de = {
|
|||||||
sending: 'Wird gesendet...',
|
sending: 'Wird gesendet...',
|
||||||
success: 'Nachricht erfolgreich gesendet! Ich melde mich bald bei Ihnen.',
|
success: 'Nachricht erfolgreich gesendet! Ich melde mich bald bei Ihnen.',
|
||||||
error: 'Fehler beim Senden. Bitte versuchen Sie es erneut oder kontaktieren Sie mich direkt.',
|
error: 'Fehler beim Senden. Bitte versuchen Sie es erneut oder kontaktieren Sie mich direkt.',
|
||||||
|
rateLimit: 'Zu viele Anfragen. Bitte warten Sie einen Moment.',
|
||||||
},
|
},
|
||||||
info: {
|
info: {
|
||||||
title: 'Kontaktdaten',
|
title: 'Kontaktdaten',
|
||||||
|
|||||||
@@ -98,6 +98,7 @@ export const en: Translations = {
|
|||||||
sending: 'Sending...',
|
sending: 'Sending...',
|
||||||
success: 'Message sent successfully! I\'ll get back to you soon.',
|
success: 'Message sent successfully! I\'ll get back to you soon.',
|
||||||
error: 'Error sending message. Please try again or contact me directly.',
|
error: 'Error sending message. Please try again or contact me directly.',
|
||||||
|
rateLimit: 'Too many requests. Please wait a moment.',
|
||||||
},
|
},
|
||||||
info: {
|
info: {
|
||||||
title: 'Contact Info',
|
title: 'Contact Info',
|
||||||
|
|||||||
@@ -2,12 +2,14 @@ import { useState, type FormEvent } from "react";
|
|||||||
import { motion } from "motion/react";
|
import { motion } from "motion/react";
|
||||||
import emailjs from "@emailjs/browser";
|
import emailjs from "@emailjs/browser";
|
||||||
import { useTranslation } from "../i18n";
|
import { useTranslation } from "../i18n";
|
||||||
|
import { useRateLimit } from "../hooks";
|
||||||
import { config } from "../config";
|
import { config } from "../config";
|
||||||
import { Button, Input, Textarea } from "../components/ui";
|
import { Button, Input, Textarea } from "../components/ui";
|
||||||
import { sanitizeInput } from "../utils/security";
|
import { sanitizeInput, isValidEmail } from "../utils/security";
|
||||||
import styles from "./Contact.module.css";
|
import styles from "./Contact.module.css";
|
||||||
|
|
||||||
const NAME_MAX_LENGTH = 100;
|
const NAME_MAX_LENGTH = 100;
|
||||||
|
const EMAIL_MAX_LENGTH = 254;
|
||||||
const SUBJECT_MAX_LENGTH = 200;
|
const SUBJECT_MAX_LENGTH = 200;
|
||||||
const MESSAGE_MAX_LENGTH = 5000;
|
const MESSAGE_MAX_LENGTH = 5000;
|
||||||
|
|
||||||
@@ -38,6 +40,8 @@ export function Contact() {
|
|||||||
const [submitStatus, setSubmitStatus] = useState<
|
const [submitStatus, setSubmitStatus] = useState<
|
||||||
"idle" | "success" | "error"
|
"idle" | "success" | "error"
|
||||||
>("idle");
|
>("idle");
|
||||||
|
const [rateLimitError, setRateLimitError] = useState(false);
|
||||||
|
const { checkRateLimit } = useRateLimit("contact-form", 60000); // 1 minute cooldown
|
||||||
|
|
||||||
const validateForm = (): boolean => {
|
const validateForm = (): boolean => {
|
||||||
const newErrors: FormErrors = {};
|
const newErrors: FormErrors = {};
|
||||||
@@ -50,7 +54,9 @@ export function Contact() {
|
|||||||
|
|
||||||
if (!formData.email.trim()) {
|
if (!formData.email.trim()) {
|
||||||
newErrors.email = "Required";
|
newErrors.email = "Required";
|
||||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
|
} else if (formData.email.length > EMAIL_MAX_LENGTH) {
|
||||||
|
newErrors.email = `Max ${EMAIL_MAX_LENGTH} characters`;
|
||||||
|
} else if (!isValidEmail(formData.email)) {
|
||||||
newErrors.email = "Invalid email";
|
newErrors.email = "Invalid email";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,8 +79,14 @@ export function Contact() {
|
|||||||
const handleSubmit = async (e: FormEvent) => {
|
const handleSubmit = async (e: FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
|
setRateLimitError(false);
|
||||||
if (!validateForm()) return;
|
if (!validateForm()) return;
|
||||||
|
|
||||||
|
if (!checkRateLimit()) {
|
||||||
|
setRateLimitError(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setIsSubmitting(true);
|
setIsSubmitting(true);
|
||||||
setSubmitStatus("idle");
|
setSubmitStatus("idle");
|
||||||
|
|
||||||
@@ -149,39 +161,51 @@ export function Contact() {
|
|||||||
>
|
>
|
||||||
<p className={styles.intro}>{t.contact.intro}</p>
|
<p className={styles.intro}>{t.contact.intro}</p>
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className={styles.form}>
|
<form
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
className={styles.form}
|
||||||
|
noValidate
|
||||||
|
>
|
||||||
<Input
|
<Input
|
||||||
label={t.contact.form.name}
|
label={t.contact.form.name}
|
||||||
|
required
|
||||||
placeholder={t.contact.form.namePlaceholder}
|
placeholder={t.contact.form.namePlaceholder}
|
||||||
value={formData.name}
|
value={formData.name}
|
||||||
onChange={(e) => handleChange("name", e.target.value)}
|
onChange={(e) => handleChange("name", e.target.value)}
|
||||||
error={errors.name}
|
error={errors.name}
|
||||||
|
maxLength={NAME_MAX_LENGTH}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Input
|
<Input
|
||||||
label={t.contact.form.email}
|
label={t.contact.form.email}
|
||||||
type="email"
|
type="email"
|
||||||
|
required
|
||||||
placeholder={t.contact.form.emailPlaceholder}
|
placeholder={t.contact.form.emailPlaceholder}
|
||||||
value={formData.email}
|
value={formData.email}
|
||||||
onChange={(e) => handleChange("email", e.target.value)}
|
onChange={(e) => handleChange("email", e.target.value)}
|
||||||
error={errors.email}
|
error={errors.email}
|
||||||
|
maxLength={EMAIL_MAX_LENGTH}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Input
|
<Input
|
||||||
label={t.contact.form.subject}
|
label={t.contact.form.subject}
|
||||||
|
required
|
||||||
placeholder={t.contact.form.subjectPlaceholder}
|
placeholder={t.contact.form.subjectPlaceholder}
|
||||||
value={formData.subject}
|
value={formData.subject}
|
||||||
onChange={(e) => handleChange("subject", e.target.value)}
|
onChange={(e) => handleChange("subject", e.target.value)}
|
||||||
error={errors.subject}
|
error={errors.subject}
|
||||||
|
maxLength={SUBJECT_MAX_LENGTH}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Textarea
|
<Textarea
|
||||||
label={t.contact.form.message}
|
label={t.contact.form.message}
|
||||||
|
required
|
||||||
placeholder={t.contact.form.messagePlaceholder}
|
placeholder={t.contact.form.messagePlaceholder}
|
||||||
value={formData.message}
|
value={formData.message}
|
||||||
onChange={(e) => handleChange("message", e.target.value)}
|
onChange={(e) => handleChange("message", e.target.value)}
|
||||||
error={errors.message}
|
error={errors.message}
|
||||||
rows={6}
|
rows={6}
|
||||||
|
maxLength={MESSAGE_MAX_LENGTH}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
@@ -201,6 +225,8 @@ export function Contact() {
|
|||||||
className={styles.success}
|
className={styles.success}
|
||||||
initial={{ opacity: 0, y: 10 }}
|
initial={{ opacity: 0, y: 10 }}
|
||||||
animate={{ opacity: 1, y: 0 }}
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
role="alert"
|
||||||
|
aria-live="polite"
|
||||||
>
|
>
|
||||||
{t.contact.form.success}
|
{t.contact.form.success}
|
||||||
</motion.p>
|
</motion.p>
|
||||||
@@ -211,10 +237,24 @@ export function Contact() {
|
|||||||
className={styles.error}
|
className={styles.error}
|
||||||
initial={{ opacity: 0, y: 10 }}
|
initial={{ opacity: 0, y: 10 }}
|
||||||
animate={{ opacity: 1, y: 0 }}
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
role="alert"
|
||||||
|
aria-live="polite"
|
||||||
>
|
>
|
||||||
{t.contact.form.error}
|
{t.contact.form.error}
|
||||||
</motion.p>
|
</motion.p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{rateLimitError && (
|
||||||
|
<motion.p
|
||||||
|
className={styles.error}
|
||||||
|
initial={{ opacity: 0, y: 10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
role="alert"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
{t.contact.form.rateLimit}
|
||||||
|
</motion.p>
|
||||||
|
)}
|
||||||
</form>
|
</form>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
@@ -235,6 +275,7 @@ export function Contact() {
|
|||||||
fill="none"
|
fill="none"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
strokeWidth="2"
|
strokeWidth="2"
|
||||||
|
aria-hidden="true"
|
||||||
>
|
>
|
||||||
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
|
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
|
||||||
<polyline points="22,6 12,13 2,6" />
|
<polyline points="22,6 12,13 2,6" />
|
||||||
@@ -250,7 +291,7 @@ export function Contact() {
|
|||||||
|
|
||||||
<div className={styles.infoItem}>
|
<div className={styles.infoItem}>
|
||||||
<div className={styles.infoIcon}>
|
<div className={styles.infoIcon}>
|
||||||
<svg viewBox="0 0 24 24" fill="currentColor">
|
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||||
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
|
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ describe('Contact Page', () => {
|
|||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
cleanup();
|
cleanup();
|
||||||
document.body.innerHTML = '';
|
document.body.innerHTML = '';
|
||||||
|
localStorage.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('submits the form with correct parameters', async () => {
|
it('submits the form with correct parameters', async () => {
|
||||||
@@ -115,6 +116,8 @@ describe('Contact Page', () => {
|
|||||||
// Verify success message
|
// Verify success message
|
||||||
const successMessage = await screen.findByText('Message sent successfully!');
|
const successMessage = await screen.findByText('Message sent successfully!');
|
||||||
expect(successMessage).toBeTruthy();
|
expect(successMessage).toBeTruthy();
|
||||||
|
expect(successMessage.getAttribute('role')).toBe('alert');
|
||||||
|
expect(successMessage.getAttribute('aria-live')).toBe('polite');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sanitizes input before sending', async () => {
|
it('sanitizes input before sending', async () => {
|
||||||
@@ -170,4 +173,54 @@ describe('Contact Page', () => {
|
|||||||
// EmailJS should NOT be called
|
// EmailJS should NOT be called
|
||||||
expect(emailjs.send).not.toHaveBeenCalled();
|
expect(emailjs.send).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows error when email contains invalid characters', async () => {
|
||||||
|
const { container } = render(<Contact />);
|
||||||
|
|
||||||
|
// Fill out the form with invalid email (XSS vector)
|
||||||
|
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'John Doe' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Email'), { target: { value: '<script>@example.com' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Subject'), { target: { value: 'Test Subject' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Hello world' } });
|
||||||
|
|
||||||
|
// Submit via form submit event to bypass browser validation (jsdom/browser would block this otherwise)
|
||||||
|
// This ensures our application-level validation logic (isValidEmail) is tested
|
||||||
|
const form = container.querySelector('form');
|
||||||
|
if (form) fireEvent.submit(form);
|
||||||
|
|
||||||
|
// Validation error should appear
|
||||||
|
const errorMessage = await screen.findByText('Invalid email');
|
||||||
|
expect(errorMessage).toBeTruthy();
|
||||||
|
|
||||||
|
// EmailJS should NOT be called
|
||||||
|
expect(emailjs.send).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows error message with alert role when submission fails', async () => {
|
||||||
|
// Mock failure
|
||||||
|
const sendMock = vi.mocked(emailjs.send);
|
||||||
|
sendMock.mockRejectedValueOnce(new Error('Network error'));
|
||||||
|
|
||||||
|
render(<Contact />);
|
||||||
|
|
||||||
|
// Fill out the form
|
||||||
|
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'John Doe' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'john@example.com' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Subject'), { target: { value: 'Test Subject' } });
|
||||||
|
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Hello world' } });
|
||||||
|
|
||||||
|
// Submit
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Send Message' }));
|
||||||
|
|
||||||
|
// Wait for submission attempt
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(emailjs.send).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Verify error message
|
||||||
|
const errorMessage = await screen.findByText('Failed to send message.');
|
||||||
|
expect(errorMessage).toBeTruthy();
|
||||||
|
expect(errorMessage.getAttribute('role')).toBe('alert');
|
||||||
|
expect(errorMessage.getAttribute('aria-live')).toBe('polite');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
56
src/utils/security.test.ts
Normal file
56
src/utils/security.test.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
|
||||||
|
// @vitest-environment jsdom
|
||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { sanitizeInput, isValidEmail } from './security';
|
||||||
|
|
||||||
|
describe('Security Utils', () => {
|
||||||
|
describe('sanitizeInput', () => {
|
||||||
|
it('escapes special HTML characters', () => {
|
||||||
|
expect(sanitizeInput('<script>')).toBe('<script>');
|
||||||
|
expect(sanitizeInput('foo & bar')).toBe('foo & bar');
|
||||||
|
expect(sanitizeInput('"quotes"')).toBe('"quotes"');
|
||||||
|
expect(sanitizeInput("'single quotes'")).toBe(''single quotes'');
|
||||||
|
expect(sanitizeInput('>')).toBe('>');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns non-string input as is', () => {
|
||||||
|
// @ts-ignore
|
||||||
|
expect(sanitizeInput(123)).toBe(123);
|
||||||
|
// @ts-ignore
|
||||||
|
expect(sanitizeInput(null)).toBe(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles mixed content correctly', () => {
|
||||||
|
const input = '<script>alert("XSS")</script>';
|
||||||
|
const expected = '<script>alert("XSS")</script>';
|
||||||
|
expect(sanitizeInput(input)).toBe(expected);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isValidEmail', () => {
|
||||||
|
it('accepts valid email addresses', () => {
|
||||||
|
expect(isValidEmail('test@example.com')).toBe(true);
|
||||||
|
expect(isValidEmail('john.doe@sub.domain.co.uk')).toBe(true);
|
||||||
|
expect(isValidEmail('user+tag@example.com')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects invalid email formats', () => {
|
||||||
|
expect(isValidEmail('plainaddress')).toBe(false);
|
||||||
|
expect(isValidEmail('@example.com')).toBe(false);
|
||||||
|
expect(isValidEmail('user@')).toBe(false);
|
||||||
|
expect(isValidEmail('user@.com')).toBe(false);
|
||||||
|
expect(isValidEmail('user@com')).toBe(false); // Missing dot in domain part (simple regex might allow, but strict one requires dot)
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects emails with dangerous characters (<, >)', () => {
|
||||||
|
expect(isValidEmail('<script>@example.com')).toBe(false);
|
||||||
|
expect(isValidEmail('user@<script>.com')).toBe(false);
|
||||||
|
expect(isValidEmail('user<name>@example.com')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects emails with whitespace', () => {
|
||||||
|
expect(isValidEmail('user @example.com')).toBe(false);
|
||||||
|
expect(isValidEmail('user@ example.com')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -16,3 +16,21 @@ export function sanitizeInput(input: string): string {
|
|||||||
.replace(/"/g, """)
|
.replace(/"/g, """)
|
||||||
.replace(/'/g, "'");
|
.replace(/'/g, "'");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates an email address format securely.
|
||||||
|
* Rejects inputs containing dangerous characters like <, >, or whitespace.
|
||||||
|
*
|
||||||
|
* @param email - The email string to validate.
|
||||||
|
* @returns True if the email is valid and safe, false otherwise.
|
||||||
|
*/
|
||||||
|
export function isValidEmail(email: string): boolean {
|
||||||
|
// Basic format check + rejection of XSS vectors (<, >)
|
||||||
|
// [^\s@<>]+ : Local part - no whitespace, @, <, or >
|
||||||
|
// @ : Literal @
|
||||||
|
// [^\s@<>]+ : Domain part - no whitespace, @, <, or >
|
||||||
|
// \. : Literal .
|
||||||
|
// [^\s@<>]+ : TLD part - no whitespace, @, <, or >
|
||||||
|
const emailRegex = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
||||||
|
return emailRegex.test(email);
|
||||||
|
}
|
||||||
|
|||||||
BIN
verification.png
Normal file
BIN
verification.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
60
verification/verify_rate_limit.py
Normal file
60
verification/verify_rate_limit.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
from playwright.sync_api import sync_playwright, expect
|
||||||
|
import time
|
||||||
|
|
||||||
|
def verify_rate_limit():
|
||||||
|
with sync_playwright() as p:
|
||||||
|
browser = p.chromium.launch(headless=True)
|
||||||
|
page = browser.new_page()
|
||||||
|
|
||||||
|
print("Navigating to home...")
|
||||||
|
page.goto("http://localhost:3000")
|
||||||
|
|
||||||
|
print("Navigating to Contact...")
|
||||||
|
# Try both English and German just in case
|
||||||
|
try:
|
||||||
|
page.get_by_role("link", name="Contact").click()
|
||||||
|
except:
|
||||||
|
page.get_by_role("link", name="Kontakt").click()
|
||||||
|
|
||||||
|
# Fill form
|
||||||
|
print("Filling form...")
|
||||||
|
# Use placeholders from en.ts
|
||||||
|
page.get_by_placeholder("Your name").fill("Test User")
|
||||||
|
page.get_by_placeholder("your@email.com").fill("test@example.com")
|
||||||
|
page.get_by_placeholder("What is it about?").fill("Test Subject")
|
||||||
|
page.get_by_placeholder("Your message...").fill("Test Message")
|
||||||
|
|
||||||
|
# Submit 1
|
||||||
|
print("Submitting first time...")
|
||||||
|
submit_btn = page.get_by_role("button", name="Send Message")
|
||||||
|
submit_btn.click()
|
||||||
|
|
||||||
|
# Wait for result (likely error due to missing keys/network)
|
||||||
|
# We expect either success or error message
|
||||||
|
print("Waiting for response...")
|
||||||
|
# Allow some time for EmailJS timeout
|
||||||
|
try:
|
||||||
|
expect(page.get_by_text("Error sending message").or_(page.get_by_text("Message sent successfully"))).to_be_visible(timeout=10000)
|
||||||
|
except:
|
||||||
|
print("Timed out waiting for first response, checking if button is enabled...")
|
||||||
|
|
||||||
|
# Ensure button is enabled before clicking again
|
||||||
|
# If it's disabled, we can't click
|
||||||
|
expect(submit_btn).not_to_be_disabled()
|
||||||
|
|
||||||
|
# Submit 2
|
||||||
|
print("Submitting second time...")
|
||||||
|
submit_btn.click()
|
||||||
|
|
||||||
|
# Check for rate limit message
|
||||||
|
print("Checking for rate limit message...")
|
||||||
|
expect(page.get_by_text("Too many requests")).to_be_visible()
|
||||||
|
|
||||||
|
# Screenshot
|
||||||
|
print("Taking screenshot...")
|
||||||
|
page.screenshot(path="verification.png")
|
||||||
|
|
||||||
|
browser.close()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
verify_rate_limit()
|
||||||
Reference in New Issue
Block a user