Skip to content
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

Rate Limit response in JSON format #5

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
22 changes: 20 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import rateLimit from "express-rate-limit";
import { port } from "./params/params";
import { HttpError } from "./utils/httpError";
import { tcpPortsScan } from "./tcpScan/tcpPortsScan";
import { isValidIp, arePortsInRange, isInLimitNumberOfPorts } from "./utils/requestAssertions";
import {
isValidIp,
arePortsInRange,
isInLimitNumberOfPorts,
} from "./utils/requestAssertions";
import { parseSanitizePortsReq } from "./utils/parseSanitizeTcpPortsReq";
import { PortsScan } from "./types/types";

Expand All @@ -17,6 +21,17 @@ const limiter = rateLimit({
// error code when too many requests: 429
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs

// Parse the response to JSON when rate limit is triggered
handler: (_, res) => {
const errorResponse = {
status: "error",
message: "Too many requests, please try again later!",
code: 429,
};

res.status(429).json(errorResponse);
},
});

// apply to all requests
Expand Down Expand Up @@ -44,7 +59,10 @@ app.get("/:host", async (req, res) => {
throw new HttpError("Too many ports introduced, no more than 20", 400);

try {
portsScanResponse.tcpPorts = await tcpPortsScan({ ports: ports.tcpPorts, host });
portsScanResponse.tcpPorts = await tcpPortsScan({
ports: ports.tcpPorts,
host,
});
} catch (e) {
throw new HttpError(`Error scanning tcp ports. Error: ${e}`, 500);
}
Expand Down