Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
94f0a79
chore: add react react-dom axios to devDependencies for local test suite
Nov 16, 2026
66afb2c
feat(security): strengthen password policy and unify validation acros…
Nov 16, 2026
f8a287e
feat(security): separate JWT access and refresh secrets and add authM…
Nov 16, 2026
aa2a19e
fix(schema): de-duplicate createdAt and add hot-path indexes for emai…
Nov 16, 2026
8f200e6
feat(security): invalidate and rotate tokens on password change (clos…
Nov 16, 2026
0f189a7
docs: add comprehensive API reference, threat model, and llms.txt (cl…
Nov 16, 2026
77aacea
Merge branch 'feat/distinct-jwt-secrets-and-authmiddleware-tests' int…
Nov 16, 2026
2fa9544
Merge branch 'fix/schema-indexes-and-deduplication' into feat/unified…
Nov 16, 2026
781fae6
Merge branch 'feat/invalidate-tokens-on-password-change' into feat/un…
Nov 16, 2026
487f7a7
Merge branch 'docs/api-reference-threat-model-and-llms-txt' into feat…
Nov 16, 2026
8eb8d32
fix(schema): de-duplicate createdAt and add hot-path indexes for emai…
Nov 16, 2026
3a97f52
fix(schema): eliminate duplicate index declarations and verify unique…
Nov 17, 2026
910b02c
fix(frontend): align SetPasswordButton validation with password polic…
Nov 17, 2026
45e73a1
chore: sync schema index verification test in unified branch
Nov 17, 2026
4b19e69
Merge branch 'fix/strengthen-password-policy' into feat/unified-secur…
Nov 17, 2026
03f2761
fix(schema): remove duplicate index specifications and verify unique …
Nov 17, 2026
27b7f8d
feat(security): harden refresh-token rotation with hashed storage, re…
Nov 17, 2026
298db2b
test(security): mock session memory store in secretEnforcement to pre…
Nov 18, 2026
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ Stand up a secure backend with a single `createAuthBackend()` call, drop an `<Au
- [Frontend Components: `AuthStatus` vs. `AuthForm`](#frontend-components-authstatus-vs-authform)
- [Backend: `createAuthBackend`](#backend-createauthbackend)
- [Backend API Reference](#backend-api-reference)
- [Full API Reference Specification](docs/API_REFERENCE.md)
- [Threat Model & Security Posture](docs/THREAT_MODEL.md)
- [LLM & AI Integration Spec (`llms.txt`)](llms.txt)
- [Customization and Contributing](#customization-and-contributing)
- [Deployment and Troubleshooting](#deployment-and-troubleshooting)
- [Use Cases](#use-cases)
Expand Down
104 changes: 104 additions & 0 deletions backend/__tests__/authMiddleware.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const request = require('supertest');
const express = require('express');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
const authMiddleware = require('../middleware/auth');

describe('authMiddleware (Issue #19 & Issue #32)', () => {
const jwtSecret = 'test-distinct-access-secret-123';
const jwtRefreshSecret = 'test-distinct-refresh-secret-456';
let app;

beforeEach(() => {
app = express();
app.use(cookieParser());
app.locals.authConfig = {
jwtSecret,
jwtRefreshSecret
};

app.get('/api/protected', authMiddleware, (req, res) => {
res.json({
success: true,
user: req.user
});
});
});

it('allows access with a valid token in authToken cookie and attaches req.user', async () => {
const validToken = jwt.sign({ userId: 'user-789', role: 'admin' }, jwtSecret, { expiresIn: '15m' });
const res = await request(app)
.get('/api/protected')
.set('Cookie', [`authToken=${validToken}`]);

expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.user.userId).toBe('user-789');
expect(res.body.user.role).toBe('admin');
});

it('allows access with a valid token in Authorization Bearer header', async () => {
const validToken = jwt.sign({ userId: 'user-bearer-1', role: 'member' }, jwtSecret, { expiresIn: '15m' });
const res = await request(app)
.get('/api/protected')
.set('Authorization', `Bearer ${validToken}`);

expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.user.userId).toBe('user-bearer-1');
});

it('returns 401 when no token is provided', async () => {
const res = await request(app).get('/api/protected');

expect(res.statusCode).toBe(401);
expect(res.body.success).toBe(false);
expect(res.body.message).toMatch(/No token provided/i);
});

it('returns 401 when token is malformed', async () => {
const res = await request(app)
.get('/api/protected')
.set('Cookie', ['authToken=not-a-valid-jwt-token']);

expect(res.statusCode).toBe(401);
expect(res.body.success).toBe(false);
expect(res.body.message).toBe('Invalid token');
});

it('returns 401 when token is signed with a different secret', async () => {
const wrongSecretToken = jwt.sign({ userId: 'user-wrong' }, 'completely-wrong-secret');
const res = await request(app)
.get('/api/protected')
.set('Cookie', [`authToken=${wrongSecretToken}`]);

expect(res.statusCode).toBe(401);
expect(res.body.success).toBe(false);
expect(res.body.message).toBe('Invalid token');
});

it('returns 401 when token is expired', async () => {
const expiredToken = jwt.sign({ userId: 'user-expired' }, jwtSecret, { expiresIn: -10 });
const res = await request(app)
.get('/api/protected')
.set('Cookie', [`authToken=${expiredToken}`]);

expect(res.statusCode).toBe(401);
expect(res.body.success).toBe(false);
expect(res.body.message).toBe('Invalid token');
});

it('prevents refresh tokens from being accepted as access tokens (Issue #32)', async () => {
// Sign a refresh token with jwtRefreshSecret
const refreshToken = jwt.sign({ userId: 'user-refresh' }, jwtRefreshSecret, { expiresIn: '7d' });

// Attempt to access protected route with the refresh token
const res = await request(app)
.get('/api/protected')
.set('Cookie', [`authToken=${refreshToken}`]);

expect(res.statusCode).toBe(401);
expect(res.body.success).toBe(false);
expect(res.body.message).toBe('Invalid token');
});
});
122 changes: 122 additions & 0 deletions backend/__tests__/passwordPolicy.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
const request = require('supertest');
const express = require('express');
const session = require('express-session');

jest.mock('../models/User', () => {
const User = jest.fn();
User.findOne = jest.fn();
User.findById = jest.fn();
return User;
});
jest.mock('passport', () => ({
authenticate: jest.fn(() => (req, res, next) => next())
}));

const User = require('../models/User');
const authRoutes = require('../routes/auth');

describe('Password Policy & Credential Validation (Issue #38)', () => {
let app;
let mockUser;

beforeEach(() => {
jest.clearAllMocks();
mockUser = {
_id: 'user-123',
id: 'user-123',
setPassword: jest.fn().mockResolvedValue(undefined),
save: jest.fn().mockResolvedValue(undefined),
toJSON: () => ({ username: 'alice', email: 'alice@example.com' })
};
User.mockImplementation(() => mockUser);
User.findOne.mockResolvedValue(null);
User.findById.mockResolvedValue(mockUser);

app = express();
app.locals.authConfig = {
enableOAuth: false,
corsOrigin: 'https://app.example.com',
jwtSecret: 'test-access-secret',
jwtRefreshSecret: 'test-refresh-secret',
cookieMaxAge: 60000
};
app.use(express.json());
app.use(session({ secret: 'test-session-secret', resave: false, saveUninitialized: false }));
app.use((req, res, next) => {
req.isAuthenticated = () => true;
req.user = mockUser;
req.login = (u, cb) => cb();
next();
});
app.use('/api/auth', authRoutes);
});

describe('Signup Password Validation', () => {
it.each([
['too short (6 chars)', 'Pass1a'],
['too short (7 chars)', 'Pass1aa'],
['no uppercase', 'password123'],
['no lowercase', 'PASSWORD123'],
['no number', 'PasswordOnly']
])('rejects non-compliant password: %s', async (desc, password) => {
const res = await request(app)
.post('/api/auth/signup')
.send({
username: 'validuser',
email: 'valid@example.com',
password,
confirmPassword: password
});

expect(res.statusCode).toBe(400);
expect(res.body.success).toBe(false);
expect(res.body.errors).toEqual(
expect.arrayContaining([expect.objectContaining({ field: 'password' })])
);
expect(User.findOne).not.toHaveBeenCalled();
});

it('accepts compliant passwords with at least 8 chars, uppercase, lowercase, and digit', async () => {
const res = await request(app)
.post('/api/auth/signup')
.send({
username: 'validuser',
email: 'valid@example.com',
password: 'ValidPassword123',
confirmPassword: 'ValidPassword123'
});

expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
});
});

describe('Set-Password Validation', () => {
it.each([
['too short (<8 chars)', 'Short1'],
['no uppercase', 'weakpass123'],
['no number', 'NoDigitsHere']
])('rejects weak password on /set-password: %s', async (desc, password) => {
const res = await request(app)
.post('/api/auth/set-password')
.send({ password });

expect(res.statusCode).toBe(400);
expect(res.body.success).toBe(false);
expect(res.body.errors).toEqual(
expect.arrayContaining([expect.objectContaining({ field: 'password' })])
);
expect(mockUser.setPassword).not.toHaveBeenCalled();
});

it('successfully updates password when compliant', async () => {
const res = await request(app)
.post('/api/auth/set-password')
.send({ password: 'StrongNewPass123' });

expect(res.statusCode).toBe(200);
expect(res.body.success).toBe(true);
expect(mockUser.setPassword).toHaveBeenCalledWith('StrongNewPass123');
});
});
});
78 changes: 78 additions & 0 deletions backend/__tests__/secretEnforcement.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
const mongoose = require('mongoose');

jest.mock('connect-mongo', () => {
const session = require('express-session');
return {
create: jest.fn().mockImplementation(() => new session.MemoryStore())
};
});

const { createAuthBackend } = require('../index');

describe('Production Secrets Enforcement (Issue #33 & Issue #32)', () => {
const originalEnv = process.env.NODE_ENV;
let connectSpy;

beforeAll(() => {
connectSpy = jest.spyOn(mongoose, 'connect').mockResolvedValue(undefined);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

afterAll(async () => {
connectSpy.mockRestore();
await mongoose.disconnect();
});

afterEach(() => {
process.env.NODE_ENV = originalEnv;
});

it('allows default secrets in development mode', () => {
process.env.NODE_ENV = 'development';
expect(() => {
createAuthBackend({
mongoUri: 'mongodb://localhost:27017/test-dev'
});
}).not.toThrow();
});

it('throws an error in production if jwtSecret uses an insecure default', () => {
process.env.NODE_ENV = 'production';
expect(() => {
createAuthBackend({
jwtSecret: 'your-secret-key-change-in-production',
jwtRefreshSecret: 'a-secure-production-refresh-secret-12345'
});
}).toThrow(/Insecure default or empty jwtSecret/i);
});

it('throws an error in production if jwtRefreshSecret uses an insecure default', () => {
process.env.NODE_ENV = 'production';
expect(() => {
createAuthBackend({
jwtSecret: 'a-secure-production-access-secret-12345',
jwtRefreshSecret: 'your-secret-key-change-in-production'
});
}).toThrow(/Insecure default or empty jwtRefreshSecret/i);
});

it('throws an error in production if jwtSecret equals jwtRefreshSecret', () => {
process.env.NODE_ENV = 'production';
const sharedSecret = 'identical-secret-shared-across-both-tokens';
expect(() => {
createAuthBackend({
jwtSecret: sharedSecret,
jwtRefreshSecret: sharedSecret
});
}).toThrow(/jwtSecret and jwtRefreshSecret must be distinct/i);
});

it('succeeds in production with distinct, secure secrets', () => {
process.env.NODE_ENV = 'production';
expect(() => {
createAuthBackend({
jwtSecret: 'super-secure-production-access-key-abc-xyz',
jwtRefreshSecret: 'another-super-secure-production-refresh-key-123-789'
});
}).not.toThrow();
});
});
Loading