-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathindex.js
More file actions
803 lines (695 loc) · 30.5 KB
/
index.js
File metadata and controls
803 lines (695 loc) · 30.5 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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
dotenv.config();
require('dotenv').config();
dotenv.config();
// Initialize structured logging and error tracking
const { logger, requestTracingMiddleware } = require('./src/utils/logger');
const { errorTracking } = require('./src/utils/errorTracking');
// Initialize error tracking
errorTracking.initialize();
const { AppDatabase } = require('./src/db/appDatabase');
const { loadConfig } = require('./src/config');
const { CdnTokenService, TokenValidationError } = require('./src/services/cdnTokenService');
const { CreatorActionService } = require('./src/services/creatorActionService');
const { CreatorAuditLogService } = require('./src/services/creatorAuditLogService');
const { CreatorAuthService } = require('./src/services/creatorAuthService');
const { SorobanSubscriptionVerifier } = require('./src/services/sorobanSubscriptionVerifier');
const { SubscriptionService } = require('./src/services/subscriptionService');
const { SubscriptionExpiryChecker } = require('./src/services/subscriptionExpiryChecker');
const { IPIntelligenceService } = require('./src/services/ipIntelligenceService');
const { IPBlockingService } = require('./src/services/ipBlockingService');
const { IPMonitoringService } = require('./src/services/ipMonitoringService');
const { IPIntelligenceMiddleware } = require('./src/middleware/ipIntelligenceMiddleware');
const { BehavioralBiometricService } = require('./src/services/behavioralBiometricService');
const { BotDetectionClassifier } = require('./src/services/botDetectionClassifier');
const VideoProcessingWorker = require('./src/services/videoProcessingWorker');
const { BackgroundWorkerService } = require('./src/services/backgroundWorkerService');
const { GlobalStatsService } = require('./src/services/globalStatsService');
const GlobalStatsWorker = require('./src/services/globalStatsWorker');
const CollaborationRevenueService = require('./services/collaborationRevenueService');
const CollaborationWatchTimeMiddleware = require('./middleware/collaborationWatchTime');
const createVideoRoutes = require('./routes/video');
const createGlobalStatsRouter = require('./routes/globalStats');
const createDeviceRoutes = require('./routes/device');
const createSwaggerRoutes = require('./routes/swagger');
const createCollaborationRoutes = require('./routes/collaborations');
const { buildAuditLogCsv } = require('./src/utils/export/auditLogCsv');
const { buildAuditLogPdf } = require('./src/utils/export/auditLogPdf');
const { getRequestIp } = require('./src/utils/requestIp');
const { getRedisClient, closeRedisClient } = require('./src/config/redis');
const { createRateLimiter } = require('./middleware/rateLimiter');
// Tier middleware — attaches req.user.tier to every request
const { attachTier } = require('./middleware/tierAuth');
/**
* Create the Express application with injectable services for testing.
*
* @param {object} [dependencies={}] Optional service overrides.
* @returns {import('express').Express}
*/
function createApp(dependencies = {}) {
const app = express();
const config = dependencies.config || loadConfig();
const database = dependencies.database || new AppDatabase(config.database.filename);
const auditLogService =
dependencies.auditLogService || new CreatorAuditLogService(database);
const auditLogService = dependencies.auditLogService || new CreatorAuditLogService(database);
const creatorActionService =
dependencies.creatorActionService ||
new CreatorActionService(database, auditLogService);
const creatorAuthService =
dependencies.creatorAuthService || new CreatorAuthService(config);
const subscriptionVerifier =
dependencies.subscriptionVerifier || new SorobanSubscriptionVerifier(config);
const tokenService = dependencies.tokenService || new CdnTokenService(config);
// ── Global middleware ──────────────────────────────────────────────────────
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// Attach req.user = { address, tier } to every request.
// Never rejects — unauthenticated requests get tier = 'guest'.
app.use(attachTier);
// Notification and email utilities
const { NotificationService } = require('./src/services/notificationService');
const { sendEmail } = require('./src/utils/email');
const notificationService = dependencies.notificationService || new NotificationService(database);
const subscriptionService =
dependencies.subscriptionService || new SubscriptionService({
database,
auditLogService,
notificationService,
emailUtil: { sendEmail },
});
dependencies.subscriptionService || new SubscriptionService({ database, auditLogService, config });
const subscriptionExpiryChecker =
dependencies.subscriptionExpiryChecker ||
new SubscriptionExpiryChecker({
database,
lowBalanceEmailService: dependencies.lowBalanceEmailService,
});
// Initialize background worker service for async processing
const backgroundWorker = dependencies.backgroundWorker || new BackgroundWorkerService(config.rabbitmq);
// Initialize federation service for ActivityPub integration
const federationService = dependencies.federationService || new FederationService(config, database, backgroundWorker);
// Initialize federation worker for background processing
const federationWorker = dependencies.federationWorker || new FederationWorker(config, database, federationService);
// expose the service on the express app so external routers can access it
app.set('subscriptionService', subscriptionService);
app.set('subscriptionExpiryChecker', subscriptionExpiryChecker);
app.set('backgroundWorker', backgroundWorker);
app.set('federationService', federationService);
app.set('federationWorker', federationWorker);
// Initialize and start AML scanner if enabled
let amlScannerWorker = null;
if (config.aml && config.aml.enabled) {
amlScannerWorker = dependencies.amlScannerWorker || new AMLScannerWorker(database, config.aml);
app.set('amlScannerWorker', amlScannerWorker);
amlScannerWorker.start().catch(error => {
console.error('Failed to start AML scanner worker:', error);
});
// Start federation worker if ActivityPub is enabled
if (config.activityPub?.enabled !== false) {
const federationWorker = dependencies.federationWorker || new FederationWorker(database, config);
federationWorker.start().catch(error => {
console.error('Failed to start federation worker:', error);
});
}
// Start leaderboard worker if enabled
if (config.leaderboard?.enabled !== false) {
const leaderboardWorker = dependencies.leaderboardWorker || new LeaderboardWorker(config, database, getRedisClient(), EngagementLeaderboardService);
leaderboardWorker.start().catch(error => {
console.error('Failed to start leaderboard worker:', error);
});
console.log('IP Intelligence services initialized');
}
const dayInMs = 24 * 60 * 60 * 1000;
const subscriptionExpiryCheckerInterval = setInterval(async () => {
try {
await subscriptionExpiryChecker.runDailyCheck();
} catch (error) {
// eslint-disable-next-line no-console
console.warn(
'Subscription expiry checker failed:',
error && error.message ? error.message : error,
);
}
}, dayInMs);
if (typeof subscriptionExpiryCheckerInterval.unref === 'function') {
subscriptionExpiryCheckerInterval.unref();
}
app.set('subscriptionExpiryCheckerInterval', subscriptionExpiryCheckerInterval);
const videoWorker = dependencies.videoWorker || new VideoProcessingWorker(config, database);
// Initialize social token gating service and middleware
const socialTokenService = dependencies.socialTokenService || new SocialTokenGatingService(config, database, getRedisClient());
const socialTokenMiddleware = dependencies.socialTokenMiddleware || new SocialTokenGatingMiddleware(socialTokenService, database, getRedisClient());
// Initialize collaboration revenue service and watch time middleware
const collaborationService = dependencies.collaborationService || new CollaborationRevenueService(config, database, getRedisClient());
const collaborationWatchTimeMiddleware = dependencies.collaborationWatchTimeMiddleware || new CollaborationWatchTimeMiddleware(collaborationService, database);
// Initialize global stats service and worker
const globalStatsService = dependencies.globalStatsService || new GlobalStatsService(database);
const globalStatsWorker = dependencies.globalStatsWorker || new GlobalStatsWorker(database, {
refreshInterval: process.env.GLOBAL_STATS_REFRESH_INTERVAL ? parseInt(process.env.GLOBAL_STATS_REFRESH_INTERVAL) : 60000,
initialDelay: process.env.GLOBAL_STATS_INITIAL_DELAY ? parseInt(process.env.GLOBAL_STATS_INITIAL_DELAY) : 5000
});
// Initialize leaderboard service and worker
const redisClient = getRedisClient();
const leaderboardService = dependencies.leaderboardService || new EngagementLeaderboardService(config, database, redisClient);
const leaderboardWorker = dependencies.leaderboardWorker || new LeaderboardWorker(config, database, redisClient, leaderboardService);
// Initialize subdomain and SSL services
const subdomainService = dependencies.subdomainService || new SubdomainService(database, config);
const sslCertificateService = dependencies.sslCertificateService || new SslCertificateService(config);
const subdomainMiddleware = dependencies.subdomainMiddleware || new SubdomainMiddleware(database, config);
// expose services on the express app so external routers can access them
app.set('subscriptionService', subscriptionService);
app.set('subscriptionExpiryChecker', subscriptionExpiryChecker);
app.set('backgroundWorker', backgroundWorker);
app.set('globalStatsService', globalStatsService);
app.set('globalStatsWorker', globalStatsWorker);
app.set('leaderboardService', leaderboardService);
app.set('leaderboardWorker', leaderboardWorker);
app.set('socialTokenService', socialTokenService);
app.set('socialTokenMiddleware', socialTokenMiddleware);
app.set('subdomainService', subdomainService);
app.set('sslCertificateService', sslCertificateService);
app.set('collaborationService', collaborationService);
app.set('collaborationWatchTimeMiddleware', collaborationWatchTimeMiddleware);
// Initialize and start predictive churn analysis worker
const { PredictiveChurnAnalysisWorker } = require('./src/services/predictiveChurnAnalysisWorker');
const churnAnalysisWorker = dependencies.churnAnalysisWorker || new PredictiveChurnAnalysisWorker(database, {
checkInterval: process.env.CHURN_ANALYSIS_INTERVAL ? parseInt(process.env.CHURN_ANALYSIS_INTERVAL) : 3600000,
});
app.set('churnAnalysisWorker', churnAnalysisWorker);
churnAnalysisWorker.start().catch(error => {
console.error('Failed to start PredictiveChurnAnalysisWorker:', error);
});
// Start global stats worker
globalStatsWorker.start().catch(error => {
console.error('Failed to start global stats worker:', error);
});
// Start federation worker if ActivityPub is enabled
if (config.activityPub?.enabled !== false) {
federationWorker.start().catch(error => {
console.error('Failed to start federation worker:', error);
});
}
app.use(cors());
app.use(express.json());
// Subscription events webhook
app.use('/api/subscription', require('./routes/subscription'));
// Payouts API
app.use('/api/payouts', require('./routes/payouts'));
// Social token gating endpoints
app.use('/api/social-token', createSocialTokenRoutes());
// Global stats endpoints
app.use('/api/global-stats', createGlobalStatsRouter({ database, globalStatsService }));
// Creator collaboration endpoints
app.use('/api/collaborations', createCollaborationRoutes());
// Subdomain management endpoints
app.use('/api/subdomains', createSubdomainRoutes({ database, config, subdomainService, sslCertificateService }));
// Price feed endpoints
const createPriceRouter = require('./routes/price');
app.use('/api/price-feed', createPriceRouter());
// Social token gating endpoints
app.use('/api/social-token', createSocialTokenRoutes());
app.use((req, res, next) => {
req.config = config;
req.database = database;
req.subscriptionVerifier = subscriptionVerifier;
next();
});
// Leaky-bucket rate limiting per wallet address (requires Redis).
if (dependencies.rateLimiter) {
app.use('/api', dependencies.rateLimiter);
} else if (process.env.REDIS_URL || process.env.REDIS_HOST) {
app.use('/api', createRateLimiter({
redis: getRedisClient(),
bucketCapacity: Number(process.env.RATE_LIMIT_CAPACITY || 60),
leakRatePerSecond: Number(process.env.RATE_LIMIT_LEAK_RATE || 1),
blockDurationSeconds: Number(process.env.RATE_LIMIT_BLOCK_SECONDS || 300),
sybilThreshold: Number(process.env.SYBIL_THRESHOLD || 3),
}));
}
// ── Health / root ──────────────────────────────────────────────────────────
app.get('/', (req, res) => {
res.json({
project: 'SubStream Protocol',
status: 'Active',
contract: config.soroban.contractId,
version: '1.0.0',
endpoints: {
auth: '/auth',
content: '/content',
analytics: '/analytics',
storage: '/storage',
posts: '/posts',
health: '/health',
},
});
});
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
version: '1.0.0',
services: {
auth: 'active',
content: 'active',
analytics: 'active',
storage: 'active',
posts: 'active',
},
});
});
// ── Auth routes ────────────────────────────────────────────────────────────
app.use('/auth', require('./routes/auth'));
app.use('/auth', require('./routes/stellarAuth'));
// ── Tier-gated content routes ──────────────────────────────────────────────
// attachTier already ran globally; routes/content.js uses requireTier
// on individual endpoints as needed.
app.use('/content', require('./routes/content'));
// ── Other feature routes ───────────────────────────────────────────────────
app.use('/analytics', require('./routes/analytics'));
app.use('/storage', require('./routes/storage'));
app.use('/posts', require('./routes/posts'));
// ── CDN token endpoints ────────────────────────────────────────────────────
app.post('/api/cdn/token', async (req, res) => {
const requiredFields = ['walletAddress', 'creatorAddress', 'contentId', 'segmentPath'];
const missingFields = requiredFields.filter((field) => !req.body?.[field]);
if (missingFields.length > 0) {
return res.status(400).json({ error: 'Missing required fields', missingFields });
}
try {
const accessRequest = {
walletAddress: req.body.walletAddress,
creatorAddress: req.body.creatorAddress,
contentId: req.body.contentId,
segmentPath: req.body.segmentPath,
};
// Check if content requires social token gating
const socialTokenService = req.app.get('socialTokenService');
let socialTokenAccess = null;
if (socialTokenService) {
socialTokenAccess = await socialTokenService.checkContentAccess(
accessRequest.walletAddress,
accessRequest.contentId
);
// If social token gating is required and access is denied, return error
if (socialTokenAccess.requiresToken && !socialTokenAccess.hasAccess) {
return res.status(403).json({
error: 'Social token requirements not met',
code: 'INSUFFICIENT_SOCIAL_TOKENS',
details: {
assetCode: socialTokenAccess.assetCode,
assetIssuer: socialTokenAccess.assetIssuer,
minimumBalance: socialTokenAccess.minimumBalance,
reason: socialTokenAccess.reason
}
});
}
}
// Verify subscription (existing logic)
const subscription = await subscriptionVerifier.verifySubscription(accessRequest);
if (!subscription.active) {
return res.status(403).json({
error: 'Active on-chain subscription required',
creatorAddress: accessRequest.creatorAddress,
contentId: accessRequest.contentId,
});
}
// Issue token with social token metadata if applicable
const tokenData = {
walletAddress: accessRequest.walletAddress,
creatorAddress: accessRequest.creatorAddress,
contentId: accessRequest.contentId,
segmentPath: accessRequest.segmentPath,
subscription,
};
// Add social token session info if required
if (socialTokenAccess && socialTokenAccess.requiresToken && socialTokenAccess.hasAccess) {
const sessionData = await socialTokenService.startBalanceReverification(
null, // Will generate session ID
accessRequest.walletAddress,
accessRequest.contentId
);
tokenData.socialTokenSession = {
sessionId: sessionData.sessionId,
verificationInterval: socialTokenAccess.verificationInterval,
assetInfo: {
code: socialTokenAccess.assetCode,
issuer: socialTokenAccess.assetIssuer,
minimumBalance: socialTokenAccess.minimumBalance
}
};
}
const issuedToken = tokenService.issueToken(tokenData);
return res.status(200).json({
token: issuedToken.token,
tokenType: 'Bearer',
expiresInSeconds: issuedToken.expiresInSeconds,
expiresAt: issuedToken.expiresAt,
playbackUrl: tokenService.buildPlaybackUrl({
contentId: accessRequest.contentId,
segmentPath: accessRequest.segmentPath,
token: issuedToken.token,
}),
socialTokenSession: tokenData.socialTokenSession || null
});
} catch (error) {
return res.status(error.statusCode || 503).json({
error: error.message || 'Unable to verify subscription',
});
}
});
app.all('/api/cdn/validate', (req, res) => {
const token = extractToken(req);
if (!token) {
return res.status(400).json({ error: 'Missing CDN access token' });
}
try {
const decoded = tokenService.verifyToken(token, {
contentId: req.query.contentId || req.body?.contentId,
segmentPath: req.query.segmentPath || req.body?.segmentPath,
});
return res.status(200).json({
valid: true,
expiresAt: new Date(decoded.exp * 1000).toISOString(),
claims: {
walletAddress: decoded.sub,
creatorAddress: decoded.creatorAddress,
contentId: decoded.contentId,
segmentPath: decoded.segmentPath,
},
});
} catch (error) {
const statusCode = error instanceof TokenValidationError ? 401 : 400;
return res.status(statusCode).json({
valid: false,
error: error.message || 'Invalid CDN access token',
});
}
});
// ── Creator action endpoints ───────────────────────────────────────────────
app.patch(
'/api/creator/flow-rate',
requireCreatorAuth(creatorAuthService),
async (req, res) => {
if (!isPresent(req.body?.flowRate)) {
return res.status(400).json({ success: false, error: 'flowRate is required' });
}
try {
const result = creatorActionService.updateFlowRate({
creatorId: req.creator.id,
flowRate: normalizeScalar(req.body.flowRate),
currency: isPresent(req.body.currency) ? String(req.body.currency) : null,
ipAddress: getRequestIp(req),
});
return res.status(200).json({ success: true, data: result });
} catch (error) {
return handleActionError(res, error);
}
},
);
app.patch(
'/api/creator/videos/:videoId/visibility',
requireCreatorAuth(creatorAuthService),
async (req, res) => {
if (!isPresent(req.body?.visibility)) {
return res.status(400).json({ success: false, error: 'visibility is required' });
}
try {
const result = creatorActionService.updateVideoVisibility({
creatorId: req.creator.id,
videoId: req.params.videoId,
visibility: String(req.body.visibility),
ipAddress: getRequestIp(req),
});
return res.status(200).json({ success: true, data: result });
} catch (error) {
return handleActionError(res, error);
}
},
);
app.patch(
'/api/creator/coop-splits/:splitId',
requireCreatorAuth(creatorAuthService),
async (req, res) => {
if (!req.body?.splits || !Array.isArray(req.body.splits) || req.body.splits.length === 0) {
return res
.status(400)
.json({ success: false, error: 'splits must be a non-empty array' });
}
try {
const result = creatorActionService.updateCoopSplit({
creatorId: req.creator.id,
splitId: req.params.splitId,
splits: req.body.splits,
ipAddress: getRequestIp(req),
});
return res.status(200).json({ success: true, data: result });
} catch (error) {
return handleActionError(res, error);
}
},
);
app.get(
'/api/creator/audit-log',
requireCreatorAuth(creatorAuthService),
(req, res) => {
const logs = auditLogService.listByCreatorId(req.creator.id);
return res.status(200).json({ success: true, data: logs });
},
);
app.get(
'/api/creator/audit-log/export',
requireCreatorAuth(creatorAuthService),
(req, res) => {
const format = String(req.query.format || '').toLowerCase();
// Get creator stats (including cached subscriber count)
app.get('/api/creator/:id/stats', (req, res) => {
try {
const creatorId = req.params.id;
const subscriberCount = database.getCreatorSubscriberCount(creatorId);
return res.status(200).json({ success: true, data: { creatorId, subscriberCount } });
} catch (error) {
return res.status(500).json({ success: false, error: error.message || 'Failed to fetch stats' });
}
});
app.get('/api/creator/audit-log/export', requireCreatorAuth(creatorAuthService), (req, res) => {
const format = String(req.query.format || '').toLowerCase();
if (!['csv', 'pdf'].includes(format)) {
return res.status(400).json({ success: false, error: 'format must be one of: csv, pdf' });
}
const logs = auditLogService.listByCreatorId(req.creator.id);
const exportTimestamp = new Date().toISOString();
if (format === 'csv') {
const csv = buildAuditLogCsv(logs);
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
res.setHeader(
'Content-Disposition',
`attachment; filename="creator-audit-log-${req.creator.id}.csv"`,
);
return res.status(200).send(csv);
}
const pdf = buildAuditLogPdf({
creatorId: req.creator.id,
exportedAt: exportTimestamp,
logs,
});
res.setHeader('Content-Type', 'application/pdf');
res.setHeader(
'Content-Disposition',
`attachment; filename="creator-audit-log-${req.creator.id}.pdf"`,
);
return res.status(200).send(pdf);
},
);
// ── Error handlers ─────────────────────────────────────────────────────────
app.use((err, req, res, next) => {
console.error('Unhandled error:', err);
res.status(500).json({ success: false, error: 'Internal server error' });
});
app.use((req, res) => {
res.status(404).json({ success: false, error: 'Endpoint not found' });
app.use('/api/videos', createVideoRoutes(config, database, videoWorker));
// Device fingerprinting endpoints for fraud prevention
if (process.env.REDIS_URL || process.env.REDIS_HOST) {
const deviceService = new DeviceFingerprintService(getRedisClient());
app.set('deviceFingerprintService', deviceService);
app.use('/api/device', createDeviceRoutes);
}
// API Documentation with Swagger UI
app.use('/api/docs', createSwaggerRoutes);
// IP Intelligence management routes
if (ipIntelligenceService) {
app.use('/api/ip-intelligence', createIPIntelligenceRoutes({
ipIntelligenceService,
ipBlockingService,
ipMonitoringService
}));
}
// Behavioral biometric management routes
if (behavioralService) {
app.use('/api/behavioral', createBehavioralBiometricRoutes({
behavioralService
}));
}
// Health check endpoint
app.get('/health', async (req, res) => {
const health = {
status: 'Healthy',
timestamp: new Date().toISOString(),
version: '1.0.0',
services: {
database: 'Unknown',
redis: 'Unknown',
rabbitmq: 'Unknown',
stellar: 'Unknown',
ipIntelligence: 'Unknown',
behavioralBiometric: 'Unknown'
},
};
let isDegraded = false;
// Check Database
try {
database.db.prepare('SELECT 1').get();
health.services.database = 'Connected';
} catch (error) {
health.services.database = 'Offline';
isDegraded = true;
}
// Check Redis
try {
if (process.env.REDIS_URL || process.env.REDIS_HOST) {
const redisClient = getRedisClient();
const ping = await redisClient.ping();
health.services.redis = ping === 'PONG' ? 'Connected' : 'Offline';
if (ping !== 'PONG') isDegraded = true;
} else {
health.services.redis = 'Not Configured';
}
} catch (error) {
health.services.redis = 'Offline';
isDegraded = true;
}
// Check RabbitMQ
try {
if (backgroundWorker && backgroundWorker.rabbitmq) {
const status = backgroundWorker.getStatus();
health.services.rabbitmq = status.connected ? 'Connected' : 'Offline';
if (!status.connected) isDegraded = true;
} else {
health.services.rabbitmq = 'Not Configured';
}
} catch (error) {
health.services.rabbitmq = 'Offline';
isDegraded = true;
}
// Check Stellar/Soroban
try {
if (subscriptionVerifier && subscriptionVerifier.server) {
await subscriptionVerifier.server.getLatestLedger();
health.services.stellar = 'Connected';
} else {
health.services.stellar = 'Not Configured';
}
} catch (error) {
health.services.stellar = 'Offline';
isDegraded = true;
}
// Check IP Intelligence
try {
if (ipIntelligenceService) {
const stats = ipIntelligenceService.getServiceStats();
health.services.ipIntelligence = 'Running';
} else {
health.services.ipIntelligence = 'Not Configured';
}
} catch (error) {
health.services.ipIntelligence = 'Error';
isDegraded = true;
}
// Check Behavioral Biometric
try {
if (behavioralService) {
const stats = behavioralService.getServiceStats();
health.services.behavioralBiometric = 'Running';
} else {
health.services.behavioralBiometric = 'Not Configured';
}
} catch (error) {
health.services.behavioralBiometric = 'Error';
isDegraded = true;
}
if (isDegraded) {
health.status = 'Degraded';
}
return res.status(isDegraded ? 200 : 200).json(health); // Reporting degraded status still returns 200 for status page transparency
});
app.use((req, res) => res.status(404).json({ success: false, error: 'Not found' }));
// Global error handler with Sentry integration
app.use((err, req, res, next) => {
// Log error with structured logging
const errorContext = {
traceId: req.logger?.fields?.traceId,
method: req.method,
path: req.path,
walletAddress: req.user?.publicKey || req.body?.walletAddress,
endpoint: req.originalUrl,
};
// Capture with Sentry
errorTracking.captureException(err, errorContext);
// Return error response
res.status(err.statusCode || err.status || 500).json({
success: false,
error: process.env.NODE_ENV === 'production'
? 'Internal server error'
: err.message,
...(process.env.NODE_ENV !== 'production' && { stack: err.stack }),
});
});
return app;
}
// ── Private helpers ────────────────────────────────────────────────────────
function extractToken(req) {
const authHeader = req.headers.authorization || '';
if (authHeader.startsWith('Bearer ')) return authHeader.slice('Bearer '.length).trim();
return req.query.token || req.body?.token || null;
}
function requireCreatorAuth(creatorAuthService) {
return (req, res, next) => {
const token = extractToken(req);
if (!token) {
return res.status(401).json({ success: false, error: 'Authentication required' });
}
try {
req.creator = creatorAuthService.verifyToken(token);
return next();
} catch (error) {
return res.status(401).json({ success: false, error: error.message });
}
};
}
function normalizeScalar(value) {
return String(value).trim();
}
function isPresent(value) {
return value !== undefined && value !== null && String(value).trim() !== '';
}
function handleActionError(res, error) {
return res
.status(error.statusCode || 500)
.json({ success: false, error: error.message || 'Request failed' });
}
// ── Bootstrap ──────────────────────────────────────────────────────────────
const app = createApp();
const port = Number(process.env.PORT || 3000);
if (require.main === module) {
app.listen(port, () => {
console.log(`SubStream API running on port ${port}`);
console.log(`Health check: http://localhost:${port}/health`);
});
}
module.exports = app;
module.exports.createApp = createApp;
module.exports.createApp = createApp;