-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
535 lines (457 loc) · 17.4 KB
/
Copy pathserver.js
File metadata and controls
535 lines (457 loc) · 17.4 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
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import rateLimit from 'express-rate-limit';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import crypto from 'crypto';
import { paymentMiddleware } from 'x402-express';
// Import services
import { analyzeSEO } from './src/services/seo-analyzer.js';
import * as userService from './src/services/user-service.js';
import * as analysisService from './src/services/analysis-service.js';
import * as paymentService from './src/services/payment-service.js';
// Normalize user input into a valid HTTP(S) URL.
const normalizeHttpUrl = (value) => {
if (typeof value !== 'string') return null;
const trimmed = value.trim();
if (!trimmed) return null;
const withProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)
? trimmed
: `https://${trimmed}`;
try {
const parsed = new URL(withProtocol);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return null;
}
if (!parsed.hostname) {
return null;
}
if (parsed.hostname !== 'localhost' && !parsed.hostname.includes('.')) {
return null;
}
return parsed.toString();
} catch (_) {
return null;
}
};
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
const DEFAULT_PUBLIC_URL =
process.env.NODE_ENV === 'production'
? 'https://easy-seo.tools'
: `http://localhost:${PORT}`;
const getPublicBaseUrl = (req) => {
const envUrl = (process.env.PUBLIC_URL || '').trim();
if (envUrl) {
return envUrl.replace(/\/+$/, '');
}
const forwardedProto = req.get('x-forwarded-proto');
const forwardedHost = req.get('x-forwarded-host');
const host = forwardedHost || req.get('host');
if (host) {
const protocol = forwardedProto || (host.includes('localhost') ? 'http' : 'https');
return `${protocol}://${host}`.replace(/\/+$/, '');
}
return DEFAULT_PUBLIC_URL;
};
const getPaymentFingerprint = (req) => {
const paymentHeader = req.get('x-payment');
if (!paymentHeader || typeof paymentHeader !== 'string' || !paymentHeader.trim()) {
return null;
}
return crypto.createHash('sha256').update(paymentHeader).digest('hex');
};
// Trust proxy for deployments behind reverse proxy (Akash, Railway, etc.)
app.set('trust proxy', 1);
// Middleware
app.use(helmet({
contentSecurityPolicy: false, // Disable for development
}));
app.use(compression());
app.use(cors({
origin: process.env.CORS_ORIGIN || '*'
}));
app.use(express.json());
const publicDir = path.join(__dirname, 'public');
const distDir = path.join(__dirname, 'dist');
const hasDist = fs.existsSync(path.join(distDir, 'index.html'));
if (process.env.NODE_ENV === 'production' && hasDist) {
app.use(express.static(distDir));
} else {
app.use(express.static(publicDir));
}
// Rate limiting
const limiter = rateLimit({
windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000,
max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100,
message: 'Too many requests from this IP, please try again later.'
});
app.use('/api/', limiter);
// x402 Payment middleware (PayAI facilitator)
const FACILITATOR_URL = process.env.FACILITATOR_URL || 'https://facilitator.payai.network';
const X402_NETWORK = process.env.NETWORK || 'solana';
const X402_ADDRESS = process.env.ADDRESS || process.env.SOLANA_RECIPIENT_WALLET;
const SOLANA_CLUSTER = process.env.SOLANA_CLUSTER || 'devnet';
const PUBLIC_SOLANA_RPC_URL = SOLANA_CLUSTER === 'mainnet'
? 'https://api.mainnet-beta.solana.com'
: 'https://api.devnet.solana.com';
const SOLANA_RPC_URL = SOLANA_CLUSTER === 'mainnet'
? (process.env.SOLANA_RPC_MAINNET || PUBLIC_SOLANA_RPC_URL)
: (process.env.SOLANA_RPC_DEVNET || PUBLIC_SOLANA_RPC_URL);
if (!X402_ADDRESS) {
console.warn('⚠️ Missing ADDRESS (or SOLANA_RECIPIENT_WALLET) for x402 payments.');
}
const pricing = paymentService.getPricing();
const x402Routes = {
'/api/payment/checkout/lite': { price: `$${pricing.lite.price}`, network: X402_NETWORK },
'/api/payment/checkout/pro': { price: `$${pricing.pro.price}`, network: X402_NETWORK },
'/api/payment/checkout/unlimited': { price: `$${pricing.unlimited.price}`, network: X402_NETWORK }
};
app.use(paymentMiddleware(
X402_ADDRESS || 'missing-address',
x402Routes,
{ url: FACILITATOR_URL }
));
// ============== API ROUTES ==============
// Health check
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', timestamp: Date.now() });
});
// Create guest user
app.post('/api/user/guest', async (req, res) => {
try {
const { deviceId } = req.body || {};
if (!deviceId) {
return res.status(400).json({ error: 'deviceId is required' });
}
const user = await userService.createGuestUser(deviceId);
res.json(user);
} catch (error) {
console.error('Error creating guest user:', error);
res.status(500).json({ error: 'Failed to create guest user' });
}
});
// Wallet authentication - login or register
app.post('/api/user/wallet', async (req, res) => {
try {
const { walletAddress } = req.body;
if (!walletAddress) {
return res.status(400).json({ error: 'Wallet address is required' });
}
console.log('Authenticating wallet:', walletAddress);
const user = await userService.createOrGetWalletUser(walletAddress);
console.log('User retrieved/created:', user.id);
const canAnalyze = await userService.canUserAnalyze(user);
res.json({
id: user.id,
walletAddress: user.wallet_address,
plan: user.plan,
credits: user.credits,
canAnalyze: canAnalyze.allowed,
remaining: canAnalyze.remaining,
freeRemaining: canAnalyze.freeRemaining,
paidRemaining: canAnalyze.paidRemaining,
isGuest: user.is_guest
});
} catch (error) {
console.error('Error with wallet authentication:', error.message, error.stack);
res.status(500).json({ error: error.message || 'Failed to authenticate with wallet' });
}
});
// Link wallet to existing guest user
app.post('/api/user/:userId/link-wallet', async (req, res) => {
try {
const { walletAddress } = req.body;
if (!walletAddress) {
return res.status(400).json({ error: 'Wallet address is required' });
}
await userService.linkWalletToUser(req.params.userId, walletAddress);
const user = await userService.getUser(req.params.userId);
const canAnalyze = await userService.canUserAnalyze(user);
res.json({
id: user.id,
walletAddress: user.wallet_address,
plan: user.plan,
credits: user.credits,
canAnalyze: canAnalyze.allowed,
remaining: canAnalyze.remaining,
freeRemaining: canAnalyze.freeRemaining,
paidRemaining: canAnalyze.paidRemaining,
isGuest: user.is_guest
});
} catch (error) {
console.error('Error linking wallet:', error);
res.status(500).json({ error: 'Failed to link wallet' });
}
});
// Get user info
app.get('/api/user/:userId', async (req, res) => {
try {
const user = await userService.getUser(req.params.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const canAnalyze = await userService.canUserAnalyze(user);
res.json({
id: user.id,
plan: user.plan,
credits: user.credits,
canAnalyze: canAnalyze.allowed,
remaining: canAnalyze.remaining,
freeRemaining: canAnalyze.freeRemaining,
paidRemaining: canAnalyze.paidRemaining
});
} catch (error) {
console.error('Error getting user:', error);
res.status(500).json({ error: 'Failed to get user info' });
}
});
// Analyze URL
app.post('/api/analyze', async (req, res) => {
try {
const { url, userId } = req.body;
const normalizedUrl = normalizeHttpUrl(url);
if (!url || !userId) {
return res.status(400).json({ error: 'URL and userId are required' });
}
if (!normalizedUrl) {
return res.status(400).json({ error: 'Invalid URL format' });
}
// Get user
const user = await userService.getUser(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Check if user can analyze
const canAnalyze = await userService.canUserAnalyze(user);
if (!canAnalyze.allowed) {
console.warn(`User ${user.id} not allowed to analyze. credits=${user.credits}`);
return res.status(402).json({
error: 'Analysis limit exceeded',
message: 'Free analyses used. Complete x402 payment to continue analyzing.',
remaining: 0,
limitExceeded: true
});
}
// Perform analysis
const result = await analyzeSEO(normalizedUrl);
// Save analysis
const { id: analysisId, publicToken } = await analysisService.saveAnalysis(userId, normalizedUrl, result, false);
// Deduct credit
await userService.deductCredit(userId, user);
// Get updated user info
const updatedUser = await userService.getUser(userId);
const updatedCanAnalyze = await userService.canUserAnalyze(updatedUser);
res.json({
...result,
analysisId,
remaining: updatedCanAnalyze.remaining
});
} catch (error) {
console.error('Error analyzing URL:', error);
res.status(500).json({ error: 'Failed to analyze URL', message: error.message });
}
});
// Get user's analysis history
app.get('/api/analyses/:userId', async (req, res) => {
try {
const analyses = await analysisService.getUserAnalyses(req.params.userId);
res.json(analyses);
} catch (error) {
console.error('Error getting analyses:', error);
res.status(500).json({ error: 'Failed to get analyses' });
}
});
// Get specific analysis
app.get('/api/analysis/:analysisId', async (req, res) => {
try {
const analysis = await analysisService.getAnalysis(req.params.analysisId);
if (!analysis) {
return res.status(404).json({ error: 'Analysis not found' });
}
res.json(analysis);
} catch (error) {
console.error('Error getting analysis:', error);
res.status(500).json({ error: 'Failed to get analysis' });
}
});
// Make analysis public and get shareable link
app.post('/api/analysis/:analysisId/share', async (req, res) => {
try {
const { userId } = req.body;
const publicToken = await analysisService.makeAnalysisPublic(req.params.analysisId, userId);
const shareUrl = `${getPublicBaseUrl(req)}/share/${publicToken}`;
res.json({ publicToken, shareUrl });
} catch (error) {
console.error('Error sharing analysis:', error);
res.status(500).json({ error: 'Failed to share analysis' });
}
});
// Get public analysis
app.get('/api/public/:token', async (req, res) => {
try {
const analysis = await analysisService.getAnalysisByPublicToken(req.params.token);
if (!analysis) {
return res.status(404).json({ error: 'Public analysis not found' });
}
res.json(analysis);
} catch (error) {
console.error('Error getting public analysis:', error);
res.status(500).json({ error: 'Failed to get public analysis' });
}
});
// Get pricing
app.get('/api/pricing', (req, res) => {
try {
const pricing = paymentService.getPricing();
res.json(pricing);
} catch (error) {
console.error('Error getting pricing:', error);
res.status(500).json({ error: 'Failed to get pricing' });
}
});
// x402 Payment rate limiter
const paymentLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // max 10 payment attempts per IP
message: 'Too many payment attempts, please try again later',
standardHeaders: true,
legacyHeaders: false,
});
const solanaRpcLimiter = rateLimit({
windowMs: 60 * 1000,
max: 120,
message: 'Too many Solana RPC requests, please try again later',
standardHeaders: true,
legacyHeaders: false,
});
const isAllowedSolanaMethod = (method) => {
if (typeof method !== 'string' || !method.trim()) return false;
if (method === 'simulateTransaction') return true;
return method.startsWith('get');
};
// Server-side Solana RPC proxy to keep private RPC keys out of client bundles.
app.post('/api/solana/rpc', solanaRpcLimiter, async (req, res) => {
try {
const payload = req.body;
if (!payload || typeof payload !== 'object') {
return res.status(400).json({ error: 'Invalid JSON-RPC payload' });
}
const requests = Array.isArray(payload) ? payload : [payload];
if (!requests.length || requests.length > 20) {
return res.status(400).json({ error: 'JSON-RPC batch size is invalid' });
}
for (const request of requests) {
if (!request || typeof request !== 'object' || !isAllowedSolanaMethod(request.method)) {
return res.status(403).json({ error: 'JSON-RPC method is not allowed' });
}
}
const upstream = await fetch(SOLANA_RPC_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const bodyText = await upstream.text();
res.status(upstream.status);
res.type(upstream.headers.get('content-type') || 'application/json');
return res.send(bodyText);
} catch (error) {
console.error('Error proxying Solana RPC:', error);
return res.status(502).json({ error: 'Solana RPC proxy failed', message: error.message });
}
});
// x402: Paid checkout endpoints (PayAI facilitator)
app.post('/api/payment/checkout/:plan', paymentLimiter, async (req, res) => {
try {
const { userId } = req.body;
const plan = req.params.plan;
const paymentFingerprint = getPaymentFingerprint(req);
if (!userId || !plan) {
return res.status(400).json({ error: 'userId and plan are required' });
}
if (!paymentFingerprint) {
return res.status(402).json({ error: 'X-PAYMENT header is required' });
}
const pricingMap = paymentService.getPricing();
if (!pricingMap[plan]) {
return res.status(400).json({ error: 'Invalid plan' });
}
const user = await userService.getUser(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const result = await paymentService.applyPlanPurchase(
userId,
plan,
paymentFingerprint,
user.wallet_address || null
);
res.json(result);
} catch (error) {
console.error('Error completing checkout:', error);
if (error?.code === '23505') {
return res.status(409).json({ error: 'Duplicate payment detected', message: 'This payment was already processed' });
}
res.status(400).json({ error: 'Checkout failed', message: error.message });
}
});
// Get latest blockhash from server-side RPC (avoid browser CORS issues)
app.get('/api/payment/blockhash', paymentLimiter, async (req, res) => {
try {
const data = await paymentService.getLatestBlockhash();
res.json(data);
} catch (error) {
console.error('Error getting blockhash:', error);
res.status(500).json({ error: 'Failed to get blockhash', message: error.message });
}
});
// Get user transactions
app.get('/api/transactions/:userId', async (req, res) => {
try {
const transactions = await paymentService.getUserTransactions(req.params.userId);
res.json(transactions);
} catch (error) {
console.error('Error getting transactions:', error);
res.status(500).json({ error: 'Failed to get transactions' });
}
});
// Serve public share page
app.get('/share/:token', (req, res) => {
res.set('X-Robots-Tag', 'noindex, follow');
res.sendFile(path.join(publicDir, 'share.html'));
});
// Serve main page
app.get('/', (req, res) => {
if (process.env.NODE_ENV === 'production' && hasDist) {
res.sendFile(path.join(distDir, 'index.html'));
return;
}
res.sendFile(path.join(publicDir, 'index.html'));
});
// Global Stats
app.get('/api/stats', async (req, res) => {
try {
const stats = await analysisService.getGlobalStats();
res.json(stats);
} catch (error) {
console.error('Stats error:', error);
res.status(500).json({ error: 'Failed to fetch stats' });
}
});
// Start server only when this file is run directly. Tests import the app.
const isDirectRun = process.argv[1]
&& path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isDirectRun) {
app.listen(PORT, () => {
console.log(`API running on http://localhost:${PORT}`);
console.log(`Environment: ${process.env.NODE_ENV}`);
});
}
export default app;