From 87fd47adce08a7a8d5d764c52fdadb6ee395adae Mon Sep 17 00:00:00 2001 From: Bsian Date: Fri, 13 Mar 2020 21:49:51 +0000 Subject: [PATCH] Rework command --- src/class/RichEmbed.ts | 352 ++++++++++++------------- src/class/Util.ts | 511 +++++++++++++++++++------------------ src/commands/cwg_create.ts | 374 ++++++++++++++++----------- types/eris.d.ts | 8 + 4 files changed, 669 insertions(+), 576 deletions(-) create mode 100644 types/eris.d.ts diff --git a/src/class/RichEmbed.ts b/src/class/RichEmbed.ts index 49d798d..678cccd 100644 --- a/src/class/RichEmbed.ts +++ b/src/class/RichEmbed.ts @@ -1,176 +1,176 @@ -/* eslint-disable no-param-reassign */ - -export default class RichEmbed { - title?: string - - type?: string - - description?: string - - url?: string - - timestamp?: Date - - color?: number - - footer?: { text: string, icon_url?: string, proxy_icon_url?: string} - - image?: { url?: string, proxy_url?: string, height?: number, width?: number } - - thumbnail?: { url?: string, proxy_url?: string, height?: number, width?: number } - - video?: { url?: string, height?: number, width?: number } - - provider?: { name?: string, url?: string} - - author?: { name?: string, url?: string, proxy_icon_url?: string, icon_url?: string} - - fields?: {name: string, value: string, inline?: boolean}[] - - constructor(data: { - title?: string, type?: string, description?: string, url?: string, timestamp?: Date, color?: number, fields?: {name: string, value: string, inline?: boolean}[] - footer?: { text: string, icon_url?: string, proxy_icon_url?: string}, image?: { url?: string, proxy_url?: string, height?: number, width?: number }, - thumbnail?: { url?: string, proxy_url?: string, height?: number, width?: number }, video?: { url?: string, height?: number, width?: number }, - provider?: { name?: string, url?: string}, author?: { name?: string, url?: string, proxy_icon_url?: string, icon_url?: string}, - } = {}) { - /* - let types: { - title?: string, type?: string, description?: string, url?: string, timestamp?: Date, color?: number, fields?: {name: string, value: string, inline?: boolean}[] - footer?: { text: string, icon_url?: string, proxy_icon_url?: string}, image?: { url?: string, proxy_url?: string, height?: number, width?: number }, - thumbnail?: { url?: string, proxy_url?: string, height?: number, width?: number }, video?: { url?: string, height?: number, width?: number }, - provider?: { name?: string, url?: string}, author?: { name?: string, url?: string, proxy_icon_url?: string, icon_url?: string} - }; - */ - this.title = data.title; - this.description = data.description; - this.url = data.url; - this.color = data.color; - this.author = data.author; - this.timestamp = data.timestamp; - this.fields = data.fields || []; - this.thumbnail = data.thumbnail; - this.image = data.image; - this.footer = data.footer; - } - - /** - * Sets the title of this embed. - */ - setTitle(title: string) { - if (typeof title !== 'string') throw new TypeError('RichEmbed titles must be a string.'); - if (title.length > 256) throw new RangeError('RichEmbed titles may not exceed 256 characters.'); - this.title = title; - return this; - } - - /** - * Sets the description of this embed. - */ - setDescription(description: string) { - if (typeof description !== 'string') throw new TypeError('RichEmbed descriptions must be a string.'); - if (description.length > 2048) throw new RangeError('RichEmbed descriptions may not exceed 2048 characters.'); - this.description = description; - return this; - } - - /** - * Sets the URL of this embed. - */ - setURL(url: string) { - if (typeof url !== 'string') throw new TypeError('RichEmbed URLs must be a string.'); - if (!url.startsWith('http://') || !url.startsWith('https://')) url = `https://${url}`; - this.url = url; - return this; - } - - /** - * Sets the color of this embed. - */ - setColor(color: string | number) { - if (typeof color === 'string' || typeof color === 'number') { - if (typeof color === 'string') { - const regex = /[^a-f0-9]/gi; - color = color.replace(/#/g, ''); - if (regex.test(color)) throw new RangeError('Hexadecimal colours must not contain characters other than 0-9 and a-f.'); - color = parseInt(color, 16); - } else if (color < 0 || color > 16777215) throw new RangeError('Base 10 colours must not be less than 0 or greater than 16777215.'); - this.color = color; - return this; - } - throw new TypeError('RichEmbed colours must be hexadecimal as string or number.'); - } - - /** - * Sets the author of this embed. - */ - setAuthor(name: string, icon_url?: string, url?: string) { - if (typeof name !== 'string') throw new TypeError('RichEmbed Author names must be a string.'); - if (url && typeof url !== 'string') throw new TypeError('RichEmbed Author URLs must be a string.'); - if (icon_url && typeof icon_url !== 'string') throw new TypeError('RichEmbed Author icons must be a string.'); - this.author = { name, icon_url, url }; - return this; - } - - /** - * Sets the timestamp of this embed. - */ - setTimestamp(timestamp = new Date()) { - // eslint-disable-next-line no-restricted-globals - if (isNaN(timestamp.getTime())) throw new TypeError('Expecting ISO8601 (Date constructor)'); - this.timestamp = timestamp; - return this; - } - - /** - * Adds a field to the embed (max 25). - */ - addField(name: string, value: string, inline = false) { - if (typeof name !== 'string') throw new TypeError('RichEmbed Field names must be a string.'); - if (typeof value !== 'string') throw new TypeError('RichEmbed Field values must be a string.'); - if (typeof inline !== 'boolean') throw new TypeError('RichEmbed Field inlines must be a boolean.'); - if (this.fields.length >= 25) throw new RangeError('RichEmbeds may not exceed 25 fields.'); - if (name.length > 256) throw new RangeError('RichEmbed field names may not exceed 256 characters.'); - if (!/\S/.test(name)) throw new RangeError('RichEmbed field names may not be empty.'); - if (value.length > 1024) throw new RangeError('RichEmbed field values may not exceed 1024 characters.'); - if (!/\S/.test(value)) throw new RangeError('RichEmbed field values may not be empty.'); - this.fields.push({ name, value, inline }); - return this; - } - - /** - * Convenience function for `.addField('\u200B', '\u200B', inline)`. - */ - addBlankField(inline = false) { - return this.addField('\u200B', '\u200B', inline); - } - - /** - * Set the thumbnail of this embed. - */ - setThumbnail(url: string) { - if (typeof url !== 'string') throw new TypeError('RichEmbed Thumbnail URLs must be a string.'); - this.thumbnail = { url }; - return this; - } - - /** - * Set the image of this embed. - */ - setImage(url: string) { - if (typeof url !== 'string') throw new TypeError('RichEmbed Image URLs must be a string.'); - if (!url.startsWith('http://') || !url.startsWith('https://')) url = `https://${url}`; - this.image = { url }; - return this; - } - - /** - * Sets the footer of this embed. - */ - setFooter(text: string, icon_url?: string) { - if (typeof text !== 'string') throw new TypeError('RichEmbed Footers must be a string.'); - if (icon_url && typeof icon_url !== 'string') throw new TypeError('RichEmbed Footer icon URLs must be a string.'); - if (text.length > 2048) throw new RangeError('RichEmbed footer text may not exceed 2048 characters.'); - this.footer = { text, icon_url }; - return this; - } -} +/* eslint-disable no-param-reassign */ + +export default class RichEmbed { + title?: string + + type?: string + + description?: string + + url?: string + + timestamp?: Date + + color?: number + + footer?: { text: string, icon_url?: string, proxy_icon_url?: string} + + image?: { url: string, proxy_url?: string, height?: number, width?: number } + + thumbnail?: { url?: string, proxy_url?: string, height?: number, width?: number } + + video?: { url: string, height?: number, width?: number } + + provider?: { name: string, url?: string} + + author?: { name: string, url?: string, proxy_icon_url?: string, icon_url?: string} + + fields?: {name: string, value: string, inline?: boolean}[] + + constructor(data: { + title?: string, type?: string, description?: string, url?: string, timestamp?: Date, color?: number, fields?: {name: string, value: string, inline?: boolean}[] + footer?: { text: string, icon_url?: string, proxy_icon_url?: string}, image?: { url: string, proxy_url?: string, height?: number, width?: number }, + thumbnail?: { url: string, proxy_url?: string, height?: number, width?: number }, video?: { url: string, height?: number, width?: number }, + provider?: { name: string, url?: string}, author?: { name: string, url?: string, proxy_icon_url?: string, icon_url?: string}, + } = {}) { + /* + let types: { + title?: string, type?: string, description?: string, url?: string, timestamp?: Date, color?: number, fields?: {name: string, value: string, inline?: boolean}[] + footer?: { text: string, icon_url?: string, proxy_icon_url?: string}, image?: { url?: string, proxy_url?: string, height?: number, width?: number }, + thumbnail?: { url?: string, proxy_url?: string, height?: number, width?: number }, video?: { url?: string, height?: number, width?: number }, + provider?: { name?: string, url?: string}, author?: { name?: string, url?: string, proxy_icon_url?: string, icon_url?: string} + }; + */ + this.title = data.title; + this.description = data.description; + this.url = data.url; + this.color = data.color; + this.author = data.author; + this.timestamp = data.timestamp; + this.fields = data.fields || []; + this.thumbnail = data.thumbnail; + this.image = data.image; + this.footer = data.footer; + } + + /** + * Sets the title of this embed. + */ + setTitle(title: string) { + if (typeof title !== 'string') throw new TypeError('RichEmbed titles must be a string.'); + if (title.length > 256) throw new RangeError('RichEmbed titles may not exceed 256 characters.'); + this.title = title; + return this; + } + + /** + * Sets the description of this embed. + */ + setDescription(description: string) { + if (typeof description !== 'string') throw new TypeError('RichEmbed descriptions must be a string.'); + if (description.length > 2048) throw new RangeError('RichEmbed descriptions may not exceed 2048 characters.'); + this.description = description; + return this; + } + + /** + * Sets the URL of this embed. + */ + setURL(url: string) { + if (typeof url !== 'string') throw new TypeError('RichEmbed URLs must be a string.'); + if (!url.startsWith('http://') || !url.startsWith('https://')) url = `https://${url}`; + this.url = url; + return this; + } + + /** + * Sets the color of this embed. + */ + setColor(color: string | number) { + if (typeof color === 'string' || typeof color === 'number') { + if (typeof color === 'string') { + const regex = /[^a-f0-9]/gi; + color = color.replace(/#/g, ''); + if (regex.test(color)) throw new RangeError('Hexadecimal colours must not contain characters other than 0-9 and a-f.'); + color = parseInt(color, 16); + } else if (color < 0 || color > 16777215) throw new RangeError('Base 10 colours must not be less than 0 or greater than 16777215.'); + this.color = color; + return this; + } + throw new TypeError('RichEmbed colours must be hexadecimal as string or number.'); + } + + /** + * Sets the author of this embed. + */ + setAuthor(name: string, icon_url?: string, url?: string) { + if (typeof name !== 'string') throw new TypeError('RichEmbed Author names must be a string.'); + if (url && typeof url !== 'string') throw new TypeError('RichEmbed Author URLs must be a string.'); + if (icon_url && typeof icon_url !== 'string') throw new TypeError('RichEmbed Author icons must be a string.'); + this.author = { name, icon_url, url }; + return this; + } + + /** + * Sets the timestamp of this embed. + */ + setTimestamp(timestamp = new Date()) { + // eslint-disable-next-line no-restricted-globals + if (isNaN(timestamp.getTime())) throw new TypeError('Expecting ISO8601 (Date constructor)'); + this.timestamp = timestamp; + return this; + } + + /** + * Adds a field to the embed (max 25). + */ + addField(name: string, value: string, inline = false) { + if (typeof name !== 'string') throw new TypeError('RichEmbed Field names must be a string.'); + if (typeof value !== 'string') throw new TypeError('RichEmbed Field values must be a string.'); + if (typeof inline !== 'boolean') throw new TypeError('RichEmbed Field inlines must be a boolean.'); + if (this.fields.length >= 25) throw new RangeError('RichEmbeds may not exceed 25 fields.'); + if (name.length > 256) throw new RangeError('RichEmbed field names may not exceed 256 characters.'); + if (!/\S/.test(name)) throw new RangeError('RichEmbed field names may not be empty.'); + if (value.length > 1024) throw new RangeError('RichEmbed field values may not exceed 1024 characters.'); + if (!/\S/.test(value)) throw new RangeError('RichEmbed field values may not be empty.'); + this.fields.push({ name, value, inline }); + return this; + } + + /** + * Convenience function for `.addField('\u200B', '\u200B', inline)`. + */ + addBlankField(inline = false) { + return this.addField('\u200B', '\u200B', inline); + } + + /** + * Set the thumbnail of this embed. + */ + setThumbnail(url: string) { + if (typeof url !== 'string') throw new TypeError('RichEmbed Thumbnail URLs must be a string.'); + this.thumbnail = { url }; + return this; + } + + /** + * Set the image of this embed. + */ + setImage(url: string) { + if (typeof url !== 'string') throw new TypeError('RichEmbed Image URLs must be a string.'); + if (!url.startsWith('http://') || !url.startsWith('https://')) url = `https://${url}`; + this.image = { url }; + return this; + } + + /** + * Sets the footer of this embed. + */ + setFooter(text: string, icon_url?: string) { + if (typeof text !== 'string') throw new TypeError('RichEmbed Footers must be a string.'); + if (icon_url && typeof icon_url !== 'string') throw new TypeError('RichEmbed Footer icon URLs must be a string.'); + if (text.length > 2048) throw new RangeError('RichEmbed footer text may not exceed 2048 characters.'); + this.footer = { text, icon_url }; + return this; + } +} diff --git a/src/class/Util.ts b/src/class/Util.ts index 0bbf3c5..22f7b5a 100644 --- a/src/class/Util.ts +++ b/src/class/Util.ts @@ -1,253 +1,258 @@ -/* eslint-disable no-param-reassign */ -import { promisify } from 'util'; -import childProcess from 'child_process'; -import nodemailer from 'nodemailer'; -import { Message, PrivateChannel, GroupChannel, Member, User } from 'eris'; -import uuid from 'uuid/v4'; -import moment from 'moment'; -import fs from 'fs'; -import os from 'os'; -import { Client } from '..'; -import { Command, RichEmbed } from '.'; -import { ModerationInterface, AccountInterface } from '../models'; - -export default class Util { - public client: Client; - - public transport: nodemailer.Transporter; - - constructor(client: Client) { - this.client = client; - this.transport = nodemailer.createTransport({ - host: 'staff.libraryofcode.org', - auth: { user: 'support', pass: this.client.config.emailPass }, - }); - } - - /** - * Executes a terminal command async. - * @param command The command to execute - * @param options childProcess.ExecOptions - */ - public async exec(command: string, options: childProcess.ExecOptions = {}): Promise { - const ex = promisify(childProcess.exec); - let result: string; - try { - const res = await ex(command, options); - result = `${res.stdout}${res.stderr}`; - } catch (err) { - return Promise.reject(new Error(`Command failed: ${err.cmd}\n${err.stderr}${err.stdout}`)); - } - return result; - } - - /** - * Resolves a command - * @param query Command input - * @param message Only used to check for errors - */ - public resolveCommand(query: string | string[], message?: Message): Promise<{cmd: Command, args: string[] }> { - try { - let resolvedCommand: Command; - if (typeof query === 'string') query = query.split(' '); - const commands = this.client.commands.toArray(); - resolvedCommand = commands.find((c) => c.name === query[0].toLowerCase() || c.aliases.includes(query[0].toLowerCase())); - - if (!resolvedCommand) return Promise.resolve(null); - query.shift(); - while (resolvedCommand.subcommands.size && query.length) { - const subCommands = resolvedCommand.subcommands.toArray(); - const found = subCommands.find((c) => c.name === query[0].toLowerCase() || c.aliases.includes(query[0].toLowerCase())); - if (!found) break; - resolvedCommand = found; - query.shift(); - } - return Promise.resolve({ cmd: resolvedCommand, args: query }); - } catch (error) { - if (message) this.handleError(error, message); - else this.handleError(error); - return Promise.reject(error); - } - } - - public async handleError(error: Error, message?: Message, command?: Command): Promise { - try { - this.client.signale.error(error); - const info = { content: `\`\`\`js\n${error.stack}\n\`\`\``, embed: null }; - if (message) { - const embed = new RichEmbed(); - embed.setColor('FF0000'); - embed.setAuthor(`Error caused by ${message.author.username}#${message.author.discriminator}`, message.author.avatarURL); - embed.setTitle('Message content'); - embed.setDescription(message.content); - embed.addField('User', `${message.author.mention} (\`${message.author.id}\`)`, true); - embed.addField('Channel', message.channel.mention, true); - let guild: string; - if (message.channel instanceof PrivateChannel || message.channel instanceof GroupChannel) guild = '@me'; - else guild = message.channel.guild.id; - embed.addField('Message link', `[Click here](https://discordapp.com/channels/${guild}/${message.channel.id}/${message.id})`, true); - embed.setTimestamp(new Date(message.timestamp)); - info.embed = embed; - } - await this.client.createMessage('595788220764127272', info); - const msg = message.content.slice(this.client.config.prefix.length).trim().split(/ +/g); - if (command) this.resolveCommand(msg).then((c) => { c.cmd.enabled = false; }); - if (message) message.channel.createMessage(`***${this.client.stores.emojis.error} An unexpected error has occured - please contact a member of the Engineering Team.${command ? ' This command has been disabled.' : ''}***`); - } catch (err) { - this.client.signale.error(err); - } - } - - public splitFields(fields: { name: string, value: string, inline?: boolean }[]): { name: string, value: string, inline?: boolean }[][] { - let index = 0; - const array: {name: string, value: string, inline?: boolean}[][] = [[]]; - while (fields.length) { - if (array[index].length >= 25) { index += 1; array[index] = []; } - array[index].push(fields[0]); fields.shift(); - } - return array; - } - - public splitString(string: string, length: number): string[] { - if (!string) return []; - if (Array.isArray(string)) string = string.join('\n'); - if (string.length <= length) return [string]; - const arrayString: string[] = []; - let str: string = ''; - let pos: number; - while (string.length > 0) { - pos = string.length > length ? string.lastIndexOf('\n', length) : string.length; - if (pos > length) pos = length; - str = string.substr(0, pos); - string = string.substr(pos); - arrayString.push(str); - } - return arrayString; - } - - - public async createHash(password: string): Promise { - const hashed = await this.exec(`mkpasswd -m sha-512 "${password}"`); - return hashed; - } - - public isValidEmail(email: string): boolean { - const checkAt = email.indexOf('@'); - if (checkAt < 1) return false; - const checkDomain = email.indexOf('.', checkAt + 2); - if (checkDomain < checkAt) return false; - return true; - } - - public randomPassword(): string { - let tempPass = ''; const passChars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; - while (tempPass.length < 5) { tempPass += passChars[Math.floor(Math.random() * passChars.length)]; } - return tempPass; - } - - public async createAccount(hash: string, etcPasswd: string, username: string, userID: string, emailAddress: string, moderatorID: string): Promise { - await this.exec(`useradd -m -p ${hash} -c ${etcPasswd} -s /bin/zsh ${username}`); - await this.exec(`chage -d0 ${username}`); - - const account = new this.client.db.Account({ - username, userID, emailAddress, createdBy: moderatorID, createdAt: new Date(), locked: false, ssInit: false, homepath: `/home/${username}`, - }); - return account.save(); - } - - public async deleteAccount(username: string): Promise { - const account = await this.client.db.Account.findOne({ username }); - if (!account) throw new Error('Account not found'); - this.exec(`lock ${username}`); - const tasks = [ - this.exec(`deluser ${username} --remove-home --backup-to /management/Archives && rm -rf -R ${account.homepath}`), - this.client.db.Account.deleteOne({ username }), - ]; - this.client.removeGuildMemberRole('446067825673633794', account.userID, '546457886440685578', 'Cloud Account Deleted').catch(); - // @ts-ignore - await Promise.all(tasks); - } - - public async messageCollector(message: Message, question: string, timeout: number, shouldDelete = false, choices: string[] = null, filter = (msg: Message): boolean|void => {}): Promise { - const msg = await message.channel.createMessage(question); - return new Promise((res, rej) => { - setTimeout(() => { if (shouldDelete) msg.delete().catch(); rej(new Error('Did not supply a valid input in time')); }, timeout); - this.client.on('messageCreate', (Msg) => { - if (filter(Msg) === false) return; - const verif = choices ? choices.includes(Msg.content) : Msg.content; - if (verif) { if (shouldDelete) msg.delete().catch(); res(Msg); } - }); - }); - } - - /** - * @param type `0` - Create - * - * `1` - Warn - * - * `2` - Lock - * - * `3` - Unlock - * - * `4` - Delete - */ - public async createModerationLog(user: string, moderator: Member|User, type: number, reason?: string, duration?: number): Promise { - const moderatorID = moderator.id; - const account = await this.client.db.Account.findOne({ $or: [{ username: user }, { userID: user }] }); - if (!account) return Promise.reject(new Error(`Account ${user} not found`)); - const { username, userID } = account; - const logInput: { username: string, userID: string, logID: string, moderatorID: string, reason?: string, type: number, date: Date, expiration?: { date: Date, processed: boolean }} = { - username, userID, logID: uuid(), moderatorID, type, date: new Date(), - }; - - const now: number = Date.now(); - let date: Date; - let processed = true; - if (reason) logInput.reason = reason; - if (type === 2) { - if (duration) { - date = new Date(now + duration); - processed = false; - } else date = null; - } - - const expiration = { date, processed }; - - logInput.expiration = expiration; - const log = new this.client.db.Moderation(logInput); - await log.save(); - - let embedTitle: string; - let color: string; - let archType: string; - switch (type) { - default: archType = 'Staff'; embedTitle = 'Cloud Account | Generic'; color = '0892e1'; break; - case 0: archType = 'Administrator'; embedTitle = 'Cloud Account | Create'; color = '00ff00'; break; - case 1: archType = 'Staff'; embedTitle = 'Account Warning | Warn'; color = 'ffff00'; break; - case 2: archType = 'Moderator'; embedTitle = 'Account Infraction | Lock'; color = 'ff6600'; break; - case 3: archType = 'Moderator'; embedTitle = 'Account Reclaim | Unlock'; color = '0099ff'; break; - case 4: archType = 'Administrator'; embedTitle = 'Cloud Account | Delete'; color = 'ff0000'; break; - } - const embed = new RichEmbed() - .setTitle(embedTitle) - .setColor(color) - .addField('User', `${username} | <@${userID}>`, true) - .addField(archType, moderatorID === this.client.user.id ? 'SYSTEM' : `<@${moderatorID}>`, true) - .setFooter(this.client.user.username, this.client.user.avatarURL) - .setTimestamp(); - if (reason) embed.addField('Reason', reason || 'Not specified'); - if (type === 2) embed.addField('Lock Expiration', `${date ? moment(date).format('dddd, MMMM Do YYYY, h:mm:ss A') : 'Indefinitely'}`); - // @ts-ignore - this.client.createMessage('580950455581147146', { embed }); this.client.getDMChannel(userID).then((channel) => channel.createMessage({ embed })).catch(); - - return Promise.resolve(log); - } - - public getAcctHash(userpath: string) { - try { - return fs.readFileSync(`${userpath}/.securesign/auth`).toString(); - } catch (error) { - return null; - } - } -} +/* eslint-disable no-param-reassign */ +import { promisify } from 'util'; +import childProcess from 'child_process'; +import nodemailer from 'nodemailer'; +import { Message, PrivateChannel, GroupChannel, Member, User } from 'eris'; +import uuid from 'uuid/v4'; +import moment from 'moment'; +import fs from 'fs'; +import os from 'os'; +import { Client } from '..'; +import { Command, RichEmbed } from '.'; +import { ModerationInterface, AccountInterface } from '../models'; + +export default class Util { + public client: Client; + + public transport: nodemailer.Transporter; + + constructor(client: Client) { + this.client = client; + this.transport = nodemailer.createTransport({ + host: 'staff.libraryofcode.org', + auth: { user: 'support', pass: this.client.config.emailPass }, + }); + } + + /** + * Executes a terminal command async. + * @param command The command to execute + * @param options childProcess.ExecOptions + */ + public async exec(command: string, options: childProcess.ExecOptions = {}): Promise { + const ex = promisify(childProcess.exec); + let result: string; + try { + const res = await ex(command, options); + result = `${res.stdout}${res.stderr}`; + } catch (err) { + return Promise.reject(new Error(`Command failed: ${err.cmd}\n${err.stderr}${err.stdout}`)); + } + return result; + } + + /** + * Resolves a command + * @param query Command input + * @param message Only used to check for errors + */ + public resolveCommand(query: string | string[], message?: Message): Promise<{cmd: Command, args: string[] }> { + try { + let resolvedCommand: Command; + if (typeof query === 'string') query = query.split(' '); + const commands = this.client.commands.toArray(); + resolvedCommand = commands.find((c) => c.name === query[0].toLowerCase() || c.aliases.includes(query[0].toLowerCase())); + + if (!resolvedCommand) return Promise.resolve(null); + query.shift(); + while (resolvedCommand.subcommands.size && query.length) { + const subCommands = resolvedCommand.subcommands.toArray(); + const found = subCommands.find((c) => c.name === query[0].toLowerCase() || c.aliases.includes(query[0].toLowerCase())); + if (!found) break; + resolvedCommand = found; + query.shift(); + } + return Promise.resolve({ cmd: resolvedCommand, args: query }); + } catch (error) { + if (message) this.handleError(error, message); + else this.handleError(error); + return Promise.reject(error); + } + } + + public async handleError(error: Error, message?: Message, command?: Command): Promise { + try { + this.client.signale.error(error); + const info = { content: `\`\`\`js\n${error.stack}\n\`\`\``, embed: null }; + if (message) { + const embed = new RichEmbed(); + embed.setColor('FF0000'); + embed.setAuthor(`Error caused by ${message.author.username}#${message.author.discriminator}`, message.author.avatarURL); + embed.setTitle('Message content'); + embed.setDescription(message.content); + embed.addField('User', `${message.author.mention} (\`${message.author.id}\`)`, true); + embed.addField('Channel', message.channel.mention, true); + let guild: string; + if (message.channel instanceof PrivateChannel || message.channel instanceof GroupChannel) guild = '@me'; + else guild = message.channel.guild.id; + embed.addField('Message link', `[Click here](https://discordapp.com/channels/${guild}/${message.channel.id}/${message.id})`, true); + embed.setTimestamp(new Date(message.timestamp)); + info.embed = embed; + } + await this.client.createMessage('595788220764127272', info); + const msg = message.content.slice(this.client.config.prefix.length).trim().split(/ +/g); + if (command) this.resolveCommand(msg).then((c) => { c.cmd.enabled = false; }); + if (message) message.channel.createMessage(`***${this.client.stores.emojis.error} An unexpected error has occured - please contact a member of the Engineering Team.${command ? ' This command has been disabled.' : ''}***`); + } catch (err) { + this.client.signale.error(err); + } + } + + public splitFields(fields: { name: string, value: string, inline?: boolean }[]): { name: string, value: string, inline?: boolean }[][] { + let index = 0; + const array: {name: string, value: string, inline?: boolean}[][] = [[]]; + while (fields.length) { + if (array[index].length >= 25) { index += 1; array[index] = []; } + array[index].push(fields[0]); fields.shift(); + } + return array; + } + + public splitString(string: string, length: number): string[] { + if (!string) return []; + if (Array.isArray(string)) string = string.join('\n'); + if (string.length <= length) return [string]; + const arrayString: string[] = []; + let str: string = ''; + let pos: number; + while (string.length > 0) { + pos = string.length > length ? string.lastIndexOf('\n', length) : string.length; + if (pos > length) pos = length; + str = string.substr(0, pos); + string = string.substr(pos); + arrayString.push(str); + } + return arrayString; + } + + + public async createHash(password: string): Promise { + const hashed = await this.exec(`mkpasswd -m sha-512 "${password}"`); + return hashed; + } + + public isValidEmail(email: string): boolean { + const checkAt = email.indexOf('@'); + if (checkAt < 1) return false; + const checkDomain = email.indexOf('.', checkAt + 2); + if (checkDomain < checkAt) return false; + return true; + } + + public randomPassword(): string { + let tempPass = ''; const passChars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; + while (tempPass.length < 5) { tempPass += passChars[Math.floor(Math.random() * passChars.length)]; } + return tempPass; + } + + public async createAccount(hash: string, etcPasswd: string, username: string, userID: string, emailAddress: string, moderatorID: string): Promise { + await this.exec(`useradd -m -p ${hash} -c ${etcPasswd} -s /bin/zsh ${username}`); + await this.exec(`chage -d0 ${username}`); + + const account = new this.client.db.Account({ + username, userID, emailAddress, createdBy: moderatorID, createdAt: new Date(), locked: false, ssInit: false, homepath: `/home/${username}`, + }); + return account.save(); + } + + public async deleteAccount(username: string): Promise { + const account = await this.client.db.Account.findOne({ username }); + if (!account) throw new Error('Account not found'); + this.exec(`lock ${username}`); + const tasks = [ + this.exec(`deluser ${username} --remove-home --backup-to /management/Archives && rm -rf -R ${account.homepath}`), + this.client.db.Account.deleteOne({ username }), + ]; + this.client.removeGuildMemberRole('446067825673633794', account.userID, '546457886440685578', 'Cloud Account Deleted').catch(); + // @ts-ignore + await Promise.all(tasks); + } + + public async messageCollector(message: Message, question: string, timeout: number, shouldDelete = false, choices: string[] = null, filter = (msg: Message): boolean|void => {}): Promise { + const msg = await message.channel.createMessage(question); + return new Promise((res, rej) => { + const func = (Msg: Message) => { + if (filter(Msg) === false) return; + const verif = choices ? choices.includes(Msg.content) : Msg.content; + if (verif) { if (shouldDelete) msg.delete().catch(); res(Msg); } + }; + + setTimeout(() => { + if (shouldDelete) msg.delete().catch(); rej(new Error('Did not supply a valid input in time')); + this.client.removeListener('messageCreate', func); + }, timeout); + this.client.on('messageCreate', func); + }); + } + + /** + * @param type `0` - Create + * + * `1` - Warn + * + * `2` - Lock + * + * `3` - Unlock + * + * `4` - Delete + */ + public async createModerationLog(user: string, moderator: Member|User, type: number, reason?: string, duration?: number): Promise { + const moderatorID = moderator.id; + const account = await this.client.db.Account.findOne({ $or: [{ username: user }, { userID: user }] }); + if (!account) return Promise.reject(new Error(`Account ${user} not found`)); + const { username, userID } = account; + const logInput: { username: string, userID: string, logID: string, moderatorID: string, reason?: string, type: number, date: Date, expiration?: { date: Date, processed: boolean }} = { + username, userID, logID: uuid(), moderatorID, type, date: new Date(), + }; + + const now: number = Date.now(); + let date: Date; + let processed = true; + if (reason) logInput.reason = reason; + if (type === 2) { + if (duration) { + date = new Date(now + duration); + processed = false; + } else date = null; + } + + const expiration = { date, processed }; + + logInput.expiration = expiration; + const log = new this.client.db.Moderation(logInput); + await log.save(); + + let embedTitle: string; + let color: string; + let archType: string; + switch (type) { + default: archType = 'Staff'; embedTitle = 'Cloud Account | Generic'; color = '0892e1'; break; + case 0: archType = 'Administrator'; embedTitle = 'Cloud Account | Create'; color = '00ff00'; break; + case 1: archType = 'Staff'; embedTitle = 'Account Warning | Warn'; color = 'ffff00'; break; + case 2: archType = 'Moderator'; embedTitle = 'Account Infraction | Lock'; color = 'ff6600'; break; + case 3: archType = 'Moderator'; embedTitle = 'Account Reclaim | Unlock'; color = '0099ff'; break; + case 4: archType = 'Administrator'; embedTitle = 'Cloud Account | Delete'; color = 'ff0000'; break; + } + const embed = new RichEmbed() + .setTitle(embedTitle) + .setColor(color) + .addField('User', `${username} | <@${userID}>`, true) + .addField(archType, moderatorID === this.client.user.id ? 'SYSTEM' : `<@${moderatorID}>`, true) + .setFooter(this.client.user.username, this.client.user.avatarURL) + .setTimestamp(); + if (reason) embed.addField('Reason', reason || 'Not specified'); + if (type === 2) embed.addField('Lock Expiration', `${date ? moment(date).format('dddd, MMMM Do YYYY, h:mm:ss A') : 'Indefinitely'}`); + // @ts-ignore + this.client.createMessage('580950455581147146', { embed }); this.client.getDMChannel(userID).then((channel) => channel.createMessage({ embed })).catch(); + + return Promise.resolve(log); + } + + public getAcctHash(userpath: string) { + try { + return fs.readFileSync(`${userpath}/.securesign/auth`).toString(); + } catch (error) { + return null; + } + } +} diff --git a/src/commands/cwg_create.ts b/src/commands/cwg_create.ts index 7ac1ee0..fa738af 100644 --- a/src/commands/cwg_create.ts +++ b/src/commands/cwg_create.ts @@ -1,147 +1,227 @@ -import fs from 'fs-extra'; -import axios from 'axios'; -import x509 from '@ghaiklor/x509'; -import { Message } from 'eris'; -import { AccountInterface } from '../models'; -import { Command, RichEmbed } from '../class'; -import { Client } from '..'; - -export default class CWG_Create extends Command { - constructor(client: Client) { - super(client); - this.name = 'create'; - this.description = 'Bind a domain to the CWG'; - this.usage = `${this.client.config.prefix}cwg create [User ID | Username] [Domain] [Port] `; - this.permissions = { roles: ['525441307037007902'] }; - this.aliases = ['bind']; - this.enabled = true; - } - - public async run(message: Message, args: string[]) { - /* - args[0] should be the user's ID OR account username; required - args[1] should be the domain; required - args[2] should be the port; required - args[3] should be the path to the x509 certificate; not required - args[4] should be the path to the x509 key; not required - */ - try { - if (!args[2]) return this.client.commands.get('help').run(message, ['cwg', this.name]); - const edit = await message.channel.createMessage(`***${this.client.stores.emojis.loading} Binding domain...***`); - const account = await this.client.db.Account.findOne({ $or: [{ username: args[0] }, { userID: args[0] }] }); - if (!account) return edit.edit(`${this.client.stores.emojis.error} Cannot locate account, please try again.`); - if (args[3] && !args[4]) return edit.edit(`${this.client.stores.emojis.error} x509 Certificate key required`); - let certs: { cert?: string, key?: string }; if (args[4]) certs = { cert: args[3], key: args[4] }; - if (await this.client.db.Domain.exists({ domain: args[1] })) return edit.edit(`***${this.client.stores.emojis.error} This domain already exists.***`); - if (await this.client.db.Domain.exists({ port: Number(args[2]) })) { - // await edit.edit(`***${this.client.stores.emojis.error} This port is already binded to a domain. Do you wish to continue? (y/n)***`); - let answer: Message; - try { - answer = await this.client.util.messageCollector(message, - `***${this.client.stores.emojis.error} This port is already binded to a domain. Do you wish to continue? (y/n)***`, - 30000, true, ['y', 'n'], (msg) => msg.author.id === message.author.id && msg.channel.id === message.channel.id); - } catch (error) { - return edit.edit(`***${this.client.stores.emojis.error} Bind request cancelled***`); - } - if (answer.content === 'n') return edit.edit(`***${this.client.stores.emojis.error} Bind request cancelled***`); - } - const domain = await this.createDomain(account, args[1], Number(args[2]), certs); - const embed = new RichEmbed(); - embed.setTitle('Domain Creation'); - embed.setColor(3066993); - embed.addField('Account Username', account.username, true); - embed.addField('Account ID', account.id, true); - embed.addField('Engineer', `<@${message.author.id}>`, true); - embed.addField('Domain', domain.domain, true); - embed.addField('Port', String(domain.port), true); - const cert = x509.parseCert(await fs.readFile(domain.x509.cert, { encoding: 'utf8' })); - embed.addField('Certificate Issuer', cert.issuer.organizationName, true); - embed.addField('Certificate Subject', cert.subject.commonName, true); - embed.setFooter(this.client.user.username, this.client.user.avatarURL); - embed.setTimestamp(new Date(message.timestamp)); - message.delete(); - await this.client.util.exec('systemctl reload nginx'); - edit.edit(`***${this.client.stores.emojis.success} Successfully binded ${domain.domain} to port ${domain.port} for ${account.userID}.***`); - // @ts-ignore - this.client.createMessage('580950455581147146', { embed }); - // @ts-ignore - this.client.getDMChannel(account.userID).then((r) => r.createMessage({ embed })); - await this.client.util.transport.sendMail({ - to: account.emailAddress, - from: 'Library of Code sp-us | Support Team ', - subject: 'Your domain has been binded', - html: ` -

Library of Code sp-us | Cloud Services

-

Hello, this is an email informing you that a new domain under your account has been binded. - Information is below.

- Domain: ${domain.domain}
- Port: ${domain.port}
- Certificate Issuer: ${cert.issuer.organizationName}
- Certificate Subject: ${cert.subject.commonName}
- Responsible Engineer: ${message.author.username}#${message.author.discriminator}

- - If you have any questions about additional setup, you can reply to this email or send a message in #cloud-support in our Discord server.
- - Library of Code sp-us | Support Team - `, - }); - if (!domain.domain.includes('cloud.libraryofcode.org')) { - const content = `__**DNS Record Setup**__\nYou recently a binded a custom domain to your Library of Code sp-us Account. You'll have to update your DNS records. We've provided the records below.\n\n\`${domain.domain} IN CNAME cloud.libraryofcode.org AUTO/500\`\nThis basically means you need to make a CNAME record with the key/host of ${domain.domain} and the value/point to cloud.libraryofcode.org. If you have any questions, don't hesitate to ask us.`; - this.client.getDMChannel(account.userID).then((r) => r.createMessage(content)); - } - return domain; - } catch (err) { - await fs.unlink(`/etc/nginx/sites-available/${args[1]}`); - await fs.unlink(`/etc/nginx/sites-enabled/${args[1]}`); - await this.client.db.Domain.deleteMany({ domain: args[1] }); - return this.client.util.handleError(err, message, this); - } - } - - /** - * This function binds a domain to a port on the CWG. - * @param account The account of the user. - * @param subdomain The domain to use. `mydomain.cloud.libraryofcode.org` - * @param port The port to use, must be between 1024 and 65535. - * @param x509 The paths to the certificate and key files. Must be already existant. - * @example await CWG.createDomain('mydomain.cloud.libraryofcode.org', 6781); - */ - public async createDomain(account: AccountInterface, domain: string, port: number, x509Certificate: { cert?: string, key?: string } = { cert: '/etc/nginx/ssl/cloud-org.chain.crt', key: '/etc/nginx/ssl/cloud-org.key.pem' }) { - try { - if (port <= 1024 || port >= 65535) throw new RangeError(`Port range must be between 1024 and 65535, received ${port}.`); - if (await this.client.db.Domain.exists({ domain })) throw new Error(`Domain ${domain} already exists in the database.`); - if (!await this.client.db.Account.exists({ userID: account.userID })) throw new Error(`Cannot find account ${account.userID}.`); - await fs.access(x509Certificate.cert, fs.constants.R_OK); - await fs.access(x509Certificate.key, fs.constants.R_OK); - let cfg = await fs.readFile('/var/CloudServices/dist/static/nginx.conf', { encoding: 'utf8' }); - cfg = cfg.replace(/\[DOMAIN]/g, domain); - cfg = cfg.replace(/\[PORT]/g, String(port)); - cfg = cfg.replace(/\[CERTIFICATE]/g, x509Certificate.cert); - cfg = cfg.replace(/\[KEY]/g, x509Certificate.key); - await fs.writeFile(`/etc/nginx/sites-available/${domain}`, cfg, { encoding: 'utf8' }); - await fs.symlink(`/etc/nginx/sites-available/${domain}`, `/etc/nginx/sites-enabled/${domain}`); - const entry = new this.client.db.Domain({ - account, - domain, - port, - x509: x509Certificate, - enabled: true, - }); - if (domain.includes('cloud.libraryofcode.org')) { - const dmn = domain.split('.'); - await axios({ - method: 'post', - url: 'https://api.cloudflare.com/client/v4/zones/5e82fc3111ed4fbf9f58caa34f7553a7/dns_records', - headers: { Authorization: `Bearer ${this.client.config.cloudflare}`, 'Content-Type': 'application/json' }, - data: JSON.stringify({ type: 'CNAME', name: `${dmn[0]}.${dmn[1]}`, content: 'cloud.libraryofcode.org', proxied: false }), - }); - } - return entry.save(); - } catch (error) { - await fs.unlink(`/etc/nginx/sites-enabled/${domain}`); - await fs.unlink(`/etc/nginx/sites-available/${domain}`); - await this.client.db.Domain.deleteMany({ domain }); - throw error; - } - } -} +import fs, { writeFile, unlink } from 'fs-extra'; +import axios from 'axios'; +import { Message } from 'eris'; +import { AccountInterface } from '../models'; +import { Command, RichEmbed } from '../class'; +import { Client } from '..'; +import { parseCertificate } from '../functions'; + +export default class CWG_Create extends Command { + public urlRegex: RegExp; + + constructor(client: Client) { + super(client); + this.name = 'create'; + this.description = 'Bind a domain to the CWG'; + this.usage = `${this.client.config.prefix}cwg create [User ID | Username] [Domain] [Port] || Use snippets raw URL`; + this.permissions = { roles: ['525441307037007902'] }; + this.aliases = ['bind']; + this.enabled = true; + this.urlRegex = /^[a-zA-Z0-9\-._~:/?#[\]@!$&'()*+,;=]+$/; + } + + public async run(message: Message, args: string[]) { + /* + args[0] should be the user's ID OR account username; required + args[1] should be the domain; required + args[2] should be the port; required + args[3] should be the path to the x509 certificate; not required + args[4] should be the path to the x509 key; not required + */ + try { + if (!args[2]) return this.client.commands.get('help').run(message, ['cwg', this.name]); + + let certs: { cert: string, key: string }; + + if (!this.urlRegex.test(args[1])) return message.channel.createMessage(`${this.client.stores.emojis.error} ***Invalid URL***`); + if (Number(args[2]) < 1024 || Number(args[2]) > 65535) return message.channel.createMessage(`${this.client.stores.emojis.error} ***Port must be greater than 1024 and less than 65535***`); + if (!args[1].endsWith('.cloud.libraryofcode.org') && !args[4]) return message.channel.createMessage(`${this.client.stores.emojis.error} ***Certificate Chain and Private Key are required for custom domains***`); + + const account = await this.client.db.Account.findOne({ $or: [{ username: args[0] }, { userID: args[0] }] }); + if (!account) return message.channel.createMessage(`${this.client.stores.emojis.error} Cannot locate account, please try again.`); + + if (await this.client.db.Domain.exists({ domain: args[1] })) return message.channel.createMessage(`${this.client.stores.emojis.error} ***This domain already exists***`); + + if (await this.client.db.Domain.exists({ port: Number(args[2]) })) { + let answer: Message; + try { + answer = await this.client.util.messageCollector( + message, + `***${this.client.stores.emojis.error} ***This port is already binded to a domain. Do you wish to continue? (y/n)***`, + 30000, true, ['y', 'n'], (msg) => msg.author.id === message.author.id && msg.channel.id === message.channel.id, + ); + } catch (error) { + return message.channel.createMessage(`${this.client.stores.emojis.error} ***Bind request cancelled***`); + } + if (answer.content === 'n') return message.channel.createMessage(`${this.client.stores.emojis.error} ***Bind request cancelled***`); + } + + const edit = await message.channel.createMessage(`${this.client.stores.emojis.loading} ***Binding domain...***`); + + if (!args[1].endsWith('.cloud.libraryofcode.org')) { + const urls = args.slice(3, 5); + if (urls.some((l) => !l.includes('snippets.cloud.libraryofcode.org/raw/'))) return message.channel.createMessage(`${this.client.stores.emojis.error} ***Invalid snippets URL***`); + + const tasks = urls.map((l) => axios({ method: 'GET', url: l })); + const response = await Promise.all(tasks); + const certAndPrivateKey: string[] = response.map((r) => r.data); + + if (!this.isValidCertificateChain(certAndPrivateKey[0])) return message.channel.createMessage(`${this.client.stores.emojis.error} ***Invalid Certificate Chain***`); + if (!this.isValidPrivateKey(certAndPrivateKey[1])) return message.channel.createMessage(`${this.client.stores.emojis.error} ***Invalid Private Key***`); + + certs = { cert: certAndPrivateKey[0], key: certAndPrivateKey[1] }; + } + + const domain = await this.createDomain(account, args[1], Number(args[2]), certs); + + const tasks = [message.delete(), this.client.util.exec('systemctl reload')]; + // @ts-ignore + await Promise.all(tasks); + + const embed = new RichEmbed() + .setTitle('Domain Creation') + .setColor(3066993) + .addField('Account Username', account.username, true) + .addField('Account ID', account.id, true) + .addField('Engineer', `<@${message.author.id}>`, true) + .addField('Domain', domain.domain, true) + .addField('Port', String(domain.port), true); + + const cert = await parseCertificate(this.client, domain.x509.cert); + + embed.addField('Certificate Issuer', cert.issuer.organizationName, true) + .addField('Certificate Subject', cert.subject.commonName, true) + .setFooter(this.client.user.username, this.client.user.avatarURL) + .setTimestamp(new Date(message.timestamp)); + + const completed = [ + edit.edit(`***${this.client.stores.emojis.success} Successfully binded ${domain.domain} to port ${domain.port} for ${account.userID}.***`), + this.client.createMessage('580950455581147146', { embed }), + this.client.getDMChannel(account.userID).then((r) => r.createMessage({ embed })), + this.client.util.transport.sendMail({ + to: account.emailAddress, + from: 'Library of Code sp-us | Support Team ', + subject: 'Your domain has been binded', + html: ` +

Library of Code sp-us | Cloud Services

+

Hello, this is an email informing you that a new domain under your account has been binded. + Information is below.

+ Domain: ${domain.domain}
+ Port: ${domain.port}
+ Certificate Issuer: ${cert.issuer.organizationName}
+ Certificate Subject: ${cert.subject.commonName}
+ Responsible Engineer: ${message.author.username}#${message.author.discriminator}

+ + If you have any questions about additional setup, you can reply to this email or send a message in #cloud-support in our Discord server.
+ + Library of Code sp-us | Support Team + `, + }), + ]; + + if (!domain.domain.includes('cloud.libraryofcode.org')) { + const content = `__**DNS Record Setup**__\nYou recently a binded a custom domain to your Library of Code sp-us Account. You'll have to update your DNS records. We've provided the records below.\n\n\`${domain.domain} IN CNAME cloud.libraryofcode.org AUTO/500\`\nThis basically means you need to make a CNAME record with the key/host of ${domain.domain} and the value/point to cloud.libraryofcode.org. If you have any questions, don't hesitate to ask us.`; + completed.push(this.client.getDMChannel(account.userID).then((r) => r.createMessage(content))); + } + + return Promise.all(completed); + } catch (err) { + await fs.unlink(`/etc/nginx/sites-available/${args[1]}`); + await fs.unlink(`/etc/nginx/sites-enabled/${args[1]}`); + await this.client.db.Domain.deleteMany({ domain: args[1] }); + return this.client.util.handleError(err, message, this); + } + } + + /** + * This function binds a domain to a port on the CWG. + * @param account The account of the user. + * @param subdomain The domain to use. `mydomain.cloud.libraryofcode.org` + * @param port The port to use, must be between 1024 and 65535. + * @param x509Certificate The contents the certificate and key files. + * @example await CWG.createDomain(account, 'mydomain.cloud.libraryofcode.org', 6781); + */ + public async createDomain(account: AccountInterface, domain: string, port: number, x509Certificate: { cert?: string, key?: string }) { + try { + if (port <= 1024 || port >= 65535) throw new RangeError(`Port range must be between 1024 and 65535, received ${port}.`); + if (await this.client.db.Domain.exists({ domain })) throw new Error(`Domain ${domain} already exists in the database.`); + if (!await this.client.db.Account.exists({ userID: account.userID })) throw new Error(`Cannot find account ${account.userID}.`); + let x509: { cert: string, key: string }; + if (x509Certificate) { + x509 = await this.createCertAndPrivateKey(domain, x509Certificate.cert, x509Certificate.key); + } + let cfg = await fs.readFile('/var/CloudServices/dist/static/nginx.conf', { encoding: 'utf8' }); + cfg = cfg.replace(/\[DOMAIN]/g, domain); + cfg = cfg.replace(/\[PORT]/g, String(port)); + cfg = cfg.replace(/\[CERTIFICATE]/g, x509.cert); + cfg = cfg.replace(/\[KEY]/g, x509.key); + await fs.writeFile(`/etc/nginx/sites-available/${domain}`, cfg, { encoding: 'utf8' }); + await fs.symlink(`/etc/nginx/sites-available/${domain}`, `/etc/nginx/sites-enabled/${domain}`); + const entry = new this.client.db.Domain({ + account, + domain, + port, + x509, + enabled: true, + }); + if (domain.includes('cloud.libraryofcode.org')) { + const dmn = domain.split('.'); + await axios({ + method: 'post', + url: 'https://api.cloudflare.com/client/v4/zones/5e82fc3111ed4fbf9f58caa34f7553a7/dns_records', + headers: { Authorization: `Bearer ${this.client.config.cloudflare}`, 'Content-Type': 'application/json' }, + data: JSON.stringify({ type: 'CNAME', name: `${dmn[0]}.${dmn[1]}`, content: 'cloud.libraryofcode.org', proxied: false }), + }); + } + return entry.save(); + } catch (error) { + await fs.unlink(`/etc/nginx/sites-enabled/${domain}`); + await fs.unlink(`/etc/nginx/sites-available/${domain}`); + await this.client.db.Domain.deleteMany({ domain }); + throw error; + } + } + + public async createCertAndPrivateKey(domain: string, certChain: string, privateKey: string) { + if (!this.isValidCertificateChain(certChain)) throw new Error('Invalid Certificate Chain'); + if (!this.isValidPrivateKey(privateKey)) throw new Error('Invalid Private Key'); + const path = `/var/CloudServices/temp/${domain}`; + const temp = [writeFile(`${path}.chain.crt`, certChain), writeFile(`${path}.key.pem`, privateKey)]; + const removeFiles = [unlink(`${path}.chain.crt`), unlink(`${path}.key.pem`)]; + await Promise.all(temp); + if (!this.isMatchingPair(`${path}.chain.crt`, `${path}.key.pem`)) { + await Promise.all(removeFiles); + throw new Error('Certificate and Private Key do not match'); + } + + const tasks = [writeFile(`/etc/nginx/ssl/${domain}.chain.crt`, certChain), writeFile(`/etc/nginx/ssl/${domain}.key.pem`, privateKey)]; + await Promise.all(tasks); + return { cert: `/etc/nginx/ssl/${domain}.chain.crt`, key: `/etc/nginx/ssl/${domain}.key.pem` }; + } + + public checkOccurance(text: string, query: string) { + return (text.match(new RegExp(query, 'g')) || []).length; + } + + public isValidCertificateChain(cert: string) { + if (!cert.replace(/^\s+|\s+$/g, '').startsWith('-----BEGIN CERTIFICATE-----')) return false; + if (!cert.replace(/^\s+|\s+$/g, '').endsWith('-----END CERTIFICATE-----')) return false; + if (this.checkOccurance(cert.replace(/^\s+|\s+$/g, ''), '-----BEGIN CERTIFICATE-----') !== 2) return false; + if (this.checkOccurance(cert.replace(/^\s+|\s+$/g, ''), '-----END CERTIFICATE-----') !== 2) return false; + return true; + } + + public isValidPrivateKey(key: string) { + if (!key.replace(/^\s+|\s+$/g, '').startsWith('-----BEGIN PRIVATE KEY-----')) return false; + if (!key.replace(/^\s+|\s+$/g, '').endsWith('-----END PRIVATE KEY-----')) return false; + if (this.checkOccurance(key.replace(/^\s+|\s+$/g, ''), '-----BEGIN PRIVATE KEY-----') !== 1) return false; + if (this.checkOccurance(key.replace(/^\s+|\s+$/g, ''), '-----END PRIVATE KEY-----') !== 1) return false; + return true; + } + + public async isMatchingPair(cert: string, privateKey: string) { + const result: string = await this.client.util.exec(`${__dirname}/../bin/checkCertSignatures ${cert} ${privateKey}`); + const { ok }: { ok: boolean } = JSON.parse(result); + return ok; + } +} diff --git a/types/eris.d.ts b/types/eris.d.ts new file mode 100644 index 0000000..e9a3c05 --- /dev/null +++ b/types/eris.d.ts @@ -0,0 +1,8 @@ +import { EmbedOptions } from 'eris'; +import RichEmbed from '../src/class/RichEmbed'; + +declare global { + namespace Eris { + type MessageContent = string | { content?: string; tts?: boolean; disableEveryone?: boolean; embed?: EmbedOptions | RichEmbed; flags?: number }; + } +}