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}
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 }
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}[]
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},
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: {

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> {
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) => {
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);
});
}

View File

@ -1,20 +1,23 @@
import fs from 'fs-extra';
import fs, { writeFile, unlink } 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 '..';
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] <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.aliases = ['bind'];
this.enabled = true;
this.urlRegex = /^[a-zA-Z0-9\-._~:/?#[\]@!$&'()*+,;=]+$/;
}
public async run(message: Message, args: string[]) {
@ -27,69 +30,101 @@ export default class CWG_Create extends Command {
*/
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...***`);
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 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 (!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]) })) {
// 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);
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***`);
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 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 <help@libraryofcode.org>',
subject: 'Your domain has been binded',
html: `
<h1>Library of Code sp-us | Cloud Services</h1>
<p>Hello, this is an email informing you that a new domain under your account has been binded.
Information is below.</p>
<b>Domain:</b> ${domain.domain}<br>
<b>Port:</b> ${domain.port}<br>
<b>Certificate Issuer:</b> ${cert.issuer.organizationName}<br>
<b>Certificate Subject:</b> ${cert.subject.commonName}<br>
<b>Responsible Engineer:</b> ${message.author.username}#${message.author.discriminator}<br><br>
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.<br>
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 <help@libraryofcode.org>',
subject: 'Your domain has been binded',
html: `
<h1>Library of Code sp-us | Cloud Services</h1>
<p>Hello, this is an email informing you that a new domain under your account has been binded.
Information is below.</p>
<b>Domain:</b> ${domain.domain}<br>
<b>Port:</b> ${domain.port}<br>
<b>Certificate Issuer:</b> ${cert.issuer.organizationName}<br>
<b>Certificate Subject:</b> ${cert.subject.commonName}<br>
<b>Responsible Engineer:</b> ${message.author.username}#${message.author.discriminator}<br><br>
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.<br>
<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')) {
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) {
await fs.unlink(`/etc/nginx/sites-available/${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 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);
* @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 } = { 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 {
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 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, x509Certificate.cert);
cfg = cfg.replace(/\[KEY]/g, x509Certificate.key);
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: x509Certificate,
x509,
enabled: true,
});
if (domain.includes('cloud.libraryofcode.org')) {
@ -144,4 +181,47 @@ export default class CWG_Create extends Command {
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 };
}
}