-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathserver.js
More file actions
1874 lines (1612 loc) · 60.4 KB
/
Copy pathserver.js
File metadata and controls
1874 lines (1612 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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 express = require("express");
const cors = require("cors");
const multer = require("multer");
const axios = require("axios");
const fs = require("fs");
const fsPromises = require("fs/promises");
const path = require("path");
const crypto = require("crypto");
const { domainToASCII } = require("url");
const { rateLimit } = require("express-rate-limit");
const slowDown = require("express-slow-down");
const helmet = require("helmet");
const jwt = require("jsonwebtoken");
const {
askSchema,
askCredentialSchema,
askPayloadSchema,
summarizeSchema,
summarizeCredentialSchema,
sessionsLookupSchema,
knowledgeGapsSchema,
generateFlashcardsSchema,
updateFlashcardProgressSchema,
MAX_QUESTION_LENGTH,
} = require("./validators/schemas");
const { clientIpFromRequest } = require("./security/ip");
const { createRedisClient } = require("./security/redis");
const authRoutes = require("./src/routes/authRoutes");
const RAG_SERVICE_URL = process.env.RAG_SERVICE_URL || "http://localhost:5000";
const getInternalRagToken = () => (process.env.INTERNAL_RAG_TOKEN || "").trim();
const PORT = process.env.PORT || 4000;
const SUPABASE_JWT_SECRET = (process.env.SUPABASE_JWT_SECRET || "").trim();
// ─── Credential Validation Cache ─────────────────────────────────────────────
// session_id and session_secret are structurally identical on every request
// within a session (same UUID, same secret). Re-running the full Zod parse
// for every /ask and /summarize call under Socratic/Tutor mode burns event-loop
// time on checks that cannot possibly fail for an already-validated credential.
//
// The cache is keyed on HMAC-SHA256(session_id:session_secret)[0:16] so the
// actual secret is never stored. TTL matches SESSION_TTL_MINUTES so entries
// expire when the RAG session would have expired anyway. The map is bounded at
// CRED_CACHE_MAX entries; when full the oldest entry (insertion order) is evicted.
const _SESSION_TTL_MS =
parseInt(process.env.SESSION_TTL_MINUTES || "43200", 10) * 60 * 1000;
const _CRED_CACHE_MAX = parseInt(process.env.CRED_CACHE_MAX_SIZE || "1000", 10);
const _credCache = new Map(); // key → { validatedAt: number }
const _hmacKey = crypto
.createHash("sha256")
.update("pdf-qa-cred-cache")
.digest();
function _credKey(sessionId, sessionSecret) {
return crypto
.createHmac("sha256", _hmacKey)
.update(`${sessionId}:${sessionSecret}`)
.digest("hex")
.slice(0, 16);
}
function _credCacheHit(sessionId, sessionSecret) {
const k = _credKey(sessionId, sessionSecret);
const entry = _credCache.get(k);
if (!entry) return false;
if (Date.now() - entry.validatedAt > _SESSION_TTL_MS) {
_credCache.delete(k);
return false;
}
return true;
}
function _credCacheStore(sessionId, sessionSecret) {
const k = _credKey(sessionId, sessionSecret);
if (_credCache.size >= _CRED_CACHE_MAX) {
_credCache.delete(_credCache.keys().next().value); // evict oldest (FIFO)
}
_credCache.set(k, { validatedAt: Date.now() });
}
function _credCacheDrop(sessionId, sessionSecret) {
_credCache.delete(_credKey(sessionId, sessionSecret));
}
// Validate /ask body: always parse payload fields (question, mode change per
// request); short-circuit credential fields on cache hit.
function validateAskBody(body) {
const rawId = typeof body?.session_id === "string" ? body.session_id : "";
const rawSecret =
typeof body?.session_secret === "string" ? body.session_secret : "";
const payloadResult = askPayloadSchema.safeParse(body);
if (!payloadResult.success) {
return { success: false, error: payloadResult.error };
}
if (_credCacheHit(rawId, rawSecret)) {
return {
success: true,
data: { ...payloadResult.data, session_id: rawId, session_secret: rawSecret },
};
}
const credResult = askCredentialSchema.safeParse(body);
if (!credResult.success) {
return { success: false, error: credResult.error };
}
_credCacheStore(rawId, rawSecret);
return { success: true, data: { ...payloadResult.data, ...credResult.data } };
}
// Validate /summarize body: only credential fields; short-circuit on cache hit.
function validateSummarizeBody(body) {
const rawId = typeof body?.session_id === "string" ? body.session_id : "";
const rawSecret =
typeof body?.session_secret === "string" ? body.session_secret : "";
if (_credCacheHit(rawId, rawSecret)) {
return { success: true, data: { session_id: rawId, session_secret: rawSecret } };
}
const result = summarizeCredentialSchema.safeParse(body);
if (!result.success) {
return { success: false, error: result.error };
}
_credCacheStore(rawId, rawSecret);
return { success: true, data: result.data };
}
const app = express();
// ─── Distributed Rate Limiting / Ban Store ───────────────────────────────────
// The in-memory stores are safe only for single-instance deployments. In any
// multi-replica setup (Kubernetes / PM2 cluster / autoscaling), a per-process
// store can be bypassed via load balancer round-robin.
const RATE_LIMIT_STORE = (process.env.RATE_LIMIT_STORE || "memory").toLowerCase();
const RATE_LIMIT_REDIS_URL =
process.env.RATE_LIMIT_REDIS_URL || process.env.REDIS_URL || "";
let redisClient = null;
let redisConnectPromise = null;
if (RATE_LIMIT_STORE === "redis") {
if (!RATE_LIMIT_REDIS_URL) {
throw new Error(
"RATE_LIMIT_STORE=redis requires RATE_LIMIT_REDIS_URL (or REDIS_URL) to be set.",
);
}
const { client, connectPromise } = createRedisClient(RATE_LIMIT_REDIS_URL);
redisClient = client;
redisConnectPromise = connectPromise;
}
// ─── Trust Proxy ────────────────────────────────────────────────────────────
// Critical for cloud deployments (AWS ALB, Cloudflare, Nginx). Without this,
// Express only sees the load-balancer IP, so the rate limiter would lock out
// ALL users the moment a single attacker spams the API.
// Set to the number of reverse proxies in front of this server (e.g. PROXY_COUNT=1).
const PROXY_COUNT = parseInt(process.env.PROXY_COUNT || "0", 10);
if (PROXY_COUNT > 0) {
app.set("trust proxy", PROXY_COUNT);
}
// ─── Helmet — HTTP Security Headers ─────────────────────────────────────────
// Hardens the HTTP layer against clickjacking, MIME sniffing, XSS, etc.
// These headers are your first line of defence before any code even runs.
app.use(helmet());
app.use(cors({
origin: process.env.ALLOWED_ORIGIN || "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true,
}));
// ─── Body Size Limit ─────────────────────────────────────────────────────────
// Cap JSON payloads at 16 KB. Prevents memory exhaustion from huge JSON bodies
// sent to /ask or /summarize by an attacker trying to blow out the parser.
app.use(express.json({ limit: "16kb" }));
// ─── IP Ban Registry ─────────────────────────────────────────────────────────
// In-memory stepped ban system. Each time an IP trips a rate limiter, its
// offence count increments and the ban window grows on a fixed stepped schedule
// (not exponential/doubling — see BAN_DURATIONS_MS for the exact policy).
// Offence 1 → 5 min ban | Offence 2 → 15 min | Offence 3+ → 1 hour
// This is a lightweight, zero-dependency solution suitable for single-instance
// deployments. For multi-instance cloud deployments, replace with Redis.
const bannedIPs = new Map(); // ip → { until: timestamp, offences: number }
const BAN_DURATIONS_MS = [
5 * 60 * 1000, // Offence 1 → 5 minutes
15 * 60 * 1000, // Offence 2 → 15 minutes
60 * 60 * 1000, // Offence 3+ → 1 hour
];
const BAN_REDIS_PREFIX = process.env.BAN_REDIS_PREFIX || "ban:";
const recordOffence = (ip) => {
const existing = bannedIPs.get(ip) || { offences: 0 };
const offences = existing.offences + 1;
const durationIndex = Math.min(offences - 1, BAN_DURATIONS_MS.length - 1);
const until = Date.now() + BAN_DURATIONS_MS[durationIndex];
bannedIPs.set(ip, { until, offences });
console.warn(`[BAN] IP=${ip} offences=${offences} banned until=${new Date(until).toISOString()}`);
};
const recordOffenceDistributed = async (ip) => {
if (!redisClient) return;
const key = `${BAN_REDIS_PREFIX}${ip}`;
// Lua for atomic offence increment + TTL update.
// Keeps behavior aligned with the in-memory version (offences reset when TTL expires).
const script = `
local key = KEYS[1]
local now = tonumber(ARGV[1])
local offences = redis.call("HINCRBY", key, "offences", 1)
local len = #ARGV - 1
local idx = offences
if idx > len then idx = len end
local duration = tonumber(ARGV[1 + idx])
local until = now + duration
redis.call("HSET", key, "until", until)
redis.call("PEXPIRE", key, duration)
return { offences, until }
`;
try {
const res = await redisClient.sendCommand([
"EVAL",
script,
"1",
key,
String(Date.now()),
...BAN_DURATIONS_MS.map(String),
]);
const offences = Array.isArray(res) ? Number(res[0]) : NaN;
const until = Array.isArray(res) ? Number(res[1]) : NaN;
if (Number.isFinite(offences) && Number.isFinite(until)) {
console.warn(
`[BAN] IP=${ip} offences=${offences} banned until=${new Date(until).toISOString()} (redis)`,
);
}
} catch (err) {
console.warn("[BAN] redis ban write failed:", err?.message || err);
}
};
// Purge expired bans every 10 minutes so the Map doesn't grow forever.
if (!redisClient) {
const banCleanupInterval = setInterval(() => {
const now = Date.now();
for (const [ip, ban] of bannedIPs.entries()) {
if (ban.until <= now) bannedIPs.delete(ip);
}
}, 10 * 60 * 1000);
if (typeof banCleanupInterval.unref === "function") {
banCleanupInterval.unref();
}
}
// Ban-check middleware — runs before every route.
const banGuard = async (req, res, next) => {
const ip = clientIpFromRequest(req);
if (!ip) return next();
if (redisClient) {
try {
const key = `${BAN_REDIS_PREFIX}${ip}`;
const until = await redisClient.sendCommand(["HGET", key, "until"]);
const untilMs = until ? Number(until) : NaN;
if (Number.isFinite(untilMs) && untilMs > Date.now()) {
const retryAfterSec = Math.ceil((untilMs - Date.now()) / 1000);
res.set("Retry-After", String(retryAfterSec));
return res.status(429).json({
error: `Your IP has been temporarily banned due to repeated abuse. Try again in ${Math.ceil(retryAfterSec / 60)} minute(s).`,
});
}
} catch (err) {
// Fail-open: don't take the whole API down if Redis is transiently unavailable.
console.warn("[BAN] redis ban read failed:", err?.message || err);
}
return next();
}
const ban = bannedIPs.get(ip);
if (ban && ban.until > Date.now()) {
const retryAfterSec = Math.ceil((ban.until - Date.now()) / 1000);
res.set("Retry-After", String(retryAfterSec));
return res.status(429).json({
error: `Your IP has been temporarily banned due to repeated abuse. Try again in ${Math.ceil(retryAfterSec / 60)} minute(s).`,
});
}
return next();
};
// A handler factory that records an offence then returns 429.
// Pass this as the `handler` option to any rateLimit() config.
const rateLimitHandler = (req, res) => {
const ip = clientIpFromRequest(req);
if (redisClient) {
void recordOffenceDistributed(ip);
} else {
recordOffence(ip);
}
res.status(429).json({
error: res.locals.rateLimitMessage || "Too many requests. Please slow down.",
});
};
const parsePositiveIntegerEnv = (rawValue, fallbackValue, name) => {
const candidate = (rawValue ?? "").toString().trim();
const value = candidate === "" ? String(fallbackValue) : candidate;
if (!/^\d+$/.test(value)) {
throw new Error(`${name} must be a positive integer. Received: "${rawValue}".`);
}
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new Error(`${name} must be a positive integer greater than 0.`);
}
return parsed;
};
const parseUploadFileSizeLimitBytes = () => {
if (typeof process.env.UPLOAD_MAX_FILE_SIZE_BYTES === "string" && process.env.UPLOAD_MAX_FILE_SIZE_BYTES.trim() !== "") {
return parsePositiveIntegerEnv(
process.env.UPLOAD_MAX_FILE_SIZE_BYTES,
20_000_000,
"UPLOAD_MAX_FILE_SIZE_BYTES",
);
}
if (typeof process.env.MAX_UPLOAD_SIZE_MB === "string" && process.env.MAX_UPLOAD_SIZE_MB.trim() !== "") {
const maxUploadSizeMb = parsePositiveIntegerEnv(
process.env.MAX_UPLOAD_SIZE_MB,
20,
"MAX_UPLOAD_SIZE_MB",
);
return maxUploadSizeMb * 1024 * 1024;
}
return 20_000_000;
};
// ─── Rate Limiters ───────────────────────────────────────────────────────────
const keyGenerator = (req) => clientIpFromRequest(req) || "unknown";
// Note: express-rate-limit's `ipv6Subnet` is not compatible with a custom
// `keyGenerator`. If you need IPv6 masking, implement it inside `clientIpFromRequest`.
let RedisStore = null;
if (redisClient) {
// Loaded only when RATE_LIMIT_STORE=redis is enabled.
({ RedisStore } = require("rate-limit-redis"));
}
const createLimiterStore = (prefix) => {
if (!redisClient || !RedisStore) return undefined;
return new RedisStore({
sendCommand: (...args) => redisClient.sendCommand(args),
prefix,
});
};
const RATE_LIMIT_WINDOW_MS = parsePositiveIntegerEnv(
process.env.RATE_LIMIT_WINDOW_MS,
60_000,
"RATE_LIMIT_WINDOW_MS",
);
const RATE_LIMIT_MAX = parsePositiveIntegerEnv(
process.env.RATE_LIMIT_MAX,
60,
"RATE_LIMIT_MAX",
);
// Global baseline — broad bot/scraper protection across every route.
// 200 req / 15 min per IP. Tripping this triggers the escalating ban.
const globalLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 200,
standardHeaders: "draft-7",
legacyHeaders: false,
keyGenerator,
store: createLimiterStore("rl:global:"),
handler: (req, res) => {
res.locals.rateLimitMessage = "Too many requests. Please slow down and try again later.";
rateLimitHandler(req, res);
},
});
// Route-specific cap for upload and inference endpoints.
// Tripping this triggers the ban system.
const uploadLimiter = rateLimit({
windowMs: RATE_LIMIT_WINDOW_MS,
max: RATE_LIMIT_MAX,
standardHeaders: "draft-7",
legacyHeaders: false,
keyGenerator,
store: createLimiterStore("rl:upload:"),
handler: (req, res) => {
res.locals.rateLimitMessage = "Too many requests. Please slow down and try again later.";
rateLimitHandler(req, res);
},
});
// Inference slow-down — adds progressive friction BEFORE the hard block fires.
// RATE_LIMIT_SLOWDOWN_AFTER (default 10): number of free requests per window.
// After that, each extra request incurs an additional (hits - delayAfter) * 500ms
// delay, starting at 500ms and capped at 5s. This gives a genuine linear ramp
// instead of jumping straight to multi-second delays on the very first hit over
// the threshold. Kept separate from RATE_LIMIT_INFERENCE_MAX so operators can
// tune slow-down friction and hard-block quota independently.
const SLOWDOWN_DELAY_AFTER = parseInt(process.env.RATE_LIMIT_SLOWDOWN_AFTER || "10", 10);
const inferenceSlowDown = slowDown({
windowMs: 5 * 60 * 1000,
delayAfter: SLOWDOWN_DELAY_AFTER,
delayMs: (hits) => (hits - SLOWDOWN_DELAY_AFTER) * 500,
maxDelayMs: 5000,
keyGenerator,
store: createLimiterStore("sd:inference:"),
});
// Inference hard limiter — fires after slow-down window if the attacker still
// keeps hammering. Triggers the escalating ban on violation.
const inferenceLimiter = rateLimit({
windowMs: RATE_LIMIT_WINDOW_MS,
max: RATE_LIMIT_MAX,
standardHeaders: "draft-7",
legacyHeaders: false,
keyGenerator,
store: createLimiterStore("rl:inference:"),
handler: (req, res) => {
res.locals.rateLimitMessage = "Too many requests. Please slow down and try again later.";
rateLimitHandler(req, res);
},
});
const UPLOAD_MAX_CONCURRENT_PER_IP = parsePositiveIntegerEnv(
process.env.UPLOAD_MAX_CONCURRENT_PER_IP,
2,
"UPLOAD_MAX_CONCURRENT_PER_IP",
);
const activeUploadsByIp = new Map();
const releaseUploadSlot = (ip) => {
if (!ip) return;
const currentCount = activeUploadsByIp.get(ip);
if (!currentCount) return;
if (currentCount <= 1) {
activeUploadsByIp.delete(ip);
} else {
activeUploadsByIp.set(ip, currentCount - 1);
}
};
const uploadConcurrencyGuard = (req, res, next) => {
const ip = clientIpFromRequest(req) || "unknown";
const currentCount = activeUploadsByIp.get(ip) || 0;
if (currentCount >= UPLOAD_MAX_CONCURRENT_PER_IP) {
console.warn(
`[upload] concurrent upload limit reached for IP=${ip} active=${currentCount} cap=${UPLOAD_MAX_CONCURRENT_PER_IP}`,
);
return res.status(429).json({
error: "Too many concurrent uploads. Please wait for an active upload to finish.",
});
}
activeUploadsByIp.set(ip, currentCount + 1);
let released = false;
const release = () => {
if (released) return;
released = true;
releaseUploadSlot(ip);
};
req.releaseUploadSlot = release;
res.on("finish", release);
res.on("close", release);
return next();
};
// Apply global limiter before ban guard so DB-backed ban checks are rate-limited.
app.use(globalLimiter);
app.use(banGuard);
app.use("/api/auth", authRoutes);
// ─── File Size Limits ──────────────────────────────────────────────────────────
// UPLOAD_MAX_FILE_SIZE_BYTES controls the maximum PDF file size allowed per upload.
// Default is 20,000,000 bytes. A legacy MAX_UPLOAD_SIZE_MB value is still honored
// when the new bytes-based env var is not set.
const MAX_PDF_SIZE_BYTES = parseUploadFileSizeLimitBytes();
const UPLOADS_DIR = path.resolve("uploads");
const isDevelopment = process.env.NODE_ENV !== "production";
if (!fs.existsSync(UPLOADS_DIR)) {
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
}
// ─── Background File Cleanup (safety net) ────────────────────────────────────
// Uploaded PDFs are deleted from disk immediately after the RAG service has
// finished indexing them (see cleanupFile call in the /upload success path).
// This interval is a safety net only: it removes any files that survived the
// immediate delete — e.g. because cleanupFile threw or the process crashed
// mid-request. The window is deliberately short (1 hour default) so orphaned
// files do not linger and cannot be accessed via direct path guessing.
//
// The /uploads directory is intentionally NOT mounted as a static file server.
// Serving PDFs through express.static would let any caller with a filename
// download the raw document with no session_secret check. Files must be
// accessed only through the authenticated /pdf/:filename route (if re-introduced
// in future) or via the in-browser blob URL created by URL.createObjectURL on
// the frontend.
const FILE_RETENTION_MS = parseInt(process.env.FILE_RETENTION_MS || "3600000", 10);
const CLEANUP_INTERVAL_MS = parseInt(process.env.CLEANUP_INTERVAL_MS || "3600000", 10);
const startUploadsCleanup = () => {
const intervalId = setInterval(async () => {
try {
const files = await fsPromises.readdir(UPLOADS_DIR);
const now = Date.now();
for (const file of files) {
if (file === ".gitkeep") continue;
const filePath = path.join(UPLOADS_DIR, file);
try {
const stats = await fsPromises.stat(filePath);
if (now - stats.birthtimeMs > FILE_RETENTION_MS) {
await fsPromises.unlink(filePath);
if (isDevelopment) {
console.log(`[cleanup] safety-net deleted orphaned file: ${path.basename(filePath)}`);
}
}
} catch (err) {
if (err.code !== "ENOENT") {
console.error(`[cleanup] failed to remove ${path.basename(filePath)}:`, err.message);
}
}
}
} catch (err) {
console.error("[cleanup] failed to read uploads directory:", err.message);
}
}, CLEANUP_INTERVAL_MS);
if (typeof intervalId.unref === "function") {
intervalId.unref();
}
};
startUploadsCleanup();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, UPLOADS_DIR);
},
filename: (req, file, cb) => {
cb(null, `${crypto.randomUUID()}.pdf`);
},
});
const upload = multer({
storage,
limits: {
fileSize: MAX_PDF_SIZE_BYTES,
// Additional limits to prevent abuse
files: 1, // Only allow one file per request
},
fileFilter: (req, file, cb) => {
const isPdfMime = file.mimetype === "application/pdf";
const isPdfExtension = file.originalname.toLowerCase().endsWith(".pdf");
if (!isPdfMime || !isPdfExtension) {
return cb(new Error("Only PDF files are allowed."));
}
cb(null, true);
},
});
const cleanupFile = async (filePath) => {
if (!filePath) return;
try {
const safePath = path.join(UPLOADS_DIR, path.basename(filePath));
await fsPromises.unlink(safePath);
if (isDevelopment) {
console.log(`[upload] deleted temp file: ${path.basename(safePath)}`);
}
} catch (err) {
// ENOENT means the file was already removed — treat as success.
if (err.code !== "ENOENT") {
console.error(`[upload] failed to delete temp file:`, err.message);
}
}
};
const sendUploadError = (res, statusCode, message, details = message) => {
console.error("Upload failed:", details);
return res.status(statusCode).json({
error: message,
details,
});
};
const stringifyServiceDetails = (details) => {
if (details == null) return "";
if (Buffer.isBuffer(details)) {
return details.toString("utf8").trim();
}
if (typeof details === "string") {
return details.trim();
}
if (typeof details === "object") {
const nested =
stringifyServiceDetails(details.detail) ||
stringifyServiceDetails(details.error) ||
stringifyServiceDetails(details.message);
if (nested) return nested;
const hasKnownErrorField =
Object.prototype.hasOwnProperty.call(details, "detail") ||
Object.prototype.hasOwnProperty.call(details, "error") ||
Object.prototype.hasOwnProperty.call(details, "message");
if (hasKnownErrorField && Object.keys(details).length <= 3) {
return "";
}
try {
const serialized = JSON.stringify(details);
return serialized === "{}" ? "" : serialized;
} catch (_) {
return "";
}
}
return String(details).trim();
};
const extractServiceDetails = (err, fallbackMessage = "Upstream service request failed.") => {
return (
stringifyServiceDetails(err.response?.data) ||
stringifyServiceDetails(err.message) ||
stringifyServiceDetails(err.code) ||
fallbackMessage
);
};
const requireInternalRagToken = () => {
if (!getInternalRagToken()) {
console.error("INTERNAL_RAG_TOKEN must be configured for RAG service requests.");
throw new Error("INTERNAL_RAG_TOKEN must be configured for RAG service requests.");
}
};
const ragAuthHeaders = () => {
const token = getInternalRagToken();
if (!token) {
throw new Error("INTERNAL_RAG_TOKEN must be configured for RAG service requests.");
}
return { "X-Internal-Token": token };
};
// When the RAG service is still loading models it returns 503 with a
// Retry-After header. Forward both the status code and the header to the
// client so it knows how long to wait before retrying rather than receiving
// a generic 500 with no guidance.
const propagateRagError = (err, res, fallback) => {
const status = err.response?.status || 500;
const detail = extractServiceDetails(err, fallback);
if (status === 503) {
const retryAfter = err.response?.headers?.["retry-after"] || "30";
res.set("Retry-After", String(retryAfter));
}
return res.status(status).json({
error: typeof detail === "string" ? detail : fallback,
details: isDevelopment ? detail : "Internal processing error",
});
};
const normalizeSessionSecret = (value) =>
typeof value === "string" ? value.trim() || null : null;
const SESSION_SECRET_COOKIE_PREFIX = "pdfqa_session_secret_";
const getSessionSecretCookieName = (sessionId) =>
`${SESSION_SECRET_COOKIE_PREFIX}${sessionId}`;
const SESSION_SECRET_TTL_MS = (parseInt(process.env.SESSION_SECRET_COOKIE_TTL_DAYS || "7", 10) || 7) * 24 * 60 * 60 * 1000;
const SESSION_SECRET_REDIS_URL = process.env.SESSION_SECRET_REDIS_URL || RATE_LIMIT_REDIS_URL || process.env.REDIS_URL || "";
const SESSION_SECRET_REDIS_PREFIX = "session-secret:";
const SESSION_SECRET_MEMORY_MAP = new Map(); // token -> { encrypted: string, expiry }
// Cookie SameSite configuration for session-secret fallback cookie.
// Default: 'lax'. Operators can set to 'none' when frontend+API are cross-site,
// but that requires Secure to be true per browser rules.
const SESSION_SECRET_COOKIE_SAMESITE = (process.env.SESSION_SECRET_COOKIE_SAMESITE || "lax").toString();
let sessionSecretRedisClient = null;
let sessionSecretRedisConnectPromise = null;
if (SESSION_SECRET_REDIS_URL) {
if (redisClient) {
sessionSecretRedisClient = redisClient;
} else {
({ client: sessionSecretRedisClient, connectPromise: sessionSecretRedisConnectPromise } = createRedisClient(SESSION_SECRET_REDIS_URL));
}
if (sessionSecretRedisConnectPromise) {
void sessionSecretRedisConnectPromise.catch((err) => {
console.warn("[session-secret] redis connect failed:", err?.message || err);
});
}
}
// Encryption key must be provided via env var as base64-encoded 32 bytes.
// If not present, generate a runtime-only key (lost on restart) and log a warning.
let ENC_KEY = null;
const _initEncKey = () => {
if (ENC_KEY) return;
const fromEnv = (process.env.SESSION_SECRET_ENC_KEY || "").trim();
if (fromEnv) {
try {
const buf = Buffer.from(fromEnv, "base64");
if (buf.length === 32) {
ENC_KEY = buf;
} else {
console.warn("SESSION_SECRET_ENC_KEY must be 32 bytes base64; falling back to runtime key");
}
} catch (_) {
console.warn("Invalid SESSION_SECRET_ENC_KEY; falling back to runtime key");
}
}
if (!ENC_KEY) {
// If Redis-backed storage is enabled (or specifically sessionSecretRedisClient is set)
// and we're running in production, require a persistent encryption key so
// stored values remain decryptable across restarts. Falling back to a
// runtime-only key in this configuration leads to opaque failures.
if (sessionSecretRedisClient && process.env.NODE_ENV === "production") {
throw new Error("SESSION_SECRET_ENC_KEY is required when using Redis-backed session secret storage in production");
}
ENC_KEY = crypto.randomBytes(32);
console.warn("No SESSION_SECRET_ENC_KEY provided — generated runtime-only key (won't persist across restarts)");
}
};
const _encryptSecret = (secret) => {
_initEncKey();
const iv = crypto.randomBytes(12); // recommended IV size for AES-GCM
const cipher = crypto.createCipheriv("aes-256-gcm", ENC_KEY, iv);
const ciphertext = Buffer.concat([cipher.update(secret, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
// Store as base64 segments iv:ciphertext:tag
return `${iv.toString("base64")}:${ciphertext.toString("base64")}:${tag.toString("base64")}`;
};
const _decryptSecret = (blob) => {
if (!blob) return null;
_initEncKey();
try {
const [ivB64, ctB64, tagB64] = blob.split(":");
const iv = Buffer.from(ivB64, "base64");
const ct = Buffer.from(ctB64, "base64");
const tag = Buffer.from(tagB64, "base64");
const decipher = crypto.createDecipheriv("aes-256-gcm", ENC_KEY, iv);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([decipher.update(ct), decipher.final()]);
return decrypted.toString("utf8");
} catch (e) {
console.warn("Failed to decrypt session secret token:", e?.message || e);
return null;
}
};
const _sessionSecretRedisKey = (token) => `${SESSION_SECRET_REDIS_PREFIX}${token}`;
const _storeSessionSecretInRedis = async (token, encrypted, expiry) => {
if (!sessionSecretRedisClient) {
return false;
}
try {
await sessionSecretRedisClient.set(
_sessionSecretRedisKey(token),
JSON.stringify({ encrypted, expiry }),
{ PX: SESSION_SECRET_TTL_MS },
);
return true;
} catch (err) {
console.warn("[session-secret] redis write failed:", err?.message || err);
return false;
}
};
const _readSessionSecretFromRedis = async (token) => {
if (!sessionSecretRedisClient) {
return null;
}
try {
const raw = await sessionSecretRedisClient.get(_sessionSecretRedisKey(token));
if (!raw) {
return null;
}
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed.encrypted !== "string") {
return null;
}
if (typeof parsed.expiry === "number" && parsed.expiry <= Date.now()) {
return null;
}
return parsed.encrypted;
} catch (err) {
console.warn("[session-secret] redis read failed:", err?.message || err);
return null;
}
};
const _storeSessionSecret = async (token, sessionSecret) => {
if (!token || !sessionSecret) return false;
const expiry = Date.now() + SESSION_SECRET_TTL_MS;
const encrypted = _encryptSecret(sessionSecret);
if (sessionSecretRedisClient) {
await _storeSessionSecretInRedis(token, encrypted, expiry);
}
SESSION_SECRET_MEMORY_MAP.set(token, { encrypted, expiry });
// Only create a per-token timer for in-memory fallback. When Redis is
// configured we rely on Redis TTLs and lazy eviction to avoid creating
// large numbers of active timers in-process.
if (!sessionSecretRedisClient) {
const timeout = setTimeout(() => {
SESSION_SECRET_MEMORY_MAP.delete(token);
}, SESSION_SECRET_TTL_MS + 1000);
if (typeof timeout.unref === "function") {
timeout.unref();
}
}
return true;
};
const _lookupSessionSecret = async (token) => {
if (!token) return null;
const encryptedFromRedis = await _readSessionSecretFromRedis(token);
if (encryptedFromRedis) {
return _decryptSecret(encryptedFromRedis);
}
const entry = SESSION_SECRET_MEMORY_MAP.get(token);
if (!entry) return null;
if (entry.expiry <= Date.now()) {
SESSION_SECRET_MEMORY_MAP.delete(token);
return null;
}
return _decryptSecret(entry.encrypted);
};
const readRequestCookies = (req) => {
const header = req.headers.cookie;
if (!header || typeof header !== "string") {
return {};
}
return header.split(";").reduce((cookies, pair) => {
const separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
return cookies;
}
const rawName = pair.slice(0, separatorIndex).trim();
const rawValue = pair.slice(separatorIndex + 1).trim();
if (!rawName) {
return cookies;
}
try {
cookies[rawName] = decodeURIComponent(rawValue);
} catch (_) {
cookies[rawName] = rawValue;
}
return cookies;
}, {});
};
const getSessionSecretFromCookie = async (req, sessionId) => {
if (!sessionId) {
return null;
}
const cookies = readRequestCookies(req);
const rawCookieValue = normalizeSessionSecret(cookies[getSessionSecretCookieName(sessionId)]);
if (!rawCookieValue) return null;
const resolvedFromStore = await _lookupSessionSecret(rawCookieValue);
if (resolvedFromStore) {
return resolvedFromStore;
}
// Legacy compatibility: older clients/tests may still send the plaintext
// session secret in the cookie. Only accept the raw value when it is not one
// of our generated UUID-like tokens, so token loss on restart does not
// silently fall back to an opaque token string.
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(rawCookieValue)) {
return rawCookieValue;
}
return null;
};
const resolveSessionSecret = async (req, sessionId, providedSecret) =>
normalizeSessionSecret(providedSecret) || getSessionSecretFromCookie(req, sessionId);
const setSessionSecretCookie = async (res, sessionId, sessionSecret) => {
if (!sessionId || !sessionSecret) {
return;
}
// Store the real secret server-side and put only a random token in the cookie.
// Generate the token outside the storage helper so cookie data never flows
// from a function that accepts the sensitive plaintext secret.
const token = crypto.randomUUID();
const stored = await _storeSessionSecret(token, sessionSecret);
if (!stored) return;
// Respect operator-configured SameSite. If operators explicitly request
// 'none', ensure the Secure flag is set (browsers require this for None).
const sameSiteRaw = (SESSION_SECRET_COOKIE_SAMESITE || "lax").toString();
const sameSite = ("" + sameSiteRaw).toLowerCase();
const secureFlag = process.env.NODE_ENV === "production" || sameSite === "none";
if (sameSite === "none" && !secureFlag) {
console.warn("SESSION_SECRET_COOKIE_SAMESITE=none was requested but secure cookies are not enabled; forcing Secure flag to true for compatibility.");
}
res.cookie(getSessionSecretCookieName(sessionId), token, {
httpOnly: true,
sameSite: sameSiteRaw,
secure: !!secureFlag,
path: "/",
maxAge: SESSION_SECRET_TTL_MS,
});
};
const attachSessionSecrets = async (req, sessions) => {
if (!Array.isArray(sessions)) {
return [];
}
return Promise.all(sessions.map(async (session) => {
const sessionId = session?.session_id;
const sessionSecret = await resolveSessionSecret(req, sessionId, session?.session_secret);
return {
...session,
session_secret: sessionSecret,
};
}));
};
const SUPABASE_ALLOWED_HOST_SUFFIXES = new Set(["supabase.co", "supabase.in"]);
const normalizeHostnameForAllowlist = (hostname) => {
if (typeof hostname !== "string") return null;
const normalizedHostname = hostname.trim().toLowerCase().replace(/\.+$/, "");
if (!normalizedHostname) return null;
const asciiHostname = domainToASCII(normalizedHostname);
if (!asciiHostname) return null;
return asciiHostname.toLowerCase().replace(/\.+$/, "");
};
const isAllowedSupabaseHostname = (hostname) => {
const normalizedHostname = normalizeHostnameForAllowlist(hostname);
if (!normalizedHostname) return false;
const hostnameLabels = normalizedHostname.split(".");