Merge branch 'dev' into feat/internal-user-passkey-support

This commit is contained in:
Milo Schwartz
2025-07-14 17:43:01 -04:00
committed by GitHub
32 changed files with 1071 additions and 1123 deletions

View File

@@ -1,179 +0,0 @@
import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import HttpCode from "@server/types/HttpCode";
import { response } from "@server/lib";
import { db } from "@server/db";
import { twoFactorBackupCodes, users } from "@server/db";
import { eq, and } from "drizzle-orm";
import { alphabet, generateRandomString } from "oslo/crypto";
import { hashPassword, verifyPassword } from "@server/auth/password";
import { verifyTotpCode } from "@server/auth/totp";
import logger from "@server/logger";
import { sendEmail } from "@server/emails";
import TwoFactorAuthNotification from "@server/emails/templates/TwoFactorAuthNotification";
import config from "@server/lib/config";
import { UserType } from "@server/types/UserTypes";
export const completeTotpSetupBody = z
.object({
email: z.string().email(),
password: z.string(),
code: z.string()
})
.strict();
export type CompleteTotpSetupBody = z.infer<typeof completeTotpSetupBody>;
export type CompleteTotpSetupResponse = {
valid: boolean;
backupCodes?: string[];
};
export async function completeTotpSetup(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedBody = completeTotpSetupBody.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { email, password, code } = parsedBody.data;
try {
// Find the user by email
const [user] = await db
.select()
.from(users)
.where(and(eq(users.email, email), eq(users.type, UserType.Internal)))
.limit(1);
if (!user) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid credentials"
)
);
}
// Verify password
const validPassword = await verifyPassword(password, user.passwordHash!);
if (!validPassword) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid credentials"
)
);
}
// Check if 2FA is enabled but not yet completed
if (!user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is not required for this user"
)
);
}
if (!user.twoFactorSecret) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User has not started two-factor authentication setup"
)
);
}
// Verify the TOTP code
const valid = await verifyTotpCode(
code,
user.twoFactorSecret,
user.userId
);
if (!valid) {
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Two-factor authentication code is incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid two-factor authentication code"
)
);
}
// Generate backup codes and finalize setup
let codes: string[] = [];
await db.transaction(async (trx) => {
// Note: We don't set twoFactorEnabled to true here because it's already true
// We just need to generate backup codes since the setup is now complete
const backupCodes = await generateBackupCodes();
codes = backupCodes;
for (const code of backupCodes) {
const hash = await hashPassword(code);
await trx.insert(twoFactorBackupCodes).values({
userId: user.userId,
codeHash: hash
});
}
});
// Send notification email
sendEmail(
TwoFactorAuthNotification({
email: user.email!,
enabled: true
}),
{
to: user.email!,
from: config.getRawConfig().email?.no_reply,
subject: "Two-factor authentication enabled"
}
);
return response<CompleteTotpSetupResponse>(res, {
data: {
valid: true,
backupCodes: codes
},
success: true,
error: false,
message: "Two-factor authentication setup completed successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to complete two-factor authentication setup"
)
);
}
}
async function generateBackupCodes(): Promise<string[]> {
const codes = [];
for (let i = 0; i < 10; i++) {
const code = generateRandomString(6, alphabet("0-9", "A-Z", "a-z"));
codes.push(code);
}
return codes;
}

View File

@@ -3,8 +3,6 @@ export * from "./signup";
export * from "./logout";
export * from "./verifyTotp";
export * from "./requestTotpSecret";
export * from "./setupTotpSecret";
export * from "./completeTotpSetup";
export * from "./disable2fa";
export * from "./verifyEmail";
export * from "./requestEmailVerificationCode";

View File

@@ -21,10 +21,7 @@ import { UserType } from "@server/types/UserTypes";
export const loginBodySchema = z
.object({
email: z
.string()
.toLowerCase()
.email(),
email: z.string().toLowerCase().email(),
password: z.string(),
code: z.string().optional()
})
@@ -39,8 +36,6 @@ export type LoginResponse = {
twoFactorSetupRequired?: boolean;
};
export const dynamic = "force-dynamic";
export async function login(
req: Request,
res: Response,
@@ -127,18 +122,20 @@ export async function login(
});
}
if (existingUser.twoFactorEnabled) {
// If 2FA is enabled but no secret exists, force setup
if (!existingUser.twoFactorSecret) {
return response<LoginResponse>(res, {
data: { twoFactorSetupRequired: true },
success: true,
error: false,
message: "Two-factor authentication setup required",
status: HttpCode.ACCEPTED
});
}
if (
existingUser.twoFactorSetupRequested &&
!existingUser.twoFactorEnabled
) {
return response<LoginResponse>(res, {
data: { twoFactorSetupRequired: true },
success: true,
error: false,
message: "Two-factor authentication setup required",
status: HttpCode.ACCEPTED
});
}
if (existingUser.twoFactorEnabled) {
if (!code) {
return response<{ codeRequested: boolean }>(res, {
data: { codeRequested: true },
@@ -151,7 +148,7 @@ export async function login(
const validOTP = await verifyTotpCode(
code,
existingUser.twoFactorSecret,
existingUser.twoFactorSecret!,
existingUser.userId
);

View File

@@ -7,16 +7,19 @@ import HttpCode from "@server/types/HttpCode";
import { response } from "@server/lib";
import { db } from "@server/db";
import { User, users } from "@server/db";
import { eq } from "drizzle-orm";
import { eq, and } from "drizzle-orm";
import { createTOTPKeyURI } from "oslo/otp";
import logger from "@server/logger";
import { verifyPassword } from "@server/auth/password";
import { unauthorized } from "@server/auth/unauthorizedResponse";
import { UserType } from "@server/types/UserTypes";
import { verifySession } from "@server/auth/sessions/verifySession";
import config from "@server/lib/config";
export const requestTotpSecretBody = z
.object({
password: z.string()
password: z.string(),
email: z.string().email().optional()
})
.strict();
@@ -43,9 +46,42 @@ export async function requestTotpSecret(
);
}
const { password } = parsedBody.data;
const { password, email } = parsedBody.data;
const user = req.user as User;
const { user: sessionUser, session: existingSession } = await verifySession(req);
let user: User | null = sessionUser;
if (!existingSession) {
if (!email) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Email is required for two-factor authentication setup"
)
);
}
const [res] = await db
.select()
.from(users)
.where(
and(eq(users.type, UserType.Internal), eq(users.email, email))
);
user = res;
}
if (!user) {
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Username or password incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Username or password is incorrect"
)
);
}
if (user.type !== UserType.Internal) {
return next(
@@ -57,7 +93,10 @@ export async function requestTotpSecret(
}
try {
const validPassword = await verifyPassword(password, user.passwordHash!);
const validPassword = await verifyPassword(
password,
user.passwordHash!
);
if (!validPassword) {
return next(unauthorized());
}

View File

@@ -1,127 +0,0 @@
import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { encodeHex } from "oslo/encoding";
import HttpCode from "@server/types/HttpCode";
import { response } from "@server/lib";
import { db } from "@server/db";
import { User, users } from "@server/db";
import { eq, and } from "drizzle-orm";
import { createTOTPKeyURI } from "oslo/otp";
import logger from "@server/logger";
import { verifyPassword } from "@server/auth/password";
import { UserType } from "@server/types/UserTypes";
export const setupTotpSecretBody = z
.object({
email: z.string().email(),
password: z.string()
})
.strict();
export type SetupTotpSecretBody = z.infer<typeof setupTotpSecretBody>;
export type SetupTotpSecretResponse = {
secret: string;
uri: string;
};
export async function setupTotpSecret(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedBody = setupTotpSecretBody.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { email, password } = parsedBody.data;
try {
// Find the user by email
const [user] = await db
.select()
.from(users)
.where(and(eq(users.email, email), eq(users.type, UserType.Internal)))
.limit(1);
if (!user) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid credentials"
)
);
}
// Verify password
const validPassword = await verifyPassword(password, user.passwordHash!);
if (!validPassword) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid credentials"
)
);
}
// Check if 2FA is enabled but no secret exists (forced setup scenario)
if (!user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is not required for this user"
)
);
}
if (user.twoFactorSecret) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User has already completed two-factor authentication setup"
)
);
}
// Generate new TOTP secret
const hex = crypto.getRandomValues(new Uint8Array(20));
const secret = encodeHex(hex);
const uri = createTOTPKeyURI("Pangolin", user.email!, hex);
// Save the secret to the database
await db
.update(users)
.set({
twoFactorSecret: secret
})
.where(eq(users.userId, user.userId));
return response<SetupTotpSecretResponse>(res, {
data: {
secret,
uri
},
success: true,
error: false,
message: "TOTP secret generated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to generate TOTP secret"
)
);
}
}

View File

@@ -6,18 +6,22 @@ import HttpCode from "@server/types/HttpCode";
import { response } from "@server/lib";
import { db } from "@server/db";
import { twoFactorBackupCodes, User, users } from "@server/db";
import { eq } from "drizzle-orm";
import { alphabet, generateRandomString } from "oslo/crypto";
import { hashPassword } from "@server/auth/password";
import { eq, and } from "drizzle-orm";
import { hashPassword, verifyPassword } from "@server/auth/password";
import { verifyTotpCode } from "@server/auth/totp";
import logger from "@server/logger";
import { sendEmail } from "@server/emails";
import TwoFactorAuthNotification from "@server/emails/templates/TwoFactorAuthNotification";
import config from "@server/lib/config";
import { UserType } from "@server/types/UserTypes";
import { generateBackupCodes } from "@server/lib/totp";
import { verifySession } from "@server/auth/sessions/verifySession";
import { unauthorized } from "@server/auth/unauthorizedResponse";
export const verifyTotpBody = z
.object({
email: z.string().email().optional(),
password: z.string().optional(),
code: z.string()
})
.strict();
@@ -45,38 +49,83 @@ export async function verifyTotp(
);
}
const { code } = parsedBody.data;
const user = req.user as User;
if (user.type !== UserType.Internal) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is not supported for external users"
)
);
}
if (user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is already enabled"
)
);
}
if (!user.twoFactorSecret) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User has not requested two-factor authentication"
)
);
}
const { code, email, password } = parsedBody.data;
try {
const { user: sessionUser, session: existingSession } =
await verifySession(req);
let user: User | null = sessionUser;
if (!existingSession) {
if (!email || !password) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Email and password are required for two-factor authentication"
)
);
}
const [res] = await db
.select()
.from(users)
.where(
and(
eq(users.type, UserType.Internal),
eq(users.email, email)
)
);
user = res;
}
if (!user) {
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Username or password incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Username or password is incorrect"
)
);
}
const validPassword = await verifyPassword(
password,
user.passwordHash!
);
if (!validPassword) {
return next(unauthorized());
}
if (user.type !== UserType.Internal) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is not supported for external users"
)
);
}
if (user.twoFactorEnabled) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Two-factor authentication is already enabled"
)
);
}
if (!user.twoFactorSecret) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User has not requested two-factor authentication"
)
);
}
const valid = await verifyTotpCode(
code,
user.twoFactorSecret,
@@ -89,7 +138,9 @@ export async function verifyTotp(
await db.transaction(async (trx) => {
await trx
.update(users)
.set({ twoFactorEnabled: true })
.set({
twoFactorEnabled: true
})
.where(eq(users.userId, user.userId));
const backupCodes = await generateBackupCodes();
@@ -153,12 +204,3 @@ export async function verifyTotp(
);
}
}
async function generateBackupCodes(): Promise<string[]> {
const codes = [];
for (let i = 0; i < 10; i++) {
const code = generateRandomString(6, alphabet("0-9", "A-Z", "a-z"));
codes.push(code);
}
return codes;
}