Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=

```

Expand All @@ -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**
Expand Down
2 changes: 0 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 0 additions & 2 deletions src/actions/index.ts
Original file line number Diff line number Diff line change
@@ -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
};
26 changes: 6 additions & 20 deletions src/actions/init-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -14,34 +14,20 @@ 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",
message: "No idToken provided"
});
}

/* 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);
Expand Down
14 changes: 0 additions & 14 deletions src/actions/remove-session.ts

This file was deleted.

14 changes: 11 additions & 3 deletions src/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => void;
reset: () => void;
};
}
42 changes: 42 additions & 0 deletions src/lib/captcha.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
13 changes: 10 additions & 3 deletions src/lib/captcha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,27 @@ interface CaptchaResponse {
"hostname"?: string;
}

export async function isCaptchaValid(token: string): Promise<boolean> {
// Fail closed: captcha is required unless explicitly disabled
export async function passesCaptcha(token?: string): Promise<boolean> {
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) {
Expand Down
35 changes: 0 additions & 35 deletions src/pages/api/init-session.ts

This file was deleted.

10 changes: 0 additions & 10 deletions src/pages/api/remove-session.ts

This file was deleted.

7 changes: 4 additions & 3 deletions src/pages/before-start.astro
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand All @@ -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 () => {
Expand Down
Loading