Skip to content

Commit

Permalink
cleanup some code
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperchupuDev committed Apr 17, 2024
1 parent efd4eaf commit bc3994e
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 35 deletions.
6 changes: 6 additions & 0 deletions .dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
APPLICATION_ID=""
DISCORD_TOKEN=""
# make sure to append /github to the end of the webhook URL
DISCORD_WEBHOOK=""
PUBLIC_KEY=""
WEBHOOK_SECRET=""
5 changes: 0 additions & 5 deletions .env.example

This file was deleted.

4 changes: 2 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Create empty .env file
run: touch .env
- name: Create empty .dev.vars file
run: touch .dev.vars

- name: Deploy commands to Discord
run: pnpm run deploy-commands
Expand Down
4 changes: 3 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ First, create an application on the [Discord Developer Portal](https://discord.c

It will be a used as a test application for development purposes of the bot.

Then, create a `.env` file at the root of the project with the following variables obtained from the dev portal:
Then, create a `.dev.vars` file at the root of the project with the following variables obtained from the dev portal:

```env
APPLICATION_ID=
DISCORD_TOKEN=
DISCORD_WEBHOOK=
PUBLIC_KEY=
WEBHOOK_SECRET=
```

### Running the Bot
Expand Down
14 changes: 13 additions & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,19 @@
"linter": {
"enabled": true,
"rules": {
"recommended": true
"recommended": true,
"correctness": {
"noUnusedImports": "error"
},
"style": {
"noNegationElse": "error",
"useBlockStatements": "error",
"useConsistentArrayType": "error",
"useFilenamingConvention": "error",
"useForOf": "error",
"useShorthandAssign": "error",
"useShorthandArrayType": "error"
}
}
},
"organizeImports": {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
"dev": "wrangler dev",
"start": "wrangler dev",
"deploy": "wrangler deploy",
"deploy-commands": "tsx --env-file=.env scripts/deploy-commands.ts",
"deploy-commands": "tsx --env-file=.dev.vars scripts/deploy-commands.ts",
"check": "biome check .",
"check:apply": "biome check --apply-unsafe .",
"format": "biome format --write .",
"lint": "biome lint .",
"typecheck": "tsc"
},
"devDependencies": {
Expand Down
35 changes: 15 additions & 20 deletions src/gh-webhook/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,57 +2,52 @@ import type { Env } from '..';

export async function handleGitHubWebhook(request: Request, env: Env): Promise<Response> {
if (request.method !== 'POST') {
return new Response('Method not allowed', { status: 405, statusText: 'Method Not Allowed' });
return new Response('Method not allowed', { status: 405 });
}

const githubSecret = env.WEBHOOK_SECRET;
const webhookUrl = env.DISCORD_WEBHOOK;

if (!githubSecret || !webhookUrl) {
return new Response('Internal server error', { status: 500, statusText: 'Internal Server Error' });
return new Response('Internal server error', { status: 500 });
}

const bodyText = await request.text().catch(() => null);
const headers = request.headers;

if (bodyText == null) {
return new Response('Failed to read request body', { status: 400, statusText: 'Bad Request' });
if (!bodyText) {
return new Response('Failed to read request body', { status: 400 });
}

const authorized = await isAuthorized(headers, bodyText, githubSecret);
const authorized = await isAuthorized(request.headers, bodyText, githubSecret);

if (!authorized) {
return new Response('Unauthorized', { status: 401, statusText: 'Unauthorized' });
return new Response('Unauthorized', { status: 401 });
}

let json: unknown | null;
let json: unknown;
try {
json = JSON.parse(bodyText);
} catch {
json = null;
}

if (json == null) {
return new Response('Failed to parse request body', { status: 400, statusText: 'Bad Request' });
return new Response('Failed to parse request body', { status: 400 });
}

const isHuman = await isHumanEvent(json);

if (!isHuman) {
return new Response('Event skipped', { status: 200, statusText: 'OK' });
return new Response('Webhook event triggered by bot, skipped', { status: 200 });
}

const sent = await sendToWebhook(json, headers, webhookUrl);
const sent = await sendToWebhook(bodyText, request.headers, webhookUrl);

if (!sent) {
return new Response('Failed to send to Discord', { status: 500, statusText: 'Internal Server Error' });
return new Response('Failed to send to Discord', { status: 500 });
}

return new Response('Event processed', { status: 200, statusText: 'OK' });
return new Response('Event processed', { status: 200 });
}

async function isAuthorized(headers: Headers, bodyText: string, githubSecret: string): Promise<boolean> {
const untrustedSignature = headers.get('x-hub-signature-256');
const untrustedSignature = headers.get('X-Hub-Signature-256');

if (untrustedSignature == null) {
return false;
Expand Down Expand Up @@ -93,7 +88,7 @@ async function isHumanEvent(json: unknown): Promise<boolean> {
);
}

async function sendToWebhook(json: unknown, headers: Headers, webhookUrl: string): Promise<boolean> {
async function sendToWebhook(body: string, headers: Headers, webhookUrl: string): Promise<boolean> {
const forwardHeaders = new Headers();

for (const [key, value] of headers) {
Expand All @@ -106,7 +101,7 @@ async function sendToWebhook(json: unknown, headers: Headers, webhookUrl: string
const response = await fetch(webhookUrl, {
method: 'POST',
headers: forwardHeaders,
body: JSON.stringify(json),
body,
});

return response.ok;
Expand Down
7 changes: 2 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ export default {
case '/github':
return handleGitHubWebhook(request, env);
default:
return handleDiscordInteraction(request, env);
return handleInteraction(request, env);
}
},
};

async function handleDiscordInteraction(request: Request, env: Env): Promise<Response> {
async function handleInteraction(request: Request, env: Env): Promise<Response> {
if (!request.headers.get('X-Signature-Ed25519') || !request.headers.get('X-Signature-Timestamp')) {
return Response.redirect('https://biomejs.dev');
}
Expand All @@ -37,10 +37,7 @@ async function handleDiscordInteraction(request: Request, env: Env): Promise<Res
}

const interaction = await request.json<APIInteraction>();
return handleInteraction(interaction, env);
}

async function handleInteraction(interaction: APIInteraction, env: Env): Promise<Response> {
if (isPing(interaction)) {
return reply(InteractionResponseType.Pong);
}
Expand Down

0 comments on commit bc3994e

Please sign in to comment.