captcha: refactor canvas size globals

This commit is contained in:
Alex Gleason 2024-10-04 15:56:32 -05:00
parent 6d09f69e26
commit c81005a050
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7

View file

@ -18,14 +18,17 @@ interface Dimensions {
const captchas = new TTLCache<string, Point>(); const captchas = new TTLCache<string, Point>();
const BG_SIZE = { w: 370, h: 400 };
const PUZZLE_SIZE = { w: 65, h: 65 };
/** Puzzle captcha controller. */ /** Puzzle captcha controller. */
export const captchaController: AppController = async (c) => { export const captchaController: AppController = async (c) => {
const { bg, puzzle, solution } = await generateCaptcha( const { bg, puzzle, solution } = await generateCaptcha(
await Deno.readFile(new URL('../../assets/captcha/bg/tj-holowaychuk.jpg', import.meta.url)), await Deno.readFile(new URL('../../assets/captcha/bg/tj-holowaychuk.jpg', import.meta.url)),
await Deno.readFile(new URL('../../assets/captcha/puzzle-mask.png', import.meta.url)), await Deno.readFile(new URL('../../assets/captcha/puzzle-mask.png', import.meta.url)),
await Deno.readFile(new URL('../../assets/captcha/puzzle-hole.png', import.meta.url)), await Deno.readFile(new URL('../../assets/captcha/puzzle-hole.png', import.meta.url)),
{ w: 370, h: 400 }, BG_SIZE,
{ w: 65, h: 65 }, PUZZLE_SIZE,
); );
const id = crypto.randomUUID(); const id = crypto.randomUUID();
@ -110,15 +113,9 @@ export const captchaVerifyController: AppController = async (c) => {
return c.json({ error: 'Captcha expired' }, { status: 410 }); return c.json({ error: 'Captcha expired' }, { status: 410 });
} }
const dim = { w: 65, h: 65 }; const solved = verifySolution(PUZZLE_SIZE, result.data, solution);
const point = result.data;
const success = areIntersecting( if (solved) {
{ ...point, ...dim },
{ ...solution, ...dim },
);
if (success) {
captchas.delete(id); captchas.delete(id);
await createAdminEvent({ await createAdminEvent({
@ -136,6 +133,13 @@ export const captchaVerifyController: AppController = async (c) => {
return c.json({ error: 'Incorrect solution' }, { status: 400 }); return c.json({ error: 'Incorrect solution' }, { status: 400 });
}; };
function verifySolution(puzzleSize: Dimensions, point: Point, solution: Point): boolean {
return areIntersecting(
{ ...point, ...puzzleSize },
{ ...solution, ...puzzleSize },
);
}
type Rectangle = Point & Dimensions; type Rectangle = Point & Dimensions;
function areIntersecting(rect1: Rectangle, rect2: Rectangle, threshold = 0.5) { function areIntersecting(rect1: Rectangle, rect2: Rectangle, threshold = 0.5) {