index.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. const http = require('http');
  2. const {parse} = require('querystring');
  3. const pages = require('./oauth.js');
  4. const dashboard = require('./guilds.js');
  5. const {db, settingsData} = require('./util.js');
  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. process.env.READONLY = 'true';
  41. const server = http.createServer((req, res) => {
  42. if ( req.method === 'POST' && req.url.startsWith( '/guild/' ) && !process.env.READONLY ) {
  43. let args = req.url.split('/');
  44. let state = req.headers.cookie?.split('; ')?.filter( cookie => {
  45. return cookie.split('=')[0] === 'wikibot';
  46. } )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)?)"$/, '$1' ) )?.join();
  47. if ( args.length === 5 && ['settings', 'verification', 'rcscript'].includes( args[3] )
  48. && settingsData.has(state) && settingsData.get(state).guilds.isMember.has(args[2]) ) {
  49. let body = '';
  50. req.on( 'data', chunk => {
  51. body += chunk.toString();
  52. } );
  53. req.on( 'error', () => {
  54. console.log( error );
  55. res.end('error');
  56. } );
  57. return req.on( 'end', () => {
  58. return posts[args[3]](res, settingsData.get(state).user.id, args[2], parse(body));
  59. } );
  60. }
  61. }
  62. if ( req.method !== 'GET' ) {
  63. let body = '<img width="400" src="https://http.cat/418"><br><strong>' + http.STATUS_CODES[418] + '</strong>';
  64. res.writeHead(418, {
  65. 'Content-Type': 'text/html',
  66. 'Content-Length': body.length
  67. });
  68. res.write( body );
  69. return res.end();
  70. }
  71. var reqURL = new URL(req.url, process.env.dashboard);
  72. if ( reqURL.pathname === '/favicon.ico' ) {
  73. res.writeHead(302, {Location: 'https://cdn.discordapp.com/avatars/461189216198590464/f69cdc197791aed829882b64f9760dbb.png?size=64'});
  74. return res.end();
  75. }
  76. if ( files.has(reqURL.pathname) ) {
  77. let file = files.get(reqURL.pathname);
  78. res.writeHead(200, {'Content-Type': file.contentType});
  79. return fs.createReadStream(file.path).pipe(res);
  80. }
  81. res.setHeader('Content-Type', 'text/html');
  82. res.setHeader('Content-Language', ['en']);
  83. var lastGuild = req.headers?.cookie?.split('; ')?.filter( cookie => {
  84. return cookie.split('=')[0] === 'guild';
  85. } )?.map( cookie => cookie.replace( /^guild="(\w*)"$/, '$1' ) )?.join();
  86. if ( lastGuild ) res.setHeader('Set-Cookie', ['guild=""; HttpOnly; Path=/; Max-Age=0']);
  87. var state = req.headers.cookie?.split('; ')?.filter( cookie => {
  88. return cookie.split('=')[0] === 'wikibot';
  89. } )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)?)"$/, '$1' ) )?.join();
  90. if ( reqURL.pathname === '/login' ) {
  91. return pages.login(res, state, reqURL.searchParams.get('action'));
  92. }
  93. if ( reqURL.pathname === '/logout' ) {
  94. settingsData.delete(state);
  95. res.writeHead(302, {
  96. Location: '/login?action=logout',
  97. 'Set-Cookie': [
  98. ...( res.getHeader('Set-Cookie') || [] ),
  99. 'wikibot=""; HttpOnly; Path=/; Max-Age=0'
  100. ]
  101. });
  102. return res.end();
  103. }
  104. if ( !state ) {
  105. res.writeHead(302, {
  106. Location: ( reqURL.pathname === '/' ? '/login' : '/login?action=unauthorized' )
  107. });
  108. return res.end();
  109. }
  110. if ( reqURL.pathname === '/oauth' ) {
  111. return pages.oauth(res, state, reqURL.searchParams, lastGuild);
  112. }
  113. if ( !settingsData.has(state) ) {
  114. res.writeHead(302, {
  115. Location: ( reqURL.pathname === '/' ? '/login' : '/login?action=unauthorized' )
  116. });
  117. return res.end();
  118. }
  119. if ( reqURL.pathname === '/refresh' ) {
  120. return pages.refresh(res, state, reqURL.searchParams.get('return'));
  121. }
  122. if ( reqURL.pathname === '/' || reqURL.pathname.startsWith( '/guild/' ) ) {
  123. return dashboard(res, state, reqURL);
  124. }
  125. res.writeHead(302, {Location: '/'});
  126. return res.end();
  127. });
  128. server.listen(8080, 'localhost', () => {
  129. console.log( '- Dashboard: Server running at http://localhost:8080/' );
  130. });
  131. /**
  132. * End the process gracefully.
  133. * @param {NodeJS.Signals} signal - The signal received.
  134. */
  135. function graceful(signal) {
  136. console.log( '- Dashboard: ' + signal + ': Closing the dashboard...' );
  137. server.close( () => {
  138. console.log( '- Dashboard: ' + signal + ': Closed the dashboard server.' );
  139. } );
  140. db.close( dberror => {
  141. if ( dberror ) {
  142. console.log( '- Dashboard: ' + signal + ': Error while closing the database connection: ' + dberror );
  143. return dberror;
  144. }
  145. console.log( '- Dashboard: ' + signal + ': Closed the database connection.' );
  146. process.exit(0);
  147. } );
  148. }
  149. process.once( 'SIGINT', graceful );
  150. process.once( 'SIGTERM', graceful );