-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDarkMessenger.js
executable file
·1558 lines (1315 loc) · 51.4 KB
/
DarkMessenger.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
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
#!/usr/bin/env node
import fs from "fs";
import { spawn, exec } from "child_process";
import parseCLI from "simpleargumentsparser";
import chalk from "chalk";
import readline from "readline";
import {
ECIES_priv_key, ECIES_pub_key, ECIES_encrypt, ECIES_decrypt,
RSA_priv_key, RSA_pub_key, RSA_encrypt, RSA_decrypt,
KYBER_priv_key, KYBER_pub_key, KYBER_encrypt, KYBER_decrypt
} from "stringmanolo-erk";
// globals
let v = false; // verbose
let d = false; // debug
let config; // config
let useErk = false;
(async () => {
const cli = await parseCLI();
if (cli.noArgs || cli.s.h || cli.c.help)
exit(`Usage:
${chalk.bold.yellow('start')} ${chalk.white('Wake up all services')}
${chalk.bold.yellow('stop')} ${chalk.white('Shutdown all services')}
${chalk.bold.yellow('add')} ${chalk.italic('[alias] [domain.onion]')} ${chalk.white('Add an address to your Address Book')}
${chalk.bold.yellow('addme')} ${chalk.italic('[domain.onion]')} ${chalk.white('Tell remote server to add you')}
${chalk.bold.yellow('contacts')} ${chalk.italic('<alias>')} ${chalk.white('Show a contact address or all contacts')}
${chalk.bold.yellow('send')} ${chalk.italic('[alias] [message]')} ${chalk.white('Send a message')}
${chalk.bold.yellow('show')} ${chalk.italic('<alias>')} ${chalk.white('Show messages from someone')}
${chalk.bold.yellow('delete')} ${chalk.italic('[id]')} ${chalk.white('Delete messages from someone')}
${chalk.bold.yellow('-v --verbose')}
${chalk.bold.yellow('-d --debug')}
`);
if (cli.s.v || cli.c.verbose) v = true;
if (cli.c.start || cli.o[0].includes("start")) {
await start(cli);
} else if (cli.c.stop || cli.o[0].includes("stop")) {
await stop(cli);
} else {
if (cli.o[0].includes("add")) {
await add(cli);
process.exit(0);
} else if (cli.o[0].includes("addme")) {
await addme(cli);
process.exit(0);
} else if (cli.o[0].includes("contacts")) {
await contacts(cli);
process.exit(0);
} else if (cli.o[0].includes("send")) {
await send(cli);
process.exit(0);
} else if (cli.o[0].includes("show")) {
await show(cli);
process.exit(0);
} else if (cli.o[0].includes("delete")) {
await del(cli);
process.exit(0);
} else if (cli.o[0].includes("wcdyu")) { // Internal Method: What Crypto Do You Use (query server for available crypto)
await wcdyu(cli);
process.exit(0);
} else if (cli.o[0].includes("erk")) { // Internal Method: Get server ERK public key
await getPublicKey(cli);
process.exit(0);
} else {
// TODO: not known commands
process.exit(0);
}
}
})();
const exit = msg => {
console.log(msg);
process.exit(0);
};
const verbose = msg => {
if (v || config?.verbose) {
console.log(`${chalk.bold.green("[VERBOSE]")} ${msg}`);
}
};
const debug = msg => {
if (d || config?.debug) {
if (config?.debug_with_time) {
const now = new Date();
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const milliseconds = now.getMilliseconds().toString().padStart(3, '0');
const timestamp = `${hours}:${minutes}:${seconds}.${milliseconds}`;
console.log(`${chalk.bold.blue("[DEBUG-" + timestamp + "]")} ${msg}`);
} else {
console.log(`${chalk.bold.blue("[DEBUG]")} ${msg}`);
}
}
};
const error = msg => {
console.log(`${chalk.bold.red("[ERROR]")} ${msg}`);
};
const sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const ask = question => {
return new Promise(resolve => {
rl.question(question, answer => {
resolve(answer);
});
});
};
const generateErkKeys = (config) => {
if (!fs.existsSync("./ERK_keys")) {
debug(`Making dir ./ERK_keys/ ... `);
fs.mkdirSync("./ERK_keys", { recursive: true });
}
const eciesKeys = [ ECIES_pub_key(), ECIES_priv_key() ];
const rsaKeys = [ RSA_pub_key(), RSA_priv_key() ];
const kyberKeys = [ KYBER_pub_key(), KYBER_priv_key() ];
if (!fs.existsSync("./ERK_keys/ECIES_private_key")) {
fs.writeFileSync("./ERK_keys/ECIES_public_key", eciesKeys[0] );
fs.writeFileSync("./ERK_keys/ECIES_private_key", eciesKeys[1] );
}
if (!fs.existsSync("./ERK_keys/RSA_private_key")) {
fs.writeFileSync("./ERK_keys/RSA_public_key", rsaKeys[0] );
fs.writeFileSync("./ERK_keys/RSA_private_key", rsaKeys[1] );
}
if (!fs.existsSync("./ERK_keys/KYBER_private_key")) {
fs.writeFileSync("./ERK_keys/KYBER_public_key", kyberKeys[0] );
fs.writeFileSync("./ERK_keys/KYBER_private_key", kyberKeys[1] );
}
if (!fs.existsSync("./ERK_keys/ERK_private_key")) {
fs.writeFileSync("./ERK_keys/ERK_public_key", `${eciesKeys[0]},${rsaKeys[0]},${kyberKeys[0]}`);
fs.writeFileSync("./ERK_keys/ERK_private_key", `${eciesKeys[1]},${rsaKeys[1]},${kyberKeys[1]}` );
}
}
const requestKeys = (remote_address) => {
if (! /^(?:[a-z2-7]{16}|[a-z2-7]{56})\.onion$/.test(cli.o[1][0])) {
error(`Onion address is not valid, preventing useless request ...`);
process.exit(0);
}
}
/* What Crypto Do You Use */
const wcdyu = async (remote_address /* || cli */) => {
v = true;
d = true;
verbose(`Starting wcdyu request to ${remote_address} ... `);
debug(`Starting wcdyu request to ${remote_address} ... `);
if (remote_address?.o?.[0]?.includes("wcdyu")) { // if this function is called from cli
remote_address = remote_address.o?.[1]?.[0]; // set cli provided address
}
// The server tells you what crypto is he using so you can encrypt using it
if (! /^(?:[a-z2-7]{16}|[a-z2-7]{56})\.onion$/.test(remote_address)) {
error(`Onion address is not valid, preventing useless request ...`);
process.exit(0);
}
let remoteCrypto;
const usedCrypto = await curl(remote_address, "wcdyu");
try {
debug(`Parsing response ${usedCrypto} ... `);
remoteCrypto = JSON.parse(usedCrypto);
} catch(err) {
error(err);
process.exit(0);
}
if (! "use_erk" in remoteCrypto) {
error(`Unexpected object response: ${JSON.stringify(remoteCrypto, null, 2)}\n`);
process.exit(0);
}
verbose(`Done.`);
debug(`wcdyu server response: ${JSON.stringify(remoteCrypto, null, 2)}`);
return remoteCrypto;
}
const getPublicKey = async (remote_address /* || cli */) => {
v = true;
d = true;
verbose(`Starting getPublicKey request ... `);
debug(`Starting getPublicKey request ... `);
if (remote_address?.o?.[0]?.includes("erk")) { // if this function is called from cli
remote_address = remote_address.o?.[1]?.[0]; // set cli provided address
}
if (! /^(?:[a-z2-7]{16}|[a-z2-7]{56})\.onion$/.test(remote_address)) {
error(`Onion address is not valid, preventing useless request ...`);
process.exit(0);
}
const remote_erk_key = await curl(remote_address, "crypto");
// Check if key is valid:
if (remote_erk_key.length > 3000 && remote_erk_key.length < 5000 && remote_erk_key?.split(",").length === 3) {
verbose(`Got the key. Done.`);
debug(`Remote Server Key: ${remote_erk_key}`);
return remote_erk_key;
} else {
error("Remote server didn't provide his ERK key");
debug(`Server answer: ${remote_erk_key}`);
process.exit(0);
}
}
const curl = async (url, args) => {
return new Promise((resolve, reject) => {
debug(`Running command: curl --socks5-hostname 127.0.0.1:9050 '${url}:9001/${args}' `);
exec(`curl --socks5-hostname 127.0.0.1:9050 ${url}:9001/${args}`, (err, stdout, stderr) => {
if (err) {
error(`Error running curl: ${err}`);
reject(err);
return;
}
/*if (stderr) {
error(`stderr: ${stderr}`);
}*/
debug(`Resolving command ...`);
resolve(stdout);
});
});
};
const add = async (cli) => {
v = true;
d = true;
debug(`Getting alias and address from cli args ...`);
const alias = cli.o?.[1]?.[0];
const address = cli.o?.[2]?.[0];
debug(`Alias: (${alias}), Address (${address})`);
debug(`Testing if alias is a valid format ...`);
if (! /^[a-zA-Z0-9\-_.@]{1,99}$/.test(alias)) {
error(`Alias can only use alphanumeric charcaters and be 1 to 99 characters long. \nThis characters are also alloweed: - _ . @`);
process.exit(0);
}
debug(`Testing if onion address is valid ...`);
if (! /^(?:[a-z2-7]{16}|[a-z2-7]{56})\.onion$/.test(address)) {
error(`The onion address is not valid. Make sure you adding a real address`);
process.exit(0);
}
let addressBook = [];
try {
debug(`Reading ./address_book/list.txt ... `);
const data = await fs.promises.readFile('./address_book/list.txt', 'utf8');
debug(`Splitting entries by line ... `);
addressBook = data.split('\n').map(line => line.trim()).filter(line => line !== '');
debug(`A total of ${addressBook.length} contacts found in your addresses list`);
} catch (err) {
error('Error reading file:', err);
process.exit(0);
}
/* Check for duplicates to prevent username spoofing */
for (let i in addressBook) {
const auxAlias = addressBook[i].split(" ")[0];
if (auxAlias == alias) {
error(`Alias "${alias}" already exists, use a different alias`);
process.exit(0);
}
}
debug(`Adding new entry to in-memory address book ... `);
addressBook.push(`${alias} ${address}`);
debug(`Removing all duplicates (if there is any) ... `);
const uniqueEntries = new Set(addressBook);
debug(`Casting addressBook array to a string (ready to dump in file)... `);
const updatedText = Array.from(uniqueEntries).join('\n');
try {
debug(`Rewrite address_book/list.txt with the new ssv alias address pair`);
await fs.promises.writeFile('./address_book/list.txt', updatedText);
console.log("Added to your address book");
} catch (err) {
error(`Error writting on the address book: ${err}`);
}
debug(`Done`);
}
const addme = async (cli) => { //TODO: Add Verbose and Debug outputs
v = true;
d = true;
try {
debug(`Loading config...`);
config = await loadConfig("./config/dark-messenger.json");
debug(`Loading hostname...`);
let hostname = config.hidden_service_hostname = (await loadFile("./hidden_service/hostname")).trim();
debug(`Extracting onion domain from cli`);
if (! cli.o?.[1]?.[0] ) {
error(`Use "./DarkMessenger addme domain.onion" to provide the address of the user you want to add you`);
process.exit(0);
}
/* Avoid making useless requests client side */
if (! /^[a-zA-Z0-9\-_.@]{1,99}$/.test(config?.username)) {
error(`Your username is not valid. Only alphanumeric characters.\nNext characters are also allowed: - _ . @`);
process.exit(0);
}
if (! /^(?:[a-z2-7]{16}|[a-z2-7]{56})\.onion$/.test(cli.o[1][0])) {
error(`Onion address is not valid, preventing useless request ...`);
process.exit(0);
}
let api = `addme -d '{ "alias":"${config.username}", "address":"${hostname}" }' -H 'Content-Type: application/json'`;
const remoteConfig = await wcdyu(hostname);
debug(`REMOTE CONFIG: ${JSON.stringify(remoteConfig)}`);
if (remoteConfig?.use_erk && (remoteConfig?.add_me?.ecies || remoteConfig?.add_me?.rsa || remoteConfig?.add_me?.crystal_kyber)) {
debug(`Using ern for username ... `);
// TODO:
const [ eciesKey, rsaKey, kyberKey ] = (await getPublicKey(hostname)).split(",");
if (remoteConfig?.add_me?.ecies) {
// TODO: encrypt username with exies and change api to post and '/'
debug(`Encrypting [[${config.username}]] with ECIES`);
config.username = JSON.stringify(ECIES_encrypt(config.username, eciesKey));
//hostname = JSON.stringify(ECIES_encrypt(hostname, eciesKey));
}
if (remoteConfig?.add_me?.rsa) {
//debug(`Encrypting [[${config.username}]] with RSA`);
config.username = JSON.stringify(RSA_encrypt(config.username, rsaKey));
}
if (remoteConfig?.add_me?.crystal_kyber) {
//debug(`Encrypting [[${config.username}]] with CRYSTAL-KYBER`);
config.username = JSON.stringify(await KYBER_encrypt(config.username, kyberKey));
//debug(`Encrypted Username is; [[${config.username}]].`);
}
config.username = Buffer.from(config.username).toString("base64");
api = `addme -d '{ "alias":"${config.username}", "address":"${hostname}" }' -H 'Content-Type: application/json'`;
}
const result = await curl(`${cli.o[1][0]}`, api);
debug(`Result: ${result}`);
} catch(err) {
error(`Error on Add() : ${err}`);
process.exit(0);
}
if (config?.add_back) {
if ( (await ask("Do you want to add the address to your contact list too? [Y/N] -> ")).toUpperCase() === "Y" ) {
let tmpUsername = "";
do {
tmpUsername = await ask("Please provide a username / alias for the contact -> ");
} while (! /^[a-zA-Z0-9\-_.@]{1,99}$/.test(tmpUsername));
cli.o[2] = [cli.o[1][0]]; // set address
cli.o[1][0] = tmpUsername; // set username
await add(cli);
}
}
}
const send = async (cli) => {
v = true;
d = true;
const alias = cli.o?.[1]?.[0];
const message = cli.o?.[2]?.[0];
let address = "";
try {
const data = await fs.promises.readFile('./address_book/list.txt', 'utf8');
const addressBook = data.split('\n').map(line => line.trim()).filter(line => line !== '');
for (let i in addressBook) {
if (addressBook[i].split(" ")[0] == alias) {
debug(`Alias found, extracting address ... `);
address = addressBook[i].split(" ")[1];
break;
}
}
debug(`Loading config...`);
config = await loadConfig("./config/dark-messenger.json");
debug(`Sending message ... `);
const result = await curl(`${address}`, `send -d '{ "from":"${config.username}", "message":"${Buffer.from(message).toString('base64')}" }' -H 'Content-Type: application/json'`);
console.log(result);
} catch(err) {
error(`Error on Add() : ${err}`);
}
}
const contacts = async (cli) => {
v = true;
d = true;
const alias = cli.o?.[1]?.[0];
// let foundContacts = false;
let result = false;
try {
const contacts = await fs.promises.readFile("./address_book/list.txt", "utf-8") || null;
if (!contacts) exit("Contact list is empty");
if (!alias) {
result = contacts;
} else {
const contactLine = contacts.split("\n");
for (let i in contactLine) {
if (contactLine[i].split(" ")[0] === alias) {
result = contactLine[i]
break;
}
}
}
} catch(err) {
error(`Unable to read contacts from ./address_book/list.txt`);
process.exit(0);
}
if (result) {
console.log(result);
} else {
console.log("Unable to find");
}
}
const show = async (cli) => {
v = true;
d = true;
const alias = cli.o?.[1]?.[0];
debug(`Alias on show function is ${alias}`);
try {
const messagesRAW = await fs.promises.readFile('./messages/list.json', 'utf8');
const messages = JSON.parse(messagesRAW);
let textMessages = "";
let found = false;
// Mark As Read
let foundIds = JSON.parse(await fs.promises.readFile("./messages/read_messages.json", "utf-8"));
if (!alias) {
for (let i in messages) {
found = true;
textMessages += `Message with id ${chalk.bold.yellow(messages[i].id)} from ${chalk.bold.yellow(messages[i].from)}\n`
textMessages += `${messages[i].message}\n\n`;
foundIds.push(messages[i].id);
}
} else {
for (let i in messages) {
if (messages[i].from === alias) {
found = true;
textMessages += `Message with id ${chalk.bold.yellow(messages[i].id)} from ${chalk.bold.yellow(messages[i].from)}\n${messages[i].message}\n\n`;
foundIds.push(messages[i].id);
}
}
}
if (!found) {
console.log(`No messages to show`);
} else {
console.log(textMessages);
foundIds = [... new Set(foundIds)]; //remove duplicated ids
await fs.promises.writeFile("./messages/read_messages.json", JSON.stringify(foundIds, null, 2))
}
} catch(err) {
error(`Unable to read/parse/access ./messages/list.json: ${err}`);
process.exit(0);
}
}
const del = async (cli) => {
v = true;
d = true;
const id = cli.o?.[1]?.[0];
debug(`Got ID ${id} from cli`);
if (!id) {
error(`You need to provide the id of the message you want to remove`);
process.exit(0);
}
try {
const messagesRAW = await fs.promises.readFile('./messages/list.json', 'utf8');
let messages = JSON.parse(messagesRAW);
debug(`Removing message ...`);
messages = messages.filter(message => +message.id !== +id);
await fs.promises.writeFile('./messages/list.json', JSON.stringify(messages, null, 2));
debug(`Making id free from ./messages/read_messages.json ...`);
let readMessages = JSON.parse(await fs.promises.readFile("./messages/read_messages.json"));
readMessages = readMessages.filter(readId => +readId !== +id);
await fs.promises.writeFile('./messages/read_messages.json', JSON.stringify(readMessages, null, 2));
} catch(err) {
error(`Unable to delete message: ${err}`);
}
console.log('Done');
}
const startTor = () => {
debug(`Creating file to store tor pid process ... `);
verbose(`Starting Tor ...`);
const process = spawn("/usr/bin/tor", ["-f", "./config/torrc.conf"], {
detached: true,
stdio: "ignore"
});
debug(`Storing tor pid at ./tor_files/tor.pid ...`);
if (!fs.existsSync("./tor_files")) {
debug(`Making dir ./tor_files/ ... `);
fs.mkdirSync("./tor_files", { recursive: true });
}
fs.writeFileSync("./tor_files/tor.pid", process.pid.toString());
debug(`Detaching tor process from node process ...`);
process.unref();
process.on('error', (err) => {
error(`Error Starting Tor: ${err}`);
});
process.on("close", (code) => {
verbose(`Closing Tor ...`);
debug(`Tor process closing with code: ${code}`);
});
};
const stopTor = () => {
debug(`Extracting tor process id from ./tor_files/tor.pid ... `);
if (fs.existsSync("./tor_files/tor.pid")) {
const pid = parseInt(fs.readFileSync("./tor_files/tor.pid").toString(), 10);
debug(`Extracted pid: ${pid}`);
try {
verbose(`Stopping Tor`);
debug(`Sending SIGTERM signal tor process id ${pid}`);
process.kill(pid, 'SIGTERM');
console.log("Tor successfully stopped.");
debug(`Deleting ./tor_files/tor.pid file ...`);
fs.unlinkSync("./tor_files/tor.pid");
debug(`./tor_files/tor.pid has been deleted`);
} catch (err) {
error(`Unable to terminate tor process with PID ${pid}: ${err}`);
}
} else {
error(`./tor_files/tor.pid can't be found`);
}
};
const start = async (cli) => {
if (cli.c.config) {
if (typeof cli.c.config === "string") {
config = await loadConfig(cli.c.config);
}
}
if (!config) {
console.log(`Loading default config file expected at (./config/dark-messenger.json) ... `);
config = await loadConfig("./config/dark-messenger.json");
if (!config) {
exit(`Unable to load any config.`);
}
}
verbose("Verbose Activated");
debug("Debug Activated");
/*
"dark_messenger_cryptography": { "use_erk": true,
"offline_messages": {
"ecies": true,
"rsa": true,
"crystal_kyber": true
},
"online_messages": { "ecies": false, "rsa": false,
"crystal_kyber": false
},
"add_me": { "ecies": true,
"rsa": true,
"crystal_kyber": true
}
}
*/
if (config?.dark_messenger_cryptography?.use_erk) {
useErk = true;
generateErkKeys(config);
}
if (!config?.username) {
let tmpUsername = "";
do {
tmpUsername = await ask("Please provide a username / alias -> ");
} while (! /^[a-zA-Z0-9\-_.@]{1,99}$/.test(tmpUsername));
config.username = tmpUsername;
// save username in config:
fs.writeFileSync("./config/dark-messenger.json", JSON.stringify(config, null, 4));
}
if (fs.existsSync("./tor_files/tor.pid")) {
const torPid = await fs.promises.readFile("./tor_files/tor.pid");
verbose(`Tor already running with pid ${torPid}`);
} else {
if (!fs.existsSync("./hidden_service")) {
debug(`./hidden_service folder dosn't exist yet. Making it ...`);
fs.mkdirSync("./hidden_service", { recursive: true });
debug(`Setting hidden_service folder permissions ...`);
fs.chmodSync("./hidden_service", 0o700);
}
if (!fs.existsSync("./logs")) {
debug(`./logs folder dosn't exist yet. Making it ...`);
fs.mkdirSync("./logs", { recursive: true });
}
startTor();
}
if (config) {
debug(`Replacing auto by hostnane ...`);
if (config?.hidden_service_hostname === "auto") {
let secondsCounter = 0;
debug(`Waiting for ./hidden_service/hostname file to be created by tor`);
while (!fs.existsSync("./hidden_service/hostname")) {
await sleep(1000);
debug(`Waited ${++secondsCounter} second/s for file to be created by Tor`);
if (secondsCounter > 10) {
debug(`Waiting for to long. Breaking from loop`);
break;
}
}
try {
config.hidden_service_hostname = (await loadFile("./hidden_service/hostname")).trim();
debug(`Got hostname: ${config.hidden_service_hostname}`);
} catch(err) {
error(`Unable to load ./hidden_service/hostanme, maybe try again: ${error}`);
}
}
debug(`Checking if alert_on_new_messages is true`);
if (config?.alert_on_new_messages) {
if (fs.existsSync("./message_alert_server.pid")) {
const masPid = await fs.promises.readFile("./message_alert_server.pid");
verbose(`Message Alert Server already running with pid ${masPid}`);
} else {
debug(`Generating MessageAlert server source code`);
const newMessageAlertServerScript = generateMessageAlertServiceScript(config);
debug(`MessageAlert Service code generated:\n${newMessageAlertServerScript}\n`);
debug(`Creating ./startMessageAlertServer.js file`);
await writeMessageAlertServerScript(newMessageAlertServerScript);
debug(`Calling startMessageAlertServer() ...`);
startMessageAlertServer();
debug(`Call done`);
}
} else {
debug(`Not using MessageNotifier, to activate it add next options to your ./config/dark-messenger.json file:\n"alert_on_new_messages": "true",\n"check_new_messages_seconds": "15",`);
}
debug(`Checking if use_web_gui is true`);
if (config?.use_web_gui) {
if (fs.existsSync("./gui_server.pid")) {
const guiPid = await fs.promises.readFile("./gui_server.pid");
verbose(`GUI Server already running with pid ${guiPid}`);
} else {
debug(`Generating GUI Server source code ...`);
const guiServerScript = generateGuiServerScript(config);
debug(`GUI Server code generated:\n${guiServerScript}\n`);
debug(`Creating ./startGuiServer.js file ...`);
await writeGuiServerScript(guiServerScript);
debug(`Calling startGuiServer() ...`);
startGuiServer();
debug(`Call done`);
debug(`Also using the Tor Proxy Server by default to allow any browser to reach .onion addresses without browser configuration ...`);
if (fs.existsSync("./proxy_server.pid")) {
const proxyPid = await fs.promises.readFile("./proxy_server.pid");
verbose(`Proxy Server already running with pid ${proxyPid}`);
} else {
debug(`generating proxy server source code ...`);
const proxyServerScript = generateProxyServerScript(config);
debug(`Proxy Server code generated:\n${proxyServerScript}\n`);
debug(`Creating ./startProxyServer.js file ...`);
await writeProxyServerScript(proxyServerScript);
debug(`Calling startProxyServer() ...`);
startProxyServer();
debug(`Call done`);
}
}
} else {
debug(`Not using Web GUI, to activate it add next options to your ./config/dark-messenger.json file:\n"use_web_gui": "true",\n"web_gui_address": "127.0.0.1",\n"web_gui_port": "9000",`);
}
if (fs.existsSync("./hidden_server.pid")) {
const hiddenPid = await fs.promises.readFile("./hidden_server.pid");
verbose(`Hidden Server already running with pid ${hiddenPid}`);
} else {
debug(`Generating Hidden Server source code ...`);
const hiddenServerScript = generateHiddenServerScript(config);
debug(`Hidden Server code generated:\n${hiddenServerScript}\n`);
debug(`Creating ./startHiddenServer.js file ...`);
await writeHiddenServerScript(hiddenServerScript);
debug(`Calling startHiddenServer() ...`);
startHiddenServer();
debug(`Call done`);
}
} else {
debug(`Config not found. This is can't never happen btw`);
}
if (config?.hidden_service_hostname) {
console.log(`\nYour address is ${chalk.bold.yellow(config.hidden_service_hostname)} \nYou can copy to share it with your friends.\n\n`);
}
process.exit(0);
};
const stop = async (cli) => {
if (cli.c.config) {
if (typeof cli.c.config === "string") {
config = await loadConfig(cli.c.config);
}
}
if (!config) {
console.log(`Loading default config file expected at (./config/dark-messenger.json) ... `);
config = await loadConfig("./config/dark-messenger.json");
if (!config) {
exit(`Unable to load any config.`);
}
}
verbose("Verbose Activated");
debug("Debug Activated");
console.log(`Stopping All Services...`);
stopMessageAlertServer();
if (config?.use_web_gui) {
stopGuiServer();
stopProxyServer();
}
stopHiddenServer();
stopTor();
process.exit(0);
};
const loadFile = async (path) => {
try {
const data = await fs.promises.readFile(path, "utf8");
return data;
} catch (err) {
error(`Unable to read ${path}: ${err}`)
throw err;
}
};
const loadConfig = async (path) => {
try {
const file = await loadFile(path);
return JSON.parse(file);
} catch (err) {
error(`Unable to load config ${path} as JSON: ${err}`)
}
};
const generateGuiServerScript = (config) => {
const script = `#!/usr/bin/env node
import fs from "fs";
import express from "express";
const app = express();
const port = ${config?.web_gui_port || 9000};
const hostname = "${config?.web_gui_address || "127.0.0.1"}";
let contacts = fs.readFileSync("./address_book/list.txt", "utf-8") || null;
let auxContacts = "";
if (contacts) {
// TODO: FIX -> XSS / HTMLi here:
auxContacts = contacts.split("\\n")
.map(line => line.length > 2 ? \`<article class="contactName" onion="\${line.split(" ")[1]}">\${line.split(" ")[0]}</article>\` : "");
contacts = "<section id='contacts'>";
contacts += auxContacts.join("\\n");
contacts += "</section>"
} else {
contacts = "No contacts found";
}
app.get('/', (req, res) => {
res.send(\`<!DOCTYPE html>
<html lang="en">
<head prefix="og:http://ogp.me/ns#">
<meta charset="utf-8">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<title>Dark Messenger GUI</title>
<meta property="og:type" content="website">
<meta name="theme-color" content="#ffffff">
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background-color: #2c2f33;
color: snow;
display: flex;
flex-direction: column;
width: 90%;
}
#messageInput {
display: flex;
flex-direction: row;
padding: 10px;
}
#sendMessageInput {
flex: 1;
padding: 10px;
border: none;
border-radius: 5px;
background-color: #40444b;
color: white;
}
#sendMessageButton {
padding: 10px;
border: none;
border-radius: 5px;
background-color: #7289da;
color: white;
}
#contacts {
display: flex;
flex: 1;
flex-direction: column;
color: white;
}
.contactName {
display: flex;
flex: 1;
border-bottom: 2px solid black;
font-size: 30px;
margin-left: 50px; /* Tmp margin for future profile picture */
}
.hidden {
display: none !important;
}
#contactHeader {
display: none;
align-items: center;
padding: 10px;
}
#backButton {
cursor: pointer;
margin-right: 20px;
}
#contactNameDisplay {
font-weight: bold;
flex: 1;
text-align: center;
}
</style>
</head>
<body>
<div id="contacts">
<!-- TODO: Avoid XSS / HTMLi -->
\${contacts}
</div>
<div id="contactHeader">
<span id="backButton">←</span>
<div id="contactNameDisplay"></div>
</div>
<div id="messageInput" class="hidden">
<input type="text" placeholder="Type a message..." id="sendMessageInput">
<button id="sendMessageButton" onclick="sendMessage()">Send</button>
</div>
<script>
let currentView = "main";
const contacts = document.querySelectorAll(".contactName");
const contactsContainer = document.querySelector("#contacts");
const contactHeader = document.querySelector("#contactHeader");
const contactNameDisplay = document.querySelector("#contactNameDisplay");
const messageInput = document.querySelector("#messageInput");
const backButton = document.querySelector("#backButton");
contacts.forEach(contact => {
contact.addEventListener("click", (evnt) => {
currentView = "contact." + evnt.target.innerHTML;
contactNameDisplay.innerHTML = evnt.target.innerHTML;
contactsContainer.classList.add("hidden");
contactHeader.style.display = "flex";
messageInput.classList.remove("hidden");
});
});
backButton.addEventListener("click", () => {
contactsContainer.classList.remove("hidden");
contactHeader.style.display = "none";
messageInput.classList.add("hidden");
});
const sendMessage = () => {
const message = document.querySelector("#sendMessageInput").value;
if (!message || message.length < 1) {
alert("Message can't be void");
return;
}
const requestData = {
from: '${config?.username || "unknown"}',
message: btoa(message)
};
fetch('${config?.http_tor_proxy_url || "http://127.0.0.1:9002/"}http://${config?.hidden_service_hostname || "127.0.0.1"}:${config?.hidden_service_port || 9001}/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
})
.then(response => response.text())
.then(data => alert(data))
.catch(error => alert('Error: ' + error.message));
}
</script>
</body>
</html>
\`);
});
const server = app.listen(port, hostname, () => {
console.log(\`GUI Server listening at http://\${hostname}:\${port}\`);
fs.writeFileSync('./gui_server.pid', process.pid.toString());
});
process.on('SIGTERM', () => {
console.log('Received SIGTERM. Closing GUI Server...');
server.close(() => {
console.log('GUI Server closed.');
fs.unlinkSync('./gui_server.pid');
console.log('gui_server.pid has been deleted.');
});
});
`;
return script.trim();
};
const writeGuiServerScript = async (scriptContent) => {
try {
await fs.promises.writeFile('./startGuiServer.js', scriptContent);
verbose('startGuiServer.js file has been created successfully.');
} catch (err) {
error(`Failed to write startGuiServer.js: ${err}`);
}
};
const startGuiServer = () => {
debug(`Running chmod 775 over ./startGuiServer.js ... `);
fs.chmod("./startGuiServer.js", 0o775, (err) => {
if (err) {
error(`CRITICAL: Error running chmod 775 over ./startGuiServer.js: ${err}`);