This repository has been archived by the owner on Feb 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
secureDiscord.js
554 lines (502 loc) · 22.2 KB
/
secureDiscord.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
/*******************************************************************************
* This file is part of DiscordCrypt (https://gitlab.com/leogx9r/DiscordCrypt).
* Copyright (c) 2019-Present Leonardo Gates
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
/**
* @typedef {Object} MainWindowOptions
* @property {string} title
* @property {null} backgroundColor
* @property {number} width
* @property {number} height
* @property {number} minWidth
* @property {number} minHeight
* @property {boolean} transparent
* @property {boolean} frame
* @property {boolean} resizable
* @property {boolean} show
* @property {{blinkFeatures: string, preload: string}} webPreferences
*/
/**
********************************************************************************************
* @desc Enhance Discord's desktop app for privacy. *
********************************************************************************************
* I N S T A L L A T I O N *
********************************************************************************************
* 1.) Save This File As: *
* < discord_desktop_core >/app/secureDiscord.js *
********************************************************************************************
* 2.) Edit The File: *
* < discord_desktop_core >/app/mainScreen.js *
* *
* Instead Of Line: *
* mainWindow = new _electron.BrowserWindow(mainWindowOptions); *
* *
* Replace With: *
* mainWindow = require( './secureDiscord.js' )( mainWindowOptions ); *
********************************************************************************************
* 3.) Configure the options below to change functionality of the plugin. *
* *
* Features: *
* *
* - Blocks various tracking and ad URLs via a subscription list. *
* - Sets your user agent to Tor's. *
* - Sets additional HTTP headers to Tor defaults. *
* - Routes all traffic over Tor ( Requires Tor to be running on 127.0.0.1:9050 ) *
* - Blocks access to known Discord tracking URLs. *
* - Adds additional block lists. *
* - Removes Discord tracking from any external URL. *
* - Removes several fingerprint based headers from requests. *
* - Logs all interactions that occurs. *
* *
********************************************************************************************
* @param {MainWindowOptions} mainWindowOptions Main BrowserWindow object created upon *
* Discord's main loading event. *
********************************************************************************************
*/
module.exports = ( mainWindowOptions ) => {
/**
* @desc Configure your options here.
*/
const options = {
/**
* @desc Whether to spoof HTTP headers sent in requests to those defined below in headerInfo.
* @type {boolean}
*/
spoofHeaders: true,
/**
* @desc Whether to remove tracking URLs by Discord. This specific path can be configured below in trackingPath.
* @type {boolean}
*/
removeTrackingURLs: true,
/**
* @desc Whether to use additional HOSTS based block lists defined below.
*/
useAdditionalBlockList: true,
/**
* @desc Whether to tunnel Discord's connections over a proxy.
* @type {boolean}
*/
useProxy: true,
/**
* @desc When using a proxy, if this is enabled and a connection fails, a direct connection will be used.
* If not, the connection is aborted.
* @type {boolean}
*/
fallbackToDirectConnection: false,
/**
* @desc Whether to enable developer tools and avoid clearing console logs upon startup.
* Useful for verifying the script works.
* @type {boolean}
*/
debug: false,
/**
* @desc Whether to be verbose in logging events that occurred.
* @type {boolean}
*/
verbose: false,
/**
* @desc If useProxy is enabled, this specifies the proxy address to use for connections.
* N.B. This must specify the protocol of the address. Example: "socks5://"
* @type {string}
*/
proxyAddress: 'socks5://127.0.0.1:9050',
/**
* Array of URLs to capture connections from.
* This is a lazy interpretation to be sure to capture all connections.
* Don't change this if you don't know what you're doing.
* @type {string[]}
*/
targetURLs: [
'*://*.*/*',
'*://*/*',
'*://*',
'*'
],
/**
* @desc Log color CSS defined for logging messages.
* @type {string}
*/
logColor: 'color: #00007f; font-weight: bold; text-shadow: 0 0 1px #f00, 0 0 2px #0f0, 0 0 3px #00f;',
/**
* @desc Log color CSS for logging filtered URL requests.
* @type {string}
*/
warnColor: 'color: #f00; font-weight: bold',
/**
* @desc Header information to modify or remove from requests.
* N.B. These must ALL be lowercase with the exception of headerInfo.insert.
* @type {{insert: Object, modify: Object, remove: string[]}}
*/
headerInfo: {
/* Headers to add to every request. If it already exists, the value is modified to those below. */
insert: {
/* NOTE: Tor has removed this header in the most recent versions. */
/* @see https://en.wikipedia.org/wiki/Do_Not_Track */
//'DNT': '1',
/* @see https://www.w3.org/TR/upgrade-insecure-requests */
'Upgrade-Insecure-Requests': '1'
},
/* Headers to modify if they're present in a request. Does not add them if they do not exist. */
modify: {
/* Tor Specific Headers */
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0',
'accept-language': 'en-US,en;q=0.5',
'accept-encoding': 'gzip, deflate, br'
},
/* Headers to remove if they're present in a request. */
remove: [
/* Remove referrers from outgoing requests. */
'referer',
/* Caching Headers. Can be used for request correlation. */
'etag',
'date',
'if-match',
'if-range',
'if-none-match',
'if-modified-since',
'if-unmodified-since',
/* Discord's Non-Standard Fields. Commonly used for tracking and reporting information. */
'x-debug',
'x-track',
'x-rpc-proxy',
'x-fingerprint',
'x-debug-options',
'x-failed-requests',
'x-super-properties',
'x-context-properties',
/* Proxy Headers. Can be used to reveal the real IP address of the host. */
'via',
'vary',
'x-forwarded-for',
'x-forwarded-host',
'x-forwarded-proto',
'x-requested-with',
/* Known Tracking Headers. May not necessarily be present or used by Discord. */
'x-uidh',
'x-csrf-token',
'x-request-id',
'x-correlation-id'
]
},
/**
* @desc Permissions specifically disabled by default.
* @see https://developer.chrome.com/extensions/permission_warnings
* @type {string[]}
*/
disabledWebPermissions: [
'bookmarks',
'geolocation',
'management',
'notifications',
'pageCapture',
'privacy',
'proxy',
'system.storage',
'tabCapture',
'topSites',
'webNavigation',
],
/**
* @desc Direct links to HOSTS file block list for filtering bad URLs.
* @type {string[]}
*/
blockListURLs: [
/* Dan Pollock's Hosts File. */
'https://someonewhocares.org/hosts/hosts',
/* HpHosts Ad & Tracker List. */
'https://hosts-file.net/ad_servers.txt',
/* Peter Lowe’s Ad & Tracking Server List. */
'https://pgl.yoyo.org/adservers/serverlist.php?showintro=0;hostformat=hosts',
],
/**
* @desc Specific domain names and paths to block access to.
* Can be used as a form of Ad-Blocking.
* @type {string[]}
*/
filteredHosts: [
/* Crash and error reporting URLs. */
'sentry.io',
'crash.discordapp.com',
/* User event tracking. ( Example: When you open menus/channels. ) */
'discordapp.com/api/science',
'discordapp.com/api/v6/science',
/* Old URLs they may eventually switch back to. */
'discordapp.com/api/track',
'discordapp.com/api/v6/track',
/* Potential future URLs when Discord upgrades their API. */
'discordapp.com/api/v7/science',
'discordapp.com/api/v7/track',
/* Various experiments that Discord makes the user participate in. */
'discordapp.com/api/v6/experiments',
/* Reports the quality of voice connections and other metadata. */
'discordapp.com/api/v6/rtc/quality-report',
/* Generic tracking URLs. */
'google-analytics.com',
'webrtc.org/experiments'
],
/**
* @desc Discord modifies any posted URL to add a tracker to it.
* This removes that and redirects to the original.
* Example:
* xxx.discordapp.net/external/< Tracking ID >/https/google.com
* -> https://google.com
* @type {string}
*/
urlTrackingPath: 'discordapp.net/external/',
};
/**
* @private
* @desc Built hosts block list.
* @type {Array<string>}
*/
let _filteredHosts = [].concat( options.filteredHosts );
/**
* @desc Electron module.
* @type {module:electron}
*/
const electron = require( 'electron' );
/* Disable specific permissions. */
electron.session.defaultSession.setPermissionRequestHandler(
( webContents, permission, callback ) => {
/* If a disabled permission is being used, reject the request. */
if( options.disabledWebPermissions.indexOf( permission ) !== -1 ) {
callback( false );
return;
}
/* Allow the permission. */
callback( true );
}
);
/* Recreate the main window. */
let mainWnd = new ( electron.BrowserWindow )( mainWindowOptions );
/**
* @desc Executes javascript code in the main window.
* @param {string} code
*/
const execJS = ( code ) => mainWnd.webContents.executeJavaScript( code );
/**
* @desc Executes a console logging operation.
* @param {string} str The output to the console.
*/
const log = ( str ) => {
if( options.verbose )
execJS( `console.log( '%c[SecureDiscord]%c ${str}', '${options.logColor}', '' );` );
};
/**
* @desc Logs a URL filtered operation.
* @param {string} path The path that was filtered.
*/
const logBlockedTracker = ( path ) => {
if( options.verbose )
execJS(
`console.log(
'%c[SecureDiscord]%c [%c✖%c] ${path}',
'${options.logColor}',
'',
'${options.warnColor}',
''
);`
);
};
/**
* @desc Parses a HOSTS file's raw data and returns all host name URIs in it.
* @param {string} data The raw string data.
* @return {string[]}
*/
const parseHosts = ( data ) => {
let result = [];
/* Remove all comments from the data and split into lines. */
data = data.replace( /#.*/g, '' ).split( /[\r\n]/ );
for( let i = 0; i < data.length; i++ ) {
/* Get the middle of the line by filtering the IP address. */
let md = ( /(\d+\.\d+\.\d+\.\d+)\s+(.+)/ ).exec( data[ i ] );
/* Skip invalid. */
if( !md )
continue;
/* Skip invalid results. */
if( md.length !== 3 )
continue;
/* Add to the array. */
result.push( md[ 2 ] )
}
return result;
};
/**
* @desc Downloads and adds all HOSTS files if required and builds the full blocking list.
*/
const buildBlockList = ( ) => {
/* Skip if not downloading additional hosts. */
if( !options.useAdditionalBlockList )
return;
/* Request each file defined in options. */
const request = require( 'request' );
for( let link of options.blockListURLs ) {
request.get(
link,
( error, response, data ) => {
/* Make sure no error occurred. */
if( error || response.statusCode !== 200 ) {
log( error || `Error downloading file: ${link} - Code ${response.statusCode}` );
return;
}
/* Gather all URLs in the hosts file. */
let result = parseHosts( data );
/* Add it to the filter list. */
if( result.length ) {
let oldLength = _filteredHosts.length;
/* Filter only the unique entries. */
_filteredHosts = _filteredHosts.concat( result ).filter( ( v, i, s ) => s.indexOf( v ) === i );
log( `Added ${_filteredHosts.length - oldLength} hosts to block list.` );
}
}
)
}
};
/**
* @desc Modifies, inserts or removes any particular headers according to the `headerInfo` defined above.
* @param {Object} request Request information defined by the Electron spec.
* @see https://electronjs.org/docs/api/web-request
*/
const modifyHeaders = ( request ) => {
try {
/* Skip encoded data URLs. */
if( request.url.indexOf( 'data:image/' ) !== -1 )
return;
/* Scan headers for removal or modification. */
for( let i in request.requestHeaders ) {
let v = options.headerInfo.modify[ i.toLowerCase() ];
if( v && request.requestHeaders[ i ] !== v )
request.requestHeaders[ i ] = v;
else if( options.headerInfo.remove.indexOf( i.toLowerCase() ) !== -1 )
delete request.requestHeaders[ i ];
}
/* Add any headers needed. */
for( let i in options.headerInfo.insert ) {
/* Determine if the header is already present in lowercase form. */
let _i = request.requestHeaders.hasOwnProperty( i.toLowerCase() ) ? i.toLowerCase() : i;
/* Skip if it already exists and the value is as expected. */
if( request.requestHeaders[ _i ] === options.headerInfo.insert[ i ] )
continue;
/* Add the header. */
request.requestHeaders[ _i ] = options.headerInfo.insert[ i ];
}
}
catch( ex ) {
log( `Exception: ${ex.toString()}` );
}
};
/**
* @desc Executes all patching necessary.
*/
try {
/* Patch the console. */
if( options.debug ) {
mainWnd.webContents.executeJavaScript( 'console.clear = () => { };' );
mainWnd.webContents.toggleDevTools();
}
/* Setup the header spoofing if required. */
if( options.spoofHeaders ) {
log( 'Setting up header patching.' );
mainWnd.webContents.setUserAgent( options.headerInfo.modify[ 'user-agent' ] );
mainWnd.webContents.setUserAgent = () => {
/* Ignore. */
};
mainWnd.webContents.session.webRequest.onBeforeSendHeaders(
[ options.targetURLs ],
( details, callback ) => {
modifyHeaders( details );
callback( { cancel: false, requestHeaders: details.requestHeaders } );
}
);
mainWnd.webContents.session.webRequest.onSendHeaders( [ options.targetURLs ], modifyHeaders );
}
/* Apply the proxy if necessary. */
if( options.useProxy ) {
log( 'Applying Proxy ...' );
mainWnd.webContents.session.setProxy(
{ proxyRules: `${options.proxyAddress}${options.fallbackToDirectConnection ? ',direct' : ''}` },
() => log( `Now routing all connections to: ${options.proxyAddress}` )
);
mainWnd.webContents.session.setProxy = () => {
/* Ignore. */
};
}
/* Filter tracking URLs if necessary. */
if( options.removeTrackingURLs ) {
/* Block specific tracking URLs. */
log( 'Blocking known tracking URLs' );
mainWnd.webContents.session.webRequest.onBeforeRequest( [ options.targetURLs ], ( details, callback ) => {
try {
/* Use the default block list. */
let filtered = _filteredHosts.filter( e => details.url.indexOf( e ) !== -1 ).length > 0;
/* Handle link tracking via external URLs if not filtered. */
let ext_tracking_pos;
if(
!filtered &&
( ext_tracking_pos = details.url.indexOf( options.urlTrackingPath ), ext_tracking_pos !== -1 )
) {
let part_url = details.url.substr( options.urlTrackingPath.length + ext_tracking_pos );
/* Scroll past the "/" identifier part. */
let link_pos = part_url.indexOf( '/' );
if( link_pos === -1 ) {
callback( { cancel: filtered } );
return;
}
part_url = part_url.substr( link_pos + 1 );
/* Make sure it begins with the "http" or "https" */
if( !( part_url.indexOf( 'https' ) === 0 || part_url.indexOf( 'http' ) === 0 ) ) {
callback( { cancel: filtered } );
return;
}
let is_https = !part_url.indexOf( 'https' );
/* Scroll past the "/" identifier part. */
link_pos = part_url.indexOf( '/' );
if( link_pos === -1 ) {
callback( { cancel: filtered } );
return;
}
part_url = part_url.substr( link_pos + 1 );
/* Build the final URL. */
let redirectURL = `${is_https ? 'https' : 'http'}://${part_url}`;
log( `Removed Tracker: ${redirectURL}` );
/* Do the redirect. */
callback( {
cancel: false,
redirectURL: redirectURL
} );
return;
}
if( filtered )
logBlockedTracker( details.url );
callback( { cancel: filtered } );
}
catch( ex ) {
log( `Exception: ${ex.toString()}` );
}
} );
/* Prevent redirect hooks that potentially re-add the tracker. */
mainWnd.webContents.session.webRequest.onBeforeRedirect = () => {
/* Ignored. */
};
/* Build the block list. */
buildBlockList();
log( typeof window );
}
}
catch( e ) {
log( `Exception occurred: ${e}` );
}
return mainWnd;
};