⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(auth): cloud abuse-mitigation gates for sign-up and invites
Andrej1d44a33fd9e0
diff --git a/.env.sample b/.env.sampleindex 229ae4c15..e243ff989 100644--- a/.env.sample+++ b/.env.sample@@ -56,3 +56,17 @@ SMTP_USER=SMTP_PASSWORD=SMTP_FROM=SMTP_REQUIRE_TLS=++# Cloud-mode abuse mitigations (only enable on hosted multi-tenant instances).+# When KANEO_CLOUD=true: signup with disposable-email providers is blocked,+# Turnstile is required on /sign-up/email, guest accounts cannot send+# workspace invites, and per-IP rate limits apply to signup + invite paths.+#KANEO_CLOUD=false++# Cloudflare Turnstile (signup captcha). Set the secret key to enforce;+# leave unset to skip verification (self-hosted).+#TURNSTILE_SECRET_KEY=+# Web container: the production image bakes "KANEO_TURNSTILE_SITE_KEY" as a+# placeholder and apps/web/env.sh substitutes it at container start from this+# env var. For local dev (vite), set VITE_TURNSTILE_SITE_KEY in apps/web/.env.+#KANEO_TURNSTILE_SITE_KEY=diff --git a/ENVIRONMENT_SETUP.md b/ENVIRONMENT_SETUP.mdindex c844b1c8b..40dd961e9 100644--- a/ENVIRONMENT_SETUP.md+++ b/ENVIRONMENT_SETUP.md@@ -85,6 +85,15 @@ For sending emails (workspace invitations, magic links, etc.), configure these v> **Note:** If you're using an SMTP server with a self-signed or invalid TLS certificate, set `SMTP_IGNORE_TLS=true` to bypass certificate validation.+#### Cloud-mode abuse mitigations++Hosted multi-tenant instances should enable the cloud abuse gates. Self-hosted instances can leave these unset.++- `KANEO_CLOUD` - Set to `true` to enable cloud-only protections: disposable-email signup block, Turnstile captcha enforcement, guest-account invite block, and tightened rate limits on `/sign-up/email` and `/organization/invite-member`.+- `TURNSTILE_SECRET_KEY` - Cloudflare Turnstile secret key (API container, server-side verification). When unset, captcha verification is skipped.+- `KANEO_TURNSTILE_SITE_KEY` - Cloudflare Turnstile site key, on the **web container**. The production web image bakes the literal placeholder `KANEO_TURNSTILE_SITE_KEY` into the bundle; `apps/web/env.sh` swaps it for the runtime value when the container starts.+- `VITE_TURNSTILE_SITE_KEY` - Local dev only. Set in `apps/web/.env` when running `pnpm dev`; Vite reads this at build/dev time. Not used in the production image.+For a complete list of all environment variables, their descriptions, and configuration options, see the [official documentation](https://kaneo.app/docs/core/installation/environment-variables).## Common Issues & Troubleshootingdiff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex eaa9e584f..218188e67 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -13,7 +13,11 @@ import {import bcrypt from "bcrypt";import { betterAuth } from "better-auth";import { drizzleAdapter } from "better-auth/adapters/drizzle";-import { APIError, createAuthMiddleware } from "better-auth/api";+import {+ APIError,+ createAuthMiddleware,+ getSessionFromCtx,+} from "better-auth/api";import {admin as adminPlugin,anonymous,@@ -33,8 +37,12 @@ import { count, eq, sql } from "drizzle-orm";import db, { schema } from "./database";import { publishEvent } from "./events";import { checkRegistrationAllowed } from "./utils/check-registration-allowed";+import { checkWorkspaceName } from "./utils/check-workspace-name";import { generateDemoName } from "./utils/generate-demo-name";import { getGithubSsoOAuthCredentials } from "./utils/github-sso-env";+import { isCloud } from "./utils/is-cloud";+import { isDisposableEmail } from "./utils/is-disposable-email";+import { verifyTurnstile } from "./utils/verify-turnstile";config();@@ -298,6 +306,12 @@ export const auth = betterAuth({},allowUserToCreateOrganization: true,organizationHooks: {+ beforeCreateOrganization: async ({ organization }) => {+ const check = checkWorkspaceName(organization.name ?? "");+ if (!check.ok) {+ throw new APIError("BAD_REQUEST", { message: check.reason });+ }+ },afterCreateOrganization: async ({ organization, user }) => {// Seed the editable default roles for this workspace. Each// role's permissions are derived from the compiled-in defaults@@ -419,6 +433,18 @@ export const auth = betterAuth({maxAge: 5 * 60,},},+ rateLimit: {+ // Enable in cloud; self-hosted instances opt in by setting KANEO_CLOUD.+ // Default better-auth rate-limit only kicks in for production; we keep the+ // global limits conservative and tighten signup/invite via customRules.+ enabled: isCloud(),+ window: 10,+ max: 100,+ customRules: {+ "/sign-up/email": { window: 60, max: 3 },+ "/organization/invite-member": { window: 60, max: 5 },+ },+ },databaseHooks: {user: {create: {@@ -495,6 +521,34 @@ export const auth = betterAuth({},hooks: {before: createAuthMiddleware(async (ctx) => {+ // Block invite-member calls on cloud from anonymous users or to+ // disposable-email addresses. The 2026-05-28 incident saw ~14k phishing+ // invites sent from throwaway disposable-email signups; gating here+ // shuts that path off without affecting self-hosted instances.+ if (ctx.path === "/organization/invite-member" && isCloud()) {+ // `before` hooks don't auto-populate ctx.context.session; load it+ // explicitly. `disableRefresh` keeps this gate cheap — we only need+ // the user record, not a session refresh side-effect.+ const session = await getSessionFromCtx(ctx, {+ disableRefresh: true,+ }).catch(() => null);+ const sessionUser = session?.user as+ | { isAnonymous?: boolean | null }+ | undefined;+ if (sessionUser?.isAnonymous) {+ throw new APIError("FORBIDDEN", {+ message: "Guest accounts may not send workspace invitations.",+ });+ }+ const inviteeEmail = (ctx.body?.email as string | undefined) ?? "";+ if (inviteeEmail && isDisposableEmail(inviteeEmail)) {+ throw new APIError("BAD_REQUEST", {+ message:+ "Invitations to disposable-email addresses are not allowed.",+ });+ }+ }+const isSignUpPath =ctx.path === "/sign-up/email" ||ctx.path.startsWith("/callback/") ||@@ -517,6 +571,31 @@ export const auth = betterAuth({"Password registration is currently disabled. Please use a configured social or OIDC sign-in method.",});}++ // Cloud-only abuse gates on password signup. Self-hosted instances+ // leave KANEO_CLOUD/TURNSTILE_SECRET_KEY unset and skip both.+ if (isCloud() && !isInstanceAdminSetup) {+ const signupEmail = (ctx.body?.email as string | undefined) ?? "";+ if (signupEmail && isDisposableEmail(signupEmail)) {+ throw new APIError("BAD_REQUEST", {+ message:+ "Sign-up with disposable email addresses is not allowed.",+ });+ }++ const turnstileToken =+ (ctx.body?.turnstileToken as string | undefined) ??+ ctx.headers?.get("x-turnstile-token") ??+ null;+ const remoteIp =+ ctx.headers?.get("cf-connecting-ip") ??+ ctx.headers?.get("x-forwarded-for")?.split(",")[0]?.trim() ??+ null;+ const verdict = await verifyTurnstile(turnstileToken, remoteIp);+ if (!verdict.ok) {+ throw new APIError("FORBIDDEN", { message: verdict.reason });+ }+ }}if (!isRegistrationDisabled || isInstanceAdminSetup) {diff --git a/apps/api/src/utils/check-workspace-name.ts b/apps/api/src/utils/check-workspace-name.tsnew file mode 100644index 000000000..995d59ddc--- /dev/null+++ b/apps/api/src/utils/check-workspace-name.ts@@ -0,0 +1,31 @@+const URL_PATTERN = /\b(https?:\/\/|www\.)\S+/i;+const MAX_NAME_LENGTH = 100;++export type WorkspaceNameCheck = { ok: true } | { ok: false; reason: string };++export function checkWorkspaceName(name: string): WorkspaceNameCheck {+ const trimmed = name?.trim() ?? "";+ if (trimmed.length === 0) {+ return { ok: false, reason: "Workspace name is required." };+ }+ if (trimmed.length > MAX_NAME_LENGTH) {+ return {+ ok: false,+ reason: `Workspace name must be ${MAX_NAME_LENGTH} characters or fewer.`,+ };+ }+ if (URL_PATTERN.test(trimmed)) {+ return {+ ok: false,+ reason: "Workspace name may not contain URLs.",+ };+ }+ // Reject HTML / control characters often used to smuggle payloads.+ if (/[<>{}]/.test(trimmed)) {+ return {+ ok: false,+ reason: "Workspace name may not contain HTML or template characters.",+ };+ }+ return { ok: true };+}diff --git a/apps/api/src/utils/disposable-email-domains.ts b/apps/api/src/utils/disposable-email-domains.tsnew file mode 100644index 000000000..972f17cc0--- /dev/null+++ b/apps/api/src/utils/disposable-email-domains.ts@@ -0,0 +1,43 @@+// Seed list of disposable-email providers observed in the 2026-05-28 phishing+// abuse, plus a few common well-known throwaway services. These match both the+// bare domain and any subdomain (the abuse used random subdomains like+// `dwv.dropmail.me`, `xu.mimimail.me`).+//+// Keep this list lowercased. Add new providers as they show up in incidents;+// don't gold-plate it with every disposable provider in existence — the goal is+// to deter automated abuse, not to be airtight.+export const DISPOSABLE_EMAIL_DOMAINS: readonly string[] = [+ "10mail.info",+ "10mail.org",+ "10mail.xyz",+ "aadl.org",+ "canyougrab.it",+ "dropmail.me",+ "emlhub.com",+ "emlpro.com",+ "emltmp.com",+ "freeml.net",+ "gzeos.com",+ "hush2u.com",+ "mail2me.co",+ "mailpwr.com",+ "mailtowin.com",+ "maximail.vip",+ "mimimail.me",+ "passinbox.com",+ "pickmail.org",+ "pickmemail.com",+ "spymail.one",+ "yomail.info",+ // Common well-known disposable services (defense-in-depth).+ "10minutemail.com",+ "guerrillamail.com",+ "mailinator.com",+ "sharklasers.com",+ "tempmail.com",+ "tempmail.net",+ "temp-mail.org",+ "throwawaymail.com",+ "trashmail.com",+ "yopmail.com",+];diff --git a/apps/api/src/utils/is-cloud.ts b/apps/api/src/utils/is-cloud.tsnew file mode 100644index 000000000..e67afe39b--- /dev/null+++ b/apps/api/src/utils/is-cloud.ts@@ -0,0 +1,3 @@+export function isCloud(): boolean {+ return process.env.KANEO_CLOUD === "true";+}diff --git a/apps/api/src/utils/is-disposable-email.ts b/apps/api/src/utils/is-disposable-email.tsnew file mode 100644index 000000000..a5da1a661--- /dev/null+++ b/apps/api/src/utils/is-disposable-email.ts@@ -0,0 +1,24 @@+import { DISPOSABLE_EMAIL_DOMAINS } from "./disposable-email-domains";++const DOMAIN_SET = new Set(+ DISPOSABLE_EMAIL_DOMAINS.map((d) => d.toLowerCase()),+);++export function isDisposableEmail(email: string): boolean {+ const at = email.lastIndexOf("@");+ if (at < 0 || at === email.length - 1) return false;+ const host = email+ .slice(at + 1)+ .toLowerCase()+ .trim();+ if (!host) return false;++ // Match the host itself, or any parent domain. e.g. `dwv.dropmail.me` and+ // `dropmail.me` both match when `dropmail.me` is in the list.+ const parts = host.split(".");+ for (let i = 0; i < parts.length - 1; i++) {+ const suffix = parts.slice(i).join(".");+ if (DOMAIN_SET.has(suffix)) return true;+ }+ return false;+}diff --git a/apps/api/src/utils/verify-turnstile.ts b/apps/api/src/utils/verify-turnstile.tsnew file mode 100644index 000000000..7fc6e34d0--- /dev/null+++ b/apps/api/src/utils/verify-turnstile.ts@@ -0,0 +1,49 @@+const TURNSTILE_VERIFY_URL =+ "https://challenges.cloudflare.com/turnstile/v0/siteverify";++export type TurnstileResult = { ok: true } | { ok: false; reason: string };++// Verifies a Cloudflare Turnstile token against the siteverify endpoint.+// Returns { ok: true } when the token is valid OR when no secret is configured+// (self-hosted instances opt out by leaving TURNSTILE_SECRET_KEY unset).+export async function verifyTurnstile(+ token: string | null | undefined,+ remoteIp?: string | null,+): Promise<TurnstileResult> {+ const secret = process.env.TURNSTILE_SECRET_KEY;+ if (!secret) {+ return { ok: true };+ }+ if (!token) {+ return { ok: false, reason: "Captcha token missing." };+ }++ const body = new URLSearchParams();+ body.set("secret", secret);+ body.set("response", token);+ if (remoteIp) {+ body.set("remoteip", remoteIp);+ }++ try {+ const res = await fetch(TURNSTILE_VERIFY_URL, {+ method: "POST",+ body,+ });+ const data = (await res.json()) as {+ success?: boolean;+ "error-codes"?: string[];+ };+ if (data.success === true) {+ return { ok: true };+ }+ const errorCodes = data["error-codes"]?.join(",") ?? "unknown";+ return {+ ok: false,+ reason: `Captcha verification failed (${errorCodes}).`,+ };+ } catch (error) {+ console.error("Turnstile verification request failed", error);+ return { ok: false, reason: "Captcha verification failed." };+ }+}diff --git a/apps/web/.env.production b/apps/web/.env.productionindex a33f218e2..5960a372d 100644--- a/apps/web/.env.production+++ b/apps/web/.env.production@@ -1,2 +1,3 @@VITE_API_URL="KANEO_API_URL"-VITE_CLIENT_URL="KANEO_CLIENT_URL"\ No newline at end of file+VITE_CLIENT_URL="KANEO_CLIENT_URL"+VITE_TURNSTILE_SITE_KEY="KANEO_TURNSTILE_SITE_KEY"\ No newline at end of filediff --git a/apps/web/src/components/auth/layout.tsx b/apps/web/src/components/auth/layout.tsxindex f07a67d3d..9600369bc 100644--- a/apps/web/src/components/auth/layout.tsx+++ b/apps/web/src/components/auth/layout.tsx@@ -15,8 +15,8 @@ type AuthLayoutProps = {export function AuthLayout({ children, title, subtitle }: AuthLayoutProps) {return (- <div className="min-h-screen w-full bg-background flex flex-col items-center justify-center px-4 py-6 sm:py-10">- <div className="w-full max-w-sm space-y-4">+ <div className="h-svh w-full overflow-y-auto bg-background flex flex-col items-center px-4 py-6 sm:py-10">+ <div className="w-full max-w-sm space-y-4 my-auto"><Logo className="mx-auto flex w-full items-end justify-center" /><Card>diff --git a/apps/web/src/components/auth/sign-up-form.tsx b/apps/web/src/components/auth/sign-up-form.tsxindex f5783281e..3d2dffc8e 100644--- a/apps/web/src/components/auth/sign-up-form.tsx+++ b/apps/web/src/components/auth/sign-up-form.tsx@@ -27,13 +27,25 @@ export type SignUpFormValues = {type SignUpFormProps = {invitationId?: string;defaultEmail?: string;+ /**+ * Captcha token lifted from the page level. When the page renders Turnstile+ * (cloud only), it passes the verified token here. `null` means captcha is+ * required but not yet completed — the submit button stays disabled.+ * `undefined` means captcha isn't required at all (self-hosted).+ */+ turnstileToken?: string | null;};-export function SignUpForm({ invitationId, defaultEmail }: SignUpFormProps) {+export function SignUpForm({+ invitationId,+ defaultEmail,+ turnstileToken,+}: SignUpFormProps) {const { t } = useTranslation();const [showPassword, setShowPassword] = useState(false);const [isPending, setIsPending] = useState(false);const { history } = useRouter();+ const captchaRequired = turnstileToken !== undefined;const signUpSchema = useMemo(() =>@@ -59,11 +71,16 @@ export function SignUpForm({ invitationId, defaultEmail }: SignUpFormProps) {const onSubmit = async (data: SignUpFormValues) => {setIsPending(true);try {- const result = await authClient.signUp.email({- email: data.email,- name: data.name,- password: data.password,- });+ const result = await authClient.signUp.email(+ {+ email: data.email,+ name: data.name,+ password: data.password,+ },+ turnstileToken+ ? { headers: { "x-turnstile-token": turnstileToken } }+ : undefined,+ );if (result.error) {toast.error(result.error.message || t("auth:signUpForm.failedSignUp"));@@ -172,7 +189,11 @@ export function SignUpForm({ invitationId, defaultEmail }: SignUpFormProps) {/></div>- <Button type="submit" disabled={isPending} className="w-full mt-4">+ <Button+ type="submit"+ disabled={isPending || (captchaRequired && !turnstileToken)}+ className="w-full mt-4"+ >{isPending? t("auth:signUpForm.creatingAccount"): t("auth:signUpForm.createAccount")}diff --git a/apps/web/src/components/auth/sso-providers.tsx b/apps/web/src/components/auth/sso-providers.tsxindex 869e3f248..1463dbf5e 100644--- a/apps/web/src/components/auth/sso-providers.tsx+++ b/apps/web/src/components/auth/sso-providers.tsx@@ -12,6 +12,7 @@ type Props = {callbackURL: string;errorCallbackURL: string;lastLoginMethod?: string | null;+ disabled?: boolean;};export function SSOProviders({@@ -19,6 +20,7 @@ export function SSOProviders({callbackURL,errorCallbackURL,lastLoginMethod,+ disabled = false,}: Props) {const { t } = useTranslation();const [loadingProvider, setLoadingProvider] = useState<string | null>(null);@@ -73,6 +75,7 @@ export function SSOProviders({{config?.hasGoogleSignIn && (<ProviderButtonproviderId="google"+ disabled={disabled}isLoading={loadingProvider === "google"}isLastUsed={lastLoginMethod === "google"}onClick={() => handleSocial("google", "auth:signIn.googleError")}@@ -97,6 +100,7 @@ export function SSOProviders({{config?.hasGithubSignIn && (<ProviderButtonproviderId="github"+ disabled={disabled}isLoading={loadingProvider === "github"}isLastUsed={lastLoginMethod === "github"}onClick={() => handleSocial("github", "auth:signIn.githubError")}@@ -108,6 +112,7 @@ export function SSOProviders({{config?.hasDiscordSignIn && (<ProviderButtonproviderId="discord"+ disabled={disabled}isLoading={loadingProvider === "discord"}isLastUsed={lastLoginMethod === "discord"}onClick={() => handleSocial("discord", "auth:signIn.discordError")}@@ -130,6 +135,7 @@ export function SSOProviders({{config?.hasCustomOAuth && (<ProviderButtonproviderId="custom"+ disabled={disabled}isLoading={loadingProvider === "custom"}isLastUsed={lastLoginMethod === "custom"}onClick={handleCustomOAuth}@@ -150,6 +156,7 @@ function ProviderButton({isLoading,isLastUsed,onClick,+ disabled = false,}: {providerId: string;icon: React.ReactNode;@@ -158,6 +165,7 @@ function ProviderButton({isLoading: boolean;isLastUsed: boolean;onClick: () => void;+ disabled?: boolean;}) {const { t } = useTranslation();return (@@ -165,7 +173,7 @@ function ProviderButton({<Buttonvariant="outline"onClick={onClick}- disabled={isLoading}+ disabled={isLoading || disabled}className={cn("w-full", isLastUsed && "border-primary/50!")}data-provider={providerId}>diff --git a/apps/web/src/components/auth/turnstile.tsx b/apps/web/src/components/auth/turnstile.tsxnew file mode 100644index 000000000..cc28f8f83--- /dev/null+++ b/apps/web/src/components/auth/turnstile.tsx@@ -0,0 +1,116 @@+import { useEffect, useRef } from "react";++const SCRIPT_SRC =+ "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";+const SCRIPT_ATTR = "data-kaneo-turnstile";++declare global {+ interface Window {+ turnstile?: {+ render: (+ container: HTMLElement,+ options: {+ sitekey: string;+ callback?: (token: string) => void;+ "error-callback"?: () => void;+ "expired-callback"?: () => void;+ theme?: "light" | "dark" | "auto";+ size?: "normal" | "compact" | "flexible" | "invisible";+ "refresh-expired"?: "auto" | "manual" | "never";+ "refresh-timeout"?: "auto" | "manual" | "never";+ },+ ) => string;+ remove: (widgetId: string) => void;+ reset: (widgetId: string) => void;+ };+ }+}++let scriptPromise: Promise<void> | null = null;++function loadScript(): Promise<void> {+ if (typeof window === "undefined") return Promise.resolve();+ if (window.turnstile) return Promise.resolve();+ if (scriptPromise) return scriptPromise;+ const existing = document.querySelector<HTMLScriptElement>(+ `script[${SCRIPT_ATTR}]`,+ );+ if (existing) {+ scriptPromise = new Promise((resolve) => {+ existing.addEventListener("load", () => resolve(), { once: true });+ });+ return scriptPromise;+ }+ scriptPromise = new Promise((resolve, reject) => {+ const script = document.createElement("script");+ script.src = SCRIPT_SRC;+ script.async = true;+ script.defer = true;+ script.setAttribute(SCRIPT_ATTR, "");+ script.onload = () => resolve();+ script.onerror = () => reject(new Error("Failed to load Turnstile"));+ document.head.appendChild(script);+ });+ return scriptPromise;+}++export type TurnstileProps = {+ siteKey: string;+ onVerify: (token: string) => void;+ onExpire?: () => void;+ onError?: () => void;+ theme?: "light" | "dark" | "auto";+};++export function Turnstile({+ siteKey,+ onVerify,+ onExpire,+ onError,+ theme = "auto",+}: TurnstileProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const widgetIdRef = useRef<string | null>(null);++ // Hold the latest callbacks in refs so the effect doesn't re-run (and+ // tear down + re-render the iframe) when the parent passes new function+ // identities. Without this, every parent re-render rebuilt the widget.+ const onVerifyRef = useRef(onVerify);+ const onExpireRef = useRef(onExpire);+ const onErrorRef = useRef(onError);+ onVerifyRef.current = onVerify;+ onExpireRef.current = onExpire;+ onErrorRef.current = onError;++ useEffect(() => {+ let cancelled = false;+ loadScript()+ .then(() => {+ if (cancelled || !containerRef.current || !window.turnstile) return;+ widgetIdRef.current = window.turnstile.render(containerRef.current, {+ sitekey: siteKey,+ callback: (token) => onVerifyRef.current(token),+ "expired-callback": () => onExpireRef.current?.(),+ "error-callback": () => onErrorRef.current?.(),+ theme,+ size: "flexible",+ // Don't silently re-challenge on focus regain / timeout. The widget+ // keeps the verified token until it actually expires (Cloudflare's+ // 300s window); on expiry the `expired-callback` clears parent+ // state and the user clicks once to re-verify.+ "refresh-expired": "manual",+ "refresh-timeout": "manual",+ });+ })+ .catch(() => onErrorRef.current?.());+ return () => {+ cancelled = true;+ if (widgetIdRef.current && window.turnstile) {+ window.turnstile.remove(widgetIdRef.current);+ widgetIdRef.current = null;+ }+ };+ }, [siteKey, theme]);++ return <div ref={containerRef} className="w-full" />;+}diff --git a/apps/web/src/components/providers/auth-provider/index.tsx b/apps/web/src/components/providers/auth-provider/index.tsxindex b02332b77..82688cac2 100644--- a/apps/web/src/components/providers/auth-provider/index.tsx+++ b/apps/web/src/components/providers/auth-provider/index.tsx@@ -1,4 +1,4 @@-import { createContext, type PropsWithChildren } from "react";+import { createContext, type PropsWithChildren, useRef } from "react";import { authClient } from "@/lib/auth-client";import type { User } from "@/types/user";import { LoadingSkeleton } from "../../ui/loading-skeleton";@@ -15,8 +15,17 @@ export const AuthContext = createContext<{function AuthProvider({ children }: PropsWithChildren) {const { data, isPending } = useSession();+ // Only show the loading skeleton during the *first* session fetch. Better+ // Auth re-fetches the session on window focus; if we kept returning the+ // skeleton while those background fetches are pending we'd unmount the+ // entire route tree on every alt-tab — which tore down the Turnstile+ // iframe and forced a re-challenge.+ const hasLoadedOnce = useRef(false);+ if (!isPending) {+ hasLoadedOnce.current = true;+ }- if (isPending) {+ if (isPending && !hasLoadedOnce.current) {return <LoadingSkeleton />;}diff --git a/apps/web/src/routes/auth/sign-in.tsx b/apps/web/src/routes/auth/sign-in.tsxindex fd52d8f78..8906f352b 100644--- a/apps/web/src/routes/auth/sign-in.tsx+++ b/apps/web/src/routes/auth/sign-in.tsx@@ -3,7 +3,7 @@ import {useNavigate,useSearch,} from "@tanstack/react-router";-import { Github, KeyRound, UserCheck } from "lucide-react";+import { Github, KeyRound } from "lucide-react";import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";import { z } from "zod/v4";@@ -40,7 +40,6 @@ function SignIn() {const [isGithubLoading, setIsGithubLoading] = useState(false);const [isGoogleLoading, setIsGoogleLoading] = useState(false);const [isDiscordLoading, setIsDiscordLoading] = useState(false);- const [isGuestLoading, setIsGuestLoading] = useState(false);const lastLoginMethod = authClient.getLastUsedLoginMethod();const { data: config, isLoading: isConfigLoading } = useGetConfig();const {@@ -92,24 +91,6 @@ function SignIn() {return `${baseUrl}/dashboard`;};- const handleGuestAccess = async () => {- setIsGuestLoading(true);- try {- const result = await authClient.signIn.anonymous();- if (result.error) {- throw new Error(result.error.message);- }- toast.success(t("auth:signIn.guestSuccess"));- navigate({ to: "/dashboard" });- } catch (error) {- toast.error(- error instanceof Error ? error.message : t("auth:signIn.guestError"),- );- } finally {- setIsGuestLoading(false);- }- };-const handleCustomOAuth = async () => {setIsCustomOAuthLoading(true);try {@@ -363,20 +344,6 @@ function SignIn() {)}</div>)}-- {config?.hasGuestAccess && !invitationId && (- <Button- variant="outline"- onClick={handleGuestAccess}- disabled={isGuestLoading}- className="w-full"- >- <UserCheck className="w-4 h-4 mr-2" />- {isGuestLoading- ? t("auth:signIn.signingIn")- : t("auth:signUp.continueAsGuest")}- </Button>- )}</div><div className="relative my-6">diff --git a/apps/web/src/routes/auth/sign-up.tsx b/apps/web/src/routes/auth/sign-up.tsxindex a6d732eb4..3afdbe74d 100644--- a/apps/web/src/routes/auth/sign-up.tsx+++ b/apps/web/src/routes/auth/sign-up.tsx@@ -4,13 +4,14 @@ import {useSearch,} from "@tanstack/react-router";import { UserCheck } from "lucide-react";-import { useEffect, useState } from "react";+import { useCallback, useEffect, useState } from "react";import { useTranslation } from "react-i18next";import { z } from "zod/v4";import { AuthLayout } from "@/components/auth/layout";import { SignUpForm } from "@/components/auth/sign-up-form";import { SSOProviders } from "@/components/auth/sso-providers";import { AuthToggle } from "@/components/auth/toggle";+import { Turnstile } from "@/components/auth/turnstile";import PageTitle from "@/components/page-title";import { Alert, AlertDescription } from "@/components/ui/alert";import { Button } from "@/components/ui/button";@@ -19,6 +20,10 @@ import useInstanceStatus from "@/hooks/queries/instance/use-instance-status";import { authClient } from "@/lib/auth-client";import { toast } from "@/lib/toast";+const TURNSTILE_SITE_KEY = import.meta.env.VITE_TURNSTILE_SITE_KEY as+ | string+ | undefined;+const signUpSearchSchema = z.object({invitationId: z.string().optional(),email: z.string().optional(),@@ -34,6 +39,15 @@ function SignUp() {const navigate = useNavigate();const search = useSearch({ from: "/auth/sign-up" });const [isGuestLoading, setIsGuestLoading] = useState(false);+ const [turnstileToken, setTurnstileToken] = useState<string | null>(null);+ const handleTurnstileVerify = useCallback((token: string) => {+ setTurnstileToken(token);+ }, []);+ const handleTurnstileExpire = useCallback(() => {+ setTurnstileToken(null);+ }, []);+ const captchaConfigured = Boolean(TURNSTILE_SITE_KEY);+ const captchaPending = captchaConfigured && !turnstileToken;const { data: config } = useGetConfig();const {data: instanceStatus,@@ -65,6 +79,7 @@ function SignUp() {const errorCallbackURL = `${baseUrl}/auth/sign-up`;const handleGuestAccess = async () => {+ if (captchaPending) return;setIsGuestLoading(true);try {const result = await authClient.signIn.anonymous();@@ -139,6 +154,7 @@ function SignUp() {config={config}callbackURL={callbackURL}errorCallbackURL={errorCallbackURL}+ disabled={captchaPending}/>);// Hide self-service alternatives (guest + SSO) when registration@@ -172,7 +188,7 @@ function SignUp() {<Buttonvariant="outline"onClick={handleGuestAccess}- disabled={isGuestLoading}+ disabled={isGuestLoading || captchaPending}className="w-full"><UserCheck className="w-4 h-4 mr-2" />@@ -196,6 +212,15 @@ function SignUp() {<SignUpForminvitationId={invitationId}defaultEmail={prefillEmail}+ turnstileToken={captchaConfigured ? turnstileToken : undefined}+ />+ )}+ {captchaConfigured && TURNSTILE_SITE_KEY && (+ <Turnstile+ siteKey={TURNSTILE_SITE_KEY}+ onVerify={handleTurnstileVerify}+ onExpire={handleTurnstileExpire}+ onError={handleTurnstileExpire}/>)}{!isInstanceAdminSetup && (diff --git a/tests/api/utils/check-workspace-name.test.ts b/tests/api/utils/check-workspace-name.test.tsnew file mode 100644index 000000000..482732b8c--- /dev/null+++ b/tests/api/utils/check-workspace-name.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import { checkWorkspaceName } from "../../../apps/api/src/utils/check-workspace-name";++describe("checkWorkspaceName", () => {+ it("accepts normal workspace names", () => {+ expect(checkWorkspaceName("Acme Inc.").ok).toBe(true);+ expect(checkWorkspaceName("My Team — Project").ok).toBe(true);+ expect(checkWorkspaceName("Crypto Snack").ok).toBe(true);+ });++ it("rejects names with embedded URLs (2026-05-28 phishing pattern)", () => {+ const result = checkWorkspaceName(+ "BANK OPER https://ij5205.craftum.io/page2",+ );+ expect(result.ok).toBe(false);+ });++ it("rejects names longer than 100 characters", () => {+ const result = checkWorkspaceName("a".repeat(101));+ expect(result.ok).toBe(false);+ });++ it("rejects names with HTML / template chars", () => {+ expect(checkWorkspaceName("<!DOCTYPE html><script>").ok).toBe(false);+ expect(checkWorkspaceName("hello {{name}}").ok).toBe(false);+ });++ it("rejects empty / whitespace-only names", () => {+ expect(checkWorkspaceName("").ok).toBe(false);+ expect(checkWorkspaceName(" ").ok).toBe(false);+ });++ it("returns the rejection reason as a string", () => {+ const r = checkWorkspaceName("a".repeat(150));+ expect(r.ok).toBe(false);+ if (!r.ok) expect(typeof r.reason).toBe("string");+ });+});diff --git a/tests/api/utils/is-disposable-email.test.ts b/tests/api/utils/is-disposable-email.test.tsnew file mode 100644index 000000000..1ee927dba--- /dev/null+++ b/tests/api/utils/is-disposable-email.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";+import { isDisposableEmail } from "../../../apps/api/src/utils/is-disposable-email";++describe("isDisposableEmail", () => {+ it("flags base disposable domains observed in the 2026-05-28 abuse", () => {+ expect(isDisposableEmail("[email protected]")).toBe(true);+ expect(isDisposableEmail("[email protected]")).toBe(true);+ expect(isDisposableEmail("[email protected]")).toBe(true);+ });++ it("flags wildcard subdomains used by the attackers", () => {+ expect(isDisposableEmail("[email protected]")).toBe(+ true,+ );+ expect(isDisposableEmail("[email protected]")).toBe(true);+ expect(isDisposableEmail("[email protected]")).toBe(true);+ });++ it("flags common well-known disposable providers", () => {+ expect(isDisposableEmail("[email protected]")).toBe(true);+ expect(isDisposableEmail("[email protected]")).toBe(true);+ });++ it("allows real provider domains", () => {+ expect(isDisposableEmail("[email protected]")).toBe(false);+ expect(isDisposableEmail("[email protected]")).toBe(false);+ expect(isDisposableEmail("[email protected]")).toBe(false);+ expect(isDisposableEmail("[email protected]")).toBe(false);+ });++ it("is case-insensitive on the host", () => {+ expect(isDisposableEmail("[email protected]")).toBe(true);+ });++ it("handles malformed inputs gracefully", () => {+ expect(isDisposableEmail("")).toBe(false);+ expect(isDisposableEmail("no-at-sign")).toBe(false);+ expect(isDisposableEmail("trailing-at@")).toBe(false);+ });+});diff --git a/tests/api/utils/verify-turnstile.test.ts b/tests/api/utils/verify-turnstile.test.tsnew file mode 100644index 000000000..403223e66--- /dev/null+++ b/tests/api/utils/verify-turnstile.test.ts@@ -0,0 +1,76 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { verifyTurnstile } from "../../../apps/api/src/utils/verify-turnstile";++describe("verifyTurnstile", () => {+ const originalSecret = process.env.TURNSTILE_SECRET_KEY;+ const originalFetch = globalThis.fetch;++ beforeEach(() => {+ process.env.TURNSTILE_SECRET_KEY = "test-secret";+ });++ afterEach(() => {+ if (originalSecret === undefined) {+ delete process.env.TURNSTILE_SECRET_KEY;+ } else {+ process.env.TURNSTILE_SECRET_KEY = originalSecret;+ }+ globalThis.fetch = originalFetch;+ vi.restoreAllMocks();+ });++ it("returns ok when no secret is configured (self-hosted opt-out)", async () => {+ delete process.env.TURNSTILE_SECRET_KEY;+ const result = await verifyTurnstile("any-token", "1.2.3.4");+ expect(result.ok).toBe(true);+ });++ it("fails when the token is missing", async () => {+ const result = await verifyTurnstile(null);+ expect(result.ok).toBe(false);+ });++ it("posts the secret, token, and remoteip to Cloudflare", async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ json: async () => ({ success: true }),+ });+ globalThis.fetch = fetchMock as unknown as typeof fetch;++ const result = await verifyTurnstile("good-token", "203.0.113.7");++ expect(result.ok).toBe(true);+ expect(fetchMock).toHaveBeenCalledOnce();+ const [url, init] = fetchMock.mock.calls[0] ?? [];+ expect(url).toBe(+ "https://challenges.cloudflare.com/turnstile/v0/siteverify",+ );+ const body = (init as { body: URLSearchParams }).body;+ expect(body.get("secret")).toBe("test-secret");+ expect(body.get("response")).toBe("good-token");+ expect(body.get("remoteip")).toBe("203.0.113.7");+ });++ it("returns the cloudflare error codes on failure", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue({+ json: async () => ({+ success: false,+ "error-codes": ["invalid-input-response"],+ }),+ }) as unknown as typeof fetch;++ const result = await verifyTurnstile("bad-token");+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.reason).toContain("invalid-input-response");+ }+ });++ it("fails gracefully when the fetch throws", async () => {+ globalThis.fetch = vi+ .fn()+ .mockRejectedValue(new Error("network down")) as unknown as typeof fetch;++ const result = await verifyTurnstile("token");+ expect(result.ok).toBe(false);+ });+});