feat: add discord interactions worker

This commit is contained in:
41666 2021-08-01 15:45:15 -04:00
parent dde05c402e
commit 9354047447
36 changed files with 486 additions and 178 deletions

View file

@ -0,0 +1,5 @@
import { respond } from '@roleypoly/worker-utils';
export const healthz = async (request: Request): Promise<Response> => {
return respond({ ok: true });
};

View file

@ -0,0 +1,49 @@
import { helloWorld } from '@roleypoly/interactions/handlers/interactions/hello-world';
import { verifyRequest } from '@roleypoly/interactions/utils/interactions';
import {
InteractionData,
InteractionRequest,
InteractionRequestCommand,
InteractionResponse,
InteractionType,
} from '@roleypoly/types';
import { respond } from '@roleypoly/worker-utils';
const commands: Record<
InteractionData['name'],
(request: InteractionRequestCommand) => Promise<InteractionResponse>
> = {
'hello-world': helloWorld,
};
export const interactionHandler = async (request: Request): Promise<Response> => {
if (!(await verifyRequest(request))) {
return new Response('invalid request signature', { status: 401 });
}
const interaction = (await request.json()) as InteractionRequest;
if (interaction.type === InteractionType.PING) {
return respond({ type: 1 });
}
if (interaction.type !== InteractionType.APPLICATION_COMMAND) {
return respond({ err: 'not implemented' }, { status: 400 });
}
if (!interaction.data) {
return respond({ err: 'data missing' }, { status: 400 });
}
const handler = commands[interaction.data.name];
if (!handler) {
return respond({ err: 'not implemented' }, { status: 400 });
}
try {
const response = await handler(interaction as InteractionRequestCommand);
return respond(response);
} catch (e) {
return respond({ err: 'command errored' }, { status: 500 });
}
};

View file

@ -0,0 +1,16 @@
import {
InteractionCallbackType,
InteractionRequestCommand,
InteractionResponse,
} from '@roleypoly/types';
export const helloWorld = async (
interaction: InteractionRequestCommand
): Promise<InteractionResponse> => {
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: `Hey there, ${interaction.member?.nick || interaction.user?.username}`,
},
};
};

View file

@ -0,0 +1,27 @@
import { respond } from '@roleypoly/worker-utils';
import { Router } from '@roleypoly/worker-utils/router';
import { healthz } from './handlers/healthz';
import { uiPublicURI } from './utils/config';
const router = new Router();
router.add('GET', '/_healthz', healthz);
// Root Zen <3
router.addFallback('root', () => {
return respond({
__warning: '🦊',
this: 'is',
a: 'fox-based',
web: 'application',
please: 'be',
mindful: 'of',
your: 'surroundings',
warning__: '🦊',
meta: uiPublicURI,
});
});
addEventListener('fetch', (event: FetchEvent) => {
event.respondWith(router.handle(event.request));
});

View file

@ -0,0 +1,15 @@
{
"name": "@roleypoly/interactions",
"version": "0.1.0",
"scripts": {
"build": "yarn workspace @roleypoly/worker-emulator build --basePath `pwd`",
"lint:types": "tsc --noEmit",
"start": "cfw-emulator"
},
"devDependencies": {
"@cloudflare/workers-types": "^2.2.2",
"@roleypoly/types": "*",
"@roleypoly/worker-utils": "*",
"tweetnacl": "^1.0.3"
}
}

View file

@ -0,0 +1,15 @@
{
"compilerOptions": {
"outDir": "./dist",
"lib": ["esnext", "webworker", "ES2020.BigInt", "ES2020.Promise"],
"types": ["@cloudflare/workers-types"],
"target": "ES2019"
},
"include": [
"./*.ts",
"./**/*.ts",
"../../node_modules/@cloudflare/workers-types/index.d.ts"
],
"exclude": ["./**/*.spec.ts", "./dist/**"],
"extends": "../../tsconfig.json"
}

View file

@ -0,0 +1,10 @@
const self = global as any as Record<string, string>;
const env = (key: string) => self[key] ?? '';
const safeURI = (x: string) => x.replace(/\/$/, '');
const list = (x: string) => x.split(',');
export const uiPublicURI = safeURI(env('UI_PUBLIC_URI'));
export const apiPublicURI = safeURI(env('API_PUBLIC_URI'));
export const publicKey = safeURI(env('DISCORD_PUBLIC_KEY'));

View file

@ -0,0 +1,25 @@
import { publicKey } from '@roleypoly/interactions/utils/config';
import nacl from 'tweetnacl';
export const verifyRequest = async (request: Request): Promise<boolean> => {
const timestamp = request.headers.get('x-signature-timestamp');
const signature = request.headers.get('x-signature-ed25519');
if (!timestamp || !signature) {
return false;
}
const body = await request.json();
if (
!nacl.sign.detached.verify(
Buffer.from(timestamp + JSON.stringify(body)),
Buffer.from(signature, 'hex'),
Buffer.from(publicKey, 'hex')
)
) {
return false;
}
return true;
};

View file

@ -0,0 +1,28 @@
const path = require('path');
const mode = process.env.NODE_ENV || 'production';
module.exports = {
target: 'webworker',
entry: path.join(__dirname, 'index.ts'),
output: {
filename: `worker.${mode}.js`,
path: path.join(__dirname, 'dist'),
},
mode,
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
transpileOnly: true,
configFile: path.join(__dirname, 'tsconfig.json'),
},
},
],
},
};

View file

@ -0,0 +1,7 @@
const reexportEnv = (keys = []) => {
return keys.reduce((acc, key) => ({ ...acc, [key]: process.env[key] }), {});
};
module.exports = {
environment: reexportEnv(['DISCORD_PUBLIC_KEY', 'UI_PUBLIC_URI', 'API_PUBLIC_URI']),
};