feat: Slash Commands (#337)

* feat: add discord interactions worker

* feat(interactions): update CI/CD and terraform to add interactions

* chore: fix lint issues

* chore: fix build & emulation

* fix(interactions): deployment + handler

* chore: remove worker-dist via gitignore

* feat: add /pickable-roles and /pick-role basis

* feat: add pick, remove, and update the general /roleypoly command

* fix: lint missing Member import
This commit is contained in:
41666 2021-08-01 20:26:47 -04:00 committed by GitHub
parent dde05c402e
commit 066f68ffef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
59 changed files with 1219 additions and 248 deletions

View file

@ -7,10 +7,13 @@ type URLParams = {
clientID: string;
permissions: number;
guildID?: string;
scopes: string[];
};
const buildURL = (params: URLParams) => {
let url = `https://discord.com/api/oauth2/authorize?client_id=${params.clientID}&scope=bot&permissions=${params.permissions}`;
let url = `https://discord.com/api/oauth2/authorize?client_id=${
params.clientID
}&scope=${params.scopes.join('%20')}&permissions=${params.permissions}`;
if (params.guildID) {
url += `&guild_id=${params.guildID}&disable_guild_select=true`;
@ -31,6 +34,7 @@ export const BotJoin = (request: Request): Response => {
clientID: botClientID,
permissions: 268435456,
guildID,
scopes: ['bot', 'application.commands'],
})
);
};

View file

@ -1,7 +1,8 @@
import { memberPassesAccessControl } from '@roleypoly/api/utils/access-control';
import { accessControlViolation } from '@roleypoly/api/utils/responses';
import { DiscordUser, GuildSlug, PresentableGuild, SessionData } from '@roleypoly/types';
import { respond, withSession } from '../utils/api-tools';
import { respond } from '@roleypoly/worker-utils';
import { withSession } from '../utils/api-tools';
import { getGuild, getGuildData, getGuildMember } from '../utils/guild';
const fail = () => respond({ error: 'guild not found' }, { status: 404 });

View file

@ -1,5 +1,6 @@
import { SessionData } from '@roleypoly/types';
import { respond, withSession } from '../utils/api-tools';
import { respond } from '@roleypoly/worker-utils';
import { withSession } from '../utils/api-tools';
export const GetSession = withSession((session?: SessionData) => (): Response => {
const { user, guilds, sessionID } = session || {};

View file

@ -1,5 +1,5 @@
import { GuildSlug } from '@roleypoly/types';
import { respond } from '../utils/api-tools';
import { respond } from '@roleypoly/worker-utils';
import { getGuild } from '../utils/guild';
export const GetSlug = async (request: Request): Promise<Response> => {

View file

@ -0,0 +1,104 @@
import { CategoryType, Member, RoleSafety } from '@roleypoly/types';
import { AuthType, discordFetch, respond } from '@roleypoly/worker-utils';
import { difference, keyBy } from 'lodash';
import { interactionsEndpoint } from '../utils/api-tools';
import { botToken } from '../utils/config';
import {
getGuild,
getGuildData,
getGuildMember,
updateGuildMember,
} from '../utils/guild';
import { conflict, invalid, notAuthenticated, notFound, ok } from '../utils/responses';
export const InteractionsPickRole = interactionsEndpoint(
async (request: Request): Promise<Response> => {
const mode = request.method === 'PUT' ? 'add' : 'remove';
const reqURL = new URL(request.url);
const [, , guildID, userID, roleID] = reqURL.pathname.split('/');
if (!guildID || !userID || !roleID) {
return invalid();
}
const guildP = getGuild(guildID);
const guildDataP = getGuildData(guildID);
const guildMemberP = getGuildMember(
{ serverID: guildID, userID },
{ skipCachePull: true }
);
const [guild, guildData, guildMember] = await Promise.all([
guildP,
guildDataP,
guildMemberP,
]);
if (!guild || !guildData || !guildMember) {
return notFound();
}
let memberRoles = guildMember.roles;
if (
(mode === 'add' && memberRoles.includes(roleID)) ||
(mode !== 'add' && !memberRoles.includes(roleID))
) {
return conflict();
}
const roleMap = keyBy(guild.roles, 'id');
const category = guildData.categories.find((category) =>
category.roles.includes(roleID)
);
// No category? illegal.
if (!category) {
return notFound();
}
// Category is hidden, this is illegal
if (category.hidden) {
return notFound();
}
// Role is unsafe, super illegal.
if (roleMap[roleID].safety !== RoleSafety.Safe) {
return notAuthenticated();
}
// In add mode, if the category is a single-mode, remove the other roles in the category.
if (mode === 'add' && category.type === CategoryType.Single) {
memberRoles = difference(memberRoles, category.roles);
}
if (mode === 'add') {
memberRoles = [...memberRoles, roleID];
} else {
memberRoles = memberRoles.filter((id) => id !== roleID);
}
const patchMemberRoles = await discordFetch<Member>(
`/guilds/${guildID}/members/${userID}`,
botToken,
AuthType.Bot,
{
method: 'PATCH',
headers: {
'content-type': 'application/json',
'x-audit-log-reason': `Picked their roles via slash command`,
},
body: JSON.stringify({
roles: memberRoles,
}),
}
);
if (!patchMemberRoles) {
return respond({ error: 'discord rejected the request' }, { status: 500 });
}
await updateGuildMember({ serverID: guildID, userID });
return ok();
}
);

View file

@ -0,0 +1,33 @@
import { Category, CategorySlug } from '@roleypoly/types';
import { respond } from '@roleypoly/worker-utils';
import { interactionsEndpoint } from '../utils/api-tools';
import { getGuildData } from '../utils/guild';
import { notFound } from '../utils/responses';
export const InteractionsPickableRoles = interactionsEndpoint(
async (request: Request): Promise<Response> => {
const reqURL = new URL(request.url);
const [, , serverID] = reqURL.pathname.split('/');
const guildData = await getGuildData(serverID);
if (!guildData) {
return notFound();
}
const roleMap: Record<Category['name'], CategorySlug> = {};
for (let category of guildData.categories) {
if (category.hidden) {
continue;
}
// TODO: role safety?
roleMap[category.name] = {
roles: category.roles,
type: category.type,
};
}
return respond(roleMap);
}
);

View file

@ -1,5 +1,6 @@
import { StateSession } from '@roleypoly/types';
import { getQuery, isAllowedCallbackHost, setupStateSession } from '../utils/api-tools';
import { getQuery } from '@roleypoly/worker-utils';
import { isAllowedCallbackHost, setupStateSession } from '../utils/api-tools';
import { Bounce } from '../utils/bounce';
import { apiPublicURI, botClientID } from '../utils/config';

View file

@ -5,25 +5,22 @@ import {
SessionData,
StateSession,
} from '@roleypoly/types';
import KSUID from 'ksuid';
import {
AuthType,
discordAPIBase,
discordFetch,
userAgent,
} from '@roleypoly/worker-utils';
import KSUID from 'ksuid';
import {
formData,
getStateSession,
isAllowedCallbackHost,
parsePermissions,
resolveFailures,
userAgent,
} from '../utils/api-tools';
import { Bounce } from '../utils/bounce';
import {
apiPublicURI,
botClientID,
botClientSecret,
discordAPIBase,
uiPublicURI,
} from '../utils/config';
import { apiPublicURI, botClientID, botClientSecret, uiPublicURI } from '../utils/config';
import { Sessions } from '../utils/kv';
const AuthErrorResponse = (extra?: string) =>

View file

@ -1,6 +1,7 @@
import { SessionData } from '@roleypoly/types';
import { formData, respond, userAgent, withSession } from '../utils/api-tools';
import { botClientID, botClientSecret, discordAPIBase } from '../utils/config';
import { discordAPIBase, respond, userAgent } from '@roleypoly/worker-utils';
import { formData, withSession } from '../utils/api-tools';
import { botClientID, botClientSecret } from '../utils/config';
import { Sessions } from '../utils/kv';
export const RevokeSession = withSession(

View file

@ -1,5 +1,3 @@
import { memberPassesAccessControl } from '@roleypoly/api/utils/access-control';
import { accessControlViolation } from '@roleypoly/api/utils/responses';
import {
GuildData,
Member,
@ -10,9 +8,10 @@ import {
SessionData,
TransactionType,
} from '@roleypoly/types';
import { AuthType, discordFetch, respond } from '@roleypoly/worker-utils';
import { difference, groupBy, keyBy, union } from 'lodash';
import { AuthType, discordFetch, respond, withSession } from '../utils/api-tools';
import { botToken } from '../utils/config';
import { withSession } from '../utils/api-tools';
import { botToken, uiPublicURI } from '../utils/config';
import {
getGuild,
getGuildData,
@ -57,10 +56,6 @@ export const UpdateRoles = withSession(
const guildData = await getGuildData(guildID);
if (!memberPassesAccessControl(guildCheck, guildMember, guildData.accessControl)) {
return accessControlViolation();
}
const newRoles = calculateNewRoles({
currentRoles: guildMember.roles,
guildRoles: guild.roles,
@ -76,7 +71,7 @@ export const UpdateRoles = withSession(
method: 'PATCH',
headers: {
'content-type': 'application/json',
'x-audit-log-reason': `${username}#${discriminator} changes their roles via ${url.hostname}`,
'x-audit-log-reason': `Picked their roles via ${uiPublicURI}`,
},
body: JSON.stringify({
roles: newRoles,

View file

@ -1,3 +1,6 @@
import { InteractionsPickRole } from '@roleypoly/api/handlers/interactions-pick-role';
import { InteractionsPickableRoles } from '@roleypoly/api/handlers/interactions-pickable-roles';
import { Router } from '@roleypoly/worker-utils/router';
import { BotJoin } from './handlers/bot-join';
import { ClearGuildCache } from './handlers/clear-guild-cache';
import { GetPickerData } from './handlers/get-picker-data';
@ -9,7 +12,6 @@ import { RevokeSession } from './handlers/revoke-session';
import { SyncFromLegacy } from './handlers/sync-from-legacy';
import { UpdateGuild } from './handlers/update-guild';
import { UpdateRoles } from './handlers/update-roles';
import { Router } from './router';
import { respond } from './utils/api-tools';
import { uiPublicURI } from './utils/config';
@ -32,6 +34,11 @@ router.add('PATCH', 'update-guild', UpdateGuild);
router.add('POST', 'sync-from-legacy', SyncFromLegacy);
router.add('POST', 'clear-guild-cache', ClearGuildCache);
// Interactions endpoints
router.add('GET', 'interactions-pickable-roles', InteractionsPickableRoles);
router.add('PUT', 'interactions-pick-role', InteractionsPickRole);
router.add('DELETE', 'interactions-pick-role', InteractionsPickRole);
// Tester Routes
router.add('GET', 'x-headers', (request) => {
const headers: { [x: string]: string } = {};

View file

@ -11,6 +11,7 @@
"@roleypoly/misc-utils": "*",
"@roleypoly/types": "*",
"@roleypoly/worker-emulator": "*",
"@roleypoly/worker-utils": "*",
"@types/deep-equal": "^1.0.1",
"deep-equal": "^2.0.5",
"ksuid": "^2.0.0",

View file

@ -1,12 +1,18 @@
import { notAuthenticated } from '@roleypoly/api/utils/responses';
import {
evaluatePermission,
permissions as Permissions,
} from '@roleypoly/misc-utils/hasPermission';
import { SessionData, UserGuildPermissions } from '@roleypoly/types';
import { Handler, WrappedKVNamespace } from '@roleypoly/worker-utils';
import KSUID from 'ksuid';
import { Handler } from '../router';
import { allowedCallbackHosts, apiPublicURI, discordAPIBase, rootUsers } from './config';
import { Sessions, WrappedKVNamespace } from './kv';
import {
allowedCallbackHosts,
apiPublicURI,
interactionsSharedKey,
rootUsers,
} from './config';
import { Sessions } from './kv';
export const formData = (obj: Record<string, any>): string => {
return Object.keys(obj)
@ -14,18 +20,8 @@ export const formData = (obj: Record<string, any>): string => {
.join('&');
};
export const addCORS = (init: ResponseInit = {}) => ({
...init,
headers: {
...(init.headers || {}),
'access-control-allow-origin': '*',
'access-control-allow-methods': '*',
'access-control-allow-headers': '*',
},
});
export const respond = (obj: Record<string, any>, init: ResponseInit = {}) =>
new Response(JSON.stringify(obj), addCORS(init));
new Response(JSON.stringify(obj), init);
export const resolveFailures =
(
@ -70,44 +66,6 @@ export const getSessionID = (request: Request): { type: string; id: string } | n
return { type, id };
};
export const userAgent =
'DiscordBot (https://github.com/roleypoly/roleypoly, git-main) (+https://roleypoly.com)';
export enum AuthType {
Bearer = 'Bearer',
Bot = 'Bot',
}
export const discordFetch = async <T>(
url: string,
auth: string,
authType: AuthType = AuthType.Bearer,
init?: RequestInit
): Promise<T | null> => {
const response = await fetch(discordAPIBase + url, {
...(init || {}),
headers: {
...(init?.headers || {}),
authorization: `${AuthType[authType]} ${auth}`,
'user-agent': userAgent,
},
});
if (response.status >= 400) {
console.error('discordFetch failed', {
url,
authType,
payload: await response.text(),
});
}
if (response.ok) {
return (await response.json()) as T;
} else {
return null;
}
};
export type CacheLayerOptions = {
skipCachePull?: boolean;
};
@ -195,16 +153,6 @@ export const onlyRootUsers = (handler: Handler): Handler =>
);
});
export const getQuery = (request: Request): { [x: string]: string } => {
const output: { [x: string]: string } = {};
for (let [key, value] of new URL(request.url).searchParams.entries()) {
output[key] = value;
}
return output;
};
export const isAllowedCallbackHost = (host: string): boolean => {
return (
host === apiPublicURI ||
@ -215,3 +163,14 @@ export const isAllowedCallbackHost = (host: string): boolean => {
null
);
};
export const interactionsEndpoint =
(handler: Handler): Handler =>
async (request: Request): Promise<Response> => {
const authHeader = request.headers.get('authorization') || '';
if (authHeader !== `Shared ${interactionsSharedKey}`) {
return notAuthenticated();
}
return handler(request);
};

View file

@ -1,35 +1,21 @@
import { userAgent } from '@roleypoly/api/utils/api-tools';
import { uiPublicURI } from '@roleypoly/api/utils/config';
import {
Category,
DiscordUser,
Embed,
GuildData,
GuildDataUpdate,
GuildSlug,
WebhookValidationStatus,
} from '@roleypoly/types';
import { userAgent } from '@roleypoly/worker-utils';
import deepEqual from 'deep-equal';
import { sortBy, uniq } from 'lodash';
type WebhookEmbed = {
fields: {
name: string;
value: string;
inline: boolean;
}[];
timestamp: string;
title: string;
color: number;
author?: {
name: string;
icon_url: string;
};
};
type WebhookPayload = {
username: string;
avatar_url: string;
embeds: WebhookEmbed[];
embeds: Embed[];
provider: {
name: string;
url: string;
@ -39,7 +25,7 @@ type WebhookPayload = {
type ChangeHandler = (
oldValue: GuildDataUpdate[keyof GuildDataUpdate],
newValue: GuildData[keyof GuildDataUpdate]
) => WebhookEmbed[];
) => Embed[];
const changeHandlers: Record<keyof GuildDataUpdate, ChangeHandler> = {
message: (oldValue, newValue) => [

View file

@ -13,5 +13,4 @@ export const apiPublicURI = safeURI(env('API_PUBLIC_URI'));
export const rootUsers = list(env('ROOT_USERS'));
export const allowedCallbackHosts = list(env('ALLOWED_CALLBACK_HOSTS'));
export const importSharedKey = env('BOT_IMPORT_TOKEN');
export const discordAPIBase = 'https://discordapp.com/api/v9';
export const interactionsSharedKey = env('INTERACTIONS_SHARED_KEY');

View file

@ -1,4 +1,3 @@
import { Handler } from '@roleypoly/api/router';
import {
lowPermissions,
missingParameters,
@ -18,14 +17,8 @@ import {
SessionData,
UserGuildPermissions,
} from '@roleypoly/types';
import {
AuthType,
cacheLayer,
CacheLayerOptions,
discordFetch,
isRoot,
withSession,
} from './api-tools';
import { AuthType, discordFetch, Handler } from '@roleypoly/worker-utils';
import { cacheLayer, CacheLayerOptions, isRoot, withSession } from './api-tools';
import { botClientID, botToken } from './config';
import { GuildData, Guilds } from './kv';
import { useRateLimiter } from './rate-limiting';

View file

@ -1,83 +1,4 @@
export class WrappedKVNamespace {
constructor(private kvNamespace: KVNamespace) {}
async get<T>(key: string): Promise<T | null> {
const data = await this.kvNamespace.get(key, 'text');
if (!data) {
return null;
}
return JSON.parse(data) as T;
}
async put<T>(key: string, value: T, ttlSeconds?: number) {
await this.kvNamespace.put(key, JSON.stringify(value), {
expirationTtl: ttlSeconds,
});
}
list = this.kvNamespace.list;
getWithMetadata = this.kvNamespace.getWithMetadata;
delete = this.kvNamespace.delete;
}
class EmulatedKV implements KVNamespace {
constructor() {
console.warn('EmulatedKV used. Data will be lost.');
}
private data: Map<string, any> = new Map();
async get<T>(key: string): Promise<T | null> {
if (!this.data.has(key)) {
return null;
}
return this.data.get(key);
}
async getWithMetadata<T, Metadata = unknown>(
key: string
): KVValueWithMetadata<T, Metadata> {
return {
value: await this.get<T>(key),
metadata: {} as Metadata,
};
}
async put(key: string, value: string | ReadableStream<any> | ArrayBuffer | FormData) {
this.data.set(key, value);
}
async delete(key: string) {
this.data.delete(key);
}
async list(options?: { prefix?: string; limit?: number; cursor?: string }): Promise<{
keys: { name: string; expiration?: number; metadata?: unknown }[];
list_complete: boolean;
cursor: string;
}> {
let keys: { name: string }[] = [];
for (let key of this.data.keys()) {
if (options?.prefix && !key.startsWith(options.prefix)) {
continue;
}
keys.push({ name: key });
}
return {
keys,
cursor: '0',
list_complete: true,
};
}
}
const kvOrLocal = (namespace: KVNamespace | null): KVNamespace =>
namespace || new EmulatedKV();
import { kvOrLocal, WrappedKVNamespace } from '@roleypoly/worker-utils';
const self = global as any as Record<string, any>;

View file

@ -1,4 +1,4 @@
import { WrappedKVNamespace } from './kv';
import { WrappedKVNamespace } from '@roleypoly/worker-utils';
export const useRateLimiter =
(kv: WrappedKVNamespace, key: string, timeoutSeconds: number) =>

View file

@ -1,4 +1,4 @@
import { respond } from './api-tools';
import { respond } from '@roleypoly/worker-utils';
export const ok = () => respond({ ok: true });
@ -20,3 +20,6 @@ export const rateLimited = () =>
export const invalid = (obj: any = {}) =>
respond({ err: 'client sent something invalid', data: obj }, { status: 400 });
export const notAuthenticated = () =>
respond({ err: 'not authenticated' }, { status: 403 });

View file

@ -12,6 +12,7 @@ module.exports = {
'API_PUBLIC_URI',
'ROOT_USERS',
'ALLOWED_CALLBACK_HOSTS',
'INTERACTIONS_SHARED_KEY',
]),
kv: ['KV_SESSIONS', 'KV_GUILDS', 'KV_GUILD_DATA'],
};

View file

@ -204,5 +204,6 @@ fork(async () => {
reload();
});
console.log('starting on http://localhost:6609');
server.listen(6609, '0.0.0.0');
const port = args.port || 6609;
console.log(`starting on http://localhost:${port}`);
server.listen(port, '0.0.0.0');

7
packages/interactions/bindings.d.ts vendored Normal file
View file

@ -0,0 +1,7 @@
export {};
declare global {
const DISCORD_PUBLIC_KEY: string;
const UI_PUBLIC_URI: string;
const API_PUBLIC_URI: string;
}

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,58 @@
import {
InteractionData,
InteractionRequest,
InteractionRequestCommand,
InteractionResponse,
InteractionType,
} from '@roleypoly/types';
import { respond } from '@roleypoly/worker-utils';
import { verifyRequest } from '../utils/interactions';
import { somethingWentWrong } from '../utils/responses';
import { helloWorld } from './interactions/hello-world';
import { pickRole } from './interactions/pick-role';
import { pickableRoles } from './interactions/pickable-roles';
import { roleypoly } from './interactions/roleypoly';
const commands: Record<
InteractionData['name'],
(request: InteractionRequestCommand) => Promise<InteractionResponse>
> = {
'hello-world': helloWorld,
roleypoly: roleypoly,
'pickable-roles': pickableRoles,
'pick-role': pickRole('add'),
'remove-role': pickRole('remove'),
};
export const interactionHandler = async (request: Request): Promise<Response> => {
const interaction = (await request.json()) as InteractionRequest;
if (!verifyRequest(request, interaction)) {
return new Response('invalid request signature', { status: 401 });
}
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) {
console.error(e);
return respond(somethingWentWrong());
}
};

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,80 @@
import { selectRole } from '@roleypoly/interactions/utils/api';
import { invalid, mustBeInGuild } from '@roleypoly/interactions/utils/responses';
import {
InteractionCallbackType,
InteractionFlags,
InteractionRequestCommand,
InteractionResponse,
} from '@roleypoly/types';
export const pickRole =
(mode: 'add' | 'remove') =>
async (interaction: InteractionRequestCommand): Promise<InteractionResponse> => {
if (!interaction.guild_id) {
return mustBeInGuild();
}
const userID = interaction.member?.user?.id;
if (!userID) {
return mustBeInGuild();
}
const roleID = interaction.data.options?.find(
(option) => option.name === 'role'
)?.value;
if (!roleID) {
return invalid();
}
const code = await selectRole(mode, interaction.guild_id, userID, roleID);
if (code === 409) {
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: `:x: You ${mode === 'add' ? 'already' : "don't"} have that role.`,
flags: InteractionFlags.EPHEMERAL,
},
};
}
if (code === 404) {
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: `:x: <@&${roleID}> isn't pickable.`,
flags: InteractionFlags.EPHEMERAL,
},
};
}
if (code === 403) {
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: `:x: <@&${roleID}> has unsafe permissions.`,
flags: InteractionFlags.EPHEMERAL,
},
};
}
if (code !== 200) {
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: `:x: Something went wrong, please try again later.`,
flags: InteractionFlags.EPHEMERAL,
},
};
}
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: `:white_check_mark: You ${
mode === 'add' ? 'got' : 'removed'
} the role: <@&${roleID}>`,
flags: InteractionFlags.EPHEMERAL,
},
};
};

View file

@ -0,0 +1,58 @@
import { getPickableRoles } from '@roleypoly/interactions/utils/api';
import { uiPublicURI } from '@roleypoly/interactions/utils/config';
import { mustBeInGuild } from '@roleypoly/interactions/utils/responses';
import {
CategoryType,
Embed,
InteractionCallbackType,
InteractionFlags,
InteractionRequestCommand,
InteractionResponse,
} from '@roleypoly/types';
export const pickableRoles = async (
interaction: InteractionRequestCommand
): Promise<InteractionResponse> => {
if (!interaction.guild_id) {
return mustBeInGuild();
}
const pickableRoles = await getPickableRoles(interaction.guild_id);
const embed: Embed = {
color: 0xab9b9a,
fields: [],
title: 'You can pick any of these roles with /pick-role',
};
for (let categoryName in pickableRoles) {
const { roles, type } = pickableRoles[categoryName];
embed.fields.push({
name: `${categoryName}${type === CategoryType.Single ? ' *(pick one)*' : ''}`,
value: roles.map((role) => `<@&${role}>`).join('\n'),
inline: true,
});
}
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
embeds: [embed],
flags: InteractionFlags.EPHEMERAL,
components: [
{
type: 1,
components: [
// Link to Roleypoly
{
type: 2,
label: 'Pick roles on your browser',
url: `${uiPublicURI}/s/${interaction.guild_id}`,
style: 5,
},
],
},
],
},
};
};

View file

@ -0,0 +1,56 @@
import { uiPublicURI } from '@roleypoly/interactions/utils/config';
import {
Embed,
InteractionCallbackType,
InteractionFlags,
InteractionRequestCommand,
InteractionResponse,
} from '@roleypoly/types';
export const roleypoly = async (
interaction: InteractionRequestCommand
): Promise<InteractionResponse> => {
if (interaction.guild_id) {
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
embeds: [
{
color: 0x453e3d,
title: `:beginner: Hey there, ${
interaction.member?.nick || interaction.member?.user?.username || 'friend'
}!`,
description: `Try these slash commands, or pick roles from your browser!`,
fields: [
{ name: 'See all the roles', value: '/pickable-roles' },
{ name: 'Pick a role', value: '/pick-role' },
{ name: 'Remove a role', value: '/remove-role' },
],
} as Embed,
],
components: [
{
type: 1,
components: [
// Link to Roleypoly
{
type: 2,
label: `Pick roles on ${new URL(uiPublicURI).hostname}`,
url: `${uiPublicURI}/s/${interaction.guild_id}`,
style: 5,
},
],
},
],
flags: InteractionFlags.EPHEMERAL,
},
};
}
return {
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: `:beginner: Hey! I don't know what server you're in, so check out ${uiPublicURI}`,
},
};
};

View file

@ -0,0 +1,29 @@
import { interactionHandler } from '@roleypoly/interactions/handlers/interaction';
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);
router.add('POST', 'interactions', interactionHandler);
// 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,17 @@
{
"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-emulator": "*",
"@roleypoly/worker-utils": "*",
"@types/node": "^16.4.10",
"tweetnacl": "^1.0.3"
}
}

View file

@ -0,0 +1,15 @@
{
"compilerOptions": {
"outDir": "./dist",
"lib": ["esnext", "webworker", "ES2020.BigInt", "ES2020.Promise"],
"types": ["@cloudflare/workers-types", "node"],
"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,41 @@
import { Category, CategorySlug } from '@roleypoly/types';
import { apiPublicURI, interactionsSharedKey } from './config';
export const apiFetch = (url: string, init: RequestInit = {}) =>
fetch(`${apiPublicURI}${url}`, {
...init,
headers: {
...(init.headers || {}),
authorization: `Shared ${interactionsSharedKey}`,
},
});
export const getPickableRoles = async (
guildID: string
): Promise<Record<Category['name'], CategorySlug>> => {
const response = await apiFetch(`/interactions-pickable-roles/${guildID}`);
if (response.status !== 200) {
throw new Error(
`API request failed to /interactions-pickable-roles, got code: ${response.status}`
);
}
return (await response.json()) as Record<Category['name'], CategorySlug>;
};
export const selectRole = async (
mode: 'add' | 'remove',
guildID: string,
userID: string,
roleID: string
): Promise<number> => {
const response = await apiFetch(
`/interactions-pick-role/${guildID}/${userID}/${roleID}`,
{
method: mode === 'add' ? 'PUT' : 'DELETE',
}
);
return response.status;
};

View file

@ -0,0 +1,11 @@
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'));
export const interactionsSharedKey = env('INTERACTIONS_SHARED_KEY');

View file

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

View file

@ -0,0 +1,29 @@
import {
InteractionCallbackType,
InteractionFlags,
InteractionResponse,
} from '@roleypoly/types';
export const mustBeInGuild = (): InteractionResponse => ({
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: ':x: This command has to be used in a server.',
flags: InteractionFlags.EPHEMERAL,
},
});
export const invalid = (): InteractionResponse => ({
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: ':x: You filled that command out wrong...',
flags: InteractionFlags.EPHEMERAL,
},
});
export const somethingWentWrong = (): InteractionResponse => ({
type: InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: '<a:promareFlame:624850108667789333> Something went terribly wrong.',
flags: InteractionFlags.EPHEMERAL,
},
});

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,12 @@
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',
'INTERACTIONS_SHARED_KEY',
]),
};

View file

@ -11,3 +11,8 @@ export type Category = {
type: CategoryType;
position: number;
};
export type CategorySlug = {
roles: Category['roles'];
type: Category['type'];
};

View file

@ -0,0 +1,79 @@
import { DiscordUser, Member } from '@roleypoly/types/User';
export enum InteractionType {
PING = 1,
APPLICATION_COMMAND = 2,
MESSAGE_COMPONENT = 3,
}
export type InteractionRequest = {
id: string;
application_id: string;
token: string;
version: 1;
type: InteractionType;
data?: InteractionData;
guild_id?: string;
channel_id?: string;
member?: Member;
user?: DiscordUser;
message?: {};
};
export type InteractionRequestCommand = InteractionRequest & {
data: InteractionData;
};
export type InteractionData = {
id: string;
name: string;
resolved?: {};
options?: {
name: string;
type: number;
value?: string;
}[];
custom_id: string;
component_type: string;
};
export enum InteractionCallbackType {
PONG = 1,
CHANNEL_MESSAGE_WITH_SOURCE = 4,
DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5,
DEFERRED_UPDATE_MESSAGE = 6,
UPDATE_MESSAGE = 7,
}
export enum InteractionFlags {
EPHEMERAL = 1 << 6,
}
export type InteractionCallbackData = {
tts?: boolean;
content?: string;
embeds?: {};
allowed_mentions?: {};
flags?: InteractionFlags;
components?: {}[];
};
export type InteractionResponse = {
type: InteractionCallbackType;
data?: InteractionCallbackData;
};
export type Embed = {
fields: {
name: string;
value: string;
inline?: boolean;
}[];
timestamp?: string;
title: string;
color: number;
author?: {
name: string;
icon_url: string;
};
};

View file

@ -1,5 +1,6 @@
export * from './Category';
export * from './Guild';
export * from './Interactions';
export * from './Role';
export * from './Session';
export * from './User';

View file

@ -0,0 +1,21 @@
export const respond = (obj: Record<string, any>, init: ResponseInit = {}) =>
new Response(JSON.stringify(obj), {
...init,
headers: {
...(init.headers || {}),
'content-type': 'application/json',
},
});
export const userAgent =
'DiscordBot (https://github.com/roleypoly/roleypoly, git-main) (+https://roleypoly.com)';
export const getQuery = (request: Request): { [x: string]: string } => {
const output: { [x: string]: string } = {};
for (let [key, value] of new URL(request.url).searchParams.entries()) {
output[key] = value;
}
return output;
};

View file

@ -0,0 +1,38 @@
import { userAgent } from './api';
export const discordAPIBase = 'https://discordapp.com/api/v9';
export enum AuthType {
Bearer = 'Bearer',
Bot = 'Bot',
}
export const discordFetch = async <T>(
url: string,
auth: string,
authType: AuthType = AuthType.Bearer,
init?: RequestInit
): Promise<T | null> => {
const response = await fetch(discordAPIBase + url, {
...(init || {}),
headers: {
...(init?.headers || {}),
authorization: `${AuthType[authType]} ${auth}`,
'user-agent': userAgent,
},
});
if (response.status >= 400) {
console.error('discordFetch failed', {
url,
authType,
payload: await response.text(),
});
}
if (response.ok) {
return (await response.json()) as T;
} else {
return null;
}
};

View file

@ -0,0 +1,4 @@
export * from './api';
export * from './discord';
export * from './kv';
export * from './router';

View file

@ -0,0 +1,80 @@
export class WrappedKVNamespace {
constructor(private kvNamespace: KVNamespace) {}
async get<T>(key: string): Promise<T | null> {
const data = await this.kvNamespace.get(key, 'text');
if (!data) {
return null;
}
return JSON.parse(data) as T;
}
async put<T>(key: string, value: T, ttlSeconds?: number) {
await this.kvNamespace.put(key, JSON.stringify(value), {
expirationTtl: ttlSeconds,
});
}
list = this.kvNamespace.list;
getWithMetadata = this.kvNamespace.getWithMetadata;
delete = this.kvNamespace.delete;
}
class EmulatedKV implements KVNamespace {
constructor() {
console.warn('EmulatedKV used. Data will be lost.');
}
private data: Map<string, any> = new Map();
async get<T>(key: string): Promise<T | null> {
if (!this.data.has(key)) {
return null;
}
return this.data.get(key);
}
async getWithMetadata<T, Metadata = unknown>(
key: string
): KVValueWithMetadata<T, Metadata> {
return {
value: await this.get<T>(key),
metadata: {} as Metadata,
};
}
async put(key: string, value: string | ReadableStream<any> | ArrayBuffer | FormData) {
this.data.set(key, value);
}
async delete(key: string) {
this.data.delete(key);
}
async list(options?: { prefix?: string; limit?: number; cursor?: string }): Promise<{
keys: { name: string; expiration?: number; metadata?: unknown }[];
list_complete: boolean;
cursor: string;
}> {
let keys: { name: string }[] = [];
for (let key of this.data.keys()) {
if (options?.prefix && !key.startsWith(options.prefix)) {
continue;
}
keys.push({ name: key });
}
return {
keys,
cursor: '0',
list_complete: true,
};
}
}
export const kvOrLocal = (namespace: KVNamespace | null): KVNamespace =>
namespace || new EmulatedKV();

View file

@ -0,0 +1,10 @@
{
"name": "@roleypoly/worker-utils",
"version": "0.1.0",
"scripts": {
"lint:types": "tsc --noEmit"
},
"devDependencies": {
"@cloudflare/workers-types": "^2.2.2"
}
}

View file

@ -1,6 +1,3 @@
import { addCORS } from './utils/api-tools';
import { uiPublicURI } from './utils/config';
export type Handler = (request: Request) => Promise<Response> | Response;
type RoutingTree = {
@ -23,7 +20,11 @@ export class Router {
500: this.serverError,
};
private uiURL = new URL(uiPublicURI);
private corsOrigins: string[] = [];
addCORSOrigins(origins: string[]) {
this.corsOrigins = [...this.corsOrigins, ...origins];
}
addFallback(which: keyof Fallbacks, handler: Handler) {
this.fallbacks[which] = handler;
@ -40,6 +41,12 @@ export class Router {
}
async handle(request: Request): Promise<Response> {
const response = await this.processRequest(request);
this.injectCORSHeaders(request, response.headers);
return response;
}
private async processRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === '/' || url.pathname === '') {
@ -60,7 +67,7 @@ export class Router {
}
if (lowerMethod === 'options') {
return new Response(null, addCORS({}));
return new Response(null, {});
}
return this.fallbacks[404](request);
@ -81,4 +88,24 @@ export class Router {
status: 500,
});
}
private injectCORSHeaders(request: Request, headers: Headers) {
headers.set('access-control-allow-methods', '*');
headers.set('access-control-allow-headers', '*');
if (this.corsOrigins.length === 0) {
headers.set('access-control-allow-origin', '*');
return;
}
const originHeader = request.headers.get('origin');
if (!originHeader) {
return;
}
const originHostname = new URL(originHeader).hostname;
if (this.corsOrigins.includes(originHostname)) {
headers.set('access-control-allow-origin', originHostname);
}
}
}

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"
}