config.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import fs from "node:fs";
  2. import NodeRSA from "node-rsa";
  3. import { global as logger } from "../logger.js";
  4. const keysFile = '/data/keys.json';
  5. const mysqlEngine = 'mysql2';
  6. const postgresEngine = 'pg';
  7. const sqliteClientName = 'sqlite3';
  8. let instance = null;
  9. // 1. Load from config file first (not recommended anymore)
  10. // 2. Use config env variables next
  11. const configure = () => {
  12. const filename = `${process.env.NODE_CONFIG_DIR || "./config"}/${process.env.NODE_ENV || "default"}.json`;
  13. if (fs.existsSync(filename)) {
  14. let configData;
  15. try {
  16. // Load this json synchronously
  17. const rawData = fs.readFileSync(filename);
  18. configData = JSON.parse(rawData);
  19. } catch (_) {
  20. // do nothing
  21. }
  22. if (configData?.database) {
  23. logger.info(`Using configuration from file: ${filename}`);
  24. instance = configData;
  25. instance.keys = getKeys();
  26. return;
  27. }
  28. }
  29. const toBool = (v) => /^(1|true|yes|on)$/i.test((v || '').trim());
  30. const envMysqlHost = process.env.DB_MYSQL_HOST || null;
  31. const envMysqlUser = process.env.DB_MYSQL_USER || null;
  32. const envMysqlName = process.env.DB_MYSQL_NAME || null;
  33. const envMysqlSSL = toBool(process.env.DB_MYSQL_SSL);
  34. const envMysqlSSLRejectUnauthorized = process.env.DB_MYSQL_SSL_REJECT_UNAUTHORIZED === undefined ? true : toBool(process.env.DB_MYSQL_SSL_REJECT_UNAUTHORIZED);
  35. const envMysqlSSLVerifyIdentity = process.env.DB_MYSQL_SSL_VERIFY_IDENTITY === undefined ? true : toBool(process.env.DB_MYSQL_SSL_VERIFY_IDENTITY);
  36. if (envMysqlHost && envMysqlUser && envMysqlName) {
  37. // we have enough mysql creds to go with mysql
  38. logger.info("Using MySQL configuration");
  39. instance = {
  40. database: {
  41. engine: mysqlEngine,
  42. host: envMysqlHost,
  43. port: process.env.DB_MYSQL_PORT || 3306,
  44. user: envMysqlUser,
  45. password: process.env.DB_MYSQL_PASSWORD,
  46. name: envMysqlName,
  47. ssl: envMysqlSSL ? { rejectUnauthorized: envMysqlSSLRejectUnauthorized, verifyIdentity: envMysqlSSLVerifyIdentity } : false,
  48. },
  49. keys: getKeys(),
  50. };
  51. return;
  52. }
  53. const envPostgresHost = process.env.DB_POSTGRES_HOST || null;
  54. const envPostgresUser = process.env.DB_POSTGRES_USER || null;
  55. const envPostgresName = process.env.DB_POSTGRES_NAME || null;
  56. if (envPostgresHost && envPostgresUser && envPostgresName) {
  57. // we have enough postgres creds to go with postgres
  58. logger.info("Using Postgres configuration");
  59. instance = {
  60. database: {
  61. engine: postgresEngine,
  62. host: envPostgresHost,
  63. port: process.env.DB_POSTGRES_PORT || 5432,
  64. user: envPostgresUser,
  65. password: process.env.DB_POSTGRES_PASSWORD,
  66. name: envPostgresName,
  67. },
  68. keys: getKeys(),
  69. };
  70. return;
  71. }
  72. const envSqliteFile = process.env.DB_SQLITE_FILE || "/data/database.sqlite";
  73. logger.info(`Using Sqlite: ${envSqliteFile}`);
  74. instance = {
  75. database: {
  76. engine: "knex-native",
  77. knex: {
  78. client: sqliteClientName,
  79. connection: {
  80. filename: envSqliteFile,
  81. },
  82. useNullAsDefault: true,
  83. },
  84. },
  85. keys: getKeys(),
  86. };
  87. };
  88. const getKeys = () => {
  89. // Get keys from file
  90. logger.debug("Cheecking for keys file:", keysFile);
  91. if (!fs.existsSync(keysFile)) {
  92. generateKeys();
  93. } else if (process.env.DEBUG) {
  94. logger.info("Keys file exists OK");
  95. }
  96. try {
  97. // Load this json keysFile synchronously and return the json object
  98. const rawData = fs.readFileSync(keysFile);
  99. return JSON.parse(rawData);
  100. } catch (err) {
  101. logger.error(`Could not read JWT key pair from config file: ${keysFile}`, err);
  102. process.exit(1);
  103. }
  104. };
  105. const generateKeys = () => {
  106. logger.info("Creating a new JWT key pair...");
  107. // Now create the keys and save them in the config.
  108. const key = new NodeRSA({ b: 2048 });
  109. key.generateKeyPair();
  110. const keys = {
  111. key: key.exportKey("private").toString(),
  112. pub: key.exportKey("public").toString(),
  113. };
  114. // Write keys config
  115. try {
  116. fs.writeFileSync(keysFile, JSON.stringify(keys, null, 2));
  117. } catch (err) {
  118. logger.error(`Could not write JWT key pair to config file: ${keysFile}: ${err.message}`);
  119. process.exit(1);
  120. }
  121. logger.info(`Wrote JWT key pair to config file: ${keysFile}`);
  122. };
  123. /**
  124. *
  125. * @param {string} key ie: 'database' or 'database.engine'
  126. * @returns {boolean}
  127. */
  128. const configHas = (key) => {
  129. instance === null && configure();
  130. const keys = key.split(".");
  131. let level = instance;
  132. let has = true;
  133. keys.forEach((keyItem) => {
  134. if (typeof level[keyItem] === "undefined") {
  135. has = false;
  136. } else {
  137. level = level[keyItem];
  138. }
  139. });
  140. return has;
  141. };
  142. /**
  143. * Gets a specific key from the top level
  144. *
  145. * @param {string} key
  146. * @returns {*}
  147. */
  148. const configGet = (key) => {
  149. instance === null && configure();
  150. if (key && typeof instance[key] !== "undefined") {
  151. return instance[key];
  152. }
  153. return instance;
  154. };
  155. /**
  156. * Is this a sqlite configuration?
  157. *
  158. * @returns {boolean}
  159. */
  160. const isSqlite = () => {
  161. instance === null && configure();
  162. return instance.database.knex && instance.database.knex.client === sqliteClientName;
  163. };
  164. /**
  165. * Is this a mysql configuration?
  166. *
  167. * @returns {boolean}
  168. */
  169. const isMysql = () => {
  170. instance === null && configure();
  171. return instance.database.engine === mysqlEngine;
  172. };
  173. /**
  174. * Is this a postgres configuration?
  175. *
  176. * @returns {boolean}
  177. */
  178. const isPostgres = () => {
  179. instance === null && configure();
  180. return instance.database.engine === postgresEngine;
  181. };
  182. /**
  183. * Are we running in debug mdoe?
  184. *
  185. * @returns {boolean}
  186. */
  187. const isDebugMode = () => !!process.env.DEBUG;
  188. /**
  189. * Are we running in CI?
  190. *
  191. * @returns {boolean}
  192. */
  193. const isCI = () => process.env.CI === 'true' && process.env.DEBUG === 'true';
  194. /**
  195. * Returns a public key
  196. *
  197. * @returns {string}
  198. */
  199. const getPublicKey = () => {
  200. instance === null && configure();
  201. return instance.keys.pub;
  202. };
  203. /**
  204. * Returns a private key
  205. *
  206. * @returns {string}
  207. */
  208. const getPrivateKey = () => {
  209. instance === null && configure();
  210. return instance.keys.key;
  211. };
  212. /**
  213. * @returns {boolean}
  214. */
  215. const useLetsencryptStaging = () => !!process.env.LE_STAGING;
  216. /**
  217. * @returns {string|null}
  218. */
  219. const useLetsencryptServer = () => {
  220. if (process.env.LE_SERVER) {
  221. return process.env.LE_SERVER;
  222. }
  223. return null;
  224. };
  225. export { isCI, configHas, configGet, isSqlite, isMysql, isPostgres, isDebugMode, getPrivateKey, getPublicKey, useLetsencryptStaging, useLetsencryptServer };