Security patch for contact

This commit is contained in:
2026-10-09 18:00:24 +02:00
parent 2dfacb0414
commit d034ddf990
24 changed files with 437 additions and 5 deletions
+2
View File
@@ -4,5 +4,7 @@ export type { RateLimitArgs } from './rateLimit.js';
export { submitForm } from './submitForm.js';
export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js';
export { useContactForm } from './useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js';
export { validateSubmission } from './validateSubmission.js';
export type { FormValidationResult } from './validateSubmission.js';
+1
View File
@@ -3,6 +3,7 @@
export { buildFormsPlugin } from './formsPluginConfig.js';
export { checkRateLimit } from './rateLimit.js';
export { submitForm } from './submitForm.js';
export { useContactForm } from './useContactForm.js';
export { validateSubmission } from './validateSubmission.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,kBAAkB,QAAQ,0BAAyB"}
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,SAASC,kBAAkB,QAAQ,0BAAyB"}
+64
View File
@@ -0,0 +1,64 @@
import type { SubmitFormResult } from './submitForm.js';
/** Field values the form tracks. Projects add/remove keys freely. */
export type ContactFormValues = {
consent: boolean;
email: string;
message: string;
name: string;
phone: string;
topic: string;
};
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, boolean>>;
/**
* The project's server action that calls submitForm (server-only, holds the
* Turnstile secret). The hook is a client hook, so it can't call submitForm
* directly — the project injects its action.
*/
export type SubmitAction = (values: ContactFormValues, turnstileToken?: string) => Promise<{
message?: string;
success: boolean;
} | SubmitFormResult>;
type UseContactFormOptions = {
/** Generic error message shown when the action throws. */
errorFallback?: string;
initialTopic?: string;
/** Minimum message length. Default 10. */
minMessageLength?: number;
/** Whether consent is required (project passes true when consentText shown). */
requireConsent?: boolean;
/** Whether a topic must be chosen (project passes this when topics exist). */
requireTopic?: boolean;
/** Require a Turnstile token before submit (when the widget is shown). */
requireTurnstile?: boolean;
submitAction: SubmitAction;
};
/**
* All contact-form logic (state, validation, Turnstile token, submit, success)
* WITHOUT any markup — the project owns 100% of the look. Replaces the ~150
* lines of identical logic copied into every project's ContactForm, while the
* project keeps full control over field layout and styling.
*
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
* // in JSX — your own fields/classes:
* <input value={f.values.name} onChange={(e) => f.setField('name', e.target.value)}
* className={f.errors.name ? 'border-red-500' : '…'} />
* <Turnstile siteKey={siteKey} onToken={f.setTurnstileToken} />
* <form onSubmit={f.handleSubmit}>…</form>
* {f.isSuccess && <YourSuccessPanel onReset={f.reset} />}
*/
export declare function useContactForm(options: UseContactFormOptions): {
errorMessage: string | null;
errors: Partial<Record<keyof ContactFormValues, boolean>>;
handleSubmit: (e: {
preventDefault: () => void;
}) => Promise<void>;
isSubmitting: boolean;
isSuccess: boolean;
reset: () => void;
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
turnstileToken: string | null;
values: ContactFormValues;
};
export {};
+126
View File
@@ -0,0 +1,126 @@
'use client';
import { useCallback, useState } from 'react';
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
const EMPTY = {
name: '',
consent: false,
email: '',
message: '',
phone: '',
topic: ''
};
/**
* All contact-form logic (state, validation, Turnstile token, submit, success)
* WITHOUT any markup — the project owns 100% of the look. Replaces the ~150
* lines of identical logic copied into every project's ContactForm, while the
* project keeps full control over field layout and styling.
*
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
* // in JSX — your own fields/classes:
* <input value={f.values.name} onChange={(e) => f.setField('name', e.target.value)}
* className={f.errors.name ? 'border-red-500' : '…'} />
* <Turnstile siteKey={siteKey} onToken={f.setTurnstileToken} />
* <form onSubmit={f.handleSubmit}>…</form>
* {f.isSuccess && <YourSuccessPanel onReset={f.reset} />}
*/ export function useContactForm(options) {
const { errorFallback = 'Something went wrong. Please try again.', initialTopic = '', minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
const [values, setValues] = useState({
...EMPTY,
topic: initialTopic
});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [errorMessage, setErrorMessage] = useState(null);
const [turnstileToken, setTurnstileToken] = useState(null);
const setField = useCallback((key, value)=>{
setValues((prev)=>({
...prev,
[key]: value
}));
}, []);
const validate = useCallback(()=>{
const errs = {};
if (!values.name.trim()) {
errs.name = true;
}
if (!values.email.trim() || !EMAIL_RE.test(values.email)) {
errs.email = true;
}
if (requireTopic && !values.topic) {
errs.topic = true;
}
if (!values.message.trim() || values.message.length < minMessageLength) {
errs.message = true;
}
if (requireConsent && !values.consent) {
errs.consent = true;
}
setErrors(errs);
return Object.keys(errs).length === 0;
}, [
values,
requireTopic,
requireConsent,
minMessageLength
]);
const handleSubmit = useCallback(async (e)=>{
e.preventDefault();
setErrorMessage(null);
if (!validate()) {
return;
}
if (requireTurnstile && !turnstileToken) {
setErrorMessage(errorFallback);
return;
}
setIsSubmitting(true);
try {
const result = await submitAction(values, turnstileToken ?? undefined);
if (result.success) {
setIsSuccess(true);
setTurnstileToken(null);
} else {
setErrorMessage('message' in result && result.message || errorFallback);
}
} catch (err) {
setErrorMessage(err instanceof Error ? err.message : errorFallback);
} finally{
setIsSubmitting(false);
}
}, [
validate,
requireTurnstile,
turnstileToken,
submitAction,
values,
errorFallback
]);
const reset = useCallback(()=>{
setValues({
...EMPTY,
topic: initialTopic
});
setErrors({});
setIsSuccess(false);
setErrorMessage(null);
setTurnstileToken(null);
}, [
initialTopic
]);
return {
errorMessage,
errors,
handleSubmit,
isSubmitting,
isSuccess,
reset,
setField,
setTurnstileToken,
turnstileToken,
values
};
}
//# sourceMappingURL=useContactForm.js.map
File diff suppressed because one or more lines are too long