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

bug[website-builder]: [issue#1057 correct functions and convert to ts] #6

Open
wants to merge 4 commits into
base: the-one
Choose a base branch
from
Open
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 .github/workflows/cron.stale.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ jobs:
- name: Unassign contributor after days of inactivity
uses: BoundfoxStudios/action-unassign-contributor-after-days-of-inactivity@v1.0.3
with:
last-activity: 14
last-activity: 14
106 changes: 0 additions & 106 deletions index.js

This file was deleted.

133 changes: 133 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import express, {Request, Response} from "express";
Idrinth marked this conversation as resolved.
Show resolved Hide resolved
import {exec} from "child_process";
import crypto from "crypto";
import dotenv from "dotenv";

dotenv.config();
// waiting for replies
const app = express();
const port = process.env.PORT;
const secret = process.env.GITHUB_SECRET;
if(!secret) {
console.error("Error: GITHUB_SECRET environment variable is not set.");
process.exit(1);
};

let isDocumentationWebsiteUpdated = false;
let isMindmapUpdated = false;
let contributorsBuildRequired = false;

let documentationWebsiteBuildTime = 0;
let mindmapBuildTime = 0;
let contributorsBuildTime = 0;

app.use(express.json());

app.post("/webhook", async (req: Request, res: Response) => {
console.log("Request received");
Copy link
Contributor

Choose a reason for hiding this comment

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

Sanitize user-provided values before logging.

Logging user-provided values directly can lead to log injection attacks.

- console.log("Request received");
+ console.log("Request received");

Committable suggestion was skipped due to low confidence.

const signature = req.headers["x-hub-signature"] as string;
aceppaluni marked this conversation as resolved.
Show resolved Hide resolved

if(!signature) {
throw new Error("Please provide a valid signature")
}

const payload = JSON.stringify(req.body);
const hmac = crypto.createHmac("sha1", secret)

const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`

if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) {
const {result, respMessage} = await getBranchStatus(req.body);
console.log("Result: ", result);
res.status(200).send({ result, respMessage });
} else {
res.status(400).send({ error: "Invalid GitHub signature. Ensure the secret is correctly configured." });
}
});

interface BranchStatus {
result: number;
respMessage: string;
};

Idrinth marked this conversation as resolved.
Show resolved Hide resolved
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

const executeCmd = async (cmd: string) => {
try {
const {stdout, stderr} = await exec(cmd);
Fixed Show fixed Hide fixed
aceppaluni marked this conversation as resolved.
Show resolved Hide resolved
Dismissed Show dismissed Hide dismissed
return stderr + "\n" + stdout;
} catch (error: unknown) {
console.error(`exec error: ${error}`);
throw new Error("Command execution failed. Check logs for details.");
};
Idrinth marked this conversation as resolved.
Show resolved Hide resolved
aceppaluni marked this conversation as resolved.
Show resolved Hide resolved
};

const getBranchStatus = async (req: Request): Promise<BranchStatus> => {
console.log("Webhook received successfully");

const branchName = req.body?.ref?.split("/").pop();

if (!branchName) {
return { result: 400, respMessage: "Branch name not found in the request." };
}

if (branchName === process.env.BRANCH_NAME) {
const { status, message } = await buildProject();
return { result: status, respMessage: message };
}

return { result: 200, respMessage: "Build not required." };

};

Idrinth marked this conversation as resolved.
Show resolved Hide resolved
const isUpdateRequired = () => {
const currentTime = Date.now()
const mindMapUpdateInterval = Number.parseInt(process.env.MINDMAP_UPDATE_TIME_INTERVAL ?? "10000");
Copy link
Member

Choose a reason for hiding this comment

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

this never changes during the run time, please only calculate once.

const documentationWebsiteUpdateInterval = Number.parseInt(process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL ?? "10000");
Copy link
Member

Choose a reason for hiding this comment

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

this is static during a run, please only calculate once.

isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindMapUpdateInterval;
isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > documentationWebsiteUpdateInterval;
return isMindmapUpdated || isDocumentationWebsiteUpdated;
};

const buildProject = async (): Promise<{ status: number; message: string }> => {
Idrinth marked this conversation as resolved.
Show resolved Hide resolved
const currentTime = Date.now();
const contributionUpdateTimeInterval = Number.parseInt(process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL ?? "10000");
if (!isUpdateRequired()) {
if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > contributionUpdateTimeInterval) {
console.log("No update required, updating the contributors only");
await initiateBuild("npm run contributor-build", process.env.DOCUMENTATION_WEBSITE_PATH!, process.env.DOCUMENTATION_WEBSITE_DEST_PATH!);
contributorsBuildTime = currentTime;
contributorsBuildRequired = false;
return { status: 200, message: "Contributors build has been created." };
} else {
contributorsBuildRequired = true;
return { status: 202, message: "Contributors build will be done after the next build." };
}
}
if (isMindmapUpdated) {
console.log("Building Mindmap");
await initiateBuild("npm run build", process.env.MINDMAP_PATH!, process.env.MINDMAP_DEST_PATH!);
mindmapBuildTime = currentTime;
contributorsBuildTime = currentTime;
isMindmapUpdated = false;
}

if (isDocumentationWebsiteUpdated) {
console.log("Building Documentation Website");
await initiateBuild("npm run build", process.env.DOCUMENTATION_WEBSITE_PATH!, process.env.DOCUMENTATION_WEBSITE_DEST_PATH!);
documentationWebsiteBuildTime = currentTime;
contributorsBuildTime = currentTime;
isDocumentationWebsiteUpdated = false;
}

return {status: 200, message: "Contributors build will be done after the next build."};
};
Idrinth marked this conversation as resolved.
Show resolved Hide resolved

const initiateBuild = async (command: string, projectPath: string, destPath: string) => {
await executeCmd(`cd ${(projectPath)}/ && git pull`);
await executeCmd(`cd ${(projectPath)}/ && npm ci`);
await executeCmd(`cd ${(projectPath)}/ && ${(command)}`);
await executeCmd(`cp -r ${(projectPath)}/dist/ ${(destPath)}/`);
};
aceppaluni marked this conversation as resolved.
Show resolved Hide resolved
100 changes: 100 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading