All checks were successful
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
55 lines
2.9 KiB
TypeScript
55 lines
2.9 KiB
TypeScript
/** Обращение с сайта: проверка полей и защита от спама. Без капчи: скрытое поле-ловушка, минимальное время заполнения, ограничение частоты. */
|
||
|
||
export const FALLBACK_EMAIL = 'qazaqlegacy@gmail.com'
|
||
|
||
export type InquiryInput = { name?: unknown; email?: unknown; organization?: unknown; message?: unknown; consent?: unknown; website?: unknown; openedAt?: unknown }
|
||
export type InquiryField = 'name' | 'email' | 'message' | 'consent'
|
||
export type InquiryError = InquiryField | 'tooLong' | 'tooMany' | 'failed'
|
||
export type Inquiry = { name: string; email: string; organization: string; message: string }
|
||
|
||
export const LIMITS = { name: 120, email: 200, organization: 200, message: 5000 }
|
||
const MIN_FILL_MS = 2500
|
||
const MAX_PER_WINDOW = 3
|
||
const WINDOW_MS = 10 * 60 * 1000
|
||
|
||
const str = (v: unknown) => (typeof v === 'string' ? v.trim() : '')
|
||
const EMAIL_RE = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]{2,}$/
|
||
|
||
export type Validation =
|
||
| { ok: true; data: Inquiry }
|
||
| { ok: false; spam: true }
|
||
| { ok: false; spam?: false; errors: InquiryError[] }
|
||
|
||
/** Спам (ловушка заполнена или форма отправлена мгновенно) — тихо «принимаем» и выбрасываем, не подсказывая боту. */
|
||
export function validateInquiry(input: InquiryInput, now = Date.now()): Validation {
|
||
if (str(input.website)) return { ok: false, spam: true }
|
||
const opened = Number(input.openedAt)
|
||
if (Number.isFinite(opened) && opened > 0 && now - opened < MIN_FILL_MS) return { ok: false, spam: true }
|
||
|
||
const data: Inquiry = { name: str(input.name), email: str(input.email), organization: str(input.organization), message: str(input.message) }
|
||
const errors: InquiryError[] = []
|
||
if (!data.name) errors.push('name')
|
||
if (!EMAIL_RE.test(data.email)) errors.push('email')
|
||
if (!data.message) errors.push('message')
|
||
if (input.consent !== 'on' && input.consent !== true && input.consent !== 'true') errors.push('consent')
|
||
if ((Object.keys(LIMITS) as (keyof Inquiry)[]).some((k) => data[k].length > LIMITS[k])) errors.push('tooLong')
|
||
return errors.length ? { ok: false, errors } : { ok: true, data }
|
||
}
|
||
|
||
const hits = new Map<string, number[]>()
|
||
|
||
/** Не больше 3 обращений с одного адреса за 10 минут. Память процесса: для защиты от потока мусора достаточно. */
|
||
export function rateLimited(key: string, now = Date.now()): boolean {
|
||
const recent = (hits.get(key) ?? []).filter((t) => now - t < WINDOW_MS)
|
||
if (recent.length >= MAX_PER_WINDOW) {
|
||
hits.set(key, recent)
|
||
return true
|
||
}
|
||
recent.push(now)
|
||
hits.set(key, recent)
|
||
if (hits.size > 5000) for (const [k, v] of hits) if (v.every((t) => now - t >= WINDOW_MS)) hits.delete(k)
|
||
return false
|
||
}
|
||
|
||
export const resetRateLimit = () => hits.clear()
|