-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
AccountSwitcher.plugin.js
executable file
·581 lines (561 loc) · 22.8 KB
/
AccountSwitcher.plugin.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
/**
* @name AccountSwitcher
* @displayName AccountSwitcher
* @source https://github.com/l0c4lh057/AccountSwitcher/blob/master/AccountSwitcher.plugin.js
* @patreon https://www.patreon.com/l0c4lh057
* @authorId 226677096091484160
* @invite YzzeuJPpyj
*/
/**
@if (@_jscript)
// Offer to self-install for clueless users that try to run this directly.
var shell = WScript.CreateObject("WScript.Shell");
var fs = new ActiveXObject("Scripting.FileSystemObject");
var pathPlugins = shell.ExpandEnvironmentStrings("%APPDATA%\BetterDiscord\plugins");
var pathSelf = WScript.ScriptFullName;
// Put the user at ease by addressing them in the first person
shell.Popup("It looks like you've mistakenly tried to run me directly. \n(Don't do that!)", 0, "I'm a plugin for BetterDiscord", 0x30);
if (fs.GetParentFolderName(pathSelf) === fs.GetAbsolutePathName(pathPlugins)) {
shell.Popup("I'm in the correct folder already.", 0, "I'm already installed", 0x40);
} else if (!fs.FolderExists(pathPlugins)) {
shell.Popup("I can't find the BetterDiscord plugins folder.\nAre you sure it's even installed?", 0, "Can't install myself", 0x10);
} else if (shell.Popup("Should I copy myself to BetterDiscord's plugins folder for you?", 0, "Do you need some help?", 0x34) === 6) {
fs.CopyFile(pathSelf, fs.BuildPath(pathPlugins, fs.GetFileName(pathSelf)), true);
// Show the user where to put plugins in the future
shell.Exec("explorer " + pathPlugins);
shell.Popup("I'm installed!", 0, "Successfully installed", 0x40);
}
WScript.Quit();
*/
module.exports = (() => {
const config = {
info: {
name: "AccountSwitcher",
authors: [
{
name: "l0c4lh057",
discord_id: "226677096091484160",
github_username: "l0c4lh057",
twitter_username: "l0c4lh057"
}
],
version: "1.3.5",
description: "Simply switch between accounts with the ease of pressing a single key.",
github: "https://github.com/l0c4lh057/AccountSwitcher",
github_raw: "https://raw.githubusercontent.com/l0c4lh057/AccountSwitcher/master/AccountSwitcher.plugin.js"
},
changelog: [
{
title: "Fixed",
type: "fixed",
items: ["Disabling encryption doesn't crash discord anymore."]
},
{
title: "New",
type: "added",
items: ["Now Alt+Click opens the switch menu too, not only MB2 click."]
}
]
};
let password = null;
const algorithm = "aes-256-cbc";
const IV_LENGTH = 16;
const Buffer = require("buffer").Buffer;
return !global.ZeresPluginLibrary ? class {
constructor(){ this._config = config; }
getName(){ return config.info.name; }
getAuthor(){ return config.info.authors.map(a => a.name).join(", "); }
getDescription(){ return config.info.description + " **Install [ZeresPluginLibrary](https://betterdiscord.app/Download?id=9) and restart discord to use this plugin!**"; }
getVersion(){ return config.info.version; }
load(){
BdApi.showConfirmationModal("Library plugin is needed",
[`The library plugin needed for ${config.info.name} is missing. Please click Download Now to install it.`], {
confirmText: "Download",
cancelText: "Cancel",
onConfirm: () => {
require("request").get("https://rauenzi.github.io/BDPluginLibrary/release/0PluginLibrary.plugin.js", async (error, response, body) => {
if (error) return require("electron").shell.openExternal("https://betterdiscord.net/ghdl?url=https://raw.githubusercontent.com/rauenzi/BDPluginLibrary/master/release/0PluginLibrary.plugin.js");
await new Promise(r => require("fs").writeFile(require("path").join(BdApi.Plugins.folder, "0PluginLibrary.plugin.js"), body, r));
});
}
});
}
start(){}
stop(){}
} : (([Plugin, Api]) => {
const plugin = (Plugin, Api) => {
const { WebpackModules, PluginUtilities, DiscordModules, Settings, Toasts, Modals, DOMTools } = Api;
const { React, ReactDOM, UserStore, UserInfoStore } = DiscordModules;
const AccountManager = WebpackModules.getByProps("loginToken");
const unregisterKeybind = WebpackModules.getByProps("inputEventUnregister").inputEventUnregister.bind(WebpackModules.getByProps("inputEventUnregister"));
const registerKeybind = WebpackModules.getByProps("inputEventRegister").inputEventRegister.bind(WebpackModules.getByProps("inputEventUnregister"));
const crypto = require("crypto");
if(!BdApi.Plugins.get("BugReportHelper") && !BdApi.getData(config.info.name, "didShowIssueHelperPopup")){
BdApi.saveData(config.info.name, "didShowIssueHelperPopup", true);
BdApi.showConfirmationModal("Do you want to download a helper plugin?",
[`Do you want to download a helper plugin that makes it easier for you to report issues? That plugin is not needed to anything else to function correctly but nice to have when reporting issues, shortening the time until the problem gets resolved by asking you for specific information and also including additional information you did not provide.`],
{
confirmText: "Download",
cancelText: "Cancel",
onConfirm: () => {
require("request").get("https://raw.githubusercontent.com/l0c4lh057/BetterDiscordStuff/master/Plugins/BugReportHelper/BugReportHelper.plugin.js", (error, response, body) => {
if (error) return require("electron").shell.openExternal("https://betterdiscord.net/ghdl?url=https://raw.githubusercontent.com/l0c4lh057/BetterDiscordStuff/master/Plugins/BugReportHelper/BugReportHelper.plugin.js");
else require("fs").writeFile(require("path").join(BdApi.Plugins.folder, "BugReportHelper.plugin.js"), body, ()=>{
window.setTimeout(()=>BdApi.Plugins.enable("BugReportHelper"), 1000);
});
});
}
}
);
}
const KeyRecorder = class KeyRecorder extends WebpackModules.getByDisplayName("KeyRecorder") {
render() {
const ButtonOptions = WebpackModules.getByProps("ButtonLink");
const Button = ButtonOptions.default;
const ret = super.render();
ret.props.children.props.children.props.children.push(
React.createElement(
DiscordModules.FlexChild,
{
style: { margin: 0 }
},
React.createElement(
Button,
{
className: WebpackModules.getByProps("editIcon", "button").button.split(" ")[1],
size: Button.Sizes.MIN,
color: ButtonOptions.ButtonColors.GREY,
look: ButtonOptions.ButtonLooks.GHOST,
onClick: this.props.onRemove
},
"Remove"
)
)
);
return ret;
}
};
const KeybindModule = class KeybindModule extends DiscordModules.Keybind {
constructor(props) {
super(props);
}
render() {
const ret = super.render();
ret.type = KeyRecorder;
ret.props.account = this.props.account;
ret.props.onRemove = this.props.onRemove;
return ret;
}
};
const Keybind = class Keybind extends Settings.SettingField {
constructor(account, onChange, onRemove) {
super(account.name + " (" + account.id + ")", "", onChange, KeybindModule, {
defaultValue: (account.keybind[0] !== -1 && account.keybind.map(a => [0, a])) || [],
onChange: element => value => {
if (!Array.isArray(value)) return;
element.props.value = value;
this.onChange(value.map(a => a[1]));
},
account,
onRemove
});
}
};
return class AccountSwitcher extends Plugin {
updateAvatars(){
this.settings.accounts.forEach(acc => {
const u = UserStore.getUser(acc.id);
if(u) acc.avatar = u.getAvatarURL(null, 128, true);
})
}
onStart(){
password = null;
this.loadSettings();
if(this.settings.salt === undefined){
this.settings.salt = crypto.randomBytes(32).toString("base64");
}
this.settings.accounts.forEach(acc => this.registerKeybind(acc));
this.openMenu = this.openMenu.bind(this);
PluginUtilities.addStyle("accountswitcher-style", `
.accountswitcher-switchmenu {
position: fixed;
width: auto;
height: auto;
background-color: #202225;
border-radius: 10px;
overflow: hidden;
z-index: 1000;
}
.accountswitcher-accountwrapper {
position: relative;
display: inline-block;
margin: 10px;
width: 64px;
height: 64px;
}
.accountswitcher-menuavatar {
width: 64px;
height: 64px;
}
.accountswitcher-removeaccount {
position: absolute;
top: -4px;
right: -4px;
background-color: #111;
width: 1em;
height: 1em;
border-radius: 0.5em;
color: #ccc;
text-align: center;
border: 2px solid #444;
}
.accountswitcher-settingsbtnwrapper {
right: 0;
position: absolute;
}
`);
document.addEventListener("mouseup", this.openMenu);
document.addEventListener("click", this.openMenu, {capture: true});
this.updateAvatars();
if(this.settings.encryptionVersion !== 2){
if(!this.settings.encrypted){
this.settings.accounts.forEach(acc => {
acc.token = this.encryptUpdated(this.decryptDeprecated(acc.token, acc.id), acc.id);
});
this.settings.encryptionVersion = 2;
this.saveSettings();
}else{
this.requirePassword("The encryption algorithm got updated for better security. Please enter your password to decrypt your tokens and encrypt them again with the new algorithm.").then(()=>{
this.settings.encTest = this.encryptUpdated("test", password);
this.settings.accounts.forEach(acc => {
acc.token = this.encryptUpdated(this.encryptUpdated(this.decryptDeprecated(this.decryptDeprecated(acc.token, password), acc.id), acc.id), password);
});
this.settings.encryptionVersion = 2;
this.saveSettings();
});
}
}
}
onStop(){
this.settings.accounts.forEach(acc => this.unregisterKeybind(acc));
document.removeEventListener("mouseup", this.openMenu);
document.removeEventListener("click", this.openMenu, {capture: true});
PluginUtilities.removeStyle("accountswitcher-style");
}
get defaultSettings(){
return {
accounts: [],
encrypted: false,
encTest: "test",
pluginsToRestart: ["AccountDetailsPlus", "AutoStartRichPresence"],
encryptionVersion: 1
}
}
openMenu(e){
if(!(e.type === "mouseup" && e.which === 2) && !(e.type === "click" && e.which === 1 && e.altKey)) return;
if(!e.target || !e.target.classList) return;
if(!e.target.classList.contains(WebpackModules.getByProps("avatar", "container", "nameTag").avatar.split(" ")[0])) return;
e.preventDefault();
e.stopPropagation();
const menu = document.createElement("div");
const AccountPanel = account=>React.createElement(
"div",
{
className: "accountswitcher-accountwrapper"
},
React.createElement("img", {
src: account.avatar,
className: "accountswitcher-menuavatar",
onClick: e=>this.login(account)
}),
React.createElement("div", {
className: "accountswitcher-removeaccount",
onClick: e=>{
this.unregisterKeybind(account);
this.settings.accounts = this.settings.accounts.filter(acc => acc.id != account.id);
this.saveSettings();
Toasts.show("Account " + account.name + " removed", {type: Toasts.ToastTypes.success});
}
}, "⨯")
);
if(this.settings.accounts.length > 0){
const offset = DOMTools.offset(e.target);
ReactDOM.render(React.createElement(
"div",
{
className: "accountswitcher-switchmenu",
style: {
bottom: (offset.bottom - offset.top + 27),
left: (offset.left - 5)
}
},
this.settings.accounts.map(account=>React.createElement(AccountPanel, account))
), menu);
document.body.appendChild(menu);
}else{
Toasts.show("No accounts to display", {type: Toasts.ToastTypes.warning});
}
const eventHandler = ev=>{
if(!ev.target || !ev.target.classList) return;
if(!ev.target.classList.contains("accountswitcher-switchmenu") && !ev.target.classList.contains("accountswitcher-removeaccount")){
menu.remove();
document.removeEventListener(eventHandler);
}
};
document.addEventListener("click", eventHandler);
}
login(account){
console.log("Logging in as " + account.name);
if(account.id == UserStore.getCurrentUser().id) return Toasts.show("Already using account " + account.name, {type: Toasts.ToastTypes.warning});
console.log("Logging in as " + account.name);
this.requirePassword().then(r => {
const token = password == null ? account.token : this.decrypt(account.token, password);
AccountManager.loginToken(this.decrypt(token, account.id));
window.setTimeout(this.updateAvatars, 5000);
this.settings.pluginsToRestart.forEach(pl => {
if(BdApi.Plugins.isEnabled(pl)){
BdApi.Plugins.disable(pl);
window.setTimeout(()=>BdApi.Plugins.enable(pl), 5000);
}
});
});
}
getSettingsPanel(){
const panel = document.createElement("div");
panel.className = "form";
panel.style = "width:100%;"
const accountsField = new Settings.SettingGroup("Accounts", {shown:true});
const addAccount = account=>{
if(!account){
let u = UserStore.getCurrentUser();
let t = this.encrypt(UserInfoStore.getToken(), u.id);
let acc = {
name: u.tag,
id: u.id,
avatar: u.getAvatarURL(null, 128, true),
keybind: [64, 10+this.settings.accounts.length],
token: this.settings.encrypted ? this.encrypt(t, password) : t
};
this.settings.accounts.push(acc);
this.saveSettings();
this.registerKeybind(acc);
return addAccount(acc);
}
const kbPanel = new Keybind(account, keybind => {
this.unregisterKeybind(account);
account.keybind = keybind;
this.saveSettings();
this.registerKeybind(account);
}, ()=>{
this.unregisterKeybind(account);
this.settings.accounts = this.settings.accounts.filter(acc => acc.id != account.id);
this.saveSettings();
// TODO: remove account from DOM so you are not required to repopen the settings
Toasts.show("Account " + account.name + " got removed. After reopening the settings it will also be gone from this list.", {type: Toasts.ToastTypes.success});
});
accountsField.append(kbPanel);
};
const addAccountButton = document.createElement("button");
// TODO: remove hardcoded classes
addAccountButton.className = "button-38aScr lookFilled-1Gx00P colorBrand-3pXr91 sizeMedium-1AC_Sl grow-q77ONN";
addAccountButton.addEventListener("click", ()=>{
if(this.settings.accounts.some(acc => acc.id == UserStore.getCurrentUser().id)){
return Toasts.show("You already saved this account", {type: Toasts.ToastTypes.error});
}
this.requirePassword().then(r => {
addAccount();
})
});
addAccountButton.innerText = "Save Account";
const logoutButton = document.createElement("button");
logoutButton.className = addAccountButton.className;
logoutButton.addEventListener("click", ()=>{
AccountManager.loginToken("");
});
logoutButton.innerText = "Log out to add another account";
new Settings.SettingGroup(this.getName(), {shown:true}).appendTo(panel)
.append(
new Settings.Switch("Encrypt tokens", "Encrypting tokens makes sure that nobody will be able to get the tokens without knowing the password.", this.settings.encrypted, checked => {
if(checked === this.settings.encrypted) return;
if(checked){
const retry = ()=>{
let pw1 = "";
let pw2 = "";
Modals.showModal("Set password", React.createElement("div", {},
React.createElement("input", {
type: "password",
placeholder: "Password",
onChange: e=>{pw1 = e.target.value;}
}),
React.createElement("input", {
type: "password",
placeholder: "Repeat password",
onChange: e=>{pw2 = e.target.value;}
})
), {
onConfirm: ()=>{
if(pw1 != pw2){
Toasts.show("Passwords don't match", {type: Toasts.ToastTypes.error});
return retry();
}
password = pw1;
this.settings.encrypted = true;
this.settings.encTest = this.encrypt("test", password);
this.settings.accounts.forEach(acc => acc.token = this.encrypt(acc.token, password));
this.saveSettings();
}
});
}
retry();
}else{
const retry = ()=>{
let pw = "";
Modals.showModal("Disable encryption", React.createElement("div", {},
React.createElement("div", {className: "colorStandard-2KCXvj"}, "Are you sure that you want to disable encryption? To verify please input your current password. You can also choose the 'Forgot Password' option which will remove all saved accounts. To abort just click outside of this popout."),
React.createElement("input", {
type: "password",
placeholder: "Password",
onChange: e=>{pw = e.target.value;}
})
), {
onConfirm: ()=>{
try {
if(this.decrypt(this.settings.encTest, pw) !== "test"){
Toasts.show("Passwords incorrect", {type: Toasts.ToastTypes.error});
return retry();
}
this.settings.encrypted = false;
this.settings.encTest = "test";
this.settings.accounts.forEach(acc => acc.token = this.decrypt(acc.token, pw))
password = null;
this.saveSettings();
}catch(ex){
Toasts.show("Passwords incorrect", {type: Toasts.ToastTypes.error});
return retry();
}
},
onCancel: ()=>{
Modals.showConfirmationModal("Are you sure?", "You are about to disable encryption which will remove all your currently saved accounts without an option to recover them. Only use this if you really forgot your password.", {
onConfirm: ()=>{
this.settings.encTest = "test";
this.settings.encrypted = false;
this.settings.accounts = [];
password = null;
this.saveSettings();
}
});
},
confirmText: "Disable encryption",
cancelText: "Forgot Password"
});
};
retry();
}
})
)
.append(accountsField)
.append(addAccountButton)
.append(
new Settings.Textbox("Plugins to restart", "Put the name of all plugins that should get restarted when you switch accounts in this textbox separated by a comma", this.settings.pluginsToRestart.join(","), val=>{
this.settings.pluginsToRestart = val.split(",").map(x=>x.trim()).filter(x=>x);
this.saveSettings();
})
)
.append(logoutButton);
this.settings.accounts.forEach(acc => addAccount(acc));
return panel;
}
// This function does NOT return the password, it just ensures that the correct password is stored in the "password" variable.
// The password should never be exposed so there should be no way to access the password from outside this plugin.
async requirePassword(message){
if(!this.settings.encrypted || password !== null) return Promise.resolve();
return new Promise((resolve, reject) => {
const retry = t=>{
let pw = "";
Modals.showModal("Password required", React.createElement(
React.Fragment,
!message ? null : message,
!message ? null : React.createElement("br"),
React.createElement(
"input",
{
type: "password",
ref: e=>{if(e)setTimeout(()=>e.focus(),500)},
onKeyDown: e=>{if(e.keyCode===13)e.target.parentNode.nextSibling.children[0].click()},
onChange: e=>{pw = e.target.value;}
}
)
), {
onConfirm: ()=>{
try{
if(this.decrypt(this.settings.encTest, pw) !== "test"){
Toasts.show("Wrong password", {type: Toasts.ToastTypes.error});
return retry(t+1);
}
password = pw;
resolve();
}catch(ex){
Toasts.show("Wrong password", {type: Toasts.ToastTypes.error});
retry(t+1);
}
}
})
};
retry(0);
});
}
encryptDeprecated(text, pw){
const key = crypto.createCipher("aes-128-cbc", pw);
return key.update(text, "utf8", "hex") + key.final("hex");
}
decryptDeprecated(text, pw){
const key = crypto.createDecipher("aes-128-cbc", pw);
return key.update(text, "hex", "utf8") + key.final("utf8");
}
generateEncryptionKey(pw){
return crypto.pbkdf2Sync(Buffer.from(pw, "utf8"), this.settings.salt, 100000, 32, "sha512");
}
encryptUpdated(text, pw){
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(algorithm, this.generateEncryptionKey(pw), iv);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return iv.toString("base64") + ":" + encrypted.toString("base64");
}
decryptUpdated(text, pw){
const parts = text.split(":");
const iv = Buffer.from(parts.shift(), "base64");
const encrypted = Buffer.from(parts.join(":"), "base64");
const decipher = crypto.createDecipheriv(algorithm, this.generateEncryptionKey(pw), iv);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return decrypted.toString();
}
encrypt(text, pw){
return this.settings.encryptionVersion === 2 ? this.encryptUpdated(text, pw) : this.encryptDeprecated(text, pw);
}
decrypt(text, pw){
return this.settings.encryptionVersion === 2 ? this.decryptUpdated(text, pw) : this.decryptDeprecated(text, pw);
}
registerKeybind(account){
registerKeybind("119" + account.id, account.keybind.map(a=>[0,a]), pressed => {
this.login(account);
}, {blurred: false, focused: true, keydown: true, keyup: false});
}
unregisterKeybind(account){
unregisterKeybind("119" + account.id);
}
loadSettings(){
this.settings = PluginUtilities.loadSettings(this.getName(), this.defaultSettings);
if(!Array.isArray(this.settings.accounts)) this.settings.accounts = Object.values(this.settings.accounts);
this.settings.accounts.forEach(acc => {
if(!Array.isArray(acc.keybind)) acc.keybind = Object.values(acc.keybind);
});
}
saveSettings(){
PluginUtilities.saveSettings(this.getName(), this.settings);
}
}
};
return plugin(Plugin, Api);
})(global.ZeresPluginLibrary.buildPlugin(config));
})();
/*@end*/