-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2585 lines (2328 loc) · 90.5 KB
/
server.js
File metadata and controls
2585 lines (2328 loc) · 90.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
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
// Backend proxy server for RSS feeds (avoids CORS issues)
import dotenv from 'dotenv';
import express from 'express';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { createServer } from 'http';
import { setDefaultResultOrder } from 'node:dns';
import dns from 'node:dns/promises';
import net from 'node:net';
import iconv from 'iconv-lite';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import crypto from 'node:crypto';
import {
fetchHtmlSnippetBounded,
MAX_HTML_LOGO_SNIPPET_BYTES,
MAX_HTML_YOUTUBE_RESOLVE_BYTES,
} from './lib/fetchHtmlBounded.js';
import { extractArticleWithCache } from './lib/articleExtract.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load .env from the directory containing this file (reliable when cwd ≠ project root).
dotenv.config({ path: join(__dirname, '.env') });
// Prefer IPv4 when resolving hostnames — some CDNs (incl. YouTube) behave differently on IPv6 vs IPv4.
setDefaultResultOrder('ipv4first');
if (process.env.NODE_ENV === 'development') {
const ytOk = Boolean(process.env.YOUTUBE_DATA_API_KEY?.trim());
console.log(
`[actufeed] API .env: ${join(__dirname, '.env')} | YOUTUBE_DATA_API_KEY ${ytOk ? 'loaded (channel search + YouTube resolve without Atom fetch when possible)' : 'missing (channel search 503; YouTube resolve needs Atom probe)'}`
);
console.log(
'[actufeed] YouTube search logs: prefix [YouTube channel-search]. If the UI shows HTML/JSON errors but no "request" line when you search, traffic is not reaching this API (Vite proxy / BACKEND_PROXY_TARGET / port).'
);
}
const app = express();
// Ports: set VITE_PORT / BACKEND_PORT / PORT in .env (see .env.example)
const VITE_PORT = Number(process.env.VITE_PORT || 3072);
const BACKEND_PORT = Number(process.env.BACKEND_PORT || 3073);
// In dev mode, backend runs on BACKEND_PORT (proxied by Vite). In production, serves API + static on PORT.
const PORT =
process.env.NODE_ENV === 'development'
? BACKEND_PORT
: Number(process.env.PORT || 3072);
// Middleware
app.use(express.json());
// Trust proxy (important when behind reverse proxy like nginx)
// This ensures helmet gets correct client IP and protocol
app.set('trust proxy', 1);
// Security headers middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"], // Vite bundles are from same origin
styleSrc: ["'self'", "'unsafe-inline'"], // Vite may inline styles, RSS feeds may have inline styles
imgSrc: ["'self'", "data:", "https:", "http:"], // Allow all external images (RSS thumbnails, SVGs, etc.)
connectSrc: ["'self'"], // API calls to same origin
fontSrc: ["'self'", "data:", "https:"], // Fonts may be data URLs or external
objectSrc: ["'none'"], // Block plugins
mediaSrc: ["'self'", "https:"], // Allow external media
frameSrc: ["'none'"], // Block iframes
baseUri: ["'self'"],
formAction: ["'self'"],
upgradeInsecureRequests: process.env.NODE_ENV === 'production' && process.env.HTTPS === 'true' ? [] : null,
},
},
// Other security headers
xFrameOptions: { action: 'deny' }, // Prevent clickjacking
xContentTypeOptions: true, // Prevent MIME sniffing
strictTransportSecurity: process.env.NODE_ENV === 'production' && process.env.HTTPS === 'true' ? {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true,
} : false, // Only in production with HTTPS
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));
// CORS headers for API endpoints
// Get allowed origins from environment variable
const getAllowedOrigins = () => {
if (process.env.NODE_ENV === 'development') {
return [
`http://127.0.0.1:${VITE_PORT}`,
`http://127.0.0.1:${BACKEND_PORT}`,
`http://localhost:${VITE_PORT}`,
`http://localhost:${BACKEND_PORT}`,
];
}
// Production: Use environment variable
if (process.env.ALLOWED_ORIGINS) {
return process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim()).filter(Boolean);
}
// Fallback: Use HOST if set
if (process.env.HOST) {
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
return [`${protocol}://${process.env.HOST}`];
}
// Last resort: Allow all (not recommended, but better than breaking)
console.warn('[CORS] No ALLOWED_ORIGINS or HOST set, allowing all origins (not recommended for production)');
return ['*'];
};
/**
* Dev: allow browser Origin when using LAN IP (e.g. http://10.0.0.53:3072) with Vite or API port.
* Simple same-origin GETs often omit Origin; POST + JSON (e.g. batch-complete) sends Origin and
* would otherwise 403 while /api/proxy/rss GET still works — confusing in dev.
*/
function isDevelopmentLanOriginAllowed(origin) {
if (process.env.NODE_ENV !== 'development') return false;
try {
const u = new URL(origin);
if (u.protocol !== 'http:' && u.protocol !== 'https:') return false;
const port = u.port || (u.protocol === 'https:' ? '443' : '80');
const devPorts = new Set([String(VITE_PORT), String(BACKEND_PORT)]);
if (!devPorts.has(port)) return false;
const { hostname } = u;
if (hostname === 'localhost' || hostname === '127.0.0.1') return false; // already in getAllowedOrigins()
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
if (!m) return false;
const oct = m.slice(1).map((x) => Number(x));
if (oct.some((n) => n > 255)) return false;
const [a, b] = oct;
if (a === 10) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
if (a === 192 && b === 168) return true;
return false;
} catch {
return false;
}
}
/** True if Origin matches configured web CORS allowlist (not cryptographic proof of a browser). */
function isBrowserOriginTrustedForProxy(origin) {
if (!origin || typeof origin !== 'string') return false;
const allowedOrigins = getAllowedOrigins();
if (allowedOrigins.includes('*')) return true;
if (allowedOrigins.includes(origin)) return true;
if (isDevelopmentLanOriginAllowed(origin)) return true;
return false;
}
/** Same-origin fetches often omit Origin; Referer still points at the SPA (spoofable like Origin). */
function refererMatchesAllowedOrigin(referer) {
if (!referer || typeof referer !== 'string') return false;
try {
const r = new URL(referer);
const base = `${r.protocol}//${r.host}`;
return isBrowserOriginTrustedForProxy(base);
} catch {
return false;
}
}
/**
* Optional shared secret(s) for RSS/HTML/YouTube proxy routes. Comma-separated in ACTUFEED_PROXY_CLIENT_KEYS.
* When non-empty: require header X-Actufeed-Client-Key to match (timing-safe), OR trusted browser Origin.
* Mobile / RN should send the key (no Origin). Web can rely on Origin without the key.
* Note: keys are extractable from app bundles; Origin can be spoofed by non-browsers — this is abuse friction, not proof of app identity.
*/
function parseProxyClientKeys() {
const raw = process.env.ACTUFEED_PROXY_CLIENT_KEYS;
if (!raw || !raw.trim()) return [];
return raw
.split(',')
.map((s) => s.trim())
.filter((k) => k.length > 0);
}
function timingSafeEqualStr(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') return false;
const ab = Buffer.from(a, 'utf8');
const bb = Buffer.from(b, 'utf8');
if (ab.length !== bb.length) return false;
return crypto.timingSafeEqual(ab, bb);
}
const PROXY_GATED_PATHS = new Set([
'/api/proxy/rss',
'/api/proxy/batch-complete',
'/api/proxy/html',
'/api/proxy/asset/check',
'/api/article/extract',
'/api/youtube/resolve',
'/api/youtube/channel-search',
]);
const CORS_ALLOW_HEADERS = 'Content-Type, X-Actufeed-Client-Key';
app.use('/api', (req, res, next) => {
const origin = req.headers.origin;
const allowedOrigins = getAllowedOrigins();
// Same-origin requests typically don't send Origin header
// If no origin, allow (same-origin request)
if (!origin) {
// Same-origin request - allow
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.header('Access-Control-Allow-Headers', CORS_ALLOW_HEADERS);
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
return next();
}
// Cross-origin request - check if allowed
if (
allowedOrigins.includes('*') ||
allowedOrigins.includes(origin) ||
isDevelopmentLanOriginAllowed(origin)
) {
res.header('Access-Control-Allow-Origin', origin);
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.header('Access-Control-Allow-Headers', CORS_ALLOW_HEADERS);
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
return next();
}
// Origin not allowed
console.warn(`[CORS] Blocked request from origin: ${origin}`);
return res.status(403).json({ error: 'Origin not allowed' });
});
app.use((req, res, next) => {
if (!PROXY_GATED_PATHS.has(req.path)) {
return next();
}
const keys = parseProxyClientKeys();
if (keys.length === 0) {
return next();
}
const sent = req.headers['x-actufeed-client-key'];
if (typeof sent === 'string' && keys.some((k) => timingSafeEqualStr(sent, k))) {
return next();
}
if (isBrowserOriginTrustedForProxy(req.headers.origin)) {
return next();
}
if (refererMatchesAllowedOrigin(req.headers.referer)) {
return next();
}
// Vite dev proxy → API sometimes reaches here without Origin/Referer; keys would block the settings UI.
if (
process.env.NODE_ENV === 'development' &&
(req.path === '/api/youtube/channel-search' || req.path === '/api/youtube/resolve')
) {
return next();
}
console.warn(`[Proxy gate] Blocked ${req.method} ${req.path} (no valid client key, untrusted origin)`);
return res.status(403).json({ error: 'Proxy access denied' });
});
// Rate limiting for RSS proxy endpoint
// Increased limit (500/15min) to handle parallel fetching of multiple RSS feeds
// Frontend batching helps prevent hitting this limit
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 500, // 500 requests per 15 minutes (increased from 100 to handle parallel fetching)
message: 'Too many requests from this IP, please try again later.',
standardHeaders: true, // Return rate limit info in `RateLimit-*` headers
legacyHeaders: false, // Disable `X-RateLimit-*` headers
skip: (req) =>
req.path === '/api/health' ||
// One tiny POST per refresh; must not consume the same budget as N /api/proxy/rss calls
// or a full reload hits 429 here and the handler never runs (no batch-complete log).
(req.method === 'POST' && req.path === '/api/proxy/batch-complete'),
});
/** UUID (RFC 4122) from the news fetch batch; used to correlate many /api/proxy/rss calls. */
const RSS_BATCH_ID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isValidRssBatchId(id) {
return typeof id === 'string' && id.length <= 64 && RSS_BATCH_ID_RE.test(id);
}
function getClientIp(req) {
const fwd = req.headers['x-forwarded-for'];
if (typeof fwd === 'string' && fwd.trim()) {
return fwd.split(',')[0].trim();
}
if (req.ip) {
return req.ip;
}
return req.socket?.remoteAddress || 'unknown';
}
/** Apache-style UTC timestamp for logs, e.g. [07/Apr/2026:16:00:48 +0000] */
function logTimestampUTC(d = new Date()) {
const date = d instanceof Date ? d : new Date(d);
const day = String(date.getUTCDate()).padStart(2, '0');
const mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][
date.getUTCMonth()
];
const y = date.getUTCFullYear();
const hh = String(date.getUTCHours()).padStart(2, '0');
const mm = String(date.getUTCMinutes()).padStart(2, '0');
const ss = String(date.getUTCSeconds()).padStart(2, '0');
return `[${day}/${mon}/${y}:${hh}:${mm}:${ss} +0000]`;
}
/** Response-body size as sent to the client (JSON), for transfer accounting. */
function jsonUtf8ByteLength(obj) {
return Buffer.byteLength(JSON.stringify(obj), 'utf8');
}
/**
* Human-readable byte total: thousands separators + KB / MB / GB (1024-based).
* Example: "5,322.41 MB" or "1,024 KB"
*/
function formatTransferredHumanReadable(bytes) {
if (!Number.isFinite(bytes) || bytes <= 0) {
return '0 B';
}
if (bytes < 1024) {
return `${bytes.toLocaleString('en-US')} B`;
}
const kb = bytes / 1024;
if (kb < 1024) {
return `${kb.toLocaleString('en-US', { maximumFractionDigits: 2 })} KB`;
}
const mb = kb / 1024;
if (mb < 1024) {
return `${mb.toLocaleString('en-US', { maximumFractionDigits: 2 })} MB`;
}
const gb = mb / 1024;
return `${gb.toLocaleString('en-US', { maximumFractionDigits: 2 })} GB`;
}
const rssBatchStats = new Map();
const RSS_BATCH_STALE_MS = 2 * 60 * 60 * 1000;
function recordRssBatchTransfer(batchId, clientIp, byteCount) {
if (!batchId || !byteCount || byteCount < 1) return;
let entry = rssBatchStats.get(batchId);
if (!entry) {
entry = { ip: clientIp, bytes: 0, requests: 0, createdAt: Date.now() };
rssBatchStats.set(batchId, entry);
}
entry.bytes += byteCount;
entry.requests += 1;
}
function pruneStaleRssBatchStats() {
const now = Date.now();
for (const [id, entry] of rssBatchStats) {
if (now - entry.createdAt > RSS_BATCH_STALE_MS) {
rssBatchStats.delete(id);
console.warn(
`[RSS Proxy] Dropped stale batch stats (no batch-complete) batch=${id} client=${entry.ip} had ${entry.requests} req, ${formatTransferredHumanReadable(entry.bytes)}`
);
}
}
}
setInterval(pruneStaleRssBatchStats, 15 * 60 * 1000).unref?.();
function parseRssBatchQueryParam(req) {
const raw = req.query.batch;
const s = Array.isArray(raw) ? raw[0] : raw;
return typeof s === 'string' && isValidRssBatchId(s) ? s : null;
}
/** True if buffer likely contains a full RSS/Atom/RDF document (stop streaming early). */
function bufferLooksLikeCompleteXmlFeed(buf) {
if (!buf?.length) return false;
let s;
try {
s = buf.toString('utf8');
} catch {
return false;
}
return (
/<\/feed\s*>/i.test(s) ||
/<\/rss\s*>/i.test(s) ||
/<\/rdf:RDF\s*>/i.test(s) ||
/<\/RDF\s*>/i.test(s)
);
}
/** Stop validation probe early on HTML error pages (avoid reading MB of markup). */
function bufferLooksLikeHtmlDocument(buf) {
if (!buf || buf.length < 12) return false;
const head = buf.toString('utf8', 0, Math.min(buf.length, 14000)).trimStart();
return head.startsWith('<!DOCTYPE') || head.startsWith('<html');
}
/**
* Read response body with optional byte cap and/or early stop (e.g. full XML feed).
* @returns {Promise<{ buffer: Buffer, contentLengthHdr: string | null, truncated: boolean }>}
*/
async function readHttpResponseBodyBounded(response, options = {}) {
const maxBytes = options.maxBytes ?? Number.POSITIVE_INFINITY;
const stopWhen = typeof options.stopWhen === 'function' ? options.stopWhen : null;
const contentLengthHdr = response.headers.get('content-length');
if (!response.body) {
const buf = Buffer.from(await response.arrayBuffer());
const lim = Math.min(buf.length, maxBytes);
const out = buf.slice(0, lim);
return {
buffer: out,
contentLengthHdr,
truncated: lim < buf.length,
};
}
const reader = response.body.getReader();
const chunks = [];
let total = 0;
try {
while (total < maxBytes) {
const { done, value } = await reader.read();
if (done) break;
if (!value?.length) continue;
let chunk = Buffer.from(value);
const room = maxBytes - total;
if (chunk.length > room) {
chunk = chunk.slice(0, room);
chunks.push(chunk);
total += chunk.length;
const combined = Buffer.concat(chunks);
if (stopWhen?.(combined)) {
return { buffer: combined, contentLengthHdr, truncated: false };
}
return { buffer: combined, contentLengthHdr, truncated: true };
}
chunks.push(chunk);
total += chunk.length;
if (stopWhen) {
const combined = Buffer.concat(chunks);
if (stopWhen(combined)) {
return { buffer: combined, contentLengthHdr, truncated: false };
}
}
}
} finally {
try {
await reader.cancel();
} catch {
/* ignore */
}
}
const buffer = Buffer.concat(chunks);
return {
buffer,
contentLengthHdr,
truncated: Number.isFinite(maxBytes) && total >= maxBytes,
};
}
function isYoutubeFeedsVideosXmlUrl(feedUrl) {
try {
const u = new URL(feedUrl);
const h = u.hostname.replace(/^www\./i, '').toLowerCase();
return h === 'youtube.com' && u.pathname.replace(/\/+$/, '') === '/feeds/videos.xml';
} catch {
return false;
}
}
/** `feeds/videos.xml?channel_id=UC…` only (after normalization away from playlist_id). */
function extractYoutubeChannelIdFromFeedsVideosUrl(feedUrlString) {
try {
if (!isYoutubeFeedsVideosXmlUrl(feedUrlString)) return null;
const u = new URL(feedUrlString);
const id = u.searchParams.get('channel_id');
if (id && /^UC[a-zA-Z0-9_-]{10,}$/i.test(id.trim())) return id.trim();
return null;
} catch {
return null;
}
}
/**
* YouTube’s feed origin often returns 404/500 for some client fingerprints while browsers (or another UA) get 200.
* Try several realistic clients in order; do not random-pick a single Chrome UA for these URLs.
*/
const YOUTUBE_ATOM_FEED_USER_AGENTS = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:128.0) Gecko/20100101 Firefox/128.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
];
const MAX_FORWARDED_CLIENT_UA_LENGTH = 512;
/** Strip CR/LF/NUL and cap length so the inbound UA cannot inject extra headers. */
function sanitizeForwardedUserAgent(raw) {
if (raw == null || typeof raw !== 'string') return '';
const s = raw.trim().replace(/[\r\n\x00]/g, '');
return s.length <= MAX_FORWARDED_CLIENT_UA_LENGTH ? s : s.slice(0, MAX_FORWARDED_CLIENT_UA_LENGTH);
}
/**
* Prefer the browser’s User-Agent (from the request to our API) for YouTube Atom fetches so behavior
* matches “open this feed URL in my browser”; fall back to built-ins if YouTube still rejects.
*/
function buildYoutubeAtomFeedUserAgentList(clientUa) {
const cleaned = sanitizeForwardedUserAgent(clientUa);
if (!cleaned) return [...YOUTUBE_ATOM_FEED_USER_AGENTS];
const rest = YOUTUBE_ATOM_FEED_USER_AGENTS.filter((ua) => ua !== cleaned);
return [cleaned, ...rest];
}
// Helper function to fetch with retries (generic, no feed-specific logic)
async function fetchWithRetry(feedUrl, retries = 2, fetchOptions = {}) {
const maxAttempts = retries + 1;
let lastError = null;
// Try the URL with retries
for (let attempt = 0; attempt <= retries; attempt++) {
const attemptNumber = attempt + 1;
try {
console.log(`[RSS Proxy] Attempt ${attemptNumber}/${maxAttempts} for ${feedUrl}`);
// Add small delay between retries to avoid rate limiting
if (attempt > 0) {
const delay = 1000 * attempt;
console.log(`[RSS Proxy] Waiting ${delay}ms before retry...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
const tryYoutube = isYoutubeFeedsVideosXmlUrl(feedUrl);
const genericPool = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0',
];
const uaList = tryYoutube
? buildYoutubeAtomFeedUserAgentList(fetchOptions.clientUserAgent)
: [genericPool[Math.floor(Math.random() * genericPool.length)]];
let response = null;
for (let uaIdx = 0; uaIdx < uaList.length; uaIdx++) {
const userAgent = uaList[uaIdx];
const headers = tryYoutube
? {
'User-Agent': userAgent,
Accept: 'application/rss+xml, application/atom+xml, application/xml, text/xml, */*',
'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
}
: {
'User-Agent': userAgent,
Accept: 'application/rss+xml, application/xml, text/xml, application/atom+xml, */*',
'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8,fr-CA;q=0.7',
'Accept-Encoding': 'gzip, deflate, br',
Referer: `${new URL(feedUrl).origin}/`,
'Cache-Control': 'no-cache',
DNT: '1',
Connection: 'keep-alive',
'Upgrade-Insecure-Requests': '1',
};
response = await fetch(feedUrl, {
signal: controller.signal,
headers,
redirect: 'follow',
});
if (response.ok) {
if (tryYoutube && uaIdx > 0) {
console.log(
`[RSS Proxy] YouTube feed OK after alternate User-Agent (${uaIdx + 1}/${uaList.length})`
);
} else if (tryYoutube && uaIdx === 0 && sanitizeForwardedUserAgent(fetchOptions.clientUserAgent)) {
console.log('[RSS Proxy] YouTube feed OK using forwarded client User-Agent');
}
break;
}
const st = response.status;
if (
tryYoutube &&
(st === 404 || st === 500 || st === 503) &&
uaIdx < uaList.length - 1
) {
console.log(
`[RSS Proxy] YouTube feed HTTP ${st} (UA ${uaIdx + 1}/${uaList.length}), trying next fingerprint…`
);
} else {
break;
}
}
clearTimeout(timeoutId);
if (response.ok) {
const contentType = response.headers.get('content-type') || '';
const readBodyOpts = fetchOptions.minimalCompleteXml
? {
maxBytes: fetchOptions.maxFeedReadBytes ?? 2 * 1024 * 1024,
stopWhen: (buf) =>
bufferLooksLikeCompleteXmlFeed(buf) || bufferLooksLikeHtmlDocument(buf),
}
: { maxBytes: Number.POSITIVE_INFINITY };
const { buffer: rawBuffer, contentLengthHdr, truncated } =
await readHttpResponseBodyBounded(response, readBodyOpts);
console.log(
`[Feed Fetch] RSS/Atom body ${rawBuffer.length} bytes` +
(truncated ? ' (hit byte cap)' : '') +
(fetchOptions.minimalCompleteXml ? ' [validation probe]' : '') +
(contentLengthHdr ? ` (Content-Length hdr: ${contentLengthHdr})` : ' (no Content-Length / chunked)') +
` ← ${feedUrl}`
);
// First, try to detect encoding from Content-Type header
let detectedEncoding = 'utf8';
const charsetMatch = contentType.match(/charset=([^;]+)/i);
if (charsetMatch) {
detectedEncoding = charsetMatch[1].toLowerCase().trim();
// Normalize common encoding names
if (detectedEncoding === 'iso-8859-1' || detectedEncoding === 'latin1') {
detectedEncoding = 'latin1';
} else if (detectedEncoding === 'windows-1252' || detectedEncoding === 'cp1252') {
detectedEncoding = 'win1252';
} else if (detectedEncoding === 'utf-8' || detectedEncoding === 'utf8') {
detectedEncoding = 'utf8';
}
}
// Read the first part to check XML declaration for encoding
// Try UTF-8 first to read the XML declaration
const firstBytes = rawBuffer.slice(0, Math.min(500, rawBuffer.length));
let firstText = '';
try {
firstText = firstBytes.toString('utf8');
} catch (e) {
// If UTF-8 fails, try latin1
firstText = firstBytes.toString('latin1');
}
const xmlEncodingMatch = firstText.match(/<\?xml[^>]*encoding=["']([^"']+)["']/i);
if (xmlEncodingMatch) {
const xmlEncoding = xmlEncodingMatch[1].toLowerCase().trim();
// Use encoding from XML declaration if present
if (xmlEncoding === 'iso-8859-1' || xmlEncoding === 'latin1') {
detectedEncoding = 'latin1';
} else if (xmlEncoding === 'windows-1252' || xmlEncoding === 'cp1252') {
detectedEncoding = 'win1252';
} else if (xmlEncoding === 'utf-8' || xmlEncoding === 'utf8') {
detectedEncoding = 'utf8';
}
} else {
// No encoding in XML declaration - check if content looks like UTF-8
// If we can successfully decode as UTF-8 and it contains valid UTF-8 characters,
// assume it's UTF-8 (many feeds don't declare encoding but are UTF-8)
try {
const testText = rawBuffer.toString('utf8');
// Check if it contains valid UTF-8 sequences (Portuguese chars, etc.)
// If the text decodes cleanly as UTF-8 and contains non-ASCII, it's likely UTF-8
if (testText.includes('<?xml') && /[\u00C0-\u00FF]/.test(testText)) {
// Contains Portuguese/Latin characters and decodes as UTF-8 - likely UTF-8
detectedEncoding = 'utf8';
}
} catch (e) {
// UTF-8 decode failed, keep detected encoding
}
}
// Convert buffer to string using detected encoding, then to UTF-8
// Use iconv-lite for proper encoding conversion
let text;
// First, always try UTF-8 to see if it decodes cleanly
// Many feeds are UTF-8 but don't declare it, or incorrectly declare ISO-8859-1
const utf8Test = rawBuffer.toString('utf8');
// Check if UTF-8 decodes cleanly and contains Portuguese/Latin characters
const looksLikeUtf8 = utf8Test.includes('<?xml') &&
/[^\x00-\x7F]/.test(utf8Test) && // Contains non-ASCII characters
/[\u00C0-\u00FF\u0100-\u017F\u0180-\u024F]/.test(utf8Test); // Contains Portuguese/Latin chars
if (detectedEncoding === 'latin1' || detectedEncoding === 'iso-8859-1') {
// Only use Latin1 if explicitly declared
// But first, check if it might actually be UTF-8 (common misdeclaration)
if (looksLikeUtf8) {
// Looks like valid UTF-8 with Portuguese characters - use UTF-8 instead
text = utf8Test;
console.log(`[RSS Proxy] Feed declared ${detectedEncoding} but appears to be UTF-8, using UTF-8`);
} else {
// Convert from ISO-8859-1/Latin1 to UTF-8 using iconv-lite
text = iconv.decode(rawBuffer, 'iso-8859-1');
}
} else if (detectedEncoding === 'win1252' || detectedEncoding === 'cp1252' || detectedEncoding === 'windows-1252') {
// Windows-1252 - try UTF-8 first, fallback to Windows-1252
if (looksLikeUtf8) {
text = utf8Test;
} else {
// Use iconv-lite for proper Windows-1252 conversion
text = iconv.decode(rawBuffer, 'windows-1252');
}
} else {
// Default to UTF-8 (most common)
text = utf8Test;
}
// Check if response is HTML (error page) instead of XML
const trimmedText = text.trim();
if (trimmedText.startsWith('<!DOCTYPE') || trimmedText.startsWith('<html')) {
// Got HTML instead of XML - this is likely a 404 page or error
const error = new Error('Response is HTML (likely error page), not RSS/XML');
console.log(`[RSS Proxy] Attempt ${attemptNumber} failed: ${error.message}`);
lastError = error;
if (attempt < retries) continue;
throw error;
}
// Validate it's XML/RSS
if (trimmedText.includes('<rss') ||
trimmedText.includes('<feed') ||
trimmedText.includes('<?xml') ||
trimmedText.includes('<RDF')) {
// Normalize XML declaration to ensure UTF-8 encoding
// This is critical for proper character encoding of accented characters
let normalizedText = text;
if (trimmedText.startsWith('<?xml')) {
// Replace or add encoding="UTF-8" in XML declaration
normalizedText = text.replace(
/<\?xml\s+version=["']([^"']+)["'](\s+encoding=["'][^"']+["'])?/i,
'<?xml version="$1" encoding="UTF-8"'
);
// If no XML declaration exists, add one (shouldn't happen, but safety check)
if (!normalizedText.includes('<?xml')) {
normalizedText = '<?xml version="1.0" encoding="UTF-8"?>\n' + normalizedText;
}
} else if (!trimmedText.includes('<?xml')) {
// No XML declaration, add one with UTF-8
normalizedText = '<?xml version="1.0" encoding="UTF-8"?>\n' + text;
}
console.log(
`[RSS Proxy] ✓ Success on attempt ${attemptNumber}/${maxAttempts} for ${feedUrl} (encoding: ${detectedEncoding}, ${rawBuffer.length} bytes)`
);
return { text: normalizedText, contentType, url: feedUrl };
} else {
const error = new Error('Response is not valid RSS/XML feed');
console.log(`[RSS Proxy] Attempt ${attemptNumber} failed: ${error.message}`);
lastError = error;
if (attempt < retries) continue;
throw error;
}
} else {
// Non-200 response
const status = response.status;
const error = new Error(`HTTP ${status} ${response.statusText}`);
console.log(`[RSS Proxy] Attempt ${attemptNumber} failed: ${error.message}`);
lastError = error;
if (status === 403) {
console.log(`[RSS Proxy] Permanent failure (403), not retrying`);
throw error;
}
// Non-YouTube 404: permanent. YouTube feeds: 404/500/503 often flip between edges — retry.
if (status === 404 && !tryYoutube) {
console.log(`[RSS Proxy] Permanent failure (404), not retrying`);
throw error;
}
if (
tryYoutube &&
(status === 404 || status === 500 || status === 503) &&
attempt < retries
) {
console.log(`[RSS Proxy] YouTube HTTP ${status}, backing off and retrying attempt…`);
continue;
}
if (attempt < retries) {
continue;
}
throw error;
}
} catch (error) {
lastError = error;
if (error.name === 'AbortError') {
console.log(`[RSS Proxy] Attempt ${attemptNumber} failed: Request timeout`);
// Timeout - retry if attempts remain
if (attempt < retries) {
continue;
}
const timeoutError = new Error('Request timeout after all retries');
console.log(`[RSS Proxy] ✗ All ${maxAttempts} attempts exhausted for ${feedUrl}: ${timeoutError.message}`);
throw timeoutError;
}
if (error.message.includes('HTTP 403')) {
console.log(`[RSS Proxy] ✗ Permanent failure on attempt ${attemptNumber}, not retrying: ${error.message}`);
throw error;
}
if (error.message.includes('HTTP 404') && !isYoutubeFeedsVideosXmlUrl(feedUrl)) {
console.log(`[RSS Proxy] ✗ Permanent failure on attempt ${attemptNumber}, not retrying: ${error.message}`);
throw error;
}
// Network errors or other issues - retry if attempts remain
if (attempt < retries) {
console.log(`[RSS Proxy] Attempt ${attemptNumber} failed: ${error.message}, will retry...`);
continue;
}
// Last attempt failed
console.log(`[RSS Proxy] ✗ All ${maxAttempts} attempts exhausted for ${feedUrl}: ${error.message}`);
throw error;
}
}
// Should never reach here, but just in case
console.log(`[RSS Proxy] ✗ All ${maxAttempts} attempts exhausted for ${feedUrl}: ${lastError?.message || 'Unknown error'}`);
throw lastError || new Error('Failed after all retries');
}
/** Unwrap undici/node `fetch` errors — `error.message` is often only "fetch failed". */
function describeFetchFailure(error) {
if (!error || typeof error !== 'object') return String(error);
const parts = [error.message || String(error)];
let c = error.cause;
for (let i = 0; i < 6 && c; i++) {
if (c instanceof Error) {
parts.push(c.message);
c = c.cause;
} else {
parts.push(String(c));
break;
}
}
return parts.filter(Boolean).join(' → ');
}
async function fetchHtmlSnippetForLogo(pageUrl) {
return fetchHtmlSnippetBounded(pageUrl, MAX_HTML_LOGO_SNIPPET_BYTES);
}
/** Scan stride while streaming; canonical / og:url for @handle often appears around ~600KB. */
const YOUTUBE_HTML_CHANNEL_ID_CHECK_STRIDE = 40 * 1024;
/** Fetch YouTube browse HTML but stop reading once a channel id can be parsed from the buffer. */
async function fetchYoutubeBrowseHtmlUntilChannelId(pageUrl) {
const maxBytes = MAX_HTML_YOUTUBE_RESOLVE_BYTES;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
const userAgents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
];
const userAgent = userAgents[Math.floor(Math.random() * userAgents.length)];
const response = await fetch(pageUrl, {
signal: controller.signal,
headers: {
'User-Agent': userAgent,
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8,fr-CA;q=0.7',
'Accept-Encoding': 'gzip, deflate, br',
Referer: new URL(pageUrl).origin + '/',
'Cache-Control': 'no-cache',
DNT: '1',
Connection: 'keep-alive',
'Upgrade-Insecure-Requests': '1',
},
redirect: 'follow',
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}`);
}
if (!response.body) {
const buf = Buffer.from(await response.arrayBuffer()).slice(0, maxBytes);
console.log(
`[Feed Fetch] HTML body ${buf.length} bytes (read cap ${maxBytes}, no stream) ← ${pageUrl}`
);
return buf.toString('utf8');
}
const reader = response.body.getReader();
const chunks = [];
let total = 0;
let lastCheckedAt = 0;
try {
while (total < maxBytes) {
const { done, value } = await reader.read();
if (done) break;
if (value?.length) {
chunks.push(Buffer.from(value));
total += value.length;
}
if (total - lastCheckedAt >= YOUTUBE_HTML_CHANNEL_ID_CHECK_STRIDE || done) {
const combined = Buffer.concat(chunks).slice(0, maxBytes);
const html = combined.toString('utf8');
if (extractYoutubeChannelIdFromHtml(html)) {
console.log(
`[Feed Fetch] HTML body ${combined.length} bytes (early stop after channel id, cap ${maxBytes}) ← ${pageUrl}`
);
return html;
}
lastCheckedAt = total;
}
}
} finally {
try {
await reader.cancel();
} catch {
/* ignore */
}
}
const buf = Buffer.concat(chunks).slice(0, maxBytes);
console.log(`[Feed Fetch] HTML body ${buf.length} bytes (read cap ${maxBytes}) ← ${pageUrl}`);
return buf.toString('utf8');
}
// SSRF Protection: Validate URL is safe to fetch
const isPrivateIP = (hostname) => {
// Check for localhost variants
if (hostname === 'localhost' ||
hostname === '127.0.0.1' ||
hostname === '0.0.0.0' ||
hostname === '::1' ||
hostname.startsWith('127.') ||
hostname.startsWith('::ffff:127.')) {
return true;
}
// Check for private IP ranges
const privateIPPatterns = [
/^10\./, // 10.0.0.0/8
/^172\.(1[6-9]|2[0-9]|3[0-1])\./, // 172.16.0.0/12
/^192\.168\./, // 192.168.0.0/16
/^169\.254\./, // 169.254.0.0/16 (link-local)
/^fc00:/i, // IPv6 private
/^fe80:/i, // IPv6 link-local
];
return privateIPPatterns.some(pattern => pattern.test(hostname));
};
// --- Resolved-address SSRF guard (production): hostname literals can still resolve to private/metadata IPs ---
function ipv4ToUint32(ip) {
const m = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (!m) return null;
const parts = [m[1], m[2], m[3], m[4]].map((x) => parseInt(x, 10));
if (parts.some((n) => n > 255)) return null;
return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
}
function isBlockedResolvedIPv4(ip) {
const n = ipv4ToUint32(ip);
if (n === null) return true;
const b0 = n >>> 24;
const b1 = (n >>> 16) & 0xff;
if (b0 === 0) return true; // 0.0.0.0/8
if (b0 === 10) return true; // 10.0.0.0/8
if (b0 === 127) return true; // 127.0.0.0/8
if (b0 === 169 && b1 === 254) return true; // 169.254.0.0/16 (link-local, cloud metadata)
if (b0 === 172 && b1 >= 16 && b1 <= 31) return true; // 172.16.0.0/12
if (b0 === 192 && b1 === 168) return true; // 192.168.0.0/16
if (b0 === 100 && b1 >= 64 && b1 <= 127) return true; // 100.64.0.0/10 (CGNAT)
if (b0 >= 224) return true; // 224.0.0.0/4 multicast + reserved
return false;
}
/** @returns {{ mappedV4?: string, parts?: number[] } | null} */
function expandIPv6Parts(address) {
const addr = address.split('%')[0].toLowerCase();
const mapped = addr.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
if (mapped) return { mappedV4: mapped[1] };
if (addr.includes('::')) {
const [head, tail] = addr.split('::', 2);
const left = head ? head.split(':').filter((x) => x.length) : [];
const right = tail ? tail.split(':').filter((x) => x.length) : [];
const missing = 8 - left.length - right.length;
if (missing < 0) return null;
const parts = [...left, ...Array(missing).fill('0'), ...right];