Files
WRNexusJS/packages/captcha/src/normalize.ts
2026-07-27 12:42:18 +05:30

29 lines
998 B
TypeScript

import type { CaptchaChallengeRecord, VerifyCaptchaInput } from "./types.ts";
export function normalizeTextAnswer(value: unknown, caseSensitive: boolean): string {
const normalized = String(value ?? "")
.normalize("NFKC")
.trim()
.replace(/\s+/g, " ");
return caseSensitive ? normalized : normalized.toUpperCase();
}
export function normalizeSelections(values: unknown): string {
if (!Array.isArray(values)) return "";
return [...new Set(values.map((value) => String(value).trim()).filter(Boolean))].sort().join(",");
}
export function normalizedSubmittedAnswer(
record: CaptchaChallengeRecord,
input: VerifyCaptchaInput,
): string {
if (record.answerKind === "selections") return normalizeSelections(input.selections);
if (record.answerKind === "invisible") {
return JSON.stringify({
honeypot: String(input.honeypot ?? ""),
timingToken: String(input.timingToken ?? ""),
});
}
return normalizeTextAnswer(input.answer, record.caseSensitive);
}