index.js 12 KB

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