Skip to content

Commit

Permalink
message encryption
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-737 authored Jun 15, 2024
1 parent a702ab7 commit 5a7ac0f
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 23 deletions.
2 changes: 1 addition & 1 deletion src/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import 'dotenv/config';

const clusterManager = new ClusterManager('build/index.js', {
token: process.env.TOKEN,
shardsPerClusters: 2,
shardsPerClusters: 5,
totalClusters: 'auto',
});

Expand Down
2 changes: 1 addition & 1 deletion src/core/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default class SuperClient extends Client {
filter: () => () => true, // Remove all reactions...
},
},
partials: [Partials.Message],
partials: [Partials.Message, Partials.Channel],
intents: [
IntentsBitField.Flags.MessageContent,
IntentsBitField.Flags.Guilds,
Expand Down
40 changes: 28 additions & 12 deletions src/scripts/network/sendMessage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { APIMessage, WebhookClient, WebhookMessageCreateOptions } from 'discord.js';
import { isDevBuild } from '../../utils/Constants.js';
import { APIEmbed, APIMessage, WebhookMessageCreateOptions } from 'discord.js';
// import { isDevBuild } from '../../utils/Constants.js';
import { encryptMessage } from '../../utils/Utils.js';

const { INTERCHAT_API_URL1, INTERCHAT_API_URL2 } = process.env;
let primaryUrl = INTERCHAT_API_URL1 ?? INTERCHAT_API_URL2;
Expand All @@ -12,38 +13,53 @@ const sendMessage = async (
webhookUrl: string,
message: WebhookMessageCreateOptions,
tries = 0,
encrypt = true,
): Promise<string | APIMessage | undefined> => {
// No need for external apis in development mode
if (isDevBuild) {
const webhook = new WebhookClient({ url: webhookUrl });
return await webhook.send(message);
}
// No need for external apis in development mode FIXME
// if (isDevBuild) {
// const webhook = new WebhookClient({ url: webhookUrl });
// return await webhook.send(message);
// }

if (!process.env.NETWORK_ENCRYPT_KEY) throw new Error('Missing encryption key for network.');

const encryptKey = Buffer.from(process.env.NETWORK_ENCRYPT_KEY, 'base64');
const networkKey = process.env.NETWORK_API_KEY;
if (!networkKey || !primaryUrl) {
throw new Error('Missing NETWORK_API_KEY or INTERCHAT_API_URL(s) environment variables.');
throw new Error('NETWORK_API_KEY or INTERCHAT_API_URL(s) env variables missing.');
}

const embed = message.embeds?.at(0) as APIEmbed;
const content = message.content;
if (encrypt && content) message.content = encryptMessage(content, encryptKey);
if (encrypt && embed.description) {
(message.embeds as APIEmbed[])![0].description = encryptMessage(embed.description, encryptKey);
}

console.log(primaryUrl);

const res = await fetch(primaryUrl, {
method: 'PUT',
body: JSON.stringify(message),
body: JSON.stringify({ webhookUrl, data: message }),
headers: {
authorization: networkKey,
'x-webhook-url': webhookUrl,
'Content-Type': 'application/json',
},
});
console.log(res);

const data = await res.json();
console.log(data);
if (res.status !== 200) {
if (tries <= 2) {
primaryUrl = switchUrl(primaryUrl);
return await sendMessage(webhookUrl, message, tries++);
return await sendMessage(webhookUrl, message, tries++, !encrypt);
}
return String(res.statusText);
return String(data.error);
}

return (await res.json()).result as APIMessage;
return data.result as APIMessage;
};

export default sendMessage;
2 changes: 1 addition & 1 deletion src/scripts/tasks/pauseIdleConnections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default async (manager: ClusterManager) => {
});

// disconnect the channel
await modifyConnection({ channelId }, { lastActive: null, connected: false });
await modifyConnection({ channelId }, { connected: false });
});

const embed = simpleEmbed(
Expand Down
29 changes: 21 additions & 8 deletions src/utils/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
emojis,
SUPPORT_SERVER_ID,
} from './Constants.js';
import { randomBytes } from 'crypto';
import { createCipheriv, randomBytes } from 'crypto';
import { supportedLocaleCodes, t } from './Locale.js';
import 'dotenv/config';
import { captureException } from '@sentry/node';
Expand Down Expand Up @@ -509,13 +509,18 @@ export const fetchCommands = async (client: Client) => {
return await client.application?.commands.fetch();
};

export const findCommand = (name: string, commands: Collection<
string,
ApplicationCommand<{
guild: GuildResolvable;
}>
> | undefined) => {
return commands?.find(command => command.name === name);
export const findCommand = (
name: string,
commands:
| Collection<
string,
ApplicationCommand<{
guild: GuildResolvable;
}>
>
| undefined,
) => {
return commands?.find((command) => command.name === name);
};

export const findSubcommand = (
Expand All @@ -533,3 +538,11 @@ export const findSubcommand = (
({ type, name }) => type === ApplicationCommandOptionType.Subcommand && name === subName,
);
};

export const encryptMessage = (string: string, key: Buffer) => {
const iv: Buffer = randomBytes(16); // Initialization vector
const cipher = createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(string, 'utf8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
};

0 comments on commit 5a7ac0f

Please sign in to comment.