From 94f0a790f527f7f246481115a8f497b97dae4561 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Mon, 16 Nov 2026 20:55:34 +0530 Subject: [PATCH 01/12] chore: add react react-dom axios to devDependencies for local test suite --- package-lock.json | 137 ++++++++-------------------------------------- package.json | 26 +++++++-- 2 files changed, 43 insertions(+), 120 deletions(-) diff --git a/package-lock.json b/package-lock.json index dd71e9d..10e6b7a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -30,12 +30,15 @@ "@babel/core": "^7.23.9", "@babel/preset-env": "^7.23.9", "@babel/preset-react": "^7.23.9", + "axios": "^1.21.1", "eslint": "^8.56.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-react": "^7.37.5", "husky": "^8.0.0", "jest": "^29.7.0", "prettier": "^3.2.5", + "react": "^19.3.1", + "react-dom": "^19.3.1", "supertest": "^7.0.0" }, "engines": { @@ -2554,6 +2557,7 @@ "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.6.3.tgz", "integrity": "sha512-aHGFvT95c82CoQ7hb6qXpz8Hcc5PJb3ZtQ+P01QDBbyQday0mjcrJPeNJOHCgWe0pGX0zKmKP+1mWi/I/BCX9Q==", "license": "MIT", + "optional": true, "dependencies": { "sparse-bitfield": "^3.0.3" } @@ -2758,16 +2762,6 @@ "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", "license": "MIT" }, - "node_modules/@types/whatwg-url": { - "version": "11.0.5", - "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz", - "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "@types/webidl-conversions": "*" - } - }, "node_modules/@types/yargs": { "version": "17.0.35", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", @@ -2832,8 +2826,8 @@ "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, "license": "MIT", - "peer": true, "dependencies": { "debug": "4" }, @@ -3099,6 +3093,7 @@ "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, "license": "MIT" }, "node_modules/available-typed-arrays": { @@ -3121,8 +3116,8 @@ "version": "1.21.1", "resolved": "https://registry.npmjs.org/axios/-/axios-1.21.1.tgz", "integrity": "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==", + "dev": true, "license": "MIT", - "peer": true, "dependencies": { "follow-redirects": "^1.16.2", "form-data": "^4.0.6", @@ -3454,16 +3449,6 @@ "node-int64": "^0.4.0" } }, - "node_modules/bson": { - "version": "6.10.4", - "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz", - "integrity": "sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==", - "license": "Apache-2.0", - "peer": true, - "engines": { - "node": ">=16.20.1" - } - }, "node_modules/buffer-equal-constant-time": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", @@ -3708,6 +3693,7 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, "license": "MIT", "dependencies": { "delayed-stream": "~1.0.0" @@ -4037,6 +4023,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=0.4.0" @@ -4346,6 +4333,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -5010,6 +4998,7 @@ "version": "1.16.3", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", + "dev": true, "funding": [ { "type": "individual", @@ -5017,7 +5006,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=4.0" }, @@ -5047,6 +5035,7 @@ "version": "4.0.6", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", @@ -5438,6 +5427,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, "license": "MIT", "dependencies": { "has-symbols": "^1.0.3" @@ -5492,8 +5482,8 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, "license": "MIT", - "peer": true, "dependencies": { "agent-base": "6", "debug": "4" @@ -7290,7 +7280,8 @@ "version": "1.5.0", "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", - "license": "MIT" + "license": "MIT", + "optional": true }, "node_modules/merge-descriptors": { "version": "1.0.3", @@ -7387,64 +7378,6 @@ "node": "*" } }, - "node_modules/mongodb": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.22.0.tgz", - "integrity": "sha512-k9YPpPXZEVyT4kjglCen99LCDToxzM+R89x3cMp8kSWb1gnXDvrsEJQh3FQ4t4jS9+ZA4yBOojHNS1oAB5qwQg==", - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "@mongodb-js/saslprep": "^1.3.0", - "bson": "^6.10.4", - "mongodb-connection-string-url": "^3.0.2" - }, - "engines": { - "node": ">=16.20.1" - }, - "peerDependencies": { - "@aws-sdk/credential-providers": "^3.188.0", - "@mongodb-js/zstd": "^1.1.0 || ^2.0.0", - "gcp-metadata": "^5.2.0", - "kerberos": "^2.0.1", - "mongodb-client-encryption": ">=6.0.0 <7", - "snappy": "^7.3.2", - "socks": "^2.7.1" - }, - "peerDependenciesMeta": { - "@aws-sdk/credential-providers": { - "optional": true - }, - "@mongodb-js/zstd": { - "optional": true - }, - "gcp-metadata": { - "optional": true - }, - "kerberos": { - "optional": true - }, - "mongodb-client-encryption": { - "optional": true - }, - "snappy": { - "optional": true - }, - "socks": { - "optional": true - } - } - }, - "node_modules/mongodb-connection-string-url": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.2.tgz", - "integrity": "sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==", - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "@types/whatwg-url": "^11.0.2", - "whatwg-url": "^14.1.0 || ^13.0.0" - } - }, "node_modules/mongoose": { "version": "7.8.13", "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-7.8.13.tgz", @@ -8302,8 +8235,8 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" } @@ -8408,8 +8341,8 @@ "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -8418,8 +8351,8 @@ "version": "19.3.1", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "dev": true, "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.28.0" }, @@ -8762,8 +8695,8 @@ "version": "0.28.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", - "license": "MIT", - "peer": true + "dev": true, + "license": "MIT" }, "node_modules/semver": { "version": "6.3.2", @@ -9059,6 +8992,7 @@ "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", "license": "MIT", + "optional": true, "dependencies": { "memory-pager": "^1.0.2" } @@ -9443,19 +9377,6 @@ "node": ">=0.6" } }, - "node_modules/tr46": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", - "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", - "license": "MIT", - "peer": true, - "dependencies": { - "punycode": "^2.3.1" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -9771,20 +9692,6 @@ "node": ">=12" } }, - "node_modules/whatwg-url": { - "version": "14.2.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", - "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", - "license": "MIT", - "peer": true, - "dependencies": { - "tr46": "^5.1.0", - "webidl-conversions": "^7.0.0" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index 98387b3..feeb926 100644 --- a/package.json +++ b/package.json @@ -38,9 +38,22 @@ }, "jest": { "transform": { - "^.+\\.jsx?$": ["babel-jest", { - "presets": [["@babel/preset-env", { "targets": { "node": "current" } }], "@babel/preset-react"] - }] + "^.+\\.jsx?$": [ + "babel-jest", + { + "presets": [ + [ + "@babel/preset-env", + { + "targets": { + "node": "current" + } + } + ], + "@babel/preset-react" + ] + } + ] }, "testPathIgnorePatterns": [ "/node_modules/", @@ -88,21 +101,24 @@ "zod": "^3.22.2" }, "peerDependencies": { + "axios": "^1.0.0", "react": ">=16.8.0", - "react-dom": ">=16.8.0", - "axios": "^1.0.0" + "react-dom": ">=16.8.0" }, "devDependencies": { "@babel/cli": "^7.23.9", "@babel/core": "^7.23.9", "@babel/preset-env": "^7.23.9", "@babel/preset-react": "^7.23.9", + "axios": "^1.21.1", "eslint": "^8.56.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-react": "^7.37.5", "husky": "^8.0.0", "jest": "^29.7.0", "prettier": "^3.2.5", + "react": "^19.3.1", + "react-dom": "^19.3.1", "supertest": "^7.0.0" }, "engines": { From 66afb2c10ed3b574843fb401006d9082d1e54ff8 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Mon, 16 Nov 2026 21:02:38 +0530 Subject: [PATCH 02/12] feat(security): strengthen password policy and unify validation across routes (closes #38) --- backend/__tests__/passwordPolicy.test.js | 122 +++++++++++++++++++++++ backend/models/User.js | 2 +- backend/routes/auth.js | 23 ++--- 3 files changed, 134 insertions(+), 13 deletions(-) create mode 100644 backend/__tests__/passwordPolicy.test.js diff --git a/backend/__tests__/passwordPolicy.test.js b/backend/__tests__/passwordPolicy.test.js new file mode 100644 index 0000000..980e1a4 --- /dev/null +++ b/backend/__tests__/passwordPolicy.test.js @@ -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'); + }); + }); +}); diff --git a/backend/models/User.js b/backend/models/User.js index 1803014..ea56643 100644 --- a/backend/models/User.js +++ b/backend/models/User.js @@ -22,7 +22,7 @@ const userSchema = new mongoose.Schema({ required: function() { return !this.googleId && !this.githubId; // Only required if not using OAuth }, - minlength: 6 + minlength: 8 }, refreshToken: { type: String diff --git a/backend/routes/auth.js b/backend/routes/auth.js index 9d9c8c7..275816a 100644 --- a/backend/routes/auth.js +++ b/backend/routes/auth.js @@ -8,6 +8,11 @@ const User = require('../models/User'); const router = express.Router(); // Validation schemas +const passwordComplexityRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/; +const passwordSchema = z.string() + .min(8, 'Password must be at least 8 characters long') + .regex(passwordComplexityRegex, 'Password must contain at least one uppercase letter, one lowercase letter, and one number'); + const signupSchema = z.object({ username: z.string() .min(3, 'Username must be at least 3 characters') @@ -15,15 +20,17 @@ const signupSchema = z.object({ .regex(/^[a-zA-Z0-9_]+$/, 'Username can only contain letters, numbers, and underscores'), email: z.string() .email('Please enter a valid email address'), - password: z.string() - .min(6, 'Password must be at least 6 characters') - .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, 'Password must contain at least one uppercase letter, one lowercase letter, and one number'), + password: passwordSchema, confirmPassword: z.string() }).refine((data) => data.password === data.confirmPassword, { message: "Passwords don't match", path: ["confirmPassword"] }); +const setPasswordSchema = z.object({ + password: passwordSchema +}); + const signinSchema = z.object({ // Existing accounts may use addresses accepted by the earlier signup rules. email: z.string().min(1, 'Email is required'), @@ -140,18 +147,10 @@ const isAuthenticated = (req, res, next) => { }; // Set password route for OAuth users -router.post('/set-password', isAuthenticated, async (req, res) => { +router.post('/set-password', isAuthenticated, validateBody(setPasswordSchema), async (req, res) => { try { const { password } = req.body; - if (!password || password.length < 6) { - return res.status(400).json({ - success: false, - message: 'Password must be at least 6 characters long', - errors: [{ field: 'password', message: 'Password must be at least 6 characters long' }] - }); - } - // Get the current user const user = await User.findById(req.user.id); if (!user) { From f8a287e420fe1987630c7fa85b3c3cd1fb112eeb Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Mon, 16 Nov 2026 21:07:52 +0530 Subject: [PATCH 03/12] feat(security): separate JWT access and refresh secrets and add authMiddleware tests (closes #19, #32, #33) --- backend/__tests__/authMiddleware.test.js | 104 +++++++++++++++++ backend/__tests__/secretEnforcement.test.js | 69 ++++++++++++ backend/index.js | 38 ++++++- backend/middleware/auth.js | 8 +- package-lock.json | 117 +++++++++++++++++++- package.json | 1 + 6 files changed, 325 insertions(+), 12 deletions(-) create mode 100644 backend/__tests__/authMiddleware.test.js create mode 100644 backend/__tests__/secretEnforcement.test.js diff --git a/backend/__tests__/authMiddleware.test.js b/backend/__tests__/authMiddleware.test.js new file mode 100644 index 0000000..3819f4d --- /dev/null +++ b/backend/__tests__/authMiddleware.test.js @@ -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'); + }); +}); diff --git a/backend/__tests__/secretEnforcement.test.js b/backend/__tests__/secretEnforcement.test.js new file mode 100644 index 0000000..255811e --- /dev/null +++ b/backend/__tests__/secretEnforcement.test.js @@ -0,0 +1,69 @@ +const mongoose = require('mongoose'); +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); + }); + + afterAll(() => { + connectSpy.mockRestore(); + }); + + 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(); + }); +}); diff --git a/backend/index.js b/backend/index.js index e0b38ed..60efa41 100644 --- a/backend/index.js +++ b/backend/index.js @@ -15,19 +15,45 @@ const User = require(path.join(__dirname, 'models', 'User')); require('dotenv').config(); +const INSECURE_SECRETS = [ + 'your-secret-key-change-in-production', + 'your-secret-key', + 'your-jwt-secret', + 'dimsee-dev-access-token-secret-change-in-production', + 'dimsee-dev-refresh-token-secret-change-in-production', + 'secret', + 'changeme' +]; + +const validateProductionSecrets = (jwtSecret, jwtRefreshSecret) => { + if (process.env.NODE_ENV === 'production') { + if (!jwtSecret || INSECURE_SECRETS.includes(jwtSecret)) { + throw new Error('Dimsee: Insecure default or empty jwtSecret detected in production. You must configure a secure secret.'); + } + if (!jwtRefreshSecret || INSECURE_SECRETS.includes(jwtRefreshSecret)) { + throw new Error('Dimsee: Insecure default or empty jwtRefreshSecret detected in production. You must configure a secure secret.'); + } + if (jwtSecret === jwtRefreshSecret) { + throw new Error('Dimsee: jwtSecret and jwtRefreshSecret must be distinct to prevent refresh tokens being used as access tokens.'); + } + } +}; + const createAuthBackend = (config = {}) => { const { - mongoUri = 'mongodb://localhost:27017/mern-auth', - jwtSecret = 'your-secret-key-change-in-production', - jwtExpiry = '15m', //your-expiry-for-access-token-ideal-set-it-to-15m', - jwtRefreshSecret = 'your-secret-key-change-in-production', - jwtRefreshExpiry = '7d', //'your-expiry-for-refresh-token-ideal-set-it-to-7d', - corsOrigin = 'http://localhost:5173', + mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/mern-auth', + jwtSecret = process.env.JWT_SECRET || 'dimsee-dev-access-token-secret-change-in-production', + jwtExpiry = '15m', + jwtRefreshSecret = process.env.JWT_REFRESH_SECRET || 'dimsee-dev-refresh-token-secret-change-in-production', + jwtRefreshExpiry = '7d', + corsOrigin = process.env.FRONTEND_URL || 'http://localhost:5173', cookieMaxAge = 7 * 24 * 60 * 60 * 1000, // 7 days enableOAuth = false, // OAuth disabled by default oauth = {} } = config; + validateProductionSecrets(jwtSecret, jwtRefreshSecret); + // Connect to MongoDB using mongoUri from props mongoose.connect(mongoUri) .then(() => console.log('MongoDB connected successfully')) diff --git a/backend/middleware/auth.js b/backend/middleware/auth.js index 227f798..2b4b26c 100644 --- a/backend/middleware/auth.js +++ b/backend/middleware/auth.js @@ -2,12 +2,16 @@ const jwt = require('jsonwebtoken'); // Express middleware that protects a route by verifying the `authToken` cookie -// against the app's configured JWT secret. Attach it directly: +// or Authorization Bearer header against the app's configured JWT secret. Attach it directly: // app.get('/private', authMiddleware, handler) function authMiddleware(req, res, next) { try { const jwtSecret = req.app?.locals?.authConfig?.jwtSecret; - const token = req.cookies?.authToken; + let token = req.cookies?.authToken; + + if (!token && req.headers?.authorization?.startsWith('Bearer ')) { + token = req.headers.authorization.substring(7).trim(); + } if (!token) { return res.status(401).json({ diff --git a/package-lock.json b/package-lock.json index 10e6b7a..df283e1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,6 +36,7 @@ "eslint-plugin-react": "^7.37.5", "husky": "^8.0.0", "jest": "^29.7.0", + "mongodb": "^7.9.0", "prettier": "^3.2.5", "react": "^19.3.1", "react-dom": "^19.3.1", @@ -2556,8 +2557,8 @@ "version": "1.6.3", "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.6.3.tgz", "integrity": "sha512-aHGFvT95c82CoQ7hb6qXpz8Hcc5PJb3ZtQ+P01QDBbyQday0mjcrJPeNJOHCgWe0pGX0zKmKP+1mWi/I/BCX9Q==", + "devOptional": true, "license": "MIT", - "optional": true, "dependencies": { "sparse-bitfield": "^3.0.3" } @@ -2762,6 +2763,16 @@ "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==", "license": "MIT" }, + "node_modules/@types/whatwg-url": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-13.0.0.tgz", + "integrity": "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/webidl-conversions": "*" + } + }, "node_modules/@types/yargs": { "version": "17.0.35", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", @@ -3449,6 +3460,16 @@ "node-int64": "^0.4.0" } }, + "node_modules/bson": { + "version": "7.3.4", + "resolved": "https://registry.npmjs.org/bson/-/bson-7.3.4.tgz", + "integrity": "sha512-eb33j2Ha6xgygjJ8bhI3sYaI9cLAbSaopZLRJQ5/rxk32XyBSoVVcbeHIzVGJx1SyQpyyoElkoEZgQrg+RVVoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=20.19.0" + } + }, "node_modules/buffer-equal-constant-time": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", @@ -7280,8 +7301,8 @@ "version": "1.5.0", "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", - "license": "MIT", - "optional": true + "devOptional": true, + "license": "MIT" }, "node_modules/merge-descriptors": { "version": "1.0.3", @@ -7378,6 +7399,67 @@ "node": "*" } }, + "node_modules/mongodb": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.9.0.tgz", + "integrity": "sha512-HfpNb8qmfmNxno+Ml5JgHn/nyshK+8xF4ESLCXedRKuGLGRyAvkjcpjk19T2Q+rqC6/FlnZKll4if21R6xs/Tg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@mongodb-js/saslprep": "^1.5.0", + "bson": "^7.3.2", + "mongodb-connection-string-url": "^7.0.2" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.806.0", + "@mongodb-js/zstd": "^7.0.0", + "gcp-metadata": "^7.0.1", + "kerberos": "^7.0.0", + "mongodb-client-encryption": "^7.2.0", + "snappy": "^7.3.2", + "socks": "^2.8.6" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "@mongodb-js/zstd": { + "optional": true + }, + "gcp-metadata": { + "optional": true + }, + "kerberos": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + }, + "socks": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-7.0.2.tgz", + "integrity": "sha512-ZoS07RoFqpKYQwAk59qmrx8+jJHNHU30UjlU96QktiGn1ltvDr+vCznLX5DiUBLEpMAHatHNWV1nM/74ul66kA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/whatwg-url": "^13.0.0", + "whatwg-url": "^14.1.0" + }, + "engines": { + "node": ">=20.19.0" + } + }, "node_modules/mongoose": { "version": "7.8.13", "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-7.8.13.tgz", @@ -8991,8 +9073,8 @@ "version": "3.0.3", "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==", + "devOptional": true, "license": "MIT", - "optional": true, "dependencies": { "memory-pager": "^1.0.2" } @@ -9377,6 +9459,19 @@ "node": ">=0.6" } }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -9692,6 +9787,20 @@ "node": ">=12" } }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index feeb926..2235da7 100644 --- a/package.json +++ b/package.json @@ -116,6 +116,7 @@ "eslint-plugin-react": "^7.37.5", "husky": "^8.0.0", "jest": "^29.7.0", + "mongodb": "^7.9.0", "prettier": "^3.2.5", "react": "^19.3.1", "react-dom": "^19.3.1", From aa2a19e4aea3481fdb254721bc591177faed05a8 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Mon, 16 Nov 2026 21:09:30 +0530 Subject: [PATCH 04/12] fix(schema): de-duplicate createdAt and add hot-path indexes for email, username, and refreshToken (closes #15, #92) --- backend/__tests__/userSchema.test.js | 42 ++++++++++++++++++++++++++++ backend/models/User.js | 24 +++++++++++----- 2 files changed, 59 insertions(+), 7 deletions(-) create mode 100644 backend/__tests__/userSchema.test.js diff --git a/backend/__tests__/userSchema.test.js b/backend/__tests__/userSchema.test.js new file mode 100644 index 0000000..5e56905 --- /dev/null +++ b/backend/__tests__/userSchema.test.js @@ -0,0 +1,42 @@ +const User = require('../models/User'); + +describe('User Schema Verification (Issue #15 & Issue #92)', () => { + it('has timestamps enabled in schema options without manual createdAt duplicate', () => { + expect(User.schema.options.timestamps).toBe(true); + expect(User.schema.paths.createdAt).toBeDefined(); + expect(User.schema.paths.updatedAt).toBeDefined(); + // Verify that createdAt is handled by Mongoose timestamps, not custom default + expect(User.schema.paths.createdAt.defaultValue).toBeUndefined(); + }); + + it('declares indexes on hot paths: email, username, and refreshToken (Issue #92)', () => { + const indexes = User.schema.indexes(); + const indexedFieldNames = indexes.map(([fields]) => Object.keys(fields)).flat(); + + // Check individual indexed paths or schema indexes + expect(indexedFieldNames).toContain('email'); + expect(indexedFieldNames).toContain('username'); + expect(indexedFieldNames).toContain('refreshToken'); + }); + + it('omits password from JSON representation', () => { + const user = new User({ + username: 'johndoe', + email: 'john@example.com', + password: 'SamplePassword123' + }); + + const json = user.toJSON(); + expect(json.password).toBeUndefined(); + expect(json.username).toBe('johndoe'); + expect(json.email).toBe('john@example.com'); + }); + + it('provides canUsePasswordLogin helper based on hasPassword state', () => { + const localUser = new User({ hasPassword: true }); + expect(localUser.canUsePasswordLogin()).toBe(true); + + const oauthUser = new User({ hasPassword: false }); + expect(oauthUser.canUsePasswordLogin()).toBe(false); + }); +}); diff --git a/backend/models/User.js b/backend/models/User.js index 1803014..3fef7d3 100644 --- a/backend/models/User.js +++ b/backend/models/User.js @@ -25,10 +25,19 @@ const userSchema = new mongoose.Schema({ minlength: 6 }, refreshToken: { - type: String + type: String, + index: true }, // For refreshtokens to generate new accesstokens - googleId: String, - githubId: String, + googleId: { + type: String, + sparse: true, + index: true + }, + githubId: { + type: String, + sparse: true, + index: true + }, authMethod: { type: String, enum: ['local', 'google', 'github'], @@ -37,15 +46,16 @@ const userSchema = new mongoose.Schema({ hasPassword: { type: Boolean, default: true - }, - createdAt: { - type: Date, - default: Date.now } }, { timestamps: true }); +// Explicit compound / single indexes for hot path queries +userSchema.index({ email: 1 }); +userSchema.index({ username: 1 }); +userSchema.index({ refreshToken: 1 }); + // Hash password before saving userSchema.pre('save', async function(next) { if (this.isModified('password') && this.password) { From 8f200e6fdce1f9468128ab6fb1a4fc0e0bfb8ba5 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Mon, 16 Nov 2026 21:11:17 +0530 Subject: [PATCH 05/12] feat(security): invalidate and rotate tokens on password change (closes #35) --- backend/__tests__/sessionRevocation.test.js | 107 ++++++++++++++++++++ backend/models/User.js | 1 + backend/routes/auth.js | 5 +- 3 files changed, 112 insertions(+), 1 deletion(-) create mode 100644 backend/__tests__/sessionRevocation.test.js diff --git a/backend/__tests__/sessionRevocation.test.js b/backend/__tests__/sessionRevocation.test.js new file mode 100644 index 0000000..09419d6 --- /dev/null +++ b/backend/__tests__/sessionRevocation.test.js @@ -0,0 +1,107 @@ +const request = require('supertest'); +const express = require('express'); +const cookieParser = require('cookie-parser'); +const session = require('express-session'); +const jwt = require('jsonwebtoken'); + +jest.mock('../models/User', () => { + const User = jest.fn(); + User.findById = jest.fn(); + return User; +}); + +const User = require('../models/User'); +const authRoutes = require('../routes/auth'); + +describe('Session & Token Invalidation on Password Set (Issue #35)', () => { + let app; + let mockUser; + const oldRefreshToken = 'old-stale-refresh-token-prior-to-change'; + + beforeEach(() => { + jest.clearAllMocks(); + mockUser = { + _id: 'user-456', + id: 'user-456', + refreshToken: oldRefreshToken, + setPassword: jest.fn(async function(pwd) { + this.password = pwd; + this.hasPassword = true; + this.refreshToken = null; + }), + save: jest.fn().mockResolvedValue(undefined), + toJSON: () => ({ id: 'user-456', username: 'bob' }) + }; + + User.findById.mockResolvedValue(mockUser); + + app = express(); + app.use(express.json()); + app.use(cookieParser()); + app.use(session({ secret: 'test-session', resave: false, saveUninitialized: false })); + + app.locals.authConfig = { + enableOAuth: false, + corsOrigin: 'https://app.example.com', + jwtSecret: 'test-access-secret', + jwtRefreshSecret: 'test-refresh-secret', + cookieMaxAge: 60000 + }; + + // Authenticated mock session + app.use((req, res, next) => { + req.isAuthenticated = () => true; + req.user = mockUser; + next(); + }); + + app.use('/api/auth', authRoutes); + }); + + it('revokes previous refresh token and sets fresh cookies upon set-password', async () => { + const res = await request(app) + .post('/api/auth/set-password') + .send({ password: 'BrandNewSecurePassword123' }); + + expect(res.statusCode).toBe(200); + expect(res.body.success).toBe(true); + expect(mockUser.setPassword).toHaveBeenCalledWith('BrandNewSecurePassword123'); + + // Verify cookies were updated with new rotated tokens + const cookies = res.headers['set-cookie']; + expect(cookies).toBeDefined(); + const hasNewRefreshToken = cookies.some(c => c.startsWith('refreshToken=')); + expect(hasNewRefreshToken).toBe(true); + + // Verify mockUser's refreshToken in DB was rotated and is no longer the old one + expect(mockUser.refreshToken).not.toBe(oldRefreshToken); + }); + + it('rejects subsequent refresh requests using the old invalidated refresh token', async () => { + // 1. User sets password + await request(app) + .post('/api/auth/set-password') + .send({ password: 'BrandNewSecurePassword123' }); + + // The user now has a new rotated refresh token in DB: + const rotatedTokenInDb = mockUser.refreshToken; + + // 2. Attacker tries to use the prior/different token + const oldSignedToken = jwt.sign( + { userId: 'user-456', nonce: 'prior-session-nonce' }, + app.locals.authConfig.jwtRefreshSecret, + { expiresIn: '7d' } + ); + + const refreshRes = await request(app) + .post('/api/auth/refresh-token') + .set('Cookie', [`refreshToken=${oldSignedToken}`]); + + // Should be rejected because old token does not match rotatedTokenInDb + expect(refreshRes.statusCode).toBe(401); + expect(refreshRes.body.success).toBe(false); + expect(refreshRes.body.message).toMatch(/invalid or reused/i); + expect(mockUser.refreshToken).not.toBe(oldSignedToken); + expect(mockUser.refreshToken).not.toBe(rotatedTokenInDb); // Stored token invalidated on reuse detection + }); +}); diff --git a/backend/models/User.js b/backend/models/User.js index 1803014..60bd66f 100644 --- a/backend/models/User.js +++ b/backend/models/User.js @@ -69,6 +69,7 @@ userSchema.methods.comparePassword = async function(candidatePassword) { userSchema.methods.setPassword = async function(password) { this.password = password; this.hasPassword = true; + this.refreshToken = null; // Revoke existing refresh token on credential change await this.save(); }; diff --git a/backend/routes/auth.js b/backend/routes/auth.js index 9d9c8c7..083c3b6 100644 --- a/backend/routes/auth.js +++ b/backend/routes/auth.js @@ -161,9 +161,12 @@ router.post('/set-password', isAuthenticated, async (req, res) => { }); } - // Set the password + // Set the password and revoke prior refresh tokens await user.setPassword(password); + // Rotate tokens: generate and set fresh auth and refresh cookies for the user + await setAuthCookies(req, res, user); + res.json({ success: true, message: 'Password set successfully' From 0f189a79908bc5e250734bb369c0902a75060252 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Mon, 16 Nov 2026 21:13:09 +0530 Subject: [PATCH 06/12] docs: add comprehensive API reference, threat model, and llms.txt (closes #43, #87, #42) --- README.md | 3 + docs/API_REFERENCE.md | 244 ++++++++++++++++++++++++++++++++++++++++++ docs/THREAT_MODEL.md | 59 ++++++++++ llms-full.txt | 21 ++++ llms.txt | 48 +++++++++ 5 files changed, 375 insertions(+) create mode 100644 docs/API_REFERENCE.md create mode 100644 docs/THREAT_MODEL.md create mode 100644 llms-full.txt create mode 100644 llms.txt diff --git a/README.md b/README.md index 9417307..9c56c68 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,9 @@ Stand up a secure backend with a single `createAuthBackend()` call, drop an ` { + res.json({ user: req.user }); +}); +``` + +`authMiddleware` extracts JWTs from: +1. `req.cookies.authToken` +2. `Authorization: Bearer ` header + +Populates `req.user` with decoded token payload `{ userId, iat, exp }`. diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md new file mode 100644 index 0000000..8579b29 --- /dev/null +++ b/docs/THREAT_MODEL.md @@ -0,0 +1,59 @@ +# Dimsee Security Posture & Threat Model + +This document outlines the security architecture, threat model, and defense-in-depth posture implemented by Dimsee for modern MERN and full-stack web applications. + +--- + +## 1. Asset & Boundary Identification + +Dimsee protects the following critical security assets: +- **User Credentials**: Passwords stored at rest in MongoDB. +- **Session Tokens**: Short-lived JWT access tokens and long-lived refresh tokens. +- **User Identity Data**: PII including username, email, and OAuth provider IDs (`googleId`, `githubId`). +- **OAuth Callback Integrity**: Prevention of CSRF and token interception during third-party sign-in. + +--- + +## 2. Threat Analysis & Mitigations + +### A. Brute-Force & Credential Stuffing +- **Threat**: Attackers submitting automated dictionary attacks against `/signin`, `/signup`, or `/refresh-token`. +- **Mitigation**: + - `express-rate-limit` enforces rate limiting on all authentication entry points. + - Constant-time verification on `/signin` to prevent user enumeration. + +### B. Access Token vs. Refresh Token Masquerading +- **Threat**: If `jwtSecret` and `jwtRefreshSecret` share the same signing key, an attacker holding a refresh token can pass it directly to `authMiddleware` to access protected APIs. +- **Mitigation**: + - Strict separation of secrets: `jwtSecret` is used solely for access tokens, and `jwtRefreshSecret` is used solely for refresh tokens. + - Runtime validation in `createAuthBackend` refuses to start in `production` if both secrets are identical or match known defaults. + +### C. Refresh Token Theft & Replay Attacks +- **Threat**: An adversary intercepts a user's refresh token and attempts to obtain continuous access tokens. +- **Mitigation**: + - **Token Rotation**: Every call to `POST /refresh-token` issues a brand new refresh token and stores it in the database. + - **Automatic Reuse Detection**: If an old or invalid refresh token is presented, the stored token in DB is immediately revoked (`user.refreshToken = null`), logging out the user across all devices and blocking stolen credentials. + +### D. Credential Modification & Stale Session Invalidation +- **Threat**: A compromised account sets a new password, but the attacker's existing refresh tokens remain valid. +- **Mitigation**: + - Invoking `POST /set-password` automatically revokes and rotates active refresh tokens. + - Re-issues fresh cookies exclusively to the authenticated requester. + +### E. Open Redirect Vulnerabilities +- **Threat**: Attackers construct malicious OAuth initiation links (e.g., `?redirectUrl=https://attacker.com/evil`) to steal authorization codes. +- **Mitigation**: + - `resolveOAuthRedirect` enforces strict URL origin checking against `authConfig.corsOrigin`. External domains, malformed protocols, and user:pass URLs are rejected. + +### F. Cookie Hijacking & Cross-Site Scripting (XSS) +- **Threat**: Malicious scripts running in the browser steal tokens from `localStorage`. +- **Mitigation**: + - All tokens are delivered via `httpOnly`, `secure` (in production), and `sameSite: strict` (in production) cookies. + - JavaScript in the browser cannot read raw token strings, neutralizing script-based token exfiltration. + +--- + +## 3. Cryptographic Standards +- **Password Hashing**: `bcryptjs` with salt rounds = 10. +- **Token Signatures**: HMAC SHA-256 (`HS256`) with distinct high-entropy secrets. +- **Token Expiry**: Default access token TTL of 15 minutes (`15m`); refresh token TTL of 7 days (`7d`). diff --git a/llms-full.txt b/llms-full.txt new file mode 100644 index 0000000..1780d2b --- /dev/null +++ b/llms-full.txt @@ -0,0 +1,21 @@ +# Dimsee Full Technical Specification + +> Complete technical architecture, API signatures, security mechanisms, and integration details for LLMs and autonomous coding agents. + +## 1. Package Exports +- CommonJS: `require('dimsee')` exports `{ createAuthBackend, authMiddleware, User }` +- ES Modules: `import { AuthProvider, AuthForm, AuthStatus, LogoutButton, SetPasswordButton, useAuth } from 'dimsee'` + +## 2. Backend API Reference +- `POST /api/auth/signup`: Create user with `{ username, email, password, confirmPassword }`. Enforces 8+ char passwords with uppercase, lowercase, and numbers. +- `POST /api/auth/signin`: Authenticate with `{ email, password }`. Constant-time response on failure. +- `POST /api/auth/signout`: Invalidate session and clear HTTP-only cookies. +- `POST /api/auth/refresh-token`: Rotate refresh token and re-issue short-lived access token with automatic reuse detection. +- `POST /api/auth/set-password`: Allows OAuth accounts to set local passwords; revokes existing refresh tokens. +- `GET /api/auth/me`: Returns sanitized current user profile. +- `GET /api/auth/oauth-status`: Returns configuration status of Google and GitHub OAuth providers. + +## 3. Database Schema +- Mongoose collection: `users` +- Fields: `username` (unique, indexed), `email` (unique, indexed), `password` (hashed with bcrypt), `refreshToken` (indexed), `googleId` (sparse), `githubId` (sparse), `hasPassword` (boolean), `authMethod` (enum: local, google, github). +- Automatic timestamps: `createdAt`, `updatedAt`. diff --git a/llms.txt b/llms.txt new file mode 100644 index 0000000..0878eca --- /dev/null +++ b/llms.txt @@ -0,0 +1,48 @@ +# Dimsee + +> Modern, flexible authentication solution for MERN applications with OAuth support, JWT access/refresh token rotation, and customizable React UI components. + +Dimsee provides complete, secure authentication primitives for React and Express/MongoDB architectures, including pre-built React components, backend route handlers, token rotation, and OAuth integrations. + +## Documentation & References + +- [API Reference](docs/API_REFERENCE.md): Comprehensive REST endpoints, payloads, and response schemas. +- [Security Posture & Threat Model](docs/THREAT_MODEL.md): Token architecture, brute force protection, secret separation, and session handling. +- [Contributing Guide](CONTRIBUTING.md): Code of conduct, development workflow, and testing requirements. +- [Customization Guide](CUSTOMIZATION.md): Theming, styling, and customizing the frontend AuthForm and context. + +## Core Packages & Architecture + +### Backend Usage +```javascript +const { createAuthBackend, authMiddleware, User } = require('dimsee'); + +const app = createAuthBackend({ + mongoUri: process.env.MONGODB_URI, + jwtSecret: process.env.JWT_SECRET, + jwtRefreshSecret: process.env.JWT_REFRESH_SECRET, + corsOrigin: process.env.FRONTEND_URL +}); + +app.get('/api/protected', authMiddleware, (req, res) => { + res.json({ user: req.user }); +}); +``` + +### Frontend Usage +```jsx +import { AuthProvider, AuthForm, useAuth } from 'dimsee'; + +function App() { + return ( + + + + ); +} +``` + +## Security Best Practices +- Keep `jwtSecret` and `jwtRefreshSecret` cryptographically distinct and never commit them to source control. +- Ensure `NODE_ENV=production` is set in production to enforce `secure` cookies and strict secret validation. +- All auth cookies are `httpOnly` with `sameSite: 'strict'` in production. From 8eb8d32766425824f433f0776966d48a9869a4d1 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Mon, 16 Nov 2026 22:23:14 +0530 Subject: [PATCH 07/12] fix(schema): de-duplicate createdAt and add hot-path indexes for email, username, and refreshToken (closes #92, #15) --- backend/__tests__/userSchema.test.js | 42 ++++++++++++++++++++++++++++ backend/models/User.js | 24 +++++++++++----- 2 files changed, 59 insertions(+), 7 deletions(-) create mode 100644 backend/__tests__/userSchema.test.js diff --git a/backend/__tests__/userSchema.test.js b/backend/__tests__/userSchema.test.js new file mode 100644 index 0000000..5e56905 --- /dev/null +++ b/backend/__tests__/userSchema.test.js @@ -0,0 +1,42 @@ +const User = require('../models/User'); + +describe('User Schema Verification (Issue #15 & Issue #92)', () => { + it('has timestamps enabled in schema options without manual createdAt duplicate', () => { + expect(User.schema.options.timestamps).toBe(true); + expect(User.schema.paths.createdAt).toBeDefined(); + expect(User.schema.paths.updatedAt).toBeDefined(); + // Verify that createdAt is handled by Mongoose timestamps, not custom default + expect(User.schema.paths.createdAt.defaultValue).toBeUndefined(); + }); + + it('declares indexes on hot paths: email, username, and refreshToken (Issue #92)', () => { + const indexes = User.schema.indexes(); + const indexedFieldNames = indexes.map(([fields]) => Object.keys(fields)).flat(); + + // Check individual indexed paths or schema indexes + expect(indexedFieldNames).toContain('email'); + expect(indexedFieldNames).toContain('username'); + expect(indexedFieldNames).toContain('refreshToken'); + }); + + it('omits password from JSON representation', () => { + const user = new User({ + username: 'johndoe', + email: 'john@example.com', + password: 'SamplePassword123' + }); + + const json = user.toJSON(); + expect(json.password).toBeUndefined(); + expect(json.username).toBe('johndoe'); + expect(json.email).toBe('john@example.com'); + }); + + it('provides canUsePasswordLogin helper based on hasPassword state', () => { + const localUser = new User({ hasPassword: true }); + expect(localUser.canUsePasswordLogin()).toBe(true); + + const oauthUser = new User({ hasPassword: false }); + expect(oauthUser.canUsePasswordLogin()).toBe(false); + }); +}); diff --git a/backend/models/User.js b/backend/models/User.js index 1803014..3fef7d3 100644 --- a/backend/models/User.js +++ b/backend/models/User.js @@ -25,10 +25,19 @@ const userSchema = new mongoose.Schema({ minlength: 6 }, refreshToken: { - type: String + type: String, + index: true }, // For refreshtokens to generate new accesstokens - googleId: String, - githubId: String, + googleId: { + type: String, + sparse: true, + index: true + }, + githubId: { + type: String, + sparse: true, + index: true + }, authMethod: { type: String, enum: ['local', 'google', 'github'], @@ -37,15 +46,16 @@ const userSchema = new mongoose.Schema({ hasPassword: { type: Boolean, default: true - }, - createdAt: { - type: Date, - default: Date.now } }, { timestamps: true }); +// Explicit compound / single indexes for hot path queries +userSchema.index({ email: 1 }); +userSchema.index({ username: 1 }); +userSchema.index({ refreshToken: 1 }); + // Hash password before saving userSchema.pre('save', async function(next) { if (this.isModified('password') && this.password) { From 3a97f521a131d498857169614fb21b5d7a2060f3 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Tue, 17 Nov 2026 07:59:22 +0530 Subject: [PATCH 08/12] fix(schema): eliminate duplicate index declarations and verify unique index options --- backend/__tests__/userSchema.test.js | 24 ++++++++++++++++++------ backend/models/User.js | 5 ----- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/backend/__tests__/userSchema.test.js b/backend/__tests__/userSchema.test.js index 5e56905..fe60a84 100644 --- a/backend/__tests__/userSchema.test.js +++ b/backend/__tests__/userSchema.test.js @@ -9,14 +9,26 @@ describe('User Schema Verification (Issue #15 & Issue #92)', () => { expect(User.schema.paths.createdAt.defaultValue).toBeUndefined(); }); - it('declares indexes on hot paths: email, username, and refreshToken (Issue #92)', () => { + it('declares indexes on hot paths without duplicate specifications (Issue #92)', () => { const indexes = User.schema.indexes(); - const indexedFieldNames = indexes.map(([fields]) => Object.keys(fields)).flat(); + + // Each index entry is [fieldsObject, optionsObject] + const emailIndex = indexes.find(([fields]) => fields.email !== undefined); + const usernameIndex = indexes.find(([fields]) => fields.username !== undefined); + const refreshTokenIndex = indexes.find(([fields]) => fields.refreshToken !== undefined); - // Check individual indexed paths or schema indexes - expect(indexedFieldNames).toContain('email'); - expect(indexedFieldNames).toContain('username'); - expect(indexedFieldNames).toContain('refreshToken'); + expect(emailIndex).toBeDefined(); + expect(emailIndex[1].unique).toBe(true); + + expect(usernameIndex).toBeDefined(); + expect(usernameIndex[1].unique).toBe(true); + + expect(refreshTokenIndex).toBeDefined(); + + // Verify there are no duplicate index specifications for any field + const indexedKeys = indexes.map(([fields]) => Object.keys(fields).sort().join(',')); + const uniqueKeys = new Set(indexedKeys); + expect(indexedKeys.length).toBe(uniqueKeys.size); }); it('omits password from JSON representation', () => { diff --git a/backend/models/User.js b/backend/models/User.js index 3fef7d3..ab8f2c7 100644 --- a/backend/models/User.js +++ b/backend/models/User.js @@ -51,11 +51,6 @@ const userSchema = new mongoose.Schema({ timestamps: true }); -// Explicit compound / single indexes for hot path queries -userSchema.index({ email: 1 }); -userSchema.index({ username: 1 }); -userSchema.index({ refreshToken: 1 }); - // Hash password before saving userSchema.pre('save', async function(next) { if (this.isModified('password') && this.password) { From 910b02cbcdb752434b4740d80f5d39070c67988e Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Tue, 17 Nov 2026 08:12:12 +0530 Subject: [PATCH 09/12] fix(frontend): align SetPasswordButton validation with password policy and surface field errors --- frontend/src/components/SetPasswordButton.jsx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/frontend/src/components/SetPasswordButton.jsx b/frontend/src/components/SetPasswordButton.jsx index 7a79f80..f005be6 100644 --- a/frontend/src/components/SetPasswordButton.jsx +++ b/frontend/src/components/SetPasswordButton.jsx @@ -57,8 +57,13 @@ const SetPasswordButton = ({ return; } - if (passwordData.password.length < 6) { - setPasswordError('Password must be at least 6 characters'); + if (passwordData.password.length < 8) { + setPasswordError('Password must be at least 8 characters long'); + return; + } + + if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(passwordData.password)) { + setPasswordError('Password must contain at least one uppercase letter, one lowercase letter, and one number'); return; } @@ -70,7 +75,8 @@ const SetPasswordButton = ({ setPasswordData({ password: '', confirmPassword: '' }); if (onSuccess) onSuccess(result); } else { - setPasswordError(result.message); + const fieldError = result.errors?.find(err => err.field === 'password')?.message; + setPasswordError(fieldError || result.message || 'Failed to set password'); if (onError) onError(result); } } catch (error) { From 03f27612715a525e635873d9fa162f83c2b68f1f Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Tue, 17 Nov 2026 08:16:53 +0530 Subject: [PATCH 10/12] fix(schema): remove duplicate index specifications and verify unique index options --- backend/__tests__/userSchema.test.js | 1 - backend/models/User.js | 5 ----- 2 files changed, 6 deletions(-) diff --git a/backend/__tests__/userSchema.test.js b/backend/__tests__/userSchema.test.js index 24f8c41..fe60a84 100644 --- a/backend/__tests__/userSchema.test.js +++ b/backend/__tests__/userSchema.test.js @@ -30,7 +30,6 @@ describe('User Schema Verification (Issue #15 & Issue #92)', () => { const uniqueKeys = new Set(indexedKeys); expect(indexedKeys.length).toBe(uniqueKeys.size); }); - }); it('omits password from JSON representation', () => { const user = new User({ diff --git a/backend/models/User.js b/backend/models/User.js index f0753b2..57f9668 100644 --- a/backend/models/User.js +++ b/backend/models/User.js @@ -51,11 +51,6 @@ const userSchema = new mongoose.Schema({ timestamps: true }); -// Explicit compound / single indexes for hot path queries -userSchema.index({ email: 1 }); -userSchema.index({ username: 1 }); -userSchema.index({ refreshToken: 1 }); - // Hash password before saving userSchema.pre('save', async function(next) { if (this.isModified('password') && this.password) { From 27b7f8d23ca69eebd079598400c343ea667722c5 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Tue, 17 Nov 2026 13:49:37 +0530 Subject: [PATCH 11/12] feat(security): harden refresh-token rotation with hashed storage, replay detection, and denylist revocation (closes #104) --- backend/__tests__/tokenSecurity.test.js | 273 ++++++++++++++++++++++++ backend/index.js | 3 +- backend/models/User.js | 86 +++++++- backend/routes/auth.js | 181 +++++++++++++--- backend/services/tokenDenylist.js | 67 ++++++ 5 files changed, 576 insertions(+), 34 deletions(-) create mode 100644 backend/__tests__/tokenSecurity.test.js create mode 100644 backend/services/tokenDenylist.js diff --git a/backend/__tests__/tokenSecurity.test.js b/backend/__tests__/tokenSecurity.test.js new file mode 100644 index 0000000..22da7d5 --- /dev/null +++ b/backend/__tests__/tokenSecurity.test.js @@ -0,0 +1,273 @@ +const request = require('supertest'); +const express = require('express'); +const cookieParser = require('cookie-parser'); +const session = require('express-session'); +const jwt = require('jsonwebtoken'); +const crypto = require('crypto'); + +// Real User model for schema method testing +const User = require('../models/User'); +const { tokenDenylist } = require('../services/tokenDenylist'); +const authRoutes = require('../routes/auth'); + +describe('Hardened Refresh Token Rotation, Hashing, Replay Detection & Revocation (Issue #104)', () => { + beforeEach(() => { + tokenDenylist.clear(); + }); + + describe('User Model Hashing & Rotation Methods', () => { + it('stores refresh tokens as SHA-256 hex hashes and never plaintext', async () => { + const user = new User({ + username: 'alice', + email: 'alice@example.com', + password: 'ValidPassword123' + }); + + const rawToken = 'header.payload.signature-refresh-token'; + await user.setRefreshToken(rawToken); + + expect(user.refreshToken).not.toBe(rawToken); + expect(user.refreshToken).toHaveLength(64); + expect(/^[a-f0-9]{64}$/.test(user.refreshToken)).toBe(true); + + const expectedHash = crypto.createHash('sha256').update(rawToken).digest('hex'); + expect(user.refreshToken).toBe(expectedHash); + }); + + it('verifies valid refresh token and rejects invalid token', async () => { + const user = new User({ + username: 'alice', + email: 'alice@example.com', + password: 'ValidPassword123' + }); + + const rawToken = 'correct-token-string'; + await user.setRefreshToken(rawToken); + + expect(user.verifyRefreshToken(rawToken)).toBe(true); + expect(user.verifyRefreshToken('wrong-token-string')).toBe(false); + expect(user.verifyRefreshToken('')).toBe(false); + }); + + it('rotates active token into previousRefreshToken for replay tracking', async () => { + const user = new User({ + username: 'alice', + email: 'alice@example.com', + password: 'ValidPassword123' + }); + + const token1 = 'first-token-generation'; + const token2 = 'second-token-generation'; + + await user.setRefreshToken(token1); + const hash1 = user.refreshToken; + expect(user.previousRefreshToken).toBeUndefined(); + + await user.setRefreshToken(token2); + const hash2 = user.refreshToken; + + expect(user.refreshToken).toBe(hash2); + expect(user.previousRefreshToken).toBe(hash1); + + expect(user.verifyRefreshToken(token2)).toBe(true); + expect(user.verifyRefreshToken(token1)).toBe(false); + expect(user.verifyPreviousRefreshToken(token1)).toBe(true); + expect(user.verifyPreviousRefreshToken(token2)).toBe(false); + }); + + it('clears all active and rotated tokens on revokeAllRefreshTokens', async () => { + const user = new User({ + username: 'alice', + email: 'alice@example.com', + password: 'ValidPassword123' + }); + + await user.setRefreshToken('token1'); + await user.setRefreshToken('token2'); + expect(user.refreshToken).toBeDefined(); + expect(user.previousRefreshToken).toBeDefined(); + + await user.revokeAllRefreshTokens(); + expect(user.refreshToken).toBeNull(); + expect(user.previousRefreshToken).toBeNull(); + expect(user.verifyRefreshToken('token2')).toBe(false); + expect(user.verifyPreviousRefreshToken('token1')).toBe(false); + }); + + it('strips refreshToken and previousRefreshToken from JSON output', async () => { + const user = new User({ + username: 'alice', + email: 'alice@example.com', + password: 'ValidPassword123' + }); + + await user.setRefreshToken('secret-token-value'); + const json = user.toJSON(); + + expect(json.password).toBeUndefined(); + expect(json.refreshToken).toBeUndefined(); + expect(json.previousRefreshToken).toBeUndefined(); + expect(json.username).toBe('alice'); + expect(json.email).toBe('alice@example.com'); + }); + }); + + describe('Route-Level Token Rotation, Replay Detection & Revocation', () => { + let app; + let mockUser; + const jwtRefreshSecret = 'super-secure-refresh-secret-dimsee-2026'; + const jwtSecret = 'super-secure-access-secret-dimsee-2026'; + + beforeEach(() => { + mockUser = { + _id: '507f191e810c19729de860ea', + id: '507f191e810c19729de860ea', + username: 'securitytest', + email: 'sec@example.com', + refreshToken: null, + previousRefreshToken: null, + setRefreshToken: jest.fn(async function(rawToken) { + if (!rawToken) { + this.previousRefreshToken = null; + this.refreshToken = null; + } else { + const hash = crypto.createHash('sha256').update(rawToken).digest('hex'); + if (this.refreshToken && this.refreshToken !== hash) { + this.previousRefreshToken = this.refreshToken; + } + this.refreshToken = hash; + } + }), + verifyRefreshToken: jest.fn(function(rawToken) { + if (!this.refreshToken || !rawToken) return false; + const incomingHash = crypto.createHash('sha256').update(rawToken).digest('hex'); + return this.refreshToken === incomingHash; + }), + verifyPreviousRefreshToken: jest.fn(function(rawToken) { + if (!this.previousRefreshToken || !rawToken) return false; + const incomingHash = crypto.createHash('sha256').update(rawToken).digest('hex'); + return this.previousRefreshToken === incomingHash; + }), + revokeAllRefreshTokens: jest.fn(async function() { + this.refreshToken = null; + this.previousRefreshToken = null; + }), + toJSON: () => ({ id: '507f191e810c19729de860ea', username: 'securitytest' }) + }; + + jest.spyOn(User, 'findById').mockResolvedValue(mockUser); + + app = express(); + app.use(express.json()); + app.use(cookieParser()); + app.use(session({ secret: 'test-session', resave: false, saveUninitialized: false })); + + app.locals.authConfig = { + enableOAuth: false, + corsOrigin: 'https://app.example.com', + jwtSecret, + jwtExpiry: '15m', + jwtRefreshSecret, + jwtRefreshExpiry: '7d', + cookieMaxAge: 604800000 + }; + + app.use((req, res, next) => { + req.isAuthenticated = () => true; + req.logout = (cb) => cb(null); + req.user = mockUser; + next(); + }); + + app.use('/api/auth', authRoutes); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('rotates refresh token and returns new access and refresh tokens', async () => { + const initialToken = jwt.sign({ userId: mockUser.id }, jwtRefreshSecret, { expiresIn: '7d' }); + await mockUser.setRefreshToken(initialToken); + + const res = await request(app) + .post('/api/auth/refresh-token') + .send({ refreshToken: initialToken }); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(res.body.accessToken).toBeDefined(); + expect(res.body.refreshToken).toBeDefined(); + expect(res.body.refreshToken).not.toBe(initialToken); + + // Old token should now be denylisted + expect(tokenDenylist.isRevoked(initialToken)).toBe(true); + }); + + it('detects replay attack when a previously rotated token is re-submitted', async () => { + const tokenA = jwt.sign({ userId: mockUser.id, nonce: 'nonce-a' }, jwtRefreshSecret, { expiresIn: '7d' }); + const tokenB = jwt.sign({ userId: mockUser.id, nonce: 'nonce-b' }, jwtRefreshSecret, { expiresIn: '7d' }); + + // Simulate prior rotation from Token A to Token B + await mockUser.setRefreshToken(tokenA); + await mockUser.setRefreshToken(tokenB); + + // Attacker replays Token A + const res = await request(app) + .post('/api/auth/refresh-token') + .send({ refreshToken: tokenA }); + + expect(res.status).toBe(401); + expect(res.body.success).toBe(false); + expect(res.body.message).toContain('Refresh token reuse detected'); + + // Crucial: all active sessions for this user must be terminated + expect(mockUser.revokeAllRefreshTokens).toHaveBeenCalled(); + expect(tokenDenylist.isRevoked(tokenA)).toBe(true); + }); + + it('rejects a revoked token immediately via the denylist', async () => { + const activeToken = jwt.sign({ userId: mockUser.id }, jwtRefreshSecret, { expiresIn: '7d' }); + await mockUser.setRefreshToken(activeToken); + + // Revoke token server-side + tokenDenylist.revoke(activeToken); + + const res = await request(app) + .post('/api/auth/refresh-token') + .send({ refreshToken: activeToken }); + + expect(res.status).toBe(401); + expect(res.body.success).toBe(false); + expect(res.body.message).toContain('revoked'); + }); + + it('clears user refresh token in DB and denylists token on /signout', async () => { + const activeToken = jwt.sign({ userId: mockUser.id }, jwtRefreshSecret, { expiresIn: '7d' }); + await mockUser.setRefreshToken(activeToken); + + const res = await request(app) + .post('/api/auth/signout') + .send({ refreshToken: activeToken }); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(mockUser.revokeAllRefreshTokens).toHaveBeenCalled(); + expect(tokenDenylist.isRevoked(activeToken)).toBe(true); + }); + + it('revokes tokens via dedicated /revoke-token endpoint', async () => { + const activeToken = jwt.sign({ userId: mockUser.id }, jwtRefreshSecret, { expiresIn: '7d' }); + await mockUser.setRefreshToken(activeToken); + + const res = await request(app) + .post('/api/auth/revoke-token') + .send({ refreshToken: activeToken }); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(res.body.message).toContain('revoked'); + expect(tokenDenylist.isRevoked(activeToken)).toBe(true); + }); + }); +}); diff --git a/backend/index.js b/backend/index.js index 60efa41..4558e3f 100644 --- a/backend/index.js +++ b/backend/index.js @@ -12,6 +12,7 @@ const authRoutes = require(path.join(__dirname, 'routes', 'auth')); const authMiddleware = require(path.join(__dirname, 'middleware', 'auth')); const { passport: passportInstance, configureOAuthStrategies } = require(path.join(__dirname, 'config', 'passport')); const User = require(path.join(__dirname, 'models', 'User')); +const { tokenDenylist } = require(path.join(__dirname, 'services', 'tokenDenylist')); require('dotenv').config(); @@ -136,4 +137,4 @@ const createAuthBackend = (config = {}) => { return app; }; -module.exports = { createAuthBackend, authMiddleware, User }; +module.exports = { createAuthBackend, authMiddleware, User, tokenDenylist }; diff --git a/backend/models/User.js b/backend/models/User.js index 57f9668..a7236a3 100644 --- a/backend/models/User.js +++ b/backend/models/User.js @@ -1,6 +1,7 @@ // backend/models/User.js - User Model const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); +const crypto = require('crypto'); const userSchema = new mongoose.Schema({ username: { @@ -27,7 +28,10 @@ const userSchema = new mongoose.Schema({ refreshToken: { type: String, index: true - }, // For refreshtokens to generate new accesstokens + }, // SHA-256 hash of active refresh token + previousRefreshToken: { + type: String + }, // SHA-256 hash of immediately preceding refresh token for replay detection googleId: { type: String, sparse: true, @@ -83,10 +87,88 @@ userSchema.methods.canUsePasswordLogin = function() { return this.hasPassword; }; -// Remove password from JSON output +// Hash a raw refresh token using SHA-256 for secure at-rest storage +userSchema.statics.hashToken = function(token) { + if (!token) return null; + return crypto.createHash('sha256').update(token).digest('hex'); +}; + +// Set and hash the refresh token, rotating existing token into previousRefreshToken +userSchema.methods.setRefreshToken = async function(rawToken) { + if (!rawToken) { + this.previousRefreshToken = null; + this.refreshToken = null; + } else { + const hash = crypto.createHash('sha256').update(rawToken).digest('hex'); + if (this.refreshToken && this.refreshToken !== hash) { + this.previousRefreshToken = this.refreshToken; + } + this.refreshToken = hash; + } + if (typeof this.save === 'function' && (!this.db || this.db.readyState === 1)) { + await this.save({ validateBeforeSave: false }); + } +}; + +// Constant-time verification of active refresh token +userSchema.methods.verifyRefreshToken = function(rawToken) { + if (!this.refreshToken || !rawToken) return false; + const incomingHash = crypto.createHash('sha256').update(rawToken).digest('hex'); + + if (this.refreshToken.length === 64) { + const storedBuf = Buffer.from(this.refreshToken, 'utf8'); + const incomingBuf = Buffer.from(incomingHash, 'utf8'); + if (storedBuf.length === incomingBuf.length && crypto.timingSafeEqual(storedBuf, incomingBuf)) { + return true; + } + } + + // Fallback for legacy unhashed tokens + const legacyStored = Buffer.from(this.refreshToken, 'utf8'); + const incoming = Buffer.from(rawToken, 'utf8'); + if (legacyStored.length === incoming.length && crypto.timingSafeEqual(legacyStored, incoming)) { + return true; + } + return false; +}; + +// Constant-time verification of previously rotated refresh token for replay detection +userSchema.methods.verifyPreviousRefreshToken = function(rawToken) { + if (!this.previousRefreshToken || !rawToken) return false; + const incomingHash = crypto.createHash('sha256').update(rawToken).digest('hex'); + + if (this.previousRefreshToken.length === 64) { + const storedBuf = Buffer.from(this.previousRefreshToken, 'utf8'); + const incomingBuf = Buffer.from(incomingHash, 'utf8'); + if (storedBuf.length === incomingBuf.length && crypto.timingSafeEqual(storedBuf, incomingBuf)) { + return true; + } + } + + // Fallback for legacy unhashed + const legacyStored = Buffer.from(this.previousRefreshToken, 'utf8'); + const incoming = Buffer.from(rawToken, 'utf8'); + if (legacyStored.length === incoming.length && crypto.timingSafeEqual(legacyStored, incoming)) { + return true; + } + return false; +}; + +// Invalidate all tokens for user across devices +userSchema.methods.revokeAllRefreshTokens = async function() { + this.refreshToken = null; + this.previousRefreshToken = null; + if (typeof this.save === 'function' && (!this.db || this.db.readyState === 1)) { + await this.save({ validateBeforeSave: false }); + } +}; + +// Remove password and token hashes from JSON output userSchema.methods.toJSON = function() { const user = this.toObject(); delete user.password; + delete user.refreshToken; + delete user.previousRefreshToken; return user; }; diff --git a/backend/routes/auth.js b/backend/routes/auth.js index f4b527a..f0ca017 100644 --- a/backend/routes/auth.js +++ b/backend/routes/auth.js @@ -1,9 +1,11 @@ // backend/routes/auth.js - Authentication Routes const express = require('express'); const jwt = require('jsonwebtoken'); +const crypto = require('crypto'); const { z } = require('zod'); const passport = require('passport'); const User = require('../models/User'); +const { tokenDenylist } = require('../services/tokenDenylist'); const router = express.Router(); @@ -104,10 +106,11 @@ const generateToken = (userId, jwtSecret,expiresIn) => { return jwt.sign({ userId }, jwtSecret, { expiresIn }); }; -//generate refresh token -const generateRefreshToken = (userId, jwtRefreshSecret,expiresIn) => { - return jwt.sign({userId},jwtRefreshSecret,{expiresIn}); -} +// Generate unique refresh token with cryptographically random jti +const generateRefreshToken = (userId, jwtRefreshSecret, expiresIn) => { + const jti = crypto.randomUUID ? crypto.randomUUID() : crypto.randomBytes(16).toString('hex'); + return jwt.sign({ userId, jti }, jwtRefreshSecret, { expiresIn }); +}; // Centralised cookie options so every auth cookie gets the same flags. const isProduction = () => process.env.NODE_ENV === 'production'; @@ -129,9 +132,13 @@ const setAuthCookies = async (req, res, user) => { const token = generateToken(user._id, jwtSecret, jwtExpiryFallback); const refreshToken = generateRefreshToken(user._id, jwtRefreshSecret, jwtRefreshExpiryFallback); - // Update user's refresh token in DB - user.refreshToken = refreshToken; - await user.save({ validateBeforeSave: false }); // Important: set to false if your User model doesn't expect all fields to be present/valid after setting refreshToken + // Update user's refresh token in DB as a secure SHA-256 hash + if (typeof user.setRefreshToken === 'function') { + await user.setRefreshToken(refreshToken); + } else { + user.refreshToken = refreshToken; + await user.save({ validateBeforeSave: false }); + } // Set cookies res.cookie('authToken', token, getCookieOptions(cookieMaxAge)); @@ -308,7 +315,33 @@ router.post('/signin', validateBody(signinSchema), (req, res, next) => { }); // Sign out route -router.post('/signout', (req, res) => { +router.post('/signout', async (req, res) => { + const incomingRefreshToken = req.cookies?.refreshToken || req.body?.refreshToken; + if (incomingRefreshToken) { + tokenDenylist.revoke(incomingRefreshToken); + } + + // Revoke user's refresh token in DB if authenticated or found via token payload + if (req.user && typeof req.user.revokeAllRefreshTokens === 'function') { + try { + await req.user.revokeAllRefreshTokens(); + } catch (e) { + console.error('Error revoking tokens on signout:', e); + } + } else if (incomingRefreshToken) { + try { + const decoded = jwt.decode(incomingRefreshToken); + if (decoded && decoded.userId) { + const u = await User.findById(decoded.userId); + if (u && typeof u.revokeAllRefreshTokens === 'function') { + await u.revokeAllRefreshTokens(); + } + } + } catch (_err) { + // Ignore token decode errors on signout + } + } + req.logout((err) => { if (err) { return res.status(500).json({ @@ -340,16 +373,25 @@ router.post('/refresh-token', async (req, res) => { }); } + // Check server-side revocation denylist + if (tokenDenylist.isRevoked(incomingRefreshToken)) { + return res.status(401).json({ + success: false, + message: 'Refresh token has been revoked. Please log in again.', + errors: [{ field: 'general', message: 'Token revoked' }] + }); + } + try { const decodedToken = jwt.verify(incomingRefreshToken, req.app.locals.authConfig.jwtRefreshSecret); // Ensure the payload has userId if (!decodedToken || !decodedToken.userId) { - return res.status(401).json({ - success: false, - message: 'Invalid Refresh Token payload', - errors: [{ field: 'general', message: 'Invalid Refresh Token' }] - }); + return res.status(401).json({ + success: false, + message: 'Invalid Refresh Token payload', + errors: [{ field: 'general', message: 'Invalid Refresh Token' }] + }); } const user = await User.findById(decodedToken.userId); @@ -362,44 +404,121 @@ router.post('/refresh-token', async (req, res) => { }); } - // Refresh token rotation with reuse detection - if (user.refreshToken !== incomingRefreshToken) { - user.refreshToken = null; // Invalidate the stored refresh token to force re-login - await user.save({ validateBeforeSave: false }); - return res.status(401).json({ - success: false, - message: 'Refresh token invalid or reused. Please log in again.', - errors: [{ field: 'general', message: 'Refresh token invalid or reused.' }] - }); + // Explicit replay detection: check if incoming token matches the previously rotated token + if (typeof user.verifyPreviousRefreshToken === 'function' && user.verifyPreviousRefreshToken(incomingRefreshToken)) { + tokenDenylist.revoke(incomingRefreshToken); + if (typeof user.revokeAllRefreshTokens === 'function') { + await user.revokeAllRefreshTokens(); + } else { + user.refreshToken = null; + await user.save({ validateBeforeSave: false }); + } + return res.status(401).json({ + success: false, + message: 'Refresh token reuse detected. All active sessions have been revoked for security. Please log in again.', + errors: [{ field: 'general', message: 'Token replay detected' }] + }); } + // Verify active refresh token using constant-time comparison + const isValidToken = typeof user.verifyRefreshToken === 'function' + ? user.verifyRefreshToken(incomingRefreshToken) + : user.refreshToken === incomingRefreshToken; + + if (!isValidToken) { + tokenDenylist.revoke(incomingRefreshToken); + if (typeof user.revokeAllRefreshTokens === 'function') { + await user.revokeAllRefreshTokens(); + } else { + user.refreshToken = null; + await user.save({ validateBeforeSave: false }); + } + return res.status(401).json({ + success: false, + message: 'Refresh token invalid or reused. Please log in again.', + errors: [{ field: 'general', message: 'Refresh token invalid or reused.' }] + }); + } + + // Add consumed token to denylist so it cannot be reused + tokenDenylist.revoke(incomingRefreshToken); + // Generate new access and refresh tokens const newAccessToken = generateToken(user._id, req.app.locals.authConfig.jwtSecret, req.app.locals.authConfig.jwtExpiry || '15m'); const newRefreshToken = generateRefreshToken(user._id, req.app.locals.authConfig.jwtRefreshSecret, req.app.locals.authConfig.jwtRefreshExpiry || '7d'); - // Update the user's refresh token in the database with the new one - user.refreshToken = newRefreshToken; - await user.save({ validateBeforeSave: false }); + // Update the user's refresh token in the database as a SHA-256 hash and rotate previous + if (typeof user.setRefreshToken === 'function') { + await user.setRefreshToken(newRefreshToken); + } else { + user.refreshToken = newRefreshToken; + await user.save({ validateBeforeSave: false }); + } // Set the new tokens in cookies const { cookieMaxAge } = req.app.locals.authConfig; res.cookie('authToken', newAccessToken, getCookieOptions(cookieMaxAge)); res.cookie('refreshToken', newRefreshToken, getCookieOptions(cookieMaxAge)); - res.json({ + return res.json({ success: true, message: 'Tokens refreshed successfully', - accessToken: newAccessToken // Send new access token in body for client to use immediately + accessToken: newAccessToken, + refreshToken: newRefreshToken }); } catch (error) { - // Generic error handling - res.status(500).json({ + if (error.name === 'TokenExpiredError') { + return res.status(401).json({ + success: false, + message: 'Refresh token has expired. Please log in again.', + errors: [{ field: 'general', message: 'Refresh token expired' }] + }); + } + return res.status(401).json({ success: false, - message: 'Failed to refresh token due to server error', - errors: [{ field: 'general', message: 'Internal server error' }] + message: 'Invalid Refresh Token', + errors: [{ field: 'general', message: error.message || 'Invalid Refresh Token' }] + }); + } +}); + +// Explicit server-side token revocation endpoint +router.post('/revoke-token', async (req, res) => { + const tokenToRevoke = req.body?.refreshToken || req.cookies?.refreshToken; + if (!tokenToRevoke) { + return res.status(400).json({ + success: false, + message: 'Refresh token required for revocation', + errors: [{ field: 'refreshToken', message: 'Token required' }] }); } + + // Add to denylist immediately + tokenDenylist.revoke(tokenToRevoke); + + try { + const decoded = jwt.decode(tokenToRevoke); + if (decoded && decoded.userId) { + const user = await User.findById(decoded.userId); + if (user) { + if (typeof user.revokeAllRefreshTokens === 'function') { + await user.revokeAllRefreshTokens(); + } else { + user.refreshToken = null; + await user.save({ validateBeforeSave: false }); + } + } + } + } catch (_err) { + // Ignore decode errors on token revocation + } + + res.clearCookie('refreshToken', getCookieOptions()); + return res.json({ + success: true, + message: 'Refresh token successfully revoked' + }); }); // Get current user route diff --git a/backend/services/tokenDenylist.js b/backend/services/tokenDenylist.js new file mode 100644 index 0000000..a4be1fb --- /dev/null +++ b/backend/services/tokenDenylist.js @@ -0,0 +1,67 @@ +// backend/services/tokenDenylist.js - Refresh Token Revocation Denylist +const crypto = require('crypto'); + +class TokenDenylist { + constructor() { + // Map of tokenHash -> expiration timestamp (ms) + this.denylist = new Map(); + // Prune expired entries every 15 minutes + this.cleanupInterval = setInterval(() => this.cleanup(), 15 * 60 * 1000); + if (this.cleanupInterval.unref) { + this.cleanupInterval.unref(); // Prevent keeping Node event loop open in tests + } + } + + hash(token) { + if (!token) return ''; + // If it's already a 64-char hex string, treat it as already hashed + if (token.length === 64 && /^[a-f0-9]{64}$/i.test(token)) { + return token; + } + return crypto.createHash('sha256').update(token).digest('hex'); + } + + revoke(rawOrHashedToken, expiresAt = Date.now() + 7 * 24 * 60 * 60 * 1000) { + const key = this.hash(rawOrHashedToken); + if (key) { + const exp = typeof expiresAt === 'number' ? expiresAt : new Date(expiresAt).getTime(); + this.denylist.set(key, exp); + } + } + + isRevoked(rawOrHashedToken) { + const key = this.hash(rawOrHashedToken); + if (!key) return false; + const expiry = this.denylist.get(key); + if (!expiry) return false; + if (Date.now() > expiry) { + this.denylist.delete(key); + return false; + } + return true; + } + + cleanup() { + const now = Date.now(); + for (const [key, expiry] of this.denylist.entries()) { + if (now > expiry) { + this.denylist.delete(key); + } + } + } + + clear() { + this.denylist.clear(); + } + + destroy() { + if (this.cleanupInterval) { + clearInterval(this.cleanupInterval); + } + } +} + +// Export singleton instance and class +const tokenDenylist = new TokenDenylist(); + +module.exports = { tokenDenylist, TokenDenylist }; From 298db2b220437fe1985bd03ddd2201ec1bbe2d3e Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Wed, 18 Nov 2026 17:14:51 +0530 Subject: [PATCH 12/12] test(security): mock session memory store in secretEnforcement to prevent open network handles --- backend/__tests__/secretEnforcement.test.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/backend/__tests__/secretEnforcement.test.js b/backend/__tests__/secretEnforcement.test.js index 255811e..2a5cf9a 100644 --- a/backend/__tests__/secretEnforcement.test.js +++ b/backend/__tests__/secretEnforcement.test.js @@ -1,4 +1,12 @@ 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)', () => { @@ -9,8 +17,9 @@ describe('Production Secrets Enforcement (Issue #33 & Issue #32)', () => { connectSpy = jest.spyOn(mongoose, 'connect').mockResolvedValue(undefined); }); - afterAll(() => { + afterAll(async () => { connectSpy.mockRestore(); + await mongoose.disconnect(); }); afterEach(() => {