Files
ipal-kit/src/modules/forms/honeypot.ts
T

59 lines
1.9 KiB
TypeScript

/**
* A honeypot: a hidden field real users never see or fill, but naive bots do.
* A cheap, zero-friction second layer alongside Turnstile — no network call, no
* user interaction. Pure functions, usable on client (render the input) and
* server (check it in the action).
*/
/**
* Default field name. Looks like a real field a bot would want to fill, but is
* not one your form uses. Override per project if you like — just keep the
* client and server in sync.
*/
export const HONEYPOT_FIELD = 'company_url'
/**
* Props for the hidden input. Hidden from sight AND from assistive tech and tab
* order, so no real user (sighted, screen-reader, or keyboard) ever fills it —
* only a bot auto-filling every field.
*
* <input {...honeypotInputProps()} />
* // or with your own name:
* <input {...honeypotInputProps('website_2')} />
*/
export function honeypotInputProps(name: string = HONEYPOT_FIELD) {
return {
name,
type: 'text' as const,
'aria-hidden': true,
autoComplete: 'off' as const,
tabIndex: -1,
// Off-screen rather than display:none — some bots skip display:none fields.
style: {
height: '1px',
left: '-9999px',
overflow: 'hidden' as const,
position: 'absolute' as const,
width: '1px',
},
}
}
/**
* True when the honeypot was filled → treat the submission as spam and drop it
* (silently return success so the bot gets no signal). Call it FIRST in your
* server action, before submitForm:
*
* if (isHoneypotTripped(values)) return { success: true } // pretend-accept
* // strip it so submitForm doesn't see an unknown field:
* const { [HONEYPOT_FIELD]: _hp, ...clean } = values
* return submitForm({ ...clean })
*/
export function isHoneypotTripped(
values: Record<string, unknown>,
name: string = HONEYPOT_FIELD,
): boolean {
const v = values[name]
return typeof v === 'string' ? v.trim().length > 0 : v != null
}