Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
3730 lines (3417 loc) · 137 KB
/
Copy pathserver.js
File metadata and controls
3730 lines (3417 loc) · 137 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
require('dotenv').config();
const path = require('path');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
const { spawn } = require('child_process');
const express = require('express');
const multer = require('multer');
const sqlite3 = require('sqlite3').verbose();
const session = require('express-session');
const SQLiteStore = require('connect-sqlite3')(session);
const bcrypt = require('bcryptjs');
const compression = require('compression');
const sharp = require('sharp');
const { S3Client, PutObjectCommand, DeleteObjectCommand } = require('@aws-sdk/client-s3');
const { ToolRegistry } = require('./src/framework/tool-registry');
const { createPdfMergeTool } = require('./src/tools/pdf-merge-tool');
const { buildProviders, streamChatResponse, refreshCustomModels } = require('./src/tools/ai-chat-tool');
const BackupManager = require('./src/backup-manager');
const CacheManager = require('./src/cache-manager');
let pdfParse = null;
try {
pdfParse = require('pdf-parse');
} catch (err) {
// Optional: PDF text extraction stays disabled until installed.
}
let nodemailer = null;
try {
nodemailer = require('nodemailer');
} catch (err) {
// Optional dependency: registration email verification stays disabled until installed.
}
const app = express();
app.disable('x-powered-by');
const NODE_ENV = String(process.env.NODE_ENV || 'development').trim().toLowerCase();
const IS_PRODUCTION = NODE_ENV === 'production';
const PORT = process.env.PORT || 3000;
const UPLOADS_DIR = path.join(__dirname, 'uploads');
const DB_PATH = process.env.DB_PATH || path.join(__dirname, 'data.db');
const SESSION_SECRET = String(process.env.SESSION_SECRET || 'devsecret');
const BODY_LIMIT = process.env.BODY_LIMIT || '256kb';
const DAILY_UPLOAD_LIMIT = Math.max(1, Number.parseInt(process.env.DAILY_UPLOAD_LIMIT || '1000', 10));
const DAILY_REGISTRATION_LIMIT = Math.max(1, Number.parseInt(process.env.DAILY_REGISTRATION_LIMIT || '200', 10));
const MAX_IMAGES_PER_POST = Math.max(1, Number.parseInt(process.env.MAX_IMAGES_PER_POST || '10', 10));
const MAX_UPLOAD_FILE_SIZE_MB = Math.max(1, Number.parseInt(process.env.MAX_UPLOAD_FILE_SIZE_MB || '10', 10));
const MAX_UPLOAD_FILE_SIZE_BYTES = MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024;
const MAX_VIDEO_FILE_SIZE_MB = Math.max(1, Number.parseInt(process.env.MAX_VIDEO_FILE_SIZE_MB || '50', 10));
const MAX_VIDEO_FILE_SIZE_BYTES = MAX_VIDEO_FILE_SIZE_MB * 1024 * 1024;
const MAX_MEDIA_UPLOAD_FILE_SIZE_BYTES = Math.max(MAX_UPLOAD_FILE_SIZE_BYTES, MAX_VIDEO_FILE_SIZE_BYTES);
const MAX_FILES_PER_POST = MAX_IMAGES_PER_POST + 1;
const POSTS_PER_PAGE = Math.max(10, Number.parseInt(process.env.POSTS_PER_PAGE || '20', 10));
const ENABLE_SERVER_VIDEO_PROCESSING = process.env.ENABLE_SERVER_VIDEO_PROCESSING === 'true';
const ENABLE_VIDEO_TRANSCODE = process.env.ENABLE_VIDEO_TRANSCODE !== 'false';
const FFMPEG_PATH = String(process.env.FFMPEG_PATH || 'ffmpeg').trim() || 'ffmpeg';
const GHOSTSCRIPT_PATH = String(process.env.GHOSTSCRIPT_PATH || 'gs').trim() || 'gs';
const MAX_TOOL_PDF_FILES = Math.max(2, Number.parseInt(process.env.MAX_TOOL_PDF_FILES || '10', 10));
const MAX_TOOL_PDF_FILE_SIZE_MB = Math.max(1, Number.parseInt(process.env.MAX_TOOL_PDF_FILE_SIZE_MB || '20', 10));
const MAX_TOOL_PDF_TOTAL_INPUT_MB = Math.max(1, Number.parseInt(process.env.MAX_TOOL_PDF_TOTAL_INPUT_MB || '80', 10));
const TOOL_RUN_TIMEOUT_SECONDS = Math.max(5, Number.parseInt(process.env.TOOL_RUN_TIMEOUT_SECONDS || '45', 10));
const toolRegistry = new ToolRegistry();
toolRegistry.register(createPdfMergeTool({
ghostscriptPath: GHOSTSCRIPT_PATH,
maxFiles: MAX_TOOL_PDF_FILES,
maxFileSizeMb: MAX_TOOL_PDF_FILE_SIZE_MB,
maxTotalInputSizeMb: MAX_TOOL_PDF_TOTAL_INPUT_MB,
executionTimeoutSeconds: TOOL_RUN_TIMEOUT_SECONDS
}));
const TOOL_DEFINITIONS = Object.freeze(toolRegistry.list().map((tool) => ({
key: tool.key,
name: tool.name,
description: tool.description,
inputFieldName: tool.inputFieldName,
inputLabel: tool.inputLabel || null,
fileAccept: tool.fileAccept || null,
supportsOutputName: tool.supportsOutputName === true,
outputNamePlaceholder: tool.outputNamePlaceholder || null,
notes: Array.isArray(tool.notes) ? tool.notes.slice() : [],
submitLabel: tool.submitLabel || 'Run',
maxFiles: tool.maxFiles || null,
maxFileSizeMb: tool.maxFileSizeMb || null,
maxTotalInputSizeMb: tool.maxTotalInputSizeMb || null
})));
const TOOL_KEYS = toolRegistry.keys();
// Register ai_chat as a virtual tool key for the permission system
TOOL_KEYS.push('ai_chat');
const TOOL_KEY_SET = new Set(TOOL_KEYS);
const AUTH_RATE_LIMIT_WINDOW_MINUTES = Math.max(1, Number.parseInt(process.env.AUTH_RATE_LIMIT_WINDOW_MINUTES || '15', 10));
const AUTH_RATE_LIMIT_MAX_ATTEMPTS = Math.max(1, Number.parseInt(process.env.AUTH_RATE_LIMIT_MAX_ATTEMPTS || '25', 10));
const AUTH_RATE_LIMIT_WINDOW_MS = AUTH_RATE_LIMIT_WINDOW_MINUTES * 60 * 1000;
const TOOL_RATE_LIMIT_WINDOW_SECONDS = Math.max(10, Number.parseInt(process.env.TOOL_RATE_LIMIT_WINDOW_SECONDS || '60', 10));
const TOOL_RATE_LIMIT_MAX_RUNS = Math.max(1, Number.parseInt(process.env.TOOL_RATE_LIMIT_MAX_RUNS || '6', 10));
const TOOL_RATE_LIMIT_WINDOW_MS = TOOL_RATE_LIMIT_WINDOW_SECONDS * 1000;
const TOOL_MAX_CONCURRENT_RUNS = Math.max(1, Number.parseInt(process.env.TOOL_MAX_CONCURRENT_RUNS || '2', 10));
const TOOL_MAX_CONCURRENT_RUNS_PER_TOOL = Math.max(1, Number.parseInt(process.env.TOOL_MAX_CONCURRENT_RUNS_PER_TOOL || '1', 10));
// AI Chat configuration
const AI_CHAT_ENABLED = process.env.AI_CHAT_ENABLED !== 'false';
const ANTHROPIC_API_KEY = (process.env.ANTHROPIC_API_KEY || '').trim();
const OPENAI_API_KEY = (process.env.OPENAI_API_KEY || '').trim();
const CUSTOM_LLM_API_KEY = (process.env.CUSTOM_LLM_API_KEY || '').trim();
const CUSTOM_LLM_BASE_URL = (process.env.CUSTOM_LLM_BASE_URL || '').trim();
const CUSTOM_LLM_MODELS = (process.env.CUSTOM_LLM_MODELS || '').trim();
const CUSTOM_LLM_NAME = (process.env.CUSTOM_LLM_NAME || '').trim();
const AI_CHAT_MAX_MESSAGE_LENGTH = Math.max(100, Number.parseInt(process.env.AI_CHAT_MAX_MESSAGE_LENGTH || '16000', 10));
const AI_CHAT_RATE_LIMIT_WINDOW_SECONDS = Math.max(10, Number.parseInt(process.env.AI_CHAT_RATE_LIMIT_WINDOW_SECONDS || '60', 10));
const AI_CHAT_RATE_LIMIT_MAX_SENDS = Math.max(1, Number.parseInt(process.env.AI_CHAT_RATE_LIMIT_MAX_SENDS || '10', 10));
const AI_CHAT_RATE_LIMIT_WINDOW_MS = AI_CHAT_RATE_LIMIT_WINDOW_SECONDS * 1000;
const AI_CHAT_PROVIDERS = AI_CHAT_ENABLED ? buildProviders({
anthropicApiKey: ANTHROPIC_API_KEY,
openaiApiKey: OPENAI_API_KEY,
customLlmApiKey: CUSTOM_LLM_API_KEY,
customLlmBaseUrl: CUSTOM_LLM_BASE_URL,
customLlmModels: CUSTOM_LLM_MODELS,
customLlmName: CUSTOM_LLM_NAME
}) : {};
const TRUST_PROXY = process.env.TRUST_PROXY === 'true';
const SESSION_COOKIE_SECURE = process.env.SESSION_COOKIE_SECURE === 'true';
const SESSION_COOKIE_SAME_SITE = process.env.SESSION_COOKIE_SAME_SITE || 'lax';
const REGISTRATION_CODE_TTL_MINUTES = Math.max(
1,
Number.parseInt(process.env.REGISTRATION_CODE_TTL_MINUTES || '10', 10)
);
const REGISTRATION_CODE_TTL_MS = REGISTRATION_CODE_TTL_MINUTES * 60 * 1000;
const SMTP_HOST = (process.env.SMTP_HOST || '').trim();
const SMTP_PORT = Math.max(1, Number.parseInt(process.env.SMTP_PORT || '587', 10));
const SMTP_SECURE = process.env.SMTP_SECURE === 'true';
const SMTP_USER = (process.env.SMTP_USER || '').trim();
const SMTP_PASS = process.env.SMTP_PASS || '';
const SMTP_FROM = (process.env.SMTP_FROM || '').trim();
const EMAIL_VERIFICATION_ENABLED = Boolean(nodemailer && SMTP_HOST && SMTP_FROM);
const hasR2UploadConfig = Boolean(
process.env.R2_ENDPOINT &&
process.env.R2_BUCKET &&
process.env.R2_ACCESS_KEY_ID &&
process.env.R2_SECRET_ACCESS_KEY
);
const WEAK_SESSION_SECRETS = new Set([
'devsecret',
'change_this_to_a_long_random_secret',
'change_me'
]);
if (IS_PRODUCTION && (SESSION_SECRET.length < 24 || WEAK_SESSION_SECRETS.has(SESSION_SECRET))) {
console.warn('[security] Weak SESSION_SECRET detected for production runtime.');
}
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
// Initialize backup manager
const BACKUP_ENABLED = process.env.BACKUP_ENABLED !== 'false';
const BACKUP_INTERVAL_HOURS = Math.max(1, Number.parseInt(process.env.BACKUP_INTERVAL_HOURS || '24', 10));
const BACKUP_MAX_KEEP = Math.max(1, Number.parseInt(process.env.BACKUP_MAX_KEEP || '7', 10));
// Initialize cache manager
const CACHE_ENABLED = process.env.CACHE_ENABLED !== 'false';
const REDIS_URL = process.env.REDIS_URL || null;
const CACHE_TTL = Math.max(60, Number.parseInt(process.env.CACHE_TTL || '300', 10));
const cacheManager = new CacheManager({
enabled: CACHE_ENABLED && Boolean(REDIS_URL),
redisUrl: REDIS_URL,
ttl: CACHE_TTL
});
const backupManager = new BackupManager({
dbPath: DB_PATH,
uploadsDir: UPLOADS_DIR,
backupDir: path.join(__dirname, 'backups'),
intervalHours: BACKUP_INTERVAL_HOURS,
maxBackups: BACKUP_MAX_KEEP,
enabled: BACKUP_ENABLED
});
if (TRUST_PROXY) {
app.set('trust proxy', 1);
}
// Configure storage: we'll upload to Cloudflare R2 using S3-compatible API.
const upload = multer({
storage: multer.memoryStorage(),
limits: {
files: MAX_FILES_PER_POST,
fileSize: MAX_MEDIA_UPLOAD_FILE_SIZE_BYTES
}
});
const uploadPostMedia = upload.fields([
{ name: 'photos', maxCount: MAX_IMAGES_PER_POST },
{ name: 'video', maxCount: 1 }
]);
const uploadAiChatFiles = upload.array('files', 5);
const toolUploadMiddlewares = new Map(
toolRegistry.list().map((tool) => [tool.key, tool.createUploadMiddleware(multer)])
);
function buildDefaultToolAccessMap() {
const map = {};
for (const toolKey of TOOL_KEYS) map[toolKey] = false;
return map;
}
function buildAdminToolAccessMap() {
const map = {};
for (const toolKey of TOOL_KEYS) map[toolKey] = true;
return map;
}
function normalizeToolAccessMap(value) {
const normalized = buildDefaultToolAccessMap();
if (!value || typeof value !== 'object') return normalized;
for (const toolKey of TOOL_KEYS) {
normalized[toolKey] = Boolean(value[toolKey]);
}
return normalized;
}
function userHasAnyToolAccess(accessMap) {
for (const toolKey of TOOL_KEYS) {
if (Boolean(accessMap?.[toolKey])) return true;
}
return false;
}
function buildToolCatalogForAccess(accessMap) {
return toolRegistry.list().map((tool) => ({
key: tool.key,
name: tool.name,
description: tool.description,
inputFieldName: tool.inputFieldName,
inputLabel: tool.inputLabel || null,
fileAccept: tool.fileAccept || null,
supportsOutputName: tool.supportsOutputName === true,
outputNamePlaceholder: tool.outputNamePlaceholder || null,
notes: Array.isArray(tool.notes) ? tool.notes.slice() : [],
submitLabel: tool.submitLabel || 'Run',
maxFiles: tool.maxFiles || null,
maxFileSizeMb: tool.maxFileSizeMb || null,
maxTotalInputSizeMb: tool.maxTotalInputSizeMb || null,
hasAccess: Boolean(accessMap?.[tool.key])
}));
}
// Setup view engine and static
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Enable compression for all responses
app.use(compression({
level: 6,
threshold: 1024, // Only compress responses larger than 1KB
filter: (req, res) => {
if (req.headers['x-no-compression']) return false;
if (res.getHeader('Content-Type') === 'text/event-stream') return false;
return compression.filter(req, res);
}
}));
// Static files with aggressive caching
app.use('/static', express.static(path.join(__dirname, 'public'), {
maxAge: '1y',
immutable: true,
etag: true
}));
app.use('/uploads', express.static(UPLOADS_DIR, {
maxAge: '30d',
etag: true,
lastModified: true
}));
app.use(express.urlencoded({ extended: true, limit: BODY_LIMIT }));
app.use(express.json({ limit: BODY_LIMIT }));
// DB
const db = new sqlite3.Database(DB_PATH);
// Sessions with SQLite store for persistence (after db initialization)
const sessionStore = new SQLiteStore({
db: path.basename(DB_PATH, '.db'),
dir: path.dirname(DB_PATH),
table: 'sessions'
});
app.use(session({
store: sessionStore,
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: SESSION_COOKIE_SECURE,
sameSite: SESSION_COOKIE_SAME_SITE,
httpOnly: true,
maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
}
}));
// Basic HTTP security headers.
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
if (req.secure || SESSION_COOKIE_SECURE) {
res.setHeader('Strict-Transport-Security', 'max-age=15552000; includeSubDomains');
}
next();
});
function ensureSessionCsrfToken(req) {
if (!req.session) return '';
if (!req.session.csrfToken) {
req.session.csrfToken = crypto.randomBytes(32).toString('hex');
}
return req.session.csrfToken;
}
function verifyCsrfToken(req, res, next) {
const expected = req.session ? req.session.csrfToken : '';
const provided = String(
(req.body && req.body._csrf) ||
req.get('x-csrf-token') ||
''
);
if (!expected || !provided || provided !== expected) {
return res.status(403).send('Invalid CSRF token');
}
return next();
}
// Expose CSRF token to all templates.
app.use((req, res, next) => {
res.locals.csrfToken = ensureSessionCsrfToken(req);
next();
});
const authRateLimitBuckets = new Map();
const toolRateLimitBuckets = new Map();
const aiChatRateLimitBuckets = new Map();
let activeToolRunsGlobal = 0;
const activeToolRunsByKey = new Map();
function makeAuthRateLimiter(scope) {
return (req, res, next) => {
const now = Date.now();
if (authRateLimitBuckets.size > 5000) {
for (const [bucketKey, bucketValue] of authRateLimitBuckets.entries()) {
if (bucketValue.resetAt <= now) authRateLimitBuckets.delete(bucketKey);
}
}
const ip = req.ip || req.socket?.remoteAddress || 'unknown';
const key = `${scope}:${ip}`;
const current = authRateLimitBuckets.get(key);
if (!current || current.resetAt <= now) {
authRateLimitBuckets.set(key, { count: 1, resetAt: now + AUTH_RATE_LIMIT_WINDOW_MS });
return next();
}
if (current.count >= AUTH_RATE_LIMIT_MAX_ATTEMPTS) {
const retryAfterSeconds = Math.max(1, Math.ceil((current.resetAt - now) / 1000));
res.setHeader('Retry-After', String(retryAfterSeconds));
return res.status(429).send('Too many attempts. Please try again later.');
}
current.count += 1;
authRateLimitBuckets.set(key, current);
return next();
};
}
function makeToolRunRateLimiter() {
return (req, res, next) => {
const toolKey = String(req.params?.toolKey || '').trim().toLowerCase();
const now = Date.now();
if (toolRateLimitBuckets.size > 5000) {
for (const [bucketKey, bucketValue] of toolRateLimitBuckets.entries()) {
if (bucketValue.resetAt <= now) toolRateLimitBuckets.delete(bucketKey);
}
}
const actor = req.session?.userId
? `u:${req.session.userId}`
: `ip:${req.ip || req.socket?.remoteAddress || 'unknown'}`;
const bucketKey = `${toolKey}:${actor}`;
const current = toolRateLimitBuckets.get(bucketKey);
if (!current || current.resetAt <= now) {
toolRateLimitBuckets.set(bucketKey, { count: 1, resetAt: now + TOOL_RATE_LIMIT_WINDOW_MS });
return next();
}
if (current.count >= TOOL_RATE_LIMIT_MAX_RUNS) {
const retryAfterSeconds = Math.max(1, Math.ceil((current.resetAt - now) / 1000));
res.setHeader('Retry-After', String(retryAfterSeconds));
return res.status(429).send('Tool rate limit reached. Please try again later.');
}
current.count += 1;
toolRateLimitBuckets.set(bucketKey, current);
return next();
};
}
function makeAiChatRateLimiter() {
return (req, res, next) => {
const now = Date.now();
if (aiChatRateLimitBuckets.size > 5000) {
for (const [k, v] of aiChatRateLimitBuckets.entries()) {
if (v.resetAt <= now) aiChatRateLimitBuckets.delete(k);
}
}
const actor = req.session?.userId
? `u:${req.session.userId}`
: `ip:${req.ip || req.socket?.remoteAddress || 'unknown'}`;
const bucketKey = `ai_chat:${actor}`;
const current = aiChatRateLimitBuckets.get(bucketKey);
if (!current || current.resetAt <= now) {
aiChatRateLimitBuckets.set(bucketKey, { count: 1, resetAt: now + AI_CHAT_RATE_LIMIT_WINDOW_MS });
return next();
}
if (current.count >= AI_CHAT_RATE_LIMIT_MAX_SENDS) {
const retryAfterSeconds = Math.max(1, Math.ceil((current.resetAt - now) / 1000));
res.setHeader('Retry-After', String(retryAfterSeconds));
return res.status(429).json({ error: 'Rate limit reached. Please try again later.' });
}
current.count += 1;
aiChatRateLimitBuckets.set(bucketKey, current);
return next();
};
}
function tryAcquireToolRunSlot(toolKey) {
const normalizedToolKey = String(toolKey || '').trim();
const currentToolRuns = Number(activeToolRunsByKey.get(normalizedToolKey) || 0);
if (activeToolRunsGlobal >= TOOL_MAX_CONCURRENT_RUNS) return false;
if (currentToolRuns >= TOOL_MAX_CONCURRENT_RUNS_PER_TOOL) return false;
activeToolRunsGlobal += 1;
activeToolRunsByKey.set(normalizedToolKey, currentToolRuns + 1);
return true;
}
function releaseToolRunSlot(toolKey) {
const normalizedToolKey = String(toolKey || '').trim();
const currentToolRuns = Number(activeToolRunsByKey.get(normalizedToolKey) || 0);
if (currentToolRuns <= 1) activeToolRunsByKey.delete(normalizedToolKey);
else activeToolRunsByKey.set(normalizedToolKey, currentToolRuns - 1);
if (activeToolRunsGlobal > 0) activeToolRunsGlobal -= 1;
}
// Attach user role/permissions to request for authorization checks
app.use(async (req, res, next) => {
if (req.session && req.session.userId) {
// Use session cache if available
if (req.session.userRole && typeof req.session.userCanPin === 'boolean') {
req.userRole = req.session.userRole;
req.userCanPin = req.session.userCanPin;
} else {
// Fetch from DB and cache in session
const user = await dbGetAsync('SELECT role, can_pin FROM users WHERE id = ?', [req.session.userId]);
req.userRole = user ? user.role : null;
req.userCanPin = Boolean(user && Number(user.can_pin || 0) === 1);
if (req.userRole) {
req.session.userRole = req.userRole;
req.session.userCanPin = req.userCanPin;
}
}
if (req.userRole === 'admin') {
req.userToolAccess = buildAdminToolAccessMap();
req.session.userToolAccess = req.userToolAccess;
req.session.userToolAccessLoaded = true;
} else {
if (req.session.userToolAccessLoaded === true) {
req.userToolAccess = normalizeToolAccessMap(req.session.userToolAccess);
} else {
const placeholders = TOOL_KEYS.map(() => '?').join(',');
const permissionRows = TOOL_KEYS.length === 0
? []
: await dbAllAsync(
`SELECT tool_key FROM user_tool_permissions WHERE user_id = ? AND tool_key IN (${placeholders})`,
[req.session.userId, ...TOOL_KEYS]
);
const toolAccess = buildDefaultToolAccessMap();
for (const row of permissionRows) {
if (!row || !TOOL_KEY_SET.has(row.tool_key)) continue;
toolAccess[row.tool_key] = true;
}
req.userToolAccess = toolAccess;
req.session.userToolAccess = toolAccess;
req.session.userToolAccessLoaded = true;
}
}
res.locals.userRole = req.userRole; // Make available to views
res.locals.userCanPin = req.userCanPin;
res.locals.userToolAccess = req.userToolAccess;
res.locals.hasToolsAccess = req.userRole === 'admin' || userHasAnyToolAccess(req.userToolAccess);
} else {
req.userRole = null;
req.userCanPin = false;
req.userToolAccess = buildDefaultToolAccessMap();
res.locals.userRole = null;
res.locals.userCanPin = false;
res.locals.userToolAccess = req.userToolAccess;
res.locals.hasToolsAccess = false;
}
next();
});
db.serialize(() => {
const hasColumn = (cols, name) => Array.isArray(cols) && cols.some((col) => col.name === name);
const addColumnIfMissing = (tableName, cols, columnName, columnTypeSql, options = {}) => {
const { errorLabel, onAdded } = options;
if (hasColumn(cols, columnName)) return;
db.run(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${columnTypeSql}`, (alterErr) => {
if (alterErr) {
console.error(errorLabel || `${tableName} ${columnName} migration error:`, alterErr);
return;
}
if (typeof onAdded === 'function') onAdded();
});
};
db.run(`CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT,
originalname TEXT,
video_filename TEXT,
video_originalname TEXT,
video_mimetype TEXT,
video_poster_filename TEXT,
video_poster_originalname TEXT,
note TEXT,
author_label TEXT,
location_text TEXT,
rating_value REAL,
is_pinned INTEGER DEFAULT 0,
created_at INTEGER,
is_draft INTEGER DEFAULT 0,
deleted_at INTEGER,
deleted_by INTEGER,
collection_id INTEGER
)`);
db.all('PRAGMA table_info(entries)', (pragmaErr, cols) => {
if (pragmaErr) return console.error('PRAGMA entries error:', pragmaErr);
addColumnIfMissing('entries', cols, 'is_pinned', 'INTEGER DEFAULT 0', {
errorLabel: 'entries migration error:'
});
// Migration: Add user_id column to entries table
addColumnIfMissing('entries', cols, 'user_id', 'INTEGER', {
errorLabel: 'entries user_id migration error:',
onAdded: () => {
console.log('✓ Added user_id column to entries');
// Set existing entries to first user (id=1)
db.run('UPDATE entries SET user_id = 1 WHERE user_id IS NULL', (updateErr) => {
if (updateErr) console.error('entries user_id backfill error:', updateErr);
else console.log('✓ Backfilled existing entries to user_id = 1');
});
// Create index for faster queries
db.run('CREATE INDEX IF NOT EXISTS idx_entries_user_id ON entries(user_id)');
}
});
[
['is_draft', 'INTEGER DEFAULT 0'],
['deleted_at', 'INTEGER'],
['deleted_by', 'INTEGER'],
['collection_id', 'INTEGER'],
['author_label', 'TEXT'],
['location_text', 'TEXT'],
['rating_value', 'REAL'],
['video_filename', 'TEXT'],
['video_originalname', 'TEXT'],
['video_mimetype', 'TEXT'],
['video_poster_filename', 'TEXT'],
['video_poster_originalname', 'TEXT']
].forEach(([columnName, columnTypeSql]) => {
addColumnIfMissing('entries', cols, columnName, columnTypeSql, {
errorLabel: `entries ${columnName} migration error:`,
onAdded: () => console.log(`✓ Added ${columnName} column to entries`)
});
});
db.run('CREATE INDEX IF NOT EXISTS idx_entries_created_at ON entries(created_at)');
db.run('CREATE INDEX IF NOT EXISTS idx_entries_deleted_at ON entries(deleted_at)');
db.run('CREATE INDEX IF NOT EXISTS idx_entries_collection_id ON entries(collection_id)');
});
db.run(`CREATE TABLE IF NOT EXISTS entry_images (
id INTEGER PRIMARY KEY AUTOINCREMENT,
entry_id INTEGER NOT NULL,
filename TEXT NOT NULL,
originalname TEXT,
sort_order INTEGER DEFAULT 0
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_entry_images_entry_id ON entry_images(entry_id)');
// Backfill legacy single-image entries into entry_images.
db.run(`
INSERT INTO entry_images(entry_id, filename, originalname, sort_order)
SELECT e.id, e.filename, e.originalname, 0
FROM entries e
WHERE e.filename IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM entry_images i WHERE i.entry_id = e.id
)
`);
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
email TEXT UNIQUE,
password_hash TEXT,
role TEXT DEFAULT "normal",
can_pin INTEGER DEFAULT 0,
email_verified_at INTEGER,
last_login_at INTEGER
)`);
db.run(`CREATE TABLE IF NOT EXISTS user_tool_permissions (
user_id INTEGER NOT NULL,
tool_key TEXT NOT NULL,
granted_by INTEGER,
granted_at INTEGER NOT NULL,
PRIMARY KEY(user_id, tool_key)
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_user_tool_permissions_tool_key ON user_tool_permissions(tool_key)');
db.run(`CREATE TABLE IF NOT EXISTS pending_registrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
email TEXT NOT NULL,
password_hash TEXT NOT NULL,
verification_code TEXT NOT NULL,
code_expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_pending_registrations_expires ON pending_registrations(code_expires_at)');
db.run(`CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE
)`);
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_tags_name_unique ON tags(name)');
db.run(`CREATE TABLE IF NOT EXISTS entry_tags (
entry_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
PRIMARY KEY(entry_id, tag_id)
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_entry_tags_entry_id ON entry_tags(entry_id)');
db.run('CREATE INDEX IF NOT EXISTS idx_entry_tags_tag_id ON entry_tags(tag_id)');
db.run(`CREATE TABLE IF NOT EXISTS collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
name TEXT NOT NULL,
created_at INTEGER NOT NULL
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_collections_user_id ON collections(user_id)');
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_collections_user_name_unique ON collections(user_id, name)');
db.run(`CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
entry_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
body TEXT NOT NULL,
created_at INTEGER NOT NULL
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_comments_entry_id ON comments(entry_id)');
db.run('CREATE INDEX IF NOT EXISTS idx_comments_user_id ON comments(user_id)');
db.run(`CREATE TABLE IF NOT EXISTS entry_reactions (
entry_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
reaction TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY(entry_id, user_id)
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_entry_reactions_entry_id ON entry_reactions(entry_id)');
db.run(`CREATE TABLE IF NOT EXISTS audit_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
actor_user_id INTEGER,
action TEXT NOT NULL,
target_type TEXT,
target_id INTEGER,
meta_json TEXT,
created_at INTEGER NOT NULL
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at ON audit_logs(created_at)');
// AI Chat tables
db.run(`CREATE TABLE IF NOT EXISTS ai_conversations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title TEXT DEFAULT 'New Chat',
provider TEXT NOT NULL,
model TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_ai_conversations_user_id ON ai_conversations(user_id)');
db.run('CREATE INDEX IF NOT EXISTS idx_ai_conversations_updated_at ON ai_conversations(updated_at DESC)');
db.run(`CREATE TABLE IF NOT EXISTS ai_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
conversation_id INTEGER NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at INTEGER NOT NULL
)`);
db.run('CREATE INDEX IF NOT EXISTS idx_ai_messages_conversation_id ON ai_messages(conversation_id)');
db.all('PRAGMA table_info(ai_messages)', (pragmaErr, cols) => {
if (pragmaErr) return console.error('PRAGMA ai_messages error:', pragmaErr);
addColumnIfMissing('ai_messages', cols, 'attachments', 'TEXT DEFAULT NULL', {
errorLabel: 'ai_messages attachments migration error:',
onAdded: () => console.log('✓ Added attachments column to ai_messages')
});
});
// Enable WAL mode for better concurrent performance
db.run('PRAGMA journal_mode = WAL');
db.run('PRAGMA synchronous = NORMAL');
db.run('PRAGMA cache_size = -64000'); // 64MB cache
db.run('PRAGMA temp_store = MEMORY');
db.run('PRAGMA mmap_size = 30000000000'); // 30GB memory-mapped I/O
// Add performance indexes
db.run('CREATE INDEX IF NOT EXISTS idx_entries_created_at ON entries(created_at DESC)');
db.run('CREATE INDEX IF NOT EXISTS idx_entries_pinned ON entries(is_pinned, created_at DESC)');
db.run('CREATE INDEX IF NOT EXISTS idx_users_username ON users(username)');
// Migration: Add role column to users table
db.all('PRAGMA table_info(users)', (pragmaErr, cols) => {
if (pragmaErr) return console.error('PRAGMA users error:', pragmaErr);
const ensureUsersEmailIndex = () => {
db.run(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_unique ON users(email) WHERE email IS NOT NULL',
(indexErr) => {
if (indexErr) console.error('users email index migration error:', indexErr);
}
);
};
addColumnIfMissing('users', cols, 'role', 'TEXT DEFAULT "normal"', {
errorLabel: 'users role migration error:',
onAdded: () => {
console.log('✓ Added role column to users');
// Set first user to admin
db.run('UPDATE users SET role = "admin" WHERE id = 1', (updateErr) => {
if (updateErr) console.error('users role update error:', updateErr);
else console.log('✓ First user set to admin role');
});
}
});
if (!hasColumn(cols, 'email')) {
addColumnIfMissing('users', cols, 'email', 'TEXT', {
errorLabel: 'users email migration error:',
onAdded: () => {
console.log('✓ Added email column to users');
ensureUsersEmailIndex();
}
});
} else {
ensureUsersEmailIndex();
}
[
['email_verified_at', 'INTEGER'],
['can_pin', 'INTEGER DEFAULT 0'],
['last_login_at', 'INTEGER']
].forEach(([columnName, columnTypeSql]) => {
addColumnIfMissing('users', cols, columnName, columnTypeSql, {
errorLabel: `users ${columnName} migration error:`,
onAdded: () => console.log(`✓ Added ${columnName} column to users`)
});
});
});
});
// Configure S3 client for R2
const s3 = new S3Client({
region: process.env.R2_REGION || 'auto',
endpoint: process.env.R2_ENDPOINT || undefined,
credentials: process.env.R2_ACCESS_KEY_ID ? {
accessKeyId: process.env.R2_ACCESS_KEY_ID,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY
} : undefined,
});
function buildFileUrl(key) {
if (hasR2UploadConfig && process.env.R2_PUBLIC_BASE_URL) {
return `${process.env.R2_PUBLIC_BASE_URL.replace(/\/$/, '')}/${key}`;
}
if (hasR2UploadConfig && process.env.R2_ENDPOINT && process.env.R2_BUCKET) {
return `${process.env.R2_ENDPOINT.replace(/\/$/, '')}/${process.env.R2_BUCKET}/${key}`;
}
return `/uploads/${key}`;
}
function dbGetAsync(sql, params = []) {
return new Promise((resolve, reject) => {
db.get(sql, params, (err, row) => {
if (err) return reject(err);
resolve(row);
});
});
}
function dbAllAsync(sql, params = []) {
return new Promise((resolve, reject) => {
db.all(sql, params, (err, rows) => {
if (err) return reject(err);
resolve(rows);
});
});
}
function dbRunAsync(sql, params = []) {
return new Promise((resolve, reject) => {
db.run(sql, params, function runHandler(err) {
if (err) return reject(err);
resolve(this);
});
});
}
function normalizeEmail(value) {
return String(value || '').trim().toLowerCase();
}
function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
function generateVerificationCode() {
return String(Math.floor(100000 + Math.random() * 900000));
}
function maskEmail(email) {
const [local, domain] = String(email || '').split('@');
if (!local || !domain) return email;
const first = local.slice(0, 1);
const last = local.length > 1 ? local.slice(-1) : '';
return `${first}${'*'.repeat(Math.max(1, local.length - 2))}${last}@${domain}`;
}
let emailTransporter = null;
function getEmailTransporter() {
if (!EMAIL_VERIFICATION_ENABLED) return null;
if (emailTransporter) return emailTransporter;
const baseConfig = {
host: SMTP_HOST,
port: SMTP_PORT,
secure: SMTP_SECURE
};
if (SMTP_USER && SMTP_PASS) {
baseConfig.auth = {
user: SMTP_USER,
pass: SMTP_PASS
};
}
emailTransporter = nodemailer.createTransport(baseConfig);
return emailTransporter;
}
async function sendRegistrationVerificationEmail(email, username, code) {
const transporter = getEmailTransporter();
if (!transporter) throw new Error('Email verification is not configured');
await transporter.sendMail({
from: SMTP_FROM,
to: email,
subject: 'Your MyFoodWebsite confirmation code',
text: [
`Hi ${username},`,
'',
`Your confirmation code is: ${code}`,
`This code expires in ${REGISTRATION_CODE_TTL_MINUTES} minute(s).`,
'',
'If you did not request this, please ignore this email.'
].join('\n')
});
}
const ENTRY_SELECT_WITH_AUTHOR = `
SELECT e.*, u.username AS author_username, c.name AS collection_name
FROM entries e
LEFT JOIN users u ON u.id = e.user_id
LEFT JOIN collections c ON c.id = e.collection_id
`;
async function getEntryImagesForEntry(entryId, legacyEntry) {
const rows = await dbAllAsync(
'SELECT id, entry_id, filename, originalname, sort_order FROM entry_images WHERE entry_id = ? ORDER BY sort_order, id',
[entryId]
);
if (rows.length > 0) return rows;
if (legacyEntry && legacyEntry.filename) {
await dbRunAsync(
'INSERT INTO entry_images(entry_id, filename, originalname, sort_order) VALUES (?,?,?,?)',
[entryId, legacyEntry.filename, legacyEntry.originalname || null, 0]
);
return dbAllAsync(
'SELECT id, entry_id, filename, originalname, sort_order FROM entry_images WHERE entry_id = ? ORDER BY sort_order, id',
[entryId]
);
}
return [];
}
async function getEntryImagesMap(entryIds, entriesById) {
const map = {};
if (!entryIds.length) return map;
const placeholders = entryIds.map(() => '?').join(',');
const rows = await dbAllAsync(
`SELECT id, entry_id, filename, originalname, sort_order
FROM entry_images
WHERE entry_id IN (${placeholders})
ORDER BY entry_id, sort_order, id`,
entryIds
);
for (const row of rows) {
if (!map[row.entry_id]) map[row.entry_id] = [];
map[row.entry_id].push(row);
}
for (const entryId of entryIds) {
if (!map[entryId] || map[entryId].length === 0) {
const legacy = entriesById[entryId];
if (legacy && legacy.filename) {
map[entryId] = [{
id: null,
entry_id: entryId,
filename: legacy.filename,
originalname: legacy.originalname || null,
sort_order: 0
}];
} else {
map[entryId] = [];
}
}
}
return map;
}
async function deleteStoredFile(filename) {
if (!filename) return;
if (hasR2UploadConfig) {
await s3.send(new DeleteObjectCommand({
Bucket: process.env.R2_BUCKET,
Key: filename
}));
return;
}
const safeFilename = path.basename(filename);
await fs.promises.unlink(path.join(UPLOADS_DIR, safeFilename));
}
const HEIC_IMAGE_EXTENSIONS = new Set(['.heic', '.heif']);
const HEIC_IMAGE_MIME_TYPES = new Set(['image/heic', 'image/heif', 'image/heic-sequence', 'image/heif-sequence']);
const GENERIC_BINARY_MIME_TYPES = new Set(['', 'application/octet-stream', 'binary/octet-stream']);
function getFileExtensionFromUpload(file) {
return path.extname(String(file?.originalname || '')).toLowerCase();
}
function getNormalizedMimeType(value) {
return String(value || '').trim().toLowerCase();
}
function isHeicImageUpload(file) {
const mime = getNormalizedMimeType(file?.mimetype);
if (HEIC_IMAGE_MIME_TYPES.has(mime)) return true;
const ext = getFileExtensionFromUpload(file);
return HEIC_IMAGE_EXTENSIONS.has(ext) && GENERIC_BINARY_MIME_TYPES.has(mime);
}
function isSupportedPhotoUpload(file) {
const mime = getNormalizedMimeType(file?.mimetype);
if (mime.startsWith('image/')) return true;
return isHeicImageUpload(file);
}
function getStorageContentType(file) {
const mime = getNormalizedMimeType(file?.mimetype);
if (mime && !GENERIC_BINARY_MIME_TYPES.has(mime)) return mime;
if (isHeicImageUpload(file)) return 'image/heic';
return mime || 'application/octet-stream';
}
async function optimizeImageBuffer(buffer, mimetype) {
try {
// Only optimize images, not videos or other files
if (!mimetype || !mimetype.startsWith('image/')) {
return buffer;
}
const image = sharp(buffer);
const metadata = await image.metadata();
// Skip if image is already small enough
if (metadata.width <= 1920 && metadata.height <= 1920 && buffer.length < 500000) {
return buffer;
}
// Resize and compress
const optimized = await image
.resize(1920, 1920, {
fit: 'inside',