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.

fix(auth): gate sign-in emails to deliverable addresses (#1758)

Yiğit Serind6afc9bfebe6
diff --git a/ENVIRONMENT_SETUP.md b/ENVIRONMENT_SETUP.md
index 65def7f8b..db2f8122c 100644
--- a/ENVIRONMENT_SETUP.md
+++ b/ENVIRONMENT_SETUP.md
@@ -89,6 +89,10 @@ For a private SMTP certificate authority, configure Node's `NODE_EXTRA_CA_CERTS`
When SMTP is configured, sign-in uses email verification codes by default. Set `DISABLE_EMAIL_OTP_SIGN_IN=true` to use email/password sign-in instead (workspace invitation emails still use SMTP).
+After initial setup, when `DISABLE_REGISTRATION=true`, sign-in emails (OTP codes and magic links) are only sent to addresses that already have an account or hold a pending workspace invitation — unknown addresses get a generic success response with no email. When `DISABLE_PASSWORD_REGISTRATION=true`, only existing accounts receive them. An empty instance with `DISABLE_REGISTRATION=true` still accepts sign-in emails for any address until the first non-guest account is created.
+
+Sign-in email eligibility checks and delivery run in the API process after the request is accepted, so the response does not wait for SMTP. Pending sends are given up to 10 seconds to finish during graceful shutdown; they are not persisted across a process crash.
+
#### Cloud-mode abuse mitigations
Hosted multi-tenant instances should enable the cloud abuse gates. Self-hosted instances can leave these unset.
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index ed5f82977..4835d36b7 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -46,7 +46,11 @@ import { authDatabaseAdapter } from "./database/auth-adapter";
import { publishEvent } from "./events";
import deleteAccountData from "./user/controllers/delete-account-data";
import { resolveAuthSecret } from "./utils/auth-secret";
-import { checkRegistrationAllowed } from "./utils/check-registration-allowed";
+import {
+ canSendSignInEmail,
+ checkRegistrationAllowed,
+ userExistsByEmail,
+} from "./utils/check-registration-allowed";
import { checkWorkspaceName } from "./utils/check-workspace-name";
import { mapCustomOAuthProfileToUser } from "./utils/custom-oauth-profile";
import { generateDemoName } from "./utils/generate-demo-name";
@@ -67,6 +71,7 @@ import {
assertUserRegistrationAllowed,
normalizeInvitationId,
} from "./utils/registration-policy";
+import { queueSignInEmail } from "./utils/sign-in-email-tasks";
import { authCaptchaPaths, verifyTurnstile } from "./utils/verify-turnstile";
config();
@@ -130,6 +135,22 @@ function getLocaleKey(locale?: string | null) {
return "en";
}
+// 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") {
+ return userExistsByEmail(email);
+ }
+ if (process.env.DISABLE_REGISTRATION === "true") {
+ // Mirror `assertUserRegistrationAllowed`: the first non-guest user can
+ // always complete initial instance setup.
+ if (!(await hasRegisteredUsers())) {
+ return true;
+ }
+ return canSendSignInEmail(email);
+ }
+ return true;
+}
+
function getAuthEmailCopy(locale?: string | null) {
const localeKey = getLocaleKey(locale);
@@ -286,16 +307,17 @@ export const auth = betterAuth({
magicLink({
disableSignUp: isPasswordRegistrationDisabled,
sendMagicLink: async ({ email, url }) => {
- try {
+ queueSignInEmail(async () => {
+ if (!(await shouldDeliverSignInEmail(email))) {
+ return;
+ }
const locale = await getUserLocale(email);
const copy = getAuthEmailCopy(locale);
await sendMagicLinkEmail(email, copy.magicLinkSubject, {
magicLink: url,
locale,
});
- } catch (error) {
- console.error(error);
- }
+ });
},
}),
...(isEmailOtpSignInDisabled
@@ -306,11 +328,16 @@ export const auth = betterAuth({
disableSignUp: isPasswordRegistrationDisabled,
async sendVerificationOTP({ email, otp, type }) {
if (type === "sign-in") {
- const locale = await getUserLocale(email);
- const copy = getAuthEmailCopy(locale);
- await sendOtpEmail(email, copy.otpSubject, {
- otp,
- locale,
+ queueSignInEmail(async () => {
+ if (!(await shouldDeliverSignInEmail(email))) {
+ return;
+ }
+ const locale = await getUserLocale(email);
+ const copy = getAuthEmailCopy(locale);
+ await sendOtpEmail(email, copy.otpSubject, {
+ otp,
+ locale,
+ });
});
}
},
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 68918edf5..48f65c271 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -76,6 +76,7 @@ import { migrateSessionColumn } from "./utils/migrate-session-column";
import { migrateWorkspaceUserEmail } from "./utils/migrate-workspace-user-email";
import { normalizeApiServerUrl } from "./utils/openapi-spec";
import { seedDefaultWorkspaceRoles } from "./utils/seed-default-workspace-roles";
+import { drainSignInEmails } from "./utils/sign-in-email-tasks";
import { validateWorkspaceAccess } from "./utils/validate-workspace-access";
import workflowRule from "./workflow-rule";
import workspace from "./workspace";
@@ -959,7 +960,13 @@ export async function startServer(
shutdownScheduler();
await shutdownWebSocketAdapter();
server.close();
- await drainPasswordResetDeliveries();
+ const [, signInEmailsDrained] = await Promise.all([
+ drainPasswordResetDeliveries(),
+ drainSignInEmails(),
+ ]);
+ if (!signInEmailsDrained) {
+ console.warn("Timed out waiting for pending sign-in emails");
+ }
process.exit(0);
};
diff --git a/apps/api/src/utils/check-registration-allowed.ts b/apps/api/src/utils/check-registration-allowed.ts
index 50ce13b0c..5bbbbdd4b 100644
--- a/apps/api/src/utils/check-registration-allowed.ts
+++ b/apps/api/src/utils/check-registration-allowed.ts
@@ -198,6 +198,22 @@ export async function getInvitationDetails(
};
}
+export async function userExistsByEmail(email: string): Promise<boolean> {
+ const [user] = await db
+ .select({ id: userTable.id })
+ .from(userTable)
+ .where(eq(userTable.email, email.toLowerCase()))
+ .limit(1);
+ return Boolean(user);
+}
+
+export async function canSendSignInEmail(email: string): Promise<boolean> {
+ if (await userExistsByEmail(email)) {
+ return true;
+ }
+ return (await getUserPendingInvitations(email)).length > 0;
+}
+
export async function getUserPendingInvitations(userEmail: string) {
const now = new Date();
diff --git a/apps/api/src/utils/sign-in-email-tasks.ts b/apps/api/src/utils/sign-in-email-tasks.ts
new file mode 100644
index 000000000..1c85d39ab
--- /dev/null
+++ b/apps/api/src/utils/sign-in-email-tasks.ts
@@ -0,0 +1,31 @@
+const pending = new Set<Promise<void>>();
+
+// Queue eligibility checks as well as SMTP so neither determines response time.
+export function queueSignInEmail(deliver: () => Promise<void>): void {
+ const task = Promise.resolve()
+ .then(deliver)
+ .catch(() => {
+ // Provider errors can contain addresses, tokens, or SMTP credentials.
+ console.error("Sign-in email delivery failed");
+ })
+ .finally(() => pending.delete(task));
+ pending.add(task);
+}
+
+// Bound shutdown waiting when a mail provider is unavailable.
+export async function drainSignInEmails(timeoutMs = 10_000): Promise<boolean> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ (async () => {
+ while (pending.size > 0) await Promise.all([...pending]);
+ return true;
+ })(),
+ new Promise<boolean>((resolve) => {
+ timer = setTimeout(() => resolve(false), timeoutMs);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdx
index 0059e8ab1..ee2960bd8 100644
--- a/apps/docs/core/installation/environment-variables.mdx
+++ b/apps/docs/core/installation/environment-variables.mdx
@@ -103,7 +103,7 @@ only the small `{"type":"ping"}` text keepalive, with a 64-byte message limit.
Name | Description | Default |
--- | --- | --- |
| `DISABLE_GUEST_ACCESS` | Disable anonymous/guest sign-in. Guests are also blocked before initial instance setup and when registration, local registration, or the local login form is disabled. | `false` |
-| `DISABLE_REGISTRATION` | Disable public user registration. When set to `true`, the sign-up option will not be shown on the sign-in page and new user creation is blocked (including via SSO). **Note:** Invited password signups must present the matching invitation link. OAuth, OTP, and magic-link signups may match an invitation by email only after that email has been verified. The first non-guest user can complete initial instance setup. | `false` |
+| `DISABLE_REGISTRATION` | Disable public user registration. When set to `true`, the sign-up option will not be shown on the sign-in page and new user creation is blocked (including via SSO). **Note:** Invited password signups must present the matching invitation link. OAuth, OTP, and magic-link signups may match an invitation by email only after that email has been verified. Sign-in emails (OTP codes and magic links) are only sent to existing accounts or pending invitations. The first non-guest user can complete initial instance setup. | `false` |
| `DISABLE_PASSWORD_REGISTRATION` | Disable local account creation through password, email OTP, magic link, and guest access. Existing accounts can still use email sign-in unless `DISABLE_LOGIN_FORM=true`. Social/OIDC registration remains available unless `DISABLE_REGISTRATION=true`. The initial administrator can still be created through password signup. | `false` |
| `DISABLE_EMAIL_OTP_SIGN_IN` | When SMTP is configured, sign-in uses email verification codes by default. Set to `true` to use email/password sign-in instead. Workspace invitation and password-reset emails still use SMTP. | `false` |
| `DISABLE_LOGIN_FORM` | Hide the email/password login form on the sign-in page. When set to `true`, only SSO/OAuth buttons are shown. Useful when you want to enforce authentication exclusively through an external identity provider. | `false` |
diff --git a/tests/api-integration/auth-registration-policy.test.ts b/tests/api-integration/auth-registration-policy.test.ts
index 609e88afc..4c7f8c0f2 100644
--- a/tests/api-integration/auth-registration-policy.test.ts
+++ b/tests/api-integration/auth-registration-policy.test.ts
@@ -6,6 +6,7 @@ import { createApp } from "../../apps/api/src/index";
import getInstanceStatus from "../../apps/api/src/instance/controllers/get-instance-status";
import { promoteInitialAdministrator } from "../../apps/api/src/utils/instance-bootstrap";
import { assertUserRegistrationAllowed } from "../../apps/api/src/utils/registration-policy";
+import { drainSignInEmails } from "../../apps/api/src/utils/sign-in-email-tasks";
import { resetTestDatabase } from "./helpers/database";
import { createWorkspaceMember } from "./helpers/fixtures";
@@ -13,16 +14,19 @@ const headers = {
"content-type": "application/json",
Origin: "http://localhost:5173",
};
-function post(
+async function post(
path: string,
body: unknown,
extraHeaders: Record<string, string> = {},
+ waitForEmail = true,
) {
- return createApp().app.request(`/api/auth${path}`, {
+ const response = await createApp().app.request(`/api/auth${path}`, {
method: "POST",
headers: { ...headers, ...extraHeaders },
body: JSON.stringify(body),
});
+ if (waitForEmail) await drainSignInEmails();
+ return response;
}
function signup(email: string, extraHeaders?: Record<string, string>) {
return post(
@@ -204,6 +208,9 @@ describe("auth registration and bootstrap boundaries", () => {
const member = await createWorkspaceMember();
vi.stubEnv("DISABLE_PASSWORD_REGISTRATION", "true");
const send = vi.spyOn(email, "sendOtpEmail").mockResolvedValue(undefined);
+ const sendMagicLink = vi
+ .spyOn(email, "sendMagicLinkEmail")
+ .mockResolvedValue(undefined);
for (const address of ["[email protected]", member.user.email]) {
expect(
(
@@ -213,17 +220,151 @@ describe("auth registration and bootstrap boundaries", () => {
})
).status,
).toBe(200);
- const data = send.mock.lastCall?.[2] as { otp: string } | undefined;
- expect(data?.otp).toBeTruthy();
- const response = await post("/sign-in/email-otp", {
- email: address,
- otp: data?.otp,
- });
- expect(response.status).toBe(address === member.user.email ? 200 : 403);
+ expect(
+ (await post("/sign-in/magic-link", { email: address })).status,
+ ).toBe(200);
}
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(send.mock.lastCall?.[0]).toBe(member.user.email);
+ expect(sendMagicLink).toHaveBeenCalledTimes(1);
+ expect(sendMagicLink.mock.lastCall?.[0]).toBe(member.user.email);
+ const data = send.mock.lastCall?.[2] as { otp: string } | undefined;
+ expect(data?.otp).toBeTruthy();
+ const response = await post("/sign-in/email-otp", {
+ email: member.user.email,
+ otp: data?.otp,
+ });
+ expect(response.status).toBe(200);
+ expect(await db.select().from(schema.userTable)).toHaveLength(1);
+ });
+
+ it("still emails the first user's OTP and magic link for initial setup when registration is disabled", async () => {
+ vi.stubEnv("DISABLE_REGISTRATION", "true");
+ const sendOtp = vi
+ .spyOn(email, "sendOtpEmail")
+ .mockResolvedValue(undefined);
+ const sendMagicLink = vi
+ .spyOn(email, "sendMagicLinkEmail")
+ .mockResolvedValue(undefined);
+
+ expect(
+ (
+ await post("/email-otp/send-verification-otp", {
+ email: "[email protected]",
+ type: "sign-in",
+ })
+ ).status,
+ ).toBe(200);
+ expect(
+ (await post("/sign-in/magic-link", { email: "[email protected]" }))
+ .status,
+ ).toBe(200);
+ expect(sendOtp.mock.calls.map((call) => call[0])).toEqual([
+ ]);
+ expect(sendMagicLink.mock.calls.map((call) => call[0])).toEqual([
+ ]);
+
+ const data = sendOtp.mock.lastCall?.[2] as { otp: string };
+ const response = await post("/sign-in/email-otp", {
+ email: "[email protected]",
+ otp: data.otp,
+ });
+ expect(response.status).toBe(200);
expect(await db.select().from(schema.userTable)).toHaveLength(1);
});
+ it("only emails sign-in OTPs and magic links to existing or invited addresses when registration is disabled", async () => {
+ const member = await createWorkspaceMember();
+ const invite = await invitation("[email protected]");
+ vi.stubEnv("DISABLE_REGISTRATION", "true");
+ const sendOtp = vi
+ .spyOn(email, "sendOtpEmail")
+ .mockResolvedValue(undefined);
+ const sendMagicLink = vi
+ .spyOn(email, "sendMagicLinkEmail")
+ .mockResolvedValue(undefined);
+
+ for (const address of [
+ member.user.email,
+ invite.email,
+ ]) {
+ expect(
+ (
+ await post("/email-otp/send-verification-otp", {
+ email: address,
+ type: "sign-in",
+ })
+ ).status,
+ ).toBe(200);
+ expect(
+ (await post("/sign-in/magic-link", { email: address })).status,
+ ).toBe(200);
+ }
+
+ const expectedRecipients = [invite.email, member.user.email].sort();
+ const recipients = (mock: {
+ mock: { calls: [to: string, subject: string, data: unknown][] };
+ }) => mock.mock.calls.map((call) => call[0]).sort();
+ expect(recipients(sendOtp)).toEqual(expectedRecipients);
+ expect(recipients(sendMagicLink)).toEqual(expectedRecipients);
+ });
+
+ it.each([
+ ["/email-otp/send-verification-otp", "sendOtpEmail"],
+ ["/sign-in/magic-link", "sendMagicLinkEmail"],
+ ] as const)(
+ "returns from %s without waiting for SMTP",
+ async (path, method) => {
+ const member = await createWorkspaceMember();
+ const invite = await invitation("[email protected]");
+ vi.stubEnv("DISABLE_REGISTRATION", "true");
+ let releaseDelivery!: () => void;
+ const blockedDelivery = new Promise<void>((resolve) => {
+ releaseDelivery = resolve;
+ });
+ const send = vi.spyOn(email, method).mockReturnValue(blockedDelivery);
+ const responses: { status: number; body: unknown }[] = [];
+ const requests: Promise<Response>[] = [];
+
+ try {
+ for (const address of [
+ member.user.email,
+ invite.email,
+ ]) {
+ const request = post(
+ path,
+ { email: address, type: "sign-in" },
+ {},
+ false,
+ );
+ requests.push(request);
+ void request.then(async (response) => {
+ responses.push({
+ status: response.status,
+ body: await response.json(),
+ });
+ });
+ }
+ // The SMTP promise stays unresolved until all three HTTP responses arrive.
+ await vi.waitFor(() => expect(responses).toHaveLength(3));
+ expect(responses[0].status).toBe(200);
+ expect(responses).toEqual([responses[0], responses[0], responses[0]]);
+ await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(2));
+ expect(send.mock.calls.map(([address]) => address).sort()).toEqual(
+ [member.user.email, invite.email].sort(),
+ );
+ } finally {
+ releaseDelivery();
+ await Promise.all(requests);
+ await drainSignInEmails();
+ }
+ },
+ );
+
it("stores a five-minute OTP expiry and rejects an expired code", async () => {
const member = await createWorkspaceMember();
const send = vi.spyOn(email, "sendOtpEmail").mockResolvedValue(undefined);
diff --git a/tests/api/utils/sign-in-email-tasks.test.ts b/tests/api/utils/sign-in-email-tasks.test.ts
new file mode 100644
index 000000000..cda92edee
--- /dev/null
+++ b/tests/api/utils/sign-in-email-tasks.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ drainSignInEmails,
+ queueSignInEmail,
+} from "../../../apps/api/src/utils/sign-in-email-tasks";
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe("background sign-in emails", () => {
+ it("returns before eligibility or delivery finishes and drains pending work", async () => {
+ let release!: () => void;
+ const deliver = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ }),
+ );
+ expect(queueSignInEmail(deliver)).toBeUndefined();
+ expect(deliver).not.toHaveBeenCalled();
+ await Promise.resolve();
+ expect(deliver).toHaveBeenCalledOnce();
+ let drained = false;
+ const draining = drainSignInEmails().then((complete) => {
+ drained = complete;
+ });
+ await Promise.resolve();
+ expect(drained).toBe(false);
+ release();
+ await draining;
+ expect(drained).toBe(true);
+ });
+
+ it.each([false, true])(
+ "handles delivery failures without logging sensitive details (sync: %s)",
+ async (sync) => {
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+ queueSignInEmail(() => {
+ const error = new Error(
+ "smtp-secret token=123456 [email protected]",
+ );
+ if (sync) throw error;
+ return Promise.reject(error);
+ });
+ expect(await drainSignInEmails()).toBe(true);
+ expect(log).toHaveBeenCalledExactlyOnceWith(
+ "Sign-in email delivery failed",
+ );
+ },
+ );
+
+ it("bounds shutdown waiting without discarding the pending send", async () => {
+ vi.useFakeTimers();
+ let release!: () => void;
+ queueSignInEmail(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ }),
+ );
+ const draining = drainSignInEmails(100);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(await draining).toBe(false);
+ release();
+ expect(await drainSignInEmails()).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});