setup.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. const fs = require('fs');
  2. const NodeRSA = require('node-rsa');
  3. const config = require('config');
  4. const logger = require('./logger').setup;
  5. const certificateModel = require('./models/certificate');
  6. const userModel = require('./models/user');
  7. const userPermissionModel = require('./models/user_permission');
  8. const utils = require('./lib/utils');
  9. const authModel = require('./models/auth');
  10. const settingModel = require('./models/setting');
  11. const dns_plugins = require('./global/certbot-dns-plugins');
  12. const debug_mode = process.env.NODE_ENV !== 'production' || !!process.env.DEBUG;
  13. /**
  14. * Creates a new JWT RSA Keypair if not alread set on the config
  15. *
  16. * @returns {Promise}
  17. */
  18. const setupJwt = () => {
  19. return new Promise((resolve, reject) => {
  20. // Now go and check if the jwt gpg keys have been created and if not, create them
  21. if (!config.has('jwt') || !config.has('jwt.key') || !config.has('jwt.pub')) {
  22. logger.info('Creating a new JWT key pair...');
  23. // jwt keys are not configured properly
  24. const filename = config.util.getEnv('NODE_CONFIG_DIR') + '/' + (config.util.getEnv('NODE_ENV') || 'default') + '.json';
  25. let config_data = {};
  26. try {
  27. config_data = require(filename);
  28. } catch (err) {
  29. // do nothing
  30. if (debug_mode) {
  31. logger.debug(filename + ' config file could not be required');
  32. }
  33. }
  34. // Now create the keys and save them in the config.
  35. let key = new NodeRSA({ b: 2048 });
  36. key.generateKeyPair();
  37. config_data.jwt = {
  38. key: key.exportKey('private').toString(),
  39. pub: key.exportKey('public').toString(),
  40. };
  41. // Write config
  42. fs.writeFile(filename, JSON.stringify(config_data, null, 2), (err) => {
  43. if (err) {
  44. logger.error('Could not write JWT key pair to config file: ' + filename);
  45. reject(err);
  46. } else {
  47. logger.info('Wrote JWT key pair to config file: ' + filename);
  48. delete require.cache[require.resolve('config')];
  49. resolve();
  50. }
  51. });
  52. } else {
  53. // JWT key pair exists
  54. if (debug_mode) {
  55. logger.debug('JWT Keypair already exists');
  56. }
  57. resolve();
  58. }
  59. });
  60. };
  61. /**
  62. * Creates a default admin users if one doesn't already exist in the database
  63. *
  64. * @returns {Promise}
  65. */
  66. const setupDefaultUser = () => {
  67. return userModel
  68. .query()
  69. .select(userModel.raw('COUNT(`id`) as `count`'))
  70. .where('is_deleted', 0)
  71. .first()
  72. .then((row) => {
  73. if (!row.count) {
  74. // Create a new user and set password
  75. logger.info('Creating a new user: [email protected] with password: changeme');
  76. let data = {
  77. is_deleted: 0,
  78. email: '[email protected]',
  79. name: 'Administrator',
  80. nickname: 'Admin',
  81. avatar: '',
  82. roles: ['admin'],
  83. };
  84. return userModel
  85. .query()
  86. .insertAndFetch(data)
  87. .then((user) => {
  88. return authModel
  89. .query()
  90. .insert({
  91. user_id: user.id,
  92. type: 'password',
  93. secret: 'changeme',
  94. meta: {},
  95. })
  96. .then(() => {
  97. return userPermissionModel.query().insert({
  98. user_id: user.id,
  99. visibility: 'all',
  100. proxy_hosts: 'manage',
  101. redirection_hosts: 'manage',
  102. dead_hosts: 'manage',
  103. streams: 'manage',
  104. access_lists: 'manage',
  105. certificates: 'manage',
  106. });
  107. });
  108. })
  109. .then(() => {
  110. logger.info('Initial admin setup completed');
  111. });
  112. } else if (debug_mode) {
  113. logger.debug('Admin user setup not required');
  114. }
  115. });
  116. };
  117. /**
  118. * Creates default settings if they don't already exist in the database
  119. *
  120. * @returns {Promise}
  121. */
  122. const setupDefaultSettings = () => {
  123. return settingModel
  124. .query()
  125. .select(settingModel.raw('COUNT(`id`) as `count`'))
  126. .where({id: 'default-site'})
  127. .first()
  128. .then((row) => {
  129. if (!row.count) {
  130. settingModel
  131. .query()
  132. .insert({
  133. id: 'default-site',
  134. name: 'Default Site',
  135. description: 'What to show when Nginx is hit with an unknown Host',
  136. value: 'congratulations',
  137. meta: {},
  138. })
  139. .then(() => {
  140. logger.info('Default settings added');
  141. });
  142. }
  143. if (debug_mode) {
  144. logger.debug('Default setting setup not required');
  145. }
  146. });
  147. };
  148. /**
  149. * Installs all Certbot plugins which are required for an installed certificate
  150. *
  151. * @returns {Promise}
  152. */
  153. const setupCertbotPlugins = () => {
  154. return certificateModel
  155. .query()
  156. .where('is_deleted', 0)
  157. .andWhere('provider', 'letsencrypt')
  158. .then((certificates) => {
  159. if (certificates && certificates.length) {
  160. let plugins = [];
  161. let promises = [];
  162. certificates.map(function (certificate) {
  163. if (certificate.meta && certificate.meta.dns_challenge === true) {
  164. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  165. const packages_to_install = `${dns_plugin.package_name}${dns_plugin.version_requirement || ''} ${dns_plugin.dependencies}`;
  166. if (plugins.indexOf(packages_to_install) === -1) plugins.push(packages_to_install);
  167. // Make sure credentials file exists
  168. const credentials_loc = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  169. const credentials_cmd = '[ -f \'' + credentials_loc + '\' ] || { mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + certificate.meta.dns_provider_credentials.replace('\'', '\\\'') + '\' > \'' + credentials_loc + '\' && chmod 600 \'' + credentials_loc + '\'; }';
  170. promises.push(utils.exec(credentials_cmd));
  171. }
  172. });
  173. if (plugins.length) {
  174. const install_cmd = 'pip install ' + plugins.join(' ');
  175. promises.push(utils.exec(install_cmd));
  176. }
  177. if (promises.length) {
  178. return Promise.all(promises)
  179. .then(() => {
  180. logger.info('Added Certbot plugins ' + plugins.join(', '));
  181. });
  182. }
  183. }
  184. });
  185. };
  186. /**
  187. * Starts a timer to call run the logrotation binary every two days
  188. * @returns {Promise}
  189. */
  190. const setupLogrotation = () => {
  191. const intervalTimeout = 1000 * 60 * 60 * 24 * 2; // 2 days
  192. const runLogrotate = async () => {
  193. try {
  194. await utils.exec('logrotate /etc/logrotate.d/nginx-proxy-manager');
  195. logger.info('Logrotate completed.');
  196. } catch (e) { logger.warn(e); }
  197. };
  198. logger.info('Logrotate Timer initialized');
  199. setInterval(runLogrotate, intervalTimeout);
  200. // And do this now as well
  201. return runLogrotate();
  202. };
  203. module.exports = function () {
  204. return setupJwt()
  205. .then(setupDefaultUser)
  206. .then(setupDefaultSettings)
  207. .then(setupCertbotPlugins)
  208. .then(setupLogrotation);
  209. };