Repository navigation
Expand file tree
/
Copy pathnative.ts
More file actions
1400 lines (1241 loc) · 63.4 KB
/
Copy pathnative.ts
File metadata and controls
1400 lines (1241 loc) · 63.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
/*
* Vencord, a Discord client mod
* Copyright (c) 2026 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { NativeSettings } from "@main/settings";
import { createHash, Hash, randomUUID } from "crypto";
import { subscribe } from "diagnostics_channel";
import { lookup } from "dns/promises";
import { BrowserWindow, dialog, IpcMainInvokeEvent, MessageBoxOptions, WebContents } from "electron";
import { constants, rmSync } from "fs";
import { FileHandle, lstat, mkdir, open, readdir, stat, statfs, unlink } from "fs/promises";
import { request as httpsRequest, RequestOptions } from "https";
import { isIP } from "net";
import { tmpdir } from "os";
import { join } from "path";
import { Readable, Transform } from "stream";
import { pipeline } from "stream/promises";
import { constants as zlibConstants, createBrotliDecompress, createGunzip, createInflate, createInflateRaw } from "zlib";
import { approvalTarget, classifyFetchError, classifyHttpBlock, describeNetworkError, firstErrorCode, httpHostKind, httpLanOnlyText, isBuiltInOrigin, isDnsCode, isPrivateAddress, isPublicSourceAddress, NATIVE_MAX_BUFFER, NativeErrorCode, PROXY_RETRY_KINDS, RESPONSE_GRACE_MS, SPOOL_HEAD_BYTES, SPOOL_MAX_BYTES, SPOOL_SLICE_BYTES, SpoolSource, UploadAbortError, UploadFailure } from "./utils/shared";
const sessionOrigins = new Set<string>();
const pendingApprovals = new Map<string, Promise<OriginApproval>>();
type OriginApproval = "approved" | "trusted" | "allowed" | "cancelled";
const APPROVAL_TEXT = "This server wasn't approved for uploads";
function httpOrigin(url: unknown): string | null {
if (typeof url !== "string" || !URL.canParse(url)) return null;
const { protocol, origin } = new URL(url);
return protocol === "https:" || protocol === "http:" ? origin : null;
}
const approvalOrigin = (url: string) => httpOrigin(approvalTarget(url));
function trustedOrigins(): string[] {
const saved = NativeSettings.store.plugins.BigFileUpload?.approvedOrigins;
return Array.isArray(saved) ? saved.filter((origin): origin is string => typeof origin === "string") : [];
}
function originApproved(url: string): boolean {
const origin = approvalOrigin(url);
return origin !== null && (isBuiltInOrigin(url) || sessionOrigins.has(origin) || trustedOrigins().includes(origin));
}
const unapproved = (url: string) => httpOrigin(url) !== null && !originApproved(url);
async function askOrigin(e: IpcMainInvokeEvent, origin: string): Promise<OriginApproval> {
try {
const options: MessageBoxOptions = {
type: "warning", title: "BigFileUpload", noLink: true,
message: `BigFileUpload wants to upload to ${new URL(origin).host}`,
detail: `Server: ${origin}\n\nOnly trust servers you recognise. Trust remembers it on this device. Allow until restart permits it until Discord restarts.`,
buttons: ["Trust", "Allow until restart", "Cancel"], defaultId: 2, cancelId: 2
};
const window = BrowserWindow.fromWebContents(e.sender);
const { response } = window ? await dialog.showMessageBox(window, options) : await dialog.showMessageBox(options);
if (response === 0) {
const { plugins } = NativeSettings.store;
plugins.BigFileUpload ??= {};
plugins.BigFileUpload.approvedOrigins = [...new Set([...trustedOrigins(), origin])];
return "trusted";
}
if (response === 1) {
sessionOrigins.add(origin);
return "allowed";
}
} catch { }
return "cancelled";
}
export async function requestOriginApproval(e: IpcMainInvokeEvent, url: string): Promise<OriginApproval> {
const origin = approvalOrigin(url);
if (!origin) return "cancelled";
if (originApproved(url)) return "approved";
let pending = pendingApprovals.get(origin);
if (!pending) {
pending = askOrigin(e, origin).finally(() => pendingApprovals.delete(origin));
pendingApprovals.set(origin, pending);
}
return pending;
}
export async function listApprovedOrigins(): Promise<string[]> {
return trustedOrigins();
}
export async function forgetApprovedOrigins(): Promise<boolean> {
sessionOrigins.clear();
const plugin = NativeSettings.store.plugins.BigFileUpload;
if (plugin && "approvedOrigins" in plugin) delete plugin.approvedOrigins;
return true;
}
let transferOwner: number | null = null;
let lastOwner: number | null = null;
type NativeBusy = SourceFailure & { busy: true; };
async function withNativeTransfer<T>(e: IpcMainInvokeEvent, run: () => Promise<T>): Promise<T | NativeBusy> {
if (transferOwner !== null) return { success: false, busy: true, code: "local", error: "Another window is transferring a file. Try again when it finishes" };
transferOwner = e.sender.id;
if (lastOwner !== transferOwner) resetProgress();
lastOwner = transferOwner;
watchSender(e.sender);
try {
return await run();
} finally {
activeUploadController?.abort();
activeUploadController = null;
streamGeneration++;
transferOwner = null;
}
}
let uploadProgress: { loaded: number; total: number; phase?: "downloading"; } = { loaded: 0, total: 0 };
export async function getUploadProgress(e: IpcMainInvokeEvent): Promise<{ loaded: number; total: number; phase: "uploading" | "downloading"; stallWatch: true; }> {
const { loaded, total, phase = "uploading" } = (transferOwner ?? lastOwner) === e.sender.id ? uploadProgress : { loaded: 0, total: 0 };
return { loaded, total, phase, stallWatch: true };
}
let abortLatch: UploadAbortError | null = null;
let uploadRunning = false;
function latchAbort(reason: UploadAbortError["reason"]): void {
if (!abortLatch || reason === "user") abortLatch = new UploadAbortError(reason);
if (reason === "user") stallText = null;
activeUploadController?.abort(abortLatch);
activeUploadController = null;
}
let lateCancel = false;
let pendingTarget: string | null = null;
let bodySent = false;
const isPending = (message: unknown) => {
const { request } = message as { request?: { origin?: unknown; path?: unknown; }; };
return Boolean(pendingTarget && request && `${request.origin}${request.path}` === pendingTarget);
};
subscribe("undici:request:bodySent", message => {
if (isPending(message)) bodySent = true;
});
let headersSent = false;
let sendHeadersSeen = false;
let pulls = 0;
const PREFETCH_PULLS = 2;
let remoteAddress: string | undefined;
subscribe("undici:client:sendHeaders", message => {
sendHeadersSeen = true;
if (!isPending(message)) return;
headersSent = true;
const address = (message as { socket?: { remoteAddress?: unknown; }; }).socket?.remoteAddress;
if (typeof address === "string") remoteAddress = address;
});
function addressesOf(error: unknown): string[] {
const found = new Set<string>();
const queue = [error];
for (let i = 0; i < 16 && queue.length; i++) {
const e = queue.shift() as { address?: unknown; cause?: unknown; errors?: unknown; } | null;
if (!e || typeof e !== "object") continue;
if (typeof e.address === "string") found.add(e.address);
if (e.cause) queue.push(e.cause);
if (Array.isArray(e.errors)) queue.push(...e.errors);
}
return [...found];
}
function failureOf(error: unknown): UploadFailure {
const stage = bodySent ? "response" : headersSent || pulls > PREFETCH_PULLS ? "body" : "connect";
const stageReliable = sendHeadersSeen || stage !== "connect";
const addresses = addressesOf(error);
return {
stage, code: firstErrorCode(error), stageReliable,
kind: classifyFetchError(error, stage, stageReliable, abortLatch?.reason),
...addresses.length && { addresses }
};
}
let stallText: string | null = null;
const userCancelled = () => abortLatch?.reason === "user" || lateCancel;
const stoppedMessage = () => userCancelled() ? "Upload cancelled by user" : stallText ?? "No upload progress, so the request was stopped";
const DEFAULT_STALL_MS = 60000;
const duration = (ms: number) => ms >= 120000 && ms % 60000 === 0 ? `${ms / 60000} min` : `${Math.round(ms / 1000)} s`;
let lastProgressAt = 0;
const touch = () => {
lastProgressAt = Date.now();
};
let bodyDone = false;
function watchForStall(stallMs: number): () => void {
touch();
bodyDone = false;
const timer = setInterval(() => {
if (abortLatch) return;
const answering = bodyDone || (uploadProgress.total > 0 && uploadProgress.loaded >= uploadProgress.total);
const limit = answering ? Math.max(stallMs, RESPONSE_GRACE_MS) : stallMs;
if (Date.now() - lastProgressAt <= limit) return;
stallText = answering
? `No answer for ${duration(limit)} after the ${uploadProgress.total > 0 ? "whole file" : "request"} was sent, so the request was stopped`
: `No upload progress for ${duration(limit)}, so the request was stopped`;
latchAbort("stalled");
}, Math.min(1000, Math.max(50, stallMs / 4)));
return () => clearInterval(timer);
}
function resetProgress(): void {
uploadProgress = { loaded: 0, total: 0 };
abortLatch = null;
lateCancel = false;
stallText = null;
}
export async function resetUploadProgress(e: IpcMainInvokeEvent): Promise<void> {
if (transferOwner !== null) return;
lastOwner = e.sender.id;
resetProgress();
}
let activeUploadController: AbortController | null = null;
export async function cancelUpload(e: IpcMainInvokeEvent, reason: "user" | "stalled" = "user"): Promise<void> {
if ((transferOwner ?? lastOwner) === e.sender.id) latchAbort(reason === "stalled" ? "stalled" : "user");
}
export async function cancelUploadUnlessBodySent(e: IpcMainInvokeEvent): Promise<boolean> {
if ((transferOwner ?? lastOwner) !== e.sender.id) return false;
if (uploadRunning && bodySent) {
lateCancel = true;
return true;
}
latchAbort("user");
return false;
}
interface Spool {
owner: number;
session: string;
path: string;
dev: number;
ino: number;
limit: number;
written: number;
hash: Hash;
sha256?: string;
file?: FileHandle;
writing?: Promise<unknown>;
}
const spools = new Map<string, Spool>();
const MAX_SPOOLS = 8;
const SPOOL_FREE_MARGIN = 512 * 1024 * 1024;
const ROOM_CHECK_BYTES = 256 * 1024 * 1024;
const SPOOL_NAME = /^(\d+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const STALE_SPOOL_MS = 2 * 24 * 60 * 60 * 1000;
const spoolDir = () => {
const uid = process.getuid?.();
return join(tmpdir(), uid === undefined ? "vc-bigfileupload" : `vc-bigfileupload-${uid}`);
};
async function isPrivateDir(dir: string): Promise<boolean> {
if (process.platform === "win32" || typeof process.getuid !== "function") return true;
try {
const info = await lstat(dir);
return info.isDirectory() && !info.isSymbolicLink() && info.uid === process.getuid() && (info.mode & 0o077) === 0;
} catch {
return false;
}
}
async function openSpoolFile(spool: { path: string; dev: number; ino: number; }): Promise<FileHandle> {
const file = await open(spool.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
try {
const { dev, ino } = await file.stat();
if (dev !== spool.dev || ino !== spool.ino) throw new Error("The temporary upload file was replaced");
return file;
} catch (error) {
await file.close().catch(() => { });
throw error;
}
}
const errorCodeOf = (error: unknown) => (error as { code?: unknown; } | null)?.code;
const gigabytes = (bytes: number) => bytes % 2 ** 30 === 0 ? `${bytes / 2 ** 30} GB` : `${Math.ceil(bytes / 1e8) / 10} GB`;
function isRunning(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return errorCodeOf(error) === "EPERM";
}
}
async function sweepSpools(): Promise<void> {
const dir = spoolDir();
if (!await isPrivateDir(dir)) return;
let names: string[];
try {
names = await readdir(dir);
} catch {
return;
}
const ours = new Set([...spools.values()].map(spool => spool.path));
for (const name of names) {
const match = SPOOL_NAME.exec(name);
const path = join(dir, name);
if (!match || ours.has(path)) continue;
const pid = Number(match[1]);
try {
const { mtimeMs } = await stat(path);
if (pid === process.pid || !isRunning(pid) || Date.now() - mtimeMs > STALE_SPOOL_MS) await unlink(path);
} catch { }
}
}
void sweepSpools();
process.once("exit", () => {
for (const spool of spools.values()) {
try {
rmSync(spool.path, { force: true });
} catch { }
}
});
async function hasRoomFor(dir: string, bytes: number): Promise<boolean> {
if (typeof statfs !== "function") return true;
try {
const { bavail, bsize } = await statfs(dir);
return bavail * bsize >= bytes + SPOOL_FREE_MARGIN;
} catch {
return true;
}
}
async function releaseSpool(id: string): Promise<void> {
const spool = spools.get(id);
if (!spool) return;
spools.delete(id);
await spool.writing?.catch(() => { });
await spool.file?.close().catch(() => { });
spool.file = undefined;
try {
await unlink(spool.path);
} catch { }
}
const watchedSenders = new Set<number>();
function watchSender(sender: WebContents): void {
const { id } = sender;
if (watchedSenders.has(id) || typeof sender?.once !== "function") return;
watchedSenders.add(id);
sender.once("destroyed", () => {
watchedSenders.delete(id);
if (transferOwner === id) latchAbort("user");
for (const [spoolId, spool] of spools) if (spool.owner === id) void releaseSpool(spoolId);
});
}
function ownedSpool(e: IpcMainInvokeEvent, id: unknown): Spool | undefined {
const spool = typeof id === "string" ? spools.get(id) : undefined;
return spool?.owner === e.sender.id ? spool : undefined;
}
async function createSpool(e: IpcMainInvokeEvent, expected: number | undefined, session: string, limit: number): Promise<{ id: string; spool: Spool; } | { error: string; }> {
const owner = e.sender.id;
for (const [id, spool] of spools) if (spool.owner === owner && spool.session !== session) await releaseSpool(id);
watchSender(e.sender);
if (spools.size >= MAX_SPOOLS) return { error: "Too many files are waiting to be uploaded" };
const dir = spoolDir();
try {
await mkdir(dir, { recursive: true, mode: 0o700 });
} catch (error) {
return { error: `Couldn't create BigFileUpload's temporary folder (${errorCodeOf(error) ?? "unknown error"})` };
}
if (!await isPrivateDir(dir)) return { error: "BigFileUpload's temporary folder isn't private to this user" };
if (expected !== undefined && !await hasRoomFor(dir, expected)) {
return { error: `Not enough free disk space to prepare the upload (it needs ${gigabytes(expected + SPOOL_FREE_MARGIN)} free)` };
}
const id = randomUUID();
const path = join(dir, `${process.pid}-${id}`);
try {
const file = await open(path, "wx", 0o600);
const { dev, ino } = await file.stat().catch(async error => {
await file.close().catch(() => { });
await unlink(path).catch(() => { });
throw error;
});
const spool: Spool = { owner, session, path, dev, ino, limit, written: 0, hash: createHash("sha256"), file };
spools.set(id, spool);
return { id, spool };
} catch (error) {
return { error: `Couldn't create a temporary file (${errorCodeOf(error) ?? "unknown error"})` };
}
}
async function appendToSpool(spool: Spool, bytes: Uint8Array): Promise<void> {
const { file } = spool;
if (!file) throw new Error("The temporary file is closed");
const work = (async () => {
for (let done = 0; done < bytes.length;) {
const { bytesWritten } = await file.write(bytes, done, bytes.length - done, spool.written + done);
if (bytesWritten <= 0) throw new Error("Writing the temporary file made no progress");
done += bytesWritten;
}
spool.hash.update(bytes);
spool.written += bytes.length;
})();
spool.writing = work;
try {
await work;
} finally {
if (spool.writing === work) spool.writing = undefined;
}
}
async function completeSpool(spool: Spool): Promise<string> {
await spool.file?.close();
spool.file = undefined;
return spool.sha256 = spool.hash.digest("hex");
}
function asBytes(data: ArrayBuffer | ArrayBufferView): Uint8Array {
return ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
}
export async function spoolOpen(e: IpcMainInvokeEvent, size: number, session = ""): Promise<{ success: boolean; id?: string; error?: string; }> {
if (!Number.isSafeInteger(size) || size <= 0) return { success: false, error: "Invalid file size" };
if (size > SPOOL_MAX_BYTES) return { success: false, error: `Files over ${gigabytes(SPOOL_MAX_BYTES)} can't be uploaded from the desktop app` };
const created = await createSpool(e, size, String(session), size);
return "error" in created ? { success: false, error: created.error } : { success: true, id: created.id };
}
export async function spoolWrite(e: IpcMainInvokeEvent, id: string, offset: number, chunk: ArrayBuffer | ArrayBufferView): Promise<{ success: boolean; written?: number; sha256?: string; error?: string; cancelled?: true; }> {
const spool = ownedSpool(e, id);
if (!spool) return { success: false, error: "The temporary upload file is gone" };
if (lastOwner === e.sender.id && abortLatch?.reason === "user") return { success: false, cancelled: true, error: "Upload cancelled by user" };
if (spool.sha256 !== undefined || spool.writing) return { success: false, error: "The temporary upload file isn't writable now" };
if (offset !== spool.written) return { success: false, error: "File slices arrived out of order" };
const bytes = chunk instanceof ArrayBuffer || ArrayBuffer.isView(chunk) ? asBytes(chunk) : null;
if (!bytes?.length || bytes.length > SPOOL_SLICE_BYTES * 2 || bytes.length > spool.limit - spool.written) {
return { success: false, error: "Invalid file slice" };
}
try {
await appendToSpool(spool, bytes);
const sha256 = spool.written === spool.limit ? await completeSpool(spool) : undefined;
return { success: true, written: spool.written, sha256 };
} catch (error) {
return { success: false, error: `Writing the temporary upload file failed (${errorCodeOf(error) ?? (error instanceof Error ? error.message : "unknown error")})` };
}
}
export async function spoolRead(e: IpcMainInvokeEvent, id: string, offset: number, length: number): Promise<{ success: boolean; error?: string; data?: ArrayBuffer; }> {
const spool = ownedSpool(e, id);
if (!spool?.sha256) return { success: false, error: "The temporary upload file is gone" };
if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length <= 0 || length > SPOOL_SLICE_BYTES || length > spool.written - offset) {
return { success: false, error: "Invalid read range" };
}
let file: FileHandle | undefined;
try {
file = await openSpoolFile(spool);
const data = new Uint8Array(length);
for (let done = 0; done < length;) {
const { bytesRead } = await file.read(data, done, length - done, offset + done);
if (!bytesRead) throw new Error("The temporary upload file ended early");
done += bytesRead;
}
return { success: true, data: data.buffer };
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : "Reading the temporary upload file failed" };
} finally {
await file?.close().catch(() => { });
}
}
export async function spoolRelease(e: IpcMainInvokeEvent, id: string): Promise<void> {
if (ownedSpool(e, id)) await releaseSpool(id);
}
export async function spoolHash(e: IpcMainInvokeEvent, id: string, offset: number, length: number): Promise<{ success: boolean; sha256?: string; error?: string; }> {
const spool = ownedSpool(e, id);
if (!spool?.sha256) return { success: false, error: "The temporary upload file is gone" };
if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length <= 0 || length > spool.written - offset) {
return { success: false, error: "Invalid read range" };
}
let file: FileHandle | undefined;
try {
file = await openSpoolFile(spool);
const hash = createHash("sha256");
const buffer = new Uint8Array(Math.min(SPOOL_READ_CHUNK, length));
for (let done = 0; done < length;) {
const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, length - done), offset + done);
if (!bytesRead) throw new Error("The temporary upload file ended early");
hash.update(buffer.subarray(0, bytesRead));
done += bytesRead;
}
return { success: true, sha256: hash.digest("hex") };
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : "Reading the temporary upload file failed" };
} finally {
await file?.close().catch(() => { });
}
}
function withoutHeaders(headers: Record<string, string>, names: string[]): Record<string, string> {
const drop = names.map(name => name.toLowerCase());
return Object.fromEntries(Object.entries(headers).filter(([key]) => !drop.includes(key.toLowerCase())));
}
const UPLOAD_CHUNK_SIZE = 262144;
const SPOOL_READ_CHUNK = 1024 * 1024;
interface FileRange {
path: string;
dev: number;
ino: number;
start: number;
length: number;
}
type BodyPart = Uint8Array | FileRange;
let bodyReadError: string | null = null;
let streamGeneration = 0;
function progressStream(parts: BodyPart[], signal: AbortSignal): ReadableStream<Uint8Array> {
const total = parts.reduce((sum, part) => sum + part.length, 0);
const generation = ++streamGeneration;
uploadProgress = { loaded: 0, total };
bodyDone = false;
let index = 0;
let offset = 0;
let loaded = 0;
let file: FileHandle | null = null;
let cancelled = false;
const stopped = () => cancelled || signal.aborted || generation !== streamGeneration;
const closeFile = async () => {
const handle = file;
file = null;
await handle?.close().catch(() => { });
};
return new ReadableStream({
async pull(controller) {
if (stopped()) {
await closeFile();
controller.error(new Error("The request was stopped"));
return;
}
while (index < parts.length && offset >= parts[index].length) {
await closeFile();
index++;
offset = 0;
}
if (stopped()) return controller.error(new Error("The request was stopped"));
if (index >= parts.length) {
bodyDone = true;
controller.close();
return;
}
pulls++;
const part = parts[index];
let chunk: Uint8Array;
if (part instanceof Uint8Array) {
chunk = part.subarray(offset, Math.min(offset + UPLOAD_CHUNK_SIZE, part.length));
} else {
chunk = new Uint8Array(Math.min(SPOOL_READ_CHUNK, part.length - offset));
try {
file ??= await openSpoolFile(part);
if (stopped()) throw new Error("The request was stopped");
for (let done = 0; done < chunk.length;) {
const { bytesRead } = await file.read(chunk, done, chunk.length - done, part.start + offset + done);
if (stopped()) throw new Error("The request was stopped");
if (!bytesRead) throw new Error("it ended early");
done += bytesRead;
}
} catch (error) {
await closeFile();
if (stopped()) throw error;
bodyReadError = `Reading the temporary upload file failed (${errorCodeOf(error) ?? (error instanceof Error ? error.message : "unknown error")})`;
throw new Error(bodyReadError);
}
}
controller.enqueue(chunk);
offset += chunk.length;
loaded += chunk.length;
uploadProgress = { loaded, total };
touch();
},
cancel() {
cancelled = true;
return closeFile();
}
});
}
async function streamFetch(url: string, method: string, headers: Record<string, string>, parts: BodyPart[], contentType?: string, insecureOrigin?: string, viaProxy = false): Promise<Response> {
const total = parts.reduce((sum, part) => sum + part.length, 0);
const base = withoutHeaders(headers, contentType ? ["content-length", "content-type"] : ["content-length"]);
const finalHeaders: Record<string, string> = { ...base, "Content-Length": String(total) };
if (contentType) finalHeaders["Content-Type"] = contentType;
const controller = new AbortController();
activeUploadController = controller;
const { origin } = new URL(url);
let currentUrl = url;
for (let attempt = 0; attempt < 4; attempt++) {
const target = new URL(currentUrl);
pendingTarget = target.origin + target.pathname + target.search;
bodySent = headersSent = false;
pulls = 0;
const response = await fetch(currentUrl, {
method,
headers: finalHeaders,
body: progressStream(parts, controller.signal),
duplex: "half",
redirect: "manual",
signal: controller.signal
} as RequestInit & { duplex: "half"; });
touch();
if (viaProxy && response.status >= 300 && response.status < 400) {
await response.body?.cancel().catch(() => { });
throw new RedirectRefusal(`The CORS proxy answered with a redirect (${response.status}), which isn't followed`);
}
const location = response.headers.get("location");
const redirected = (response.status === 307 || response.status === 308) && location;
if (redirected || [301, 302, 303].includes(response.status)) await response.body?.cancel().catch(() => { });
if (redirected) {
if (abortLatch || lateCancel) throw new Error(stoppedMessage());
const next = new URL(location, currentUrl);
if (next.origin !== origin || await uploadUrlProblem(next.toString(), insecureOrigin)) {
throw new RedirectRefusal(`Upload endpoint redirected to a different or insecure origin (${next.origin}). Update the configured URL to the final address`);
}
currentUrl = next.toString();
continue;
}
if ([301, 302, 303].includes(response.status)) {
const shown = location && URL.canParse(location, currentUrl) ? new URL(location, currentUrl) : null;
throw new RedirectRefusal(`Upload endpoint redirected (${response.status}${shown ? ` to ${shown.origin}${shown.pathname}` : ""}). Update the configured URL to the final address`);
}
return response;
}
throw new RedirectRefusal("Too many redirects from upload endpoint");
}
class RedirectRefusal extends Error { }
const MAX_RESPONSE_BYTES = 1024 * 1024;
const MAX_RESPONSE_HEADERS = 200;
async function readResponseText(response: Response, { max = MAX_RESPONSE_BYTES, progress = touch, tolerateErrors = false } = {}): Promise<{ text: string; truncated: boolean; }> {
const reader = response.body?.getReader();
if (!reader) return { text: "", truncated: false };
const decoder = new TextDecoder();
let text = "";
let received = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) return { text: text + decoder.decode(), truncated: false };
progress();
if (!value?.length) continue;
const room = max - received;
if (value.length > room) {
text += decoder.decode(value.subarray(0, room));
return { text, truncated: true };
}
received += value.length;
text += decoder.decode(value, { stream: true });
}
} catch (error) {
if (!tolerateErrors) throw error;
return { text: text + decoder.decode(), truncated: true };
} finally {
await reader.cancel().catch(() => { });
reader.releaseLock();
}
}
function multipartFetch(url: string, fields: Record<string, string>, fileFieldName: string, file: BodyPart, filename: string, headers: Record<string, string>, fileContentType: string | undefined, method: string, insecureOrigin?: string, viaProxy = false): Promise<Response> {
const boundary = `----BigFileUpload${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`;
const encoder = new TextEncoder();
const escapeName = (value: string) => value.replace(/["\r\n]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
const safeName = escapeName(filename);
const safeContentType = (fileContentType || "application/octet-stream").replace(/[\r\n]/g, "");
let head = "";
for (const [name, value] of Object.entries(fields)) {
head += `--${boundary}\r\nContent-Disposition: form-data; name="${escapeName(name)}"\r\n\r\n${value}\r\n`;
}
head += `--${boundary}\r\nContent-Disposition: form-data; name="${escapeName(fileFieldName)}"; filename="${safeName}"\r\nContent-Type: ${safeContentType}\r\n\r\n`;
const parts = [encoder.encode(head), file, encoder.encode(`\r\n--${boundary}--\r\n`)];
return streamFetch(url, method, headers, parts, `multipart/form-data; boundary=${boundary}`, insecureOrigin, viaProxy);
}
const isValidHttpsUrl = (url: string) => URL.canParse(url) && new URL(url).protocol === "https:";
function isPublicSourceUrl(url: string): boolean {
if (!isValidHttpsUrl(url)) return false;
const host = new URL(url).hostname.toLowerCase();
if (host.startsWith("[") || isIP(host)) return isPublicSourceAddress(host);
return httpHostKind(host) === "public";
}
const MAX_SOURCE_REDIRECTS = 5;
const UPLOAD_URL_RULE = "Upload URL must be https (or http on a local/private network)";
const DNS_TIMEOUT_MS = 10000;
async function resolveAll(host: string): Promise<string[]> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(Object.assign(new Error(`DNS lookup of ${host} timed out`), { code: "EAI_AGAIN" })), DNS_TIMEOUT_MS);
});
try {
const answers = await Promise.race([lookup(host, { all: true }), timeout]);
return answers.map(answer => answer.address);
} finally {
clearTimeout(timer);
}
}
type UrlProblem = { error: string; lookupError?: undefined; } | { error?: undefined; lookupError: unknown; };
async function uploadUrlProblem(url: string, insecureOrigin?: unknown): Promise<UrlProblem | null> {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
return { error: UPLOAD_URL_RULE };
}
if (parsed.protocol === "https:") return null;
if (parsed.protocol !== "http:") return { error: UPLOAD_URL_RULE };
if (typeof insecureOrigin === "string" && parsed.origin === insecureOrigin) return null;
const kind = httpHostKind(parsed.hostname);
if (kind === "private") return null;
if (kind === "public") return { error: httpLanOnlyText(parsed.host, false) };
let addresses: string[];
try {
addresses = await resolveAll(parsed.hostname);
} catch (error) {
return { lookupError: error };
}
return addresses.length && addresses.every(isPrivateAddress) ? null : { error: httpLanOnlyText(parsed.hostname, true) };
}
function lookupFailure(error: unknown): CustomUploadResponse {
const described = describeNetworkError(error, "connect");
if (described.code === "local") return { success: false, ...described };
return { success: false, ...described, failure: { stage: "connect", code: firstErrorCode(error), stageReliable: true } };
}
export async function checkHttpHost(_: IpcMainInvokeEvent, url: string): Promise<{ lan: boolean | null; }> {
if (typeof url !== "string") return { lan: false };
const problem = await uploadUrlProblem(url);
return { lan: !problem ? true : problem.lookupError !== undefined ? null : false };
}
export interface CustomUploadRequestOptions {
url: string;
method?: string;
headers?: Record<string, string>;
bodyType: "multipart" | "binary" | "json";
fields?: Record<string, string>;
fileFieldName?: string;
filename?: string;
fileContentType?: string;
stallTimeoutMs?: number;
insecureOrigin?: string;
viaProxy?: boolean;
resolveAddresses?: boolean;
}
export interface CustomUploadResponse {
success: boolean;
busy?: true;
status?: number;
statusText?: string;
contentType?: string;
responseText?: string;
responseTruncated?: true;
retryAfter?: string;
etag?: string;
headers?: [string, string][];
url?: string;
error?: string;
code?: NativeErrorCode;
cancelled?: true;
failure?: UploadFailure;
block?: true;
remoteAddress?: string;
}
const isSpoolSource = (body: unknown): body is SpoolSource =>
typeof body === "object" && body !== null && (body as SpoolSource).kind === "spool";
function requestBody(e: IpcMainInvokeEvent, body: ArrayBuffer | ArrayBufferView | SpoolSource | null | undefined): BodyPart | string {
if (!isSpoolSource(body)) return body ? asBytes(body) : new Uint8Array(0);
const spool = ownedSpool(e, body.id);
if (!spool?.sha256) return "The file prepared for upload is no longer available";
const start = body.offset ?? 0;
const length = body.length ?? spool.written - start;
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(length) || start < 0 || length < 0 || length > spool.written - start) {
return "Invalid range of the prepared file";
}
return { path: spool.path, dev: spool.dev, ino: spool.ino, start, length };
}
export async function customUploadRequest(...args: Parameters<typeof performCustomUploadRequest>): Promise<CustomUploadResponse> {
return withNativeTransfer(args[0], () => performCustomUploadRequest(...args));
}
async function performCustomUploadRequest(
e: IpcMainInvokeEvent,
options: CustomUploadRequestOptions,
body: ArrayBuffer | SpoolSource
): Promise<CustomUploadResponse> {
const {
url,
method = "POST",
headers = {},
bodyType,
fields = {},
fileFieldName = "file",
filename = "upload.bin",
fileContentType,
stallTimeoutMs
} = options;
const insecureOrigin = typeof options.insecureOrigin === "string" ? options.insecureOrigin : undefined;
const viaProxy = options.viaProxy === true;
if (unapproved(url)) return { success: false, code: "approval", error: APPROVAL_TEXT };
const problem = await uploadUrlProblem(url, insecureOrigin);
if (problem) return problem.lookupError !== undefined ? lookupFailure(problem.lookupError) : { success: false, code: "local", error: problem.error };
if (abortLatch || lateCancel) {
return userCancelled() ? { success: false, cancelled: true, code: "cancelled", error: stoppedMessage() } : { success: false, code: "stalled", error: stoppedMessage() };
}
const file = bodyType === "json" ? new Uint8Array(0) : requestBody(e, body);
if (typeof file === "string") return { success: false, code: "local", error: file };
const hasHeader = (name: string) => Object.keys(headers).some(header => header.toLowerCase() === name);
uploadRunning = true;
bodyReadError = null;
remoteAddress = undefined;
const stallMs = typeof stallTimeoutMs === "number" && Number.isFinite(stallTimeoutMs) && stallTimeoutMs > 0 ? Math.max(1000, stallTimeoutMs) : DEFAULT_STALL_MS;
const stopWatch = watchForStall(stallMs);
try {
let response: Response;
if (bodyType === "multipart") {
response = await multipartFetch(url, fields, fileFieldName, file, filename, headers, fileContentType, method, insecureOrigin, viaProxy);
} else if (bodyType === "binary") {
const binaryHeaders = { ...headers };
if (fileContentType && !hasHeader("content-type")) {
binaryHeaders["Content-Type"] = fileContentType;
}
response = await streamFetch(url, method, binaryHeaders, [file], undefined, insecureOrigin, viaProxy);
} else if (bodyType === "json") {
const payload = new TextEncoder().encode(JSON.stringify(fields));
const jsonHeaders = { ...headers };
if (!hasHeader("content-type")) {
jsonHeaders["Content-Type"] = "application/json";
}
response = await streamFetch(url, method, jsonHeaders, [payload], undefined, insecureOrigin, viaProxy);
} else {
return { success: false, code: "local", error: `Unsupported body type: ${bodyType}` };
}
const { text, truncated } = await readResponseText(response);
const address = remoteAddress as string | undefined;
return {
success: true,
status: response.status,
statusText: response.statusText,
contentType: response.headers.get("content-type") || "",
headers: [...response.headers].slice(0, MAX_RESPONSE_HEADERS),
url: response.url || undefined,
...truncated && { responseTruncated: true as const },
...classifyHttpBlock(response.status, name => response.headers.get(name), text.slice(0, 8192)) && { block: true as const },
...address && { remoteAddress: address },
responseText: text
};
} catch (e) {
if (userCancelled()) return { success: false, cancelled: true, code: "cancelled", error: "Upload cancelled by user" };
if (abortLatch) return { success: false, code: "stalled", error: stoppedMessage(), failure: failureOf(e) };
if (e instanceof RedirectRefusal) return { success: false, code: "http", error: e.message };
if (bodyReadError) return { success: false, code: "local", error: bodyReadError };
const failure = failureOf(e);
const described = describeNetworkError(e, failure.stage);
if (options.resolveAddresses === true && !failure.addresses && PROXY_RETRY_KINDS.has(failure.kind!) && !isDnsCode(failure.code)) {
const { hostname } = new URL(url);
if (!hostname.startsWith("[") && !isIP(hostname)) {
const addresses = await resolveAll(hostname).catch(() => []);
if (addresses.length) failure.addresses = addresses;
}
}
if (described.code === "local" && e instanceof TypeError && /invalid header/i.test(e.message)) {
return { success: false, code: "local", error: "A request header is invalid (check the host's token or ShareX headers)" };
}
return described.code === "local" ? { success: false, ...described } : { success: false, ...described, failure };
} finally {
stopWatch();
uploadRunning = false;
pendingTarget = null;
bodySent = headersSent = false;
remoteAddress = undefined;
if (isSpoolSource(body) && body.offset !== undefined) uploadProgress = { loaded: 0, total: 0 };
}
}
async function timed<T>(ms: number, fail: (error: string) => T, run: (signal: AbortSignal) => Promise<T>): Promise<T> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
return await run(controller.signal);
} catch (e) {
return fail(controller.signal.aborted ? `No answer within ${ms / 1000} s` : describeNetworkError(e).error);
} finally {
clearTimeout(timer);
}
}
const CLEANUP_TIMEOUT_MS = 15000;
export interface CleanupRequestOptions {
url: string;
method: "DELETE";
headers?: Record<string, string>;
insecureOrigin?: string;
}
type CleanupResult = { success: boolean; status?: number; error?: string; code?: "approval"; };
export async function cleanupRequest(_: IpcMainInvokeEvent, options: CleanupRequestOptions): Promise<CleanupResult> {
const { url, method, headers = {}, insecureOrigin } = options ?? {};
if (typeof url !== "string") return { success: false, error: UPLOAD_URL_RULE };
if (method !== "DELETE") return { success: false, error: "Only DELETE is supported" };
if (unapproved(url)) return { success: false, code: "approval", error: APPROVAL_TEXT };
const problem = await uploadUrlProblem(url, insecureOrigin);
if (problem) return { success: false, error: problem.error ?? describeNetworkError(problem.lookupError).error };
return timed<CleanupResult>(CLEANUP_TIMEOUT_MS, error => ({ success: false, error }), async signal => {
const response = await fetch(url, { method, headers, redirect: "manual", signal });
await response.body?.cancel().catch(() => { });
return { success: true, status: response.status };
});
}
const MAX_DELETE_ANSWER = 16 * 1024;
export interface DeleteRequestOptions {
url: string;
method: "GET" | "POST" | "DELETE";
headers?: Record<string, string>;
form?: Record<string, string>;
publicOnly?: boolean;