index.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. const http = require('http');
  2. const pages = require('./oauth.js');
  3. const dashboard = require('./guilds.js');
  4. const {db, settingsData} = require('./util.js');
  5. global.isDebug = ( process.argv[2] === 'debug' );
  6. const posts = {
  7. settings: require('./settings.js').post,
  8. verification: require('./verification.js').post,
  9. rcscript: require('./rcscript.js').post
  10. };
  11. const fs = require('fs');
  12. const path = require('path');
  13. const files = new Map(fs.readdirSync( './dashboard/src' ).map( file => {
  14. let contentType = 'text/html';
  15. switch ( path.extname(file) ) {
  16. case '.css':
  17. contentType = 'text/css';
  18. break;
  19. case '.js':
  20. contentType = 'text/javascript';
  21. break;
  22. case '.json':
  23. contentType = 'application/json';
  24. break;
  25. case '.svg':
  26. contentType = 'image/svg+xml';
  27. break;
  28. case '.png':
  29. contentType = 'image/png';
  30. break;
  31. case '.jpg':
  32. contentType = 'image/jpg';
  33. break;
  34. }
  35. return [`/src/${file}`, {
  36. name: file, contentType,
  37. path: `./dashboard/src/${file}`
  38. }];
  39. } ));
  40. const server = http.createServer((req, res) => {
  41. if ( req.method === 'POST' && req.url.startsWith( '/guild/' ) ) {
  42. let args = req.url.split('/');
  43. let state = req.headers.cookie?.split('; ')?.filter( cookie => {
  44. return cookie.split('=')[0] === 'wikibot';
  45. } )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)?)"$/, '$1' ) )?.join();
  46. if ( args.length === 5 && ['settings', 'verification', 'rcscript'].includes( args[3] )
  47. && /^(?:default|new|\d+)$/.test(args[4]) && settingsData.has(state)
  48. && settingsData.get(state).guilds.isMember.has(args[2]) ) {
  49. if ( process.env.READONLY ) return save_response(`${req.url}?save=failed`);
  50. let body = '';
  51. req.on( 'data', chunk => {
  52. body += chunk.toString();
  53. } );
  54. req.on( 'error', () => {
  55. console.log( error );
  56. res.end('error');
  57. } );
  58. return req.on( 'end', () => {
  59. var settings = {};
  60. body.split('&').forEach( arg => {
  61. if ( arg ) {
  62. let setting = decodeURIComponent(arg.replace( /\+/g, ' ' )).split('=');
  63. if ( setting[0] && setting.slice(1).join('=').trim() ) {
  64. if ( settings[setting[0]] ) {
  65. settings[setting[0]] += '|' + setting.slice(1).join('=').trim();
  66. }
  67. else settings[setting[0]] = setting.slice(1).join('=').trim();
  68. }
  69. }
  70. } );
  71. if ( isDebug ) console.log( '- Dashboard:', req.url, settings, settingsData.get(state).user.id );
  72. return posts[args[3]](save_response, settingsData.get(state), args[2], args[4], settings);
  73. } );
  74. /**
  75. * @param {String} [resURL]
  76. */
  77. function save_response(resURL = '/') {
  78. return dashboard(res, state, new URL(resURL, process.env.dashboard));
  79. }
  80. }
  81. }
  82. if ( req.method !== 'GET' ) {
  83. let body = '<img width="400" src="https://http.cat/418"><br><strong>' + http.STATUS_CODES[418] + '</strong>';
  84. res.writeHead(418, {
  85. 'Content-Type': 'text/html',
  86. 'Content-Length': body.length
  87. });
  88. res.write( body );
  89. return res.end();
  90. }
  91. var reqURL = new URL(req.url, process.env.dashboard);
  92. if ( reqURL.pathname === '/favicon.ico' ) {
  93. res.writeHead(302, {Location: 'https://cdn.discordapp.com/avatars/461189216198590464/f69cdc197791aed829882b64f9760dbb.png?size=64'});
  94. return res.end();
  95. }
  96. if ( files.has(reqURL.pathname) ) {
  97. let file = files.get(reqURL.pathname);
  98. res.writeHead(200, {'Content-Type': file.contentType});
  99. return fs.createReadStream(file.path).pipe(res);
  100. }
  101. res.setHeader('Content-Type', 'text/html');
  102. res.setHeader('Content-Language', ['en']);
  103. var lastGuild = req.headers?.cookie?.split('; ')?.filter( cookie => {
  104. return cookie.split('=')[0] === 'guild' && /^"\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?"$/.test(( cookie.split('=')[1] || '' ));
  105. } )?.map( cookie => cookie.replace( /^guild="(\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?)"$/, '$1' ) )?.join();
  106. if ( lastGuild ) res.setHeader('Set-Cookie', ['guild=""; HttpOnly; Path=/; Max-Age=0']);
  107. var state = req.headers.cookie?.split('; ')?.filter( cookie => {
  108. return cookie.split('=')[0] === 'wikibot' && /^"(\w*(?:-\d+)?)"$/.test(( cookie.split('=')[1] || '' ));
  109. } )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)?)"$/, '$1' ) )?.join();
  110. if ( reqURL.pathname === '/login' ) {
  111. return pages.login(res, state, reqURL.searchParams.get('action'));
  112. }
  113. if ( reqURL.pathname === '/logout' ) {
  114. settingsData.delete(state);
  115. res.setHeader('Set-Cookie', [
  116. ...( res.getHeader('Set-Cookie') || [] ),
  117. 'wikibot=""; HttpOnly; Path=/; Max-Age=0'
  118. ]);
  119. return pages.login(res, state, 'logout');
  120. }
  121. if ( !state ) {
  122. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  123. let pathGuild = reqURL.pathname.split('/').slice(2, 5).join('/');
  124. if ( /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(pathGuild) ) {
  125. res.setHeader('Set-Cookie', [`guild="${pathGuild}"; HttpOnly; Path=/`]);
  126. }
  127. }
  128. return pages.login(res, state, ( reqURL.pathname === '/' ? '' : 'unauthorized' ));
  129. }
  130. if ( reqURL.pathname === '/oauth' ) {
  131. return pages.oauth(res, state, reqURL.searchParams, lastGuild);
  132. }
  133. if ( !settingsData.has(state) ) {
  134. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  135. let pathGuild = reqURL.pathname.split('/').slice(2, 5).join('/');
  136. if ( /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(pathGuild) ) {
  137. res.setHeader('Set-Cookie', [`guild="${pathGuild}"; HttpOnly; Path=/`]);
  138. }
  139. }
  140. return pages.login(res, state, ( reqURL.pathname === '/' ? '' : 'unauthorized' ));
  141. }
  142. if ( reqURL.pathname === '/refresh' ) {
  143. let returnLocation = reqURL.searchParams.get('return');
  144. if ( !/^\/guild\/\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(returnLocation) ) {
  145. returnLocation = '/';
  146. }
  147. return pages.refresh(res, state, returnLocation);
  148. }
  149. if ( reqURL.pathname === '/' || reqURL.pathname.startsWith( '/guild/' ) ) {
  150. return dashboard(res, state, reqURL);
  151. }
  152. return dashboard(res, state, new URL('/', process.env.dashboard));
  153. });
  154. server.listen(8080, 'localhost', () => {
  155. console.log( '- Dashboard: Server running at http://localhost:8080/' );
  156. });
  157. String.prototype.replaceSave = function(pattern, replacement) {
  158. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  159. };
  160. /**
  161. * End the process gracefully.
  162. * @param {NodeJS.Signals} signal - The signal received.
  163. */
  164. function graceful(signal) {
  165. console.log( '- Dashboard: ' + signal + ': Closing the dashboard...' );
  166. server.close( () => {
  167. console.log( '- Dashboard: ' + signal + ': Closed the dashboard server.' );
  168. } );
  169. db.close( dberror => {
  170. if ( dberror ) {
  171. console.log( '- Dashboard: ' + signal + ': Error while closing the database connection: ' + dberror );
  172. return dberror;
  173. }
  174. console.log( '- Dashboard: ' + signal + ': Closed the database connection.' );
  175. process.exit(0);
  176. } );
  177. }
  178. process.once( 'SIGINT', graceful );
  179. process.once( 'SIGTERM', graceful );