LUISGDUV commited on
Commit
50df368
·
verified ·
1 Parent(s): f504979

Create server.js

Browse files
Files changed (1) hide show
  1. server.js +206 -0
server.js ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const cors = require('cors');
3
+ const axios = require('axios');
4
+
5
+ const app = express();
6
+ app.use(cors());
7
+ app.use(express.json());
8
+
9
+ // =========================================================
10
+ // CREDENCIAIS OFICIAIS (LUISGDUV) - BANCO DE DADOS GITHUB
11
+ // =========================================================
12
+ const GITHUB_TOKEN = "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";
13
+ const REPO_OWNER = "LUISGDUV";
14
+ const REPO_NAME = "protix-host";
15
+ const FILE_PATH = "sissy/api/database.json";
16
+ const GITHUB_API_URL = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/contents/${FILE_PATH}`;
17
+
18
+ let comandosPendentes = {};
19
+
20
+ async function lerBancoGitHub() {
21
+ try {
22
+ const res = await axios.get(GITHUB_API_URL, {
23
+ headers: {
24
+ 'Authorization': `token ${GITHUB_TOKEN}`,
25
+ 'Accept': 'application/vnd.github.v3+json',
26
+ 'User-Agent': 'ProtixHost-App'
27
+ }
28
+ });
29
+ const jsonString = Buffer.from(res.data.content, 'base64').toString('utf-8');
30
+ return { dados: JSON.parse(jsonString), sha: res.data.sha };
31
+ } catch (err) {
32
+ console.error("❌ [ERRO CRÍTICO GITHUB]: Falha ao acessar repositório.");
33
+ throw err;
34
+ }
35
+ }
36
+
37
+ async function salvarBancoGitHub(dados, sha) {
38
+ try {
39
+ const jsonString = JSON.stringify(dados, null, 4);
40
+ const contentBase64 = Buffer.from(jsonString).toString('base64');
41
+ await axios.put(GITHUB_API_URL, {
42
+ message: "📦 ProtixHost Database Auto-Sync (Cluster Node Update)",
43
+ content: contentBase64,
44
+ sha: sha
45
+ }, {
46
+ headers: {
47
+ 'Authorization': `token ${GITHUB_TOKEN}`,
48
+ 'Accept': 'application/vnd.github.v3+json',
49
+ 'User-Agent': 'ProtixHost-App'
50
+ }
51
+ });
52
+ return true;
53
+ } catch (err) {
54
+ console.error("❌ [ERRO AO SALVAR]:", err.message);
55
+ return false;
56
+ }
57
+ }
58
+
59
+ // LOGIN COM AUTO-REGISTRO PADRÃO SECURITY
60
+ app.post('/api/login', async (req, res) => {
61
+ const { username, password } = req.body;
62
+ try {
63
+ const { dados, sha } = await lerBancoGitHub();
64
+ if (!dados || !dados.users) return res.status(500).json({ success: false, error: "Estrutura corrompida no JSON." });
65
+
66
+ let user = dados.users.find(u => u.username.toLowerCase() === username.toLowerCase());
67
+
68
+ // 🚀 SE O USUÁRIO NÃO EXISTIR, CRIA ELE AUTOMATICAMENTE COM TOKEN SECURITY + HASH
69
+ if (!user) {
70
+ const hashUsuario = Math.random().toString(36).substring(2, 10);
71
+ const limpoUsername = username.trim().replace(/\s+/g, '');
72
+ const novoUsuario = {
73
+ username: username,
74
+ password: password,
75
+ botToken: `ProtixHost_Security_${limpoUsername}_${hashUsuario}`,
76
+ bots: []
77
+ };
78
+ dados.users.push(novoUsuario);
79
+ await salvarBancoGitHub(dados, sha);
80
+ console.log(`✅ Novo usuário [${username}] criado com token Security!`);
81
+ return res.json({ success: true, data: novoUsuario });
82
+ }
83
+
84
+ // Se o usuário existe mas a senha tá errada
85
+ if (user.password !== password) {
86
+ return res.status(401).json({ success: false, error: "Credenciais incorretas." });
87
+ }
88
+
89
+ if (!user.bots) { user.bots = []; await salvarBancoGitHub(dados, sha); }
90
+ res.json({ success: true, data: user });
91
+ } catch (err) { res.status(500).json({ success: false, error: "Erro de conexão com o banco de dados." }); }
92
+ });
93
+
94
+ // CRIAR BOT PADRÃO SECURITY
95
+ app.post('/api/bot/create', async (req, res) => {
96
+ const { token, botName } = req.body;
97
+ try {
98
+ const { dados, sha } = await lerBancoGitHub();
99
+ let user = dados.users.find(u => u.botToken === token || (u.bots && u.bots.some(b => b.botToken === token)));
100
+ if (!user) return res.status(403).json({ success: false, error: "Token inválido." });
101
+ if (user.bots.length >= 50) return res.status(400).json({ success: false, error: "Limite de 50 bots atingido." });
102
+
103
+ const hashAleatorio = Math.random().toString(36).substring(2, 10);
104
+ const limpoBotName = botName.trim().replace(/\s+/g, '');
105
+ // Alinhado exatamente com o padrão ProtixHost_Security_Nome_hash
106
+ const novoTokenExclusivo = `ProtixHost_Security_${limpoBotName}_${hashAleatorio}`;
107
+
108
+ const novoBotInstance = {
109
+ id: Date.now() + Math.floor(Math.random() * 1000),
110
+ nome: botName.trim().substring(0, 16),
111
+ botToken: novoTokenExclusivo,
112
+ inventory: []
113
+ };
114
+
115
+ user.bots.push(novoBotInstance);
116
+ await salvarBancoGitHub(dados, sha);
117
+ res.json({ success: true, data: novoBotInstance });
118
+ } catch (e) { res.status(500).json({ success: false }); }
119
+ });
120
+
121
+ // RENOMEAR BOT
122
+ app.post('/api/bot/rename', async (req, res) => {
123
+ const { token, newName } = req.body;
124
+ try {
125
+ const { dados, sha } = await lerBancoGitHub();
126
+ let botEncontrado = null;
127
+
128
+ for (let user of dados.users) {
129
+ if (user.bots) {
130
+ botEncontrado = user.bots.find(b => b.botToken === token);
131
+ if (botEncontrado) { botEncontrado.nome = newName.trim().substring(0, 16); break; }
132
+ }
133
+ }
134
+ if (!botEncontrado) return res.status(404).json({ success: false, error: "Bot não localizado." });
135
+
136
+ await salvarBancoGitHub(dados, sha);
137
+ res.json({ success: true, newName: botEncontrado.nome });
138
+ } catch (e) { res.status(500).json({ success: false }); }
139
+ });
140
+
141
+ // DELETAR BOT
142
+ app.post('/api/bot/delete', async (req, res) => {
143
+ const { token } = req.body;
144
+ try {
145
+ const { dados, sha } = await lerBancoGitHub();
146
+ let deletado = false;
147
+
148
+ for (let user of dados.users) {
149
+ if (user.bots) {
150
+ const index = user.bots.findIndex(b => b.botToken === token);
151
+ if (index !== -1) {
152
+ user.bots.splice(index, 1);
153
+ deletado = true;
154
+ break;
155
+ }
156
+ }
157
+ }
158
+ if (!deletado) return res.status(404).json({ success: false, error: "Bot não encontrado." });
159
+
160
+ await salvarBancoGitHub(dados, sha);
161
+ if (comandosPendentes[token]) delete comandosPendentes[token];
162
+ res.json({ success: true });
163
+ } catch (e) { res.status(500).json({ success: false }); }
164
+ });
165
+
166
+ // AÇÕES E SINCRONIZAÇÃO
167
+ app.post('/api/bot/action', (req, res) => {
168
+ const { token, action, direction, targetPlayer, item, amount } = req.body;
169
+ if(!token) return res.status(400).json({ success: false });
170
+ comandosPendentes[token] = { action, direction, targetPlayer, item, amount };
171
+ res.json({ success: true });
172
+ });
173
+
174
+ app.get('/api/bot/sync', async (req, res) => {
175
+ const { token } = req.query;
176
+ if (!token) return res.status(400).json({ success: false });
177
+ try {
178
+ const { dados } = await lerBancoGitHub();
179
+ let botEncontrado = null;
180
+ for (let user of dados.users) {
181
+ if (user.bots) { botEncontrado = user.bots.find(b => b.botToken === token); if (botEncontrado) break; }
182
+ }
183
+ if (!botEncontrado) return res.status(404).json({ success: false });
184
+ const comandoParaExecutar = comandosPendentes[token] || null;
185
+ if (comandoParaExecutar) delete comandosPendentes[token];
186
+ res.json({ success: true, botName: botEncontrado.nome, inventory: botEncontrado.inventory || [], comandoPendente: comandoParaExecutar });
187
+ } catch (err) { res.status(500).json({ success: false }); }
188
+ });
189
+
190
+ app.post('/api/bot/update_inventory', async (req, res) => {
191
+ const { token, inventory } = req.body;
192
+ try {
193
+ const { dados, sha } = await lerBancoGitHub();
194
+ let botAlvo = null;
195
+ for (let user of dados.users) {
196
+ if (user.bots) { botAlvo = user.bots.find(b => b.botToken === token); if (botAlvo) break; }
197
+ }
198
+ if (!botAlvo) return res.status(404).json({ success: false });
199
+ botAlvo.inventory = inventory;
200
+ await salvarBancoGitHub(dados, sha);
201
+ res.json({ success: true });
202
+ } catch (err) { res.status(500).json({ success: false }); }
203
+ });
204
+
205
+ const PORT = process.env.PORT || 10000;
206
+ app.listen(PORT, () => { console.log(`🚀 ProtixHost rodando na porta ${PORT}`); });