diff --git a/CLAUDE.md b/CLAUDE.md index 40fe76c2..8075fd51 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ StateOfDev.ma is an annual survey website for developers in Morocco by GeeksBlaB - `/survey/` - YAML question definitions (format: `{position}-{section-name}.yml`) - `/results/{year}/` - Exported results + metadata (results.json, questions.json) -- `/src/actions/` - Astro server actions (init-session, submit-answers, remove-session) +- `/src/actions/` - Astro server actions (init-session, submit-answers) - `/src/lib/firebase/` - Firebase client/server/database operations - `/src/components/survey/` - Survey form components - `/src/components/chart/` - Results visualization diff --git a/README.md b/README.md index b14b2a50..29d35fc4 100644 --- a/README.md +++ b/README.md @@ -56,10 +56,9 @@ FIREBASE_TOKEN_URI= FIREBASE_AUTH_CERT_URL= FIREBASE_CLIENT_CERT_URL= -# captcha keys (optional) make sure to set it to false in dev mode +# captcha: required in prod; set CAPTCHA_ENABLED=false for local dev CAPTCHA_ENABLED=false -CAPTCHA_SITE_KEY= -CAPTCHA_SECRET_KEY= +TURNSTILE_SECRET_KEY= ``` @@ -85,8 +84,8 @@ The survey form submission process is designed to be secure, anonymous, and user - A CAPTCHA is displayed to prevent spam submissions(using Cloudflare Turnstile). - When the user clicks "Start": - An anonymous Firebase authentication session is created. - - The session token and CAPTCHA token are sent to the server (actions/initialize-session.ts). - - The server (actions/initialize-session.ts) validates the Firebase session and the CAPTCHA, initializes the session, and sets a session cookie. + - The session token and CAPTCHA token are sent to the server (actions/init-session.ts). + - The server (actions/init-session.ts) validates the Firebase session and the CAPTCHA, initializes the session, and sets a session cookie. - Upon successful initialization, the user is redirected to the `/survey` page. 2. **Survey Page** diff --git a/docs/architecture.md b/docs/architecture.md index e7909705..c2e2fa42 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -23,7 +23,6 @@ Astro server actions (API endpoints). - `init-session.ts` - Initialize anonymous Firebase session with CAPTCHA validation - `submit-answers.ts` - Validate session and save answers to Firestore -- `remove-session.ts` - Clean up session data - `index.ts` - Exports all actions as `server` object ### `/src/lib/firebase/` @@ -59,7 +58,6 @@ Astro pages (hybrid rendering). - `thanks.astro` - Post-survey thank you page with social sharing - `{year}.astro` - Results pages for each survey year - `playground.astro` - Interactive data exploration with filters -- `/api/` - API endpoints ### `/scripts/` Utility scripts. diff --git a/src/actions/index.ts b/src/actions/index.ts index 6956e1a8..ee6af9de 100644 --- a/src/actions/index.ts +++ b/src/actions/index.ts @@ -1,9 +1,7 @@ import { initSession } from "./init-session"; -import { removeSession } from "./remove-session"; import { submitAnswers } from "./submit-answers"; export const server = { initSession, - removeSession, submitAnswers }; diff --git a/src/actions/init-session.ts b/src/actions/init-session.ts index ca7eb56d..58656505 100644 --- a/src/actions/init-session.ts +++ b/src/actions/init-session.ts @@ -2,7 +2,7 @@ import { ActionError, defineAction } from "astro:actions"; import { z } from "astro:schema"; import { getAuth } from "firebase-admin/auth"; -import { isCaptchaValid } from "@/lib/captcha"; +import { passesCaptcha } from "@/lib/captcha"; import { initUserSubmission } from "@/lib/firebase/database"; import { getActiveApp } from "@/lib/firebase/server"; @@ -14,13 +14,6 @@ export const initSession = defineAction({ }), handler: async ({ idToken, captchaToken }, { cookies }) => { const auth = getAuth(getActiveApp()); - /* Validate inputs */ - if (!captchaToken && import.meta.env.CAPTCHA_ENABLED === "true") { - throw new ActionError({ - code: "UNAUTHORIZED", - message: "Captcha token is required" - }); - } if (!idToken) { throw new ActionError({ code: "UNAUTHORIZED", @@ -28,20 +21,13 @@ export const initSession = defineAction({ }); } - /* Validate captcha */ - if (captchaToken && import.meta.env.CAPTCHA_ENABLED === "true") { - console.log("checking captcha "); - - const isValid = await isCaptchaValid(captchaToken); - if (!isValid) { - throw new ActionError({ - code: "UNAUTHORIZED", - message: "Invalid captcha" - }); - } + if (!(await passesCaptcha(captchaToken))) { + throw new ActionError({ + code: "UNAUTHORIZED", + message: "Invalid captcha" + }); } - /* Verify id token and save user to database */ try { const decodedToken = await auth.verifyIdToken(idToken); const user = await auth.getUser(decodedToken.uid); diff --git a/src/actions/remove-session.ts b/src/actions/remove-session.ts deleted file mode 100644 index ab4ab4a3..00000000 --- a/src/actions/remove-session.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineAction } from "astro:actions"; - -export const removeSession = defineAction({ - accept: "json", - handler: async (_input, { cookies }) => { - cookies.delete("__session", { - path: "/" - }); - - return { - success: true - }; - } -}); diff --git a/src/env.d.ts b/src/env.d.ts index 840d6281..0eb6c035 100644 --- a/src/env.d.ts +++ b/src/env.d.ts @@ -22,11 +22,19 @@ interface ImportMetaEnv { readonly PUBLIC_FIREBASE_APP_ID: string; // captcha - readonly RECAPTCHA_ENABLED: boolean; - readonly RECAPTCHA_SITE_KEY: string; - readonly RECAPTCHA_SECRET_KEY: string; + readonly CAPTCHA_ENABLED: string; + readonly TURNSTILE_SECRET_KEY: string; } interface ImportMeta { readonly env: ImportMetaEnv; } + +// Set by the Cloudflare Turnstile script loaded in before-start.astro +interface Window { + onloadTurnstileCallback?: () => void; + turnstile?: { + render: (container: string, options: Record) => void; + reset: () => void; + }; +} diff --git a/src/lib/captcha.test.ts b/src/lib/captcha.test.ts new file mode 100644 index 00000000..4dae8746 --- /dev/null +++ b/src/lib/captcha.test.ts @@ -0,0 +1,42 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { passesCaptcha } from "./captcha"; + +describe("passesCaptcha", () => { + beforeEach(() => vi.stubEnv("CAPTCHA_ENABLED", "true")); + afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + it("sends secret and token as JSON to Turnstile", async () => { + vi.stubEnv("TURNSTILE_SECRET_KEY", "s3cret"); + const fetchMock = vi.fn().mockResolvedValue({ + json: async () => ({ success: true }) + }); + vi.stubGlobal("fetch", fetchMock); + + expect(await passesCaptcha("tok")).toBe(true); + const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(init.headers).toEqual({ "Content-Type": "application/json" }); + expect(JSON.parse(init.body as string)).toEqual({ secret: "s3cret", response: "tok" }); + }); + + it("fails closed: no token is rejected when CAPTCHA_ENABLED is unset", async () => { + vi.stubEnv("CAPTCHA_ENABLED", undefined); + vi.stubGlobal("fetch", vi.fn()); + expect(await passesCaptcha(undefined)).toBe(false); + expect(fetch).not.toHaveBeenCalled(); + }); + + it("skips the check only when CAPTCHA_ENABLED is \"false\"", async () => { + vi.stubEnv("CAPTCHA_ENABLED", "false"); + expect(await passesCaptcha(undefined)).toBe(true); + }); + + it("returns false when fetch fails", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("down"))); + vi.spyOn(console, "error").mockImplementation(() => {}); + expect(await passesCaptcha("tok")).toBe(false); + }); +}); diff --git a/src/lib/captcha.ts b/src/lib/captcha.ts index e4072bbf..cfc99a4d 100644 --- a/src/lib/captcha.ts +++ b/src/lib/captcha.ts @@ -8,20 +8,27 @@ interface CaptchaResponse { "hostname"?: string; } -export async function isCaptchaValid(token: string): Promise { +// Fail closed: captcha is required unless explicitly disabled +export async function passesCaptcha(token?: string): Promise { + if (import.meta.env.CAPTCHA_ENABLED === "false") + return true; + if (!token) + return false; try { const response = await fetch(CLOUDFLARE_CAPTCHA_URL, { method: "POST", headers: { - "Content-Type": "application/x-www-form-urlencoded" + "Content-Type": "application/json" }, body: JSON.stringify({ - secret: String(import.meta.env.PUBLIC_TURNSTILE_SECRET_KEY ?? ""), + secret: import.meta.env.TURNSTILE_SECRET_KEY ?? "", response: token }) }); const data = await response.json() as CaptchaResponse; + if (!data.success) + console.error("Captcha rejected:", data["error-codes"]); return data.success ?? false; } catch (error) { diff --git a/src/pages/api/init-session.ts b/src/pages/api/init-session.ts deleted file mode 100644 index 521ee048..00000000 --- a/src/pages/api/init-session.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { APIRoute } from "astro"; -import { getAuth } from "firebase-admin/auth"; -import { getActiveApp } from "@/lib/firebase/server"; -// TODO: check if we really need this -export const prerender = false; - -export const GET: APIRoute = async ({ request, cookies, redirect }) => { - const auth = getAuth(getActiveApp()); - - /* Get token from request headers */ - const idToken = request.headers.get("Authorization")?.split("Bearer ")[1]; - if (!idToken) { - return new Response("No token found", { status: 401 }); - } - - /* Verify id token */ - try { - await auth.verifyIdToken(idToken); - } - catch { - return new Response("Invalid token", { status: 401 }); - } - - /* Create and set session cookie */ - const fiveDays = 60 * 60 * 24 * 5 * 1000; - const sessionCookie = await auth.createSessionCookie(idToken, { - expiresIn: fiveDays - }); - - cookies.set("__session", sessionCookie, { - path: "/" - }); - - return redirect("/survey"); -}; diff --git a/src/pages/api/remove-session.ts b/src/pages/api/remove-session.ts deleted file mode 100644 index 5f7d6bdd..00000000 --- a/src/pages/api/remove-session.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { APIRoute } from "astro"; - -export const prerender = false; - -export const GET: APIRoute = async ({ redirect, cookies }) => { - cookies.delete("__session", { - path: "/" - }); - return redirect("/before-start"); -}; diff --git a/src/pages/before-start.astro b/src/pages/before-start.astro index 304f75f4..290365b3 100644 --- a/src/pages/before-start.astro +++ b/src/pages/before-start.astro @@ -84,10 +84,8 @@ const errorMessage = document.querySelector( "#error-message" ) as HTMLParagraphElement; let captchaToken = ""; -// @ts-expect-error - Turnstile callback is added to window dynamically window.onloadTurnstileCallback = function () { - // @ts-expect-error - Turnstile is added to window dynamically by Cloudflare script - window.turnstile.render("#captcha-container", { + window.turnstile?.render("#captcha-container", { sitekey: "0x4AAAAAAAkS5usDr1HhE7Gm", callback(token: string) { console.log(`Challenge Success ${token}`); @@ -103,6 +101,9 @@ function handleError() { startButton.innerHTML = "Start Survey"; startButton.disabled = false; startButton.classList.remove("opacity-50", "cursor-not-allowed"); + // Turnstile tokens are single-use; get a fresh one for the retry + captchaToken = ""; + window.turnstile?.reset(); } startButton.addEventListener("click", async () => {