import fs, { writeFile, unlink } from 'fs-extra'; import axios from 'axios'; import { randomBytes } from 'crypto'; import { Message, MessageEmbed, TextChannel } from 'discord.js'; import { AccountInterface } from '../models'; import { Client, Command } from '../class'; 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: ['662163685439045632', '701454780828221450'] }; 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]); if (!this.urlRegex.test(args[1])) return this.error(message.channel, 'Invalid URL supplied.'); if (Number(args[2]) <= 1024 || Number(args[2]) >= 65535) return this.error(message.channel, 'Port must be greater than 1024 and less than 65535.'); if (!args[1].endsWith('.cloud.libraryofcode.org') && !args[4]) return this.error(message.channel, '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 this.error(message.channel, 'Cannot locate account.'); if (await this.client.db.Domain.exists({ domain: args[1] })) return this.error(message.channel, '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 bound 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 this.error(message.channel, 'Bind request cancelled.'); } if (answer.content === 'n') return this.error(message.channel, 'Bind request cancelled.'); } const edit = await this.loading(message.channel, 'Binding domain...'); let certs: { cert?: string, key?: string } = {}; 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 this.error(message.channel, 'Invalid snippets URL. Make sure to use https://snippets.cloud.libraryofcode.org/raw/*.'); 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 this.error(message.channel, 'The certificate chain provided is invalid.'); if (!this.isValidPrivateKey(certAndPrivateKey[1])) return this.error(message.channel, 'The private key provided is invalid.'); certs = { cert: certAndPrivateKey[0], key: certAndPrivateKey[1] }; } else { certs.cert = await fs.readFile('/etc/ssl/private/cloud-libraryofcode-org.chain.crt', { encoding: 'utf8' }); certs.key = await fs.readFile('/etc/ssl/private/cloud-libraryofcode-org.key', { encoding: 'utf8' }); } const domain = await this.createDomain(account, args[1], Number(args[2]), certs); const tasks = [message.delete(), this.client.util.exec('systemctl reload nginx')]; // @ts-ignore await Promise.all(tasks); const embed = new MessageEmbed() .setTitle('Domain Creation') .setColor(3066993) .addField('Account Username', `${account.username} | <@${account.userId}>`, true) .addField('Account ID', account.id, true) .addField('Technician', message.author.toString(), true) .addField('Domain', domain.domain, true) .addField('Port', String(domain.port), true); const certPath = `/opt/CloudServices/temp/${randomBytes(5).toString('hex')}`; await writeFile(certPath, certs.cert, { encoding: 'utf8' }); const cert = await parseCertificate(this.client, certPath); 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.createdTimestamp)); const completed = [ edit.edit(`***${this.client.stores.emojis.success} Successfully bound ${domain.domain} to port ${domain.port} for ${account.username}.***`), (this.client.channels.cache.get('580950455581147146') as TextChannel).send({ embeds: [embed] }), this.client.users.fetch(account.userId).then((r) => r.send({ embeds: [embed] })), this.client.util.transport.sendMail({ to: account.emailAddress, from: 'Library of Code sp-us | Support Team ', subject: 'Your domain has been bound', html: `

Library of Code sp-us | Cloud Services

Hello, this is an email informing you that a new domain under your account has been bound. 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 bound 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.users.fetch(account.userId).then((r) => r.send(content))); } return Promise.all(completed); } catch (err) { this.client.util.handleError(err, message, this); const tasks = [fs.unlink(`/etc/nginx/sites-enabled/${args[1]}`), fs.unlink(`/etc/nginx/sites-available/${args[1]}`), this.client.db.Domain.deleteMany({ domain: args[1] })]; return Promise.allSettled(tasks); } } /** * 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); } else { x509 = { cert: '/etc/ssl/private/cloud-libraryofcode-org.chain.crt', key: '/etc/ssl/private/cloud-libraryofcode-org.key', }; } let cfg = await fs.readFile('/opt/CloudServices/src/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, }); return entry.save(); } catch (error) { const tasks = [fs.unlink(`/etc/nginx/sites-enabled/${domain}`), fs.unlink(`/etc/nginx/sites-available/${domain}`), this.client.db.Domain.deleteMany({ domain })]; await Promise.allSettled(tasks); 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 = `/opt/CloudServices/temp/${domain}`; await Promise.all([writeFile(`${path}.chain.crt`, certChain), writeFile(`${path}.key.pem`, privateKey)]); if (!this.isMatchingPair(`${path}.chain.crt`, `${path}.key.pem`)) { await Promise.all([unlink(`${path}.chain.crt`), unlink(`${path}.key.pem`)]); throw new Error('Certificate and Private Key do not match'); } await Promise.all([writeFile(`/etc/ssl/certs/cwg/${domain}.chain.crt`, certChain), writeFile(`/etc/ssl/private/cwg/${domain}.key.pem`, privateKey)]); return { cert: `/etc/ssl/certs/cwg/${domain}.chain.crt`, key: `/etc/ssl/private/cwg/${domain}.key.pem` }; } public checkOccurrence(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.checkOccurrence(cert.replace(/^\s+|\s+$/g, ''), '-----BEGIN CERTIFICATE-----') !== 2) return false; if (this.checkOccurrence(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-----') && !key.replace(/^\s+|\s+$/g, '').startsWith('-----BEGIN RSA PRIVATE KEY-----') && !key.replace(/^\s+|\s+$/g, '').startsWith('-----BEGIN ECC PRIVATE KEY-----')) return false; if (!key.replace(/^\s+|\s+$/g, '').endsWith('-----END PRIVATE KEY-----') && !key.replace(/^\s+|\s+$/g, '').endsWith('-----END RSA PRIVATE KEY-----') && !key.replace(/^\s+|\s+$/g, '').endsWith('-----END ECC PRIVATE KEY-----')) return false; if ((this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----BEGIN PRIVATE KEY-----') !== 1) && (this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----BEGIN RSA PRIVATE KEY-----') !== 1) && (this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----BEGIN ECC PRIVATE KEY-----') !== 1)) return false; if ((this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----END PRIVATE KEY-----') !== 1) && (this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----END RSA PRIVATE KEY-----') !== 1) && (this.checkOccurrence(key.replace(/^\s+|\s+$/g, ''), '-----END ECC 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; } }