Repository navigation
a #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
a #3
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,6 +1,13 @@ | ||||||
| import express, { Router } from "express"; | ||||||
|
|
||||||
| import { register, login, verify, logout, me } from "../controllers/auth.js"; | ||||||
| import { | ||||||
| register, | ||||||
| login, | ||||||
| verify, | ||||||
| logout, | ||||||
| me, | ||||||
| refresh, | ||||||
| } from "../controllers/auth.js"; | ||||||
| import { registerSchema, loginSchema } from "../validations/auth.js"; | ||||||
| import { validateSchema } from "../middlewares/joiValidation.js"; | ||||||
| import { authlimiter } from "../middlewares/rateLimit.js"; | ||||||
|
|
@@ -10,7 +17,8 @@ const router: Router = express.Router(); | |||||
| router.post("/register", authlimiter, validateSchema(registerSchema), register); | ||||||
| router.post("/login", authlimiter, validateSchema(loginSchema), login); | ||||||
| router.get("/verify/:token", verify); | ||||||
| router.post("/logout",authMiddleware, logout); | ||||||
| router.post("/logout", authMiddleware, logout); | ||||||
| router.post("/refresh", refresh); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Missing rate limiting and no guard against missing cookies. The Additionally, the Consider:
Suggested fix-router.post("/refresh", refresh);
+router.post("/refresh", authlimiter, refresh);And in the controller, add a guard: const tokens: Tokens | undefined = req.signedCookies["tokens"];
if (!tokens?.refreshToken) {
return res.status(401).json(createAPIResponse({
success: false,
message: "No refresh token provided",
}));
}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||
| router.get("/me", authMiddleware, me); | ||||||
|
|
||||||
| export default router; | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| import { InferSchemaType } from "mongoose"; | ||
| import { usersSchema } from "../models/users.js"; | ||
| import { testSchema } from "../models/test.js"; | ||
| import { testSchema } from "../models/load.js"; | ||
|
|
||
| export type User = InferSchemaType<typeof usersSchema>; | ||
|
|
||
|
|
@@ -20,14 +20,14 @@ export interface ServiceErrorInput { | |
| details?: any; | ||
| } | ||
|
|
||
| export interface ApiResponseinput { | ||
| export interface ApiResponseinput<T = unknown> { | ||
| success: boolean; | ||
| message: string; | ||
| token?: string; | ||
| tokens?: Tokens; | ||
| user?: User; | ||
| data?: string; | ||
| datas?: string[] | ||
| data?: T; | ||
| datas?: T[]; | ||
|
Comment on lines
+23
to
+30
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Good improvement: Generic interface enhances type safety. The generic function createAPIResponse<T>(input: ApiResponseinput<T>) {
return {
...input,
timestamp: new Date().toISOString(),
};
}Without this, the generic parameter won't propagate through the helper function. 🤖 Prompt for AI Agents |
||
| error?: string; | ||
| errors?: Record<string, string[]>; | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,4 +12,4 @@ export const loadSchema = Joi.object({ | |
| body: Joi.any(), | ||
| concurrency: Joi.number().min(1).default(10), | ||
| duration: Joi.number().min(1).default(30), | ||
| }).unknown(true); | ||
| }).unknown(false); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This The intent to reject unknown fields is good for strict validation. However, since To enforce strict rejection of unknown fields, either:
🤖 Prompt for AI Agents |
||
This file was deleted.
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,115 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import "dotenv/config"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { jest, describe, it, expect, beforeAll, afterAll } from "@jest/globals"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import request from "supertest"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import mongoose from "mongoose"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| jest.unstable_mockModule("../../src/services/emailService.js", () => ({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| verificationEmail: jest.fn<() => Promise<void>>().mockResolvedValue(undefined), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| })); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const testEmail = `auth+${Date.now()}-${Math.random().toString(16).slice(2)}@example.com`; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const testPassword = "Babylon.!1"; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const { default: app } = await import("../../src/app.js"); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const { default: connectDB } = await import("../../src/config/db.js"); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const { default: Users } = await import("../../src/models/users.js"); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const { default: processConfig } = await import("../../src/config/env.js"); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const { generateToken } = await import("../../src/utils/jwt.js"); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const registerUser = async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const registerResponse = await request(app) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .post("/api/auth/register") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .set("Content-Type", "application/json") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .set("Accept", "application/json") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .send({ email: testEmail, password: testPassword }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(registerResponse.status).toBe(201); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return registerResponse; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const verifyUser = async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const user = await Users.findOne({ email: testEmail }).lean(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(user).toBeTruthy(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const verifyKey = processConfig.JWTs.verifyEmail.key; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const verifyDuration = processConfig.JWTs.verifyEmail.duration; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(verifyKey).toBeTruthy(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(verifyDuration).toBeTruthy(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const token = await generateToken( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| id: user!._id.toString(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| email: user!.email, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| paid: user!.paid, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| verifyKey!, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| verifyDuration!, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const verifyResponse = await request(app) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .get(`/api/auth/verify/${token}`) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .set("Accept", "application/json"); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(verifyResponse.status).toBe(200); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return verifyResponse; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const loginUser = async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const loginResponse = await request(app) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .post("/api/auth/login") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .set("Content-Type", "application/json") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .set("Accept", "application/json") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .send({ email: testEmail, password: testPassword }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(loginResponse.status).toBe(200); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return loginResponse; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| beforeAll(async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| await connectDB(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (mongoose.connection.db) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| await mongoose.connection.db | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .collection("users") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .deleteMany({ email: testEmail }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| },20000); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| afterAll(async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (mongoose.connection.db) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| await mongoose.connection.db | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .collection("users") | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .deleteMany({ email: testEmail }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| await mongoose.disconnect(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| },20000); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+69
to
+85
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor formatting: Add space after comma in timeout parameter. 🔧 Proposed fix-},20000);
+}, 20000);Apply to both 📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| describe("Auth routes", () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| it("registers a new user", async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const registerResponse = await registerUser(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(registerResponse.body).toMatchObject({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| success: true, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| message: "User Created Successfully", | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const user = await Users.findOne({ email: testEmail }).lean(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(user).toBeTruthy(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(user?.verified).toBe(false); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| it("verifies a registered user", async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| await verifyUser(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const verifiedUser = await Users.findOne({ email: testEmail }).lean(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(verifiedUser?.verified).toBe(true); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| it("logs in a verified user", async () => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const loginResponse = await loginUser(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(loginResponse.body).toMatchObject({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| success: true, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| message: "User Logged In Successfully", | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| expect(loginResponse.headers["set-cookie"]).toBeDefined(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+87
to
+115
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Tests are sequentially dependent, which may cause cascading failures. The tests rely on shared state: "verifies a registered user" assumes "registers a new user" ran first, and "logs in a verified user" assumes verification completed. If any earlier test fails or is skipped, subsequent tests will fail with misleading errors. Consider moving the prerequisite steps into the test setup or using explicit dependencies. ♻️ Proposed refactor: Move shared setup into beforeAll or make tests independentOption 1: Move registration to beforeAll for dependent tests +let isRegistered = false;
+let isVerified = false;
+
describe("Auth routes", () => {
+ beforeAll(async () => {
+ await registerUser();
+ isRegistered = true;
+ await verifyUser();
+ isVerified = true;
+ });
+
it("registers a new user", async () => {
- const registerResponse = await registerUser();
- expect(registerResponse.body).toMatchObject({
+ // Registration already done in beforeAll, verify the state
+ const user = await Users.findOne({ email: testEmail }).lean();
+ expect(user).toBeTruthy();
+ });Option 2: Make each test fully independent (preferred for isolation) Each test registers its own user with a unique email, ensuring complete isolation. 🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: deepx4344/SurgeTest
Length of output: 108
🏁 Script executed:
Repository: deepx4344/SurgeTest
Length of output: 1797
🌐 Web query:
Joi stripUnknown precedence over unknown(false) validation order💡 Result:
In Joi,
stripUnknowneffectively wins overunknown(false)(the default) for object keys:unknown(false), Joi would normally raiseobject.unknown(“is not allowed”). But if you also setstripUnknown(e.g.{ stripUnknown: true }or{ stripUnknown: { objects: true } }), Joi will remove the unknown keys and not error. This is shown in the Joi repo issue repro: the same schema that errors withoutstripUnknownreturns{ error: null, value: <stripped> }withstripUnknownenabled. [1]object.unknown([allow])controls whether unknown keys are allowed/ignored at the schema level. [2]stripUnknownis a validation preference that deletes unknown keys from the validated value. [3][4]stripUnknownremoval happens even if the schema allows unknown keys viaobject().unknown()—it still strips them whenstripUnknownis on (the “unexpected interaction” noted in the same issue). [1]So, validation “order/precedence” for this behavior is: when
stripUnknownis enabled, unknown keys are stripped instead of producing anobject.unknownerror, regardless ofunknown(false)(and historically even regardless ofunknown(true)/.unknown()). [1]Practical takeaway
stripUnknown; keepunknown(false)(default).stripUnknown(you can keepunknown(false); it won’t error). [1][3]Sources: [1] [2] [3] [4]
🏁 Script executed:
Repository: deepx4344/SurgeTest
Length of output: 2422
stripUnknown: truedefault makesunknown(false)schemas ineffective.At line 9 of
src/routes/load.ts,validateSchema(loadSchema)is called without custom options, using the middleware's defaultstripUnknown: true. SinceloadSchemaexplicitly sets.unknown(false)to reject unknown keys, but the middleware strips unknown keys before schema validation, the schema's validation rule never gets triggered. Unknown properties are silently removed instead of returning a validation error.If schemas like
loadSchemaare intentionally strict about rejecting unknown fields, either:stripUnknown: truefrom the middleware defaults, or{ stripUnknown: false }when callingvalidateSchema(loadSchema)(and other strict schemas)🤖 Prompt for AI Agents