Files
amari/src/modules/processGitHubEvent.ts
T
naomi 994f50c174
Node.js CI / Lint and Test (push) Successful in 44s
feat: protect github route with secret too
2025-08-27 19:04:06 -07:00

85 lines
2.8 KiB
TypeScript

/**
* @copyright NHCarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { logger } from "../utils/logger.js";
import type { Amari } from "../interfaces/amari.js";
import type { IssueCreated,
PullRequestCreated,
GithubPayload } from "../interfaces/github.js";
import type { FastifyRequest, FastifyReply } from "fastify";
const isIssue = (body: GithubPayload): body is IssueCreated => {
return "issue" in body;
};
const isPull = (body: GithubPayload): body is PullRequestCreated => {
return "pull_request" in body;
};
/**
* Handles a payload from a GitHub webhook.
* @param amari - Amari's instance.
* @param request - The Fastify request payload.
* @param response - The Fastify reply class.
*/
// eslint-disable-next-line max-statements, max-lines-per-function -- STFU.
export const processGithubEvent = async(
amari: Amari,
request: FastifyRequest<{
// eslint-disable-next-line @typescript-eslint/naming-convention -- Fastify standard.
Body: GithubPayload;
// eslint-disable-next-line @typescript-eslint/naming-convention -- Fastify standard.
Querystring: { secret: string };
}>,
response: FastifyReply,
): Promise<void> => {
const { secret } = request.query;
if (secret !== process.env.GH_WEBHOOK_SECRET) {
await response.status(403).send({
message: "Invalid secret provided!",
});
}
const event = request.headers["x-github-event"];
if (typeof event !== "string") {
await response.status(400).
send({ message: "Invalid GitHub event header." });
return;
}
if (event === "ping") {
await response.status(200).send({ message: "Pong!" });
return;
}
const { action } = request.body;
await response.status(200).send({ message: "Payload received!" });
if (action === "opened" && event === "issues" && isIssue(request.body)) {
await logger.log("info", "Processing new issue");
const { issue, repository } = request.body;
const { number } = issue;
const { owner, name } = repository;
await amari.github.rest.issues.addAssignees({
assignees: [ "naomi-lgbt" ],
// eslint-disable-next-line @typescript-eslint/naming-convention -- Github SDK requirement.
issue_number: number,
owner: owner.login,
repo: name,
});
return;
}
if (action === "opened" && event === "pull_request" && isPull(request.body)) {
await logger.log("info", "Processing new PR");
const { pull_request: pr, repository } = request.body;
const { number } = pr;
const { owner, name } = repository;
await amari.github.rest.pulls.requestReviewers({
owner: owner.login,
// eslint-disable-next-line @typescript-eslint/naming-convention -- Github SDK requirement.
pull_number: number,
repo: name,
reviewers: [ "naomi-lgbt" ],
});
}
};