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

feat: implement webhook event for user installs #101

Merged
merged 2 commits into from
Oct 25, 2024
Merged
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
9 changes: 6 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# TOKENS [REQUIRED]
TOKEN=

MONGO_CONNECTION=
SENTRY_DSN=
PUBLIC_KEY=

NODE_ENV=


# OPTIONALS
# TOPGG [OPTIONAL]
TOPGG_TOKEN=
DBL_TOKEN=
NODE_ENV=

# WEBHOOKS [OPTIONAL]
GUILD=
Expand All @@ -17,3 +19,4 @@ SUGGESTION=
CONTACT_US=
COMMANDS_USED=
BUG_REPORTS=

1 change: 1 addition & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
MONGO_CONNECTION: ${{secrets.MONGO_CONNECTION}}
AUTH_TOKEN: ${{secrets.AUTH_TOKEN}}
SENTRY_DSN: ${{secrets.SENTRY_DSN}}
PUBLIC_KEY: ${{secrets.PUBLIC_KEY}}
DBL_TOKEN: ${{secrets.DBL_TOKEN}}
BUG_REPORTS: ${{secrets.BUG_REPORTS}}
COMMANDS_USED: ${{secrets.COMMANDS_USED}}
Expand Down
45 changes: 45 additions & 0 deletions src/api/controllers/discord-webhooks.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { SkyHelper as BotService } from "#bot/structures/SkyHelper";
import { Body, Controller, Inject, Post, Req } from "@nestjs/common";

Check warning on line 2 in src/api/controllers/discord-webhooks.controller.ts

View workflow job for this annotation

GitHub Actions / Tests

'Req' is defined but never used. Allowed unused vars must match /^_/u
import { type APIGuild, type APIUser, ApplicationIntegrationType, WebhookClient } from "discord.js";
enum WebhookTypes {
PING,
EVENT,
}
interface ApplicationAuthorizedEventPaylaod {
integration_type?: ApplicationIntegrationType;
user: APIUser;
scopes: string[];
guild?: APIGuild;
}
type WebhookEvent = {
type: "APPLICATION_AUTHORIZED";
timestamp: string;
data?: ApplicationAuthorizedEventPaylaod;
};
type WebhookPayload = {
version: number;
application_id: string;
type: WebhookTypes;
event: WebhookEvent;
};
// Handles webhook events from discord
@Controller("/webhook-event")
export class WebhookEventController {
constructor(@Inject("BotClient") private readonly bot: BotService) {}

@Post()
async handleWebhookEvent(@Body() body: WebhookPayload) {
if (body.event.type !== "APPLICATION_AUTHORIZED") return;
if (!body.event.data) return;
const data = body.event.data;
if (!data.integration_type) return;
if (data.integration_type !== ApplicationIntegrationType.UserInstall) return;
const { user } = data;
const webhook = process.env.GUILD ? new WebhookClient({ url: process.env.GUILD }) : undefined;
if (!webhook) return;
webhook.send({
content: `User ${user.username} - ${user.global_name} (\`${user.id}\`) has authorized the application`,
});
return;
}
}
6 changes: 5 additions & 1 deletion src/api/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,21 @@
import { UsersController } from "./controllers/user.controller.js";
import { GuildMiddleware } from "./middlewares/guild.middleware.js";
import { UpdateMiddleware } from "./middlewares/update.middleware.js";
import { WebhookEventMiddleware } from "./middlewares/discord-webhook.middleware.js";
import { WebhookEventController } from "./controllers/discord-webhooks.controller.js";
import * as express from "express";

Check warning on line 16 in src/api/main.ts

View workflow job for this annotation

GitHub Actions / Tests

'express' is defined but never used. Allowed unused vars must match /^_/u
export async function Dashboard(client: SkyHelper) {
@Module({
imports: [],
controllers: [AppController, GuildController, StatsController, UpdateController, UsersController],
controllers: [AppController, GuildController, StatsController, UpdateController, UsersController, WebhookEventController],
providers: [{ provide: "BotClient", useValue: client }],
})
class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(AuthMiddleware).forRoutes("guilds", "update");
consumer.apply(GuildMiddleware).forRoutes("guilds");
consumer.apply(UpdateMiddleware).forRoutes("update");
consumer.apply(WebhookEventMiddleware).forRoutes("webhook-event");
}
}

Expand Down
12 changes: 12 additions & 0 deletions src/api/middlewares/discord-webhook.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Injectable, type NestMiddleware } from "@nestjs/common";
import type { Request, Response, NextFunction } from "express";
import { verifyKeyMiddleware } from "../utils/verifyKeyMiddleware.js";

@Injectable()
export class WebhookEventMiddleware implements NestMiddleware {
constructor() {}

async use(req: Request, res: Response, next: NextFunction) {
verifyKeyMiddleware(process.env.PUBLIC_KEY!)(req, res, next);
}
}
103 changes: 103 additions & 0 deletions src/api/utils/keyUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/**
* MIT License

Copyright (c) 2020 Ian Webster

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
* Based on environment, get a reference to the Web Crypto API's SubtleCrypto interface.
* @returns An implementation of the Web Crypto API's SubtleCrypto interface.
*/
function getSubtleCrypto(): SubtleCrypto {
if (typeof window !== "undefined" && window.crypto) {
return window.crypto.subtle;
}
if (typeof globalThis !== "undefined" && globalThis.crypto) {
return globalThis.crypto.subtle;
}
if (typeof crypto !== "undefined") {
return crypto.subtle;
}
if (typeof require === "function") {
// Cloudflare Workers are doing what appears to be a regex check to look and
// warn for this pattern. We should never get here in a Cloudflare Worker, so
// I am being coy to avoid detection and a warning.
const cryptoPackage = "node:crypto";
const crypto = require(cryptoPackage);
return crypto.webcrypto.subtle;
}
throw new Error("No Web Crypto API implementation found");
}

export const subtleCrypto = getSubtleCrypto();

/**
* Converts different types to Uint8Array.
*
* @param value - Value to convert. Strings are parsed as hex.
* @param format - Format of value. Valid options: 'hex'. Defaults to utf-8.
* @returns Value in Uint8Array form.
*/
export function valueToUint8Array(value: Uint8Array | ArrayBuffer | Buffer | string, format?: string): Uint8Array {
if (value == null) {
return new Uint8Array();
}
if (typeof value === "string") {
if (format === "hex") {
const matches = value.match(/.{1,2}/g);
if (matches == null) {
throw new Error("Value is not a valid hex string");
}
const hexVal = matches.map((byte: string) => Number.parseInt(byte, 16));
return new Uint8Array(hexVal);
}

return new TextEncoder().encode(value);
}
try {
if (Buffer.isBuffer(value)) {
return new Uint8Array(value);
}
} catch (_ex) {
// Runtime doesn't have Buffer
}
if (value instanceof ArrayBuffer) {
return new Uint8Array(value);
}
if (value instanceof Uint8Array) {
return value;
}
throw new Error("Unrecognized value type, must be one of: string, Buffer, ArrayBuffer, Uint8Array");
}

/**
* Merge two arrays.
*
* @param arr1 - First array
* @param arr2 - Second array
* @returns Concatenated arrays
*/
export function concatUint8Arrays(arr1: Uint8Array, arr2: Uint8Array): Uint8Array {
const merged = new Uint8Array(arr1.length + arr2.length);
merged.set(arr1);
merged.set(arr2, arr1.length);
return merged;
}
143 changes: 143 additions & 0 deletions src/api/utils/verifyKeyMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/**
* MIT License

Copyright (c) 2020 Ian Webster

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import { concatUint8Arrays, subtleCrypto, valueToUint8Array } from "./keyUtils.js";
import type { Request, Response, NextFunction } from "express";
/**
* Validates a payload from Discord against its signature and key.
*
* @param rawBody - The raw payload data
* @param signature - The signature from the `X-Signature-Ed25519` header
* @param timestamp - The timestamp from the `X-Signature-Timestamp` header
* @param clientPublicKey - The public key from the Discord developer dashboard
* @returns Whether or not validation was successful
*/
export async function verifyKey(
rawBody: Uint8Array | ArrayBuffer | Buffer | string,
signature: string,
timestamp: string,
clientPublicKey: string | CryptoKey,
): Promise<boolean> {
try {
const timestampData = valueToUint8Array(timestamp);
const bodyData = valueToUint8Array(rawBody);
const message = concatUint8Arrays(timestampData, bodyData);
const publicKey =
typeof clientPublicKey === "string"
? await subtleCrypto.importKey(
"raw",
valueToUint8Array(clientPublicKey, "hex"),
{
name: "ed25519",
namedCurve: "ed25519",
},
false,
["verify"],
)
: clientPublicKey;
const isValid = await subtleCrypto.verify(
{
name: "ed25519",
},
publicKey,
valueToUint8Array(signature, "hex"),
message,
);
return isValid;
} catch (_ex) {
return false;
}
}

/**
* Creates a middleware function for use in Express-compatible web servers.
*
* @param clientPublicKey - The public key from the Discord developer dashboard
* @returns The middleware function
*/
export function verifyKeyMiddleware(clientPublicKey: string): (req: Request, res: Response, next: NextFunction) => void {
if (!clientPublicKey) {
throw new Error("You must specify a Discord client public key");
}

return async (req: Request, res: Response, next: NextFunction) => {
const timestamp = req.header("X-Signature-Timestamp") || "";
const signature = req.header("X-Signature-Ed25519") || "";

if (!timestamp || !signature) {
res.statusCode = 401;
res.end("[discord-interactions] Invalid signature");
return;
}

async function onBodyComplete(rawBody: Buffer) {
const isValid = await verifyKey(rawBody, signature, timestamp, clientPublicKey);
if (!isValid) {
res.statusCode = 401;
res.end("[discord-interactions] Invalid signature");
return;
}

const body = JSON.parse(rawBody.toString("utf-8")) || {};
// Ping
if (body.type === 0) {
res.setHeader("Content-Type", "application/json");
res.end(
JSON.stringify({
type: 0,
}),
);
return;
}

req.body = body;
next();
}

if (req.body) {
if (Buffer.isBuffer(req.body)) {
await onBodyComplete(req.body);
} else if (typeof req.body === "string") {
await onBodyComplete(Buffer.from(req.body, "utf-8"));
} else {
console.warn(
"[Event-Webhooks]: req.body was tampered with, probably by some other middleware. We recommend disabling middleware for interaction routes so that req.body is a raw buffer.",
);
// Attempt to reconstruct the raw buffer. This works but is risky
// because it depends on JSON.stringify matching the Discord backend's
// JSON serialization.
await onBodyComplete(Buffer.from(JSON.stringify(req.body), "utf-8"));
}
} else {
const chunks: Array<Buffer> = [];
req.on("data", (chunk) => {
chunks.push(chunk);
});
req.on("end", async () => {
const rawBody = Buffer.concat(chunks);
await onBodyComplete(rawBody);
});
}
};
}
1 change: 1 addition & 0 deletions src/bot/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ declare global {
NODE_ENV: "development" | "production";
MONGO_CONNECTION: string;
SENTRY_DSN: string;
PUBLIC_KEY: string;
AUTH_TOKEN: string;
TOPGG_TOKEN?: string;
GUILD?: string;
Expand Down
25 changes: 13 additions & 12 deletions src/bot/utils/validators.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import logger from "#bot/handlers/logger";

export function validateEnv() {
if (!process.env.TOKEN) throw new Error("TOKEN is not provided in the environment variables");
if (!process.env.MONGO_CONNECTION) throw new Error("MONGO_CONNECTION is not provided in the environment variables");
if (!process.env.SENTRY_DSN) throw new Error("SENTRY_DSN is not provided in the environment variables");
if (!process.env.CONTACT_US) logger.warn("CONTACT_US Webhook is not provided, command '/contact-us' will not work properly");
for (const key of ["TOPGG_TOKEN", "DBL_TOKEN"]) {
// prettier-ignore
if (!process.env[key]) logger.warn(`${key} is not provided in the environment variables, the bot will not be able to post stats`);
}
}
import logger from "#bot/handlers/logger";

export function validateEnv() {
if (!process.env.TOKEN) throw new Error("TOKEN is not provided in the environment variables");
if (!process.env.MONGO_CONNECTION) throw new Error("MONGO_CONNECTION is not provided in the environment variables");
if (!process.env.SENTRY_DSN) throw new Error("SENTRY_DSN is not provided in the environment variables");
if (!process.env.PUBLIC_KEY) throw new Error("PUBLIC_KEY is not provided in the environment variables");
if (!process.env.CONTACT_US) logger.warn("CONTACT_US Webhook is not provided, command '/contact-us' will not work properly");
for (const key of ["TOPGG_TOKEN", "DBL_TOKEN"]) {
// prettier-ignore
if (!process.env[key]) logger.warn(`${key} is not provided in the environment variables, the bot will not be able to post stats`);
}
}
Loading