From b12c1c3a82941f2767ade8f497db56933415b94d Mon Sep 17 00:00:00 2001 From: Mohamed Bassem Date: Sun, 30 Nov 2025 00:01:07 +0000 Subject: feat: add support for turnstile on signup --- packages/shared/config.ts | 22 +++++++++++++ packages/shared/types/users.ts | 1 + packages/trpc/lib/turnstile.ts | 71 ++++++++++++++++++++++++++++++++++++++++++ packages/trpc/routers/users.ts | 13 ++++++++ 4 files changed, 107 insertions(+) create mode 100644 packages/trpc/lib/turnstile.ts (limited to 'packages') diff --git a/packages/shared/config.ts b/packages/shared/config.ts index 634f083b..60beae1e 100644 --- a/packages/shared/config.ts +++ b/packages/shared/config.ts @@ -54,6 +54,8 @@ const allEnv = z.object({ OAUTH_TIMEOUT: z.coerce.number().optional().default(3500), OAUTH_SCOPE: z.string().default("openid email profile"), OAUTH_PROVIDER_NAME: z.string().default("Custom Provider"), + TURNSTILE_SITE_KEY: z.string().optional(), + TURNSTILE_SECRET_KEY: z.string().optional(), OPENAI_API_KEY: z.string().optional(), OPENAI_BASE_URL: z.string().url().optional(), OLLAMA_BASE_URL: z.string().url().optional(), @@ -237,6 +239,11 @@ const serverConfigSchema = allEnv.transform((val, ctx) => { name: val.OAUTH_PROVIDER_NAME, timeout: val.OAUTH_TIMEOUT, }, + turnstile: { + enabled: val.TURNSTILE_SITE_KEY !== undefined, + siteKey: val.TURNSTILE_SITE_KEY, + secretKey: val.TURNSTILE_SECRET_KEY, + }, }, email: { smtp: val.SMTP_HOST @@ -401,6 +408,15 @@ const serverConfigSchema = allEnv.transform((val, ctx) => { }); return z.NEVER; } + if (obj.auth.turnstile.enabled && !obj.auth.turnstile.secretKey) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: + "TURNSTILE_SECRET_KEY is required when TURNSTILE_SITE_KEY is set", + fatal: true, + }); + return z.NEVER; + } return obj; }); @@ -416,6 +432,12 @@ export const clientConfig = { disableSignups: serverConfig.auth.disableSignups, disablePasswordAuth: serverConfig.auth.disablePasswordAuth, }, + turnstile: + serverConfig.auth.turnstile.enabled && serverConfig.auth.turnstile.siteKey + ? { + siteKey: serverConfig.auth.turnstile.siteKey, + } + : null, inference: { isConfigured: serverConfig.inference.isConfigured, inferredTagLang: serverConfig.inference.inferredTagLang, diff --git a/packages/shared/types/users.ts b/packages/shared/types/users.ts index 2fad4f83..9f020d52 100644 --- a/packages/shared/types/users.ts +++ b/packages/shared/types/users.ts @@ -11,6 +11,7 @@ export const zSignUpSchema = z email: z.string().email(), password: z.string().min(PASSWORD_MIN_LENGTH).max(PASSWORD_MAX_LENGTH), confirmPassword: z.string(), + turnstileToken: z.string().optional(), }) .refine((data) => data.password === data.confirmPassword, { message: "Passwords don't match", diff --git a/packages/trpc/lib/turnstile.ts b/packages/trpc/lib/turnstile.ts new file mode 100644 index 00000000..3ba25f05 --- /dev/null +++ b/packages/trpc/lib/turnstile.ts @@ -0,0 +1,71 @@ +import { z } from "zod"; + +import serverConfig from "@karakeep/shared/config"; +import logger from "@karakeep/shared/logger"; + +const TurnstileVerifyResponseSchema = z.object({ + success: z.boolean(), + challenge_ts: z.string().optional(), + hostname: z.string().optional(), + "error-codes": z.array(z.string()).optional(), +}); + +export async function verifyTurnstileToken( + token: string, + remoteIp?: string | null, +) { + if (!serverConfig.auth.turnstile.enabled) { + return { success: true }; + } + + if (!token) { + return { success: false, "error-codes": ["missing-input-response"] }; + } + + const body = new URLSearchParams(); + body.append("secret", serverConfig.auth.turnstile.secretKey!); + body.append("response", token); + if (remoteIp) { + body.append("remoteip", remoteIp); + } + + try { + const response = await fetch( + "https://challenges.cloudflare.com/turnstile/v0/siteverify", + { + method: "POST", + body, + }, + ); + + if (!response.ok) { + logger.warn( + `[Turnstile] Verification request failed with status ${response.status}`, + ); + return { success: false, "error-codes": ["request-not-ok"] }; + } + + const json = await response.json(); + const parseResult = TurnstileVerifyResponseSchema.safeParse(json); + + if (!parseResult.success) { + logger.warn("[Turnstile] Invalid response format", { + error: parseResult.error, + remoteIp, + }); + return { success: false, "error-codes": ["invalid-response"] }; + } + + const parsed = parseResult.data; + if (!parsed.success) { + logger.warn("[Turnstile] Verification failed", { + errorCodes: parsed["error-codes"], + remoteIp, + }); + } + return parsed; + } catch (error) { + logger.warn("[Turnstile] Verification threw", { error, remoteIp }); + return { success: false, "error-codes": ["internal-error"] }; + } +} diff --git a/packages/trpc/routers/users.ts b/packages/trpc/routers/users.ts index 5ce9c67e..d3bc06d9 100644 --- a/packages/trpc/routers/users.ts +++ b/packages/trpc/routers/users.ts @@ -18,6 +18,7 @@ import { publicProcedure, router, } from "../index"; +import { verifyTurnstileToken } from "../lib/turnstile"; import { User } from "../models/users"; export const usersAppRouter = router({ @@ -51,6 +52,18 @@ export const usersAppRouter = router({ message: errorMessage, }); } + if (serverConfig.auth.turnstile.enabled) { + const result = await verifyTurnstileToken( + input.turnstileToken ?? "", + ctx.req.ip, + ); + if (!result.success) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Turnstile verification failed", + }); + } + } const user = await User.create(ctx, input); return { id: user.id, -- cgit v1.2.3-70-g09d2