-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2014 lines (1811 loc) · 93.4 KB
/
Copy pathserver.js
File metadata and controls
2014 lines (1811 loc) · 93.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
const express = require('express');
const compression = require('compression');
const cors = require('cors');
const path = require('path');
const fsPromises = require('fs').promises;
const os = require('os');
const { execFile } = require('child_process');
const { promisify } = require('util');
const crypto = require('crypto');
const Groq = require('groq-sdk');
const { Resend } = require('resend');
const { Supadata } = require('@supadata/js');
const { createClient } = require('@supabase/supabase-js');
const multer = require('multer');
// Load local .env values for `npm start`/local development.
// In production, platform environment variables still take precedence.
require('dotenv').config();
const resend = process.env.RESEND_API_KEY ? new Resend(process.env.RESEND_API_KEY) : null;
const hashEmail = (email) => crypto.createHash('sha256').update(email.toLowerCase().trim()).digest('hex');
const ANON_CREDITS_MAX = Math.max(0, Number.parseInt(process.env.ANON_CREDITS_MAX || '2', 10) || 2);
const ANON_CREDITS_PERIOD_MS = 7 * 24 * 60 * 60 * 1000;
const CREDIT_AUTH_TIMEOUT_MS = Math.max(500, Number.parseInt(process.env.CREDIT_AUTH_TIMEOUT_MS || '3500', 10) || 3500);
const CREDIT_DB_TIMEOUT_MS = Math.max(500, Number.parseInt(process.env.CREDIT_DB_TIMEOUT_MS || '3500', 10) || 3500);
const AI_REQUIRE_AUTH = process.env.AI_REQUIRE_AUTH === '1';
const AI_ANON_RPM = Math.max(1, Number.parseInt(process.env.AI_ANON_RPM || '6', 10) || 6);
const AI_AUTH_RPM = Math.max(1, Number.parseInt(process.env.AI_AUTH_RPM || '20', 10) || 20);
const ANON_AI_MAX_PER_DAY = Math.max(0, Number.parseInt(process.env.ANON_AI_MAX_PER_DAY || '24', 10) || 24);
const ANON_AI_PERIOD_MS = 24 * 60 * 60 * 1000;
const _anonCreditsMap = new Map();
const _creditFallbackCounts = new Map();
const _anonAiQuotaMap = new Map();
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getClientKey = (req) => String(req.ip || req.socket?.remoteAddress || 'unknown');
const redactClientKey = (value) => crypto.createHash('sha1').update(String(value)).digest('hex').slice(0, 10);
function normalizeCreditFallbackReason(reason) {
const text = String(reason || 'unknown').toLowerCase();
if (text.includes('fetch failed')) return 'supabase_network_fetch_failed';
if (text.includes('network')) return 'supabase_network_error';
if (text.includes('timeout')) return 'supabase_timeout';
if (text.includes('jwt')) return 'auth_jwt_error';
if (text.includes('permission') || text.includes('denied') || text.includes('forbidden')) return 'db_permission_error';
if (text.includes('concurrent')) return 'db_concurrency_conflict';
return text.slice(0, 120);
}
function decodeJwtPayload(token) {
try {
const parts = String(token || '').split('.');
if (parts.length !== 3) return null;
const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
const json = Buffer.from(padded, 'base64').toString('utf8');
return JSON.parse(json);
} catch {
return null;
}
}
function sendSseEventAndClose(res, event, body) {
res.write(`event: ${event}\ndata: ${JSON.stringify(body)}\n\n`);
res.end();
}
function extractBearerToken(req) {
const authHeader = req.headers.authorization || '';
return authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
}
function denyCreditRequest(req, res, { status, body, sseEvent = 'transcript_error', user = null }) {
if (res.headersSent) {
sendSseEventAndClose(res, sseEvent, body);
} else {
res.status(status).json(body);
}
return { ok: false, user, creditInfo: null };
}
function consumeAnonCredit(req, res) {
if (ANON_CREDITS_MAX <= 0) {
return denyCreditRequest(req, res, {
status: 402,
body: { error: 'Guest credits are currently unavailable. Please sign in.' },
sseEvent: 'out_of_credits',
});
}
const key = getClientKey(req);
const now = Date.now();
let e = _anonCreditsMap.get(key);
if (!e || now > e.resetAt) e = { used: 0, resetAt: now + ANON_CREDITS_PERIOD_MS };
if (e.used >= ANON_CREDITS_MAX) {
return denyCreditRequest(req, res, {
status: 402,
body: {
error: 'Out of credits',
used: e.used,
tier_max: ANON_CREDITS_MAX,
reset_at: new Date(e.resetAt).toISOString(),
},
sseEvent: 'out_of_credits',
});
}
e.used += 1;
_anonCreditsMap.set(key, e);
return {
ok: true,
user: null,
creditInfo: {
used: e.used,
tier_max: ANON_CREDITS_MAX,
reset_at: new Date(e.resetAt).toISOString(),
},
};
}
function fallbackToAnonOnCreditError(req, res, reason) {
const reasonKey = normalizeCreditFallbackReason(reason);
const count = (_creditFallbackCounts.get(reasonKey) || 0) + 1;
_creditFallbackCounts.set(reasonKey, count);
if (count <= 3 || count % 25 === 0) {
console.warn(
`[credits] fallback mode=anon reason=${reasonKey} count=${count} method=${req.method} path=${req.path} client=${redactClientKey(getClientKey(req))} auth=${Boolean(req.headers.authorization)}`
);
}
return consumeAnonCredit(req, res);
}
function consumeAnonAiQuota(req, res) {
if (ANON_AI_MAX_PER_DAY <= 0) {
res.status(401).json({ error: 'Sign in required for AI features.' });
return false;
}
const key = getClientKey(req);
const now = Date.now();
let entry = _anonAiQuotaMap.get(key);
if (!entry || now > entry.resetAt) entry = { used: 0, resetAt: now + ANON_AI_PERIOD_MS };
if (entry.used >= ANON_AI_MAX_PER_DAY) {
res.setHeader('Retry-After', Math.max(1, Math.ceil((entry.resetAt - now) / 1000)));
res.status(429).json({
error: 'Anonymous AI limit reached for today. Please sign in or try again later.',
used: entry.used,
max: ANON_AI_MAX_PER_DAY,
reset_at: new Date(entry.resetAt).toISOString(),
});
return false;
}
entry.used += 1;
_anonAiQuotaMap.set(key, entry);
return true;
}
// ── Multer config for local file uploads ──────────────────────────────────────
const uploadStorage = multer.diskStorage({
destination: (_req, _file, cb) => cb(null, os.tmpdir()),
filename: (_req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase() || '.mp3';
const name = `upload_${Date.now()}_${crypto.randomBytes(6).toString('hex')}${ext}`;
cb(null, name);
},
});
const ALLOWED_AUDIO_MIME = new Set([
'audio/mpeg', 'audio/mp3', 'audio/mp4', 'audio/x-m4a', 'audio/m4a',
'audio/wav', 'audio/x-wav', 'audio/webm', 'video/webm',
'audio/ogg', 'audio/opus', 'audio/flac', 'video/mp4',
'video/quicktime', 'video/x-msvideo', 'video/x-matroska',
'video/x-ms-wmv', 'video/mpeg', 'video/3gpp',
]);
const uploadMiddleware = multer({
storage: uploadStorage,
limits: { fileSize: 500 * 1024 * 1024 }, // 500 MB — ffmpeg compresses before Whisper
fileFilter: (_req, file, cb) => {
if (ALLOWED_AUDIO_MIME.has(file.mimetype)) return cb(null, true);
const ext = path.extname(file.originalname).toLowerCase().slice(1);
const ALLOWED_EXT = ['mp3', 'mp4', 'm4a', 'wav', 'webm', 'ogg', 'opus', 'flac', 'mpeg', 'mpga', 'mov', 'avi', 'mkv', 'wmv', '3gp'];
if (ALLOWED_EXT.includes(ext)) return cb(null, true);
cb(new Error('Unsupported file type. Use mp4, mov, mp3, m4a, wav, or similar.'));
},
}).single('file');
// ── Compress any audio/video to a tiny speech-quality mp3 for Whisper ────────
// 16 kHz mono 16 kbps ≈ 7 MB/hour — comfortably under Groq's 25 MB limit
async function compressForWhisper(inputFile) {
const outFile = inputFile.replace(/(\.[^.]+)?$/, '_whisper.mp3');
await withTimeout(
execFileAsync('ffmpeg', [
'-i', inputFile,
'-vn', // strip video
'-ar', '16000', // 16 kHz (Whisper's native rate)
'-ac', '1', // mono
'-b:a', '16k', // 16 kbps — tiny, excellent for speech
'-y', // overwrite if exists
outFile,
]),
300000 // 5-minute cap for very large files
);
return outFile;
}
// ── Supabase admin client (server-side only, uses service role key) ───────────
let supabaseAdmin = null;
if (process.env.SUPABASE_URL && process.env.SUPABASE_SERVICE_ROLE_KEY) {
const supabaseKeyPayload = decodeJwtPayload(process.env.SUPABASE_SERVICE_ROLE_KEY);
if (supabaseKeyPayload?.role && supabaseKeyPayload.role !== 'service_role') {
console.error(
`[config] SUPABASE_SERVICE_ROLE_KEY appears to have role="${supabaseKeyPayload.role}" (expected "service_role"). Credit checks may fail.`
);
}
supabaseAdmin = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_SERVICE_ROLE_KEY,
{ auth: { autoRefreshToken: false, persistSession: false } }
);
}
// ── requireAuth middleware ─────────────────────────────────────────────────────
// Validates the Bearer JWT from the client. Attaches req.user if valid.
// Returns 401 if no valid token. Not applied to any routes yet (future use).
async function requireAuth(req, res, next) {
console.log(`[requireAuth] ${req.method} ${req.path}`);
if (!supabaseAdmin) {
console.error('[requireAuth] supabaseAdmin is null — SUPABASE_SERVICE_ROLE_KEY missing?');
return res.status(503).json({ error: 'Auth not configured' });
}
const authHeader = req.headers.authorization || '';
const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null;
if (!token) {
console.error('[requireAuth] No Bearer token in request');
return res.status(401).json({ error: 'Unauthorized' });
}
const { data: { user }, error } = await supabaseAdmin.auth.getUser(token);
if (error || !user) {
console.error('[requireAuth] Token invalid:', error?.message);
return res.status(401).json({ error: 'Invalid or expired token' });
}
req.user = user;
next();
}
// ── Server-side credit system ─────────────────────────────────────────────────
// Reads the JWT token from either the Authorization header or the ?_t= query
// param (needed for EventSource / SSE which cannot send custom headers).
// For authenticated users: checks and atomically deducts 1 credit from the
// user_credits table (see supabase/user_credits.sql).
// For anonymous / unauthenticated users: enforces server-side free credits per
// client IP (default 2 per 7 days, configurable via ANON_CREDITS_MAX).
// For token-authenticated requests: preserve legacy fail-open behavior on
// Supabase/auth/DB errors so signed-in users are not downgraded to guest quota.
//
// Returns: { ok, user, creditInfo }
// ok — true if the request may proceed
// user — Supabase user object (null for anon)
// creditInfo — { used, tier_max, reset_at } after deduction
// response already sent if ok === false (402/503)
async function checkAndDeductCredit(req, res) {
try {
// Read token from Authorization header OR ?_t= query param (for SSE)
const authHeader = req.headers.authorization || '';
const tokenFromQuery = typeof req.query?._t === 'string' ? req.query._t : null;
const token = authHeader.startsWith('Bearer ')
? authHeader.slice(7)
: tokenFromQuery;
// Anonymous request — enforce guest credits server-side
if (!token) return consumeAnonCredit(req, res);
// Legacy behavior: if auth infra is unavailable, do not downgrade a
// tokened request to anonymous quota.
if (!supabaseAdmin) return { ok: true, user: null, creditInfo: null };
// Validate JWT
let user = null;
let authErr = null;
try {
const authResult = await withTimeout(
supabaseAdmin.auth.getUser(token),
CREDIT_AUTH_TIMEOUT_MS
);
user = authResult?.data?.user || null;
authErr = authResult?.error || null;
} catch (err) {
console.warn('[credits] auth lookup failed (fail-open):', err?.message || err);
return { ok: true, user: null, creditInfo: null };
}
if (authErr || !user) {
console.warn('[credits] token invalid (fail-open):', authErr?.message || 'no user');
return { ok: true, user: null, creditInfo: null };
}
const referralBonus = user.user_metadata?.referral_bonus || 0;
const tierMax = 20 + referralBonus;
const now = new Date();
const nowIso = now.toISOString();
const resetAt = new Date(now.getTime() + ANON_CREDITS_PERIOD_MS).toISOString();
// Ensure a credits row exists for this user (insert only if missing)
await withTimeout(
supabaseAdmin
.from('user_credits')
.insert({ user_id: user.id, used: 0, reset_at: resetAt, tier_max: tierMax })
.select()
.maybeSingle(), // ignore conflict (row already exists)
CREDIT_DB_TIMEOUT_MS
).catch((err) => {
console.warn('[credits] ensure-row insert failed (continuing):', err?.message || err);
});
// Retry loop handles concurrent requests racing on the same user.
for (let attempt = 0; attempt < 3; attempt++) {
const { data: row, error: rowErr } = await withTimeout(
supabaseAdmin
.from('user_credits')
.select('used, reset_at, tier_max')
.eq('user_id', user.id)
.single(),
CREDIT_DB_TIMEOUT_MS
);
if (rowErr || !row) {
console.error('[credits] read error (fail-open):', rowErr?.message);
return { ok: true, user, creditInfo: null };
}
let currentUsed = row.used;
let currentResetAt = row.reset_at;
const effectiveTierMax = Math.max(row.tier_max || 0, tierMax);
if (new Date(row.reset_at) < now) {
// Best-effort reset (guarded by reset_at < now so only stale windows are reset).
await withTimeout(
supabaseAdmin
.from('user_credits')
.update({ used: 0, reset_at: resetAt, tier_max: effectiveTierMax, updated_at: nowIso })
.eq('user_id', user.id)
.lt('reset_at', nowIso),
CREDIT_DB_TIMEOUT_MS
).catch(() => {});
currentUsed = 0;
currentResetAt = resetAt;
}
if (currentUsed >= effectiveTierMax) {
return denyCreditRequest(req, res, {
status: 402,
body: { error: 'Out of credits', used: currentUsed, tier_max: effectiveTierMax, reset_at: currentResetAt },
sseEvent: 'out_of_credits',
user,
});
}
const { data: updated, error: updateErr } = await withTimeout(
supabaseAdmin
.from('user_credits')
.update({ used: currentUsed + 1, tier_max: effectiveTierMax, updated_at: nowIso })
.eq('user_id', user.id)
.eq('used', currentUsed)
.select('used, tier_max, reset_at')
.maybeSingle(),
CREDIT_DB_TIMEOUT_MS
);
if (updateErr) {
console.error(`[credits] deduct error (attempt ${attempt + 1}/3):`, updateErr.message);
if (attempt < 2) {
await delay(20 + attempt * 20);
continue;
}
return { ok: true, user, creditInfo: null };
}
// No row updated means a concurrent request won the race; retry with fresh row.
if (!updated) {
if (attempt < 2) {
await delay(20 + attempt * 20);
continue;
}
return { ok: true, user, creditInfo: null };
}
const creditInfo = {
used: updated.used,
tier_max: updated.tier_max || effectiveTierMax,
reset_at: updated.reset_at || currentResetAt,
};
console.log(`[credits] deducted 1 credit for ${user.id}: ${creditInfo.used}/${creditInfo.tier_max}`);
return { ok: true, user, creditInfo };
}
return { ok: true, user, creditInfo: null };
} catch (err) {
console.error('[credits] unexpected error (fail-open):', err?.message || err);
return { ok: true, user: null, creditInfo: null };
}
}
// Best-effort rollback when extraction fails after a credit was deducted.
// Uses optimistic matching on the expected `used` value to avoid over-refunding.
async function refundDeductedCredit(user, creditInfo, reason = 'unknown') {
try {
if (!supabaseAdmin || !user?.id) return false;
const deductedUsed = Number(creditInfo?.used);
if (!Number.isFinite(deductedUsed) || deductedUsed <= 0) return false;
const refundTo = deductedUsed - 1;
const { data: refunded, error } = await supabaseAdmin
.from('user_credits')
.update({ used: refundTo, updated_at: new Date().toISOString() })
.eq('user_id', user.id)
.eq('used', deductedUsed)
.select('used')
.maybeSingle();
if (error) {
console.warn(`[credits] refund failed for ${user.id}:`, error.message);
return false;
}
if (!refunded) {
console.warn(`[credits] refund skipped for ${user.id} (concurrent credit change). reason=${reason}`);
return false;
}
console.log(`[credits] refunded 1 credit for ${user.id}: ${deductedUsed} -> ${refundTo}. reason=${reason}`);
return true;
} catch (err) {
console.warn(`[credits] refund unexpected error for ${user?.id || 'unknown'}:`, err?.message || err);
return false;
}
}
async function aiComplete(prompt, maxTokens = 1024) {
// Try Groq first
if (process.env.GROQ_API_KEY) {
try {
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const completion = await groq.chat.completions.create({
model: 'llama-3.1-8b-instant',
messages: [{ role: 'user', content: prompt }],
max_tokens: maxTokens,
});
return completion.choices[0].message.content;
} catch (err) {
const msg = err.message || '';
const status = err.status || err.statusCode || 0;
// Only hard-fail on auth errors — fall through to OpenRouter for everything else
if (status === 401 || msg.includes('401') || msg.includes('invalid_api_key') || msg.includes('unauthorized')) throw err;
// Fall through to OpenRouter for rate limits, 5xx, timeouts, model errors, etc.
}
}
// Fallback: OpenRouter
if (process.env.OPENROUTER_API_KEY) {
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'meta-llama/llama-3.1-8b-instruct:free',
messages: [{ role: 'user', content: prompt }],
max_tokens: maxTokens,
}),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
throw new Error(data.error?.message || `OpenRouter error: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
throw new Error('No AI provider configured (GROQ_API_KEY or OPENROUTER_API_KEY required)');
}
// Multi-turn chat — accepts a full messages array (system / user / assistant)
// Streaming variant — calls onChunk(token) for each text delta, returns when done
async function aiChatStream(messages, onChunk, maxTokens = 1024) {
if (process.env.GROQ_API_KEY) {
try {
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const stream = await groq.chat.completions.create({
model: 'llama-3.1-8b-instant',
messages,
max_tokens: maxTokens,
stream: true,
});
for await (const chunk of stream) {
const token = chunk.choices[0]?.delta?.content;
if (token) onChunk(token);
}
return;
} catch (err) {
const msg = err.message || '';
const status = err.status || err.statusCode || 0;
if (status === 401 || msg.includes('401') || msg.includes('invalid_api_key') || msg.includes('unauthorized')) throw err;
// Fall through to OpenRouter
}
}
if (process.env.OPENROUTER_API_KEY) {
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'meta-llama/llama-3.1-8b-instruct:free',
messages,
max_tokens: maxTokens,
stream: true,
}),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
throw new Error(data.error?.message || `OpenRouter error: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buf = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const lines = buf.split('\n');
buf = lines.pop(); // keep incomplete line
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed.startsWith('data:')) continue;
const jsonStr = trimmed.slice(5).trim();
if (jsonStr === '[DONE]') return;
try {
const parsed = JSON.parse(jsonStr);
const token = parsed.choices?.[0]?.delta?.content;
if (token) onChunk(token);
} catch { /* skip malformed lines */ }
}
}
return;
}
throw new Error('No AI provider configured (GROQ_API_KEY or OPENROUTER_API_KEY required)');
}
const LANG_NAMES = { en:'English', es:'Spanish', fr:'French', de:'German', it:'Italian', pt:'Portuguese', ru:'Russian', 'zh-Hans':'Chinese (Simplified)', 'zh-Hant':'Chinese (Traditional)', ja:'Japanese', ko:'Korean', ar:'Arabic', hi:'Hindi', tr:'Turkish', nl:'Dutch', pl:'Polish' };
// Translate segments to targetLang using AI, in parallel batches to stay within token limits
// DISABLED — translation is on ice until a better solution is found
async function translateSegments(segments, targetLang, send) {
return segments; // no-op: skip all AI translation
if (!segments.length) return segments;
if (!process.env.GROQ_API_KEY && !process.env.OPENROUTER_API_KEY) return segments;
const langName = LANG_NAMES[targetLang] || targetLang;
send('progress', { stage: 'translate', message: `Translating to ${langName}…`, percent: 88 });
const SEP = '|||';
const CHUNK = 80;
const groq = process.env.GROQ_API_KEY ? new Groq({ apiKey: process.env.GROQ_API_KEY }) : null;
// Split into chunks upfront
const chunks = [];
for (let i = 0; i < segments.length; i += CHUNK) chunks.push(segments.slice(i, i + CHUNK));
// Translate a single chunk with retry
const translateChunk = async (batch) => {
const inputText = batch.map(s => s.text).join(`\n${SEP}\n`);
const messages = [
{ role: 'system', content: `You are a translator. Translate the user's text to ${langName}. The text contains segments separated by "${SEP}". Preserve every "${SEP}" separator exactly where it is. Do not add or remove separators.` },
{ role: 'user', content: inputText },
];
let translatedText = null;
for (let attempt = 0; attempt < 2; attempt++) {
try {
if (attempt > 0) await new Promise(r => setTimeout(r, 1500));
if (groq) {
const r = await groq.chat.completions.create({ model: 'llama-3.1-8b-instant', messages, max_tokens: 8192, temperature: 0 });
translatedText = r.choices[0].message.content;
} else {
const r = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'meta-llama/llama-3.1-8b-instruct:free', messages, max_tokens: 8192, temperature: 0 }) });
const d = await r.json();
translatedText = d.choices[0].message.content;
}
break;
} catch (e) {
console.error(`[translate] attempt ${attempt + 1} failed:`, e.message);
}
}
if (translatedText) {
const parts = translatedText.split(SEP).map(p => p.trim());
if (parts.length > 0) {
return batch.map((s, j) => ({ ...s, text: (parts[j] && parts[j].trim()) || s.text }));
}
}
return batch; // keep originals on failure
};
// Run all chunks in parallel — ~4× faster than sequential for multi-chunk videos
const results = await Promise.allSettled(chunks.map(chunk => translateChunk(chunk)));
return results.flatMap((r, i) => r.status === 'fulfilled' ? r.value : chunks[i]);
}
// Race a promise against a ms timeout (rejects on timeout)
const withTimeout = (promise, ms) => Promise.race([
promise,
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms)),
]);
const execFileAsync = promisify(execFile);
// ── Production flag ───────────────────────────────────────────────────────────
const isProd = !!(process.env.RAILWAY_ENVIRONMENT || process.env.NODE_ENV === 'production');
const safeErr = (err) => isProd ? undefined : (err?.message || String(err));
// ── Simple in-memory rate limiter (no extra dep) ──────────────────────────────
const _rlMap = new Map();
// Purge expired entries every minute to prevent unbounded memory growth
setInterval(() => {
const now = Date.now();
for (const [key, e] of _rlMap) if (now > e.resetAt) _rlMap.delete(key);
for (const [key, e] of _anonCreditsMap) if (now > e.resetAt) _anonCreditsMap.delete(key);
for (const [key, e] of _anonAiQuotaMap) if (now > e.resetAt) _anonAiQuotaMap.delete(key);
}, 60_000).unref(); // .unref() so this timer doesn't keep the process alive alone
function makeRateLimit({ windowMs, max, scope, keyFn }) {
return function rateLimitMw(req, res, next) {
const keyPart = keyFn ? keyFn(req) : getClientKey(req);
const key = `${scope}:${String(keyPart || getClientKey(req))}`;
const now = Date.now();
let e = _rlMap.get(key);
if (!e || now > e.resetAt) e = { count: 0, resetAt: now + windowMs };
e.count++;
_rlMap.set(key, e);
if (e.count > max) {
const retryAfter = Math.ceil((e.resetAt - now) / 1000);
const body = { error: 'Too many requests. Please slow down and try again shortly.' };
res.setHeader('Retry-After', retryAfter);
// EventSource clients cannot read non-2xx JSON bodies. Return an SSE error
// event so the UI can show the real reason instead of a generic connection error.
const accept = String(req.headers.accept || '').toLowerCase();
if (accept.includes('text/event-stream')) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') res.flushHeaders();
res.write(`event: transcript_error\ndata: ${JSON.stringify(body)}\n\n`);
res.end();
return;
}
return res.status(429).json(body);
}
next();
};
}
const aiAnonRateLimit = makeRateLimit({ scope: 'ai_anon', windowMs: 60_000, max: AI_ANON_RPM }); // anon AI calls/min per IP
const aiAuthRateLimit = makeRateLimit({ scope: 'ai_auth', windowMs: 60_000, max: AI_AUTH_RPM, keyFn: (req) => req.aiUser?.id || getClientKey(req) }); // auth AI calls/min per user
const uploadRateLimit = makeRateLimit({ scope: 'upload', windowMs: 60_000, max: 3 }); // 3 uploads/min per IP
const transcriptRateLimit = makeRateLimit({ scope: 'transcript', windowMs: 60_000, max: 30 }); // 30 fetches/min per IP
// Cache token → user for 60 s to avoid a Supabase round-trip on every AI call.
const _tokenCache = new Map(); // token → { user, expiresAt }
async function aiAccessGuard(req, res, next) {
const token = extractBearerToken(req);
if (token && supabaseAdmin) {
try {
const now = Date.now();
let cached = _tokenCache.get(token);
if (!cached || now > cached.expiresAt) {
const { data: { user }, error } = await supabaseAdmin.auth.getUser(token);
if (!error && user) {
cached = { user, expiresAt: now + 60_000 };
_tokenCache.set(token, cached);
} else {
cached = null;
_tokenCache.delete(token);
}
}
if (cached) {
req.aiUser = cached.user;
return aiAuthRateLimit(req, res, next);
}
} catch (err) {
console.warn('[ai-access] auth lookup failed, treating as anonymous:', err?.message || err);
}
}
if (AI_REQUIRE_AUTH) {
return res.status(401).json({ error: 'Sign in to continue using AI features.' });
}
if (!consumeAnonAiQuota(req, res)) return;
return aiAnonRateLimit(req, res, next);
}
// ── SSRF guard: only allow safe external http/https URLs ──────────────────────
function isSafeExternalUrl(rawUrl) {
let parsed;
try { parsed = new URL(rawUrl); } catch { return false; }
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
const host = parsed.hostname.toLowerCase();
// Block all loopback / localhost forms
if (host === 'localhost') return false;
// Block IPv6 — covers ::1, ::ffff:127.x, fc00::/7, fe80::/10, and all bracketed forms
if (host.startsWith('[') || host.includes(':')) return false;
// Block IPv4 private/reserved ranges
const ipv4 = host.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if (ipv4) {
const [a, b] = ipv4.slice(1).map(Number);
if (a === 10) return false; // 10.0.0.0/8
if (a === 127) return false; // 127.0.0.0/8
if (a === 169 && b === 254) return false; // 169.254.0.0/16 (link-local + AWS metadata)
if (a === 172 && b >= 16 && b <= 31) return false; // 172.16.0.0/12
if (a === 192 && b === 168) return false; // 192.168.0.0/16
if (a === 0) return false; // 0.0.0.0/8
if (a === 100 && b >= 64 && b <= 127) return false; // 100.64.0.0/10 (CGNAT)
if (a === 198 && (b === 18 || b === 19)) return false; // 198.18.0.0/15 (benchmarking)
if (a === 240) return false; // 240.0.0.0/4 (reserved)
}
// Block hostnames that are just decimal/octal/hex IP encodings (e.g. http://2130706433 = 127.0.0.1)
if (/^\d+$/.test(host) || /^0x[\da-f]+$/i.test(host)) return false;
return true;
}
const app = express();
const PORT = process.env.PORT || 3000;
// Write cookies to a temp file once at startup if YT_COOKIES env var is set
let cookiesPath = null;
if (process.env.YT_COOKIES) {
cookiesPath = require('path').join(require('os').tmpdir(), 'yt-cookies.txt');
require('fs').writeFileSync(cookiesPath, process.env.YT_COOKIES);
console.log('YouTube cookies loaded from YT_COOKIES env var');
}
// Build cookie args: use file if YT_COOKIES env var is set, otherwise no cookies.
// --cookies-from-browser was removed: it causes yt-dlp to abort on systems where
// Chrome's keychain is inaccessible (e.g. headless servers, macOS without UI).
const cookieArgs = cookiesPath ? ['--cookies', cookiesPath] : [];
// Resolve Node.js path for yt-dlp JS runtime (avoids "no runtime found" warning)
const { execFileSync } = require('child_process');
let nodePath = 'node';
try { nodePath = execFileSync('which', ['node'], { encoding: 'utf8' }).trim(); } catch {}
const jsRuntimeArgs = ['--js-runtimes', `node:${nodePath}`];
// Webshare residential proxy (bypasses YouTube datacenter IP blocking)
const proxyArgs = process.env.WEBSHARE_PROXY_URL ? ['--proxy', process.env.WEBSHARE_PROXY_URL] : [];
if (process.env.WEBSHARE_PROXY_URL) console.log('Webshare proxy loaded');
else console.log('No proxy configured — running without proxy');
// AI fallback download quality (Whisper source audio).
// Higher quality by default; can be tuned via env vars.
const ytdlpAudioQuality = process.env.YTDLP_AUDIO_QUALITY || '0'; // 0 best, 9 smallest
const ytdlpAudioFormat = process.env.YTDLP_AUDIO_FORMAT || 'bestaudio';
app.disable('x-powered-by');
app.set('trust proxy', 1); // Trust Railway/Cloudflare's X-Forwarded-For so req.ip is the real client IP
app.use(compression({
filter: (req, res) => {
// Never compress SSE endpoints. Compression can buffer event chunks and
// break incremental delivery in some browsers/proxies.
const isTranscriptSseRoute = req.path === '/api/transcript' || req.path === '/api/transcript/upload';
const acceptsSse = String(req.headers.accept || '').toLowerCase().includes('text/event-stream');
if (isTranscriptSseRoute || acceptsSse) return false;
return compression.filter(req, res);
},
}));
app.use(cors());
app.use(express.json({ limit: '5mb' }));
// Redirect www → non-www (canonical domain)
app.use((req, res, next) => {
const isApiRoute = req.path === '/api' || req.path.startsWith('/api/');
if (!isApiRoute && req.hostname && req.hostname.startsWith('www.')) {
const nonWww = req.hostname.slice(4);
return res.redirect(301, `${req.protocol}://${nonWww}${req.originalUrl}`);
}
next();
});
// ── Security headers ──────────────────────────────────────────────────────────
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
// HSTS: only set over HTTPS (Railway sets x-forwarded-proto; direct TLS sets req.protocol)
if (req.headers['x-forwarded-proto'] === 'https' || req.protocol === 'https') {
res.setHeader('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload');
}
next();
});
// ── Redirect .html → clean canonical URL (must run before static middleware) ──
app.use((req, res, next) => {
if (req.path.endsWith('.html')) {
const clean = req.path.slice(0, -5) || '/';
return res.redirect(301, clean);
}
next();
});
// Serve static files from React app
// `index: false` prevents `/` from resolving to client/public/index.html (template).
app.use(express.static(path.join(__dirname, 'client/public'), { index: false }));
app.use(express.static(path.join(__dirname, 'client/build'), {
setHeaders: (res, filePath) => {
// Never cache index.html — browsers must always fetch the latest so
// new content-hashed JS/CSS filenames are picked up after each deploy.
if (path.basename(filePath) === 'index.html') {
res.set('Cache-Control', 'no-cache, no-store, must-revalidate');
}
},
}));
function parseTimestamp(ts) {
const parts = ts.trim().replace(',', '.').split(':');
if (parts.length === 3) return parseInt(parts[0]) * 3600 + parseInt(parts[1]) * 60 + parseFloat(parts[2]);
if (parts.length === 2) return parseInt(parts[0]) * 60 + parseFloat(parts[1]);
return 0;
}
function parseVTT(content) {
const lines = content.split('\n');
const rawSegments = [];
let currentSeconds = null;
let currentTexts = [];
const flush = () => {
if (currentSeconds !== null && currentTexts.length > 0) {
const text = currentTexts.join(' ').replace(/\s+/g, ' ').trim();
if (text) rawSegments.push({ seconds: currentSeconds, text });
}
currentTexts = [];
currentSeconds = null;
};
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) { flush(); continue; }
if (trimmed.startsWith('WEBVTT') || trimmed.startsWith('Kind:') || trimmed.startsWith('Language:')) continue;
const tsMatch = trimmed.match(/^([\d:]+[.,]\d+)\s*-->/);
if (tsMatch) {
flush();
currentSeconds = Math.floor(parseTimestamp(tsMatch[1]));
continue;
}
if (/^\d+$/.test(trimmed)) continue;
const cleaned = trimmed.replace(/<[^>]+>/g, '').trim();
if (cleaned) currentTexts.push(cleaned);
}
flush();
// Strip rolling overlaps: YouTube auto-captions repeat previous line in each block.
// For each segment, remove words at the start that already appeared at the end of the previous segment.
const segments = [];
let lastText = '';
for (const seg of rawSegments) {
const words = seg.text.split(/\s+/);
const lastWords = lastText.split(/\s+/);
let overlap = 0;
for (let len = Math.min(words.length, lastWords.length); len > 0; len--) {
if (lastWords.slice(-len).join(' ').toLowerCase() === words.slice(0, len).join(' ').toLowerCase()) {
overlap = len;
break;
}
}
const newWords = words.slice(overlap);
if (newWords.length === 0) { lastText = seg.text; continue; }
segments.push({ seconds: seg.seconds, text: newWords.join(' ') });
lastText = seg.text;
}
const transcript = segments.map(s => s.text).join(' ').replace(/\s+/g, ' ').trim();
return { transcript, segments };
}
function parseJSON3(content) {
const json3 = JSON.parse(content);
const rawSegments = [];
for (const event of json3.events) {
if (!event.segs) continue;
const seconds = Math.floor((event.tStartMs || 0) / 1000);
const text = event.segs.map(s => s.utf8 || '').join('').replace(/\n/g, ' ').trim();
if (text) rawSegments.push({ seconds, text });
}
// Same rolling overlap removal as VTT
const segments = [];
let lastText = '';
for (const seg of rawSegments) {
const words = seg.text.split(/\s+/);
const lastWords = lastText.split(/\s+/);
let overlap = 0;
for (let len = Math.min(words.length, lastWords.length); len > 0; len--) {
if (lastWords.slice(-len).join(' ').toLowerCase() === words.slice(0, len).join(' ').toLowerCase()) {
overlap = len;
break;
}
}
const newWords = words.slice(overlap);
if (newWords.length === 0) { lastText = seg.text; continue; }
segments.push({ seconds: seg.seconds, text: newWords.join(' ') });
lastText = seg.text;
}
const transcript = segments.map(s => s.text).join(' ').replace(/\s+/g, ' ').trim();
return { transcript, segments };
}
function toWhisperLang(lang) {
return lang.split('-')[0];
}
function classifyYtdlpError(err) {
if (err?.code === 'ENOENT') return 'Transcript extraction tool (yt-dlp) is not installed on this server.';
const msg = (err?.stderr || err?.message || '').toLowerCase();
const missingBinary =
(msg.includes('spawn yt-dlp') && msg.includes('enoent')) ||
(msg.includes('yt-dlp') && msg.includes(': not found')) ||
(msg.includes('yt-dlp') && msg.includes('no such file or directory') && msg.includes('spawn'));
if (missingBinary)
return 'Transcript extraction tool (yt-dlp) is not installed on this server.';
if (msg.includes('429') || msg.includes('too many requests'))
return 'YouTube is rate-limiting this IP. Please wait a minute and try again.';
if (
msg.includes("sign in to confirm you're not a bot") ||
msg.includes("sign in to confirm you're not a bot") ||
msg.includes('not a bot') ||
msg.includes('use --cookies')
) {
return 'YouTube is blocking this request right now. Please try again in a few minutes.';
}
// Instagram-specific errors
if (
msg.includes('login required') ||
msg.includes('login_required') ||
msg.includes('challenge_required') ||
msg.includes('checkpoint_required') ||
msg.includes('please wait a few minutes') ||
(msg.includes('instagram') && msg.includes('not logged in'))
) {
return 'Instagram requires a login to access this video. Public Reels and posts may be restricted — try a different video.';
}
if (msg.includes('private') || msg.includes('members only'))
return 'This video is private or members-only.';
if (msg.includes('unavailable') || msg.includes('no longer available'))
return 'This video is unavailable.';
if (msg.includes('copyright'))
return 'This video is unavailable due to a copyright claim.';
return null;
}
async function cleanup(tmpDir, prefix) {
try {
const files = await fsPromises.readdir(tmpDir);
for (const f of files.filter(f => f.startsWith(prefix))) {
await fsPromises.unlink(path.join(tmpDir, f)).catch(() => {});
}
} catch {}
}
// ── Shared Whisper transcription helper ───────────────────────────────────────
async function whisperTranscribe(audioFile, safeLang) {
const { createReadStream } = require('fs');
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const transcription = await withTimeout(
groq.audio.transcriptions.create({
file: createReadStream(audioFile),
model: 'whisper-large-v3-turbo',
response_format: 'verbose_json',
timestamp_granularities: ['segment'],
language: toWhisperLang(safeLang),
}),
150000 // 2.5-minute cap — leaves buffer before the client's 3-minute kill timer
);
await fsPromises.unlink(audioFile).catch(() => {});
const rawSegments = transcription.segments || [];
const seen = new Set();
const segments = rawSegments
.map(s => ({ seconds: Math.floor(s.start), text: s.text.trim() }))
.filter(s => s.text && !seen.has(s.text) && seen.add(s.text));
const transcript = segments.map(s => s.text).join(' ').replace(/\s+/g, ' ').trim();
return { transcript, segments };
}
// ── Video metadata proxy (avoids browser CORS on oEmbed APIs) ─────────────────