Skip to content
Open

a #3

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/controllers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const refresh = asyncHandler(async (req, res) => {
const newToken: string = await auth.refresh(tokens.refreshToken);
tokens.accessToken = newToken;
res.cookie("tokens", tokens, cookieOptions);
res.status(200).end()
res.status(200).end();
});

export const me = asyncHandler(async (req, res) => {
Expand Down
4 changes: 2 additions & 2 deletions src/middlewares/joiValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ApiResponseinput } from "../types/index.js";
export const validateSchema = (
schema: Joi.Schema,
property: "body" | "query" | "params" = "body",
options: Joi.ValidationOptions = { abortEarly: false }
options: Joi.ValidationOptions = { abortEarly: false, stripUnknown: true },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for schemas using unknown(false)
rg -n 'unknown\s*\(\s*false\s*\)' --type ts

Repository: deepx4344/SurgeTest

Length of output: 108


🏁 Script executed:

#!/bin/bash
# Check the joiValidation.ts file
echo "=== joiValidation.ts ==="
cat -n src/middlewares/joiValidation.ts | head -50

echo -e "\n=== load.ts schema context ==="
cat -n src/validations/load.ts

Repository: deepx4344/SurgeTest

Length of output: 1797


🌐 Web query:

Joi stripUnknown precedence over unknown(false) validation order

💡 Result:

In Joi, stripUnknown effectively wins over unknown(false) (the default) for object keys:

  • If you validate an object with extra keys using unknown(false), Joi would normally raise object.unknown (“is not allowed”). But if you also set stripUnknown (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 without stripUnknown returns { error: null, value: <stripped> } with stripUnknown enabled. [1]
  • object.unknown([allow]) controls whether unknown keys are allowed/ignored at the schema level. [2]
  • stripUnknown is a validation preference that deletes unknown keys from the validated value. [3][4]
  • Also, stripUnknown removal happens even if the schema allows unknown keys via object().unknown()—it still strips them when stripUnknown is on (the “unexpected interaction” noted in the same issue). [1]

So, validation “order/precedence” for this behavior is: when stripUnknown is enabled, unknown keys are stripped instead of producing an object.unknown error, regardless of unknown(false) (and historically even regardless of unknown(true)/.unknown()). [1]

Practical takeaway

  • Want an error on extra keys? Don’t use stripUnknown; keep unknown(false) (default).
  • Want to silently drop extra keys? Use stripUnknown (you can keep unknown(false); it won’t error). [1][3]

Sources: [1] [2] [3] [4]


🏁 Script executed:

#!/bin/bash
# Search for usage of validateSchema with loadSchema
echo "=== Looking for validateSchema usage ==="
rg -n 'validateSchema' --type ts -A 3 -B 1

echo -e "\n=== Looking for loadSchema usage ==="
rg -n 'loadSchema' --type ts -A 2 -B 1

Repository: deepx4344/SurgeTest

Length of output: 2422


stripUnknown: true default makes unknown(false) schemas ineffective.

At line 9 of src/routes/load.ts, validateSchema(loadSchema) is called without custom options, using the middleware's default stripUnknown: true. Since loadSchema explicitly 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 loadSchema are intentionally strict about rejecting unknown fields, either:

  1. Remove stripUnknown: true from the middleware defaults, or
  2. Pass custom options { stripUnknown: false } when calling validateSchema(loadSchema) (and other strict schemas)
🤖 Prompt for AI Agents
In `@src/middlewares/joiValidation.ts` at line 10, The middleware default options
set stripUnknown: true which removes unknown properties before Joi runs, so
schemas that use .unknown(false) (e.g. loadSchema used via
validateSchema(loadSchema) in src/routes/load.ts) never get an "unknown field"
error; fix by either removing stripUnknown: true from the default
Joi.ValidationOptions in the middleware (options variable in joiValidation.ts)
or make validateSchema accept/forward custom options and update the call site
validateSchema(loadSchema) to pass { stripUnknown: false } for strict schemas
like loadSchema so Joi's .unknown(false) can reject extra keys.

) => {
return (req: Request, res: Response, next: NextFunction) => {
const target = (req as any)[property];
Expand All @@ -24,4 +24,4 @@ export const validateSchema = (
(req as any)[property] = value;
return next();
};
};
};
File renamed without changes.
12 changes: 10 additions & 2 deletions src/routes/auth.ts
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";
Expand All @@ -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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Missing rate limiting and no guard against missing cookies.

The /refresh endpoint lacks the authlimiter middleware that protects /login and /register. This could allow attackers to abuse the refresh mechanism.

Additionally, the refresh controller (in src/controllers/auth.ts, lines 44-49) accesses req.signedCookies["tokens"].refreshToken without checking if tokens exists. If the cookie is missing, this will throw a TypeError.

Consider:

  1. Adding authlimiter to prevent abuse
  2. Adding validation for cookie presence (either via middleware or in the controller)
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

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
router.post("/refresh", refresh);
router.post("/refresh", authlimiter, refresh);
🤖 Prompt for AI Agents
In `@src/routes/auth.ts` at line 21, The /refresh route currently lacks the
authlimiter middleware and the refresh controller (function refresh in
src/controllers/auth.ts) dereferences req.signedCookies["tokens"].refreshToken
without checking for tokens, which can throw a TypeError and allows brute
forcing; update the router.post("/refresh", refresh) registration to include the
existing authlimiter middleware (same as used for /login and /register) and add
a guard at the start of the refresh controller to validate presence of
req.signedCookies["tokens"] and tokens.refreshToken, returning a 401 JSON API
response (using createAPIResponse) if missing; ensure the change references the
refresh handler and authlimiter symbol so the middleware and null-check are
applied consistently.

router.get("/me", authMiddleware, me);

export default router;
7 changes: 0 additions & 7 deletions src/services/emailService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,6 @@ export const verificationEmail = async (
pass: processConfig.mailer.pass,
},
});
transporter.verify(function (error, success) {
if (error) {
logger.error(`Connection Error: `,error);
} else {
logger.info("Server is ready to send messages.");
}
});
await transporter.sendMail({
from: `verify@${processConfig.name}.com`,
to: to,
Expand Down
3 changes: 1 addition & 2 deletions src/services/loadService.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import Undici from "undici";

import Test from "../models/test.js";
import Tests from "../models/test.js";
import Tests from "../models/load.js";

class loadService {
createTest = async (configs: any): Promise<string> => {
Expand Down
8 changes: 4 additions & 4 deletions src/types/index.ts
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>;

Expand All @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Good improvement: Generic interface enhances type safety.

The generic ApiResponseinput<T> allows for typed data and datas fields. However, for consumers to fully benefit, createAPIResponse in src/utils/index.ts (line 13-18) should also be made 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
In `@src/types/index.ts` around lines 23 - 30, The ApiResponseinput<T> generic
isn’t propagated because createAPIResponse is not generic; update the
createAPIResponse function to accept a generic type parameter (e.g., function
createAPIResponse<T>(input: ApiResponseinput<T>)) and have it return the
appropriately typed response including the added timestamp so callers receive
the correct generic typing for data/datas; reference the ApiResponseinput and
createAPIResponse symbols when making this change.

error?: string;
errors?: Record<string, string[]>;
}
Expand Down
2 changes: 1 addition & 1 deletion src/validations/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

This unknown(false) is effectively a no-op due to middleware defaults.

The intent to reject unknown fields is good for strict validation. However, since joiValidation.ts now defaults to stripUnknown: true, unknown properties are stripped before this check runs, meaning this constraint will never trigger a validation error.

To enforce strict rejection of unknown fields, either:

  1. Remove stripUnknown from the middleware defaults, or
  2. Pass { stripUnknown: false } when calling validateSchema(loadSchema) in the route
🤖 Prompt for AI Agents
In `@src/validations/load.ts` at line 15, The unknown(false) check in loadSchema
is ineffective because the middleware in joiValidation.ts currently strips
unknown properties by default; update the call site that applies
validateSchema(loadSchema) to pass an override option { stripUnknown: false }
(or alternatively remove/disable stripUnknown in joiValidation.ts) so that
unknown(false) can actually reject unknown fields; reference the loadSchema
defined in src/validations/load.ts and the validateSchema(...) usage in your
route/middleware to apply the fix.

54 changes: 0 additions & 54 deletions tests/auth.test.ts

This file was deleted.

115 changes: 115 additions & 0 deletions tests/auth/auth.test.ts
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Minor formatting: Add space after comma in timeout parameter.

🔧 Proposed fix
-},20000);
+}, 20000);

Apply to both beforeAll (line 76) and afterAll (line 85).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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);
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);
🤖 Prompt for AI Agents
In `@tests/auth/auth.test.ts` around lines 69 - 85, Fix the minor formatting in
the test hooks by adding a space after the comma in the timeout parameter for
both beforeAll and afterAll; locate the beforeAll(...) and afterAll(...)
invocations (which call connectDB(), use mongoose.connection.db to deleteMany on
the "users" collection with testEmail, and call mongoose.disconnect()) and
change the timeout argument formatting from "},20000);" to "}, 20000);" in both
places.


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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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 independent

Option 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
In `@tests/auth/auth.test.ts` around lines 87 - 115, The tests are dependent on
shared state; make them independent by either (A) moving the shared setup into a
beforeAll that calls registerUser() (and verifyUser() if needed) and then
querying Users.findOne({ email: testEmail }) in tests, or (B, preferred) have
each it() create its own user by calling registerUser() with a unique email and,
when needed, calling verifyUser() or loginUser() within the same test so
registerUser, verifyUser, and loginUser are invoked locally; update assertions
to use the local email and keep Users.findOne({ email: testEmail }) references
consistent with the chosen approach.

Loading