setup.js 6.9 KB

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