-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
2033 lines (1797 loc) · 86.2 KB
/
server.ts
File metadata and controls
2033 lines (1797 loc) · 86.2 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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import { createServer } from "http";
import { WebSocketServer, WebSocket } from "ws";
import Database from "better-sqlite3";
import bcrypt from "bcryptjs";
import { createServer as createViteServer } from "vite";
import path from "path";
import { fileURLToPath } from "url";
import fs from "fs";
import archiver from "archiver";
import crypto from "crypto";
// @ts-ignore
import nodemailer from 'nodemailer';
// @ts-ignore
import PDFDocument from 'pdfkit';
import os from 'os';
import { promisify } from 'util';
import { lookup as dnsLookup } from 'dns/promises';
const writeFile = promisify(fs.writeFile);
const SMTP_CONNECTION_TIMEOUT_MS = Number(process.env.SMTP_CONNECTION_TIMEOUT_MS || 8000);
const SMTP_GREETING_TIMEOUT_MS = Number(process.env.SMTP_GREETING_TIMEOUT_MS || 8000);
const SMTP_SOCKET_TIMEOUT_MS = Number(process.env.SMTP_SOCKET_TIMEOUT_MS || 12000);
function withSmtpTimeouts(config: any) {
return {
...config,
connectionTimeout: Number(config?.connectionTimeout || SMTP_CONNECTION_TIMEOUT_MS),
greetingTimeout: Number(config?.greetingTimeout || SMTP_GREETING_TIMEOUT_MS),
socketTimeout: Number(config?.socketTimeout || SMTP_SOCKET_TIMEOUT_MS),
};
}
function shouldRetryWithIpv4(err: any, host: unknown) {
if (typeof host !== 'string' || host.trim().length === 0) return false;
const code = String(err?.code || '').toUpperCase();
const address = String(err?.address || '');
const message = String(err?.message || '').toUpperCase();
const ipv6AddressUsed = address.includes(':') || message.includes(':::0');
return (code === 'ENETUNREACH' || code === 'EHOSTUNREACH') && ipv6AddressUsed;
}
async function sendMailWithFallback(smtpConfig: any, message: any) {
const baseConfig = withSmtpTimeouts(smtpConfig);
try {
const transporter = nodemailer.createTransport(baseConfig as any);
await transporter.sendMail(message);
return;
} catch (err) {
if (!shouldRetryWithIpv4(err, baseConfig?.host)) throw err;
const host = String(baseConfig.host);
const lookup = await dnsLookup(host, { family: 4 });
const fallbackConfig = {
...baseConfig,
host: lookup.address,
tls: {
...(baseConfig?.tls || {}),
servername: host,
},
};
const transporter = nodemailer.createTransport(fallbackConfig as any);
await transporter.sendMail(message);
}
}
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const TENANT_LOGO_DIR = path.join(__dirname, "tenant-logos");
if (!fs.existsSync(TENANT_LOGO_DIR)) {
fs.mkdirSync(TENANT_LOGO_DIR, { recursive: true });
}
const BILLING_FILES_DIR = path.join(__dirname, "billing-files");
const PAYMENT_PROOFS_DIR = path.join(BILLING_FILES_DIR, "proofs");
const RECEIPTS_DIR = path.join(BILLING_FILES_DIR, "receipts");
const BILLING_QR_DIR = path.join(BILLING_FILES_DIR, "qr");
for (const dir of [BILLING_FILES_DIR, PAYMENT_PROOFS_DIR, RECEIPTS_DIR, BILLING_QR_DIR]) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
const DEFAULT_BRANCHES = [
"Carcar Branch", "Moalboal Branch", "Talisay Branch", "Carbon Branch",
"Solinea Branch", "Mandaue Branch", "Danao Branch", "Bogo Branch", "Capitol Branch",
];
const DEFAULT_SERVICES = [
"Cash/Check Deposit", "Withdrawal", "Account Opening", "Customer Service", "Loans",
];
const VALID_PRIORITIES = new Set(["Regular", "Priority"]);
const VALID_CUSTOMER_TERMS = new Set(["customer", "client", "patient", "citizen"]);
const PLAN_LIMITS: Record<string, { maxBranches: number | null; maxServices: number | null }> = {
free: { maxBranches: 1, maxServices: 5 },
starter: { maxBranches: 9, maxServices: 15 },
pro: { maxBranches: null, maxServices: null },
};
const PLAN_PRICES: Record<string, number> = {
free: 0,
starter: 999,
pro: 2499,
};
async function startServer() {
const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });
// Trust proxy headers so req.ip works correctly behind reverse proxies
app.set("trust proxy", 1);
const PORT = Number(process.env.PORT) || 3000;
server.listen(PORT, "0.0.0.0", () => {
console.log(`Server is live on port ${PORT}`);
if (!process.env.ADMIN_PASSWORD) {
console.warn(`[ADMIN] Warning: Using default admin password. Set ADMIN_EMAIL and ADMIN_PASSWORD env vars for production.`);
}
});
// Allow base64 image payloads for logo/payment proof uploads.
app.use(express.json({ limit: "8mb" }));
app.use("/tenant-logos", express.static(TENANT_LOGO_DIR));
app.use("/billing-files", express.static(BILLING_FILES_DIR));
// ===== DATABASE =====
const db = new Database(path.join(__dirname, "ssb_queue.db"));
db.exec(`
CREATE TABLE IF NOT EXISTS queue (
id TEXT PRIMARY KEY,
tenant_id TEXT DEFAULT 'default',
name TEXT,
branch TEXT,
service TEXT,
priority TEXT,
checkInTime TEXT,
status TEXT,
calledTime TEXT,
completedTime TEXT,
notes TEXT
);
CREATE TABLE IF NOT EXISTS history (
id TEXT PRIMARY KEY,
tenant_id TEXT DEFAULT 'default',
name TEXT,
branch TEXT,
service TEXT,
priority TEXT,
checkInTime TEXT,
status TEXT,
calledTime TEXT,
completedTime TEXT,
notes TEXT
);
CREATE TABLE IF NOT EXISTS ip_whitelist (
ip TEXT PRIMARY KEY,
label TEXT,
addedAt TEXT
);
CREATE TABLE IF NOT EXISTS admin_sessions (
token TEXT PRIMARY KEY,
createdAt TEXT,
user_id TEXT
);
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'tenant_admin',
tenant_id TEXT DEFAULT 'default',
createdAt TEXT,
lastLoginAt TEXT,
reset_token TEXT,
reset_token_expiry TEXT
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
);
CREATE TABLE IF NOT EXISTS tenants (
id TEXT PRIMARY KEY,
name TEXT,
slug TEXT,
settings TEXT,
createdAt TEXT
);
CREATE TABLE IF NOT EXISTS tenant_branches (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
name TEXT NOT NULL,
createdAt TEXT,
UNIQUE(tenant_id, name)
);
CREATE TABLE IF NOT EXISTS tenant_services (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
name TEXT NOT NULL,
createdAt TEXT,
UNIQUE(tenant_id, name)
);
CREATE TABLE IF NOT EXISTS subscriptions (
tenant_id TEXT PRIMARY KEY,
plan TEXT NOT NULL DEFAULT 'free',
status TEXT NOT NULL DEFAULT 'active',
period_start TEXT,
period_end TEXT,
grace_days INTEGER NOT NULL DEFAULT 5,
amount REAL NOT NULL DEFAULT 0,
updatedAt TEXT
);
CREATE TABLE IF NOT EXISTS payment_submissions (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
desired_plan TEXT NOT NULL,
amount REAL NOT NULL DEFAULT 0,
reference_code TEXT,
proof_url TEXT,
status TEXT NOT NULL DEFAULT 'pending',
notes TEXT,
submittedAt TEXT,
reviewedAt TEXT,
reviewed_by TEXT
);
CREATE TABLE IF NOT EXISTS receipts (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
payment_submission_id TEXT,
receipt_no TEXT NOT NULL,
amount REAL NOT NULL DEFAULT 0,
plan TEXT,
period_start TEXT,
period_end TEXT,
pdf_url TEXT,
createdAt TEXT,
created_by TEXT
);
`);
// Ensure tenant columns exist (for older DBs)
const hasColumn = (table: string, col: string) => {
const info = db.prepare(`PRAGMA table_info(${table})`).all() as any[];
return info.some((r) => r.name === col);
};
if (!hasColumn('queue', 'tenant_id')) {
db.prepare(`ALTER TABLE queue ADD COLUMN tenant_id TEXT DEFAULT 'default'`).run();
}
if (!hasColumn('history', 'tenant_id')) {
db.prepare(`ALTER TABLE history ADD COLUMN tenant_id TEXT DEFAULT 'default'`).run();
}
if (!hasColumn('queue', 'notes')) {
db.prepare(`ALTER TABLE queue ADD COLUMN notes TEXT`).run();
}
if (!hasColumn('history', 'notes')) {
db.prepare(`ALTER TABLE history ADD COLUMN notes TEXT`).run();
}
if (!hasColumn('admin_sessions', 'user_id')) {
db.prepare(`ALTER TABLE admin_sessions ADD COLUMN user_id TEXT`).run();
}
if (!hasColumn('users', 'name')) {
db.prepare(`ALTER TABLE users ADD COLUMN name TEXT DEFAULT ''`).run();
}
if (!hasColumn('tenants', 'plan')) {
db.prepare(`ALTER TABLE tenants ADD COLUMN plan TEXT DEFAULT 'free'`).run();
}
// Performance indexes — safe to run repeatedly (IF NOT EXISTS)
db.exec(`CREATE INDEX IF NOT EXISTS idx_history_tenant_completed ON history(tenant_id, completedTime);`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_history_branch_completed ON history(branch, completedTime);`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_queue_tenant_status ON queue(tenant_id, status);`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_tenant_branches_tenant ON tenant_branches(tenant_id, name);`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_tenant_services_tenant ON tenant_services(tenant_id, name);`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_payment_submissions_status ON payment_submissions(status, submittedAt);`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_payment_submissions_tenant ON payment_submissions(tenant_id, submittedAt);`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_receipts_tenant ON receipts(tenant_id, createdAt);`);
// Seed default super_admin user if none exist
const userCount = (db.prepare('SELECT COUNT(1) as c FROM users').get() as any).c as number;
if (userCount === 0) {
const email = process.env.ADMIN_EMAIL || 'admin@ssb.local';
const rawPassword = process.env.ADMIN_PASSWORD || 'SSBAdmin2025!';
const hash = await bcrypt.hash(rawPassword, 12);
db.prepare(
'INSERT INTO users (id, email, password_hash, role, tenant_id, createdAt) VALUES (?, ?, ?, ?, ?, ?)'
).run(crypto.randomUUID(), email, hash, 'super_admin', 'default', new Date().toISOString());
console.log(`[AUTH] Seeded default admin: ${email}`);
}
// Sessions are persistent until explicit logout.
// ===== HELPERS =====
const normalizeIP = (ip: string): string => {
if (!ip) return "";
if (ip === "::1") return "127.0.0.1";
return ip.replace("::ffff:", "");
};
const getClientIP = (req: express.Request): string => {
const forwarded = req.headers["x-forwarded-for"];
const raw = forwarded
? (typeof forwarded === "string" ? forwarded : forwarded[0]).split(",")[0].trim()
: req.socket.remoteAddress || "";
return normalizeIP(raw);
};
const requireAdmin = (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
const token = req.headers["x-admin-token"] as string;
if (!token) return res.status(401).json({ error: "Unauthorized" });
const session = db.prepare("SELECT token FROM admin_sessions WHERE token = ?").get(token);
if (!session) return res.status(401).json({ error: "Invalid or expired session" });
next();
};
const requireSuperAdmin = (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
const token = req.headers["x-admin-token"] as string;
if (!token) return res.status(401).json({ error: "Unauthorized" });
const session = db.prepare("SELECT user_id FROM admin_sessions WHERE token = ?").get(token) as any;
if (!session) return res.status(401).json({ error: "Invalid or expired session" });
const user = db.prepare("SELECT role FROM users WHERE id = ?").get(session.user_id) as any;
if (!user || user.role !== 'super_admin') return res.status(403).json({ error: "Super admin access required" });
next();
};
const getUserFromToken = (token: string) => {
const session = db.prepare("SELECT user_id FROM admin_sessions WHERE token = ?").get(token) as any;
if (!session?.user_id) return null;
return db.prepare("SELECT * FROM users WHERE id = ?").get(session.user_id) as any;
};
const canAccessTenant = (user: any, tenantId: string) => {
if (!user) return false;
if (user.role === "super_admin") return true;
return user.tenant_id === tenantId;
};
const normalizeNameList = (items: unknown): string[] => {
if (!Array.isArray(items)) return [];
const seen = new Set<string>();
const cleaned: string[] = [];
for (const item of items) {
if (typeof item !== "string") continue;
const value = item.trim();
if (!value) continue;
const dedupeKey = value.toLowerCase();
if (seen.has(dedupeKey)) continue;
seen.add(dedupeKey);
cleaned.push(value);
}
return cleaned;
};
const getPlanLimits = (planRaw?: string) => {
const plan = (planRaw || "free").toLowerCase();
return PLAN_LIMITS[plan] || PLAN_LIMITS.free;
};
const getPlanPrice = (planRaw?: string) => {
const plan = (planRaw || "free").toLowerCase();
return PLAN_PRICES[plan] ?? 0;
};
const getBillingConfig = () => {
const row = db.prepare("SELECT value FROM settings WHERE key = 'billing_config'").get() as any;
const parsed = row?.value ? JSON.parse(row.value) : {};
return {
bankName: parsed?.bankName || "",
accountName: parsed?.accountName || "",
accountNumber: parsed?.accountNumber || "",
instructions: parsed?.instructions || "",
qrUrl: parsed?.qrUrl || "",
graceDays: Number.isFinite(parsed?.graceDays) ? Number(parsed.graceDays) : 5,
};
};
const saveBillingConfig = (config: any) => {
db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('billing_config', ?)")
.run(JSON.stringify(config));
};
const getTenantCatalog = (tenantId: string) => {
const tenant = db
.prepare("SELECT id, plan, settings FROM tenants WHERE id = ?")
.get(tenantId) as any;
const plan = (tenant?.plan || "free").toLowerCase();
const limits = getPlanLimits(plan);
const branchRows = db
.prepare("SELECT name FROM tenant_branches WHERE tenant_id = ? ORDER BY name ASC")
.all(tenantId) as { name: string }[];
const serviceRows = db
.prepare("SELECT name FROM tenant_services WHERE tenant_id = ? ORDER BY name ASC")
.all(tenantId) as { name: string }[];
const settings = tenant?.settings ? JSON.parse(tenant.settings) : {};
const customerTerm = typeof settings?.customerTerm === "string" && VALID_CUSTOMER_TERMS.has(settings.customerTerm)
? settings.customerTerm
: "customer";
return {
tenantId,
plan,
branches: (
branchRows.length ? branchRows.map((r) => r.name) : [...DEFAULT_BRANCHES]
).slice(0, limits.maxBranches ?? undefined),
services: (
serviceRows.length ? serviceRows.map((r) => r.name) : [...DEFAULT_SERVICES]
).slice(0, limits.maxServices ?? undefined),
customerTerm,
};
};
const checkIPAccess = (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
// Authenticated admins can always submit tickets (kiosk IP limits apply to public access)
const token = req.headers["x-admin-token"] as string | undefined;
if (token && getUserFromToken(token)) return next();
const whitelist = (
db.prepare("SELECT ip FROM ip_whitelist").all() as { ip: string }[]
).map((r) => r.ip);
// If no IPs are configured, allow all (setup mode)
if (whitelist.length === 0) return next();
const clientIP = getClientIP(req);
if (whitelist.includes(clientIP)) return next();
return res.status(403).json({
error: `Access denied. IP address ${clientIP} is not authorized to access this queue.`,
});
};
// ===== WEBSOCKET BROADCAST =====
const broadcast = (data: any) => {
wss.clients.forEach((client: WebSocket) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
};
// ===== UTILITY ROUTES =====
// Protected: only admins can download the source code
app.get("/api/download", requireAdmin, (_req, res) => {
const archive = archiver("zip", { zlib: { level: 9 } });
res.attachment("project_source.zip");
archive.on("error", (err: Error) => { res.status(500).send({ error: err.message }); });
archive.pipe(res);
const rootDir = process.cwd();
fs.readdirSync(rootDir).forEach((item) => {
const fullPath = path.join(rootDir, item);
const isDir = fs.lstatSync(fullPath).isDirectory();
if (isDir) {
if (!["node_modules", "dist", ".git", ".next"].includes(item)) {
archive.directory(fullPath, item);
}
} else {
if (!["project_source.zip", "ssb_queue.db", "ssb_queue.db-journal"].includes(item)) {
archive.file(fullPath, { name: item });
}
}
});
archive.finalize();
});
app.get("/health", (_req, res) => res.send("OK - Health Check Passed"));
app.get("/api/diag", (_req, res) => {
const distPath = path.resolve(__dirname, "dist");
res.json({
nodeEnv: process.env.NODE_ENV,
cwd: process.cwd(),
dirname: __dirname,
distExists: fs.existsSync(distPath),
distFiles: fs.existsSync(distPath) ? fs.readdirSync(distPath) : [],
indexExists: fs.existsSync(path.join(distPath, "index.html")),
});
});
// ===== ADMIN ROUTES =====
// Simple in-memory rate limiter for login attempts
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
const LOGIN_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
const LOGIN_MAX_ATTEMPTS = 5;
const handleAdminLogin = async (
req: express.Request,
res: express.Response,
requiredRole?: "tenant_admin" | "super_admin"
) => {
const ip = getClientIP(req);
const now = Date.now();
const rec = loginAttempts.get(ip);
if (rec && now < rec.resetAt) {
if (rec.count >= LOGIN_MAX_ATTEMPTS) {
return res.status(429).json({ error: "Too many login attempts. Please wait 15 minutes." });
}
rec.count++;
} else {
loginAttempts.set(ip, { count: 1, resetAt: now + LOGIN_WINDOW_MS });
}
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: "Email and password are required" });
}
const user = db.prepare("SELECT * FROM users WHERE email = ?").get(
(email as string).toLowerCase().trim()
) as any;
if (!user || !(await bcrypt.compare(password, user.password_hash))) {
return res.status(401).json({ error: "Invalid email or password" });
}
if (requiredRole && user.role !== requiredRole) {
return res.status(403).json({
error: requiredRole === "super_admin"
? "Super admin credentials required"
: "Tenant admin credentials required",
});
}
loginAttempts.delete(ip);
const token = crypto.randomBytes(32).toString("hex");
db.prepare("INSERT INTO admin_sessions (token, createdAt, user_id) VALUES (?, ?, ?)").run(
token, new Date().toISOString(), user.id
);
db.prepare("UPDATE users SET lastLoginAt = ? WHERE id = ?").run(new Date().toISOString(), user.id);
res.json({ token, role: user.role, email: user.email });
};
// Backward-compatible login endpoint (no role restriction)
app.post("/api/admin/login", async (req, res) => handleAdminLogin(req, res));
app.post("/api/admin/login/tenant", async (req, res) => handleAdminLogin(req, res, "tenant_admin"));
app.post("/api/admin/login/super", async (req, res) => handleAdminLogin(req, res, "super_admin"));
app.post("/api/admin/logout", requireAdmin, (req, res) => {
const token = req.headers["x-admin-token"] as string;
db.prepare("DELETE FROM admin_sessions WHERE token = ?").run(token);
res.json({ status: "ok" });
});
app.get("/api/admin/verify", requireAdmin, (_req, res) => {
res.json({ valid: true });
});
app.get("/api/auth/me", requireAdmin, (req, res) => {
const token = req.headers["x-admin-token"] as string;
const session = db.prepare("SELECT user_id FROM admin_sessions WHERE token = ?").get(token) as any;
if (!session?.user_id) return res.status(401).json({ error: "Invalid or expired session" });
const user = db.prepare("SELECT id, email, role, tenant_id FROM users WHERE id = ?").get(session.user_id) as any;
if (!user) return res.status(401).json({ error: "Invalid or expired session" });
res.json(user);
});
app.post("/api/auth/change-password", requireAdmin, async (req, res) => {
const token = req.headers["x-admin-token"] as string;
const session = db.prepare("SELECT user_id FROM admin_sessions WHERE token = ?").get(token) as any;
if (!session?.user_id) return res.status(401).json({ error: "Invalid or expired session" });
const { currentPassword, newPassword } = req.body || {};
if (typeof currentPassword !== "string" || typeof newPassword !== "string") {
return res.status(400).json({ error: "Current password and new password are required" });
}
if (newPassword.length < 8) {
return res.status(400).json({ error: "New password must be at least 8 characters" });
}
const user = db.prepare("SELECT id, password_hash FROM users WHERE id = ?").get(session.user_id) as any;
if (!user) return res.status(401).json({ error: "Invalid or expired session" });
const isValid = await bcrypt.compare(currentPassword, user.password_hash);
if (!isValid) return res.status(400).json({ error: "Current password is incorrect" });
const hash = await bcrypt.hash(newPassword, 12);
db.prepare("UPDATE users SET password_hash = ?, reset_token = NULL, reset_token_expiry = NULL WHERE id = ?")
.run(hash, user.id);
res.json({ status: "ok" });
});
app.post("/api/auth/register", async (req, res) => {
const { name, organization, email, password } = req.body;
if (!name || !email || !password) {
return res.status(400).json({ error: "Name, email, and password are required" });
}
if ((password as string).length < 8) {
return res.status(400).json({ error: "Password must be at least 8 characters" });
}
const existing = db.prepare("SELECT id FROM users WHERE email = ?").get(
(email as string).toLowerCase().trim()
);
if (existing) {
return res.status(409).json({ error: "An account with this email already exists" });
}
const hash = await bcrypt.hash(password, 12);
const userId = crypto.randomUUID();
const tenantId = crypto.randomUUID();
const orgName = (organization as string | undefined)?.trim() || (name as string).trim();
const orgSlug = orgName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
db.prepare(
"INSERT INTO users (id, email, password_hash, role, tenant_id, name, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?)"
).run(userId, (email as string).toLowerCase().trim(), hash, "tenant_admin", tenantId, (name as string).trim(), new Date().toISOString());
db.prepare(
"INSERT INTO tenants (id, name, slug, settings, plan, createdAt) VALUES (?, ?, ?, ?, ?, ?)"
).run(tenantId, orgName, orgSlug, JSON.stringify({}), 'free', new Date().toISOString());
ensureTenantCatalog(tenantId);
ensureTenantSubscription(tenantId);
const token = crypto.randomBytes(32).toString("hex");
db.prepare("INSERT INTO admin_sessions (token, createdAt, user_id) VALUES (?, ?, ?)").run(
token, new Date().toISOString(), userId
);
res.status(201).json({ token, role: "tenant_admin", email: (email as string).toLowerCase().trim(), organization: orgName });
});
app.post("/api/auth/forgot-password", async (req, res) => {
const { email } = req.body;
if (!email) return res.status(400).json({ error: "Email is required" });
const user = db.prepare("SELECT * FROM users WHERE email = ?").get(
(email as string).toLowerCase().trim()
) as any;
// Always return ok to prevent user enumeration
if (!user) return res.json({ status: "ok" });
const resetToken = crypto.randomBytes(32).toString("hex");
const expiry = new Date(Date.now() + 60 * 60 * 1000).toISOString();
db.prepare("UPDATE users SET reset_token = ?, reset_token_expiry = ? WHERE id = ?")
.run(resetToken, expiry, user.id);
const configuredAppUrl = (process.env.APP_URL || "").trim().replace(/\/+$/, "");
const hostUrl = req.get("host") ? `${req.protocol}://${req.get("host")}` : "";
const baseUrl = configuredAppUrl || hostUrl || "https://erp-queue-production.up.railway.app";
const resetLink = `${baseUrl}/?reset_token=${resetToken}`;
let tenantSettings: any = {};
try {
const tenant = db.prepare("SELECT settings FROM tenants WHERE id = ?").get(user.tenant_id) as any;
tenantSettings = tenant?.settings ? JSON.parse(tenant.settings) : {};
} catch {
tenantSettings = {};
}
const tenantSmtp = tenantSettings?.smtp?.host
? {
host: tenantSettings.smtp.host,
port: Number(tenantSettings.smtp.port || 587),
secure: !!tenantSettings.smtp.secure,
auth: tenantSettings.smtp.auth?.user
? {
user: tenantSettings.smtp.auth.user,
pass: tenantSettings.smtp.auth.pass || "",
}
: undefined,
from: tenantSettings.smtp.from || undefined,
}
: null;
const envSmtp = process.env.SMTP_HOST
? {
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT || 25),
secure: process.env.SMTP_SECURE === "true",
auth: process.env.SMTP_USER
? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
: undefined,
from: process.env.SMTP_FROM || undefined,
}
: null;
const smtpCandidates = [
tenantSmtp ? { source: "tenant", ...tenantSmtp } : null,
envSmtp ? { source: "env", ...envSmtp } : null,
].filter(Boolean) as Array<any>;
let sent = false;
let lastError: unknown = null;
for (const smtp of smtpCandidates) {
try {
await sendMailWithFallback(smtp, {
from: smtp.from || process.env.SMTP_FROM || "no-reply@ssb.local",
to: user.email,
subject: "Password Reset Request",
text: `You requested a password reset.\n\nClick the link below to reset your password (valid for 1 hour):\n\n${resetLink}\n\nIf you did not request this, you can ignore this email.`,
});
sent = true;
break;
} catch (err) {
lastError = err;
console.error(`[AUTH] Failed to send reset email using ${smtp.source} SMTP:`, err);
}
}
if (!sent) {
if (!smtpCandidates.length) {
console.error("[AUTH] Failed to send reset email: SMTP is not configured");
} else {
console.error("[AUTH] Failed to send reset email after all SMTP attempts", lastError);
}
if (process.env.NODE_ENV !== "production") {
console.warn("[AUTH] Dev fallback reset link:", resetLink);
}
}
res.json({ status: "ok" });
});
app.post("/api/auth/reset-password", async (req, res) => {
const { token, password } = req.body;
if (!token || !password) return res.status(400).json({ error: "Token and password are required" });
if ((password as string).length < 8) return res.status(400).json({ error: "Password must be at least 8 characters" });
const user = db.prepare("SELECT * FROM users WHERE reset_token = ?").get(token) as any;
if (!user) return res.status(400).json({ error: "Invalid or expired reset link" });
if (new Date(user.reset_token_expiry) < new Date()) {
return res.status(400).json({ error: "Reset link has expired. Please request a new one." });
}
const hash = await bcrypt.hash(password, 12);
db.prepare("UPDATE users SET password_hash = ?, reset_token = NULL, reset_token_expiry = NULL WHERE id = ?")
.run(hash, user.id);
db.prepare("DELETE FROM admin_sessions WHERE user_id = ?").run(user.id);
res.json({ status: "ok" });
});
// Returns the calling client's IP address
app.get("/api/admin/my-ip", (req, res) => {
res.json({ ip: getClientIP(req) });
});
app.get("/api/admin/ips", requireAdmin, (_req, res) => {
const rows = db.prepare("SELECT * FROM ip_whitelist ORDER BY addedAt DESC").all();
res.json(rows);
});
app.post("/api/admin/ips", requireAdmin, (req, res) => {
const { ip, label } = req.body;
if (!ip) return res.status(400).json({ error: "IP address is required" });
try {
db.prepare(
"INSERT OR REPLACE INTO ip_whitelist (ip, label, addedAt) VALUES (?, ?, ?)"
).run(normalizeIP(ip.trim()), label?.trim() || "", new Date().toISOString());
res.json({ status: "ok" });
} catch {
res.status(500).json({ error: "Failed to add IP" });
}
});
app.delete("/api/admin/ips/:ip", requireAdmin, (req, res) => {
db.prepare("DELETE FROM ip_whitelist WHERE ip = ?").run(req.params.ip);
res.json({ status: "ok" });
});
// API Key settings — returns masked key only (never the raw value)
app.get("/api/admin/settings", requireAdmin, (_req, res) => {
const row = db.prepare("SELECT value FROM settings WHERE key = 'apiKey'").get() as { value: string } | undefined;
const key = row?.value ?? "";
const masked = key.length > 12
? `${key.slice(0, 8)}${"•".repeat(key.length - 12)}${key.slice(-4)}`
: "•".repeat(key.length);
res.json({ configured: key.length > 0, masked });
});
app.post("/api/admin/settings", requireAdmin, (req, res) => {
const { apiKey } = req.body;
if (typeof apiKey !== "string" || apiKey.trim().length === 0) {
return res.status(400).json({ error: "apiKey must be a non-empty string" });
}
db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('apiKey', ?)").run(apiKey.trim());
res.json({ status: "ok" });
});
app.delete("/api/admin/settings/apikey", requireAdmin, (_req, res) => {
db.prepare("DELETE FROM settings WHERE key = 'apiKey'").run();
res.json({ status: "ok" });
});
// ===== SMTP SETTINGS =====
app.get("/api/admin/smtp", requireAdmin, (req, res) => {
const user = getUserFromToken(req.headers["x-admin-token"] as string);
if (!user) return res.json({});
const tenant = db.prepare("SELECT settings FROM tenants WHERE id = ?").get(user.tenant_id) as any;
const settings = tenant?.settings ? JSON.parse(tenant.settings) : {};
const smtp = settings.smtp || {};
res.json({
host: smtp.host || '',
port: smtp.port || 587,
secure: smtp.secure || false,
user: smtp.auth?.user || '',
from: smtp.from || '',
to: settings.email_contact || '',
configured: !!(smtp.host),
});
});
app.post("/api/admin/smtp", requireAdmin, (req, res) => {
const { host, port, secure, user, pass, from, to } = req.body;
const dbUser = getUserFromToken(req.headers["x-admin-token"] as string);
if (!dbUser) return res.status(401).json({ error: "Session invalid" });
const tenant = db.prepare("SELECT settings FROM tenants WHERE id = ?").get(dbUser.tenant_id) as any;
const currentSettings = tenant?.settings ? JSON.parse(tenant.settings) : {};
const smtp: any = { host: host || '', port: Number(port) || 587, secure: !!secure };
if (user) smtp.auth = { user, pass: pass || currentSettings.smtp?.auth?.pass || '' };
if (from) smtp.from = from;
const newSettings = { ...currentSettings, smtp, email_contact: to || currentSettings.email_contact || '' };
db.prepare("UPDATE tenants SET settings = ? WHERE id = ?").run(JSON.stringify(newSettings), dbUser.tenant_id);
res.json({ status: "ok" });
});
app.get("/api/admin/profile", requireAdmin, (req, res) => {
const dbUser = getUserFromToken(req.headers["x-admin-token"] as string);
if (!dbUser) return res.status(401).json({ error: "Session invalid" });
const tenant = db.prepare("SELECT name, settings FROM tenants WHERE id = ?").get(dbUser.tenant_id) as any;
const settings = tenant?.settings ? JSON.parse(tenant.settings) : {};
res.json({
companyName: tenant?.name || "",
industry: settings?.industry || "",
contactEmail: settings?.contact_email || settings?.email_contact || "",
contactPhone: settings?.contact_phone || "",
logoUrl: settings?.logo_url || "",
});
});
app.post("/api/admin/profile", requireAdmin, (req, res) => {
const dbUser = getUserFromToken(req.headers["x-admin-token"] as string);
if (!dbUser) return res.status(401).json({ error: "Session invalid" });
const { companyName, industry, contactEmail, contactPhone } = req.body;
const tenant = db.prepare("SELECT settings FROM tenants WHERE id = ?").get(dbUser.tenant_id) as any;
const currentSettings = tenant?.settings ? JSON.parse(tenant.settings) : {};
const nextSettings = {
...currentSettings,
industry: typeof industry === "string" ? industry.trim().slice(0, 120) : "",
contact_email: typeof contactEmail === "string" ? contactEmail.trim().slice(0, 160) : "",
contact_phone: typeof contactPhone === "string" ? contactPhone.trim().slice(0, 40) : "",
};
db.prepare("UPDATE tenants SET settings = ? WHERE id = ?").run(JSON.stringify(nextSettings), dbUser.tenant_id);
if (typeof companyName === "string" && companyName.trim()) {
db.prepare("UPDATE tenants SET name = ? WHERE id = ?").run(companyName.trim().slice(0, 160), dbUser.tenant_id);
}
res.json({ status: "ok" });
});
app.post("/api/admin/profile/logo", requireAdmin, (req, res) => {
const dbUser = getUserFromToken(req.headers["x-admin-token"] as string);
if (!dbUser) return res.status(401).json({ error: "Session invalid" });
const dataUrl = typeof req.body?.dataUrl === "string" ? req.body.dataUrl : "";
if (!dataUrl.startsWith("data:image/")) {
return res.status(400).json({ error: "Invalid image data" });
}
const match = dataUrl.match(/^data:(image\/(?:png|jpeg|jpg|webp));base64,(.+)$/i);
if (!match) return res.status(400).json({ error: "Unsupported image format" });
const mime = match[1].toLowerCase();
const base64 = match[2];
const ext = mime.includes("png") ? "png" : mime.includes("webp") ? "webp" : "jpg";
const buffer = Buffer.from(base64, "base64");
if (buffer.length > 2 * 1024 * 1024) {
return res.status(400).json({ error: "Logo file too large (max 2MB)" });
}
const filename = `${dbUser.tenant_id}-${Date.now()}.${ext}`;
const filePath = path.join(TENANT_LOGO_DIR, filename);
fs.writeFileSync(filePath, buffer);
const logoUrl = `/tenant-logos/${filename}`;
const tenant = db.prepare("SELECT settings FROM tenants WHERE id = ?").get(dbUser.tenant_id) as any;
const currentSettings = tenant?.settings ? JSON.parse(tenant.settings) : {};
const oldLogoUrl = currentSettings?.logo_url as string | undefined;
const nextSettings = { ...currentSettings, logo_url: logoUrl };
db.prepare("UPDATE tenants SET settings = ? WHERE id = ?").run(JSON.stringify(nextSettings), dbUser.tenant_id);
if (oldLogoUrl && oldLogoUrl.startsWith("/tenant-logos/")) {
const oldFilePath = path.join(TENANT_LOGO_DIR, oldLogoUrl.replace("/tenant-logos/", ""));
try { if (fs.existsSync(oldFilePath)) fs.unlinkSync(oldFilePath); } catch {}
}
res.json({ status: "ok", logoUrl });
});
app.get("/api/logos/public", (_req, res) => {
const rows = db.prepare("SELECT name, settings FROM tenants WHERE id != 'default' ORDER BY createdAt DESC LIMIT 40").all() as any[];
const logos = rows
.map((r) => {
const settings = r.settings ? JSON.parse(r.settings) : {};
const logoUrl = settings?.logo_url || "";
const name = (r.name || "").trim();
if (!logoUrl || !name) return null;
const abbr = name
.split(/\s+/)
.slice(0, 2)
.map((p: string) => p[0] || "")
.join("")
.toUpperCase();
return { name, logoUrl, abbr: abbr || name.slice(0, 2).toUpperCase() };
})
.filter(Boolean);
res.json(logos);
});
app.get("/api/billing/me", requireAdmin, (req, res) => {
const dbUser = getUserFromToken(req.headers["x-admin-token"] as string);
if (!dbUser) return res.status(401).json({ error: "Session invalid" });
const tenant = db.prepare("SELECT id, name, plan, settings FROM tenants WHERE id = ?").get(dbUser.tenant_id) as any;
const subscription = db.prepare("SELECT * FROM subscriptions WHERE tenant_id = ?").get(dbUser.tenant_id) as any;
const recentSubmissions = db.prepare("SELECT * FROM payment_submissions WHERE tenant_id = ? ORDER BY submittedAt DESC LIMIT 5").all(dbUser.tenant_id);
const billing = getBillingConfig();
const settings = tenant?.settings ? JSON.parse(tenant.settings) : {};
res.json({
tenant: {
id: tenant?.id,
name: tenant?.name,
plan: tenant?.plan || "free",
contactEmail: settings?.contact_email || "",
},
subscription: subscription || null,
pricing: PLAN_PRICES,
billing,
submissions: recentSubmissions,
});
});
app.post("/api/billing/submit-proof", requireAdmin, (req, res) => {
const dbUser = getUserFromToken(req.headers["x-admin-token"] as string);
if (!dbUser || dbUser.role === "super_admin") return res.status(401).json({ error: "Tenant admin session required" });
const desiredPlan = String(req.body?.desiredPlan || "").toLowerCase();
const referenceCode = typeof req.body?.referenceCode === "string" ? req.body.referenceCode.trim().slice(0, 120) : "";
const notes = typeof req.body?.notes === "string" ? req.body.notes.trim().slice(0, 500) : "";
const dataUrl = typeof req.body?.proofDataUrl === "string" ? req.body.proofDataUrl : "";
if (!["starter", "pro"].includes(desiredPlan)) return res.status(400).json({ error: "Invalid paid plan" });
if (!referenceCode) return res.status(400).json({ error: "Reference code is required" });
if (!dataUrl.startsWith("data:image/")) return res.status(400).json({ error: "Payment proof image is required" });
const match = dataUrl.match(/^data:(image\/(?:png|jpeg|jpg|webp));base64,(.+)$/i);
if (!match) return res.status(400).json({ error: "Unsupported image format" });
const mime = match[1].toLowerCase();
const base64 = match[2];
const ext = mime.includes("png") ? "png" : mime.includes("webp") ? "webp" : "jpg";
const buffer = Buffer.from(base64, "base64");
if (buffer.length > 4 * 1024 * 1024) return res.status(400).json({ error: "Proof image too large (max 4MB)" });
const id = crypto.randomUUID();
const filename = `${dbUser.tenant_id}-${Date.now()}.${ext}`;
const filePath = path.join(PAYMENT_PROOFS_DIR, filename);
fs.writeFileSync(filePath, buffer);
const proofUrl = `/billing-files/proofs/${filename}`;
db.prepare(
"INSERT INTO payment_submissions (id, tenant_id, desired_plan, amount, reference_code, proof_url, status, notes, submittedAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
).run(
id,
dbUser.tenant_id,
desiredPlan,
getPlanPrice(desiredPlan),
referenceCode,
proofUrl,
"pending",
notes,
new Date().toISOString()
);
res.status(201).json({ status: "ok", id });
});