-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathnative.ts
More file actions
3213 lines (2816 loc) · 121 KB
/
native.ts
File metadata and controls
3213 lines (2816 loc) · 121 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
/*
* Vencord, a Discord client mod
* Copyright (c) 2024 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import crypto from "crypto";
import { BrowserWindow, dialog, WebContents } from "electron";
import fs from "fs";
import http from "http";
import https from "https";
import os from "os";
import path from "path";
// Type definitions for upload service responses
interface GoFileResponse {
status: "ok" | "error";
data?: {
downloadPage?: string;
code?: string;
fileName?: string;
fileId?: string;
};
error?: string;
}
type LoggingLevel = "errors" | "info" | "debug";
const levelPriority: Record<LoggingLevel, number> = {
errors: 0,
info: 1,
debug: 2
};
let currentLoggingLevel: LoggingLevel = "errors";
// Uploaders that don't support EXE files
const EXE_BLOCKED_UPLOADERS = ["Catbox", "Litterbox", "0x0.st"];
const EXE_FALLBACK_UPLOADER = "GoFile";
// Security: Maximum response body size to prevent memory exhaustion from server responses
// Note: This does NOT limit upload file size - files stream directly from disk with no memory limit
// This only limits the JSON/text response from the upload service (1MB is plenty for any valid response)
const MAX_RESPONSE_SIZE = 1 * 1024 * 1024;
// Nitro upload limits (used to decide whether to use Discord's native upload)
const NITRO_LIMITS: Record<string, number> = {
none: 10 * 1024 * 1024, // 10MB for no Nitro
basic: 50 * 1024 * 1024, // 50MB for Nitro Basic
full: 500 * 1024 * 1024, // 500MB for full Nitro
};
function isExeFile(fileName: string): boolean {
return fileName.toLowerCase().endsWith(".exe");
}
function getEffectiveUploader(fileName: string, selectedUploader: string): string {
if (isExeFile(fileName) && EXE_BLOCKED_UPLOADERS.includes(selectedUploader)) {
nativeLog.info(`[BigFileUpload] ${selectedUploader} doesn't support EXE files, using ${EXE_FALLBACK_UPLOADER} instead`);
return EXE_FALLBACK_UPLOADER;
}
return selectedUploader;
}
/** Ensure timeout is a valid positive number (req.setTimeout throws if NaN). Default 5 min. */
function safeUploadTimeout(ms: number | undefined): number {
const n = Number(ms);
return Number.isFinite(n) && n > 0 ? n : 300000;
}
/**
* Video extensions supported by each embed service
* - embeddr.top: only .mp4, .mov, .mkv
* - x266.mov: more diverse, includes .webm and others
* - nfp: no .mkv support, no HEVC/h.265
*/
const EMBED_SERVICE_EXTENSIONS: Record<string, string[]> = {
embeddr: [".mp4", ".mov", ".mkv"],
x266: [".mp4", ".mov", ".mkv", ".webm", ".avi", ".flv"],
nfp: [".mp4", ".mov", ".webm", ".avi"], // .mkv does NOT work per their site
};
/**
* Check if a URL ends with a supported video extension for the given embed service
*/
function isEmbeddableVideoForService(url: string, service: string | undefined): boolean {
const lower = url.toLowerCase();
const extensions = EMBED_SERVICE_EXTENSIONS[service || "x266"] || EMBED_SERVICE_EXTENSIONS.x266;
return extensions.some(ext => lower.endsWith(ext));
}
/**
* Apply embed service to a video URL if appropriate
* Only applies if the URL ends with a supported video extension for that service
* Different services have different URL formats:
* - embeddr.top: https://embeddr.top/<url>
* - x266.mov: https://x266.mov/e/<url>
* - discord.nfp.is: https://discord.nfp.is/?v=<url-encoded>
*/
function applyEmbedService(url: string, service: string | undefined): string {
const svc = service || "x266";
if (!isEmbeddableVideoForService(url, svc)) {
const extensions = EMBED_SERVICE_EXTENSIONS[svc] || EMBED_SERVICE_EXTENSIONS.x266;
nativeLog.debug(`[BigFileUpload] Skipping embed service - URL must end with ${extensions.join(", ")}: ${url}`);
return url;
}
switch (svc) {
case "x266":
return "https://x266.mov/e/" + url;
case "nfp":
// discord.nfp.is uses ?v= query parameter with URL encoding
return "https://discord.nfp.is/?v=" + encodeURIComponent(url);
case "embeddr":
default:
return "https://embeddr.top/" + url;
}
}
/**
* Check if an IP address is in a private/reserved range (SSRF protection)
*/
function isPrivateOrReservedIP(hostname: string): boolean {
// Check for localhost variations
if (hostname === "localhost" || hostname === "localhost.localdomain") {
return true;
}
// Check if it's an IP address
const ipv4Match = hostname.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (ipv4Match) {
const [, a, b, c] = ipv4Match.map(Number);
// Loopback (127.0.0.0/8)
if (a === 127) return true;
// Private Class A (10.0.0.0/8)
if (a === 10) return true;
// Private Class B (172.16.0.0/12)
if (a === 172 && b >= 16 && b <= 31) return true;
// Private Class C (192.168.0.0/16)
if (a === 192 && b === 168) return true;
// Link-local (169.254.0.0/16) - includes cloud metadata service
if (a === 169 && b === 254) return true;
// Current network (0.0.0.0/8)
if (a === 0) return true;
// Broadcast
if (a === 255) return true;
}
// Check for IPv6 loopback
if (hostname === "::1" || hostname === "[::1]") {
return true;
}
// Check for IPv6 link-local or private
if (hostname.startsWith("fe80:") || hostname.startsWith("[fe80:")) {
return true;
}
if (hostname.startsWith("fc") || hostname.startsWith("[fc") ||
hostname.startsWith("fd") || hostname.startsWith("[fd")) {
return true;
}
return false;
}
/**
* Validate that a URL returned from an upload service is safe to use
* Prevents malformed URLs, injection attacks, and SSRF
*/
function validateUploadUrl(url: string): boolean {
if (!url || typeof url !== "string") return false;
// Must be a valid URL
try {
const parsed = new URL(url);
// Must be http or https
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
nativeLog.warn(`[BigFileUpload] Invalid URL protocol: ${parsed.protocol}`);
return false;
}
// Must have a valid hostname
if (!parsed.hostname || parsed.hostname.length < 3) {
nativeLog.warn(`[BigFileUpload] Invalid URL hostname: ${parsed.hostname}`);
return false;
}
// SSRF protection: reject private/reserved IPs and localhost
if (isPrivateOrReservedIP(parsed.hostname)) {
nativeLog.warn(`[BigFileUpload] Blocked private/reserved IP in URL: ${parsed.hostname}`);
return false;
}
// Reject hostnames that are just numbers (likely IP obfuscation)
if (/^\d+$/.test(parsed.hostname)) {
nativeLog.warn(`[BigFileUpload] Blocked numeric-only hostname: ${parsed.hostname}`);
return false;
}
// Hostname should contain at least one dot (basic TLD check)
if (!parsed.hostname.includes(".")) {
nativeLog.warn(`[BigFileUpload] Invalid hostname (no TLD): ${parsed.hostname}`);
return false;
}
return true;
} catch {
nativeLog.warn(`[BigFileUpload] Invalid URL format: ${url.substring(0, 100)}`);
return false;
}
}
/**
* Dangerous headers that should not be set by users (security risk)
*/
const BLOCKED_HEADERS = new Set([
"host",
"connection",
"upgrade",
"proxy-authorization",
"proxy-connection",
"te",
"trailer",
"transfer-encoding",
"keep-alive",
"expect",
"cookie",
"set-cookie",
"authorization", // Prevent credential theft via custom uploaders
"www-authenticate",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
"x-real-ip",
"forwarded"
]);
/**
* Sanitize custom headers to prevent header injection attacks
* Removes dangerous headers that could be used for SSRF or credential theft
*/
function sanitizeHeaders(headers: Record<string, string>): Record<string, string> {
const sanitized: Record<string, string> = {};
for (const [key, value] of Object.entries(headers)) {
const lowerKey = key.toLowerCase().trim();
// Skip blocked headers
if (BLOCKED_HEADERS.has(lowerKey)) {
nativeLog.warn(`[BigFileUpload] Blocked dangerous header: ${key}`);
continue;
}
// Skip empty keys
if (!key || key.trim() === "") {
continue;
}
// Validate header value (no newlines to prevent header injection)
if (typeof value === "string" && !value.includes("\n") && !value.includes("\r")) {
sanitized[key] = value;
} else {
nativeLog.warn(`[BigFileUpload] Blocked header with invalid value: ${key}`);
}
}
return sanitized;
}
/**
* Safely parse JSON with a fallback default value
*/
function parseJsonSafe<T>(json: string | undefined, defaultValue: T): T {
if (!json || json.trim() === "") return defaultValue;
try {
return JSON.parse(json);
} catch {
nativeLog.warn(`[BigFileUpload] Failed to parse JSON: ${json.substring(0, 100)}`);
return defaultValue;
}
}
/**
* Navigate a JSON object using a path that supports:
* - Dot notation: "data.url"
* - Array indices: "files[0].url" or "files.0.url"
* - Nested paths: "response.data.files[0].link"
*/
function navigateJsonPath(obj: any, pathParts: string[]): any {
let current = obj;
for (const part of pathParts) {
if (current === null || current === undefined) {
return undefined;
}
// Handle array index notation: "files[0]" -> access files then index 0
const arrayMatch = part.match(/^([^[]+)\[(\d+)\]$/);
if (arrayMatch) {
const [, key, index] = arrayMatch;
if (key) {
current = current[key];
if (current === null || current === undefined) return undefined;
}
current = current[parseInt(index, 10)];
}
// Handle numeric string as array index
else if (/^\d+$/.test(part) && Array.isArray(current)) {
current = current[parseInt(part, 10)];
}
// Standard object property access
else {
current = current[part];
}
}
return current;
}
/**
* Extract URL from response text using multiple strategies
*/
function extractUrlFromResponse(responseText: string, responseType: string, urlPath: string[], baseUrl?: string): string {
const trimmed = responseText.trim();
// Strategy 1: JSON response parsing
if (responseType === "JSON" || (responseType === "Text" && trimmed.startsWith("{") || trimmed.startsWith("["))) {
try {
const parsed = JSON.parse(trimmed);
// If urlPath is provided, use it
if (urlPath.length > 0) {
const extracted = navigateJsonPath(parsed, urlPath);
if (typeof extracted === "string" && extracted.length > 0) {
return resolveUrl(extracted, baseUrl);
}
}
// Auto-detect common URL fields if no path or path failed
const commonFields = [
["url"], ["link"], ["href"], ["file"], ["download"],
["data", "url"], ["data", "link"], ["data", "file"],
["result", "url"], ["result", "link"],
["response", "url"], ["response", "link"],
["files", "0", "url"], ["files", "0", "link"],
["image", "url"], ["image", "link"],
["upload", "url"], ["upload", "link"]
];
for (const path of commonFields) {
const value = navigateJsonPath(parsed, path);
if (typeof value === "string" && (value.startsWith("http") || value.startsWith("/"))) {
nativeLog.debug(`[BigFileUpload] Auto-detected URL at path: ${path.join(".")}`);
return resolveUrl(value, baseUrl);
}
}
// If the response is just a string URL in JSON
if (typeof parsed === "string" && (parsed.startsWith("http") || parsed.startsWith("/"))) {
return resolveUrl(parsed, baseUrl);
}
throw new Error("Could not find URL in JSON response. Try specifying a URL path.");
} catch (e) {
if (responseType === "JSON") {
throw e;
}
// Fall through to text parsing if auto-detect JSON failed
}
}
// Strategy 2: Direct URL (response is just a URL)
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
// Take only the first line if multi-line
const firstLine = trimmed.split(/[\r\n]/)[0].trim();
if (firstLine.startsWith("http")) {
return firstLine;
}
}
// Strategy 3: Extract URL from text using regex
const urlRegex = /https?:\/\/[^\s<>"')\]]+/gi;
const matches = trimmed.match(urlRegex);
if (matches && matches.length > 0) {
// Prefer longer URLs (more likely to be the actual file URL)
const bestMatch = matches.reduce((a, b) => a.length >= b.length ? a : b);
nativeLog.debug(`[BigFileUpload] Extracted URL from text response: ${bestMatch}`);
return bestMatch;
}
// Strategy 4: Handle relative URLs
if (trimmed.startsWith("/") && baseUrl) {
return resolveUrl(trimmed, baseUrl);
}
// If nothing worked, return trimmed response (might be a valid URL)
return trimmed;
}
/**
* Resolve potentially relative URL against a base URL
*/
function resolveUrl(url: string, baseUrl?: string): string {
if (!url) return "";
// Already absolute
if (url.startsWith("http://") || url.startsWith("https://")) {
return url;
}
// Relative URL - need base
if (baseUrl) {
try {
const base = new URL(baseUrl);
if (url.startsWith("/")) {
return `${base.protocol}//${base.host}${url}`;
}
// Relative path
return new URL(url, baseUrl).href;
} catch {
// Failed to construct URL
}
}
// Return as-is
return url;
}
const nativeLog = {
info: (...args: any[]) => {
if (levelPriority[currentLoggingLevel] >= levelPriority.info) {
console.log(...args);
}
},
debug: (...args: any[]) => {
if (levelPriority[currentLoggingLevel] >= levelPriority.debug) {
console.debug(...args);
}
},
warn: (...args: any[]) => console.warn(...args),
error: (...args: any[]) => console.error(...args)
};
function updateLoggingLevel(level?: LoggingLevel) {
currentLoggingLevel = level ?? "errors";
}
/**
* Save ArrayBuffer to temporary file (fallback when file.path not available)
* Uses timestamp + random UUID to prevent collisions with concurrent uploads
*/
async function saveTempFile(fileBuffer: ArrayBuffer, fileName: string): Promise<string> {
const tempDir = os.tmpdir();
// Use both timestamp and random string to prevent collision in concurrent uploads
const uniqueId = `${Date.now()}-${crypto.randomBytes(8).toString("hex")}`;
const tempFileName = `vencord-upload-${uniqueId}-${fileName}`;
const tempPath = path.join(tempDir, tempFileName);
await fs.promises.writeFile(tempPath, Buffer.from(fileBuffer));
return tempPath;
}
/**
* Race multiple upload promises and return the first successful one.
* Unlike Promise.race(), this ignores rejections/nulls and waits for the first success.
* If all promises reject or return null, returns null.
*/
async function raceToFirstSuccess<T>(
promises: Array<Promise<T | null>>
): Promise<T | null> {
if (promises.length === 0) return null;
return new Promise(resolve => {
let settled = false;
let pendingCount = promises.length;
for (const promise of promises) {
promise
.then(result => {
if (!settled && result !== null) {
settled = true;
resolve(result);
} else {
pendingCount--;
if (pendingCount === 0 && !settled) {
resolve(null);
}
}
})
.catch(() => {
pendingCount--;
if (pendingCount === 0 && !settled) {
resolve(null);
}
});
}
});
}
/**
* Delete temporary file
*/
async function deleteTempFile(filePath: string): Promise<void> {
try {
await fs.promises.unlink(filePath);
nativeLog.debug(`[BigFileUpload] Temp file deleted: ${filePath}`);
} catch (error) {
// Log cleanup errors at debug level to help diagnose orphaned temp files
// Don't throw - cleanup failure shouldn't break the upload flow
const errorMsg = error instanceof Error ? error.message : String(error);
nativeLog.debug(`[BigFileUpload] Failed to delete temp file ${filePath}: ${errorMsg}`);
}
}
async function getGoFileUploadUrl(): Promise<string> {
// GoFile API updated May 2025 - uses global upload endpoint
// Regional endpoints available: upload-eu-par, upload-na-phx, upload-ap-sgp, etc.
return "https://upload.gofile.io/uploadfile";
}
/**
* Stream file upload using PUT request (for transfer.sh)
* Streams file directly without multipart encoding
*/
function streamFilePutUpload(
url: string,
filePath: string,
fileName: string,
customHeaders: Record<string, string> = {},
webContents?: WebContents,
uploadId?: string,
timeout: number = 300000
): Promise<string> {
let isCancelled = false;
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const isHttps = urlObj.protocol === "https:";
const client = isHttps ? https : http;
// Verify file exists and get size
if (!fs.existsSync(filePath)) {
reject(new Error(`File not found: ${filePath}`));
return;
}
const fileStats = fs.statSync(filePath);
const fileSize = fileStats.size;
// Validate file size is non-zero
if (fileSize === 0) {
reject(new Error(`File is empty (0 bytes): ${filePath}`));
return;
}
// Validate file is readable
try {
fs.accessSync(filePath, fs.constants.R_OK);
} catch (err) {
reject(new Error(`File is not readable: ${filePath}`));
return;
}
const options: any = {
hostname: urlObj.hostname,
port: urlObj.port || (isHttps ? 443 : 80),
path: urlObj.pathname + urlObj.search,
method: "PUT",
headers: {
"Content-Type": "application/octet-stream",
"Content-Length": fileSize,
...customHeaders
}
};
// Add TLS options for HTTPS connections to prevent handshake issues
if (isHttps) {
// Create a custom agent with proper TLS settings
options.agent = new https.Agent({
keepAlive: true,
timeout: 30000,
rejectUnauthorized: true
});
}
const startTime = Date.now();
let lastProgressTime = Date.now();
let uploadedBytes = 0;
// Stall detection
const stallCheckInterval = setInterval(() => {
const timeSinceLastProgress = Date.now() - lastProgressTime;
if (timeSinceLastProgress > 300000) { // 5 minutes
clearInterval(stallCheckInterval);
req.destroy();
reject(new Error("Upload stalled - no progress for 5 minutes"));
}
}, 10000);
const req = client.request(options, res => {
let responseData = "";
let responseTruncated = false;
// Set socket timeout to prevent hanging connections
res.socket.setTimeout(60000); // 60 second timeout for responses
res.on("data", chunk => {
// Security: Limit response size to prevent memory exhaustion
if (responseData.length + chunk.length > MAX_RESPONSE_SIZE) {
if (!responseTruncated) {
nativeLog.warn(`[BigFileUpload] Response exceeded ${MAX_RESPONSE_SIZE} bytes, truncating`);
responseTruncated = true;
}
return; // Stop accumulating data
}
responseData += chunk;
});
res.on("end", () => {
clearInterval(stallCheckInterval);
if (uploadId) {
activeRequests.delete(uploadId);
}
// Check if this upload was cancelled before resolving
if (uploadId && cancelledUploads.has(uploadId)) {
cancelledUploads.delete(uploadId);
reject(new Error("Upload cancelled by user"));
return;
}
// Reject truncated responses to prevent JSON parsing errors
if (responseTruncated) {
reject(new Error(`Response exceeded maximum size (${MAX_RESPONSE_SIZE} bytes) and was truncated. The upload may have succeeded but the response could not be processed.`));
return;
}
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
// Clean up from cancelled set only on successful completion
if (uploadId) {
cancelledUploads.delete(uploadId);
}
resolve(responseData);
} else {
let errorMessage = `HTTP ${res.statusCode}: ${res.statusMessage}`;
if (res.statusCode === 500) {
errorMessage = "HTTP 500: Server Internal Error - The upload service is experiencing issues. Try using a different uploader (temp.sh, Catbox, 0x0.st, or file.io).";
} else if (res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
errorMessage = `HTTP ${res.statusCode}: Service Unavailable - The upload service is temporarily down or overloaded. Try using a different uploader.`;
} else if (res.statusCode === 429) {
errorMessage = "HTTP 429: Rate Limited - Too many requests. Please wait before trying again.";
} else if (res.statusCode === 413) {
errorMessage = "HTTP 413: File Too Large - The file exceeds the service's size limit.";
}
if (responseData && responseData.length > 0 && responseData.length < 500) {
errorMessage += `\nServer response: ${responseData}`;
}
reject(new Error(errorMessage));
}
});
});
// Set request timeout (user-configurable, default 5 minutes)
req.setTimeout(timeout);
req.on("timeout", () => {
clearInterval(stallCheckInterval);
if (uploadId) {
activeRequests.delete(uploadId);
}
req.destroy();
reject(new Error("Request timeout - The server took too long to respond."));
});
req.on("error", error => {
clearInterval(stallCheckInterval);
if (uploadId) {
activeRequests.delete(uploadId);
}
if (isCancelled) {
reject(new Error("Upload cancelled by user"));
} else {
const errorMessage = error.message || String(error);
if (errorMessage.includes("ECONNRESET") || errorMessage.includes("Client network socket disconnected")) {
// More detailed error for connection reset
const serviceName = url.includes("0x0.st") ? "0x0.st" :
url.includes("tmpfiles.org") ? "tmpfiles.org" :
url.includes("catbox") ? "Catbox/Litterbox" :
"the upload service";
let alternativeServices = "";
if (url.includes("catbox") || url.includes("litterbox")) {
alternativeServices = "Please try using: 0x0.st, tmpfiles.org, temp.sh, file.io, or transfer.sh instead.";
} else if (url.includes("0x0.st") || url.includes("tmpfiles")) {
alternativeServices = "Please try using: Catbox, Litterbox, temp.sh, file.io, or transfer.sh instead.";
} else {
alternativeServices = "Please try using a different uploader service.";
}
reject(new Error(`Connection blocked to ${serviceName} - This could mean:\n` +
"1. Your network/firewall is blocking SSL/TLS connections to this service\n" +
"2. The service is blocked by your ISP or organization\n" +
"3. There's a proxy interfering with the connection\n\n" +
"Try using a VPN, proxy, or connecting from a different network.\n\n" +
alternativeServices));
} else if (errorMessage.includes("ETIMEDOUT")) {
reject(new Error("Connection timed out - The upload service did not respond in time. Try again or use a different uploader."));
} else if (errorMessage.includes("ENOTFOUND")) {
reject(new Error("Service not found - Cannot reach the upload service. Check your internet connection."));
} else if (errorMessage.includes("EPIPE") || errorMessage.includes("ECONNABORTED")) {
reject(new Error("Connection aborted - The server terminated the connection. This may be due to file size limits or server issues. Try a different uploader."));
} else if (errorMessage.includes("self signed certificate") || errorMessage.includes("SELF_SIGNED") ||
errorMessage.includes("UNABLE_TO_VERIFY_LEAF_SIGNATURE") || errorMessage.includes("DEPTH_ZERO_SELF_SIGNED_CERT")) {
// Certificate errors - likely behind corporate proxy or firewall
const serviceName = url.includes("0x0.st") ? "0x0.st" :
url.includes("tmpfiles.org") ? "tmpfiles.org" :
url.includes("catbox") ? "Catbox/Litterbox" :
url.includes("temp.sh") ? "temp.sh" :
url.includes("filebin.net") ? "filebin.net" :
url.includes("buzzheavier") ? "buzzheavier.com" :
url.includes("gofile") ? "GoFile" :
"the upload service";
reject(new Error(`SSL certificate error with ${serviceName} - You may be behind a corporate firewall or proxy that uses self-signed certificates. ` +
"The plugin will try alternative uploaders automatically."));
} else {
reject(error);
}
}
});
// Progress tracking helper
const logProgress = () => {
// Don't send progress for cancelled uploads
if (uploadId && cancelledUploads.has(uploadId)) {
return;
}
const elapsed = (Date.now() - startTime) / 1000;
const uploadSpeed = uploadedBytes / elapsed / 1024 / 1024; // MB/s
const percentComplete = (uploadedBytes / fileSize) * 100;
const remaining = elapsed > 0 ? (fileSize - uploadedBytes) / (uploadedBytes / elapsed) : 0;
if (webContents && !webContents.isDestroyed() && uploadId) {
const progressData = {
uploadId,
fileName,
loaded: uploadedBytes,
total: fileSize,
percent: percentComplete,
speed: uploadSpeed,
eta: remaining
};
latestProgress = progressData;
}
};
// Stream file directly from disk
const fileStream = fs.createReadStream(filePath, { highWaterMark: 256 * 1024 });
let lastLogBytes = 0;
fileStream.on("data", chunk => {
// Stop processing if cancelled (use local flag, not global set)
if (isCancelled) {
fileStream.destroy();
return;
}
const canContinue = req.write(chunk);
uploadedBytes += chunk.length;
lastProgressTime = Date.now();
// Progress logging
let logInterval: number;
if (fileSize > 100 * 1024 * 1024) {
logInterval = 5 * 1024 * 1024; // 5MB for large files
} else if (fileSize > 10 * 1024 * 1024) {
logInterval = 2 * 1024 * 1024; // 2MB for medium files
} else {
logInterval = 512 * 1024; // 512KB for small files
}
if (uploadedBytes - lastLogBytes >= logInterval || uploadedBytes === chunk.length) {
logProgress();
lastLogBytes = uploadedBytes;
}
if (!canContinue) {
fileStream.pause();
req.once("drain", () => {
fileStream.resume();
});
}
});
fileStream.on("end", () => {
// Don't finish the request if upload was cancelled (use local flag)
if (isCancelled) {
req.destroy();
return;
}
logProgress();
req.end();
});
fileStream.on("error", error => {
clearInterval(stallCheckInterval);
req.destroy();
reject(error);
});
// Store request for cancellation
if (uploadId) {
activeRequests.set(uploadId, {
req,
cleanup: () => {
isCancelled = true;
clearInterval(stallCheckInterval);
// Destroy file stream first to stop reading
try {
fileStream.destroy();
} catch (e) {
// Ignore errors
}
// Aggressively abort the request without flushing
try {
// Destroy underlying socket immediately to prevent any more data transmission
if (req.socket) {
req.socket.destroy();
}
// Also destroy the request itself
req.destroy();
} catch (e) {
// Ignore errors
}
}
});
}
});
}
/**
* Stream binary file upload for custom uploaders (PUT/PATCH/POST with raw body)
* Similar to streamFilePutUpload but with configurable method and content type
* Used for ShareX-style binary uploads where the file is sent as raw request body
*/
function streamFileBinaryCustom(
url: string,
filePath: string,
fileName: string,
fileType: string,
method: "PUT" | "PATCH" | "POST",
customHeaders: Record<string, string> = {},
webContents?: WebContents,
uploadId?: string,
timeout: number = 300000
): Promise<string> {
let isCancelled = false;
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const isHttps = urlObj.protocol === "https:";
const client = isHttps ? https : http;
// SSRF protection: reject private/reserved IPs
if (isPrivateOrReservedIP(urlObj.hostname)) {
reject(new Error(`Custom uploader: Blocked request to private/reserved IP: ${urlObj.hostname}`));
return;
}
// Verify file exists and get size
if (!fs.existsSync(filePath)) {
reject(new Error(`File not found: ${filePath}`));
return;
}
const fileStats = fs.statSync(filePath);
const fileSize = fileStats.size;
// Validate file size is non-zero
if (fileSize === 0) {
reject(new Error(`File is empty (0 bytes): ${filePath}`));
return;
}
// Validate file is readable
try {
fs.accessSync(filePath, fs.constants.R_OK);
} catch (err) {
reject(new Error(`File is not readable: ${filePath}`));
return;
}
// Sanitize custom headers to remove dangerous headers
const sanitizedHeaders = sanitizeHeaders(customHeaders);
const options: any = {
hostname: urlObj.hostname,
port: urlObj.port || (isHttps ? 443 : 80),
path: urlObj.pathname + urlObj.search,
method: method,
headers: {
"Content-Type": fileType || "application/octet-stream",
"Content-Length": fileSize,
"User-Agent": "Vencord-BigFileUpload/1.0",
...sanitizedHeaders
}
};
// Add TLS options for HTTPS connections
if (isHttps) {
options.agent = new https.Agent({
keepAlive: true,
timeout: 30000,
rejectUnauthorized: true
});
}
const startTime = Date.now();
let lastProgressTime = Date.now();
let uploadedBytes = 0;
// Stall detection
const stallCheckInterval = setInterval(() => {
const timeSinceLastProgress = Date.now() - lastProgressTime;
if (timeSinceLastProgress > 300000) { // 5 minutes
clearInterval(stallCheckInterval);
req.destroy();
reject(new Error("Upload stalled - no progress for 5 minutes"));
}
}, 10000);
const req = client.request(options, res => {
let responseData = "";
let responseTruncated = false;
res.socket.setTimeout(60000);
res.on("data", chunk => {
if (responseData.length + chunk.length > MAX_RESPONSE_SIZE) {
if (!responseTruncated) {
nativeLog.warn(`[BigFileUpload] Response exceeded ${MAX_RESPONSE_SIZE} bytes, truncating`);
responseTruncated = true;
}
return;
}
responseData += chunk;
});
res.on("end", () => {
clearInterval(stallCheckInterval);
if (uploadId) {
activeRequests.delete(uploadId);
}
if (uploadId && cancelledUploads.has(uploadId)) {
cancelledUploads.delete(uploadId);
reject(new Error("Upload cancelled by user"));
return;
}
if (responseTruncated) {
reject(new Error(`Response exceeded maximum size (${MAX_RESPONSE_SIZE} bytes) and was truncated.`));
return;
}
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
if (uploadId) {
cancelledUploads.delete(uploadId);
}
resolve(responseData);
} else {
let errorMessage = `HTTP ${res.statusCode}: ${res.statusMessage}`;
if (res.statusCode === 500) {
errorMessage = "HTTP 500: Server Internal Error - The custom upload service is experiencing issues.";
} else if (res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
errorMessage = `HTTP ${res.statusCode}: Service Unavailable - The custom upload service is temporarily down.`;
} else if (res.statusCode === 429) {
errorMessage = "HTTP 429: Rate Limited - Too many requests to the custom uploader.";
} else if (res.statusCode === 413) {
errorMessage = "HTTP 413: File Too Large - The file exceeds the custom service's size limit.";
}