-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
executable file
·1170 lines (1067 loc) · 32.7 KB
/
background.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
/* eslint-disable no-restricted-globals */
/* eslint-disable no-undef */
/* eslint-disable no-param-reassign */
/* eslint-disable no-var */
/* eslint-disable vars-on-top */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-use-before-define */
/* eslint-disable camelcase */
/*
You'll also need to modify the "websocket" variable in the
initialize() function in this script with the appropriate
connection URI for your host. For simple testing, the default
connection string of "ws://127.0.0.1:4343" should be fine.
*/
const getUnixTimestamp = () => Math.floor(Date.now() / 1000);
const isUUID = (id) => typeof id === "string" && id.length === 36;
const generateRandomNumber = () => {
const randomNumber = Math.random() * 100000000;
return Math.floor(randomNumber);
};
let websocket = false;
let lastLiveConnectionTimestamp = getUnixTimestamp();
let retries = 0;
const PING_INTERVAL = 2 * 60 * 1000; // 2 minutes
const HEADERS_TO_REPLACE = [
"origin",
"referer",
// 'accept-charset',
// 'accept-encoding',
"access-control-request-headers",
"access-control-request-method",
"access-control-allow-origin", // TODO it's not a forbidden header. Consider removing
// 'connection',
// 'content-length',
"cookie",
"date",
"dnt",
// 'expect',
// 'host',
// 'keep-alive',
// 'permissions-policy',
// 'te',
"trailer",
// 'transfer-encoding',
"upgrade",
// 'via',
// 'user-agent'
];
const DEFAULT_STORAGE_KEY_EXPIRE_MS = 10 * 60 * 1000; // 10 mins
const DEFAULT_STORAGE_EXPIRATION_CHECK = 60 * 1000; // 1 min
const FETCH_TIMEOUT = 10 * 1000; // 10 sec
const REDIRECT_DATA_TIMEOUT = 5 * 1000; // 5 sec
const RESPONSE_COOKIE_TIMEOUT = 5 * 1000; // 5 sec
const CHROME_PING_INTERVAL = 3 * 1000;
const WEBSOCKET_URLS = [
"wss://proxy.wynd.network:4650",
"wss://proxy.wynd.network:4444",
];
// const WEBSOCKET_URLS = ["wss://proxy.dev.wynd.network"];
// const WEBSOCKET_URLS = ["ws://127.0.0.1"];
const RPC_CALL_TABLE = {
HTTP_REQUEST: performHttpRequest,
AUTH: authenticate,
PONG: () => {},
};
const BROWSER_ID_KEY = "wynd:browser_id";
const USER_ID_KEY = "wynd:user_id";
const JWT_KEY = "wynd:jwt";
const STATUS_KEY = "wynd:status";
const DEVICE_KEY = "wynd:device";
const USER_KEY = "wynd:user";
const AUTHENTICATED_KEY = "wynd:authenticated";
const SETTINGS_KEY = "wynd:settings";
const POPUP_STATE_KEY = "wynd:popup";
const PERMISSIONS_KEY = "wynd:permissions";
const ACCESS_TOKEN_KEY = "accessToken";
const REFRESH_TOKEN_KEY = "refreshToken";
const USERNAME_KEY = "username";
const STATUSES = {
CONNECTED: "CONNECTED",
DISCONNECTED: "DISCONNECTED",
DEAD: "DEAD",
CONNECTING: "CONNECTING",
};
class Mutex {
/**
* When multiple operations attempt to acquire the lock,
* this queue remembers the order of operations.
*/
#queue;
#isLocked;
constructor() {
this.#queue = [];
this.#isLocked = false;
}
/**
* Enqueue a function to be run serially.
*
* This ensures no other functions will start running
* until `callback` finishes running.
* @param callback Function to be run exclusively.
* @returns The return value of `callback`.
*/
async runExclusive(callback) {
const release = await this.#acquire();
try {
return await callback();
} finally {
release();
}
}
/**
* Wait until the lock is acquired.
* @returns A function that releases the acquired lock.
*/
#acquire() {
return new Promise((resolve) => {
this.#queue.push({ resolve });
this.#dispatch();
});
}
/**
* Check the availability of the resource
* and provide access to the next operation in the queue.
*
* dispatch is called whenever availability changes,
* such as after lock acquire request or lock release.
*/
#dispatch() {
if (this.#isLocked) {
// The resource is still locked.
// Wait until next time.
return;
}
const nextEntry = this.#queue.shift();
if (!nextEntry) {
// There is nothing in the queue.
// Do nothing until next dispatch.
return;
}
// The resource is available.
this.#isLocked = true; // Lock it.
// and give access to the next operation
// in the queue.
nextEntry.resolve(this.#buildRelease());
}
/**
* Build a release function for each operation
* so that it can release the lock after
* the operation is complete.
*/
#buildRelease() {
return () => {
// Each release function makes
// the resource available again
this.#isLocked = false;
// and call dispatch.
this.#dispatch();
};
}
}
// Simple class for sending logs back to proxy-server
class LogsTransporter {
static sendLogs(logs) {
websocket.send(
JSON.stringify({
action: "LOGS",
data: logs,
})
);
}
}
// Key-value storage with expiration time (per key)
class CustomStorage {
// expiration time of the key in storage (in milliseconds)
#defaultExpireMs;
#storage;
constructor(defaultExpireMs = DEFAULT_STORAGE_KEY_EXPIRE_MS) {
this.#defaultExpireMs = defaultExpireMs;
this.#storage = {};
const clearExpiredInterval = setInterval(() => {
this.#clearExpired();
}, DEFAULT_STORAGE_EXPIRATION_CHECK);
}
/**
* @returns stored value or null (if key does not exist)
* @note it is POSSIBLE to set value === null:
* - storage.set(key, null);
* - storage.get(key); # null
* - storage.exists(key); # true
*/
get(key) {
this.#checkKeyIsExpired(key);
return this.#storage[key]?.value ?? null;
}
set(key, value, exMs = null) {
const expirationTimeMs = exMs ?? this.#defaultExpireMs;
const data = {
value,
metainfo: {
expire_at: Date.now() + expirationTimeMs,
},
};
this.#storage[key] = data;
}
del(key) {
delete this.#storage[key];
}
exists(key) {
this.#checkKeyIsExpired(key);
return this.#storage[key] !== null && this.#storage[key] !== undefined;
}
#clearExpired() {
Object.keys(this.#storage).forEach((key) => {
this.#checkKeyIsExpired(key);
});
}
#checkKeyIsExpired(key) {
const data = this.#storage[key];
if (
data === null ||
data === undefined ||
Date.now() > data.metainfo.expire_at
) {
delete this.#storage[key];
}
}
}
class ResponseProcessor {
// mutexes
#cookieMutex;
#redirectMutex;
// wait tasks
#waitCookieTasks;
#waitRedirectTasks;
// storages
#cookieStorage;
#redirectDataStorage;
constructor() {
this.#cookieMutex = new Mutex();
this.#redirectMutex = new Mutex();
this.#waitCookieTasks = new CustomStorage();
this.#waitRedirectTasks = new CustomStorage();
this.#cookieStorage = new CustomStorage();
this.#redirectDataStorage = new CustomStorage();
}
async getResponseCookies(requestId, timeoutMs) {
return new Promise(async (resolve, reject) => {
const timeout = setTimeout(async () => {
await this.#cookieMutex.runExclusive(() => {
this.#waitCookieTasks.del(requestId);
LogsTransporter.sendLogs(
`Timeout Error: Could not get Cookies from response to request ${requestId}`
);
reject(
`Timeout Error: Could not get Cookies from response to request ${requestId}`
);
});
}, timeoutMs);
await this.#cookieMutex.runExclusive(() => {
const cookies = this.#cookieStorage.get(requestId);
// @note
// empty Cookies are '[]'
// error Cookies are '' (empty string)
if (cookies !== null) {
clearTimeout(timeout);
resolve(cookies);
} else {
this.#waitCookieTasks.set(requestId, (c) => {
clearTimeout(timeout);
resolve(c);
});
}
});
});
}
async setResponseCookies(requestId, cookies) {
return this.#cookieMutex.runExclusive(() => {
const resolve = this.#waitCookieTasks.get(requestId);
if (resolve) {
resolve(cookies);
this.#waitCookieTasks.del(requestId);
} else {
this.#cookieStorage.set(requestId, cookies);
}
});
}
async setRedirectData(requestId, redirectData) {
return this.#redirectMutex.runExclusive(() => {
const resolve = this.#waitRedirectTasks.get(requestId);
if (resolve) {
resolve(redirectData);
this.#waitRedirectTasks.del(requestId);
} else {
this.#redirectDataStorage.set(requestId, redirectData);
}
});
}
async getRedirectData(requestId, timeoutMs) {
return new Promise(async (resolve, reject) => {
const timeout = setTimeout(async () => {
await this.#redirectMutex.runExclusive(() => {
this.#waitRedirectTasks.del(requestId);
LogsTransporter.sendLogs(
`Timeout Error: Could not get Redirect data from response to request ${requestId}`
);
reject(
`Timeout Error: Could not get Redirect data from response to request ${requestId}`
);
});
}, timeoutMs);
await this.#redirectMutex.runExclusive(() => {
const redirectData = this.#redirectDataStorage.get(requestId);
if (redirectData !== null) {
clearTimeout(timeout);
resolve(redirectData);
} else {
this.#waitRedirectTasks.set(requestId, (data) => {
clearTimeout(timeout);
resolve(data);
});
}
});
});
}
async registerOnErrorOccuredEvent(requestId) {
return this.setResponseCookies(requestId, "");
}
}
// Synchronize all fetch() requests
class RequestFetcher {
#usedChromeRequestIds;
#resolve;
#webRequestMutex;
#fetchMutex;
constructor() {
this.#usedChromeRequestIds = new CustomStorage();
this.#resolve = null;
this.#webRequestMutex = new Mutex();
this.#fetchMutex = new Mutex();
}
// Run fetch() and return new requestId.
// Next fetch() will wait until the requestId of previous fetch() is established.
async fetch(url, requestOptions) {
return this.#fetchMutex.runExclusive(() => {
return new Promise(async (resolve, reject) => {
let responsePromise = null;
const timeout = setTimeout(async () => {
await this.#webRequestMutex.runExclusive(() => {
// for unknown reason, sometimes fetch request ignores all webRequest listeners
// so we won't be able to propagate Set-Cookie from the response
this.#resolve = null;
LogsTransporter.sendLogs(
`Resolved WITHOUT REQUEST ID: ${url}, ${JSON.stringify(
requestOptions
)}`
);
resolve({
requestId: null,
responsePromise,
});
});
}, FETCH_TIMEOUT);
await this.#webRequestMutex.runExclusive(() => {
if (this.#resolve) {
this.#resolve = null;
clearTimeout(timeout);
LogsTransporter.sendLogs(
`Inconsistency detected. Waiting for more than 1 requestId: ${url}, ${JSON.stringify(
requestOptions
)}`
);
reject(
`Inconsistency detected. Waiting for more than 1 requestId.`
);
}
responsePromise = fetch(url, requestOptions).catch((e) => {
LogsTransporter.sendLogs(
`Fetch error for ${url} ${JSON.stringify(
requestOptions
)} : ${e}, ${e.stack}`
);
throw e;
});
this.#resolve = (requestId) => {
clearTimeout(timeout);
return resolve({ requestId, responsePromise });
};
});
});
});
}
async registerOnBeforeRequestEvent(requestId) {
return this.#webRequestMutex.runExclusive(() => {
if (!this.#usedChromeRequestIds.exists(requestId)) {
this.#processNewRequestId(requestId);
}
});
}
async registerOnBeforeRedirectEvent(requestId) {
return this.#webRequestMutex.runExclusive(() => {
if (!this.#usedChromeRequestIds.exists(requestId)) {
this.#processNewRequestId(requestId);
}
});
}
// @note
// usually, fetch() triggers onBeforeRequest listener. But in some rare cases
// request skips all previous events (onBeforeRequest, onResponseStarted, etc...)
// so we may notice that SOMETHING was fetched only when fetch() is already completed
async registerOnCompletedEvent(requestId) {
return this.#webRequestMutex.runExclusive(async () => {
if (!this.#usedChromeRequestIds.exists(requestId)) {
this.#processNewRequestId(requestId);
}
});
}
async registerOnErrorOccuredEvent(requestId) {
return this.#webRequestMutex.runExclusive(async () => {
if (!this.#usedChromeRequestIds.exists(requestId)) {
// if fetch() is waiting for new requestId, resolve it.
this.#processNewRequestId(requestId);
} else {
await RESPONSE_PROCESSOR.registerOnErrorOccuredEvent(requestId);
}
});
}
// @note
// must be called under webRequestMutex
#processNewRequestId(requestId) {
// mark requestId as used
this.#usedChromeRequestIds.set(requestId, 1);
const resolve = this.#resolve;
this.#resolve = null;
resolve(requestId);
}
}
const validateJWT = (jwt) => {
websocket.send(JSON.stringify({ jwt, action: "VALIDATE_JWT" }));
};
const parseValue = (value) => {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
};
function getLocalStorage(key) {
return new Promise((resolve, reject) => {
chrome.storage.local
.get([key])
.then((data) => {
resolve(parseValue(data[key]));
})
.catch(reject);
});
}
function setLocalStorage(key, value) {
return new Promise((resolve, reject) => {
chrome.storage.local
.set({ [key]: JSON.stringify(value) })
.then(() => {
resolve();
})
.catch(reject);
});
}
async function authenticate() {
let browser_id = await getLocalStorage(BROWSER_ID_KEY);
const user_id = await getLocalStorage(USER_ID_KEY);
const version = chrome.runtime.getManifest().version;
// If no browser ID is already set we generate a
// new one and return it to the server.
if (!isUUID(browser_id)) {
return;
}
/*
Return the browser's unique ID as well as
some metadata about the instance.
*/
const authenticationResponse = {
browser_id,
user_id: null,
user_agent: navigator.userAgent,
timestamp: getUnixTimestamp(),
device_type: "extension",
version,
};
if (Boolean(user_id)) {
authenticationResponse.user_id = user_id;
}
return authenticationResponse;
}
function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
}
function arrayBufferToBase64(buffer) {
let binary = "";
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i += 1) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
// Checks the websocket connection to ensure it's still live
// If it's not, then we attempt a reconnect
const websocket_check_interval = setInterval(async () => {
const PENDING_STATES = [
0, // CONNECTING
2, // CLOSING
];
if (websocket) {
if (websocket.readyState === 1) {
await setLocalStorage(STATUS_KEY, STATUSES.CONNECTED);
} else if (websocket.readyState === 3) {
await setLocalStorage(STATUS_KEY, STATUSES.DISCONNECTED);
}
}
// Check WebSocket state and make sure it's appropriate
if (PENDING_STATES.includes(websocket.readyState)) {
console.log("WebSocket not in appropriate state for liveness check...");
return;
}
// Check if timestamp is older than ~15 seconds. If it
// is the connection is probably dead and we should restart it.
const current_timestamp = getUnixTimestamp();
const seconds_since_last_live_message =
current_timestamp - lastLiveConnectionTimestamp;
if (seconds_since_last_live_message > 129 || websocket.readyState === 3) {
console.error(
"WebSocket does not appear to be live! Restarting the WebSocket connection..."
);
try {
websocket.close();
} catch (e) {
// Do nothing.
}
initialize();
return;
}
// Send PING message down websocket, this will be
// replied to with a PONG message form the server
// which will trigger a function to update the
// lastLiveConnectionTimestamp variable.
// If this timestamp gets too old, the WebSocket
// will be severed and started again.
websocket.send(
JSON.stringify({
id: uuidv4(),
version: "1.0.0",
action: "PING",
data: {},
})
);
}, PING_INTERVAL);
const RESPONSE_PROCESSOR = new ResponseProcessor();
const REQUEST_FETCHER = new RequestFetcher();
async function performHttpRequest(params) {
const replacedRequestHeaders = Object.keys(params.headers)
.filter((headerKey) => {
return HEADERS_TO_REPLACE.includes(headerKey.toLowerCase()); // || headerKey.toLowerCase().startsWith('sec-') || headerKey.toLowerCase().startsWith('proxy-');
})
.map((headerKey) => {
return {
header: headerKey,
operation: "set",
value: params.headers[headerKey],
};
});
const newRuleIds = [];
if (replacedRequestHeaders.length > 0) {
const newRuleId = generateRandomNumber();
newRuleIds.push(newRuleId);
const newRule = {
id: newRuleId,
priority: 1,
action: {
type: "modifyHeaders",
requestHeaders: replacedRequestHeaders,
},
condition: {
urlFilter: `${params.url.replace(/\/$/, "")}`,
tabIds: [chrome.tabs.TAB_ID_NONE],
},
};
chrome.declarativeNetRequest.updateSessionRules({
addRules: [newRule],
});
}
const request_options = {
method: params.method,
mode: "cors",
cache: "no-cache",
credentials: "omit",
headers: params.headers,
redirect: "manual",
};
// If there is a request body, we decode it
// and set it for the request.
if (params.body) {
// This is a hack to convert base64 to a Blob
const fetchURL = `data:application/octet-stream;base64,${params.body}`;
const fetchResp = await fetch(fetchURL);
request_options.body = await fetchResp.blob();
}
const { requestId, responsePromise } = await REQUEST_FETCHER.fetch(
params.url,
request_options
).catch((e) => {
console.error(`Error occurred while extracting requestId: ${e}`);
LogsTransporter.sendLogs(
`Error occurred while extracting requestId ${
params.url
}, ${JSON.stringify(request_options)}: ${e}, ${e.stack}`
);
return { requestId: undefined, responsePromise: undefined };
});
if (responsePromise === undefined) {
// Empty response.
return null;
}
const response = await responsePromise.catch((e) => {
console.error(`Error occurred while performing fetch: ${e}`);
LogsTransporter.sendLogs(
`Error occurred while performing fetch <${requestId}> ${
params.url
}, ${JSON.stringify(request_options)}: ${e}, ${e.stack}`
);
});
if (newRuleIds) {
chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: newRuleIds,
});
}
if (!response) {
return {
url: params.url,
status: 400,
status_text: "Bad Request",
headers: {},
body: "",
};
}
// process redirects manually
if (response.type === "opaqueredirect") {
if (!requestId) {
console.error(`No requestId for redirect.`);
LogsTransporter.sendLogs(
`Error occurred in redirect ${params.url}, ${JSON.stringify(
request_options
)}: No requestId for redirect`
);
// Empty response.
return null;
}
const redirectResponse = await RESPONSE_PROCESSOR.getRedirectData(
requestId,
REDIRECT_DATA_TIMEOUT
)
.then((redirectData) => {
const responseMetadata = JSON.parse(redirectData);
if (Object.hasOwn(responseMetadata.headers, "Set-Cookie")) {
responseMetadata.headers["Set-Cookie"] = JSON.parse(
responseMetadata.headers["Set-Cookie"]
);
}
return {
url: response.url,
status: responseMetadata.statusCode,
status_text: "Redirect",
headers: responseMetadata.headers,
body: "",
};
})
.catch((e) => {
console.error(
`Error occured while processing redirect metadata : ${e}`
);
LogsTransporter.sendLogs(
`Error occured while processing redirect metadata <${requestId}> ${
params.url
}, ${JSON.stringify(request_options)}: ${e}, ${e.stack}`
);
// Empty response.
return null;
});
return redirectResponse;
}
const headers = {};
// response.headers is an iterable object Headers (not a json)
// so we must manually copy before returning
response.headers.forEach((value, key) => {
// remove Content-Encoding header
if (key.toLowerCase() !== "content-encoding") {
headers[key] = value;
}
});
if (requestId) {
await RESPONSE_PROCESSOR.getResponseCookies(
requestId,
RESPONSE_COOKIE_TIMEOUT
)
.then((responseCookies) => {
// onErrorOccurred listener sets cookies = ''
if (responseCookies !== "") {
const cookies = JSON.parse(responseCookies);
if (cookies.length !== 0) {
headers["Set-Cookie"] = cookies;
}
}
})
.catch((e) => {
// could not extract response cookies. Just skip
console.error(`Error occured while processing response cookies: ${e}`);
LogsTransporter.sendLogs(
`Error occured while processing response cookies <${requestId}> ${
params.url
}, ${JSON.stringify(request_options)}: ${e}, ${e.stack}`
);
});
}
return {
url: response.url,
status: response.status,
status_text: response.statusText,
headers: headers,
body: arrayBufferToBase64(await response.arrayBuffer()),
};
}
chrome.webRequest.onBeforeRequest.addListener(
async (details) => {
// Ensure we only process requests done by the Chrome extension
if (details.initiator !== location.origin.toString()) {
return;
}
await REQUEST_FETCHER.registerOnBeforeRequestEvent(details.requestId);
},
{ urls: ["<all_urls>"] },
[]
);
function extractCookies(responseHeaders) {
const cookies = [];
responseHeaders.forEach((header) => {
if (header.name.toLowerCase() === "set-cookie") {
if (Object.hasOwn(header, "value")) {
cookies.push(header.value);
} else if (Object.hasOwn(header, "binaryValue")) {
cookies.push(header.binaryValue);
}
}
});
return cookies;
}
// Extract redirect headers
// We process all redirects manually
chrome.webRequest.onBeforeRedirect.addListener(
async (details) => {
// Ensure we only process requests done by the Chrome extension
if (details.initiator !== location.origin.toString()) {
return;
}
const responseHeaders = {};
details.responseHeaders.forEach((header) => {
if (header.name.toLowerCase() !== "set-cookie") {
// TODO any other non-unique headers?
if (Object.hasOwn(header, "value")) {
responseHeaders[header.name] = header.value;
} else if (Object.hasOwn(header, "binaryValue")) {
responseHeaders[header.name] = header.binaryValue;
}
}
});
const cookies = extractCookies(details.responseHeaders);
if (cookies.length !== 0) {
// We pack array of cookies into string and depack later.
// Otherwise multiple Set-Cookie headers would override each other.
responseHeaders["Set-Cookie"] = JSON.stringify(cookies);
}
await REQUEST_FETCHER.registerOnBeforeRedirectEvent(details.requestId);
await RESPONSE_PROCESSOR.setRedirectData(
details.requestId,
JSON.stringify({
// 'url': details.url,
statusCode: details.statusCode,
headers: responseHeaders,
})
);
},
{ urls: ["<all_urls>"] },
["responseHeaders", "extraHeaders"]
);
// Extract response Set-Cookies header
chrome.webRequest.onCompleted.addListener(
async (details) => {
// Ensure we only process requests done by the Chrome extension
if (details.initiator !== location.origin.toString()) {
return;
}
const cookies = extractCookies(details.responseHeaders);
await REQUEST_FETCHER.registerOnCompletedEvent(details.requestId);
await RESPONSE_PROCESSOR.setResponseCookies(
details.requestId,
JSON.stringify(cookies)
);
},
{ urls: ["<all_urls>"] },
["responseHeaders", "extraHeaders"]
);
chrome.webRequest.onErrorOccurred.addListener(
async (details) => {
// Ensure we only process requests done by the Chrome extension
if (details.initiator !== location.origin.toString()) {
return;
}
LogsTransporter.sendLogs(
`onErrorOccured, ${details.requestId}, ${details.url}, ${details.error}`
);
await REQUEST_FETCHER.registerOnErrorOccuredEvent(details.requestId);
},
{ urls: ["<all_urls>"] },
[]
);
async function initialize() {
// Replace the below connection URI with whatever
// the host details you're using are.
// ** Ideal setup is the following **
// Have Nginx doing a reverse-proxy (proxy_pass) to
// the CursedChrome server with a HTTPS cert setup.
// For SSL/TLS WebSockets, instead of https:// you need
// to use wss:// as the protocol. For maximum stealth,
// setting the WebSocket port to be the standard
// TLS/SSL port (this will make sure tools like little
// snitch don't alert on a new port connection from Chrome).
// Do not allow the websocket to run if permissions & browser id is blank
const browserId = await getLocalStorage(BROWSER_ID_KEY);
if (!browserId) {
console.warn("[INITIALIZE] Browser ID is blank. Cancelling connection...");
return;
}
const hasPermissions = await getLocalStorage(PERMISSIONS_KEY);
if (!hasPermissions) {
console.warn(
"[INITIALIZE] Permissions is disabled. Cancelling connection..."
);
return;
}
// Loop through each websocketUrl in case the other does not work
const websocketUrl = WEBSOCKET_URLS[retries % WEBSOCKET_URLS.length];
websocket = new WebSocket(websocketUrl);
websocket.onopen = async function (e) {
console.log("Websocket Open");
lastLiveConnectionTimestamp = getUnixTimestamp();
await setLocalStorage(STATUS_KEY, STATUSES.CONNECTED);
};
websocket.onmessage = async function (event) {
// Update last live connection timestamp
lastLiveConnectionTimestamp = getUnixTimestamp();
let parsed_message;
try {
parsed_message = JSON.parse(event.data);
} catch (e) {
console.error("Could not parse WebSocket message!", event.data);
console.error(e);
return;
}
if (parsed_message.action in RPC_CALL_TABLE) {
try {
const result = await RPC_CALL_TABLE[parsed_message.action](
parsed_message.data
);
websocket.send(
JSON.stringify({
// Use same ID so it can be correlated with the response
id: parsed_message.id,
origin_action: parsed_message.action,
result: result,
})
);
} catch (e) {
LogsTransporter.sendLogs(
`RPC encountered error for message ${JSON.stringify(
parsed_message
)}: ${e}, ${e.stack}`
);
console.error(
`RPC action ${parsed_message.action} encountered error: `,
e
);
}
} else {
console.error(`No RPC action ${parsed_message.action}!`);
}
};
websocket.onclose = async function (event) {
if (event.wasClean) {
console.log(
`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`
);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
console.log("[close] Connection died");
await setLocalStorage(STATUS_KEY, STATUSES.DEAD);