{"id":14155125,"url":"https://github.com/tsmx/secure-config","last_synced_at":"2025-05-02T17:33:37.797Z","repository":{"id":42500068,"uuid":"283006694","full_name":"tsmx/secure-config","owner":"tsmx","description":"Easy and secure NodeJS configuration management.","archived":false,"fork":false,"pushed_at":"2024-09-05T18:54:41.000Z","size":423,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-06T18:01:25.463Z","etag":null,"topics":["aes","configuration","configuration-management","credentials","crypto","encryption-at-rest","environment","hmac","json","key","multi-environment","nodejs","secret"],"latest_commit_sha":null,"homepage":"https://tsmx.net/secure-config/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tsmx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-27T20:18:27.000Z","updated_at":"2024-09-05T18:52:47.000Z","dependencies_parsed_at":"2023-02-15T19:01:01.020Z","dependency_job_id":"395ca1f2-d6fc-481e-88d5-27b576bc1f1e","html_url":"https://github.com/tsmx/secure-config","commit_stats":{"total_commits":103,"total_committers":3,"mean_commits":"34.333333333333336","dds":0.3398058252427184,"last_synced_commit":"4643a4bd92abc73a2058b1a2c56226f182ef8f24"},"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsmx%2Fsecure-config","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsmx%2Fsecure-config/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsmx%2Fsecure-config/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsmx%2Fsecure-config/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tsmx","download_url":"https://codeload.github.com/tsmx/secure-config/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224324404,"owners_count":17292521,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aes","configuration","configuration-management","credentials","crypto","encryption-at-rest","environment","hmac","json","key","multi-environment","nodejs","secret"],"created_at":"2024-08-17T08:02:10.240Z","updated_at":"2024-11-12T18:10:39.419Z","avatar_url":"https://github.com/tsmx.png","language":"JavaScript","funding_links":[],"categories":["nodejs"],"sub_categories":[],"readme":"# [**@tsmx/secure-config**](https://github.com/tsmx/secure-config)\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)\n![npm (scoped)](https://img.shields.io/npm/v/@tsmx/secure-config)\n![node-current (scoped)](https://img.shields.io/node/v/@tsmx/secure-config)\n[![Build Status](https://img.shields.io/github/actions/workflow/status/tsmx/secure-config/git-build.yml?branch=master)](https://img.shields.io/github/actions/workflow/status/tsmx/secure-config/git-build.yml?branch=master)\n[![Coverage Status](https://coveralls.io/repos/github/tsmx/secure-config/badge.svg?branch=master)](https://coveralls.io/github/tsmx/secure-config?branch=master)\n\n\u003e Easy and secure configuration management. \n\nManage JSON based configurations with encrypted secrets and optional HMAC validation to ensure data integrity.\n\nWorks with CommonJS and ESM/ECMAScript.\n\nIf you are upgrading from an older version prior to 2.x please read this [important note](#upgrading-from-versions-prior-to-2x).\n\n## Usage\n\n1. Encrypt sensitive data in your JSON configuration file. Most easy way to do this is using the [secure-config-tool](https://www.npmjs.com/package/@tsmx/secure-config-tool).\nFor more details please see [generating an encrypted configuration](#generating-an-encrypted-configuration) and [naming conventions](#naming-conventions).\n    ```json\n    {\n      \"database\": {\n        \"host\": \"127.0.0.1\",\n        \"user\": \"ENCRYPTED|50ceed2f97223100fbdf842ecbd4541f|df9ed9002bfc956eb14b1d2f8d960a11\",\n        \"pass\": \"ENCRYPTED|8fbf6ded36bcb15bd4734b3dc78f2890|7463b2ea8ed2c8d71272ac2e41761a35\"\n      }\n    }\n    ```\n\n2. Use your configuration in the code.\n    ```js\n    // CommonJS\n    const conf = require('@tsmx/secure-config')();\n\n    // ESM\n    import secureConfig from '@tsmx/secure-config';\n    const conf = secureConfig();\n\n    function MyFunc() {\n      let dbHost = conf.database.host; // = '127.0.0.1'\n      let dbUser = conf.database.user; // = 'MySecretDbUser'\n      let dbPass = conf.database.pass; // = 'MySecretDbPass'\n      //...\n    }\n    ```\n    For further customization and advanced features like HMAC validation you can pass an options object - please refer to the [options section](#options).\n\n3. Run your app. See below for different [options on how to pass the key](#injecting-the-decryption-key).\n   ```bash\n   $ export CONFIG_ENCRYPTION_KEY=...\n   $ node app.js\n   ```\n\nA fully working [example project](https://github.com/tsmx/secure-config-test) is also available on GitHub. \n\nTo get all information please also check out the [full documentation](https://tsmx.net/secure-config/).\n\n## Naming conventions\n\nYou can have multiple configuration files for different environments or stages. They are distinguished by the environment variable `NODE_ENV`. The basic configuration file name is `config.json` if this variable is not present. If it is present, a configuration file with the name `config-[NODE_ENV].json`\nis used. An exception will be thrown if no configuration file is found.\n\nTo change the default configuration file name or loading multiple configuration files you can pass the [prefix](#prefix) option.\n\nBy default, all configuration files are expected be located in a `conf/` directory of the current running app, meaning a direct subdirectory of the current working directory (`CWD/conf/`). To overwrite this behaviour, you can pass the [directory](#directory) option.\n\n### Example structure\n\n| Stage       | Value of NODE_ENV | Filename                    | \n|-------------|-------------------|-----------------------------|\n| Development | not set           | conf/config.json            | \n| Production  | `production`      | conf/config-production.json | \n| Test        | `test`            | conf/config-test.json       |\n\nResulting folders/files setup:\n```\npath-to-your-app/\n├── conf/\n│   ├── config.json\n│   ├── config-production.json\n│   └── config-test.json\n├── app.js\n└── package.json\n```\n\n## Options\n\nTo retrieve a configuration using all default values and without advanced features, you simply invoke a function after the require/import statement without any argument (set of parenthesis after `require` or simple method call after `import`).\n\n```js\n// CommonJS\nconst conf = require('@tsmx/secure-config')();\n\n// ESM\nimport secureConfig from '@tsmx/secure-config';\nconst conf = secureConfig();\n```\n\nTo make use of the more advanced features and customize default values, you can pass an options object to this function call.\n\n```js\nconst confOptions = {\n  keyVariable: 'CUSTOM_CONFIG_KEY',\n  hmacValidation: true, \n  hmacProperty: '_signature',\n  directory: '/path/to/config',\n  prefix: 'myconf'\n}\n\n// CommonJS\nconst conf = require('@tsmx/secure-config')(confOptions);\n\n// ESM\nimport secureConfig from '@tsmx/secure-config';\nconst conf = secureConfig(confOptions);\n```\n\nThe following options are available.\n\n### keyVariable\n\nType: `String`\nDefault: `CONFIG_ENCRYPTION_KEY`\n\nThe name of the environment variable containing the key for decrypting configuration values and validating the HMAC. See also [options on how to pass the key](#injecting-the-decryption-key).\n\n### hmacValidation\n\nType: `Boolean`\nDefault: `false`\n\nSpecifies if the loaded configuration should be validated against a given HMAC. If set to true, secure-config will validate the HMAC of the decrypted configuration content against a given HMAC using the current key. If the validation fails, an exception will be thrown. If it succeeds, the decrypted configuration will be returned.\n\nThe given HMAC is retrieved from a configuration file property with the name of [hmacProperty](#hmacProperty), e.g.:\n\n```json\n{\n  \"database\": {\n    \"host\": \"127.0.0.1\",\n    \"user\": \"ENCRYPTED|50ceed2f97223100fbdf842ecbd4541f|df9ed9002bfc956eb14b1d2f8d960a11\",\n    \"pass\": \"ENCRYPTED|8fbf6ded36bcb15bd4734b3dc78f2890|7463b2ea8ed2c8d71272ac2e41761a35\"\n  },\n  \"__hmac\": \"3023eb8cf76894c0d5c7f893819916d876f98f781f8944b77e87257ef77c1adf\"\n}\n```\n\nEnabling this option is recommended for production environments as it adds more security to your configuration management ensuring the loaded configuration is safe against tampering. Unwanted modifications of any - even unencrypted - entries in your configuration would cause the HMAC validation to fail and throw the error `HMAC validation failed`.\n\nPlease ensure that your stored configuration files have an appropriate HMAC property before enabling this option. Otherwise loading the configuration would always fail. [secure-config-tool](https://www.npmjs.com/package/@tsmx/secure-config-tool) adds the HMAC by default when creating secured configuration files.\n\nTo get more information on how the HMAC creation \u0026 validation works under the hood, please refer to the package [object-hmac](https://www.npmjs.com/package/@tsmx/object-hmac) which is used for that. The HMAC value is created out of the entire configuration object before optional encryption is applied.\n\n### hmacProperty\n\nType: `String`\nDefault: `__hmac`\n\nThe name of the HMAC property in a configuration file to be validated against. Only used when [hmacValidation](#hmacValidation) is set tor `true`.\n\nExample configuration file using a custom HMAC property name:\n```json\n{\n  \"database\": {\n    \"host\": \"127.0.0.1\",\n    \"user\": \"ENCRYPTED|50ceed2f97223100fbdf842ecbd4541f|df9ed9002bfc956eb14b1d2f8d960a11\",\n    \"pass\": \"ENCRYPTED|8fbf6ded36bcb15bd4734b3dc78f2890|7463b2ea8ed2c8d71272ac2e41761a35\"\n  },\n  \"_signature\": \"3023eb8cf76894c0d5c7f893819916d876f98f781f8944b77e87257ef77c1adf\"\n}\n```\n\nLoading the configuration with HMAC validation enabled:\n```js\nconst confOptions = {\n    hmacValidation: true, \n    hmacProperty: '_signature'\n}\nconst conf = require('@tsmx/secure-config')(confOptions);\n```\n\n### directory\n\nType: `String`\nDefault: `./conf/`\n\nUse this parameter to change the directory where the configuration files should be loaded from.\n\nE.g. if the files are located under `/var/myapp/configurations`:\n\n```js\nconst confOptions = {\n    directory: '/var/myapp/configurations'\n}\nconst conf = require('@tsmx/secure-config')(confOptions);\n```\n\nThis option can be combined with the [prefix](#prefix) option to control the configuration filenames within the directory. [Naming conventions](#naming-conventions) according to `NODE_ENV` are applied as normal.\n\n***Hint:*** Setting a relative path within the current running app or an unit-test can easily be achieved by using `path.join` with `process.cwd`. E.g. if the files are located in `./test/configurations`.\n\n```js\nconst confOptions = {\n    directory: path.join(process.cwd(), 'test/configurations')\n}\n```\n\n### prefix\n\nType: `String`\nDefault: `config`\n\nUse this parameter to change the default file name pattern from `config-[NODE_ENV].json` to `[prefix]-[NODE_ENV].json` for loading files with deviating names or additional ones. The value of `NODE_ENV` will be evaluated as described in the [naming conventions](#naming-conventions).\n\nTo load multiple configurations, use the following pattern in your code.\n\n```js\nconst secureConf = require('@tsmx/secure-config');\nconst config = secureConf();\nconst myconf = secureConf({ prefix: 'myconf', keyVariable: 'MYCONF_KEY' });\n```\n\nThis example will load the default `config.json` using the the key from environment variable `CONFIG_ENCRYPTION_KEY` as well as the additional `myconf.json` using  the key from `MYCONF_KEY`. Note that different configurations should use different encryption keys. \n\nDepending on the value of `NODE_ENV` the following configuration files will be loaded in this example.\n\n| Value of NODE_ENV | variable             | Filename                                                   | \n|-------------------|----------------------|------------------------------------------------------------|\n| not set           | `config`\u003cbr\u003e`myconf` | conf/config.json\u003cbr\u003econf/myconf.json                       | \n| `production`      | `config`\u003cbr\u003e`myconf` | conf/config-production.json\u003cbr\u003econf/myconf-production.json | \n| `test`            | `config`\u003cbr\u003e`myconf` | conf/config-test.json\u003cbr\u003econf/myconfig-test.json           |\n\n## Injecting the decryption key\n\nThe key for decrypting the encrypted values is derived from an environment variable. The default name of this variable is `CONFIG_ENCRYPTION_KEY`, but you can also pass any other name via [options](#options). You can set the environment variable whatever way is most suitable, e.g.\n\n- set/export in the command line or in your bash pofile\n  ```\n  export CONFIG_ENCRYPTION_KEY=0123456789qwertzuiopasdfghjklyxc\n  ```\n- using an env block in your VS-Code launch configuration\n  ```json\n  \"env\": {\n    \"CONFIG_ENCRYPTION_KEY\": \"0123456789qwertzuiopasdfghjklyxc\"\n  }\n  ```\n- using an env block in your deployment descriptor, e.g. app.yaml for Google App Engine\n  ```yaml\n  env_variables:\n    CONFIG_ENCRYPTION_KEY: \"0123456789qwertzuiopasdfghjklyxc\"\n  ```\n- for testing with [Jest](https://jestjs.io/) I recommend to create a test key and set it globally for all tests in the `jest.config.js`, e.g.\n  ```javascript\n  process.env['CONFIG_ENCRYPTION_KEY'] = '0123456789qwertzuiopasdfghjklyxc';\n\n  module.exports = {\n      testEnvironment: 'node'\n  };\n  ```\n- etc.\n\nMore examples are available in the [full documentation](https://tsmx.net/secure-config/).\n\nThe key length must be 32 bytes! The value set in `CONFIG_ENCRYPTION_KEY` has to be:\n- a string of 32 characters length, or\n- a hexadecimal value of 64 characters length (= 32 bytes)\n\nOtherwise an error will be thrown.\n\nExamples of valid key strings:\n- 32 byte string: `MySecretConfigurationKey-123$%\u0026/`\n- 32 byte hex value: `9af7d400be4705147dc724db25bfd2513aa11d6013d7bf7bdb2bfe050593bd0f`\n\nDifferent keys for each configuration environment are strongly recommended.\n\n## Generating an encrypted configuration\n\n### Option 1: secure-config-tool\n\nFor better convenience I provided a very basic [secure-config-tool](https://www.npmjs.com/package/@tsmx/secure-config-tool) to easily generate encrypted configuration files with an optional HMAC.\n\n### Option 2: NodeJS crypto functions \n\nYou can also simply use `crypto` functions from NodeJS with the following snippet to create the encrypted entries in a configuration file on your own:\n\n```js\nconst crypto = require('crypto');\nconst algorithm = 'aes-256-cbc';\n\nfunction encrypt(value) {\n  let iv = crypto.randomBytes(16);\n  let key = Buffer.from('YOUR_KEY_HERE');\n  let cipher = crypto.createCipheriv(algorithm, key, iv);\n  let encrypted = cipher.update(value);\n  encrypted = Buffer.concat([encrypted, cipher.final()]);\n  return 'ENCRYPTED|' + iv.toString('hex') + '|' + encrypted.toString('hex');\n}\n```\n\n### Remarks\n\nThe generated encrypted entry must always have the form: `ENCRYPTED | IV | DATA`. \n\n| Part        | Description |\n|-------------|-------------|\n| `ENCRYPTED` | The prefix `ENCRYPTED` used to identify configuration values that must be decrypted. |\n| `IV`        | The ciphers initialization vector (IV) that was used for encryption. Hexadecimal value. |\n| `DATA`      | The AES-256-CBC encrypted value. Hexadecimal value. |\n\n## Upgrading from versions prior to 2.x\n\nIn versions before 2.x, secure-config directly exported the configuration object when requiring in the module. To add more flexibility and being able to provide new features, this was changed in the 2.x versions. The module now exports a function which can receive additional [options](#options). \n\nSince there's a full backward compatibility, all you have to do in your existing code using version 1.x so far is to invoke the function by adding a set of parenthesis.\n\n```js\n// version 1.x - requiring in without any function call\nconst conf = require('@tsmx/secure-config');\n\n// version 2.x - change to that for retaining full backward compatibility\nconst conf = require('@tsmx/secure-config')();\n\n// use conf as you did before...\n```\n\n## Changelog\n\n### 2.1.0\n- Support for encrypted properties of objects in arrays added, e.g. `{  configArray: [ { key: 'ENCRYPTED|...' }, { key: 'ENCRYPTED|... ' } ] }`\n\n### 2.2.0\n- Support for loading multiple configurations with new option [prefix](#prefix) added.\n\n### 2.3.0\n- Support for custom configuration file path with new option [directory](#directory) added.\n\n## Test\n\n```\nnpm install\nnpm test\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftsmx%2Fsecure-config","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftsmx%2Fsecure-config","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftsmx%2Fsecure-config/lists"}