-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
346 lines (317 loc) · 11.3 KB
/
index.js
File metadata and controls
346 lines (317 loc) · 11.3 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
const Discord = require("discord.js")
const bot = new Discord.Client({
allowedMentions: {
repliedUser: false,
parse: ["users"]
},
failIfNotExists: false,
intents: [
Discord.GatewayIntentBits.Guilds
]
})
bot.login("<Token>")
const ems = require("enhanced-ms")({shortFormat: true})
const moment = require("moment")
require("moment-duration-format")
const speakeasy = require("@levminer/speakeasy")
const QRCode = require("qrcode")
const schedule = require("node-schedule")
const Enmap = require("enmap")
bot.mfa = new Enmap({
name: "mfa"
})
bot.mfasettings = new Enmap({
name: "mfasettings"
})
/*
{
id: "", // Role ID
time: 0, // Time in ms after which to remove the role - 0 = permanently
channels: [], // List of channels in which users can verify and get the role
roles: [] // List of roles needed to verify
}
*/
const defaultSettings = {
roles: {}
}
const botlinkrow = new Discord.ActionRowBuilder()
.addComponents(
new Discord.MessageButton()
.setLabel("Support server")
.setEmoji("712731848673067108")
.setURL("https://discord.gg/ZqzFUC8qe9")
.setStyle("LINK")
)
const confirmrow = new Discord.ActionRowBuilder()
.addComponents(
new Discord.MessageButton()
.setCustomId("2fa_setup_yes")
.setLabel("Continue")
.setStyle("DANGER")
)
.addComponents(
new Discord.MessageButton()
.setCustomId("2fa_setup_no")
.setLabel("Cancel")
.setStyle("SUCCESS")
)
const setupverifyrow = new Discord.ActionRowBuilder()
.addComponents(
new Discord.MessageButton()
.setCustomId("2fa_setup_verify")
.setLabel("Verify")
.setStyle("PRIMARY")
)
const verifymodal = new Discord.ModalBuilder()
.setCustomId("setup_confirm")
.setTitle("Confirm 2FA")
.addComponents(
new Discord.ActionRowBuilder()
.addComponents(
new Discord.TextInputBuilder()
.setCustomId("setup_code")
.setLabel("Enter your 2FA code")
.setStyle(Discord.TextInputStyle.Short)
.setPlaceholder("2FA code, e.g. 123456")
.setMinLength(6)
.setMaxLength(6)
)
)
const updateSlashcommands = () => {
bot.application.commands.set([
{
name: "help",
description: "Displays help and stats about the bot",
descriptionLocalizations: {
de: "Zeigt die Hilfe und Statistiken vom Bot an"
}
},{
name: "setup",
description: "Sets up 2FA",
descriptionLocalizations: {
de: "Richtet 2FA ein"
}
},{
name: "config",
description: "Modifies the config for the server",
descriptionLocalizations: {
de: "Ändert die Einstellungen für den Server"
},
defaultMemberPermissions: ["Administrator"],
integrationTypes: [0],
contexts: [0],
options: [{
name: "list",
type: Discord.ApplicationCommandOptionType.Subcommand,
description: "Displays the settings",
descriptionLocalizations: {
de: "Zeigt die Einstellungen an"
}
},{
name: "roleadd",
type: Discord.ApplicationCommandOptionType.Subcommand,
description: "Adds a new role",
descriptionLocalizations: {
de: "Fügt eine neue Rolle hinzu"
},
options: [{
name: "role",
type: Discord.ApplicationCommandOptionType.Role,
description: "The role",
descriptionLocalizations: {
de: "Die Rolle"
},
required: true
},{
name: "time",
type: Discord.ApplicationCommandOptionType.String,
description: "Die Zeit, nachdem die Rolle entfernt werden soll und der Nutzer sich neu authentifizieren muss",
maxLength: 50
}]
},{
name: "roleremove",
type: Discord.ApplicationCommandOptionType.Subcommand,
description: "Removes a verified role",
descriptionLocalizations: {
de: "Löscht eine Verifizierten-Rolle"
},
options: [{
name: "role",
type: Discord.ApplicationCommandOptionType.Role,
description: "The role",
descriptionLocalizations: {
de: "Die Rolle"
},
required: true
}]
}]
},{
name: "auth",
description: "Authenticates you",
descriptionLocalizations: {
de: "Authenfiziert dich"
},
integrationTypes: [0],
contexts: [0],
options: [{
name: "code",
type: Discord.ApplicationCommandOptionType.String,
description: "Der Code der Auth-App oder einer deiner Backupcodes",
required: true,
minLength: 6,
maxLength: 11
}]
}
])
}
schedule.scheduleJob("*/3 * * * *", () => { // Check every 3 minutes if a verification role's time is over
bot.mfa.forEach(user => {
if (!user.timers || user.timers.length == 0) return
const newtimers = []
user.timers.forEach(async timer => {
if (Date.now() >= timer.time) {
const member = await bot.guilds.cache.get(timer.guild).members.fetch(user.id)
member.roles.remove(timer.role)
} else newtimers.push(timer)
})
bot.mfa.set(user.id, newtimers, "timers")
})
})
bot.on("ready", () => {
updateSlashcommands()
bot.user.setPresence({activities: [{name: "/setup", type: Discord.ActivityType.Listening}]})
})
bot.on("guildCreate", guild => {
bot.mfasettings.ensure(guild.id, defaultSettings)
})
bot.on("guildDelete", guild => {
bot.mfasettings.delete(guild.id)
})
bot.on("interactionCreate", async interaction => {
if (interaction.type == Discord.InteractionType.ModalSubmit && interaction.customId == "2fa_setup_verify") {
const secret = bot.mfa.get(interaction.user.id, "tempsecret")
const verified = speakeasy.totp.verify({secret, token: Number.parseInt(interaction.fields.getTextInputValue("setup_code")), encoding: "base32", window: 1})
if (!verified) return interaction.reply({content: ":x: The code is invalid!", ephemeral: true})
const codes = [Math.random(), Math.random(), Math.random(), Math.random(), Math.random()].map(code => code.toString(36).slice(2))
bot.mfa.set(interaction.user.id, {
id: interaction.user.id,
secret,
backupCodes: codes,
timers: []
})
interaction.update({
content: "2FA wurde erfolgreich aktiviert!\n\nDies sind deine Backupcodes - sie sind die einzige Möglichkeit, " +
"2FA zu deaktivieren, solltest du dein Gerät verlieren! **Speichere sie an einem sicheren Ort.**",
files: [{
name: "2fabot_backupcodes.txt",
attachment: Buffer.from("2FA Bot Backupcodes\n" + codes.join("\n"), "utf8")
}],
embeds: [],
components: []
})
}
if (interaction.type != Discord.InteractionType.ApplicationCommand) return
const settings = bot.mfasettings.ensure(interaction.guild.id, defaultSettings)
if (interaction.commandName == "help") {
const embed = new Discord.MessageEmbed()
.setAuthor({name: "Bot-Info", iconURL: bot.user.displayAvatarURL()})
.addField("Server", "" + bot.guilds.cache.size, true)
.addField("Registered users", "" + bot.mfa.size, true)
.addField("Uptime", moment.duration(bot.uptime).format("D [Tage], H [Stunden], m [Minuten], s [Sekunden]"), true)
await interaction.reply({embeds: [embed], components: [botlinkrow]})
} else if (interaction.commandName == "config") {
if (interaction.options.getSubcommand(false) == "list") {
let text = ""
Object.keys(settings).forEach(key => {
text += key + ": " + JSON.stringify(settings[key]) + "\n"
})
const embed = new Discord.MessageEmbed()
.setDescription(text)
interaction.reply({embeds: [embed]})
} else if (interaction.options.getSubcommand(false) == "roleadd") {
const role = interaction.options.getRole("role")
const time = interaction.options.getString("time")
bot.mfasettings.push(interaction.guild.id, {
id: role.id,
time: time ? (ems(time) || 0) : 0,
channels: [], // Liste der Kanäle, in denen man sich verifizieren kann
roles: [] // Liste der Rollen, die man zum Verifizieren braucht
}, "roles")
if (bot.mfasettings.roles.some(r => r.id == role.id)) interaction.reply("The verification role <@&" + role.id + "> was edited!")
else interaction.reply("The role <@&" + role.id + "> was added as verification role!")
} else if (interaction.options.getSubcommand(false) == "roleremove") {
const findrole = interaction.options.getRole("role")
const newroles = []
Object.values(settings.roles).forEach(role => {
if (role.id != findrole.id) newroles.push(role)
})
if (newroles.length == Object.values(settings.roles).length) interaction.reply("The role <@&" + findrole.id + "> is not a verification role!")
else {
bot.mfasettings.set(interaction.guild.id, newroles, "roles")
interaction.reply("The verification role <@&" + findrole.id + "> was removed!")
}
}
} else if (interaction.commandName == "setup") {
if (bot.mfa.has(interaction.user.id)) {
const msg = await interaction.reply({
content: ":warning: Du hast bereits eine aktive Verifizierung! Wenn du fortfährst wird die alte Verifizierung ungültig.",
components: [confirmrow],
ephemeral: true,
fetchReply: true
})
const confirmbutton = await msg.awaitMessageComponent({time: 45000, componentType: Discord.ComponentType.Button})
if (confirmbutton.customId == "2fa_setup_no") return interaction.editReply({content: ":x: Cancelled.", components: []})
else await confirmbutton.deferUpdate()
}
const secret = speakeasy.generateSecret({name: interaction.user.tag, issuer: "2FA Bot"})
bot.mfa.set(interaction.user.id, secret.base32, "tempsecret")
QRCode.toDataURL(secret.otpauth_url.replace("2FA Bot", "2FA%20Bot") + "&algorithm=SHA1&digits=6&period=30", async (err, url) => {
const embed = new Discord.MessageEmbed()
.setAuthor({name: "2FA Setup", iconURL: bot.user.displayAvatarURL()})
.setDescription("Bitte scanne diesen QR-Code mit einer Authenticator-App ein.\n\nAlternativ kannst du auch \"Zeitbasiert\" " +
"auswählen und folgendes Secret angeben:\n||**`" + secret.base32 + "`**||")
.setImage("attachment://qrcode.png")
if (interaction.replied) await interaction.editReply({
content: null,
embeds: [embed],
files: [{
name: "qrcode.png",
attachment: new Buffer.from(url.split(",")[1], "base64"),
description: "2FA-QR-Code"
}],
components: [setupverifyrow],
ephemeral: true
})
else await interaction.reply({
embeds: [embed],
files: [{
name: "qrcode.png",
attachment: new Buffer.from(url.split(",")[1], "base64"),
description: "2FA-QR-Code"}],
components: [setupverifyrow],
ephemeral: true
})
const msg = await interaction.fetchReply()
const collector = msg.createMessageComponentCollector({time: 120000, componentType: Discord.ComponentType.Button})
collector.on("collect", async i => {
i.showModal(verifymodal)
})
})
} else if (interaction.commandName == "auth") {
const user = bot.mfa.get(interaction.user.id)
if (!user) return interaction.reply({content: "You dont have an account! Create one using `/setup`.", ephemeral: true})
if (interaction.options.getString("code").toString().length != 6) return interaction.reply({content: "The code must be 6 characters long!", ephemeral: true})
const verified = speakeasy.totp.verify({secret: user.secret, token: interaction.options.getString("code"), encoding: "base32", window: 1})
if (!verified) return interaction.reply({content: ":x: Invalid code!", ephemeral: true})
interaction.reply({content: ":white_check_mark: You were verified successfully!", ephemeral: true})
Object.values(settings.roles).forEach(role => {
interaction.member.roles.add(role.id)
if (role.time > 0)
bot.mfa.push(interaction.user.id, {
role: role.id,
guild: interaction.guild.id,
time: Date.now() + role.time
}, "timers")
})
}
})