Rework command

merge-requests/4/head
Bsian 2020-03-13 21:49:51 +00:00
parent f25b118eff
commit 87fd47adce
No known key found for this signature in database
GPG Key ID: 097FB9A291026091
4 changed files with 669 additions and 576 deletions

View File

@ -15,23 +15,23 @@ export default class RichEmbed {
footer?: { text: string, icon_url?: string, proxy_icon_url?: string} footer?: { text: string, icon_url?: string, proxy_icon_url?: string}
image?: { url?: string, proxy_url?: string, height?: number, width?: number } image?: { url: string, proxy_url?: string, height?: number, width?: number }
thumbnail?: { 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 } video?: { url: string, height?: number, width?: number }
provider?: { name?: string, url?: string} provider?: { name: string, url?: string}
author?: { name?: string, url?: string, proxy_icon_url?: string, icon_url?: string} author?: { name: string, url?: string, proxy_icon_url?: string, icon_url?: string}
fields?: {name: string, value: string, inline?: boolean}[] fields?: {name: string, value: string, inline?: boolean}[]
constructor(data: { constructor(data: {
title?: string, type?: string, description?: string, url?: string, timestamp?: Date, color?: number, fields?: {name: string, value: string, inline?: boolean}[] 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 }, 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 }, 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}, provider?: { name: string, url?: string}, author?: { name: string, url?: string, proxy_icon_url?: string, icon_url?: string},
} = {}) { } = {}) {
/* /*
let types: { let types: {

View File

@ -171,12 +171,17 @@ export default class Util {
public async messageCollector(message: Message, question: string, timeout: number, shouldDelete = false, choices: string[] = null, filter = (msg: Message): boolean|void => {}): Promise<Message> { public async messageCollector(message: Message, question: string, timeout: number, shouldDelete = false, choices: string[] = null, filter = (msg: Message): boolean|void => {}): Promise<Message> {
const msg = await message.channel.createMessage(question); const msg = await message.channel.createMessage(question);
return new Promise((res, rej) => { return new Promise((res, rej) => {
setTimeout(() => { if (shouldDelete) msg.delete().catch(); rej(new Error('Did not supply a valid input in time')); }, timeout); const func = (Msg: Message) => {
this.client.on('messageCreate', (Msg) => {
if (filter(Msg) === false) return; if (filter(Msg) === false) return;
const verif = choices ? choices.includes(Msg.content) : Msg.content; const verif = choices ? choices.includes(Msg.content) : Msg.content;
if (verif) { if (shouldDelete) msg.delete().catch(); res(Msg); } 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);
}); });
} }

View File

@ -1,20 +1,23 @@
import fs from 'fs-extra'; import fs, { writeFile, unlink } from 'fs-extra';
import axios from 'axios'; import axios from 'axios';
import x509 from '@ghaiklor/x509';
import { Message } from 'eris'; import { Message } from 'eris';
import { AccountInterface } from '../models'; import { AccountInterface } from '../models';
import { Command, RichEmbed } from '../class'; import { Command, RichEmbed } from '../class';
import { Client } from '..'; import { Client } from '..';
import { parseCertificate } from '../functions';
export default class CWG_Create extends Command { export default class CWG_Create extends Command {
public urlRegex: RegExp;
constructor(client: Client) { constructor(client: Client) {
super(client); super(client);
this.name = 'create'; this.name = 'create';
this.description = 'Bind a domain to the CWG'; this.description = 'Bind a domain to the CWG';
this.usage = `${this.client.config.prefix}cwg create [User ID | Username] [Domain] [Port] <Path to x509 cert> <Path to x509 key>`; this.usage = `${this.client.config.prefix}cwg create [User ID | Username] [Domain] [Port] <Cert Chain> <Private Key> || Use snippets raw URL`;
this.permissions = { roles: ['525441307037007902'] }; this.permissions = { roles: ['525441307037007902'] };
this.aliases = ['bind']; this.aliases = ['bind'];
this.enabled = true; this.enabled = true;
this.urlRegex = /^[a-zA-Z0-9\-._~:/?#[\]@!$&'()*+,;=]+$/;
} }
public async run(message: Message, args: string[]) { public async run(message: Message, args: string[]) {
@ -27,46 +30,75 @@ export default class CWG_Create extends Command {
*/ */
try { try {
if (!args[2]) return this.client.commands.get('help').run(message, ['cwg', this.name]); 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...***`);
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] }] }); 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 (!account) return message.channel.createMessage(`${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 message.channel.createMessage(`${this.client.stores.emojis.error} ***This domain already exists***`);
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]) })) { 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; let answer: Message;
try { try {
answer = await this.client.util.messageCollector(message, answer = await this.client.util.messageCollector(
`***${this.client.stores.emojis.error} This port is already binded to a domain. Do you wish to continue? (y/n)***`, message,
30000, true, ['y', 'n'], (msg) => msg.author.id === message.author.id && msg.channel.id === message.channel.id); `***${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) { } catch (error) {
return edit.edit(`***${this.client.stores.emojis.error} Bind request cancelled***`); return message.channel.createMessage(`${this.client.stores.emojis.error} ***Bind request cancelled***`);
} }
if (answer.content === 'n') return edit.edit(`***${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 domain = await this.createDomain(account, args[1], Number(args[2]), certs);
const embed = new RichEmbed();
embed.setTitle('Domain Creation'); const tasks = [message.delete(), this.client.util.exec('systemctl reload')];
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 // @ts-ignore
this.client.createMessage('580950455581147146', { embed }); await Promise.all(tasks);
// @ts-ignore
this.client.getDMChannel(account.userID).then((r) => r.createMessage({ embed })); const embed = new RichEmbed()
await this.client.util.transport.sendMail({ .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, to: account.emailAddress,
from: 'Library of Code sp-us | Support Team <help@libraryofcode.org>', from: 'Library of Code sp-us | Support Team <help@libraryofcode.org>',
subject: 'Your domain has been binded', subject: 'Your domain has been binded',
@ -84,12 +116,15 @@ export default class CWG_Create extends Command {
<b><i>Library of Code sp-us | Support Team</i></b> <b><i>Library of Code sp-us | Support Team</i></b>
`, `,
}); }),
];
if (!domain.domain.includes('cloud.libraryofcode.org')) { 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.`; 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)); completed.push(this.client.getDMChannel(account.userID).then((r) => r.createMessage(content)));
} }
return domain;
return Promise.all(completed);
} catch (err) { } catch (err) {
await fs.unlink(`/etc/nginx/sites-available/${args[1]}`); await fs.unlink(`/etc/nginx/sites-available/${args[1]}`);
await fs.unlink(`/etc/nginx/sites-enabled/${args[1]}`); await fs.unlink(`/etc/nginx/sites-enabled/${args[1]}`);
@ -103,28 +138,30 @@ export default class CWG_Create extends Command {
* @param account The account of the user. * @param account The account of the user.
* @param subdomain The domain to use. `mydomain.cloud.libraryofcode.org` * @param subdomain The domain to use. `mydomain.cloud.libraryofcode.org`
* @param port The port to use, must be between 1024 and 65535. * @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. * @param x509Certificate The contents the certificate and key files.
* @example await CWG.createDomain('mydomain.cloud.libraryofcode.org', 6781); * @example await CWG.createDomain(account, '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' }) { public async createDomain(account: AccountInterface, domain: string, port: number, x509Certificate: { cert?: string, key?: string }) {
try { try {
if (port <= 1024 || port >= 65535) throw new RangeError(`Port range must be between 1024 and 65535, received ${port}.`); 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.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}.`); 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); let x509: { cert: string, key: string };
await fs.access(x509Certificate.key, fs.constants.R_OK); if (x509Certificate) {
x509 = await this.createCertAndPrivateKey(domain, x509Certificate.cert, x509Certificate.key);
}
let cfg = await fs.readFile('/var/CloudServices/dist/static/nginx.conf', { encoding: 'utf8' }); let cfg = await fs.readFile('/var/CloudServices/dist/static/nginx.conf', { encoding: 'utf8' });
cfg = cfg.replace(/\[DOMAIN]/g, domain); cfg = cfg.replace(/\[DOMAIN]/g, domain);
cfg = cfg.replace(/\[PORT]/g, String(port)); cfg = cfg.replace(/\[PORT]/g, String(port));
cfg = cfg.replace(/\[CERTIFICATE]/g, x509Certificate.cert); cfg = cfg.replace(/\[CERTIFICATE]/g, x509.cert);
cfg = cfg.replace(/\[KEY]/g, x509Certificate.key); cfg = cfg.replace(/\[KEY]/g, x509.key);
await fs.writeFile(`/etc/nginx/sites-available/${domain}`, cfg, { encoding: 'utf8' }); await fs.writeFile(`/etc/nginx/sites-available/${domain}`, cfg, { encoding: 'utf8' });
await fs.symlink(`/etc/nginx/sites-available/${domain}`, `/etc/nginx/sites-enabled/${domain}`); await fs.symlink(`/etc/nginx/sites-available/${domain}`, `/etc/nginx/sites-enabled/${domain}`);
const entry = new this.client.db.Domain({ const entry = new this.client.db.Domain({
account, account,
domain, domain,
port, port,
x509: x509Certificate, x509,
enabled: true, enabled: true,
}); });
if (domain.includes('cloud.libraryofcode.org')) { if (domain.includes('cloud.libraryofcode.org')) {
@ -144,4 +181,47 @@ export default class CWG_Create extends Command {
throw error; 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;
}
} }

8
types/eris.d.ts vendored Normal file
View File

@ -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 };
}
}