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
4 changes: 4 additions & 0 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { notifyRoutes } from "./routes/notify";
import { setupRoutes } from "./routes/setup";
import { handleScheduled } from "./services/scheduler";
import { getAllSettings } from "./db/queries/settings";
import { isEmailConfigured } from "./services/email";

const app = new Hono<HonoEnv>();

Expand Down Expand Up @@ -85,12 +86,15 @@ app.get("/api/system/info", async (c) => {
app_name: settings.app_name || "eNotify",
version: typeof APP_VERSION !== "undefined" ? APP_VERSION : "0.0.0",
registration_enabled: settings.registration_enabled !== "false",
email_configured: await isEmailConfigured(c.env),
});
} catch {
// Fail closed: never advertise an email entry point we cannot serve.
return c.json({
app_name: "eNotify",
version: typeof APP_VERSION !== "undefined" ? APP_VERSION : "0.0.0",
registration_enabled: true,
email_configured: false,
});
}
});
Expand Down
43 changes: 40 additions & 3 deletions worker/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { upsertNotificationConfig } from "../db/queries/notifications";
import { getSetting } from "../db/queries/settings";
import { get2FAConfig } from "../db/queries/twofa";
import { getAvailable2FAMethods } from "../services/twofa";
import { sendEmail } from "../services/email";
import { isEmailConfigured, sendEmail } from "../services/email";
import { rateLimit } from "../middleware/ratelimit";

export const authRoutes = new Hono<HonoEnv>();
Expand Down Expand Up @@ -171,7 +171,12 @@ authRoutes.post("/login", async (c) => {

const require2FA = await getSetting(c.env.DB, prefix, "require_2fa");
const twoFAConfig = await get2FAConfig(c.env.DB, prefix, user.id);
const methods = getAvailable2FAMethods(twoFAConfig);
// What the user actually enabled, and what we may offer right now: an
// unconfigured instance can never deliver an email code, so email_otp is
// filtered out of the offer (the switches themselves stay untouched).
const enabledMethods = getAvailable2FAMethods(twoFAConfig);
const emailConfigured = await isEmailConfigured(c.env);
const methods = getAvailable2FAMethods(twoFAConfig, { emailConfigured });

if (methods.length > 0) {
const tempToken = generateId();
Expand All @@ -183,6 +188,21 @@ authRoutes.post("/login", async (c) => {
});
}

// Fail closed: the user has 2FA enabled, but every method they enabled is
// unavailable right now (only email_otp, and email delivery is off). Never
// silently downgrade to password-only — that would let an admin switch off
// email sending and thereby switch off the user's second factor.
if (enabledMethods.length > 0) {
return c.json(
{
error:
"Your enabled two-factor method is currently unavailable (email delivery is not configured on this site). Please contact an administrator.",
code: "2FA_METHOD_UNAVAILABLE",
},
403,
);
}

if (require2FA === "true") {
await issueTokens(c, user.id, user.role, true);
return c.json({
Expand Down Expand Up @@ -267,7 +287,9 @@ authRoutes.post("/refresh", async (c) => {
let needs2faSetup = false;
if (require2FA === "true") {
const twoFAConfig = await get2FAConfig(c.env.DB, prefix, user.id);
needs2faSetup = getAvailable2FAMethods(twoFAConfig).length === 0;
const emailConfigured = await isEmailConfigured(c.env);
needs2faSetup =
getAvailable2FAMethods(twoFAConfig, { emailConfigured }).length === 0;
}

await issueTokens(c, user.id, user.role, needs2faSetup, payload.sid);
Expand Down Expand Up @@ -316,6 +338,21 @@ authRoutes.post("/password/forgot", async (c) => {
const { email } = await c.req.json<{ email: string }>();
if (!email) return c.json({ error: "Email required" }, 400);

// Site-level, already-public fact (see /api/system/info): when email
// delivery is not configured, no reset code can ever reach anyone. Answer
// identically for registered and unregistered addresses, before the
// cooldown and the user lookup, and write nothing to KV.
if (!(await isEmailConfigured(c.env))) {
return c.json(
{
error:
"Email delivery is not configured on this site, so password recovery by email is unavailable. Please contact an administrator to reset your password.",
code: "EMAIL_NOT_CONFIGURED",
},
503,
);
}

// Per-email cooldown: 60s between resend
// Check & set cooldown before user lookup to avoid email enumeration
const cooldownKey = `pwd_reset_cd:${email}`;
Expand Down
64 changes: 55 additions & 9 deletions worker/src/routes/auth2fa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
verifyEmailOTP,
sendOTPEmail,
} from "../services/twofa";
import { getSetting } from "../db/queries/settings";
import { isEmailConfigured } from "../services/email";
import { signJWT, generateId, generateJti, verifyPassword } from "../core/auth";
import { addSessionIndex } from "./auth";
import { setCookie } from "hono/cookie";
Expand Down Expand Up @@ -78,6 +78,19 @@ auth2faRoutes.post("/verify", async (c) => {
return c.json({ error: "2FA not configured" }, 400);
}

// Defence in depth: an old tempToken must not let anyone try email codes on
// an instance that cannot deliver them.
if (method === "email_otp" && !(await isEmailConfigured(c.env))) {
return c.json(
{
error:
"Email delivery is not configured on this site. Please contact an administrator.",
code: "EMAIL_NOT_CONFIGURED",
},
503,
);
}

let verified = false;

if (method === "totp" && config.totp_enabled && config.totp_secret) {
Expand Down Expand Up @@ -181,6 +194,18 @@ auth2faRoutes.post("/otp/send", async (c) => {
const { tempToken } = await c.req.json<{ tempToken: string }>();
if (!tempToken) return c.json({ error: "tempToken required" }, 400);

// Checked before the code is generated: no KV write, no send attempt.
if (!(await isEmailConfigured(c.env))) {
return c.json(
{
error:
"Email delivery is not configured on this site. Please contact an administrator.",
code: "EMAIL_NOT_CONFIGURED",
},
503,
);
}

const userId = await c.env.KV.get(`2fa:${tempToken}`);
if (!userId) return c.json({ error: "Invalid session" }, 401);

Expand Down Expand Up @@ -280,6 +305,18 @@ auth2faRoutes.post("/email-otp/send-verify", async (c) => {
const userId = c.get("userId");
const prefix = getTablePrefix(c.env);

// Checked before the code is generated: no KV write, no send attempt.
if (!(await isEmailConfigured(c.env))) {
return c.json(
{
error:
"Email delivery is not configured on this site. Please contact an administrator.",
code: "EMAIL_NOT_CONFIGURED",
},
503,
);
}

const user = await findUserById(c.env.DB, prefix, userId);
if (!user) return c.json({ error: "User not found" }, 404);

Expand All @@ -289,7 +326,9 @@ auth2faRoutes.post("/email-otp/send-verify", async (c) => {
return c.json({ success: true });
});

// Email OTP enable — requires verification code if email provider is configured
// Email OTP enable — requires the verification code, and email delivery must
// actually work. (An unconfigured instance used to let this through without a
// code, which is how users ended up with a method that can never log them in.)
auth2faRoutes.post("/email-otp/enable", async (c) => {
const userId = c.get("userId");
const prefix = getTablePrefix(c.env);
Expand All @@ -298,15 +337,22 @@ auth2faRoutes.post("/email-otp/enable", async (c) => {
.catch(() => ({ code: undefined }));
const code = body?.code;

const provider = await getSetting(c.env.DB, prefix, "email_provider");

if (provider && provider !== "none") {
if (!code) return c.json({ error: "Verification code required" }, 400);
const valid = await verifyEmailOTP(c.env, userId, code, "email_otp_setup");
if (!valid)
return c.json({ error: "Invalid or expired verification code" }, 400);
if (!(await isEmailConfigured(c.env))) {
return c.json(
{
error:
"Email delivery is not configured on this site. Please contact an administrator.",
code: "EMAIL_NOT_CONFIGURED",
},
503,
);
}

if (!code) return c.json({ error: "Verification code required" }, 400);
const valid = await verifyEmailOTP(c.env, userId, code, "email_otp_setup");
if (!valid)
return c.json({ error: "Invalid or expired verification code" }, 400);

await upsert2FAConfig(c.env.DB, prefix, userId, { email_otp_enabled: 1 });
return c.json({ success: true });
});
Expand Down
59 changes: 59 additions & 0 deletions worker/src/services/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,65 @@ interface ResendConfig {
from_name: string;
}

/**
* Single source of truth for "can this instance actually deliver email?".
*
* Every place that needs to know whether email sending is available must call
* this instead of reading `email_provider` / the provider config itself.
*
* The verdict mirrors the points where `sendEmail()` is guaranteed to fail:
* - provider unset or "none" → false
* - `resend` → `resend_config` must parse and carry a non-empty `api_key`
* - `smtp` → `smtp_config` must parse and carry a non-empty `host`
* - unparsable config or unknown provider → false
*
* Never throws: a broken setting must not break login / password recovery.
*/
export async function isEmailConfigured(env: Env): Promise<boolean> {
try {
const prefix = getTablePrefix(env);
const provider = await getSetting(env.DB, prefix, "email_provider");

if (!provider || provider === "none") return false;

if (provider === "resend") {
const config = await readJsonSetting<ResendConfig>(
env,
prefix,
"resend_config",
);
return Boolean(config?.api_key);
}

if (provider === "smtp") {
const config = await readJsonSetting<SMTPConfig>(
env,
prefix,
"smtp_config",
);
return Boolean(config?.host);
}

return false;
} catch {
return false;
}
}

async function readJsonSetting<T>(
env: Env,
prefix: string,
key: string,
): Promise<T | null> {
const raw = await getSetting(env.DB, prefix, key);
if (!raw) return null;
try {
return JSON.parse(raw) as T;
} catch {
return null;
}
}

export async function sendEmail(
env: Env,
options: EmailOptions,
Expand Down
15 changes: 13 additions & 2 deletions worker/src/services/twofa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,23 @@ export async function sendOTPEmail(
await sendEmail(env, { to: email, subject, html });
}

export function getAvailable2FAMethods(config: User2FA | null): string[] {
/**
* Projects the user's 2FA switches onto the methods login may offer.
*
* `emailConfigured` comes from `isEmailConfigured()`; pass it `false` and
* `email_otp` is dropped, because an unconfigured instance can never deliver
* the code. Leaving the option out keeps the raw switch view (no filtering).
*/
export function getAvailable2FAMethods(
config: User2FA | null,
options: { emailConfigured?: boolean } = {},
): string[] {
if (!config) return [];
const methods: string[] = [];
if (config.totp_enabled) methods.push("totp");
if (config.passkey_enabled) methods.push("passkey");
if (config.email_otp_enabled) methods.push("email_otp");
if (config.email_otp_enabled && options.emailConfigured !== false)
methods.push("email_otp");
return methods;
}

Expand Down
Loading
Loading