index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. global.isDebug = ( process.argv[2] === 'debug' );
  2. const http = require('http');
  3. const pages = require('./oauth.js');
  4. const dashboard = require('./guilds.js');
  5. const {db, sessionData, settingsData} = require('./util.js');
  6. const Lang = require('./i18n.js');
  7. const allLangs = Lang.allLangs();
  8. const posts = {
  9. settings: require('./settings.js').post,
  10. verification: require('./verification.js').post,
  11. rcscript: require('./rcscript.js').post,
  12. slash: require('./slash.js').post
  13. };
  14. const fs = require('fs');
  15. const path = require('path');
  16. const files = new Map([
  17. ...fs.readdirSync( './dashboard/src' ).map( file => {
  18. return [`/src/${file}`, `./dashboard/src/${file}`];
  19. } ),
  20. ...fs.readdirSync( './i18n/widgets' ).map( file => {
  21. return [`/src/widgets/${file}`, `./i18n/widgets/${file}`];
  22. } ),
  23. ...( fs.existsSync('./RcGcDb/start.py') ? fs.readdirSync( './RcGcDb/locale/widgets' ).map( file => {
  24. return [`/src/widgets/RcGcDb/${file}`, `./RcGcDb/locale/widgets/${file}`];
  25. } ) : [] )
  26. ].map( ([file, filepath]) => {
  27. let contentType = 'text/html';
  28. switch ( path.extname(file) ) {
  29. case '.css':
  30. contentType = 'text/css';
  31. break;
  32. case '.js':
  33. contentType = 'text/javascript';
  34. break;
  35. case '.json':
  36. contentType = 'application/json';
  37. break;
  38. case '.svg':
  39. contentType = 'image/svg+xml';
  40. break;
  41. case '.png':
  42. contentType = 'image/png';
  43. break;
  44. case '.jpg':
  45. contentType = 'image/jpg';
  46. break;
  47. }
  48. return [file, {path: filepath, contentType}];
  49. } ));
  50. const server = http.createServer( (req, res) => {
  51. res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
  52. if ( req.method === 'POST' && req.headers['content-type'] === 'application/x-www-form-urlencoded' && req.url.startsWith( '/guild/' ) ) {
  53. let args = req.url.split('/');
  54. let state = req.headers.cookie?.split('; ')?.filter( cookie => {
  55. return cookie.split('=')[0] === 'wikibot' && /^"([\da-f]+(?:-\d+)*)"$/.test(( cookie.split('=')[1] || '' ));
  56. } )?.map( cookie => cookie.replace( /^wikibot="([\da-f]+(?:-\d+)*)"$/, '$1' ) )?.join();
  57. if ( args.length === 5 && ['settings', 'verification', 'rcscript', 'slash'].includes( args[3] )
  58. && /^(?:default|new|notice|\d+)$/.test(args[4]) && sessionData.has(state) && settingsData.has(sessionData.get(state).user_id)
  59. && settingsData.get(sessionData.get(state).user_id).guilds.isMember.has(args[2]) ) {
  60. if ( process.env.READONLY ) return save_response(`${req.url}?save=failed`);
  61. let body = [];
  62. req.on( 'data', chunk => {
  63. body.push(chunk);
  64. } );
  65. req.on( 'error', () => {
  66. console.log( '- Dashboard: ' + error );
  67. res.end('error');
  68. } );
  69. return req.on( 'end', () => {
  70. var settings = {};
  71. Buffer.concat(body).toString().split('&').forEach( arg => {
  72. if ( arg ) {
  73. let setting = decodeURIComponent(arg.replace( /\+/g, ' ' )).split('=');
  74. if ( setting[0] && setting.slice(1).join('=').trim() ) {
  75. if ( settings[setting[0]] ) {
  76. settings[setting[0]] += '|' + setting.slice(1).join('=').trim();
  77. }
  78. else settings[setting[0]] = setting.slice(1).join('=').trim();
  79. }
  80. }
  81. } );
  82. if ( isDebug ) console.log( '- Dashboard:', req.url, settings, sessionData.get(state).user_id );
  83. return posts[args[3]](save_response, settingsData.get(sessionData.get(state).user_id), args[2], args[4], settings);
  84. } );
  85. /**
  86. * @param {String} [resURL]
  87. * @param {String} [action]
  88. * @param {String[]} [actionArgs]
  89. */
  90. function save_response(resURL = '/', action, ...actionArgs) {
  91. var themeCookie = ( req.headers?.cookie?.split('; ')?.find( cookie => {
  92. return cookie.split('=')[0] === 'theme' && /^"(?:light|dark)"$/.test(( cookie.split('=')[1] || '' ));
  93. } ) || 'dark' ).replace( /^theme="(light|dark)"$/, '$1' );
  94. var langCookie = ( req.headers?.cookie?.split('; ')?.filter( cookie => {
  95. return cookie.split('=')[0] === 'language' && /^"[a-z\-]+"$/.test(( cookie.split('=')[1] || '' ));
  96. } )?.map( cookie => cookie.replace( /^language="([a-z\-]+)"$/, '$1' ) ) || [] );
  97. var dashboardLang = new Lang(...langCookie, ...( req.headers?.['accept-language']?.split(',')?.map( lang => {
  98. lang = lang.split(';')[0].toLowerCase();
  99. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  100. lang = lang.replace( /-\w+$/, '' );
  101. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  102. lang = lang.replace( /-\w+$/, '' );
  103. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  104. return '';
  105. } ) || [] ));
  106. dashboardLang.fromCookie = langCookie;
  107. return dashboard(res, dashboardLang, themeCookie, sessionData.get(state), new URL(resURL, process.env.dashboard), action, actionArgs);
  108. }
  109. }
  110. }
  111. if ( req.method !== 'GET' ) {
  112. let body = '<img width="400" src="https://http.cat/418"><br><strong>' + http.STATUS_CODES[418] + '</strong>';
  113. res.writeHead(418, {
  114. 'Content-Type': 'text/html',
  115. 'Content-Length': Buffer.byteLength(body)
  116. });
  117. res.write( body );
  118. return res.end();
  119. }
  120. var reqURL = new URL(req.url, process.env.dashboard);
  121. if ( reqURL.pathname === '/oauth/mw' ) {
  122. return pages.verify(res, reqURL.searchParams);
  123. }
  124. if ( reqURL.pathname === '/favicon.ico' ) reqURL.pathname = '/src/icon.png';
  125. if ( files.has(reqURL.pathname) ) {
  126. let file = files.get(reqURL.pathname);
  127. res.writeHead(200, {'Content-Type': file.contentType});
  128. return fs.createReadStream(file.path).pipe(res);
  129. }
  130. res.setHeader('Content-Type', 'text/html');
  131. var themeCookie = ( req.headers?.cookie?.split('; ')?.find( cookie => {
  132. return cookie.split('=')[0] === 'theme' && /^"(?:light|dark)"$/.test(( cookie.split('=')[1] || '' ));
  133. } ) || 'dark' ).replace( /^theme="(light|dark)"$/, '$1' );
  134. var langCookie = ( req.headers?.cookie?.split('; ')?.filter( cookie => {
  135. return cookie.split('=')[0] === 'language' && /^"[a-z\-]+"$/.test(( cookie.split('=')[1] || '' ));
  136. } )?.map( cookie => cookie.replace( /^language="([a-z\-]+)"$/, '$1' ) ) || [] );
  137. var dashboardLang = new Lang(...langCookie, ...( req.headers?.['accept-language']?.split(',')?.map( lang => {
  138. lang = lang.split(';')[0].toLowerCase();
  139. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  140. lang = lang.replace( /-\w+$/, '' );
  141. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  142. lang = lang.replace( /-\w+$/, '' );
  143. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  144. return '';
  145. } ) || [] ));
  146. dashboardLang.fromCookie = langCookie;
  147. res.setHeader('Content-Language', [dashboardLang.lang]);
  148. var lastGuild = req.headers?.cookie?.split('; ')?.filter( cookie => {
  149. return cookie.split('=')[0] === 'guild' && /^"\d+\/(?:settings|verification|rcscript|slash)(?:\/(?:\d+|new|notice))?"$/.test(( cookie.split('=')[1] || '' ));
  150. } )?.map( cookie => cookie.replace( /^guild="(\d+\/(?:settings|verification|rcscript|slash)(?:\/(?:\d+|new|notice))?)"$/, '$1' ) )?.join();
  151. if ( lastGuild ) res.setHeader('Set-Cookie', ['guild=""; SameSite=Lax; Path=/; Max-Age=0']);
  152. var state = req.headers.cookie?.split('; ')?.filter( cookie => {
  153. return cookie.split('=')[0] === 'wikibot' && /^"([\da-f]+(?:-\d+)*)"$/.test(( cookie.split('=')[1] || '' ));
  154. } )?.map( cookie => cookie.replace( /^wikibot="([\da-f]+(?:-\d+)*)"$/, '$1' ) )?.join();
  155. if ( reqURL.pathname === '/login' ) {
  156. let action = '';
  157. if ( reqURL.searchParams.get('action') === 'failed' ) action = 'loginfail';
  158. return pages.login(res, dashboardLang, themeCookie, state, action);
  159. }
  160. if ( reqURL.pathname === '/logout' ) {
  161. sessionData.delete(state);
  162. res.setHeader('Set-Cookie', [
  163. ...( res.getHeader('Set-Cookie') || [] ),
  164. 'wikibot=""; HttpOnly; SameSite=Lax; Path=/; Max-Age=0'
  165. ]);
  166. return pages.login(res, dashboardLang, themeCookie, state, 'logout');
  167. }
  168. if ( !state ) {
  169. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  170. let pathGuild = reqURL.pathname.split('/').slice(2, 5).join('/');
  171. if ( /^\d+\/(?:settings|verification|rcscript|slash)(?:\/(?:\d+|new|notice))?$/.test(pathGuild) ) {
  172. res.setHeader('Set-Cookie', [`guild="${pathGuild}"; SameSite=Lax; Path=/`]);
  173. }
  174. }
  175. return pages.login(res, dashboardLang, themeCookie, state, ( reqURL.pathname === '/' ? '' : 'unauthorized' ));
  176. }
  177. if ( reqURL.pathname === '/oauth' ) {
  178. return pages.oauth(res, state, reqURL.searchParams, lastGuild);
  179. }
  180. if ( !sessionData.has(state) || !settingsData.has(sessionData.get(state).user_id) ) {
  181. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  182. let pathGuild = reqURL.pathname.split('/').slice(2, 5).join('/');
  183. if ( /^\d+\/(?:settings|verification|rcscript|slash)(?:\/(?:\d+|new|notice))?$/.test(pathGuild) ) {
  184. res.setHeader('Set-Cookie', [`guild="${pathGuild}"; SameSite=Lax; Path=/`]);
  185. }
  186. }
  187. return pages.login(res, dashboardLang, themeCookie, state, ( reqURL.pathname === '/' ? '' : 'unauthorized' ));
  188. }
  189. if ( reqURL.pathname === '/refresh' ) {
  190. let returnLocation = reqURL.searchParams.get('return');
  191. if ( !/^\/guild\/\d+\/(?:settings|verification|rcscript|slash)(?:\/(?:\d+|new|notice))?$/.test(returnLocation) ) {
  192. returnLocation = '/';
  193. }
  194. return pages.refresh(res, sessionData.get(state), returnLocation);
  195. }
  196. if ( reqURL.pathname === '/api' ) {
  197. let wiki = reqURL.searchParams.get('wiki');
  198. if ( wiki ) return pages.api(res, wiki);
  199. }
  200. let action = '';
  201. if ( reqURL.searchParams.get('refresh') === 'success' ) action = 'refresh';
  202. if ( reqURL.searchParams.get('refresh') === 'failed' ) action = 'refreshfail';
  203. if ( reqURL.searchParams.get('slash') === 'noverify' ) action = 'noverify';
  204. return dashboard(res, dashboardLang, themeCookie, sessionData.get(state), reqURL, action);
  205. } );
  206. server.listen( 8080, 'localhost', () => {
  207. console.log( '- Dashboard: Server running at http://localhost:8080/' );
  208. } );
  209. String.prototype.replaceSave = function(pattern, replacement) {
  210. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  211. };
  212. /**
  213. * End the process gracefully.
  214. * @param {NodeJS.Signals} signal - The signal received.
  215. */
  216. function graceful(signal) {
  217. console.log( '- Dashboard: ' + signal + ': Closing the dashboard...' );
  218. server.close( () => {
  219. console.log( '- Dashboard: ' + signal + ': Closed the dashboard server.' );
  220. db.end().then( () => {
  221. console.log( '- Dashboard: ' + signal + ': Closed the database connection.' );
  222. process.exit(0);
  223. }, dberror => {
  224. console.log( '- Dashboard: ' + signal + ': Error while closing the database connection: ' + dberror );
  225. } );
  226. } );
  227. }
  228. process.once( 'SIGINT', graceful );
  229. process.once( 'SIGTERM', graceful );