setup.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. let install_cloudflare_plugin = false;
  163. certificates.map(function (certificate) {
  164. if (certificate.meta && certificate.meta.dns_challenge === true) {
  165. const dns_plugin = dns_plugins[certificate.meta.dns_provider];
  166. if (dns_plugin.package_name === 'certbot-dns-cloudflare') {
  167. install_cloudflare_plugin = true;
  168. } else {
  169. const packages_to_install = `${dns_plugin.package_name}${dns_plugin.version_requirement || ''} ${dns_plugin.dependencies}`;
  170. if (plugins.indexOf(packages_to_install) === -1) plugins.push(packages_to_install);
  171. }
  172. // Make sure credentials file exists
  173. const credentials_loc = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  174. // Escape single quotes and backslashes
  175. const escapedCredentials = certificate.meta.dns_provider_credentials.replaceAll('\'', '\\\'').replaceAll('\\', '\\\\');
  176. const credentials_cmd = '[ -f \'' + credentials_loc + '\' ] || { mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + escapedCredentials + '\' > \'' + credentials_loc + '\' && chmod 600 \'' + credentials_loc + '\'; }';
  177. promises.push(utils.exec(credentials_cmd));
  178. }
  179. });
  180. if (plugins.length) {
  181. const install_cmd = 'pip install ' + plugins.join(' ');
  182. promises.push(utils.exec(install_cmd));
  183. }
  184. if (install_cloudflare_plugin) {
  185. promises.push(utils.exec('pip install certbot-dns-cloudflare --index-url https://www.piwheels.org/simple --prefer-binary'));
  186. }
  187. if (promises.length) {
  188. return Promise.all(promises)
  189. .then(() => {
  190. logger.info('Added Certbot plugins ' + plugins.join(', '));
  191. });
  192. }
  193. }
  194. });
  195. };
  196. /**
  197. * Starts a timer to call run the logrotation binary every two days
  198. * @returns {Promise}
  199. */
  200. const setupLogrotation = () => {
  201. const intervalTimeout = 1000 * 60 * 60 * 24 * 2; // 2 days
  202. const runLogrotate = async () => {
  203. try {
  204. await utils.exec('logrotate /etc/logrotate.d/nginx-proxy-manager');
  205. logger.info('Logrotate completed.');
  206. } catch (e) { logger.warn(e); }
  207. };
  208. logger.info('Logrotate Timer initialized');
  209. setInterval(runLogrotate, intervalTimeout);
  210. // And do this now as well
  211. return runLogrotate();
  212. };
  213. module.exports = function () {
  214. return setupJwt()
  215. .then(setupDefaultUser)
  216. .then(setupDefaultSettings)
  217. .then(setupCertbotPlugins)
  218. .then(setupLogrotation);
  219. };