Skip to content
Merged

a #2

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
1,346 changes: 834 additions & 512 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
"dependencies": {
"axios": "^1.13.2",
"bcrypt": "^6.0.0",
"bullmq": "^5.67.2",
"compression": "^1.8.1",
"cookie-parser": "^1.4.7",
"dotenv": "^17.2.3",
"express": "^5.2.1",
"express-rate-limit": "^8.2.1",
"ioredis": "^5.9.2",
"joi": "^18.0.2",
"jsonwebtoken": "^9.0.3",
"mongoose": "^9.0.2",
Expand Down
2 changes: 2 additions & 0 deletions public/src/routes/dashboard/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
const testId = res.test_id;
if(!testId){
status="Error: Server did not return a test ID"
running=false
if(pollInterval) clearInterval(pollInterval)
return
}
status = `Test started: ${testId}. Waiting for results...`;
Expand Down
1 change: 1 addition & 0 deletions src/controllers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +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()

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

Missing semicolon for consistency.

Line 49 is missing a semicolon, while similar statements in this file (lines 33, 41) include one.

🔧 Proposed fix
-  res.status(200).end()
+  res.status(200).end();
📝 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
res.status(200).end()
res.status(200).end();
🤖 Prompt for AI Agents
In `@src/controllers/auth.ts` at line 49, The statement using
res.status(200).end() is missing a trailing semicolon causing inconsistency with
other similar lines; update the statement (the res.status(200).end() call in the
auth controller) to include a semicolon at the end to match style of the nearby
statements (e.g., those on lines with res.status(...).end();).

});

export const me = asyncHandler(async (req, res) => {
Expand Down
14 changes: 12 additions & 2 deletions src/controllers/load.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import loadService from "../services/loadervice.js";
import loadService from "../services/loadService.js";
import { ApiResponseinput } from "../types/index.js";
import asyncHandler from "../utils/async.js";
import { createAPIResponse } from "../utils/index.js";

const load = new loadService();

export const startLoad = asyncHandler(async (req, res) => {
await load.start(req.body);
const config = req.body;
const testId = await load.createTest(config);
const dataToSend: ApiResponseinput = {
success: true,
message: "Task created successfully",
data: testId,
};
res.status(202).json(createAPIResponse(dataToSend));
});
2 changes: 1 addition & 1 deletion 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, stripUnknown: true }
options: Joi.ValidationOptions = { abortEarly: false }
) => {
return (req: Request, res: Response, next: NextFunction) => {
const target = (req as any)[property];
Expand Down
21 changes: 14 additions & 7 deletions src/models/test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mongoose from "mongoose";
import { HttpMethods, TestStatus } from "../types/index.js";

export const testSchema = new mongoose.Schema(
{
Expand All @@ -8,8 +9,8 @@ export const testSchema = new mongoose.Schema(
},
method: {
type: String,
enum: ["GET", "POST", "PUT", "DELETE", "PATCH"],
default: "GET",
enum: Object.values(HttpMethods),
required: true,
},
headers: {
type: Map,
Expand All @@ -25,13 +26,19 @@ export const testSchema = new mongoose.Schema(
},
duration: {
type: Number,
required: true, // in seconds
required: true,
default: 30,
},
name: {
type: String,
},
description: {
type: String,
},
status: {
type: String,
enum: ["pending", "running", "completed", "failed"],
default: "pending",
enum: Object.values(TestStatus),
default: TestStatus.pending,
},
results: {
totalRequests: { type: Number, default: 0 },
Expand All @@ -46,5 +53,5 @@ export const testSchema = new mongoose.Schema(
);

testSchema.index({ status: 1 });
const Test = mongoose.model("Test", testSchema);
export default Test;
const Tests = mongoose.model("Test", testSchema);
export default Tests;
2 changes: 1 addition & 1 deletion src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ 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", logout);
router.post("/logout",authMiddleware, logout);
router.get("/me", authMiddleware, me);

export default router;
4 changes: 3 additions & 1 deletion src/routes/load.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import express, { Router } from "express";

import { startLoad } from "../controllers/load.js";
import { validateSchema } from "../middlewares/joiValidation.js";
import { loadSchema } from "../validations/load.js";

const router: Router = express.Router();

router.post("/start", startLoad);
router.post("/start", validateSchema(loadSchema), startLoad);

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 authentication middleware on load testing endpoint.

The /start endpoint allows initiating load tests without authentication. This is a security risk—unauthenticated users could abuse this to launch load tests against arbitrary targets.

Add authMiddleware similar to other protected routes:

🔒 Proposed fix
+import authMiddleware from "../middlewares/auth.js";
+
 const router: Router = express.Router();
 
-router.post("/start", validateSchema(loadSchema), startLoad);
+router.post("/start", authMiddleware, validateSchema(loadSchema), startLoad);
🤖 Prompt for AI Agents
In `@src/routes/load.ts` at line 9, The POST /start route is missing
authentication; update the router.post declaration to include authMiddleware in
the middleware chain so only authenticated users can start load
tests—specifically modify the route using symbols router.post, validateSchema,
loadSchema and startLoad to insert authMiddleware (e.g., include authMiddleware
alongside validateSchema before startLoad) consistent with other protected
routes.


export default router;
14 changes: 7 additions & 7 deletions src/services/emailService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,20 @@ export const verificationEmail = async (
pass: processConfig.mailer.pass,
},
});
await transporter.sendMail({
from: `verify@${processConfig.name}.com`,
to: to,
subject: "Verify Your Email",
html: format?.html,
text: format?.text,
});
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,
subject: "Verify Your Email",
html: format?.html,
text: format?.text,
});
Comment on lines 25 to +38

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

Race condition: sendMail executes before verify callback completes.

transporter.verify() is asynchronous with a callback, but sendMail() is called immediately without waiting for verification to complete. This means emails are sent regardless of whether the transporter is properly configured.

Either remove the verify call (since it provides no protection), or promisify it and await before sending:

🔧 Proposed fix: promisify verify or remove it

Option 1: Remove verify (simpler, rely on sendMail errors)

     });
-    transporter.verify(function (error, success) {
-      if (error) {
-        logger.error(`Connection Error: `,error);
-      } else {
-        logger.info("Server is ready to send messages.");
-      }
-    });
     await transporter.sendMail({

Option 2: Await verify before sending

     });
-    transporter.verify(function (error, success) {
-      if (error) {
-        logger.error(`Connection Error: `,error);
-      } else {
-        logger.info("Server is ready to send messages.");
-      }
-    });
+    await transporter.verify().catch((error) => {
+      logger.error(`Connection Error: `, error);
+      throw error;
+    });
+    logger.info("Server is ready to send messages.");
     await transporter.sendMail({
📝 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
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,
subject: "Verify Your Email",
html: format?.html,
text: format?.text,
});
await transporter.sendMail({
from: `verify@${processConfig.name}.com`,
to: to,
subject: "Verify Your Email",
html: format?.html,
text: format?.text,
});
🤖 Prompt for AI Agents
In `@src/services/emailService.ts` around lines 25 - 38, transporter.verify is
called with a callback but sendMail is invoked immediately, causing a race;
update the flow in the email sending function to await verification before
sending by promisifying transporter.verify (or using util.promisify) and calling
await verifyPromise() prior to calling transporter.sendMail, or remove the
verify call entirely and handle sendMail errors—ensure you modify the code
around transporter.verify and transporter.sendMail in
src/services/emailService.ts so verification completes (or is removed) before
attempting to send.

} catch (e) {
logger.error("Error from send Emails", e);
throw createServiceError("SomeThing Went Wrong", 503);
Expand Down
16 changes: 16 additions & 0 deletions src/services/loadService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Undici from "undici";

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

class loadService {
createTest = async (configs: any): Promise<string> => {
const test = new Tests({
...configs
});
const savedTests = await test.save()
return savedTests._id.toString();
Comment on lines +7 to +12

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:

find . -type f -name "loadService.ts" | head -20

Repository: deepx4344/SurgeTest

Length of output: 92


🏁 Script executed:

find . -type f -name "*[Tt]est*.ts" -o -name "*[Tt]est*.js" | grep -E "(model|schema)" | head -20

Repository: deepx4344/SurgeTest

Length of output: 83


🏁 Script executed:

git ls-files | grep -i test | head -20

Repository: deepx4344/SurgeTest

Length of output: 100


🏁 Script executed:

cat -n src/services/loadService.ts

Repository: deepx4344/SurgeTest

Length of output: 529


🏁 Script executed:

cat -n src/models/test.ts

Repository: deepx4344/SurgeTest

Length of output: 1620


🏁 Script executed:

rg "createTest" --type ts --type js -B 2 -A 2

Repository: deepx4344/SurgeTest

Length of output: 645


🏁 Script executed:

rg "new loadService|loadService\(" --type ts --type js -B 2 -A 2

Repository: deepx4344/SurgeTest

Length of output: 331


🏁 Script executed:

fd "route" --type ts --type js | head -10

Repository: deepx4344/SurgeTest

Length of output: 232


🏁 Script executed:

cat -n src/controllers/load.ts

Repository: deepx4344/SurgeTest

Length of output: 743


🏁 Script executed:

rg "validate|schema|joi|zod" --type-add="ts:*.ts" -i | head -20

Repository: deepx4344/SurgeTest

Length of output: 1383


Whitelist persisted fields to prevent client-controlled status/results.

Spreading configs directly into the Mongoose model allows clients to override server-controlled fields like status and results. Extract only the intended fields from the input.

🛡️ Proposed fix
-  createTest = async (configs: any): Promise<string> => {
-    const test = new Tests({
-      ...configs
-    });
+  createTest = async (configs: any): Promise<string> => {
+    const {
+      url,
+      method,
+      name,
+      description,
+      headers,
+      body,
+      concurrency,
+      duration,
+    } = configs;
+    const test = new Tests({
+      url,
+      method,
+      name,
+      description,
+      headers,
+      body,
+      concurrency,
+      duration,
+    });
🤖 Prompt for AI Agents
In `@src/services/loadService.ts` around lines 7 - 12, The createTest function
currently spreads client-provided configs into the Tests model allowing override
of server-controlled fields like status and results; fix by whitelisting only
intended input fields from configs (e.g., title, description, params) when
constructing the Tests instance and explicitly set server-controlled fields
(status, results, createdBy, etc.) on the new Tests object before saving; update
createTest to use the Tests constructor with the extracted safe fields and
assign status/results values server-side to prevent client-controlled mutation.

};
}

export default loadService;
10 changes: 0 additions & 10 deletions src/services/loadervice.ts

This file was deleted.

25 changes: 20 additions & 5 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { InferSchemaType } from "mongoose";
import { usersSchema } from "../models/users.js";
import { testSchema } from "../models/test.js";

export type User =InferSchemaType<typeof usersSchema>
export type User = InferSchemaType<typeof usersSchema>;

export interface TestResults {
totalRequests: number;
Expand All @@ -11,7 +11,7 @@ export interface TestResults {
errors: string[];
}

export type Test = InferSchemaType<typeof testSchema>
export type Test = InferSchemaType<typeof testSchema>;

export interface ServiceErrorInput {
message: string;
Expand All @@ -25,9 +25,9 @@ export interface ApiResponseinput {
message: string;
token?: string;
tokens?: Tokens;
user?:User;
data?: object | string;
datas?: Record<string, string[]> | object[];
user?: User;
data?: string;
datas?: string[]
error?: string;
errors?: Record<string, string[]>;
}
Expand All @@ -47,3 +47,18 @@ export interface configs {
totalPerTest: number;
testPerHour: number;
}

export enum TestStatus {
pending = "PENDING",
running = "RUNNING",
completed = "COMPLETED",
failed = "FAILED",
}

export enum HttpMethods {
get = "GET",
post = "POST",
put = "PUT",
delete = "DELETE",
patch = "PATCH",
}
15 changes: 15 additions & 0 deletions src/validations/load.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import Joi from "joi";
import { HttpMethods } from "../types/index.js";

export const loadSchema = Joi.object({
url: Joi.string().required(),
method: Joi.string()
.valid(...Object.values(HttpMethods))
.required(),
name: Joi.string().max(30).allow(""),
description: Joi.string().max(255).allow(""),
headers: Joi.any(),
body: Joi.any(),
concurrency: Joi.number().min(1).default(10),
duration: Joi.number().min(1).default(30),
}).unknown(true);
Comment on lines +4 to +15

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:

# First, let's see the full context of the file
head -30 src/validations/load.ts

Repository: deepx4344/SurgeTest

Length of output: 528


🏁 Script executed:

# Search for where loadSchema is used
rg "loadSchema" --type ts

Repository: deepx4344/SurgeTest

Length of output: 278


🏁 Script executed:

# Check other Joi schemas in the codebase for comparison
rg "Joi\.object" --type ts -A 5 | head -100

Repository: deepx4344/SurgeTest

Length of output: 1164


🏁 Script executed:

# Check if there's a pattern of using .unknown() in other schemas
rg "\.unknown\(" --type ts

Repository: deepx4344/SurgeTest

Length of output: 104


🏁 Script executed:

# Check the validateSchema middleware to understand how it processes the schema
rg "validateSchema" --type ts -B 5 -A 10

Repository: deepx4344/SurgeTest

Length of output: 2800


🏁 Script executed:

# Check the startLoad handler to see what it does with the payload
rg "startLoad" --type ts -B 3 -A 15

Repository: deepx4344/SurgeTest

Length of output: 1283


🏁 Script executed:

# Check if there are any comments or documentation about why unknown(true) is used
rg "unknown" --type ts -B 2 -A 2

Repository: deepx4344/SurgeTest

Length of output: 1927


🏁 Script executed:

# Get the full validateSchema middleware implementation
cat -n src/middlewares/joiValidation.ts

Repository: deepx4344/SurgeTest

Length of output: 1147


🏁 Script executed:

# Check what load.createTest does with the config
rg "createTest" --type ts -B 2 -A 15

Repository: deepx4344/SurgeTest

Length of output: 1208


🏁 Script executed:

# Check the loadService to understand the full flow
fd "loadService" --type ts

Repository: deepx4344/SurgeTest

Length of output: 232


🏁 Script executed:

# Find the Tests model to see if it has schema validation
rg "Tests" --type ts | grep -E "(schema|model|interface)" | head -20

Repository: deepx4344/SurgeTest

Length of output: 239


🏁 Script executed:

# Look for the database model definition
fd "test" --type ts | grep -i model

Repository: deepx4344/SurgeTest

Length of output: 232


🏁 Script executed:

# Search for MongoDB model definitions
rg "new Schema\|mongoose.Schema" --type ts -B 2 -A 5

Repository: deepx4344/SurgeTest

Length of output: 45


🏁 Script executed:

# Check what the Tests model looks like
rg "Tests" --type ts -B 3 -A 10 | grep -A 15 "export\|class\|new"

Repository: deepx4344/SurgeTest

Length of output: 1419


🏁 Script executed:

# Get the full test.ts model definition
cat -n src/models/test.ts

Repository: deepx4344/SurgeTest

Length of output: 1620


Reject unknown keys in load payloads.

unknown(true) permits clients to send unexpected fields that reach the MongoDB model, including server-controlled fields like status and results. This bypasses intended field restrictions. Change to unknown(false) to enforce strict validation.

🔒 Proposed fix
-}).unknown(true);
+}).unknown(false);
📝 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
export const loadSchema = Joi.object({
url: Joi.string().required(),
method: Joi.string()
.valid(...Object.values(HttpMethods))
.required(),
name: Joi.string().max(30).allow(""),
description: Joi.string().max(255).allow(""),
headers: Joi.any(),
body: Joi.any(),
concurrency: Joi.number().min(1).default(10),
duration: Joi.number().min(1).default(30),
}).unknown(true);
export const loadSchema = Joi.object({
url: Joi.string().required(),
method: Joi.string()
.valid(...Object.values(HttpMethods))
.required(),
name: Joi.string().max(30).allow(""),
description: Joi.string().max(255).allow(""),
headers: Joi.any(),
body: Joi.any(),
concurrency: Joi.number().min(1).default(10),
duration: Joi.number().min(1).default(30),
}).unknown(false);
🤖 Prompt for AI Agents
In `@src/validations/load.ts` around lines 4 - 15, The loadSchema validation
currently calls unknown(true) which allows unexpected client fields (including
server-controlled fields like status/results) to pass through; update loadSchema
to reject unknown keys by replacing unknown(true) with unknown(false) so only
the defined properties on the Joi schema (url, method, name, description,
headers, body, concurrency, duration) are accepted and extraneous fields are
rejected before reaching the MongoDB model.