Skip to content

Commit

Permalink
🔄 Change Discord token sending method
Browse files Browse the repository at this point in the history
🔐 Crypt Token in PKG_MODE
🤏 Some corrections to the core plugin system
  • Loading branch information
Ashu11-A committed Jun 18, 2024
1 parent a312a3d commit fec052c
Show file tree
Hide file tree
Showing 21 changed files with 296 additions and 81 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ release
*.key
*.hash
*.license
*.pem
24 changes: 21 additions & 3 deletions core/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
},
"dependencies": {
"@types/cron": "^2.4.0",
"@types/node-forge": "^1.3.11",
"argon2": "^0.40.3",
"check-password-strength": "^2.0.10",
"chokidar": "^3.6.0",
Expand All @@ -54,6 +55,7 @@
"marked": "^12.0.2",
"marked-terminal": "^7.0.0",
"mysql2": "^3.10.0",
"node-forge": "^1.3.1",
"prompts": "^2.4.2",
"reflect-metadata": "^0.2.2",
"signale": "^1.4.0",
Expand Down
4 changes: 2 additions & 2 deletions core/src/controller/config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ApplicationCommandSubCommandData } from "discord.js";

export interface ConfigOptions extends ApplicationCommandSubCommandData {
name: string
pluginId: string
name: string
pluginId: string
}

export class Config {
Expand Down
29 changes: 27 additions & 2 deletions core/src/controller/crypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ import { randomBytes } from 'crypto';
import CryptoJS from 'crypto-js';
import { readFile, rm, writeFile } from "fs/promises";
import prompts from "prompts";
import forge from 'node-forge'

export const credentials = new Map<string, string | object | boolean | number>()

export class Crypt {
constructor() {}

async checker () {
if (!(await exists(`${RootPATH}/.key`)) && process.env?.Token === undefined) await this.create()
if (!(await exists(`${RootPATH}/privateKey.pem`)) || !(await exists(`${RootPATH}/publicKey.pem`))) await this.genKeys()

for (const path of ['.key', '.hash']) {
const wather = watch(path, { cwd: RootPATH })
Expand All @@ -28,6 +28,31 @@ export class Crypt {
}
}

async genKeys () {
const { privateKey, publicKey } = forge.pki.rsa.generateKeyPair(4096)

await writeFile('privateKey.pem', forge.pki.privateKeyToPem(privateKey))
await writeFile('publicKey.pem', forge.pki.publicKeyToPem(publicKey))
}

async privateKey () {
if (!(await exists(`${RootPATH}/privateKey.pem`))) throw new Error('PrivateKey não existe!')
return forge.pki.privateKeyFromPem(await readFile(`${RootPATH}/privateKey.pem`, { encoding: 'utf8' }))
}

async publicKey () {
if (!await (exists(`${RootPATH}/privateKey.pem`))) throw new Error('PublicKey não existe!')
return forge.pki.publicKeyFromPem(await readFile(`${RootPATH}/publicKey.pem`, { encoding: 'utf8' }))
}

async encript (data: string) {
return (await this.publicKey()).encrypt(data, 'RSA-OAEP')
}

async decrypt (data: string) {
return (await this.privateKey()).decrypt(data, 'RSA-OAEP')
}

async create () {
const select = await prompts({
name: 'type',
Expand Down
17 changes: 9 additions & 8 deletions core/src/controller/events.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Command } from '@/discord/Commands.js'
import { PKG_MODE } from '@/index.js'
import { type Socket } from 'socket.io'
import { Config } from './config.js'
import { credentials } from './crypt.js'
import { credentials, Crypt } from './crypt.js'
import { Database } from './database.js'
import { Plugins } from './plugins.js'

Expand Down Expand Up @@ -32,14 +33,14 @@ export class Event {
await Plugins.events(this.client, eventName, args)
})
this.client.on('disconnect', async () => { await this.disconnect() })
}
this.client.on('send_me_the_Discord_token_please', async () => {
const token = credentials.get('token')

if (token === undefined || typeof token !== 'string') throw new Error('Token do Discord está vazio!')

connected () {
const token = credentials.get('token')
console.log(token)
if (token === undefined || typeof token !== 'string') throw new Error('Token do Discord está vazio!')
console.log(`⚠️ Token sendo enviado para: ${this.client.id}`)
this.client.emit('discord', token)
console.log(`⚠️ Token${PKG_MODE ? ' criptografado' : ''} sendo enviado para: ${this.client.id}`)
this.client.emit('discord', PKG_MODE ? (await new Crypt().encript(token)) : token)
})
}

async disconnect () {
Expand Down
82 changes: 51 additions & 31 deletions core/src/controller/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { fileURLToPath } from 'url'
import { createVerify } from 'crypto'

const __dirname = dirname(fileURLToPath(import.meta.url))
const cacheWatcher = new Map<string, boolean>()
interface Metadata {
name: string
version: string
Expand All @@ -27,14 +28,14 @@ interface Metadata {

interface Plugin {
metadata?: Metadata,
commands?: { name: string, description: string, dmPermission: boolean, type: number }[]
events?: { name: string }[]
components?: { customId: string, cache: string, type: string }[]
configs?: ConfigOptions[]
commands: { name: string, description: string, dmPermission: boolean, type: number }[]
events: { name: string }[]
components: { customId: string, cache: string, type: string }[]
configs: ConfigOptions[]
crons: string[]
// signature: string
// date: Date
// size: string
// crons: string[]
}

interface PluginsOptions {
Expand Down Expand Up @@ -96,6 +97,7 @@ export class Plugins {
child.on('exit', (code, signal) => {
if (code === 0) resolve(null)
Plugins.plugins = Plugins.plugins - 1
cacheWatcher.delete(filePath)
return reject(`O binário ${filePath} saiu com código de erro ${code} e sinal ${signal}`)
})

Expand All @@ -104,7 +106,17 @@ export class Plugins {
})

child.stdout.once('data', (message) => {
Plugins.running.push({ process: child, metadata: info as Metadata, entries: [], listen: false })
Plugins.running.push({
metadata: info,
process: child,
listen: false,
components: [],
commands: [],
entries: [],
configs: [],
events: [],
crons: []
})


return resolve(message)
Expand Down Expand Up @@ -152,6 +164,8 @@ export class Plugins {
const watcher = watch(this.path)

watcher.on('add', async (filePath) => {
if (!cacheWatcher.get(filePath)) cacheWatcher.set(filePath, true)
else return
// Isso é necessario para que os bytes do arquivo movido termine de serem processados pela maquina host
await new Promise<void>((resolve) => setInterval(resolve, 2000))
if (!(await isBinaryFile(filePath))) {
Expand Down Expand Up @@ -181,19 +195,16 @@ export class Plugins {
Plugins.running.splice(index, 1)
break
} else {
Plugins.running[index] = {
...Plugins.running[index],
...info,
listen: true
}
Plugins.running[index] = Object.assign(Plugins.running[index], info, { listen: true })
}
} else {
Plugins.running.push({
...info,
entries: [],
id: socket.id,
listen: true
})
Plugins.running.push(Object.assign(info,
{
entries: [],
id: socket.id,
listen: true
}
))
}

for (const pathFile of Plugins.running[index].entries) {
Expand All @@ -206,19 +217,19 @@ export class Plugins {
}

for (const command of ((info.commands ?? []) as Array<CommandData<boolean>>)) {
console.log(command.name, socket.id, )
Command.all.set(command.name, { ...command, pluginId: socket.id })
Command.all.set(command.name, Object.assign(command, { pluginId: socket.id }))
}

console.log(`
✅ Iniciando Plugin ${info.metadata?.name}...
🤖 Commands: ${info.commands?.length}
🧩 Components: ${info.components?.length}
🎉 Events: ${info.events?.length}
⚙️ Configs: ${info.configs?.length}
🤖 Commands: ${info.commands.length}
🧩 Components: ${info.components.length}
🎉 Events: ${info.events.length}
⚙️ Configs: ${info.configs.length}
🕑 Crons: ${info.crons.length}
`)

for (const config of (info?.configs ?? [])) new Config({ ...config, pluginId: socket.id })
for (const config of info.configs) new Config({ ...config, pluginId: socket.id })

if (Plugins.loaded === 0 && Plugins.plugins === 0) {
console.log('\n🚨 Modo de desenvolvimento\n')
Expand All @@ -239,23 +250,23 @@ export class Plugins {
}

if (Database.client === undefined) {
const client = new Database()
const database = new Database()
console.log('🗂️ Iniciando Banco de dados...')

await client.create({
await database.create({
type: 'mysql',
host: 'node.seventyhost.net',
port: 3306,
username: 'u1692_A71YtsRYy2',
password: 't2y9gseoHzo+mm!VX=bva9Gt',
database: 's1692_SeventyHost'
})
await client.start()
await database.start()
}

const client = new Discord()
if (Discord?.client === undefined) {
client.createClient()
if (Discord.client === undefined) {
client.create()
await client.start()
} else {
console.log('⚠️ Atenção: Plugin adicionado após o primeiro registro, talvez seja necessário expulsar o bot, e adicioná-lo novamente ao servidor!')
Expand All @@ -279,7 +290,6 @@ export class Plugins {
let match;
while ((match = regex.exec(code)) !== null) {
const content = match[1];
console.log(content)
if (content) {
const replacedPath = `"${join(__dirname, '../../')}node_modules/${content}"`;
const genRegex = new RegExp(`"${content}"`, 'g')
Expand All @@ -294,7 +304,17 @@ export class Plugins {
if (pluginIndex !== -1) {
Plugins.running[pluginIndex].entries.push(`${path}/${fileName}`)
} else {
Plugins.running.push({ id: socket.id, entries: [`${path}/${fileName}`], listen: false })
Plugins.running.push({
id: socket.id,
entries: [`${path}/${fileName}`],
listen: false,
metadata: undefined,
commands: [],
events: [],
components: [],
configs: [],
crons: []
})
}
socket.emit(`${fileName}_OK`)
break
Expand Down
6 changes: 1 addition & 5 deletions core/src/controller/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@ export class SocketController {
}

ready () {
SocketController.io.on('connection', async (client) => {
const event = new Event({ client })
event.connected()
event.controller()
})
SocketController.io.on('connection', async (client) => new Event({ client }).controller())
}
}
Loading

0 comments on commit fec052c

Please sign in to comment.