-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
553 lines (488 loc) · 15.9 KB
/
server.js
File metadata and controls
553 lines (488 loc) · 15.9 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { ethers } = require('ethers');
const { v4: uuidv4 } = require('uuid');
const { processCommand, provider } = require('./ai-agent');
const walletManager = require('./wallet-manager');
require('dotenv').config();
// Initialize Express app
const app = express();
const PORT = process.env.PORT || 3000;
// Validate essential env vars on startup
const REQUIRED_ENV = ['RPC_URL', 'ENCRYPTION_KEY', 'OPENROUTER_API_KEY'];
REQUIRED_ENV.forEach(key => {
if (!process.env[key]) {
console.error(`FATAL: Missing required environment variable: ${key}`);
process.exit(1);
}
});
// Middleware
app.use(helmet()); // Basic security headers
const allowedOrigins = (process.env.CORS_ORIGINS || 'http://localhost:5173,http://localhost:3000')
.split(',')
.map((o) => o.trim())
.filter(Boolean);
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) return callback(null, true);
return callback(new Error('Not allowed by CORS'));
}
}));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((req, res, next) => {
req.requestId = uuidv4();
const start = Date.now();
res.setHeader('x-request-id', req.requestId);
res.on('finish', () => {
console.log(JSON.stringify({
requestId: req.requestId,
method: req.method,
path: req.originalUrl,
status: res.statusCode,
durationMs: Date.now() - start
}));
});
next();
});
// Rate limiting to prevent brute force
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 20, // Limit each IP to 20 requests per window
message: { success: false, message: 'Too many attempts, please try again later.' }
});
const chatLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 30, // Limit each IP to 30 chat messages per minute
message: { success: false, message: 'Slow down! Too many messages.' }
});
const AUTH_SESSIONS_FILE = path.join(__dirname, 'data', 'auth-sessions.json');
const authSessions = new Map();
const AUTH_TTL_MS = 12 * 60 * 60 * 1000; // 12h
function ensureAuthSessionStorage() {
const dir = path.join(__dirname, 'data');
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
if (!fs.existsSync(AUTH_SESSIONS_FILE)) fs.writeFileSync(AUTH_SESSIONS_FILE, JSON.stringify({}), 'utf8');
}
function loadAuthSessions() {
ensureAuthSessionStorage();
try {
const raw = JSON.parse(fs.readFileSync(AUTH_SESSIONS_FILE, 'utf8'));
Object.entries(raw).forEach(([token, session]) => authSessions.set(token, session));
} catch (e) {}
}
function saveAuthSessions() {
ensureAuthSessionStorage();
const obj = {};
for (const [token, session] of authSessions.entries()) obj[token] = session;
fs.writeFileSync(AUTH_SESSIONS_FILE, JSON.stringify(obj, null, 2), 'utf8');
}
function createAuthSession(userId, password) {
const token = crypto.randomBytes(32).toString('hex');
authSessions.set(token, {
userId,
password,
authVersion: walletManager.getAuthVersion(userId),
createdAt: Date.now(),
expiresAt: Date.now() + AUTH_TTL_MS
});
saveAuthSessions();
return token;
}
function getSessionFromRequest(req) {
const authHeader = req.headers.authorization || '';
const match = authHeader.match(/^Bearer\s+(.+)$/i);
if (!match) return null;
const token = match[1].trim();
const session = authSessions.get(token);
if (!session) return null;
if (Date.now() > session.expiresAt) {
authSessions.delete(token);
saveAuthSessions();
return null;
}
const currentAuthVersion = walletManager.getAuthVersion(session.userId);
if ((session.authVersion || 1) !== currentAuthVersion) {
authSessions.delete(token);
saveAuthSessions();
return null;
}
return { token, ...session };
}
function revokeAuthSession(req) {
const authHeader = req.headers.authorization || '';
const match = authHeader.match(/^Bearer\s+(.+)$/i);
if (!match) return false;
const deleted = authSessions.delete(match[1].trim());
if (deleted) saveAuthSessions();
return deleted;
}
// Authentication middleware
async function authenticateUser(req, res, next) {
const requestedUserId = req.headers['x-user-id'] || req.body.userId || req.params.userId;
const password = req.headers['x-password'];
const authHeader = req.headers.authorization || '';
const hasBearerToken = /^Bearer\s+.+/i.test(authHeader);
const session = getSessionFromRequest(req);
if (session) {
if (requestedUserId && requestedUserId !== session.userId) {
return res.status(403).json({ success: false, message: 'Token does not match requested user.' });
}
req.authUserId = session.userId;
req.authPassword = session.password;
return next();
}
if (hasBearerToken) {
return res.status(401).json({ success: false, message: 'Session expired or invalid. Please log in again.' });
}
const userId = requestedUserId;
if (!userId) {
return res.status(401).json({ success: false, message: 'User ID is required' });
}
// Check if user exists
const wallet = walletManager.getWallet(userId);
if (!wallet) {
// If user doesn't exist, we allow it (for signup/first chat)
return next();
}
// If user exists, they must provide a password
if (!password) {
return res.status(401).json({ success: false, message: 'Password is required' });
}
const isValid = await walletManager.verifyPassword(userId, password);
if (!isValid) {
return res.status(401).json({ success: false, message: 'Invalid password' });
}
req.authUserId = userId;
req.authPassword = password;
next();
}
// Signup endpoint
app.post('/api/signup', authLimiter, async (req, res) => {
try {
const { userId, password } = req.body;
if (!userId || !password) {
return res.status(400).json({ success: false, message: 'UserId and password required' });
}
const result = await walletManager.createWallet(userId, password);
if (result.success) {
const token = createAuthSession(userId, password);
return res.json({ ...result, token, userId });
}
res.json(result);
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
// Login endpoint
app.post('/api/login', authLimiter, async (req, res) => {
try {
const { userId, password } = req.body;
const isValid = await walletManager.verifyPassword(userId, password);
if (isValid) {
const wallet = walletManager.getWallet(userId);
const token = createAuthSession(userId, password);
res.json({ success: true, token, userId, address: wallet.address });
} else {
res.status(401).json({ success: false, message: 'Invalid credentials' });
}
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
/**
* API Routes
*/
// Chat endpoint - process user messages and manage session state
app.post('/api/chat', [authenticateUser, chatLimiter], async (req, res) => {
try {
const { userId: bodyUserId, message, sessionId, mode, activeAddress } = req.body;
const userId = req.authUserId || bodyUserId;
if (!userId || !message) {
return res.status(400).json({
success: false,
message: 'Both userId and message are required'
});
}
// Process the message through the AI agent
const password = req.authPassword || req.headers['x-password'];
const result = await processCommand(
userId,
message,
sessionId,
mode || 'custodial',
password,
activeAddress
);
// Respond with the result
res.json(result);
} catch (error) {
console.error('Error processing chat message:', error);
res.status(500).json({
success: false,
message: `Server error: ${error.message}`
});
}
});
// Get wallet info (addresses and balances)
app.get('/api/wallet/:userId', authenticateUser, async (req, res) => {
try {
const userId = req.authUserId || req.params.userId;
const wallet = walletManager.getSafeWallet(userId);
if (!wallet) {
return res.status(404).json({
success: false,
message: 'No wallet found for this user'
});
}
// Get the wallet's balance
const balance = await provider.getBalance(wallet.address);
res.json({
success: true,
...wallet,
balance: ethers.formatEther(balance),
balanceWei: balance.toString()
});
} catch (error) {
console.error('Error getting wallet info:', error);
res.status(500).json({
success: false,
message: `Server error: ${error.message}`
});
}
});
// Create a new wallet
app.post('/api/wallet/:userId', async (req, res) => {
try {
const { userId } = req.params;
const { password } = req.body;
const result = await walletManager.createWallet(userId, password);
res.json(result);
} catch (error) {
console.error('Error creating wallet:', error);
res.status(500).json({
success: false,
message: `Server error: ${error.message}`
});
}
});
// Send ETH to a recipient
app.post('/api/transaction/:userId', authenticateUser, async (req, res) => {
try {
const userId = req.authUserId || req.params.userId;
const { recipient, amount } = req.body;
if (!recipient || !amount) {
return res.status(400).json({
success: false,
message: 'Both recipient and amount are required'
});
}
// Validate address
if (!ethers.isAddress(recipient)) {
return res.status(400).json({
success: false,
message: 'Invalid recipient address'
});
}
// Validate amount
const amountFloat = parseFloat(amount);
if (isNaN(amountFloat) || amountFloat <= 0) {
return res.status(400).json({
success: false,
message: 'Amount must be a positive number'
});
}
// Get wallet instance
const password = req.authPassword || req.headers['x-password'];
const walletInstance = walletManager.getWalletInstance(userId, provider, password);
if (!walletInstance) {
return res.status(404).json({
success: false,
message: 'No wallet found for this user'
});
}
// Check balance
const balance = await walletInstance.getBalance();
const amountWei = ethers.parseEther(amount.toString());
if (balance.lt(amountWei)) {
return res.status(400).json({
success: false,
message: `Insufficient balance. You have ${ethers.formatEther(balance)} ETH, trying to send ${amount} ETH`
});
}
// Check Guardrails (Daily Limit)
const allowed = walletManager.checkAndUpdateLimit(userId, amount);
if (!allowed) {
return res.status(400).json({
success: false,
message: 'Daily limit exceeded'
});
}
// Send transaction
const tx = await walletInstance.sendTransaction({
to: recipient,
value: amountWei,
gasLimit: 21000 // Standard gas limit for ETH transfers
});
// Record transaction
walletManager.recordTransaction(userId, {
type: 'send',
to: recipient,
amount: amount,
hash: tx.hash,
status: 'success',
mode: 'custodial'
});
res.json({
success: true,
txHash: tx.hash,
from: walletInstance.address,
to: recipient,
amount
});
} catch (error) {
console.error('Error sending transaction:', error);
res.status(500).json({
success: false,
message: `Server error: ${error.message}`
});
}
});
// Get transaction history
app.get('/api/history/:userId', authenticateUser, async (req, res) => {
try {
const userId = req.authUserId || req.params.userId;
const wallet = walletManager.getSafeWallet(userId);
if (!wallet) {
return res.status(404).json({
success: false,
message: 'No wallet found for this user'
});
}
res.json({
success: true,
transactions: wallet.transactions || []
});
} catch (error) {
console.error('Error getting history:', error);
res.status(500).json({
success: false,
message: `Server error: ${error.message}`
});
}
});
// Record a transaction (useful for non-custodial mode)
app.post('/api/record-tx', authenticateUser, async (req, res) => {
try {
const userId = req.authUserId || req.body.userId;
const { tx } = req.body;
walletManager.recordTransaction(userId, tx);
res.json({ success: true });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
// Get security status
app.get('/api/security-status/:userId', authenticateUser, (req, res) => {
try {
const userId = req.authUserId || req.params.userId;
const status = walletManager.getSecurityStatus(userId);
res.json({ success: true, ...status });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
app.post('/api/logout', authenticateUser, (req, res) => {
revokeAuthSession(req);
res.json({ success: true });
});
app.get('/api/auth/me', authenticateUser, (req, res) => {
res.json({ success: true, userId: req.authUserId });
});
app.post('/api/auth/refresh', authenticateUser, (req, res) => {
const userId = req.authUserId;
const password = req.authPassword;
revokeAuthSession(req);
const token = createAuthSession(userId, password);
res.json({ success: true, token, userId });
});
// Basic health check
app.get('/api/health', (req, res) => {
res.json({ success: true, status: 'IntentPay is active' });
});
// Serve a simple home page
app.get('/', (req, res) => {
res.send(`
<html>
<head>
<title>IntentPay</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
h1 {
color: #333;
border-bottom: 1px solid #ddd;
padding-bottom: 10px;
}
.endpoint {
background: #f5f5f5;
padding: 15px;
margin-bottom: 15px;
border-radius: 5px;
}
.method {
font-weight: bold;
color: #0066cc;
}
code {
background: #eee;
padding: 2px 5px;
border-radius: 3px;
}
</style>
</head>
<body>
<h1>IntentPay API</h1>
<p>Welcome to the Multi-User Wallet AI Agent API. Below are the available endpoints:</p>
<div class="endpoint">
<p><span class="method">POST</span> /api/chat</p>
<p>Process natural language commands and interact with the wallet agent.</p>
<p>Required parameters: <code>userId</code>, <code>message</code></p>
<p>Optional parameters: <code>sessionId</code></p>
</div>
<div class="endpoint">
<p><span class="method">GET</span> /api/wallet/:userId</p>
<p>Get wallet information including address and balance.</p>
</div>
<div class="endpoint">
<p><span class="method">POST</span> /api/wallet/:userId</p>
<p>Create a new wallet for the specified user.</p>
</div>
<div class="endpoint">
<p><span class="method">POST</span> /api/transaction/:userId</p>
<p>Send ETH from the user's wallet to a specified address.</p>
<p>Required parameters: <code>recipient</code>, <code>amount</code></p>
</div>
<p>For more information, please refer to the documentation.</p>
</body>
</html>
`);
});
// Start the server
loadAuthSessions();
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`RPC URL: ${process.env.RPC_URL.substring(0, 20)}...`);
console.log(`Visit http://localhost:${PORT} to view the API documentation`);
});