Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

discord bot

Brendan Allanbf24391ddf58
diff --git a/apps/discord-bot/.editorconfig b/apps/discord-bot/.editorconfig
new file mode 100644
index 000000000..a727df347
--- /dev/null
+++ b/apps/discord-bot/.editorconfig
@@ -0,0 +1,12 @@
+# http://editorconfig.org
+root = true
+
+[*]
+indent_style = tab
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.yml]
+indent_style = space
diff --git a/apps/discord-bot/.gitignore b/apps/discord-bot/.gitignore
new file mode 100644
index 000000000..3b0fe33c4
--- /dev/null
+++ b/apps/discord-bot/.gitignore
@@ -0,0 +1,172 @@
+# Logs
+
+logs
+_.log
+npm-debug.log_
+yarn-debug.log*
+yarn-error.log*
+lerna-debug.log*
+.pnpm-debug.log*
+
+# Diagnostic reports (https://nodejs.org/api/report.html)
+
+report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
+
+# Runtime data
+
+pids
+_.pid
+_.seed
+\*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+
+lib-cov
+
+# Coverage directory used by tools like istanbul
+
+coverage
+\*.lcov
+
+# nyc test coverage
+
+.nyc_output
+
+# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
+
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+
+bower_components
+
+# node-waf configuration
+
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+
+build/Release
+
+# Dependency directories
+
+node_modules/
+jspm_packages/
+
+# Snowpack dependency directory (https://snowpack.dev/)
+
+web_modules/
+
+# TypeScript cache
+
+\*.tsbuildinfo
+
+# Optional npm cache directory
+
+.npm
+
+# Optional eslint cache
+
+.eslintcache
+
+# Optional stylelint cache
+
+.stylelintcache
+
+# Microbundle cache
+
+.rpt2_cache/
+.rts2_cache_cjs/
+.rts2_cache_es/
+.rts2_cache_umd/
+
+# Optional REPL history
+
+.node_repl_history
+
+# Output of 'npm pack'
+
+\*.tgz
+
+# Yarn Integrity file
+
+.yarn-integrity
+
+# dotenv environment variable files
+
+.env
+.env.development.local
+.env.test.local
+.env.production.local
+.env.local
+
+# parcel-bundler cache (https://parceljs.org/)
+
+.cache
+.parcel-cache
+
+# Next.js build output
+
+.next
+out
+
+# Nuxt.js build / generate output
+
+.nuxt
+dist
+
+# Gatsby files
+
+.cache/
+
+# Comment in the public line in if your project uses Gatsby and not Next.js
+
+# https://nextjs.org/blog/next-9-1#public-directory-support
+
+# public
+
+# vuepress build output
+
+.vuepress/dist
+
+# vuepress v2.x temp and cache directory
+
+.temp
+.cache
+
+# Docusaurus cache and generated files
+
+.docusaurus
+
+# Serverless directories
+
+.serverless/
+
+# FuseBox cache
+
+.fusebox/
+
+# DynamoDB Local files
+
+.dynamodb/
+
+# TernJS port file
+
+.tern-port
+
+# Stores VSCode versions used for testing VSCode extensions
+
+.vscode-test
+
+# yarn v2
+
+.yarn/cache
+.yarn/unplugged
+.yarn/build-state.yml
+.yarn/install-state.gz
+.pnp.\*
+
+# wrangler project
+
+.dev.vars
+.wrangler/
diff --git a/apps/discord-bot/.prettierrc b/apps/discord-bot/.prettierrc
new file mode 100644
index 000000000..5c7b5d3c7
--- /dev/null
+++ b/apps/discord-bot/.prettierrc
@@ -0,0 +1,6 @@
+{
+ "printWidth": 140,
+ "singleQuote": true,
+ "semi": true,
+ "useTabs": true
+}
diff --git a/apps/discord-bot/package.json b/apps/discord-bot/package.json
new file mode 100644
index 000000000..7da0d1918
--- /dev/null
+++ b/apps/discord-bot/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@cap/discord-bot",
+ "private": true,
+ "scripts": {
+ "deploy": "wrangler deploy",
+ "dev": "wrangler dev",
+ "start": "wrangler dev",
+ "test": "vitest",
+ "cf-typegen": "wrangler types"
+ },
+ "devDependencies": {
+ "@cloudflare/vitest-pool-workers": "^0.6.4",
+ "@cloudflare/workers-types": "^4.20250214.0",
+ "typescript": "^5.5.2",
+ "vitest": "~2.1.9",
+ "wrangler": "^3.109.1"
+ },
+ "dependencies": {
+ "@hono/valibot-validator": "^0.5.2",
+ "buffer": "^6.0.3",
+ "hono": "^4.7.1",
+ "jose": "^5.10.0",
+ "tweetnacl": "^1.0.3",
+ "valibot": "1.0.0-rc.1"
+ }
+}
diff --git a/apps/discord-bot/src/index.ts b/apps/discord-bot/src/index.ts
new file mode 100644
index 000000000..243f172aa
--- /dev/null
+++ b/apps/discord-bot/src/index.ts
@@ -0,0 +1,222 @@
+import nacl from 'tweetnacl';
+import { Buffer } from 'buffer';
+import { Hono } from 'hono';
+import { vValidator } from '@hono/valibot-validator';
+import * as v from 'valibot';
+import * as jose from 'jose';
+import { createMiddleware } from 'hono/factory';
+
+const DISCORD_APP_ID = '1334742236096757861';
+const PUBLIC_KEY = 'fea8bb4c1432223609db5a37e074c5a5474b89bf4bea12515bc4e09d564e4f61';
+
+const GITHUB_ORG = 'CapSoftware';
+const GITHUB_REPO = 'Cap';
+const WORKFLOW_FILE = 'publish.yml';
+
+const CHANNEL_MESSAGE_WITH_SOURCE = 4;
+
+type InteractionBody = {
+ id: string;
+ token: string;
+ member: {
+ user: {
+ id: string;
+ username: string;
+ };
+ };
+ data: {
+ id: string;
+ name: string;
+ type: 1;
+ };
+};
+
+const app = new Hono<{ Bindings: Env }>();
+
+app.post('/', async (c) => {
+ const body = await c.req.json();
+
+ if (!verifyRequest(c.req.raw, body)) return new Response('Invalid signature', { status: 401 });
+
+ // Ping
+ if (body.type === 1) return Response.json({ type: 1 });
+
+ // Slash command
+ if (body.type === 2) {
+ const response = await handleCommand(body, c.env);
+ return Response.json(response);
+ }
+});
+
+const ghActionsOidc = createMiddleware<{ Variables: { githubToken: { run_id: string; repository_id: string; actor: string } } }>(
+ async (c, next) => {
+ const authHeader = c.req.header('Authorization');
+ if (!authHeader || !authHeader.startsWith('Bearer ')) return new Response('No token provided', { status: 401 });
+
+ const token = authHeader.slice('Bearer '.length);
+
+ try {
+ const keysResponse = await fetch('https://token.actions.githubusercontent.com/.well-known/jwks');
+ const { keys } = (await keysResponse.json()) as { keys: { kty: string; alg: string; use: string; kid: string; n: string }[] };
+
+ const [header] = token.split('.');
+ const { kid } = JSON.parse(Buffer.from(header, 'base64').toString());
+
+ const signingKey = keys.find((key) => key.kid === kid);
+ if (!signingKey) return new Response('Invalid key ID', { status: 401 });
+
+ const publicKey = await jose.importJWK(signingKey);
+ const { payload } = await jose.jwtVerify(token, publicKey, {
+ issuer: 'https://token.actions.githubusercontent.com',
+ audience: 'cap-discord-bot',
+ });
+
+ if (!payload.sub) return new Response('Missing sub claim', { status: 401 });
+
+ if (!payload.sub?.includes(`${GITHUB_ORG}/${GITHUB_REPO}`)) {
+ return new Response('Invalid repository', { status: 401 });
+ }
+
+ c.set('githubToken', payload as any);
+ } catch (error) {
+ if (error instanceof Error) return new Response(`Token validation failed: ${error.message}`, { status: 401 });
+ }
+
+ await next();
+ }
+);
+
+app.post(
+ '/github-workflow',
+ ghActionsOidc,
+ vValidator(
+ 'json',
+ v.object({
+ type: v.literal('release-ready'),
+ tag: v.string(),
+ version: v.string(),
+ interactionId: v.string(),
+ releaseUrl: v.string(),
+ })
+ ),
+ async (c) => {
+ const body = c.req.valid('json');
+
+ switch (body.type) {
+ case 'release-ready': {
+ const interactionStr = await c.env.release_discord_interactions.get(body.interactionId);
+ if (!interactionStr) return new Response('Interaction not found', { status: 404 });
+
+ const interaction: InteractionBody = JSON.parse(interactionStr);
+
+ if (interaction.data.name !== 'release') return new Response('Invalid interaction', { status: 400 });
+
+ await fetch(`https://discord.com/api/v10/webhooks/${DISCORD_APP_ID}/${interaction.token}/messages/@original`, {
+ method: 'PATCH',
+ body: JSON.stringify(releaseWorkflowRunningMessageData(body.version, body.releaseUrl, c.get('githubToken').run_id)),
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+ return new Response('Successfully updated message', { status: 200 });
+ }
+ default: {
+ return new Response('Invalid type', { status: 400 });
+ }
+ }
+ }
+);
+
+export default app;
+
+async function handleCommand(interaction: InteractionBody, env: Env) {
+ const { data } = interaction;
+
+ switch (data.name) {
+ case 'release': {
+ await env.release_discord_interactions.put(interaction.id, JSON.stringify(interaction));
+
+ const workflowResponse = await fetch(
+ `https://api.github.com/repos/${GITHUB_ORG}/${GITHUB_REPO}/actions/workflows/${WORKFLOW_FILE}/dispatches`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ ref: 'main', inputs: { interactionId: interaction.id } }),
+ headers: {
+ Accept: 'application/vnd.github+json',
+ Authorization: `Bearer ${env.GITHUB_TOKEN}`,
+ 'X-GitHub-Api-Version': '2022-11-28',
+ 'User-Agent': 'CapBot',
+ },
+ }
+ );
+
+ if (workflowResponse.status !== 204)
+ return { type: 4, data: { content: `Failed to start release workflow: ${await workflowResponse.text()}` } };
+
+ return {
+ type: CHANNEL_MESSAGE_WITH_SOURCE,
+ data: releaseWorkflowStartedMessageData(),
+ };
+ }
+ default: {
+ return { type: 4, data: { content: `Unknown command ${data.name}` } };
+ }
+ }
+}
+
+async function verifyRequest(request: Request, jsonBody: any) {
+ const signature = request.headers.get('X-Signature-Ed25519');
+ if (!signature) throw new Error('Signature header not found');
+
+ const timestamp = request.headers.get('X-Signature-Timestamp');
+ if (!timestamp) throw new Error('Timestamp header not found');
+
+ return nacl.sign.detached.verify(
+ new Buffer(timestamp + JSON.stringify(jsonBody)),
+ new Buffer(signature, 'hex'),
+ new Buffer(PUBLIC_KEY, 'hex')
+ );
+}
+
+function releaseWorkflowStartedMessageData() {
+ return {
+ content: 'Release workflow started, standby...',
+ components: [
+ {
+ type: 1,
+ components: [
+ {
+ type: 2,
+ label: 'Workflow Runs',
+ url: `https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/actions/workflows/${WORKFLOW_FILE}`,
+ style: 5,
+ },
+ ],
+ },
+ ],
+ };
+}
+
+function releaseWorkflowRunningMessageData(version: string, releaseUrl: string, workflowRunId: string) {
+ return {
+ content: `v${version} workflow running, go edit the release notes!`,
+ components: [
+ {
+ type: 1,
+ components: [
+ {
+ type: 2,
+ label: 'Release Notes',
+ url: releaseUrl,
+ style: 5,
+ },
+ {
+ type: 2,
+ label: 'Workflow Run',
+ url: `https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/actions/runs/${workflowRunId}`,
+ style: 5,
+ },
+ ],
+ },
+ ],
+ };
+}
diff --git a/apps/discord-bot/test/index.spec.ts b/apps/discord-bot/test/index.spec.ts
new file mode 100644
index 000000000..fbee335d7
--- /dev/null
+++ b/apps/discord-bot/test/index.spec.ts
@@ -0,0 +1,25 @@
+// test/index.spec.ts
+import { env, createExecutionContext, waitOnExecutionContext, SELF } from 'cloudflare:test';
+import { describe, it, expect } from 'vitest';
+import worker from '../src/index';
+
+// For now, you'll need to do something like this to get a correctly-typed
+// `Request` to pass to `worker.fetch()`.
+const IncomingRequest = Request<unknown, IncomingRequestCfProperties>;
+
+describe('Hello World worker', () => {
+ it('responds with Hello World! (unit style)', async () => {
+ const request = new IncomingRequest('http://example.com');
+ // Create an empty context to pass to `worker.fetch()`.
+ const ctx = createExecutionContext();
+ const response = await worker.fetch(request, env, ctx);
+ // Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions
+ await waitOnExecutionContext(ctx);
+ expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`);
+ });
+
+ it('responds with Hello World! (integration style)', async () => {
+ const response = await SELF.fetch('https://example.com');
+ expect(await response.text()).toMatchInlineSnapshot(`"Hello World!"`);
+ });
+});
diff --git a/apps/discord-bot/test/tsconfig.json b/apps/discord-bot/test/tsconfig.json
new file mode 100644
index 000000000..7fc436289
--- /dev/null
+++ b/apps/discord-bot/test/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "types": ["@cloudflare/workers-types/experimental", "@cloudflare/vitest-pool-workers"]
+ },
+ "include": ["./**/*.ts", "../worker-configuration.d.ts"],
+ "exclude": []
+}
diff --git a/apps/discord-bot/tsconfig.json b/apps/discord-bot/tsconfig.json
new file mode 100644
index 000000000..33bdb791a
--- /dev/null
+++ b/apps/discord-bot/tsconfig.json
@@ -0,0 +1,46 @@
+{
+ "compilerOptions": {
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
+
+ /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
+ "target": "es2021",
+ /* Specify a set of bundled library declaration files that describe the target runtime environment. */
+ "lib": ["es2021"],
+ /* Specify what JSX code is generated. */
+ "jsx": "react-jsx",
+
+ /* Specify what module code is generated. */
+ "module": "es2022",
+ /* Specify how TypeScript looks up a file from a given module specifier. */
+ "moduleResolution": "Bundler",
+ /* Specify type package names to be included without being referenced in a source file. */
+ "types": [
+ "@cloudflare/workers-types/2023-07-01"
+ ],
+ /* Enable importing .json files */
+ "resolveJsonModule": true,
+
+ /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
+ "allowJs": true,
+ /* Enable error reporting in type-checked JavaScript files. */
+ "checkJs": false,
+
+ /* Disable emitting files from a compilation. */
+ "noEmit": true,
+
+ /* Ensure that each file can be safely transpiled without relying on other imports. */
+ "isolatedModules": true,
+ /* Allow 'import x from y' when a module doesn't have a default export. */
+ "allowSyntheticDefaultImports": true,
+ /* Ensure that casing is correct in imports. */
+ "forceConsistentCasingInFileNames": true,
+
+ /* Enable all strict type-checking options. */
+ "strict": true,
+
+ /* Skip type checking all .d.ts files. */
+ "skipLibCheck": true
+ },
+ "exclude": ["test"],
+ "include": ["worker-configuration.d.ts", "src/**/*.ts"]
+}
diff --git a/apps/discord-bot/vitest.config.mts b/apps/discord-bot/vitest.config.mts
new file mode 100644
index 000000000..977f64c4e
--- /dev/null
+++ b/apps/discord-bot/vitest.config.mts
@@ -0,0 +1,11 @@
+import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';
+
+export default defineWorkersConfig({
+ test: {
+ poolOptions: {
+ workers: {
+ wrangler: { configPath: './wrangler.jsonc' },
+ },
+ },
+ },
+});
diff --git a/apps/discord-bot/worker-configuration.d.ts b/apps/discord-bot/worker-configuration.d.ts
new file mode 100644
index 000000000..45ec127f5
--- /dev/null
+++ b/apps/discord-bot/worker-configuration.d.ts
@@ -0,0 +1,6 @@
+// Generated by Wrangler by running `wrangler types`
+
+interface Env {
+ release_discord_interactions: KVNamespace;
+ GITHUB_TOKEN: "SECRET";
+}
diff --git a/apps/discord-bot/wrangler.jsonc b/apps/discord-bot/wrangler.jsonc
new file mode 100644
index 000000000..4c4a4c8eb
--- /dev/null
+++ b/apps/discord-bot/wrangler.jsonc
@@ -0,0 +1,48 @@
+/**
+ * For more details on how to configure Wrangler, refer to:
+ * https://developers.cloudflare.com/workers/wrangler/configuration/
+ */
+{
+ "$schema": "node_modules/wrangler/config-schema.json",
+ "name": "cap-discord-bot",
+ "main": "src/index.ts",
+ "compatibility_date": "2025-02-14",
+ "observability": {
+ "enabled": true
+ },
+ /**
+ * Smart Placement
+ * Docs: https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement
+ */
+ // "placement": { "mode": "smart" },
+
+ /**
+ * Bindings
+ * Bindings allow your Worker to interact with resources on the Cloudflare Developer Platform, including
+ * databases, object storage, AI inference, real-time communication and more.
+ * https://developers.cloudflare.com/workers/runtime-apis/bindings/
+ */
+ "kv_namespaces": [{ "binding": "release_discord_interactions", "id": "846b080b86914e2ba666d35acee35c9a" }]
+
+ /**
+ * Environment Variables
+ * https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables
+ */
+ // "vars": { "MY_VARIABLE": "production_value" },
+ /**
+ * Note: Use secrets to store sensitive data.
+ * https://developers.cloudflare.com/workers/configuration/secrets/
+ */
+
+ /**
+ * Static Assets
+ * https://developers.cloudflare.com/workers/static-assets/binding/
+ */
+ // "assets": { "directory": "./public/", "binding": "ASSETS" },
+
+ /**
+ * Service Bindings (communicate between multiple Workers)
+ * https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings
+ */
+ // "services": [{ "binding": "MY_SERVICE", "service": "my-service" }]
+}