setup.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. ssl_passthrough_hosts: 'manage',
  106. streams: 'manage',
  107. access_lists: 'manage',
  108. certificates: 'manage',
  109. });
  110. });
  111. })
  112. .then(() => {
  113. logger.info('Initial admin setup completed');
  114. });
  115. } else if (debug_mode) {
  116. logger.debug('Admin user setup not required');
  117. }
  118. });
  119. };
  120. /**
  121. * Creates default settings if they don't already exist in the database
  122. *
  123. * @returns {Promise}
  124. */
  125. const setupDefaultSettings = () => {
  126. return settingModel
  127. .query()
  128. .select(settingModel.raw('COUNT(`id`) as `count`'))
  129. .where({id: 'default-site'})
  130. .first()
  131. .then((row) => {
  132. if (!row.count) {
  133. settingModel
  134. .query()
  135. .insert({
  136. id: 'default-site',
  137. name: 'Default Site',
  138. description: 'What to show when Nginx is hit with an unknown Host',
  139. value: 'congratulations',
  140. meta: {},
  141. })
  142. .then(() => {
  143. logger.info('Default settings added');
  144. });
  145. }
  146. if (debug_mode) {
  147. logger.debug('Default setting setup not required');
  148. }
  149. });
  150. };
  151. /**
  152. * Installs all Certbot plugins which are required for an installed certificate
  153. *
  154. * @returns {Promise}
  155. */
  156. const setupCertbotPlugins = () => {
  157. return certificateModel
  158. .query()
  159. .where('is_deleted', 0)
  160. .andWhere('provider', 'letsencrypt')
  161. .then((certificates) => {
  162. if (certificates && certificates.length) {
  163. let plugins = [];
  164. let promises = [];
  165. certificates.map(function (certificate) {
  166. if (certificate.meta && certificate.meta.dns_challenge === true) {
  167. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  168. const packages_to_install = `${dns_plugin.package_name}==${dns_plugin.package_version} ${dns_plugin.dependencies}`;
  169. if (plugins.indexOf(packages_to_install) === -1) plugins.push(packages_to_install);
  170. // Make sure credentials file exists
  171. const credentials_loc = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  172. 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 + '\'; }';
  173. promises.push(utils.exec(credentials_cmd));
  174. }
  175. });
  176. if (plugins.length) {
  177. const install_cmd = 'pip install ' + plugins.join(' ');
  178. promises.push(utils.exec(install_cmd));
  179. }
  180. if (promises.length) {
  181. return Promise.all(promises)
  182. .then(() => {
  183. logger.info('Added Certbot plugins ' + plugins.join(', '));
  184. });
  185. }
  186. }
  187. });
  188. };
  189. /**
  190. * Starts a timer to call run the logrotation binary every two days
  191. * @returns {Promise}
  192. */
  193. const setupLogrotation = () => {
  194. const intervalTimeout = 1000 * 60 * 60 * 24 * 2; // 2 days
  195. const runLogrotate = async () => {
  196. try {
  197. await utils.exec('logrotate /etc/logrotate.d/nginx-proxy-manager');
  198. logger.info('Logrotate completed.');
  199. } catch (e) { logger.warn(e); }
  200. };
  201. logger.info('Logrotate Timer initialized');
  202. setInterval(runLogrotate, intervalTimeout);
  203. // And do this now as well
  204. return runLogrotate();
  205. };
  206. /**
  207. * Makes sure the ssl passthrough option is reflected in the nginx config
  208. * @returns {Promise}
  209. */
  210. const setupSslPassthrough = () => {
  211. return internalNginx.configure(passthroughHostModel, 'ssl_passthrough_host', {}).then(() => internalNginx.reload());
  212. };
  213. module.exports = function () {
  214. return setupJwt()
  215. .then(setupDefaultUser)
  216. .then(setupDefaultSettings)
  217. .then(setupCertbotPlugins)
  218. .then(setupLogrotation)
  219. .then(setupSslPassthrough);
  220. };