Skip to content

Commit

Permalink
refactor: organize into github directory
Browse files Browse the repository at this point in the history
the future vision of this kernel is to be able to handle
webhook events from other platforms like telegram as well
  • Loading branch information
0x4007 committed Feb 3, 2024
1 parent 7d77f6f commit 75c5a62
Show file tree
Hide file tree
Showing 10 changed files with 32 additions and 27 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ The kernel is designed to:
You need to obtain a private key from your GitHub App settings and convert it to Public-Key Cryptography Standards #8 (PKCS#8) format. You can use the following command to perform this conversion and append the result to your `.dev.vars` file:

```sh
echo "PRIVATE_KEY=\"$(openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in YOUR_PRIVATE_KEY.PEM | awk 'BEGIN{ORS="\\n"} 1')\"" >> .dev.vars
```
echo "PRIVATE_KEY=\"$(openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in YOUR_PRIVATE_KEY.PEM | awk 'BEGIN{ORS="\\n"} 1')\"" >> .dev.vars
```

###### Please replace `YOUR_PRIVATE_KEY.PEM` with the path to your actual PEM file when running the command.

- `WEBHOOK_SECRET`
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"scripts": {
"dev": "run-p worker proxy",
"predev": "lsof -i tcp:8787 | grep LISTEN | awk '{print $2}' | xargs kill -9",
"predev": "lsof -i tcp:8787 | grep LISTEN | awk '{print $2}' | xargs kill -9",
"format": "run-s format:lint format:prettier format:cspell",
"format:lint": "eslint --fix .",
"format:prettier": "prettier --write .",
Expand Down
File renamed without changes.
6 changes: 3 additions & 3 deletions src/context.ts → src/github/github-context.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { EmitterWebhookEvent as WebhookEvent, EmitterWebhookEventName as WebhookEventName } from "@octokit/webhooks";
import { customOctokit } from "./octokit";
import { customOctokit } from "./github-client";

export class Context<T extends WebhookEventName = WebhookEventName> {
export class GitHubContext<T extends WebhookEventName = WebhookEventName> {
public key: WebhookEventName;
public name: WebhookEventName;
public id: string;
Expand All @@ -21,4 +21,4 @@ export class Context<T extends WebhookEventName = WebhookEventName> {
}
}

export type SimplifiedContext = Omit<Context, keyof WebhookEventName>;
export type SimplifiedContext = Omit<GitHubContext, keyof WebhookEventName>;
8 changes: 4 additions & 4 deletions src/event-handler.ts → src/github/github-event-handler.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { Webhooks } from "@octokit/webhooks";
import { Context, SimplifiedContext } from "./context";
import { customOctokit } from "./octokit";
import { customOctokit } from "./github-client";
import { GitHubContext, SimplifiedContext } from "./github-context";

export type Options = {
webhookSecret: string;
appId: string | number;
privateKey: string;
};

export class EventHandler {
export class GitHubEventHandler {
public webhooks: Webhooks<SimplifiedContext>;
public on: Webhooks<SimplifiedContext>["on"];
public onAny: Webhooks<SimplifiedContext>["onAny"];
Expand Down Expand Up @@ -38,7 +38,7 @@ export class EventHandler {
},
});

return new Context(event, octokit);
return new GitHubContext(event, octokit);
},
});

Expand Down
4 changes: 2 additions & 2 deletions src/handlers/index.ts → src/github/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EventHandler } from "../event-handler";
import { GitHubEventHandler } from "../github-event-handler";
import { handleIssueCommentCreated } from "./issue/comment_created";

export function bindHandlers(webhooks: EventHandler) {
export function bindHandlers(webhooks: GitHubEventHandler) {
webhooks.on("issue_comment.created", handleIssueCommentCreated);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Context } from "../../context";
import { GitHubContext } from "../../github-context";

export async function handleIssueCommentCreated(event: Context<"issue_comment.created">) {
export async function handleIssueCommentCreated(event: GitHubContext<"issue_comment.created">) {
if (event.payload.comment.user.type === "Bot") {
console.log("Skipping bot comment");
return;
Expand Down
File renamed without changes.
File renamed without changes.
30 changes: 17 additions & 13 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,36 @@
import { EmitterWebhookEventName as WebhookEventName, emitterEventNames } from "@octokit/webhooks";
import { Value } from "@sinclair/typebox/value";
import { EventHandler } from "./event-handler";
import { bindHandlers } from "./handlers";
import { Env, envSchema } from "./types/env";
import { GitHubEventHandler } from "./github/github-event-handler";
import { bindHandlers } from "./github/handlers";
import { Env, envSchema } from "./github/types/env";
export default {
async fetch(request: Request, env: Env): Promise<Response> {
try {
validateEnv(env);
const eventName = getEventName(request);
const signatureSHA256 = getSignature(request);
const id = getId(request);
const eventHandler = new EventHandler({ webhookSecret: env.WEBHOOK_SECRET, appId: env.APP_ID, privateKey: env.PRIVATE_KEY });
const eventHandler = new GitHubEventHandler({ webhookSecret: env.WEBHOOK_SECRET, appId: env.APP_ID, privateKey: env.PRIVATE_KEY });
bindHandlers(eventHandler);
await eventHandler.webhooks.verifyAndReceive({ id, name: eventName, payload: await request.text(), signature: signatureSHA256 });
return new Response("ok\n", { status: 200, headers: { "content-type": "text/plain" } });
} catch (error) {
console.error(error);
let status = 500;
let errorMessage = "An unspecified error occurred";
if (error instanceof AggregateError) {
const err = error.errors[0];
errorMessage = err.message ? `${err.name}: ${err.message}` : "Error: An unspecified error occurred";
status = typeof err.status !== "undefined" ? err.status : 500;
}
return new Response(JSON.stringify({ error: errorMessage }), { status: status, headers: { "content-type": "application/json" } });
return handleUncaughtError(error);
}
},
};
function handleUncaughtError(error: unknown) {
console.error(error);
let status = 500;
let errorMessage = "An uncaught error occurred";
if (error instanceof AggregateError) {
const err = error.errors[0];
errorMessage = err.message ? `${err.name}: ${err.message}` : `Error: ${errorMessage}`;
status = typeof err.status !== "undefined" ? err.status : 500;
}
return new Response(JSON.stringify({ error: errorMessage }), { status: status, headers: { "content-type": "application/json" } });
}

function validateEnv(env: Env): void {
if (!Value.Check(envSchema, env)) {
const errors = [...Value.Errors(envSchema, env)];
Expand Down

0 comments on commit 75c5a62

Please sign in to comment.