-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
795 lines (636 loc) · 26.4 KB
/
api.js
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
/**
* API library for Distore
*/
const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const nanoid = require('nanoid').nanoid;
const crypto = require('crypto');
const deta = require('deta');
const axios = require('axios').default;
const FormData = require('form-data');
const chalk = require('chalk');
const {performance} = require('perf_hooks');
const {formatSize, fetchAll} = require('./util');
const stream = require('node:stream');
// Max chunk size in bytes
const MAX_CHUNK_SIZE = 24 * 1024 * 1024; // 24 MiB
// Max byte range size for fetching
const MAX_BYTE_RANGE = 128 * 1024 * 1024; // 128 MiB
// No. of parallel chunk uploads
let MAX_PARALLEL_CHUNK_UPLOAD = 3;
// No. of parallel chunk downloads
let MAX_PARALLEL_CHUNK_DOWNLOAD = 3;
class API {
// Console API
console = {
error: (message) => {
console.error(chalk.redBright("error:"), message);
},
warn: (message) => {
console.warn(chalk.yellowBright("warning:"), message);
},
info: (message) => {
console.log(chalk.gray("info:"), message);
},
success: (message) => {
console.log(chalk.greenBright("success:"), message);
}
};
// File manager
fileManager = {
/**
* Downloads a file to disk.
* @param {string} id - File ID
* @param {string} savePath - Full path of destination file
*/
downloadFile: async (id, savePath, parallel, updateFn) => {
if(typeof updateFn == "undefined") updateFn = () => {};
// Override parallel chunks to download
MAX_PARALLEL_CHUNK_DOWNLOAD = parallel;
// Check if any file exists at this location
let stat, alreadyExists;
try {
stat = await fs.promises.stat(savePath);
alreadyExists = true;
}catch(e) {
alreadyExists = false;
}
// Throw if file already exists
if(alreadyExists === true) {
this.console.error(`A file or folder already exists at \`${savePath}\`!`);
process.exit(1);
}
let file = await this.db.getFile(id);
let chunksMeta = await this.db.getChunks(id);
console.log(chalk.blueBright("download"), `${file.name} (${formatSize(file.size)}, ${chunksMeta.length} chunks)`, `→`, chalk.yellowBright(savePath), chalk.gray(`[${id}]`));
// Emit `start` event
updateFn('start', {
chunks: chunksMeta.length,
file: file
});
let jobs = [];
let jobsCompleted = [];
let jobIndex = 0;
// Downloads a chunk at an index
const downloadChunk = async (i) => {
let chunkMeta = chunksMeta[i];
let response = await axios.get(this.config.data.webhook + `/messages/` + chunkMeta.message_id);
let dataUrl = response.data.attachments[0].url;
// Emit `chunkdownload` event
updateFn('chunkdownload', {
meta: chunkMeta,
url: dataUrl,
index: i
});
// Record download start time
const startTime = performance.now();
// Download the chunk data
let chunkResponse = await axios.get(dataUrl, {responseType: 'arraybuffer'});
const elapsed = performance.now() - startTime;
// Measure average download speed (bytes per second)
const avgSpeed = chunkResponse.data.length / (elapsed / 1000);
// Decrypt chunk data
let deciphertext = this.crypto.decrypt(this.config.data.encryption_key, chunkResponse.data);
jobsCompleted++;
// Emit `chunkdownloaded` event
updateFn('chunkdownloaded', {
meta: chunkMeta,
url: dataUrl,
avgSpeed: avgSpeed,
size: chunkResponse.data.length,
time: elapsed
});
return {
index: i,
data: deciphertext
};
};
const queue = (resolve, reject) => {
if(jobsCompleted === chunksMeta.length) return resolve();
// Queue download jobs
for(let i=0; i<MAX_PARALLEL_CHUNK_DOWNLOAD; i++) {
if(jobIndex === chunksMeta.length) break;
jobs.push(downloadChunk(jobIndex));
jobIndex++;
}
Promise.all(jobs).then(async data => {
// Sort in ascending order
data.sort((a, b) => a.index - b.index);
// Append data to save file
for(let i in data) {
await fs.appendFile(savePath, data[i].data);
// Emit `chunksaved` event
updateFn('chunksaved', {
bytes: data[i].data.length
});
}
// Reset jobs
jobs = [];
// Queue next batch
queue(resolve, reject);
});
};
// Wait for all jobs to complete
await new Promise((resolve, reject) => {
queue(resolve, reject);
});
// Emit `end` event
updateFn('end', {
path: savePath,
file: file,
chunks: chunksMeta.length
});
},
/**
* Uploads a chunk to the file system.
* @param {string} id - File ID the chunk belongs to
* @param {string} filepath - Full path to the file on disk being uploaded
* @param {string} index - Index of chunk to upload
*/
uploadChunk: async (id, filepath, index) => {
let start = index * MAX_CHUNK_SIZE;
let end = start + MAX_CHUNK_SIZE - 1;
// Read entire range of file
let chunks = [];
for await (let chunk of fs.createReadStream(filepath, { start, end, autoClose: true })) {
chunks.push(chunk);
}
chunks = Buffer.concat(chunks);
// Make sure range end is correct
if(chunks.length < MAX_CHUNK_SIZE) end = start + chunks.length - 1;
// Encrypt chunk
let ciphertext = this.crypto.encrypt(this.config.data.encryption_key, chunks);
// Create new FormData and append data
const form = new FormData();
form.append(id + `.chunk` + index, ciphertext, {
filename: id + `.chunk` + index
});
form.append('payload_json', JSON.stringify({
content: JSON.stringify({
size: chunks.length
}),
username: 'Distore'
}));
// Measure download duration
const startTime = performance.now();
// Upload the chunk to Discord
let response = await axios.post(this.config.data.webhook + `?wait=true`, form);
let elapsed = performance.now() - startTime;
// Measure average download speed (bytes per second)
let avgSpeed = chunks.length / (elapsed / 1000);
// Register chunk to database
await this.db.addChunk(id, {
index: index,
range: {
start,
end
},
message_id: response.data.id
});
// Return upload stats
return {
time: elapsed,
avgSpeed: avgSpeed,
size: chunks.length
};
},
/**
* Uploads a file to the file system.
* @param {string} filepath - Full path to file on disk
* @param {string} dbpath - Full path to file on database
*/
uploadFile: async (filepath, dbpath, parallel, updateFn) => {
if(typeof updateFn == "undefined") updateFn = () => {};
// Override parallel chunks to upload
MAX_PARALLEL_CHUNK_UPLOAD = parallel;
let stat;
try {
stat = await fs.promises.stat(filepath);
}catch(e) {
if(e.code === 'ENOENT') this.console.error(`No such file or directory`);
else this.console.error(`Failed to stat file \`${filepath}\``);
process.exit(1);
}
const chunks = Math.ceil(stat.size / MAX_CHUNK_SIZE);
// Emit `registerfile` event
updateFn('registerfile', {
path: filepath,
destination: dbpath
});
// Register directories in database
await this.db.registerPath(path.dirname(dbpath));
// Register file in database
const fileResult = await this.db.addFile(path.basename(dbpath), path.dirname(dbpath), stat.size);
console.log(chalk.blueBright("upload"), path.basename(filepath), `(${formatSize(stat.size)}, ${chunks} chunks)`, `→`, chalk.yellowBright(dbpath), chalk.gray(`[${fileResult.key}]`));
// Emit `start` event
updateFn('start', {
path: filepath,
destination: dbpath,
file: fileResult,
chunks: chunks
});
let jobs = 0;
let jobIndex = 0;
let jobsCompleted = 0;
const queue = (resolve, reject) => {
let free = MAX_PARALLEL_CHUNK_UPLOAD - jobs;
// If jobs completed = no. of chunks, all chunks have been uploaded
if(jobsCompleted === chunks) return resolve(true);
for(let i=0; i<free; i++) {
// Don't queue more jobs than chunks
if(jobIndex === chunks) break;
// Emit `chunkupload` event
updateFn('chunkupload', {
index: jobIndex
});
// Upload chunk
jobs++;
this.fileManager.uploadChunk(fileResult.key, filepath, jobIndex).then(stats => {
jobs--;
jobsCompleted++;
// Emit `chunkuploaded` event
updateFn('chunkuploaded', stats);
queue(resolve, reject);
});
// Bump job index
jobIndex++;
}
};
// Queue chunks
await new Promise((resolve, reject) => {
queue(resolve, reject);
});
// Emit `end` event
updateFn('end', {
path: filepath,
destination: dbpath,
file: fileResult,
chunks: chunks
});
return fileResult;
},
/**
* Returns given byte range from File of given ID as a stream.
* @param {string} id - File ID
* @param {number} start - Starting byte offset
* @param {number} end - Ending byte offset
*/
getBytes: async (id, start, end) => {
let readable = new stream.Readable();
readable._read = () => {};
// Fetch list of chunks for range
const chunksMeta = await this.db.getChunksFromByteRange(id, start, end);
// Validate byte range
if(start < 0 || chunksMeta.length<1 || end > chunksMeta[chunksMeta.length - 1].range.end) throw new Error('INVALID_RANGE');
const downloadChunk = async (i) => {
let chunkMeta = chunksMeta[i];
let response = await axios.get(this.config.data.webhook + `/messages/` + chunkMeta.message_id);
let dataUrl = response.data.attachments[0].url;
// Download the chunk data
let chunkResponse = await axios.get(dataUrl, {responseType: 'arraybuffer'});
// Decrypt chunk data
let deciphertext = this.crypto.decrypt(this.config.data.encryption_key, chunkResponse.data);
return {
index: i,
data: deciphertext
};
};
let startFetch = async () => {
for(let i=0; i<chunksMeta.length; i++) {
const data = await downloadChunk(i);
const chunk = chunksMeta[i];
if(start > chunk.range.start && end < chunk.range.end) {
readable.push(data.data.subarray(start - chunk.range.start, end - chunk.range.start));
}
else if(start > chunk.range.start && end >= chunk.range.end) {
readable.push(data.data.subarray(start - chunk.range.start));
}
else if(chunk.range.start >= start && chunk.range.end <= end) {
readable.push(data.data);
}
else if(chunk.range.start >= start && chunk.range.end > end) {
readable.push(data.data.subarray(0, end - chunk.range.start));
}
}
readable.push(null);
};
startFetch();
return readable;
}
};
// Database related functions
db = {
// Initialized instance of Deta
deta: null,
/**
* Returns a authenticated Deta instance
* @param {string} key - Deta Collection API Key
*/
init: () => {
this.db.deta = deta.Deta(this.config.data.deta_api_key);
return this.db.deta;
},
/**
* Searches for a file.
* @param {string} name - Name of the file
*/
searchFile: async (name) => {
const files = this.db.deta.Base('files');
const result = await files.fetch({
"search?contains": name.toLowerCase()
});
return result.items;
},
/**
* Fetches a list of files for a given path in virtual filesystem.
* @param {string} dirpath - Path to directory in virtual filesystem
*/
listDirectory: async (dirpath) => {
const files = this.db.deta.Base('files');
const directories = this.db.deta.Base('directories');
// Remove trailing slash
if(dirpath.endsWith('/') && dirpath != '/') dirpath = dirpath.substring(0, dirpath.length - 1);
const listFiles = await fetchAll(files, {
path: dirpath
});
const listDirs = await fetchAll(directories, {
parent: dirpath
});
return {
files: listFiles,
dirs: listDirs
};
},
/**
* Recursively creates directories in the database to construct the given full path.
* @param {string} fullpath - Full path to most nested directory
*/
registerPath: async (fullpath) => {
const directories = this.db.deta.Base('directories');
if(fullpath === '/') return;
else {
// Check if path already exists
if(await directories.get(fullpath) != null) return;
fullpath = fullpath.substring(1);
}
let dirs = fullpath.split('/');
let current = ``;
let parent = `/`;
for(let i=0; i<dirs.length; i++) {
current += `/` + dirs[i];
await directories.put({
parent: parent
}, current);
parent += (parent === `/` ? dirs[i] : `/` + dirs[i]);
}
},
/**
* Registers a file in the file system
* @param {string} name - Name of the file
* @param {string} dirpath - Full path upto file's parent directory
* @param {number} size - Size of the file in bytes
*/
addFile: async (name, dirpath, size) => {
const files = this.db.deta.Base('files');
const id = nanoid();
return await files.put({
name: name,
path: dirpath,
size: size,
createdAt: Math.floor(Date.now() / 1000),
search: name.toLowerCase() // Required for searching
}, id);
},
/**
* Registers a file chunk to the database
* @param {string} id - ID of file in database
* @param {number} data.index - Index of chunk among all chunks
* @param {number} data.range.start - Starting byte offset of chunk
* @param {number} data.range.end - Ending byte offset of chunk
* @param {string} data.message_id - Discord Message ID
*/
addChunk: async (id, data) => {
const chunks = this.db.deta.Base('file_chunks');
return await chunks.put({
file: id,
index: data.index,
message_id: data.message_id,
range: {
start: data.range.start,
end: data.range.end
}
});
},
/**
* Fetches file metadata for a given ID
* @param {string} id - File ID
*/
getFile: async (id) => {
const files = this.db.deta.Base('files');
return files.get(id);
},
/**
* Fetches file metadata for a given path
* @param {string} filepath - File Path on virtual filesystem
*/
getFileFromPath: async (filepath) => {
const files = this.db.deta.Base('files');
const result = await files.fetch({
name: path.basename(filepath),
path: path.dirname(filepath)
}, {limit: 1});
if(result.items.length < 1) return null;
else return result.items[0];
},
/**
* Fetches the list of chunks for a given File ID
* @param {string} id - File ID
*/
getChunks: async (id) => {
const chunks = this.db.deta.Base('file_chunks');
let chunksList = await fetchAll(chunks, {
file: id
});
// Sort chunks by index in ascending order
chunksList.sort((a, b) => a.index - b.index);
return chunksList;
},
/**
* Fetches the list of chunks for a given File ID, at given byte range
* @param {string} id - File ID
* @param {number} start - Starting byte offset
* @param {number} end - Ending byte offset
*/
getChunksFromByteRange: async (id, start, end) => {
const chunks = this.db.deta.Base('file_chunks');
let chunksList = await fetchAll(chunks, [
// Chunks with start >= range start && end <= range end
{
"file": id,
"range.start?gte": start,
"range.end?lte": end
},
// Chunks with start <= range end && end >= range end
{
"file": id,
"range.start?lte": end,
"range.end?gte": end
}
]);
// Sort chunks by index in ascending order
chunksList.sort((a, b) => a.index - b.index);
return chunksList;
},
/**
* Deletes a given File ID and all of it's chunks
* This also deletes the Discord messages for each chunk
* @param {string} id - File ID
*/
deleteFile: async (id, updateFn) => {
const files = this.db.deta.Base('files');
const chunks = this.db.deta.Base('file_chunks');
// Emit `start` event
updateFn(`start`, {});
// Get list of chunks for file
const chunksList = await this.db.getChunks(id);
if(chunksList.length < 1) throw new Error(`Invalid File: \`${id}\` has no chunks in database.`);
// Emit `fetchchunks` event
updateFn(`fetchchunks`, {chunksList});
// Delete the file entry
await files.delete(id);
// Delete file chunks
for(let i in chunksList) {
// Emit `chunkdelete` event
updateFn(`chunkdelete`, {
id: i,
key: chunksList[i].key
});
await chunks.delete(chunksList[i].key);
// Delete Discord message for this chunk
const response = await axios.delete(this.config.data.webhook + `/messages/` + chunksList[i].message_id);
if(response.status != 204) throw new Error(`Unexpected Response from Discord: Deleting message ${chunksList[i].message_id} returned ${response.statusText}.`);
// Emit `chunkdeleted` event
updateFn(`chunkdeleted`, {
id: i
});
}
// Emit `end` event
updateFn(`end`, {});
}
};
// Configuration related functions
config = {
/**
* Cached configuration
*/
data: null,
/**
* Path to directory containing the config file
*/
dir: path.join(os.homedir(), ".distore"),
/**
* Full path to config file
*/
path: path.join(os.homedir(), ".distore", "config.json"),
/**
* Initializes the configuration file and loads it in memory
*/
init: async () => {
// Ensure config directory exists
await fs.ensureDir(this.config.dir);
// Check if config JSON file exists
let exists;
try {
await fs.promises.access(this.config.path, fs.constants.F_OK);
exists = true;
}catch(e) {
exists = false;
}
if(exists === true) {
const contents = JSON.parse((await fs.readFile(this.config.path)).toString());
this.config.data = contents;
return contents;
}else {
// Initialize new configuration with encryption key
const nullConfig = {
webhook: null,
deta_api_key: null,
encryption_key: this.crypto.generateKey()
};
// Make config JSON file
await fs.writeFile(this.config.path, JSON.stringify(nullConfig));
this.console.info(`Initialized configuration file at \`${this.config.path}\` with new encryption key.`);
this.config.data = nullConfig;
return nullConfig;
}
},
/**
* Sets the contents of the config file
* @param {string} config.webhook - Discord Webhook URL
* @param {string} config.deta_api_key - Deta Collection API key
* @param {string} config.encryption_key - Encryption key for E2EE
*/
setConfig: async (config) => {
await fs.writeFile(this.config.path, JSON.stringify(config));
this.config.data = config;
}
};
//Cryptography related functions
crypto = {
/**
* Generates a 256-bit safe, random key for AES-GCM-256 cryptography
*/
generateKey: () => {
return nanoid(32);
},
/**
* Generates a 96-bit safe, random IV for AES-GCM-256 cryptography
*/
generateIV: () => {
return nanoid(12);
},
/**
* Encrypts a given buffer using AES-GCM-256 algorithm
* Generated ciphertext contains 12-byte IV, 16-byte auth tag inserted before payload
* @param {string} key - Encryption key
* @param {Buffer} data - Data to encrypt
*/
encrypt: (key, data) => {
// Generate IV
const iv = Buffer.from(this.crypto.generateIV(), 'utf8');
// Create AES 256 GCM Mode cipher
let cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
// Encrypt the given buffer
let encrypted = Buffer.concat([cipher.update(data, 'utf8'), cipher.final()]);
// Extract the auth tag
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, encrypted]);
},
/**
* Decrypts an encrypted payload
* @param {string} key - Encryption key
* @param {Buffer} data - Encrypted payload to decrypt
*/
decrypt: (key, data) => {
let bData = Buffer.from(data, 'base64');
// Extract data from ciphertext
const iv = bData.subarray(0, 12);
const tag = bData.subarray(12, 28);
const text = bData.subarray(28);
// Decipher with AES 256 GCM Mode
let decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
// Decrypt the given payload
let decrypted;
try {
decrypted = Buffer.concat([decipher.update(text), decipher.final()]);
}catch(e) {
this.console.error("Failed to decrypt data!");
process.exit(1);
}
return decrypted;
}
};
};
module.exports = new API();