-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
788 lines (684 loc) · 20.7 KB
/
Copy pathdatabase.js
File metadata and controls
788 lines (684 loc) · 20.7 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
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const DB_FILE = path.join(__dirname, 'db.json');
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || 'leadforge_secure_aes_encryption_key_2026';
const IV_LENGTH = 16;
/**
* Encrypt credential secrets using AES-256-CBC
*/
function encrypt(text) {
if (!text) return '';
const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
/**
* Decrypt credential secrets using AES-256-CBC
*/
function decrypt(text) {
if (!text) return '';
try {
const parts = text.split(':');
const iv = Buffer.from(parts.shift(), 'hex');
const encryptedText = Buffer.from(parts.join(':'), 'hex');
const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (err) {
console.error('[Decrypt Error]', err.message);
return '';
}
}
// Default initial database state
const DEFAULT_STATE = {
users: [
{
id: 'admin-session-id',
email: 'admin@leadforge.ai',
password: bcrypt.hashSync('admin123', 10),
role: 'admin',
isPaid: true,
credits: 99999,
leadsFoundCount: 150,
auditsCompletedCount: 42,
emailsGeneratedCount: 30,
searchesTodayCount: 0,
lastSearchDate: new Date().toISOString().split('T')[0]
}
],
transactions: [],
searches: [],
crmLeads: [],
connectedAccounts: [],
campaigns: [],
drafts: [],
auditLogs: [],
contacts: []
};
// Memory cache
let dbState = null;
/**
* Load database from disk
*/
function loadDb() {
if (dbState) return dbState;
try {
if (!fs.existsSync(DB_FILE)) {
saveDb(DEFAULT_STATE);
dbState = JSON.parse(JSON.stringify(DEFAULT_STATE));
return dbState;
}
const data = fs.readFileSync(DB_FILE, 'utf8');
dbState = JSON.parse(data);
// Auto-migrate schema
if (!dbState.crmLeads) dbState.crmLeads = [];
if (!dbState.connectedAccounts) dbState.connectedAccounts = [];
if (!dbState.campaigns) dbState.campaigns = [];
if (!dbState.drafts) dbState.drafts = [];
if (!dbState.auditLogs) dbState.auditLogs = [];
if (!dbState.contacts) dbState.contacts = [];
// Ensure existing users have stats fields
dbState.users.forEach(u => {
if (u.leadsFoundCount === undefined) u.leadsFoundCount = 0;
if (u.auditsCompletedCount === undefined) u.auditsCompletedCount = 0;
if (u.emailsGeneratedCount === undefined) u.emailsGeneratedCount = 0;
if (u.searchesTodayCount === undefined) u.searchesTodayCount = 0;
if (u.lastSearchDate === undefined) u.lastSearchDate = '';
});
return dbState;
} catch (error) {
console.error('[DB Error] Failed to read database, resetting to default:', error.message);
dbState = JSON.parse(JSON.stringify(DEFAULT_STATE));
return dbState;
}
}
/**
* Save database atomically to disk
*/
function saveDb(state) {
try {
const tempFile = DB_FILE + '.tmp';
const jsonStr = JSON.stringify(state, null, 2);
fs.writeFileSync(tempFile, jsonStr, 'utf8');
fs.renameSync(tempFile, DB_FILE);
} catch (error) {
console.error('[DB Error] Failed to save database atomically:', error.message);
}
}
/**
* Verify input password against stored hash or plain password
*/
function verifyPassword(inputPassword, storedPassword) {
if (!inputPassword || !storedPassword) return false;
if (storedPassword.startsWith('$2a$') || storedPassword.startsWith('$2b$')) {
try {
return bcrypt.compareSync(inputPassword, storedPassword);
} catch (e) {
return false;
}
}
return inputPassword === storedPassword;
}
/**
* Find user by email
*/
function findUserByEmail(email) {
const state = loadDb();
return state.users.find(u => u.email.toLowerCase() === email.toLowerCase());
}
/**
* Find user by session/token ID
*/
function findUserById(id) {
const state = loadDb();
return state.users.find(u => u.id === id);
}
/**
* Update user password with bcrypt hashing
*/
function updateUserPassword(id, newPassword) {
const state = loadDb();
const user = state.users.find(u => u.id === id);
if (!user) return { success: false, message: 'User not found.' };
user.password = bcrypt.hashSync(newPassword, 10);
saveDb(state);
return { success: true };
}
/**
* Register a new user with hashed password and optional referral credits
*/
function registerUser(email, password, referrerId = null) {
const state = loadDb();
if (findUserByEmail(email)) {
return { success: false, message: 'Email already registered.' };
}
const hashedPassword = bcrypt.hashSync(password, 10);
const newUser = {
id: 'user_' + Math.random().toString(36).substr(2, 9),
email: email.trim(),
password: hashedPassword,
role: 'user',
isPaid: false,
credits: 3,
leadsFoundCount: 0,
auditsCompletedCount: 0,
emailsGeneratedCount: 0,
searchesTodayCount: 0,
lastSearchDate: new Date().toISOString().split('T')[0]
};
if (referrerId) {
const referrer = state.users.find(u => u.id === referrerId || u.email.toLowerCase() === referrerId.trim().toLowerCase());
if (referrer) {
if (!referrer.isPaid) {
referrer.credits += 5;
}
newUser.referredBy = referrer.id;
}
}
state.users.push(newUser);
saveDb(state);
return { success: true, user: newUser };
}
/**
* Submit a UPI Transaction (UTR) for approval
*/
function submitTransaction(userId, utr, amount, plan) {
const state = loadDb();
const user = state.users.find(u => u.id === userId);
if (!user) {
return { success: false, message: 'User not found.' };
}
const exists = state.transactions.find(t => t.utr === utr.trim());
if (exists) {
return { success: false, message: 'This Transaction ID (UTR) has already been submitted.' };
}
const transaction = {
id: 'tx_' + Math.random().toString(36).substr(2, 9),
userId: user.id,
email: user.email,
utr: utr.trim(),
amount: parseFloat(amount),
plan: plan,
status: 'pending',
timestamp: new Date().toISOString()
};
state.transactions.push(transaction);
saveDb(state);
return { success: true, transaction };
}
/**
* Approve a transaction (Admin only)
*/
function approveTransaction(txId) {
const state = loadDb();
const tx = state.transactions.find(t => t.id === txId);
if (!tx) {
return { success: false, message: 'Transaction not found.' };
}
tx.status = 'approved';
const user = state.users.find(u => u.id === tx.userId);
if (user) {
user.isPaid = true;
user.credits = 99999;
}
saveDb(state);
return { success: true, transaction: tx };
}
/**
* Reject a transaction (Admin only)
*/
function rejectTransaction(txId) {
const state = loadDb();
const tx = state.transactions.find(t => t.id === txId);
if (!tx) {
return { success: false, message: 'Transaction not found.' };
}
tx.status = 'rejected';
saveDb(state);
return { success: true, transaction: tx };
}
/**
* Deduct 1 search credit from user
*/
function deductCredit(userId) {
const state = loadDb();
const user = state.users.find(u => u.id === userId);
if (!user) return false;
if (user.isPaid) return true;
if (user.credits <= 0) return false;
user.credits -= 1;
saveDb(state);
return true;
}
/**
* Increments specific user stats
*/
function incrementUserStat(userId, field, val = 1) {
const state = loadDb();
const user = state.users.find(u => u.id === userId);
if (user && user[field] !== undefined) {
user[field] += val;
saveDb(state);
return true;
}
return false;
}
/**
* Validates and resets daily search statistics counters
*/
function checkAndResetDailySearches(userId) {
const state = loadDb();
const user = state.users.find(u => u.id === userId);
if (!user) return 0;
const today = new Date().toISOString().split('T')[0];
if (user.lastSearchDate !== today) {
user.lastSearchDate = today;
user.searchesTodayCount = 0;
saveDb(state);
}
return user.searchesTodayCount;
}
/**
* Save audit/search results history
*/
function saveSearchResult(userId, query, leads) {
const state = loadDb();
const newSearch = {
id: 'search_' + Math.random().toString(36).substr(2, 9),
userId,
query,
leads,
timestamp: new Date().toISOString()
};
state.searches.push(newSearch);
if (state.searches.length > 50) {
state.searches.shift();
}
saveDb(state);
return newSearch;
}
/**
* Get search history for a user
*/
function getUserSearches(userId) {
const state = loadDb();
return state.searches.filter(s => s.userId === userId).map(s => ({
id: s.id,
query: s.query,
leadsCount: s.leads.length,
timestamp: s.timestamp
}));
}
/**
* Get a specific saved search result
*/
function getSearchResult(searchId) {
const state = loadDb();
return state.searches.find(s => s.id === searchId);
}
/**
* Admin: Get all transactions
*/
function getAllTransactions() {
const state = loadDb();
return state.transactions;
}
// --- CRM OPPORTUNITY LOGIC ---
function saveCrmLead(userId, leadData) {
const state = loadDb();
const cleanUrl = leadData.url.toLowerCase();
const exists = state.crmLeads.find(l => l.userId === userId && l.url.toLowerCase() === cleanUrl);
if (exists) {
return { success: false, message: 'This lead has already been saved to your pipeline CRM.' };
}
const newCrmLead = {
id: 'crm_' + Math.random().toString(36).substr(2, 9),
userId,
title: leadData.title || 'Unknown Business',
url: leadData.url,
industry: leadData.industry || 'Local Business',
city: leadData.city || 'Local',
email: leadData.emails ? leadData.emails[0] || '' : leadData.email || '',
phone: leadData.phones ? leadData.phones[0] || '' : leadData.phone || '',
status: 'New',
notes: '',
followUpDate: '',
lastContact: '',
priority: 'Medium',
isFavorite: false,
projectValue: leadData.ai ? leadData.ai.estimatedProjectValueInr || 15000 : 15000,
timestamp: new Date().toISOString()
};
state.crmLeads.push(newCrmLead);
saveDb(state);
return { success: true, lead: newCrmLead };
}
function getCrmLeads(userId) {
const state = loadDb();
return state.crmLeads.filter(l => l.userId === userId);
}
function updateCrmLead(userId, leadId, updates) {
const state = loadDb();
const lead = state.crmLeads.find(l => l.id === leadId && l.userId === userId);
if (!lead) {
return { success: false, message: 'Lead not found in your pipeline CRM.' };
}
const allowedUpdates = ['status', 'notes', 'followUpDate', 'lastContact', 'priority', 'isFavorite', 'projectValue', 'email', 'phone', 'ai', 'audit'];
allowedUpdates.forEach(key => {
if (updates[key] !== undefined) {
lead[key] = updates[key];
}
});
saveDb(state);
return { success: true, lead };
}
function deleteCrmLead(userId, leadId) {
const state = loadDb();
const index = state.crmLeads.findIndex(l => l.id === leadId && l.userId === userId);
if (index === -1) {
return { success: false, message: 'Lead not found in CRM.' };
}
state.crmLeads.splice(index, 1);
saveDb(state);
return { success: true };
}
/**
* Redeem promo coupon code
*/
function applyCoupon(userId, code) {
const state = loadDb();
const user = state.users.find(u => u.id === userId);
if (!user) {
return { success: false, message: 'User account not found.' };
}
const cleanCode = code.trim().toUpperCase();
if (cleanCode === 'FREE100') {
user.credits += 100;
saveDb(state);
return {
success: true,
message: 'Coupon applied! 100 search credits added to your account.',
user: { id: user.id, isPaid: user.isPaid, credits: user.credits }
};
} else if (cleanCode === 'VIP99') {
user.isPaid = true;
user.credits = 99999;
saveDb(state);
return {
success: true,
message: 'VIP Coupon applied! Upgraded to Lifetime Premium.',
user: { id: user.id, isPaid: user.isPaid, credits: user.credits }
};
} else {
return { success: false, message: 'Invalid or expired coupon code.' };
}
}
// --- SECURE OAUTH & ACCOUNT INTEGRATION LEDGERS ---
function saveConnectedAccount(userId, platform, accountData) {
const state = loadDb();
// Encrypt sensitive access and refresh tokens
const encryptedAccessToken = encrypt(accountData.accessToken);
const encryptedRefreshToken = encrypt(accountData.refreshToken);
const existingIndex = state.connectedAccounts.findIndex(
a => a.userId === userId && a.platform === platform && a.username.toLowerCase() === accountData.username.toLowerCase()
);
const accountInfo = {
id: accountData.id || 'acc_' + Math.random().toString(36).substr(2, 9),
userId,
platform,
username: accountData.username,
email: accountData.email || '',
encryptedAccessToken,
encryptedRefreshToken,
expiresAt: accountData.expiresAt || (Date.now() + 3600 * 1000), // Default 1 hour
profile: accountData.profile || {},
timestamp: new Date().toISOString()
};
if (existingIndex !== -1) {
state.connectedAccounts[existingIndex] = accountInfo;
} else {
state.connectedAccounts.push(accountInfo);
}
saveDb(state);
return accountInfo;
}
function getConnectedAccounts(userId) {
const state = loadDb();
return state.connectedAccounts.filter(a => a.userId === userId).map(account => {
// Decrypt on demand, return structured decrypted object for integration handlers
return {
id: account.id,
platform: account.platform,
username: account.username,
email: account.email,
accessToken: decrypt(account.encryptedAccessToken),
refreshToken: decrypt(account.encryptedRefreshToken),
expiresAt: account.expiresAt,
profile: account.profile
};
});
}
function deleteConnectedAccount(userId, accountId) {
const state = loadDb();
const index = state.connectedAccounts.findIndex(a => a.id === accountId && a.userId === userId);
if (index === -1) {
return { success: false, message: 'Connected account not found.' };
}
state.connectedAccounts.splice(index, 1);
saveDb(state);
return { success: true };
}
// --- OUTREACH CAMPAIGNS & DRAFTS LEDGERS ---
function saveCampaign(userId, campaignData) {
const state = loadDb();
const campaign = {
id: campaignData.id || 'camp_' + Math.random().toString(36).substr(2, 9),
userId,
name: campaignData.name,
platform: campaignData.platform, // 'reddit' | 'email' | 'indiehackers'
status: campaignData.status || 'Active', // 'Active' | 'Paused' | 'Completed'
settings: campaignData.settings || {},
timestamp: new Date().toISOString()
};
const existingIndex = state.campaigns.findIndex(c => c.id === campaign.id && c.userId === userId);
if (existingIndex !== -1) {
state.campaigns[existingIndex] = campaign;
} else {
state.campaigns.push(campaign);
}
saveDb(state);
return campaign;
}
function getCampaigns(userId) {
const state = loadDb();
return state.campaigns.filter(c => c.userId === userId);
}
function saveDraft(userId, draftData) {
const state = loadDb();
const draft = {
id: draftData.id || 'draft_' + Math.random().toString(36).substr(2, 9),
userId,
campaignId: draftData.campaignId || '',
platform: draftData.platform, // 'reddit' | 'email' | 'indiehackers'
status: draftData.status || 'Draft', // 'Draft' | 'Scheduled' | 'Approved' | 'Sent'
title: draftData.title || '',
body: draftData.body || '',
scheduledAt: draftData.scheduledAt || '', // ISO Timestamp
sentAt: draftData.sentAt || '',
metadata: draftData.metadata || {}, // Reddit subreddits, email targets, etc.
timestamp: new Date().toISOString()
};
const existingIndex = state.drafts.findIndex(d => d.id === draft.id && d.userId === userId);
if (existingIndex !== -1) {
state.drafts[existingIndex] = draft;
} else {
state.drafts.push(draft);
}
saveDb(state);
return draft;
}
function getDrafts(userId, platform = null) {
const state = loadDb();
let results = state.drafts.filter(d => d.userId === userId);
if (platform) {
results = results.filter(d => d.platform === platform);
}
return results;
}
function updateDraft(userId, draftId, updates) {
const state = loadDb();
const draft = state.drafts.find(d => d.id === draftId && d.userId === userId);
if (!draft) {
return { success: false, message: 'Draft not found.' };
}
const allowedUpdates = ['status', 'title', 'body', 'scheduledAt', 'sentAt', 'metadata', 'campaignId'];
allowedUpdates.forEach(key => {
if (updates[key] !== undefined) {
draft[key] = updates[key];
}
});
saveDb(state);
return { success: true, draft };
}
function deleteDraft(userId, draftId) {
const state = loadDb();
const index = state.drafts.findIndex(d => d.id === draftId && d.userId === userId);
if (index === -1) {
return { success: false, message: 'Draft not found.' };
}
state.drafts.splice(index, 1);
saveDb(state);
return { success: true };
}
// --- SECURE SECURITY AUDIT LOGGING ---
function writeAuditLog(userId, action, status, details = {}) {
const state = loadDb();
const log = {
id: 'log_' + Math.random().toString(36).substr(2, 9),
timestamp: new Date().toISOString(),
userId: userId || 'anonymous',
action, // e.g. 'USER_LOGIN', 'CREDITS_DEBIT', 'UTR_SUBMIT', 'REDDIT_OAUTH_CONNECT'
status, // 'success' | 'failure' | 'warning'
details // additional metadata
};
state.auditLogs.push(log);
// Cap logs size to prevent file bloat
if (state.auditLogs.length > 500) {
state.auditLogs.shift();
}
saveDb(state);
return log;
}
function getAuditLogs(userId) {
const state = loadDb();
// Admins get all logs, users get their own logs
const user = state.users.find(u => u.id === userId);
if (user && user.role === 'admin') {
return state.auditLogs;
}
return state.auditLogs.filter(l => l.userId === userId);
}
// --- CONTACTS MANAGEMENT (EMAIL OUTREACH) ---
function saveContact(userId, contactData) {
const state = loadDb();
const contact = {
id: contactData.id || 'con_' + Math.random().toString(36).substr(2, 9),
userId,
email: contactData.email.trim().toLowerCase(),
name: contactData.name || '',
phone: contactData.phone || '',
company: contactData.company || '',
status: contactData.status || 'Active', // 'Active' | 'Unsubscribed' | 'Bounced'
notes: contactData.notes || '',
timestamp: new Date().toISOString()
};
const existingIndex = state.contacts.findIndex(c => c.email === contact.email && c.userId === userId);
if (existingIndex !== -1) {
state.contacts[existingIndex] = contact;
} else {
state.contacts.push(contact);
}
saveDb(state);
return contact;
}
function getContacts(userId) {
const state = loadDb();
return state.contacts.filter(c => c.userId === userId);
}
function updateContact(userId, contactId, updates) {
const state = loadDb();
const contact = state.contacts.find(c => c.id === contactId && c.userId === userId);
if (!contact) {
return { success: false, message: 'Contact not found.' };
}
const allowedUpdates = ['name', 'phone', 'company', 'status', 'notes'];
allowedUpdates.forEach(key => {
if (updates[key] !== undefined) {
contact[key] = updates[key];
}
});
saveDb(state);
return { success: true, contact };
}
function deleteContact(userId, contactId) {
const state = loadDb();
const index = state.contacts.findIndex(c => c.id === contactId && c.userId === userId);
if (index === -1) {
return { success: false, message: 'Contact not found.' };
}
state.contacts.splice(index, 1);
saveDb(state);
return { success: true };
}
module.exports = {
loadDb,
saveDb,
findUserByEmail,
findUserById,
registerUser,
verifyPassword,
updateUserPassword,
submitTransaction,
approveTransaction,
rejectTransaction,
deductCredit,
incrementUserStat,
checkAndResetDailySearches,
saveSearchResult,
getUserSearches,
getSearchResult,
getAllTransactions,
applyCoupon,
// CRM Exports
saveCrmLead,
getCrmLeads,
updateCrmLead,
deleteCrmLead,
// Integrations Account Exports
saveConnectedAccount,
getConnectedAccounts,
deleteConnectedAccount,
// Campaigns & Drafts Exports
saveCampaign,
getCampaigns,
saveDraft,
getDrafts,
updateDraft,
deleteDraft,
// Secure Audit Logs Exports
writeAuditLog,
getAuditLogs,
// Contacts Exports
saveContact,
getContacts,
updateContact,
deleteContact
};