oauth.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. const {randomBytes} = require('crypto');
  2. const cheerio = require('cheerio');
  3. const {defaultPermissions} = require('../util/default.json');
  4. const Wiki = require('../util/wiki.js');
  5. const allLangs = require('./i18n.js').allLangs().names;
  6. const {got, db, oauth, enabledOAuth2, sessionData, settingsData, oauthVerify, sendMsg, addWidgets, createNotice, hasPerm} = require('./util.js');
  7. const file = require('fs').readFileSync('./dashboard/login.html');
  8. /**
  9. * Let a user login
  10. * @param {import('http').ServerResponse} res - The server response
  11. * @param {import('./i18n.js')} dashboardLang - The user language.
  12. * @param {String} theme - The display theme
  13. * @param {String} [state] - The user state
  14. * @param {String} [action] - The action the user made
  15. */
  16. function dashboard_login(res, dashboardLang, theme, state, action) {
  17. if ( state && sessionData.has(state) ) {
  18. if ( !action ) {
  19. res.writeHead(302, {Location: '/'});
  20. return res.end();
  21. }
  22. sessionData.delete(state);
  23. }
  24. var $ = cheerio.load(file);
  25. $('html').attr('lang', dashboardLang.lang);
  26. if ( theme === 'light' ) $('html').addClass('theme-light');
  27. $('<script>').text(`
  28. const selectLanguage = '${dashboardLang.get('general.language').replace( /'/g, '\\$&' )}';
  29. const allLangs = ${JSON.stringify(allLangs)};
  30. `).insertBefore('script#langjs');
  31. $('head title').text(dashboardLang.get('general.login') + ' – ' + dashboardLang.get('general.title'));
  32. $('#login-button span, .channel#login div').text(dashboardLang.get('general.login'));
  33. $('.channel#login').attr('title', dashboardLang.get('general.login'));
  34. $('.channel#invite-wikibot div').text(dashboardLang.get('general.invite'));
  35. $('.channel#invite-wikibot').attr('title', dashboardLang.get('general.invite'));
  36. $('.guild#invite a').attr('alt', dashboardLang.get('general.invite'));
  37. $('.guild#theme-dark a').attr('alt', dashboardLang.get('general.theme-dark'));
  38. $('.guild#theme-light a').attr('alt', dashboardLang.get('general.theme-light'));
  39. $('#support span').text(dashboardLang.get('general.support'));
  40. $('#text .description #welcome').html(dashboardLang.get('general.welcome'));
  41. let responseCode = 200;
  42. let prompt = 'none';
  43. if ( process.env.READONLY ) createNotice($, 'readonly', dashboardLang);
  44. if ( action ) createNotice($, action, dashboardLang);
  45. if ( action === 'unauthorized' ) $('<script>').text('history.replaceState(null, null, "/login");').appendTo('head');
  46. else if ( action.startsWith( 'oauth' ) ) {
  47. if ( action === 'oauth' ) createNotice($, 'oauthlogin', dashboardLang);
  48. $('<script>').text('history.replaceState(null, null, "/user");').appendTo('head');
  49. }
  50. if ( action === 'logout' ) prompt = 'consent';
  51. if ( action === 'loginfail' ) responseCode = 400;
  52. state = Date.now().toString(16) + randomBytes(16).toString('hex');
  53. while ( sessionData.has(state) ) {
  54. state = Date.now().toString(16) + randomBytes(16).toString('hex');
  55. }
  56. let invite = oauth.generateAuthUrl( {
  57. scope: ['identify', 'guilds', 'bot', 'applications.commands'],
  58. permissions: defaultPermissions, state
  59. } );
  60. $('.guild#invite a, .channel#invite-wikibot').attr('href', invite);
  61. let url = oauth.generateAuthUrl( {
  62. scope: ['identify', 'guilds'],
  63. prompt, state
  64. } );
  65. $('.channel#login, #login-button').attr('href', url);
  66. addWidgets($, dashboardLang);
  67. let body = $.html();
  68. res.writeHead(responseCode, {
  69. 'Set-Cookie': [
  70. ...( res.getHeader('Set-Cookie') || [] ),
  71. `wikibot="${state}"; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000`
  72. ],
  73. 'Content-Length': Buffer.byteLength(body)
  74. });
  75. res.write( body );
  76. return res.end();
  77. }
  78. /**
  79. * Load oauth data of a user
  80. * @param {import('http').ServerResponse} res - The server response
  81. * @param {String} state - The user state
  82. * @param {URLSearchParams} searchParams - The url parameters
  83. * @param {String} [lastGuild] - The guild to return to
  84. */
  85. function dashboard_oauth(res, state, searchParams, lastGuild) {
  86. if ( searchParams.get('error') === 'access_denied' && state === searchParams.get('state') && sessionData.has(state) ) {
  87. res.writeHead(302, {Location: '/'});
  88. return res.end();
  89. }
  90. if ( state !== searchParams.get('state') || !searchParams.get('code') ) {
  91. res.writeHead(302, {Location: '/login?action=failed'});
  92. return res.end();
  93. }
  94. sessionData.delete(state);
  95. return oauth.tokenRequest( {
  96. scope: ['identify', 'guilds'],
  97. code: searchParams.get('code'),
  98. grantType: 'authorization_code'
  99. } ).then( ({access_token}) => {
  100. return Promise.all([
  101. oauth.getUser(access_token),
  102. oauth.getUserGuilds(access_token)
  103. ]).then( ([user, guilds]) => {
  104. guilds = guilds.filter( guild => {
  105. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  106. } ).map( guild => {
  107. return {
  108. id: guild.id,
  109. name: guild.name,
  110. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  111. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  112. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) : null ),
  113. userPermissions: guild.permissions
  114. };
  115. } );
  116. sendMsg( {
  117. type: 'getGuilds',
  118. member: user.id,
  119. guilds: guilds.map( guild => guild.id )
  120. } ).then( response => {
  121. var userSession = {
  122. state: `${state}-${user.id}`,
  123. access_token,
  124. user_id: user.id
  125. };
  126. sessionData.set(userSession.state, userSession);
  127. /** @type {import('./util.js').Settings} */
  128. var settings = ( settingsData.has(user.id) ? settingsData.get(user.id) : {
  129. user: {},
  130. guilds: {}
  131. } );
  132. settings.user.id = user.id;
  133. settings.user.username = user.username;
  134. settings.user.discriminator = user.discriminator;
  135. settings.user.avatar = 'https://cdn.discordapp.com/' + ( user.avatar ? `avatars/${user.id}/${user.avatar}.` + ( user.avatar.startsWith( 'a_' ) ? 'gif' : 'png' ) : `embed/avatars/${user.discriminator % 5}.png` ) + '?size=64';
  136. settings.user.locale = user.locale;
  137. settings.guilds.count = guilds.length;
  138. /** @type {import('./util.js').Guild[]} */
  139. var isMemberGuilds = [];
  140. settings.guilds.notMember = new Map();
  141. response.forEach( (guild, i) => {
  142. if ( guild ) {
  143. if ( guild === 'noMember' ) return;
  144. isMemberGuilds.push(Object.assign(guilds[i], guild));
  145. }
  146. else settings.guilds.notMember.set(guilds[i].id, guilds[i]);
  147. } );
  148. settings.guilds.isMember = new Map(isMemberGuilds.sort( (a, b) => {
  149. return ( b.patreon - a.patreon || b.memberCount - a.memberCount );
  150. } ).map( guild => {
  151. return [guild.id, guild];
  152. } ));
  153. settingsData.set(user.id, settings);
  154. if ( searchParams.has('guild_id') && !lastGuild.startsWith( searchParams.get('guild_id') + '/' ) ) {
  155. lastGuild = searchParams.get('guild_id') + '/settings';
  156. }
  157. let returnLocation = '/';
  158. if ( lastGuild ) {
  159. if ( lastGuild === 'user' ) returnLocation += lastGuild;
  160. else if ( /^\d+\/(?:settings|verification|rcscript|slash)(?:\/(?:\d+|new|notice))?$/.test(lastGuild) ) returnLocation += 'guild/' + lastGuild;
  161. }
  162. res.writeHead(302, {
  163. Location: returnLocation,
  164. 'Set-Cookie': [`wikibot="${userSession.state}"; HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000`]
  165. });
  166. return res.end();
  167. }, error => {
  168. console.log( '- Dashboard: Error while getting the guilds:', error );
  169. res.writeHead(302, {Location: '/login?action=failed'});
  170. return res.end();
  171. } );
  172. }, error => {
  173. console.log( '- Dashboard: Error while getting user and guilds: ' + error );
  174. res.writeHead(302, {Location: '/login?action=failed'});
  175. return res.end();
  176. } );
  177. }, error => {
  178. console.log( '- Dashboard: Error while getting the token: ' + error );
  179. res.writeHead(302, {Location: '/login?action=failed'});
  180. return res.end();
  181. } );
  182. }
  183. /**
  184. * Reload the guild of a user
  185. * @param {import('http').ServerResponse} res - The server response
  186. * @param {import('./util.js').UserSession} userSession - The user session
  187. * @param {String} [returnLocation] - The return location
  188. */
  189. function dashboard_refresh(res, userSession, returnLocation = '/') {
  190. return oauth.getUserGuilds(userSession.access_token).then( guilds => {
  191. guilds = guilds.filter( guild => {
  192. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  193. } ).map( guild => {
  194. return {
  195. id: guild.id,
  196. name: guild.name,
  197. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  198. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  199. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) : null ),
  200. userPermissions: guild.permissions
  201. };
  202. } );
  203. var settings = settingsData.get(userSession.user_id);
  204. sendMsg( {
  205. type: 'getGuilds',
  206. member: settings.user.id,
  207. guilds: guilds.map( guild => guild.id )
  208. } ).then( response => {
  209. settings.guilds.count = guilds.length;
  210. /** @type {import('./util.js').Guild[]} */
  211. var isMemberGuilds = [];
  212. settings.guilds.notMember = new Map();
  213. response.forEach( (guild, i) => {
  214. if ( guild ) {
  215. if ( guild === 'noMember' ) return;
  216. isMemberGuilds.push(Object.assign(guilds[i], guild));
  217. }
  218. else settings.guilds.notMember.set(guilds[i].id, guilds[i]);
  219. } );
  220. settings.guilds.isMember = new Map(isMemberGuilds.sort( (a, b) => {
  221. return ( b.patreon - a.patreon || b.memberCount - a.memberCount );
  222. } ).map( guild => {
  223. return [guild.id, guild];
  224. } ));
  225. res.writeHead(302, {Location: returnLocation + '?refresh=success'});
  226. return res.end();
  227. }, error => {
  228. console.log( '- Dashboard: Error while getting the refreshed guilds:', error );
  229. res.writeHead(302, {Location: returnLocation + '?refresh=failed'});
  230. return res.end();
  231. } );
  232. }, error => {
  233. console.log( '- Dashboard: Error while refreshing guilds: ' + error );
  234. res.writeHead(302, {Location: returnLocation + '?refresh=failed'});
  235. return res.end();
  236. } );
  237. }
  238. /**
  239. * Check if a wiki is availabe
  240. * @param {import('http').ServerResponse} res - The server response
  241. * @param {String} input - The wiki to check
  242. */
  243. function dashboard_api(res, input) {
  244. var wiki = Wiki.fromInput('https://' + input + '/');
  245. var result = {
  246. api: true,
  247. error: false,
  248. error_code: '',
  249. wiki: wiki.href,
  250. base: '',
  251. sitename: '',
  252. logo: '',
  253. MediaWiki: false,
  254. RcGcDw: '',
  255. customRcGcDw: wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit')
  256. };
  257. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json', {
  258. responseType: 'text'
  259. } ).then( response => {
  260. try {
  261. response.body = JSON.parse(response.body);
  262. }
  263. catch (error) {
  264. if ( response.statusCode === 404 && typeof response.body === 'string' ) {
  265. let api = cheerio.load(response.body)('head link[rel="EditURI"]').prop('href');
  266. if ( api ) {
  267. wiki = new Wiki(api.split('api.php?')[0], wiki);
  268. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json' );
  269. }
  270. }
  271. }
  272. return response;
  273. } ).then( response => {
  274. var body = response.body;
  275. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general ) {
  276. console.log( '- Dashboard: ' + response.statusCode + ': Error while checking the wiki: ' + body?.error?.info );
  277. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  278. result.error_code = 'private';
  279. }
  280. result.error = true;
  281. return;
  282. }
  283. wiki.updateWiki(body.query.general);
  284. result.wiki = wiki.href;
  285. result.base = body.query.general.base;
  286. result.sitename = body.query.general.sitename;
  287. result.logo = body.query.general.logo;
  288. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) >= 30 ) {
  289. result.MediaWiki = true;
  290. }
  291. if ( body.query.allmessages[0]['*'] ) {
  292. result.RcGcDw = body.query.allmessages[0]['*'];
  293. }
  294. result.customRcGcDw = wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit');
  295. if ( wiki.isFandom() ) return;
  296. }, error => {
  297. if ( error.message?.startsWith( 'connect ECONNREFUSED ' ) || error.message?.startsWith( 'Hostname/IP does not match certificate\'s altnames: ' ) || error.message === 'certificate has expired' || error.message === 'self signed certificate' ) {
  298. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  299. result.error_code = 'http';
  300. result.error = true;
  301. return;
  302. }
  303. console.log( '- Dashboard: Error while checking the wiki: ' + error );
  304. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  305. result.error_code = 'timeout';
  306. }
  307. result.error = true;
  308. } ).finally( () => {
  309. let body = JSON.stringify(result);
  310. res.writeHead(200, {
  311. 'Content-Length': Buffer.byteLength(body),
  312. 'Content-Type': 'application/json'
  313. });
  314. res.write( body );
  315. return res.end();
  316. } );
  317. }
  318. /**
  319. * Load oauth data of a wiki user
  320. * @param {import('http').ServerResponse} res - The server response
  321. * @param {URLSearchParams} searchParams - The url parameters
  322. * @param {String} [user_id] - The current user
  323. */
  324. function mediawiki_oauth(res, searchParams, user_id) {
  325. if ( !searchParams.get('code') || !searchParams.get('state') ) {
  326. res.writeHead(302, {Location: '/user?oauth=failed'});
  327. return res.end();
  328. }
  329. var state = searchParams.get('state');
  330. var site = state.split(' ');
  331. var oauthSite = enabledOAuth2.find( oauthSite => ( site[2] || site[0] ) === oauthSite.id );
  332. if ( !oauthSite || ( !oauthVerify.has(state) && !user_id ) ) {
  333. res.writeHead(302, {Location: '/user?oauth=failed'});
  334. return res.end();
  335. }
  336. var url = oauthSite.url;
  337. if ( oauthVerify.has(state) && site[2] === oauthSite.id ) url = 'https://' + site[0] + '/';
  338. got.post( url + 'rest.php/oauth2/access_token', {
  339. form: {
  340. grant_type: 'authorization_code',
  341. code: searchParams.get('code'),
  342. redirect_uri: new URL('/oauth/mw', process.env.dashboard).href,
  343. client_id: process.env['oauth_' + oauthSite.id],
  344. client_secret: process.env['oauth_' + oauthSite.id + '_secret']
  345. }
  346. } ).then( response => {
  347. var body = response.body;
  348. if ( response.statusCode !== 200 || !body?.access_token ) {
  349. console.log( '- Dashboard: ' + response.statusCode + ': Error while getting the mediawiki token: ' + ( body?.message || body?.error ) );
  350. res.writeHead(302, {Location: '/user?oauth=failed'});
  351. return res.end();
  352. }
  353. if ( !oauthVerify.has(state) ) {
  354. if ( !body?.refresh_token || !user_id ) {
  355. res.writeHead(302, {Location: '/user?oauth=failed'});
  356. return res.end();
  357. }
  358. return db.query( 'INSERT INTO oauthusers(userid, site, token) VALUES($1, $2, $3)', [user_id, oauthSite.id, body.refresh_token] ).then( () => {
  359. console.log( '- Dashboard: OAuth2 token for ' + user_id + ' successfully saved.' );
  360. res.writeHead(302, {Location: '/user?oauth=success'});
  361. return res.end();
  362. }, dberror => {
  363. console.log( '- Dashboard: Error while saving the OAuth2 token for ' + user_id + ': ' + dberror );
  364. res.writeHead(302, {Location: '/user?oauth=failed'});
  365. return res.end();
  366. } );
  367. }
  368. sendMsg( {
  369. type: 'verifyUser', state,
  370. access_token: body.access_token
  371. } ).then( () => {
  372. let userid = oauthVerify.get(state);
  373. if ( userid && body?.refresh_token ) db.query( 'INSERT INTO oauthusers(userid, site, token) VALUES($1, $2, $3)', [userid, oauthSite.id, body.refresh_token] ).then( () => {
  374. console.log( '- Dashboard: OAuth2 token for ' + userid + ' successfully saved.' );
  375. }, dberror => {
  376. console.log( '- Dashboard: Error while saving the OAuth2 token for ' + userid + ': ' + dberror );
  377. } );
  378. oauthVerify.delete(state);
  379. if ( !userid ) res.writeHead(302, {Location: '/user?oauth=verified'});
  380. else if ( user_id && userid !== user_id ) res.writeHead(302, {Location: '/user?oauth=other'});
  381. else res.writeHead(302, {Location: '/user?oauth=success'});
  382. return res.end();
  383. }, error => {
  384. console.log( '- Dashboard: Error while sending the mediawiki token: ' + error );
  385. res.writeHead(302, {Location: '/user?oauth=failed'});
  386. return res.end();
  387. } );
  388. }, error => {
  389. console.log( '- Dashboard: Error while getting the mediawiki token: ' + error );
  390. res.writeHead(302, {Location: '/user?oauth=failed'});
  391. return res.end();
  392. } );
  393. }
  394. module.exports = {
  395. login: dashboard_login,
  396. oauth: dashboard_oauth,
  397. refresh: dashboard_refresh,
  398. api: dashboard_api,
  399. verify: mediawiki_oauth
  400. };