oauth.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. const crypto = 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, settingsData, sendMsg, createNotice, hasPerm} = require('./util.js');
  7. const DiscordOauth2 = require('discord-oauth2');
  8. const oauth = new DiscordOauth2( {
  9. clientId: process.env.bot,
  10. clientSecret: process.env.secret,
  11. redirectUri: process.env.dashboard
  12. } );
  13. const file = require('fs').readFileSync('./dashboard/login.html');
  14. /**
  15. * Let a user login
  16. * @param {import('http').ServerResponse} res - The server response
  17. * @param {import('./i18n.js')} dashboardLang - The user language.
  18. * @param {String} theme - The display theme
  19. * @param {String} [state] - The user state
  20. * @param {String} [action] - The action the user made
  21. */
  22. function dashboard_login(res, dashboardLang, theme, state, action) {
  23. if ( state && settingsData.has(state) ) {
  24. if ( !action ) {
  25. res.writeHead(302, {Location: '/'});
  26. return res.end();
  27. }
  28. settingsData.delete(state);
  29. }
  30. var $ = cheerio.load(file);
  31. $('html').attr('lang', dashboardLang.lang);
  32. if ( theme === 'light' ) $('html').addClass('theme-light');
  33. $('<script>').text(`
  34. const selectLanguage = '${dashboardLang.get('general.language').replace( /'/g, '\\$&' )}';
  35. const allLangs = ${JSON.stringify(allLangs)};
  36. `).insertBefore('script#langjs');
  37. $('head title').text(dashboardLang.get('general.login') + ' – ' + dashboardLang.get('general.title'));
  38. $('#login-button span, .channel#login div').text(dashboardLang.get('general.login'));
  39. $('.channel#invite-wikibot div').text(dashboardLang.get('general.invite'));
  40. $('.guild#invite a').attr('alt', dashboardLang.get('general.invite'));
  41. $('.guild#theme-dark a').attr('alt', dashboardLang.get('general.theme-dark'));
  42. $('.guild#theme-light a').attr('alt', dashboardLang.get('general.theme-light'));
  43. $('#support span').text(dashboardLang.get('general.support'));
  44. $('#text .description #welcome').html(dashboardLang.get('general.welcome'));
  45. let responseCode = 200;
  46. let prompt = 'none';
  47. if ( process.env.READONLY ) createNotice($, 'readonly', dashboardLang);
  48. if ( action ) createNotice($, action, dashboardLang);
  49. if ( action === 'unauthorized' ) $('head').append(
  50. $('<script>').text('history.replaceState(null, null, "/login");')
  51. );
  52. if ( action === 'logout' ) prompt = 'consent';
  53. if ( action === 'loginfail' ) responseCode = 400;
  54. state = crypto.randomBytes(16).toString("hex");
  55. while ( settingsData.has(state) ) {
  56. state = crypto.randomBytes(16).toString("hex");
  57. }
  58. let invite = oauth.generateAuthUrl( {
  59. scope: ['identify', 'guilds', 'bot', 'applications.commands'],
  60. permissions: defaultPermissions, state
  61. } );
  62. $('.guild#invite a, .channel#invite-wikibot').attr('href', invite);
  63. let url = oauth.generateAuthUrl( {
  64. scope: ['identify', 'guilds'],
  65. prompt, state
  66. } );
  67. $('.channel#login, #login-button').attr('href', url);
  68. let body = $.html();
  69. res.writeHead(responseCode, {
  70. 'Set-Cookie': [
  71. ...( res.getHeader('Set-Cookie') || [] ),
  72. `wikibot="${state}"; HttpOnly; Path=/`
  73. ],
  74. 'Content-Length': Buffer.byteLength(body)
  75. });
  76. res.write( body );
  77. return res.end();
  78. }
  79. /**
  80. * Load oauth data of a user
  81. * @param {import('http').ServerResponse} res - The server response
  82. * @param {String} state - The user state
  83. * @param {URLSearchParams} searchParams - The url parameters
  84. * @param {String} [lastGuild] - The guild to return to
  85. */
  86. function dashboard_oauth(res, state, searchParams, lastGuild) {
  87. if ( searchParams.get('error') === 'access_denied' && state === searchParams.get('state') && settingsData.has(state) ) {
  88. res.writeHead(302, {Location: '/'});
  89. return res.end();
  90. }
  91. if ( state !== searchParams.get('state') || !searchParams.get('code') ) {
  92. res.writeHead(302, {Location: '/login?action=failed'});
  93. return res.end();
  94. }
  95. settingsData.delete(state);
  96. return oauth.tokenRequest( {
  97. scope: ['identify', 'guilds'],
  98. code: searchParams.get('code'),
  99. grantType: 'authorization_code'
  100. } ).then( ({access_token}) => {
  101. return Promise.all([
  102. oauth.getUser(access_token),
  103. oauth.getUserGuilds(access_token)
  104. ]).then( ([user, guilds]) => {
  105. guilds = guilds.filter( guild => {
  106. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  107. } ).map( guild => {
  108. return {
  109. id: guild.id,
  110. name: guild.name,
  111. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  112. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  113. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) : null ),
  114. userPermissions: guild.permissions
  115. };
  116. } );
  117. sendMsg( {
  118. type: 'getGuilds',
  119. member: user.id,
  120. guilds: guilds.map( guild => guild.id )
  121. } ).then( response => {
  122. var settings = {
  123. state: `${state}-${user.id}`,
  124. access_token,
  125. user: {
  126. id: user.id,
  127. username: user.username,
  128. discriminator: user.discriminator,
  129. avatar: 'https://cdn.discordapp.com/' + ( user.avatar ?
  130. `avatars/${user.id}/${user.avatar}.` +
  131. ( user.avatar.startsWith( 'a_' ) ? 'gif' : 'png' ) :
  132. `embed/avatars/${user.discriminator % 5}.png` ) + '?size=64',
  133. locale: user.locale
  134. },
  135. guilds: {
  136. count: guilds.length,
  137. isMember: new Map(),
  138. notMember: new Map()
  139. }
  140. };
  141. response.forEach( (guild, i) => {
  142. if ( guild ) {
  143. if ( guild === 'noMember' ) return;
  144. settings.guilds.isMember.set(guilds[i].id, Object.assign(guilds[i], guild));
  145. }
  146. else settings.guilds.notMember.set(guilds[i].id, guilds[i]);
  147. } );
  148. settingsData.set(settings.state, settings);
  149. if ( searchParams.has('guild_id') ) {
  150. lastGuild = searchParams.get('guild_id') + '/settings';
  151. }
  152. res.writeHead(302, {
  153. Location: ( lastGuild && /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(lastGuild) ? `/guild/${lastGuild}` : '/' ),
  154. 'Set-Cookie': [`wikibot="${settings.state}"; HttpOnly; Path=/`]
  155. });
  156. return res.end();
  157. }, error => {
  158. console.log( '- Dashboard: Error while getting the guilds:', error );
  159. res.writeHead(302, {Location: '/login?action=failed'});
  160. return res.end();
  161. } );
  162. }, error => {
  163. console.log( '- Dashboard: Error while getting user and guilds: ' + error );
  164. res.writeHead(302, {Location: '/login?action=failed'});
  165. return res.end();
  166. } );
  167. }, error => {
  168. console.log( '- Dashboard: Error while getting the token: ' + error );
  169. res.writeHead(302, {Location: '/login?action=failed'});
  170. return res.end();
  171. } );
  172. }
  173. /**
  174. * Reload the guild of a user
  175. * @param {import('http').ServerResponse} res - The server response
  176. * @param {String} state - The user state
  177. * @param {String} [returnLocation] - The return location
  178. */
  179. function dashboard_refresh(res, state, returnLocation = '/') {
  180. var settings = settingsData.get(state);
  181. return oauth.getUserGuilds(settings.access_token).then( guilds => {
  182. guilds = guilds.filter( guild => {
  183. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  184. } ).map( guild => {
  185. return {
  186. id: guild.id,
  187. name: guild.name,
  188. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  189. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  190. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) : null ),
  191. userPermissions: guild.permissions
  192. };
  193. } );
  194. sendMsg( {
  195. type: 'getGuilds',
  196. member: settings.user.id,
  197. guilds: guilds.map( guild => guild.id )
  198. } ).then( response => {
  199. let isMember = new Map();
  200. let notMember = new Map();
  201. response.forEach( (guild, i) => {
  202. if ( guild ) {
  203. if ( guild === 'noMember' ) return;
  204. isMember.set(guilds[i].id, Object.assign(guilds[i], guild));
  205. }
  206. else notMember.set(guilds[i].id, guilds[i]);
  207. } );
  208. settings.guilds = {count: guilds.length, isMember, notMember};
  209. res.writeHead(302, {Location: returnLocation + '?refresh=success'});
  210. return res.end();
  211. }, error => {
  212. console.log( '- Dashboard: Error while getting the refreshed guilds:', error );
  213. res.writeHead(302, {Location: returnLocation + '?refresh=failed'});
  214. return res.end();
  215. } );
  216. }, error => {
  217. console.log( '- Dashboard: Error while refreshing guilds: ' + error );
  218. res.writeHead(302, {Location: returnLocation + '?refresh=failed'});
  219. return res.end();
  220. } );
  221. }
  222. /**
  223. * Check if a wiki is availabe
  224. * @param {import('http').ServerResponse} res - The server response
  225. * @param {String} input - The wiki to check
  226. */
  227. function dashboard_api(res, input) {
  228. var wiki = Wiki.fromInput('https://' + input + '/');
  229. var result = {
  230. api: true,
  231. error: false,
  232. error_code: '',
  233. wiki: wiki.href,
  234. MediaWiki: false,
  235. TextExtracts: false,
  236. PageImages: false,
  237. RcGcDw: '',
  238. customRcGcDw: wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit')
  239. };
  240. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general|extensions&format=json', {
  241. responseType: 'text'
  242. } ).then( response => {
  243. try {
  244. response.body = JSON.parse(response.body);
  245. }
  246. catch (error) {
  247. if ( response.statusCode === 404 && typeof response.body === 'string' ) {
  248. let api = cheerio.load(response.body)('head link[rel="EditURI"]').prop('href');
  249. if ( api ) {
  250. wiki = new Wiki(api.split('api.php?')[0], wiki);
  251. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general|extensions&format=json' );
  252. }
  253. }
  254. }
  255. return response;
  256. } ).then( response => {
  257. var body = response.body;
  258. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general || !body?.query?.extensions ) {
  259. console.log( '- Dashboard: ' + response.statusCode + ': Error while checking the wiki: ' + body?.error?.info );
  260. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  261. result.error_code = 'private';
  262. }
  263. result.error = true;
  264. return;
  265. }
  266. wiki.updateWiki(body.query.general);
  267. result.wiki = wiki.href;
  268. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) >= 30 ) {
  269. result.MediaWiki = true;
  270. }
  271. if ( body.query.extensions.some( extension => extension.name === 'TextExtracts' ) ) {
  272. result.TextExtracts = true;
  273. }
  274. if ( body.query.extensions.some( extension => extension.name === 'PageImages' ) ) {
  275. result.PageImages = true;
  276. }
  277. if ( body.query.allmessages[0]['*'] ) {
  278. result.RcGcDw = body.query.allmessages[0]['*'];
  279. }
  280. result.customRcGcDw = wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit');
  281. if ( wiki.isFandom() ) return;
  282. }, error => {
  283. 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' ) {
  284. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  285. result.error_code = 'http';
  286. result.error = true;
  287. return;
  288. }
  289. console.log( '- Dashboard: Error while checking the wiki: ' + error );
  290. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  291. result.error_code = 'timeout';
  292. }
  293. result.error = true;
  294. } ).finally( () => {
  295. let body = JSON.stringify(result);
  296. res.writeHead(200, {
  297. 'Content-Length': Buffer.byteLength(body),
  298. 'Content-Type': 'application/json'
  299. });
  300. res.write( body );
  301. return res.end();
  302. } );
  303. }
  304. module.exports = {
  305. login: dashboard_login,
  306. oauth: dashboard_oauth,
  307. refresh: dashboard_refresh,
  308. api: dashboard_api
  309. };