UNPKG

@sync-in/server

Version:

The secure, open-source platform for file storage, sharing, collaboration, and sync

192 lines (191 loc) 7.45 kB
/* * Copyright (C) 2012-2025 Johan Legrand <johan.legrand@sync-in.com> * This file is part of Sync-in | The open source file sync and share solution * See the LICENSE file for licensing details */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "configLoader", { enumerable: true, get: function() { return configLoader; } }); const _deepmerge = /*#__PURE__*/ _interop_require_default(require("deepmerge")); const _jsyaml = /*#__PURE__*/ _interop_require_wildcard(require("js-yaml")); const _nodefs = /*#__PURE__*/ _interop_require_default(require("node:fs")); const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path")); const _configconstants = require("./config.constants"); function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interop_require_wildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = { __proto__: null }; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for(var key in obj){ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function configLoader() { let config = loadEnvFile(_configconstants.ENVIRONMENT_PATH, _configconstants.ENVIRONMENT_FILE_NAME); if (hasEnvConfig()) { // If any environment vars are found, parse the config model and apply those settings const envConfig = getEnvOverrides(loadEnvFile(_configconstants.ENVIRONMENT_DIST_PATH, _configconstants.ENVIRONMENT_DIST_FILE_NAME, true)); config = (0, _deepmerge.default)(config, envConfig); } if (Object.keys(config).length === 0) { throw new Error(`Missing configuration: "${_configconstants.ENVIRONMENT_FILE_NAME}" not found, or no variables beginning with "${_configconstants.ENVIRONMENT_PREFIX}" are set.`); } if (config.logger?.stdout === false) { // ensure log directory exists const logFilePath = config.logger.filePath || _configconstants.DEFAULT_LOG_FILE_PATH; const dirLogPath = _nodepath.default.dirname(logFilePath); if (!_nodefs.default.existsSync(dirLogPath)) { _nodefs.default.mkdirSync(dirLogPath, { recursive: true }); } console.log(`Logging to file → ${logFilePath}`); } return config; } function buildPathsUp(basePath, fileName, levels = 4) { // Generates candidate file paths, optionally walking up from __dirname to a given depth. return Array.from({ length: levels + 1 }, (_, i)=>_nodepath.default.resolve(basePath, ...Array(i).fill('..'), fileName)); } function loadEnvFile(envPath, envFileName, throwIfMissing = false) { const candidates = [ envPath, envFileName, ...buildPathsUp(__dirname, envPath), ...buildPathsUp(__dirname, envFileName) ]; for (const envFilePath of candidates){ if (_nodefs.default.existsSync(envFilePath) && _nodefs.default.lstatSync(envFilePath).isFile()) { return _jsyaml.load(_nodefs.default.readFileSync(envFilePath, 'utf8')); } } if (throwIfMissing) { throw new Error(`${envFileName} not found`); } return {}; } function hasEnvConfig() { return Object.keys(process.env).some((key)=>key.startsWith(_configconstants.ENVIRONMENT_PREFIX)); } /** * Parse a raw env-string into boolean, number or leave as string. */ function parseEnvValue(value) { // remove first and last quote if exists value = value.replace(/^"(.*)"$/, '$1'); if (value === 'true') return true; if (value === 'false') return false; if (!isNaN(Number(value))) return Number(value); return value; } /** * Assigns a nested property into obj, creating sub-objects as needed. */ function setObjectPropertyFromString(obj, property, value) { const segments = property.split('.'); let cursor = obj; for(let i = 0; i < segments.length - 1; i++){ const seg = segments[i]; if (!(seg in cursor) || typeof cursor[seg] !== 'object') { cursor[seg] = {}; } cursor = cursor[seg]; } cursor[segments[segments.length - 1]] = value; } /** * Returns a new object containing only the env-var overrides * that match existing keys in `config`, nested and cased properly. */ function getEnvOverrides(config) { const result = {}; for (const [envKey, rawValue] of Object.entries(process.env)){ if (!envKey.startsWith(_configconstants.ENVIRONMENT_PREFIX) || rawValue === undefined) { continue; } // ["APPLICATIONS","FILES","DATAPATH"] etc. const segments = envKey.slice(_configconstants.ENVIRONMENT_PREFIX.length).split('_'); const secretFromFile = segments[segments.length - 1] === 'FILE'; if (secretFromFile) { // remove FILE attribute segments.pop(); } // Walk through config to validate path & capture real key names let cursorConfig = config; const realSegments = []; let pathExists = true; for (const seg of segments){ if (cursorConfig == null || typeof cursorConfig !== 'object') { pathExists = false; break; } // Find the actual key (preserving camelCase) whose uppercase matches seg const match = Object.keys(cursorConfig).find((k)=>k.toUpperCase() === seg); if (!match) { pathExists = false; break; } realSegments.push(match); cursorConfig = cursorConfig[match]; } if (!pathExists) { console.warn(`Ignoring unknown environment variable: "${envKey}".`); continue; } // Build the nested override in `result` const path = realSegments.join('.'); if (secretFromFile) { try { setObjectPropertyFromString(result, path, _nodefs.default.readFileSync(rawValue, 'utf-8').trim()); } catch (e) { console.error(`Unable to store secret from file ${rawValue} : ${e}`); } } else { setObjectPropertyFromString(result, path, parseEnvValue(rawValue)); } } return result; } //# sourceMappingURL=config.loader.js.map