Skip to content

Commit

Permalink
🔐 Encrypt bot Token
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashu11-A committed May 29, 2024
1 parent f776b84 commit c897c42
Show file tree
Hide file tree
Showing 7 changed files with 22 additions and 36 deletions.
14 changes: 0 additions & 14 deletions core/package-lock.json

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

1 change: 0 additions & 1 deletion core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
"cron": "^3.1.7",
"crypto-js": "^4.2.0",
"discord.js": "^14.15.2",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"glob": "^10.3.15",
"isbinaryfile": "^5.0.2",
Expand Down
6 changes: 1 addition & 5 deletions core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { join } from 'path'
import { argv, cwd } from 'process'
import prompts from 'prompts'
import 'reflect-metadata'
import { env, PKG_MODE } from '.'
import { PKG_MODE } from '.'
import { Plugins } from './controller/plugins'
import { SocketController } from './controller/socket'
import { Auth } from '@/controller/auth'
Expand All @@ -31,10 +31,6 @@ const argsList: Args[] = [
await auth.login()
await auth.validator()

if (env?.BOT_TOKEN === undefined || env?.BOT_TOKEN === 'Troque-me') {
await writeFile(join(process.cwd(), '.env'), 'BOT_TOKEN=Troque-me', { encoding: 'utf-8' })
throw new Error('Defina um token!')
}
if (existsSync(join(cwd(), 'entries'))) await rm(join(cwd(), 'entries'), { recursive: true })

const port = PKG_MODE ? String(await generatePort()) : '3000'
Expand Down
27 changes: 17 additions & 10 deletions core/src/controller/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Blowfish, enc } from 'crypto-js'
import { AES, enc } from 'crypto-js'
import { readFile, rm, writeFile } from 'fs/promises'
import { RootPATH } from '..'
import { api, key } from '../../package.json'
Expand All @@ -9,6 +9,7 @@ import { existsSync } from 'fs'
type Credentials = {
email: string
password: string
uuid: string
token: string
}

Expand Down Expand Up @@ -36,6 +37,7 @@ interface AuthData {
interface BotInfo {
uuid: string;
name: string;
token: string
enabled: boolean;
expired: boolean;
expire_at: string;
Expand All @@ -50,9 +52,10 @@ export class Auth {

async askCredentials ({ question }: { question?: (keyof Credentials)[] }): Promise<Credentials> {
const questions: PromptObject<string>[] = [
{ name: 'email', message: 'Email', type: 'text', warn: 'Apenas cadastrado em paymentbot.com' },
{ name: 'password', message: 'Senha', type: 'password', warn: 'Apenas cadastrado em paymentbot.com' },
{ name: 'token', message: 'Token', type: 'password', warn: 'Visível no Dashboard' }
{ name: 'email', message: 'Email', type: 'text', warn: 'Apenas cadastrado em https://paymentbot.com' },
{ name: 'password', message: 'Senha', type: 'password', warn: 'Apenas cadastrado em https://paymentbot.com' },
{ name: 'uuid', message: 'UUID', type: 'text', warn: 'Visível no Dashboard (https://paymentbot.com)' },
{ name: 'token', message: 'Token', type: 'password', warn: 'Token Do seu Bot https://discord.com/developers/applications' }
]

const filter = questions.filter((propmt) => question === undefined || question?.includes(propmt.name as keyof Credentials))
Expand All @@ -69,18 +72,18 @@ export class Auth {
...credentials
}

await writeFile(`${RootPATH}/.key`, Blowfish.encrypt(JSON.stringify(credentials), key).toString())
await writeFile(`${RootPATH}/.key`, AES.encrypt(JSON.stringify(credentials), key).toString())
}

async decryptCredentials(): Promise<Credentials> {
const encrypted = existsSync(`${RootPATH}/.key`) ? Blowfish.decrypt(await readFile(`${RootPATH}/.key`, { encoding: 'utf-8' }), key).toString(enc.Utf8) : '{}'
const encrypted = existsSync(`${RootPATH}/.key`) ? AES.decrypt(await readFile(`${RootPATH}/.key`, { encoding: 'utf-8' }), key).toString(enc.Utf8) : '{}'
return JSON.parse(encrypted)
}


async initialize() {
const credentials = await this.decryptCredentials()
const keys = ['email', 'password', 'token']
const keys = ['email', 'password', 'uuid', 'token']
let hasError = false

for (const key of keys) {
Expand Down Expand Up @@ -154,7 +157,7 @@ export class Auth {
await this.initialize()
}

const response = await fetch(`${api}/bots/${this.credentials?.token}`, {
const response = await fetch(`${api}/bots/${this.credentials?.uuid}`, {
headers: {
Authorization: `Bearer ${Auth.accessToken.token}`
}
Expand All @@ -181,7 +184,7 @@ export class Auth {

switch (conclusion.Error) {
case 'change': {
await this.askCredentials({ question: ['token'] })
await this.askCredentials({ question: ['uuid'] })
await this.initialize()
await this.login()
await this.validator()
Expand Down Expand Up @@ -213,8 +216,12 @@ export class Auth {
}

if (Auth.bot === undefined) this.startCron()
const bot = await this.decryptCredentials()

Auth.bot = data
Auth.bot = {
...data,
token: bot.token
}
}

startCron (): void {
Expand Down
4 changes: 2 additions & 2 deletions core/src/controller/events.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { type Socket } from 'socket.io'
import { env } from '..'
import { Database } from './database'
import { Plugins } from './plugins'
import { Command } from '@/discord/Commands'
import { Config } from './config'
import { Discord } from '@/discord/Client'
import { Auth } from './auth'

interface EventOptions {
client: Socket
Expand Down Expand Up @@ -36,7 +36,7 @@ export class Event {
}

async connected () {
this.client.emit('discord', env?.BOT_TOKEN)
this.client.emit('discord', Auth.bot?.token)
}

async disconnect () {
Expand Down
4 changes: 2 additions & 2 deletions core/src/discord/Client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type BitFieldResolvable, Client, type GatewayIntentsString, IntentsBitField, Partials, ApplicationCommandType, ChatInputCommandInteraction, CommandInteraction, MessageContextMenuCommandInteraction, UserContextMenuCommandInteraction, PermissionsBitField } from 'discord.js'
import { env } from '..'
import { Command } from './Commands'
import { Config } from '@/controller/config'
import { Auth } from '@/controller/auth'

export class Discord {
public static client: Client<boolean>
Expand Down Expand Up @@ -49,7 +49,7 @@ export class Discord {

console.log('📌 Iniciando Discord...')

await Discord.client.login(env?.BOT_TOKEN)
await Discord.client.login(Auth.bot?.token)
Discord.client.prependOnceListener('ready', async (client) => {
await new Discord().register()
console.info(`📡 Connected with ${client.user.username}`)
Expand Down
2 changes: 0 additions & 2 deletions core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import dotenv from 'dotenv'
import { existsSync } from 'fs'
import { readFile } from 'fs/promises'
import path, { resolve } from 'path'
Expand All @@ -9,4 +8,3 @@ const dev = existsSync(developmentEnvPath)
export const PKG_MODE = `${process.cwd()}/src` !== __dirname
export const RootPATH: string = PKG_MODE ? path.join(process.cwd()) : path.join(__dirname, '..')
export const metadata = async () => JSON.parse(await readFile(path.join(__dirname, '..', 'package.json'), { encoding: 'utf-8' }))
export const { parsed: env } = dotenv.config({ path: dev ? developmentEnvPath : resolve(process.cwd(), '.env') })

0 comments on commit c897c42

Please sign in to comment.