index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. const http = require('http');
  2. const crypto = require('crypto');
  3. const cheerio = require('cheerio');
  4. const {defaultPermissions} = require('../util/default.json');
  5. const sqlite3 = require('sqlite3').verbose();
  6. const mode = ( process.env.READONLY ? sqlite3.OPEN_READONLY : sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE );
  7. const db = new sqlite3.Database( './wikibot.db', mode, dberror => {
  8. if ( dberror ) {
  9. console.log( '- Dashboard: Error while connecting to the database: ' + dberror );
  10. return dberror;
  11. }
  12. console.log( '- Dashboard: Connected to the database.' );
  13. } );
  14. const DiscordOauth2 = require('discord-oauth2');
  15. const oauth = new DiscordOauth2( {
  16. clientId: process.env.bot,
  17. clientSecret: process.env.secret,
  18. redirectUri: process.env.dashboard
  19. } );
  20. const fs = require('fs');
  21. const files = {
  22. index: fs.readFileSync('./dashboard/index.html'),
  23. login: fs.readFileSync('./dashboard/login.html')
  24. }
  25. /**
  26. * @type {Map<Number, PromiseConstructor>}
  27. */
  28. var messages = new Map();
  29. var messageId = 1;
  30. process.on( 'message', message => {
  31. if ( message.id ) {
  32. if ( message.data.error ) messages.get(message.id).reject(message.data.error);
  33. else messages.get(message.id).resolve(message.data.response);
  34. return messages.delete(message.id);
  35. }
  36. console.log( '- [Dashboard]: Message received!', message );
  37. } );
  38. /**
  39. * Send messages to the manager.
  40. * @param {Object} [message] - The message.
  41. * @returns {Promise<Object>}
  42. */
  43. function sendMsg(message) {
  44. var id = messageId++;
  45. var promise = new Promise( (resolve, reject) => {
  46. messages.set(id, {resolve, reject});
  47. process.send( {id, data: message} );
  48. } );
  49. return promise;
  50. }
  51. /**
  52. * @typedef Settings
  53. * @property {String} state
  54. * @property {String} access_token
  55. * @property {User} user
  56. * @property {Object} guilds
  57. * @property {Map<String, Guild>} guilds.isMember
  58. * @property {Map<String, Guild>} guilds.notMember
  59. */
  60. /**
  61. * @typedef User
  62. * @property {String} id
  63. * @property {String} username
  64. * @property {String} discriminator
  65. * @property {String} avatar
  66. * @property {String} locale
  67. */
  68. /**
  69. * @typedef Guild
  70. * @property {String} id
  71. * @property {String} name
  72. * @property {String} acronym
  73. * @property {String} [icon]
  74. * @property {String} permissions
  75. */
  76. /**
  77. * @type {Map<String, Settings>}
  78. */
  79. var settingsData = new Map();
  80. const server = http.createServer((req, res) => {
  81. if ( req.method !== 'GET' ) {
  82. let notice = '<img width="400" src="https://http.cat/418"><br><strong>' + http.STATUS_CODES[418] + '</strong>';
  83. res.writeHead(418, {'Content-Length': notice.length});
  84. res.write( notice );
  85. return res.end();
  86. }
  87. if ( req.url === '/favicon.ico' ) {
  88. res.writeHead(302, {Location: 'https://cdn.discordapp.com/avatars/461189216198590464/f69cdc197791aed829882b64f9760dbb.png?size=64'});
  89. return res.end();
  90. }
  91. res.setHeader('Content-Type', 'text/html');
  92. res.setHeader('Content-Language', ['en']);
  93. var lastGuild = req.headers?.cookie?.split('; ')?.filter( cookie => {
  94. return cookie.split('=')[0] === 'guild';
  95. } )?.map( cookie => cookie.replace( /^guild="(\w+)"$/, '$1' ) )?.join();
  96. if ( lastGuild ) res.setHeader('Set-Cookie', [`guild="${lastGuild}"; Max-Age=0; HttpOnly; Path=/`]);
  97. var state = req.headers.cookie?.split('; ')?.filter( cookie => {
  98. return cookie.split('=')[0] === 'wikibot';
  99. } )?.map( cookie => cookie.replace( /^wikibot="(\w+(?:-\d+)?)"$/, '$1' ) )?.join();
  100. var reqURL = new URL(req.url, process.env.dashboard);
  101. if ( reqURL.pathname === '/login' ) {
  102. if ( settingsData.has(state) ) {
  103. res.writeHead(302, {Location: '/'});
  104. return res.end();
  105. }
  106. if ( state ) res.setHeader('Set-Cookie', [`wikibot="${state}"; Max-Age=0; HttpOnly`]);
  107. var $ = cheerio.load(files.login);
  108. $('.guild#invite a').attr('href', oauth.generateAuthUrl( {
  109. scope: ['identify', 'guilds', 'bot'],
  110. permissions: defaultPermissions, state
  111. } ));
  112. let responseCode = 200;
  113. if ( reqURL.searchParams.get('action') === 'failed' ) {
  114. responseCode = 400;
  115. $('replace#notice').replaceWith(`<div class="notice">
  116. <b>Login failed!</b>
  117. <div>An error occurred while logging you in, please try again.</div>
  118. </div>`);
  119. }
  120. if ( reqURL.searchParams.get('action') === 'unauthorized' ) {
  121. responseCode = 401;
  122. $('replace#notice').replaceWith(`<div class="notice">
  123. <b>Not logged in!</b>
  124. <div>Please login before you can change any settings.</div>
  125. </div>`);
  126. }
  127. if ( reqURL.searchParams.get('action') === 'logout' ) {
  128. $('replace#notice').replaceWith(`<div class="notice">
  129. <b>Successfully logged out!</b>
  130. <div>You have been successfully logged out. To change any settings you need to login again.</div>
  131. </div>`);
  132. }
  133. $('replace#notice').replaceWith('');
  134. state = crypto.randomBytes(16).toString("hex");
  135. while ( settingsData.has(state) ) {
  136. state = crypto.randomBytes(16).toString("hex");
  137. }
  138. let url = oauth.generateAuthUrl( {
  139. scope: ['identify', 'guilds'],
  140. prompt: 'none', state
  141. } );
  142. $('replace#text').replaceWith(`<a href="${url}">Login</a>`);
  143. let notice = $.html();
  144. res.writeHead(responseCode, {
  145. 'Set-Cookie': [`wikibot="${state}"; HttpOnly`],
  146. 'Content-Length': notice.length
  147. });
  148. res.write( notice );
  149. return res.end();
  150. }
  151. if ( reqURL.pathname === '/logout' ) {
  152. settingsData.delete(state);
  153. res.writeHead(302, {
  154. Location: '/login?action=logout',
  155. 'Set-Cookie': [`wikibot="${state}"; Max-Age=0; HttpOnly`]
  156. });
  157. return res.end();
  158. }
  159. if ( !state ) {
  160. res.writeHead(302, {
  161. Location: ( reqURL.pathname === '/' ? '/login' : '/login?action=unauthorized' )
  162. });
  163. return res.end();
  164. }
  165. if ( reqURL.pathname === '/oauth' ) {
  166. if ( settingsData.has(state) ) {
  167. res.writeHead(302, {Location: '/'});
  168. return res.end();
  169. }
  170. if ( state !== reqURL.searchParams.get('state') || !reqURL.searchParams.get('code') ) {
  171. res.writeHead(302, {Location: '/login?action=unauthorized'});
  172. return res.end();
  173. }
  174. return oauth.tokenRequest( {
  175. scope: ['identify', 'guilds'],
  176. code: reqURL.searchParams.get('code'),
  177. grantType: 'authorization_code'
  178. } ).then( ({access_token}) => {
  179. return Promise.all([
  180. oauth.getUser(access_token),
  181. oauth.getUserGuilds(access_token)
  182. ]).then( ([user, guilds]) => {
  183. guilds = guilds.filter( guild => {
  184. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  185. } ).map( guild => {
  186. return {
  187. id: guild.id,
  188. name: guild.name,
  189. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  190. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  191. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) + '?size=128' : null ),
  192. permissions: guild.permissions
  193. };
  194. } );
  195. sendMsg( {
  196. type: 'isMemberAll',
  197. guilds: guilds.map( guild => guild.id )
  198. } ).then( response => {
  199. let isMember = new Map();
  200. let notMember = new Map();
  201. response.forEach( (guild, i) => {
  202. if ( guild ) isMember.set(guilds[i].id, guilds[i]);
  203. else notMember.set(guilds[i].id, guilds[i]);
  204. } );
  205. settingsData.set(`${state}-${user.id}`, {
  206. state: `${state}-${user.id}`,
  207. access_token,
  208. user: {
  209. id: user.id,
  210. username: user.username,
  211. discriminator: user.discriminator,
  212. avatar: 'https://cdn.discordapp.com/' + ( user.avatar ?
  213. `avatars/${user.id}/${user.avatar}.` +
  214. ( user.avatar.startsWith( 'a_' ) ? 'gif' : 'png' ) :
  215. `embed/avatars/${user.discriminator % 5}.png` ) + '?size=64',
  216. locale: user.locale
  217. },
  218. guilds: {isMember, notMember}
  219. });
  220. res.writeHead(302, {
  221. Location: ( lastGuild ? '/guild/' + lastGuild : '/' ),
  222. 'Set-Cookie': [
  223. `wikibot="${state}"; Max-Age=0; HttpOnly`,
  224. `wikibot="${state}-${user.id}"; HttpOnly`
  225. ]
  226. });
  227. return res.end();
  228. }, error => {
  229. console.log( '- Dashboard: Error while checking the guilds:', error );
  230. res.writeHead(302, {Location: '/login?action=failed'});
  231. return res.end();
  232. } );
  233. }, error => {
  234. console.log( '- Dashboard: Error while getting user and guilds: ' + error );
  235. res.writeHead(302, {Location: '/login?action=failed'});
  236. return res.end();
  237. } );
  238. }, error => {
  239. console.log( '- Dashboard: Error while getting the token: ' + error );
  240. res.writeHead(302, {Location: '/login?action=failed'});
  241. return res.end();
  242. } );
  243. }
  244. if ( !settingsData.has(state) ) {
  245. res.writeHead(302, {
  246. Location: ( reqURL.pathname === '/' ? '/login' : '/login?action=unauthorized' )
  247. });
  248. return res.end();
  249. }
  250. var settings = settingsData.get(state);
  251. if ( reqURL.pathname === '/refresh' ) {
  252. return oauth.getUserGuilds(settings.access_token).then( guilds => {
  253. guilds = guilds.filter( guild => {
  254. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  255. } ).map( guild => {
  256. return {
  257. id: guild.id,
  258. name: guild.name,
  259. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  260. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  261. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) + '?size=128' : null ),
  262. permissions: guild.permissions
  263. };
  264. } );
  265. sendMsg( {
  266. type: 'isMemberAll',
  267. guilds: guilds.map( guild => guild.id )
  268. } ).then( response => {
  269. let isMember = new Map();
  270. let notMember = new Map();
  271. response.forEach( (guild, i) => {
  272. if ( guild ) isMember.set(guilds[i].id, guilds[i]);
  273. else notMember.set(guilds[i].id, guilds[i]);
  274. } );
  275. settings.guilds = {isMember, notMember};
  276. res.writeHead(302, {
  277. Location: ( reqURL.searchParams.get('return') || '/' )
  278. });
  279. return res.end();
  280. }, error => {
  281. console.log( '- Dashboard: Error while checking refreshed guilds:', error );
  282. res.writeHead(302, {Location: '/login?action=failed'});
  283. return res.end();
  284. } );
  285. }, error => {
  286. console.log( '- Dashboard: Error while refreshing guilds: ' + error );
  287. res.writeHead(302, {Location: '/login?action=failed'});
  288. return res.end();
  289. } );
  290. }
  291. var $ = cheerio.load(files.index);
  292. $('replace#notice').replaceWith('');
  293. $('.navbar #logout img').attr('src', settings.user.avatar);
  294. $('.navbar #logout span').text(`${settings.user.username} #${settings.user.discriminator}`);
  295. $('.guild#invite a').attr('href', oauth.generateAuthUrl( {
  296. scope: ['identify', 'guilds', 'bot'],
  297. permissions: defaultPermissions, state
  298. } ));
  299. $('.guild#refresh a').attr('href', '/refresh?return=' + reqURL.pathname);
  300. let guilds = '';
  301. if ( settings.guilds.isMember.size ) {
  302. guilds += `<div class="guild">
  303. <div class="separator"></div>
  304. </div>`;
  305. settings.guilds.isMember.forEach( guild => {
  306. guilds += `<div class="guild" id="${guild.id}">
  307. <div class="bar"></div>
  308. <a href="/guild/${guild.id}" alt="${guild.name}">` + ( guild.icon ?
  309. `<img class="avatar" src="${guild.icon}" alt="${guild.acronym}" width="48" height="48">`
  310. : `<div class="avatar noicon">${guild.acronym}</div>` ) +
  311. `</a>
  312. </div>`;
  313. } );
  314. }
  315. if ( settings.guilds.notMember.size ) {
  316. guilds += `<div class="guild">
  317. <div class="separator"></div>
  318. </div>`;
  319. settings.guilds.notMember.forEach( guild => {
  320. guilds += `<div class="guild" id="${guild.id}">
  321. <div class="bar"></div>
  322. <a href="/guild/${guild.id}" alt="${guild.name}">` + ( guild.icon ?
  323. `<img class="avatar" src="${guild.icon}" alt="${guild.acronym}" width="48" height="48">`
  324. : `<div class="avatar noicon">${guild.acronym}</div>` ) +
  325. `</a>
  326. </div>`;
  327. } );
  328. }
  329. $('replace#guilds').replaceWith(guilds);
  330. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  331. let id = reqURL.pathname.replace( '/guild/', '' );
  332. if ( settings.guilds.isMember.has(id) ) {
  333. $('.guild#' + id).addClass('selected');
  334. let guild = settings.guilds.isMember.get(id);
  335. $('head title').text(guild.name + ' – ' + $('head title').text());
  336. res.setHeader('Set-Cookie', [`guild="${id}"; HttpOnly; Path=/`]);
  337. $('replace#text').replaceWith(`${guild.permissions}`);
  338. }
  339. if ( settings.guilds.notMember.has(id) ) {
  340. $('.guild#' + id).addClass('selected');
  341. let guild = settings.guilds.notMember.get(id);
  342. $('head title').text(guild.name + ' – ' + $('head title').text());
  343. res.setHeader('Set-Cookie', [`guild="${id}"; HttpOnly; Path=/`]);
  344. let url = oauth.generateAuthUrl( {
  345. scope: ['identify', 'guilds', 'bot'],
  346. permissions: defaultPermissions,
  347. guild_id: id, state
  348. } );
  349. $('replace#text').replaceWith(`<a href="${url}">${guild.permissions}</a>`);
  350. }
  351. $('replace#text').replaceWith('You are missing the <code>MANAGE_GUILD</code> permission.');
  352. }
  353. $('replace#text').replaceWith('Keks');
  354. let notice = $.html();
  355. res.writeHead(200, {'Content-Length': notice.length});
  356. res.write( notice );
  357. return res.end();
  358. });
  359. server.listen(8080, 'localhost', () => {
  360. console.log( '- Dashboard: Server running at http://localhost:8080/' );
  361. });
  362. const permissions = {
  363. ADMINISTRATOR: 1 << 3,
  364. MANAGE_CHANNELS: 1 << 4,
  365. MANAGE_GUILD: 1 << 5,
  366. MANAGE_MESSAGES: 1 << 13,
  367. MENTION_EVERYONE: 1 << 17,
  368. MANAGE_NICKNAMES: 1 << 27,
  369. MANAGE_ROLES: 1 << 28,
  370. MANAGE_WEBHOOKS: 1 << 29,
  371. MANAGE_EMOJIS: 1 << 30
  372. }
  373. /**
  374. * Check if a permission is included in the BitField
  375. * @param {String|Number} all - BitField of multiple permissions
  376. * @param {String?} permission - Name of the permission to check for
  377. * @param {Boolean} [admin] - If administrator permission can overwrite
  378. * @returns {Boolean}
  379. */
  380. function hasPerm(all, permission, admin = true) {
  381. var bit = permissions[permission];
  382. var adminOverwrite = ( admin && (all & permissions.ADMINISTRATOR) === permissions.ADMINISTRATOR );
  383. return ( adminOverwrite || (all & bit) === bit )
  384. }
  385. /**
  386. * End the process gracefully.
  387. * @param {NodeJS.Signals} signal - The signal received.
  388. */
  389. async function graceful(signal) {
  390. console.log( '- Dashboard: ' + signal + ': Closing the dashboard...' );
  391. await server.close( () => {
  392. console.log( '- Dashboard: ' + signal + ': Closed the dashboard server.' );
  393. } );
  394. await db.close( dberror => {
  395. if ( dberror ) {
  396. console.log( '- Dashboard: ' + signal + ': Error while closing the database connection: ' + dberror );
  397. return dberror;
  398. }
  399. console.log( '- Dashboard: ' + signal + ': Closed the database connection.' );
  400. } );
  401. }
  402. process.once( 'SIGINT', graceful );
  403. process.once( 'SIGTERM', graceful );