index.js 5.2 KB

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