-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
363 lines (304 loc) · 10.1 KB
/
Copy pathserver.js
File metadata and controls
363 lines (304 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import express from 'express';
import cors from 'cors';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import fs from 'fs/promises';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const PORT = process.env.PORT || 5000;
const JWT_SECRET = 'magic-guard-secret-key';
app.use(cors());
app.use(express.json());
// Local JSON database files
const DB_FILES = {
users: 'users.json',
transactions: 'transactions.json',
alerts: 'alerts.json',
smartContracts: 'smartContracts.json',
communityReports: 'communityReports.json'
};
// Database helper functions
async function readDB(file) {
try {
const data = await fs.readFile(join(__dirname, 'data', file), 'utf8');
return JSON.parse(data);
} catch (error) {
return [];
}
}
async function writeDB(file, data) {
await fs.mkdir(join(__dirname, 'data'), { recursive: true });
await fs.writeFile(join(__dirname, 'data', file), JSON.stringify(data, null, 2));
}
// Middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ error: 'Invalid token' });
req.user = user;
next();
});
};
// AI Engine Simulation
class AIEngine {
analyzeTransaction(transaction) {
const riskFactors = [];
let riskScore = 0;
// High amount check
if (transaction.amount > 10000) {
riskFactors.push('High transaction amount');
riskScore += 30;
}
// New wallet check
if (transaction.walletAge < 30) {
riskFactors.push('New wallet');
riskScore += 20;
}
// Multiple transactions check
if (transaction.transactionCount > 50) {
riskFactors.push('High transaction frequency');
riskScore += 25;
}
// Known scam patterns
const scamPatterns = ['phishing', 'rugpull', 'honeypot'];
if (scamPatterns.some(pattern =>
transaction.description?.toLowerCase().includes(pattern))) {
riskFactors.push('Matches known scam pattern');
riskScore += 50;
}
// Determine risk level
let riskLevel = 'low';
if (riskScore >= 70) riskLevel = 'high';
else if (riskScore >= 30) riskLevel = 'medium';
return {
riskScore,
riskLevel,
riskFactors,
recommendation: this.getRecommendation(riskLevel)
};
}
getRecommendation(riskLevel) {
const recommendations = {
low: 'Proceed normally',
medium: 'Monitor transaction',
high: 'Block and investigate'
};
return recommendations[riskLevel] || 'Proceed normally';
}
analyzeSmartContract(contractCode) {
// Simulate smart contract analysis
const vulnerabilities = [];
if (contractCode.includes('selfdestruct')) {
vulnerabilities.push('Self-destruct function detected');
}
if (contractCode.includes('block.timestamp')) {
vulnerabilities.push('Timestamp dependency detected');
}
if (contractCode.includes('call.value')) {
vulnerabilities.push('Unchecked call value detected');
}
const securityScore = Math.max(0, 100 - (vulnerabilities.length * 20));
return {
securityScore,
vulnerabilities,
auditStatus: securityScore >= 80 ? 'Secure' : 'Needs Review'
};
}
}
const aiEngine = new AIEngine();
// API Routes
// User Management
app.post('/api/register', async (req, res) => {
try {
const { email, password, name, role = 'user' } = req.body;
const users = await readDB(DB_FILES.users);
if (users.find(u => u.email === email)) {
return res.status(400).json({ error: 'User already exists' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = {
id: Date.now().toString(),
email,
password: hashedPassword,
name,
role,
wallets: [],
createdAt: new Date().toISOString()
};
users.push(newUser);
await writeDB(DB_FILES.users, users);
const token = jwt.sign({ userId: newUser.id, email: newUser.email, role: newUser.role }, JWT_SECRET);
res.status(201).json({
message: 'User registered successfully',
token,
user: { id: newUser.id, email: newUser.email, name: newUser.name, role: newUser.role }
});
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/api/login', async (req, res) => {
try {
const { email, password } = req.body;
const users = await readDB(DB_FILES.users);
const user = users.find(u => u.email === email);
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign({ userId: user.id, email: user.email, role: user.role }, JWT_SECRET);
res.json({
message: 'Login successful',
token,
user: { id: user.id, email: user.email, name: user.name, role: user.role }
});
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
// Transactions & Alerts
app.post('/api/transactions/analyze', authenticateToken, async (req, res) => {
try {
const transaction = req.body;
const analysis = aiEngine.analyzeTransaction(transaction);
// Save transaction
const transactions = await readDB(DB_FILES.transactions);
const newTransaction = {
id: Date.now().toString(),
userId: req.user.userId,
...transaction,
analysis,
status: analysis.riskLevel === 'high' ? 'suspicious' : 'normal',
createdAt: new Date().toISOString()
};
transactions.push(newTransaction);
await writeDB(DB_FILES.transactions, transactions);
// Create alert if high risk
if (analysis.riskLevel === 'high') {
const alerts = await readDB(DB_FILES.alerts);
const newAlert = {
id: Date.now().toString(),
transactionId: newTransaction.id,
userId: req.user.userId,
type: 'suspicious_transaction',
severity: 'high',
description: `High risk transaction detected: ${analysis.riskFactors.join(', ')}`,
status: 'open',
createdAt: new Date().toISOString()
};
alerts.push(newAlert);
await writeDB(DB_FILES.alerts, alerts);
}
res.json({ transaction: newTransaction, analysis });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/transactions', authenticateToken, async (req, res) => {
try {
const transactions = await readDB(DB_FILES.transactions);
const userTransactions = transactions.filter(t => t.userId === req.user.userId);
res.json(userTransactions);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
// Smart Contract Audit
app.post('/api/contracts/audit', authenticateToken, async (req, res) => {
try {
const { contractCode, contractAddress, blockchain } = req.body;
const audit = aiEngine.analyzeSmartContract(contractCode);
// Save audit
const contracts = await readDB(DB_FILES.smartContracts);
const newContract = {
id: Date.now().toString(),
userId: req.user.userId,
contractAddress,
blockchain,
audit,
status: audit.auditStatus,
createdAt: new Date().toISOString()
};
contracts.push(newContract);
await writeDB(DB_FILES.smartContracts, contracts);
res.json({ contract: newContract, audit });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/contracts', authenticateToken, async (req, res) => {
try {
const contracts = await readDB(DB_FILES.smartContracts);
const userContracts = contracts.filter(c => c.userId === req.user.userId);
res.json(userContracts);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/reports', authenticateToken, async (req, res) => {
try {
const reports = await readDB(DB_FILES.communityReports);
const userReports = reports.filter(r => r.userId === req.user.userId);
res.json(userReports);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
// Update alert status
app.patch('/api/alerts/:id', authenticateToken, async (req, res) => {
try {
const { id } = req.params;
const { status } = req.body;
const alerts = await readDB(DB_FILES.alerts);
const alertIndex = alerts.findIndex(a => a.id === id && a.userId === req.user.userId);
if (alertIndex === -1) {
return res.status(404).json({ error: 'Alert not found' });
}
alerts[alertIndex].status = status;
alerts[alertIndex].updatedAt = new Date().toISOString();
await writeDB(DB_FILES.alerts, alerts);
res.json({ message: 'Alert updated successfully', alert: alerts[alertIndex] });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
// Community Reports
app.post('/api/reports', authenticateToken, async (req, res) => {
try {
const { transactionId, description, evidence } = req.body;
const reports = await readDB(DB_FILES.communityReports);
const newReport = {
id: Date.now().toString(),
userId: req.user.userId,
transactionId,
description,
evidence,
status: 'pending',
votes: 0,
createdAt: new Date().toISOString()
};
reports.push(newReport);
await writeDB(DB_FILES.communityReports, reports);
res.json({ report: newReport, message: 'Report submitted successfully' });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/api/alerts', authenticateToken, async (req, res) => {
try {
const alerts = await readDB(DB_FILES.alerts);
const userAlerts = alerts.filter(a => a.userId === req.user.userId);
res.json(userAlerts);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.listen(PORT, () => {
console.log(`MAGIC Guard backend running on port ${PORT}`);
});