Skip to content
Open
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
64 changes: 63 additions & 1 deletion apps/public-api/src/__tests__/userAuth.email.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ jest.mock('@urbackend/common', () => {
getRefreshSession: jest.fn(),
persistRefreshSession: jest.fn().mockResolvedValue(undefined),
revokeSessionChain: jest.fn().mockResolvedValue(undefined),
checkLockout: jest.fn().mockResolvedValue({ locked: false, retryAfterSeconds: 0 }),
recordFailedAttempt: jest.fn().mockResolvedValue({ locked: false, retryAfterSeconds: 0, attempts: 1 }),
clearLockout: jest.fn().mockResolvedValue(undefined),
};
});

Expand All @@ -99,7 +102,7 @@ jest.mock('../utils/refreshToken', () => ({

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { redis, authEmailQueue, __mockModel: mockModel } = require('@urbackend/common');
const { redis, authEmailQueue, __mockModel: mockModel, checkLockout, recordFailedAttempt, clearLockout } = require('@urbackend/common');
const { issueAuthTokens } = require('../utils/refreshToken');
const controller = require('../controllers/userAuth.controller');

Expand Down Expand Up @@ -238,6 +241,8 @@ describe('Email Authentication Flow', () => {
type: 'verification'
}));

expect(clearLockout).toHaveBeenCalledWith('project_1', 'new@user.com');

expect(issueAuthTokens).toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
Expand Down Expand Up @@ -333,7 +338,9 @@ describe('Email Authentication Flow', () => {

await controller.login(req, res);

expect(checkLockout).toHaveBeenCalledWith('project_1', 'test@user.com');
expect(bcrypt.compare).toHaveBeenCalledWith('password123', 'hashed_pw');
expect(clearLockout).toHaveBeenCalledWith('project_1', 'test@user.com');
expect(issueAuthTokens).toHaveBeenCalled();
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
token: 'signed_access_token'
Expand All @@ -356,8 +363,62 @@ describe('Email Authentication Flow', () => {

await controller.login(req, res);

expect(recordFailedAttempt).toHaveBeenCalledWith('project_1', 'test@user.com');
expect(res.status).toHaveBeenCalledWith(400);
});

test('returns 423 when account is already locked', async () => {
const req = makeReq({
body: { email: 'test@user.com', password: 'password123' }
});
const res = makeRes();

checkLockout.mockResolvedValueOnce({ locked: true, retryAfterSeconds: 900 });

await controller.login(req, res);

expect(bcrypt.compare).not.toHaveBeenCalled();
expect(recordFailedAttempt).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(423);
});

test('returns 423 when failures reach lockout threshold', async () => {
const req = makeReq({
body: { email: 'test@user.com', password: 'wrongpassword' }
});
const res = makeRes();

mockModel.findOne.mockReturnValueOnce({
select: jest.fn().mockResolvedValueOnce({
_id: 'user_123',
password: 'hashed_pw'
})
});
bcrypt.compare.mockResolvedValueOnce(false);
recordFailedAttempt.mockResolvedValueOnce({ locked: true, retryAfterSeconds: 900, attempts: 5 });

await controller.login(req, res);

expect(res.status).toHaveBeenCalledWith(423);
});

test('user-not-found branch records attempt and returns 423 when lockout is reached', async () => {
const req = makeReq({
body: { email: 'missing@user.com', password: 'wrongpassword' }
});
const res = makeRes();

checkLockout.mockResolvedValueOnce({ locked: false, retryAfterSeconds: 0 });
mockModel.findOne.mockReturnValueOnce({
select: jest.fn().mockResolvedValueOnce(null)
});
recordFailedAttempt.mockResolvedValueOnce({ locked: true, retryAfterSeconds: 900, attempts: 5 });

await controller.login(req, res);

expect(recordFailedAttempt).toHaveBeenCalledWith('project_1', 'missing@user.com');
expect(res.status).toHaveBeenCalledWith(423);
});
});

describe('requestPasswordReset', () => {
Expand Down Expand Up @@ -458,6 +519,7 @@ describe('Email Authentication Flow', () => {
{ email: 'reset@user.com' },
{ $set: { password: 'hashed_pw' } }
);
expect(clearLockout).toHaveBeenCalledWith('project_1', 'reset@user.com');
expect(redis.del).toHaveBeenCalled();
expect(res.json).toHaveBeenCalled();
});
Expand Down
3 changes: 3 additions & 0 deletions apps/public-api/src/__tests__/userAuth.refresh.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ jest.mock('@urbackend/common', () => {
getConnection: jest.fn().mockResolvedValue({}),
getCompiledModel: jest.fn(() => mockModel),
__mockModel: mockModel,
checkLockout: jest.fn().mockResolvedValue({ locked: false, retryAfterSeconds: 0 }),
recordFailedAttempt: jest.fn().mockResolvedValue({ locked: false, retryAfterSeconds: 0, attempts: 1 }),
clearLockout: jest.fn().mockResolvedValue(undefined),
// session manager exports
getRefreshSession: jest.fn(),
persistRefreshSession: jest.fn().mockResolvedValue(undefined),
Expand Down
3 changes: 3 additions & 0 deletions apps/public-api/src/__tests__/userAuth.social.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ jest.mock('@urbackend/common', () => {
sanitize: jest.fn((value) => value),
getConnection: jest.fn().mockResolvedValue({}),
getCompiledModel: jest.fn(() => mockUsersModel),
checkLockout: jest.fn().mockResolvedValue({ locked: false, retryAfterSeconds: 0 }),
recordFailedAttempt: jest.fn().mockResolvedValue({ locked: false, retryAfterSeconds: 0, attempts: 1 }),
clearLockout: jest.fn().mockResolvedValue(undefined),
decrypt: jest.fn((encrypted) => {
if (!encrypted?.encrypted) return null;
if (encrypted.encrypted === 'github') return 'github_secret';
Expand Down
78 changes: 75 additions & 3 deletions apps/public-api/src/controllers/userAuth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const crypto = require('crypto');
const {redis} = require('@urbackend/common');
const {Project} = require('@urbackend/common');
const { authEmailQueue } = require('@urbackend/common');
const { checkLockout, recordFailedAttempt, clearLockout } = require('@urbackend/common');
const { AppError } = require('@urbackend/common');
const { getRefreshSession, persistRefreshSession, revokeSessionChain } = require('@urbackend/common');
const { loginSchema, userSignupSchema, resetPasswordSchema, onlyEmailSchema, verifyOtpSchema, changePasswordSchema, sanitize } = require('@urbackend/common');
const { getConnection } = require('@urbackend/common');
Expand Down Expand Up @@ -1004,6 +1006,13 @@ module.exports.signup = async (req, res) => {
// Model.create handles validation and default values
const result = await Model.create(newUserPayload);

try {
// Fail-open: if Redis is unavailable, do not block successful signup.
await clearLockout(String(project._id), normalizedEmail);
} catch (lockErr) {
console.error('[login-lockout] clearLockout failed after signup:', lockErr?.message || lockErr);
}

await redis.set(`project:${project._id}:otp:verification:${normalizedEmail}`, otp, 'EX', 300);
await setPublicOtpCooldown(project._id, normalizedEmail, 'verification');

Expand Down Expand Up @@ -1046,11 +1055,34 @@ module.exports.signup = async (req, res) => {
* Issues access and refresh tokens upon successful authentication.
* @route POST /api/userAuth/login
*/
module.exports.login = async (req, res) => {
module.exports.login = async (req, res, next) => {
const sendAuthError = (statusCode, message) => {
if (typeof next === 'function') {
return next(new AppError(statusCode, message));
}
// Fallback for direct responses: use the project's standard API envelope
return res.status(statusCode).json({ success: false, data: {}, message });
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const sendLockoutServiceError = (message = 'Login lockout service unavailable') => sendAuthError(503, message);

try {
const project = req.project;
const { email, password } = loginSchema.parse(req.body);
const normalizedEmail = email.toLowerCase().trim();
const projectId = String(project._id);

let lockStatus = { locked: false, retryAfterSeconds: 0 };
try {
lockStatus = await checkLockout(projectId, normalizedEmail);
} catch (lockErr) {
console.error('[login-lockout] checkLockout failed:', lockErr?.message || lockErr);
return sendLockoutServiceError();
}
Comment on lines +1075 to +1081

if (lockStatus.locked) {
return sendAuthError(423, `Account temporarily locked. Try again in ${lockStatus.retryAfterSeconds} seconds.`);
}

const usersColConfig = project.collections.find(c => c.name === 'users');
if (!usersColConfig) return res.status(404).json({ error: "Auth collection not found" });
Expand All @@ -1060,10 +1092,43 @@ module.exports.login = async (req, res) => {

const user = await Model.findOne({ email: normalizedEmail }).select('+password');

if (!user) return res.status(400).json({ error: "Invalid email or password" });
if (!user) {
let failedStatus = { locked: false, retryAfterSeconds: 0, attempts: 0 };
try {
failedStatus = await recordFailedAttempt(projectId, normalizedEmail);
} catch (attemptErr) {
console.error('[login-lockout] recordFailedAttempt failed (user missing):', attemptErr?.message || attemptErr);
return sendLockoutServiceError();
}

if (failedStatus.locked) {
return sendAuthError(423, `Account temporarily locked. Try again in ${failedStatus.retryAfterSeconds} seconds.`);
}
return sendAuthError(400, 'Invalid email or password');
}

const validPass = await bcrypt.compare(password, user.password);
if (!validPass) return res.status(400).json({ error: "Invalid email or password" });
if (!validPass) {
let failedStatus = { locked: false, retryAfterSeconds: 0, attempts: 0 };
try {
failedStatus = await recordFailedAttempt(projectId, normalizedEmail);
} catch (attemptErr) {
console.error('[login-lockout] recordFailedAttempt failed (invalid password):', attemptErr?.message || attemptErr);
return sendLockoutServiceError();
}

if (failedStatus.locked) {
return sendAuthError(423, `Account temporarily locked. Try again in ${failedStatus.retryAfterSeconds} seconds.`);
}
return sendAuthError(400, 'Invalid email or password');
}

try {
// Fail-open: if Redis is unavailable, do not block successful login.
await clearLockout(projectId, normalizedEmail);
} catch (clearErr) {
console.error('[login-lockout] clearLockout failed:', clearErr?.message || clearErr);
}

const issuedTokens = await issueAuthTokens({
project,
Expand Down Expand Up @@ -1389,6 +1454,13 @@ module.exports.resetPasswordUser = async (req, res) => {

if (result.matchedCount === 0) return res.status(404).json({ error: "User not found" });

try {
// Fail-open: if Redis is unavailable, do not block password recovery success.
await clearLockout(String(project._id), normalizedEmail);
} catch (lockErr) {
console.error('[login-lockout] clearLockout failed after password reset:', lockErr?.message || lockErr);
}

await redis.del(redisKey);
res.json({ message: "Password updated successfully" });

Expand Down
18 changes: 7 additions & 11 deletions packages/common/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,8 @@ const {
initWebhookWorker,
generateSignature,
} = require("./queues/webhookQueue");
const {
activityRollupQueue,
scheduleActivityRollup,
initActivityRollupWorker,
} = require("./queues/activityRollupQueue");
const {
reliabilityAlertQueue,
scheduleReliabilityAlert,
initReliabilityAlertWorker,
} = require("./queues/reliabilityAlertQueue");
const { activityRollupQueue, scheduleActivityRollup, initActivityRollupWorker } = require('./queues/activityRollupQueue');
const { reliabilityAlertQueue, scheduleReliabilityAlert, initReliabilityAlertWorker } = require('./queues/reliabilityAlertQueue');

// Middleware
const checkAuthEnabled = require('./middleware/checkAuthEnabled')
Expand Down Expand Up @@ -106,6 +98,7 @@ const { validateData, validateUpdateData } = require("./utils/validateData");
const sessionManager = require("./utils/session.manager");
const planLimits = require("./utils/planLimits");
const AppError = require("./utils/AppError");
const { checkLockout, recordFailedAttempt, clearLockout } = require("./utils/loginLockout");

module.exports = {
connectDB,
Expand Down Expand Up @@ -190,7 +183,6 @@ module.exports = {
AppError,
getPresignedUploadUrl,
verifyUploadedFile,
ApiAnalytics,
PlatformEvent,
DeveloperActivity,
activityRollupQueue,
Expand All @@ -199,4 +191,8 @@ module.exports = {
reliabilityAlertQueue,
scheduleReliabilityAlert,
initReliabilityAlertWorker,
ApiAnalytics,
checkLockout,
recordFailedAttempt,
clearLockout,
};
Loading
Loading