Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(auth): require email codes for cloud sign-up

Andrejf974b0529d36
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index 108b82964..0061ec5c9 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -87,6 +87,7 @@ import { isDisposableEmail } from "./utils/is-disposable-email";
import { isLocalSignInPath } from "./utils/is-local-sign-in-path";
import { trackPasswordResetDelivery } from "./utils/password-reset-delivery";
import {
+ assertEmailCodeRecipientAllowed,
assertGuestRegistrationAllowed,
assertUserRegistrationAllowed,
normalizeInvitationId,
@@ -156,6 +157,12 @@ function getLocaleKey(locale?: string | null) {
return "en";
}
+function isEmailCodeSignInAvailable() {
+ return (
+ isSmtpConfigured() && !isEmailOtpSignInDisabled && !isLoginFormDisabled
+ );
+}
+
// Reads env at call time (not module scope) so tests can stub it.
async function shouldDeliverSignInEmail(email: string) {
if (process.env.DISABLE_PASSWORD_REGISTRATION === "true") {
@@ -827,6 +834,14 @@ export const auth = betterAuth({
});
}
+ if (
+ (ctx.path === "/email-otp/send-verification-otp" &&
+ ctx.body?.type === "sign-in") ||
+ ctx.path === "/sign-in/magic-link"
+ ) {
+ await assertEmailCodeRecipientAllowed(ctx.body?.email);
+ }
+
// 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
@@ -877,17 +892,15 @@ export const auth = betterAuth({
});
}
- // Cloud-only disposable-email check; CAPTCHA is enforced above
- // on every account-creation initiation when configured.
- if (isCloud() && !isInstanceAdminSetup) {
- const signupEmail = (ctx.body?.email as string | undefined) ?? "";
- if (signupEmail && isDisposableEmail(signupEmail)) {
- throw new APIError("BAD_REQUEST", {
- code: "DISPOSABLE_EMAIL_NOT_ALLOWED",
- message:
- "Sign-up with disposable email addresses is not allowed.",
- });
- }
+ if (
+ isCloud() &&
+ !isInstanceAdminSetup &&
+ isEmailCodeSignInAvailable()
+ ) {
+ throw new APIError("FORBIDDEN", {
+ code: "EMAIL_CODE_REGISTRATION_REQUIRED",
+ message: "Create your account with an email code.",
+ });
}
}
diff --git a/apps/api/src/config/response.ts b/apps/api/src/config/response.ts
index 6c14b70f4..860649d68 100644
--- a/apps/api/src/config/response.ts
+++ b/apps/api/src/config/response.ts
@@ -15,6 +15,10 @@ export const configSchema = z
hasCustomOAuth: z.boolean(),
hasGuestAccess: z.boolean(),
disableLoginForm: z.boolean(),
+ customOAuthName: z.string().nullable().openapi({
+ description:
+ "Label for the custom OAuth provider on the sign-in page. Null means the generic SSO label.",
+ }),
customOAuthAutoLogin: z.boolean(),
customOAuthLogoutUrl: z.string().nullable(),
billingEnabled: z.boolean(),
diff --git a/apps/api/src/utils/get-settings.ts b/apps/api/src/utils/get-settings.ts
index 38f20b105..a6535fc77 100644
--- a/apps/api/src/utils/get-settings.ts
+++ b/apps/api/src/utils/get-settings.ts
@@ -34,6 +34,7 @@ function getSettings() {
"DISABLE_LOGIN_FORM",
].every((key) => process.env[key] !== "true"),
disableLoginForm: process.env.DISABLE_LOGIN_FORM === "true",
+ customOAuthName: process.env.CUSTOM_OAUTH_NAME?.trim() || null,
customOAuthAutoLogin: process.env.CUSTOM_OAUTH_AUTO_LOGIN === "true",
customOAuthLogoutUrl: process.env.CUSTOM_OAUTH_LOGOUT_URL || null,
billingEnabled: isBillingEnabled(),
diff --git a/apps/api/src/utils/registration-policy.ts b/apps/api/src/utils/registration-policy.ts
index 69490628f..fc0f96517 100644
--- a/apps/api/src/utils/registration-policy.ts
+++ b/apps/api/src/utils/registration-policy.ts
@@ -1,6 +1,11 @@
import { APIError } from "better-auth/api";
-import { checkRegistrationAllowed } from "./check-registration-allowed";
+import {
+ checkRegistrationAllowed,
+ userExistsByEmail,
+} from "./check-registration-allowed";
import { hasRegisteredUsers } from "./instance-bootstrap";
+import { isCloud } from "./is-cloud";
+import { isDisposableEmail } from "./is-disposable-email";
export function normalizeInvitationId(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
@@ -15,6 +20,23 @@ export function isOAuthCallbackPath(path: unknown): boolean {
);
}
+function disposableEmailError() {
+ return new APIError("BAD_REQUEST", {
+ code: "DISPOSABLE_EMAIL_NOT_ALLOWED",
+ message:
+ "Use a permanent email address. Disposable addresses cannot create accounts.",
+ });
+}
+
+export async function assertEmailCodeRecipientAllowed(
+ email: unknown,
+): Promise<void> {
+ if (!isCloud() || typeof email !== "string" || !isDisposableEmail(email))
+ return;
+ if (!(await hasRegisteredUsers()) || (await userExistsByEmail(email))) return;
+ throw disposableEmailError();
+}
+
export async function assertGuestRegistrationAllowed(): Promise<void> {
if (
process.env.DISABLE_GUEST_ACCESS === "true" ||
@@ -43,6 +65,7 @@ export async function assertUserRegistrationAllowed(
return;
}
if (!(await hasRegisteredUsers())) return;
+ if (isCloud() && isDisposableEmail(user.email)) throw disposableEmailError();
if (
process.env.DISABLE_PASSWORD_REGISTRATION === "true" &&
!isOAuthCallbackPath(context?.path)
diff --git a/apps/api/src/utils/verify-turnstile.ts b/apps/api/src/utils/verify-turnstile.ts
index 523f3c47b..23405d488 100644
--- a/apps/api/src/utils/verify-turnstile.ts
+++ b/apps/api/src/utils/verify-turnstile.ts
@@ -5,6 +5,7 @@ const TURNSTILE_VERIFY_URL =
export type TurnstileResult = { ok: true } | { ok: false; reason: string };
export const authCaptchaPaths = new Set([
+ "/sign-in/email",
"/sign-up/email",
"/sign-in/social",
"/sign-in/oauth2",
diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdx
index c06e30c78..37eefa7b7 100644
--- a/apps/docs/core/installation/environment-variables.mdx
+++ b/apps/docs/core/installation/environment-variables.mdx
@@ -177,6 +177,7 @@ Name | Description |
| `CUSTOM_OAUTH_SCOPES` | (Optional) Comma-separated list of OAuth scopes. Default: `profile,email`.
| `CUSTOM_OAUTH_RESPONSE_TYPE` | (Optional) OAuth response type. Default: `code`.
| `CUSTOM_AUTH_PKCE` | (Optional) Enable/disable PKCE. Default: `true`.
+| `CUSTOM_OAUTH_NAME` | (Optional) Provider name on the sign-in button, for example `Authentik`. Default: `SSO`.
| `CUSTOM_OAUTH_LOGOUT_URL` | (Optional) Logout endpoint URL for your identity provider.
### Redis
diff --git a/apps/docs/core/social-providers/custom-oauth.mdx b/apps/docs/core/social-providers/custom-oauth.mdx
index f69e72cb8..c09931f57 100644
--- a/apps/docs/core/social-providers/custom-oauth.mdx
+++ b/apps/docs/core/social-providers/custom-oauth.mdx
@@ -33,6 +33,7 @@ If you use a discovery URL, the provider can supply the authorization, token, an
| `CUSTOM_OAUTH_SCOPES` | Comma-separated list of OAuth scopes | `profile,email` |
| `CUSTOM_OAUTH_RESPONSE_TYPE` | OAuth response type | `code` |
| `CUSTOM_AUTH_PKCE` | Enable/disable PKCE (Proof Key for Code Exchange) | `true` |
+| `CUSTOM_OAUTH_NAME` | Provider name on the sign-in button, for example `Authentik` | `SSO` |
| `CUSTOM_OAUTH_LOGOUT_URL` | Provider logout endpoint, if needed | Unset |
| `CUSTOM_OAUTH_AUTO_LOGIN` | Auto-redirect to the custom OAuth provider, bypassing the login page | `false` |
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index 7d0f4f7c0..02aa6fcc5 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -586,6 +586,13 @@
"disableLoginForm": {
"type": "boolean"
},
+ "customOAuthName": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Label for the custom OAuth provider on the sign-in page. Null means the generic SSO label."
+ },
"customOAuthAutoLogin": {
"type": "boolean"
},
@@ -613,6 +620,7 @@
"hasCustomOAuth",
"hasGuestAccess",
"disableLoginForm",
+ "customOAuthName",
"customOAuthAutoLogin",
"customOAuthLogoutUrl",
"billingEnabled"
diff --git a/tests/api-integration/auth-captcha.test.ts b/tests/api-integration/auth-captcha.test.ts
index 7afbbbc19..2406b1e95 100644
--- a/tests/api-integration/auth-captcha.test.ts
+++ b/tests/api-integration/auth-captcha.test.ts
@@ -13,6 +13,10 @@ import { resetTestDatabase } from "./helpers/database";
import { createWorkspaceMember } from "./helpers/fixtures";
const endpoints = [
+ [
+ "/sign-in/email",
+ { email: "[email protected]", password: "long-test-password" },
+ ],
[
"/sign-up/email",
{
diff --git a/tests/api-integration/auth-registration-policy.test.ts b/tests/api-integration/auth-registration-policy.test.ts
index a398008b9..08abdebcb 100644
--- a/tests/api-integration/auth-registration-policy.test.ts
+++ b/tests/api-integration/auth-registration-policy.test.ts
@@ -431,4 +431,111 @@ describe("auth registration and bootstrap boundaries", () => {
).toBe(400);
expect(await db.select().from(schema.sessionTable)).toHaveLength(0);
});
+
+ describe("cloud email-code registration", () => {
+ beforeEach(() => {
+ vi.stubEnv("KANEO_CLOUD", "true");
+ vi.spyOn(email, "isSmtpConfigured").mockReturnValue(true);
+ });
+
+ it("creates a verified account with the submitted name from an email code", async () => {
+ await createWorkspaceMember();
+ const send = vi.spyOn(email, "sendOtpEmail").mockResolvedValue(undefined);
+ expect(
+ (
+ await post("/email-otp/send-verification-otp", {
+ email: "[email protected]",
+ type: "sign-in",
+ })
+ ).status,
+ ).toBe(200);
+ const data = send.mock.lastCall?.[2] as { otp: string };
+ const response = await post("/sign-in/email-otp", {
+ email: "[email protected]",
+ otp: data.otp,
+ name: "New Person",
+ });
+ expect(response.status).toBe(200);
+ const [user] = await db
+ .select()
+ .from(schema.userTable)
+ .where(eq(schema.userTable.email, "[email protected]"));
+ expect(user).toMatchObject({ name: "New Person", emailVerified: true });
+ });
+
+ it("refuses to send a code that would create an account for a disposable address", async () => {
+ await createWorkspaceMember();
+ const send = vi.spyOn(email, "sendOtpEmail").mockResolvedValue(undefined);
+ const sendMagicLink = vi
+ .spyOn(email, "sendMagicLinkEmail")
+ .mockResolvedValue(undefined);
+ const otp = await post("/email-otp/send-verification-otp", {
+ email: "[email protected]",
+ type: "sign-in",
+ });
+ expect(otp.status).toBe(400);
+ expect(await otp.json()).toMatchObject({
+ code: "DISPOSABLE_EMAIL_NOT_ALLOWED",
+ });
+ expect(
+ (
+ await post("/sign-in/magic-link", {
+ email: "[email protected]",
+ })
+ ).status,
+ ).toBe(400);
+ expect(send).not.toHaveBeenCalled();
+ expect(sendMagicLink).not.toHaveBeenCalled();
+ expect(await db.select().from(schema.verificationTable)).toHaveLength(0);
+ });
+
+ it("still sends codes to an existing account on a disposable address", async () => {
+ await createWorkspaceMember();
+ await db.insert(schema.userTable).values({
+ id: "existing-disposable",
+ email: "[email protected]",
+ name: "Kept",
+ });
+ const send = vi.spyOn(email, "sendOtpEmail").mockResolvedValue(undefined);
+ expect(
+ (
+ await post("/email-otp/send-verification-otp", {
+ email: "[email protected]",
+ type: "sign-in",
+ })
+ ).status,
+ ).toBe(200);
+ expect(send).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects disposable addresses at account creation on every path", async () => {
+ await createWorkspaceMember();
+ for (const path of ["/sign-in/email-otp", "/callback/github"]) {
+ await expect(
+ assertUserRegistrationAllowed(
+ { email: "[email protected]", emailVerified: true },
+ { path },
+ ),
+ ).rejects.toMatchObject({
+ body: expect.objectContaining({
+ code: "DISPOSABLE_EMAIL_NOT_ALLOWED",
+ }),
+ });
+ }
+ });
+
+ it("requires an email code instead of a password for new cloud accounts", async () => {
+ await createWorkspaceMember();
+ const response = await signup("[email protected]");
+ expect(response.status).toBe(403);
+ expect(await response.json()).toMatchObject({
+ code: "EMAIL_CODE_REGISTRATION_REQUIRED",
+ });
+ expect(await db.select().from(schema.userTable)).toHaveLength(1);
+ });
+
+ it("keeps password sign-up for the first account on a fresh instance", async () => {
+ expect((await signup("[email protected]")).status).toBe(200);
+ });
+ });
});
diff --git a/tests/api-integration/config.test.ts b/tests/api-integration/config.test.ts
index 59e43bd4d..cbc55b8c9 100644
--- a/tests/api-integration/config.test.ts
+++ b/tests/api-integration/config.test.ts
@@ -27,6 +27,7 @@ describe("API integration: config", () => {
disablePasswordRegistration: false,
disableEmailOtpSignIn: false,
disableLoginForm: false,
+ customOAuthName: null,
customOAuthAutoLogin: false,
isDemoMode: false,
hasGuestAccess: true,
@@ -41,4 +42,13 @@ describe("API integration: config", () => {
].every((key) => typeof value[key] === "boolean"),
);
});
+
+ it("returns the trimmed custom OAuth name when one is set", async () => {
+ vi.stubEnv("CUSTOM_OAUTH_NAME", " Authentik ");
+ const response = await createApp().app.request("/api/config");
+ expect(await response.json()).toHaveProperty(
+ "customOAuthName",
+ "Authentik",
+ );
+ });
});
diff --git a/tests/api-integration/setup.ts b/tests/api-integration/setup.ts
index be1444d41..d61803df1 100644
--- a/tests/api-integration/setup.ts
+++ b/tests/api-integration/setup.ts
@@ -97,6 +97,7 @@ process.env.CUSTOM_OAUTH_SCOPES = "";
process.env.CUSTOM_OAUTH_RESPONSE_TYPE = "";
process.env.CUSTOM_OAUTH_DISCOVERY_URL = "";
process.env.CUSTOM_OAUTH_AUTO_LOGIN = "";
+process.env.CUSTOM_OAUTH_NAME = "";
process.env.DEVICE_AUTH_CLIENT_IDS = "kaneo-cli";
afterEach(() => {