All files / apps/huella-legal/layers/forms/server/utils turnstile.ts

100% Statements 9/9
100% Branches 6/6
100% Functions 2/2
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30                1x   9x   3x   3x 2x           1x       7x   6x    
import type { H3Event } from "h3";
 
interface Answer {
    success: boolean;
    "error-codes"?: string[];
}
 
/** Throws unless Cloudflare accepts the token: `403` when it refuses, `502` when it can't answer. */
export const assertChallenge = async (event: H3Event, token: string | undefined): Promise<void> => {
    // siteverify answers some refusals with a 400, which `$fetch` throws with the body as `data`
    const answer: Answer = await verifyTurnstileToken(token ?? "", event).catch(
        (cause: unknown) => {
            const answered = (cause as { data?: Partial<Answer> }).data;
 
            if (typeof answered?.success !== "boolean")
                throw createError({
                    statusCode: 502,
                    statusMessage: "Turnstile is unavailable",
                    cause,
                });
 
            return answered as Answer;
        },
    );
 
    if (answer.success) return;
 
    throw createError({ statusCode: 403, statusMessage: "Challenge failed", cause: answer });
};