index.js 12 KB

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