├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── deploy.yml │ ├── main.yml │ └── size.yml ├── .gitignore ├── LICENSE ├── README.md ├── jest.config.js ├── package.json ├── src ├── createConsolaExporter.ts ├── index.ts ├── interfaces │ └── options.interface.ts ├── maskLeakedSecret.ts ├── scanString.ts ├── secureLog.ts ├── test.ts ├── utils │ ├── checkForPotentialSecrets.ts │ ├── handleSecretLeakResult.ts │ ├── index.ts │ ├── maskLeakedSecrets.ts │ ├── stringOccurInObjectValue.ts │ └── utils.ts └── validateSecretLeak.ts ├── test.js ├── test ├── consola.test.ts └── log.test.ts ├── tsconfig.json ├── tsdx.config.js └── yarn.lock /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: main 4 | jobs: 5 | publish: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v3 9 | - uses: actions/setup-node@v3 10 | with: 11 | node-version: "18" 12 | - run: yarn install 13 | - run: yarn build 14 | - uses: JS-DevTools/npm-publish@v2 15 | with: 16 | token: ${{ secrets.NPM_TOKEN_PUBLIC }} 17 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | build: 10 | name: Build, lint, and test on Node ${{ matrix.node }} and ${{ matrix.os }} 11 | 12 | runs-on: ${{ matrix.os }} 13 | strategy: 14 | matrix: 15 | node: ['18.x'] 16 | os: [ubuntu-latest, windows-latest, macOS-latest] 17 | 18 | steps: 19 | - name: Checkout repo 20 | uses: actions/checkout@v2 21 | 22 | - name: Use Node ${{ matrix.node }} 23 | uses: actions/setup-node@v1 24 | with: 25 | node-version: ${{ matrix.node }} 26 | 27 | - name: Install deps 28 | run: yarn install 29 | 30 | - name: Build 31 | run: yarn build 32 | 33 | - name: Test 34 | run: yarn test 35 | 36 | # - name: Upload coverage reports to Codecov 37 | # uses: codecov/codecov-action@v3 38 | # env: 39 | # CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 40 | -------------------------------------------------------------------------------- /.github/workflows/size.yml: -------------------------------------------------------------------------------- 1 | # name: size 2 | # on: [pull_request] 3 | # jobs: 4 | # size: 5 | # runs-on: ubuntu-latest 6 | # env: 7 | # CI_JOB_NUMBER: 1 8 | # steps: 9 | # - uses: actions/checkout@v1 10 | # - uses: andresz1/size-limit-action@v1 11 | # with: 12 | # github_token: ${{ secrets.GITHUB_TOKEN }} 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .DS_Store 3 | node_modules 4 | dist 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | # Functional Source License, Version 1.1, MIT Future License 2 | 3 | ## Abbreviation 4 | 5 | FSL-1.1-MIT 6 | 7 | ## Notice 8 | 9 | Copyright (c) 2024 Treadie, Inc 10 | 11 | ## Terms and Conditions 12 | 13 | ### Licensor ("We") 14 | 15 | The party offering the Software under these Terms and Conditions. 16 | 17 | ### The Software 18 | 19 | The "Software" is each version of the software that we make available under 20 | these Terms and Conditions, as indicated by our inclusion of these Terms and 21 | Conditions with the Software. 22 | 23 | ### License Grant 24 | 25 | Subject to your compliance with this License Grant and the Patents, 26 | Redistribution and Trademark clauses below, we hereby grant you the right to 27 | use, copy, modify, create derivative works, publicly perform, publicly display 28 | and redistribute the Software for any Permitted Purpose identified below. 29 | 30 | ### Permitted Purpose 31 | 32 | A Permitted Purpose is any purpose other than a Competing Use. A Competing Use 33 | means making the Software available to others in a commercial product or 34 | service that: 35 | 36 | 1. substitutes for the Software; 37 | 38 | 2. substitutes for any other product or service we offer using the Software 39 | that exists as of the date we make the Software available; or 40 | 41 | 3. offers the same or substantially similar functionality as the Software. 42 | 43 | Permitted Purposes specifically include using the Software: 44 | 45 | 1. for your internal use and access; 46 | 47 | 2. for non-commercial education; 48 | 49 | 3. for non-commercial research; and 50 | 51 | 4. in connection with professional services that you provide to a licensee 52 | using the Software in accordance with these Terms and Conditions. 53 | 54 | ### Patents 55 | 56 | To the extent your use for a Permitted Purpose would necessarily infringe our 57 | patents, the license grant above includes a license under our patents. If you 58 | make a claim against any party that the Software infringes or contributes to 59 | the infringement of any patent, then your patent license to the Software ends 60 | immediately. 61 | 62 | ### Redistribution 63 | 64 | The Terms and Conditions apply to all copies, modifications and derivatives of 65 | the Software. 66 | 67 | If you redistribute any copies, modifications or derivatives of the Software, 68 | you must include a copy of or a link to these Terms and Conditions and not 69 | remove any copyright notices provided in or with the Software. 70 | 71 | ### Disclaimer 72 | 73 | THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR 74 | IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR 75 | PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT. 76 | 77 | IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE 78 | SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, 79 | EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE. 80 | 81 | ### Trademarks 82 | 83 | Except for displaying the License Details and identifying us as the origin of 84 | the Software, you have no right under these Terms and Conditions to use our 85 | trademarks, trade names, service marks or product names. 86 | 87 | ## Grant of Future License 88 | 89 | We hereby irrevocably grant you an additional license to use the Software under 90 | the MIT license that is effective on the second anniversary of the date we make 91 | the Software available. On or after that date, you may use the Software under 92 | the MIT license, in which case the following will apply: 93 | 94 | Permission is hereby granted, free of charge, to any person obtaining a copy of 95 | this software and associated documentation files (the "Software"), to deal in 96 | the Software without restriction, including without limitation the rights to 97 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 98 | of the Software, and to permit persons to whom the Software is furnished to do 99 | so, subject to the following conditions: 100 | 101 | The above copyright notice and this permission notice shall be included in all 102 | copies or substantial portions of the Software. 103 | 104 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 105 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 106 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 107 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 108 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 109 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 110 | SOFTWARE. 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | # Securelog Logs [![Release](https://github.com/onboardbase/secure-log/actions/workflows/main.yml/badge.svg)](https://github.com/onboardbase/secure-log/actions/workflows/main.yml)[![Lint](https://github.com/onboardbase/secure-log/actions/workflows/main.yml/badge.svg)](https://github.com/onboardbase/secure-log/actions/workflows/main.yml) 4 | 5 | A better and more secure console logging experience. Detects and prevents leaking secrets and API tokens into your logs. 6 | 7 | Need Secret scanning in other places? 8 | 9 | - [Securelog for your build and runtime logs](https://github.com/Onboardbase/securelog-scan) 10 | - [Securelog for your react server components](https://github.com/Onboardbase/securelog-rsc) 11 | 12 | 13 | [Powered by Securelog](https://securelog.com) 14 |
15 | 16 | # Contents 17 | 18 | - [Install](#install) 19 | - [Usage](#usage) 20 | - [Supported console methods](#supported-console-methods) 21 | 22 | ## Install 23 | 24 | To use `SecureLog`, 25 | 26 | --- 27 | 28 | ```bash 29 | yarn add securelogs # npm i securelogs 30 | ``` 31 | 32 | --- 33 | 34 | ## Usage 35 | 36 | Import the SecureLog library at the top level of your project. If you use any env/secret library (e.g. dotenv) in your project, you should import those before importing SecureLog. 37 | 38 | --- 39 | 40 | ```js 41 | import SecureLog from 'securelogs'; 42 | new SecureLog(); // For JS projects, use new SecureLog.default() 43 | 44 | console.log('random value'); // Onboardbase Signatures here: random value. 45 | ``` 46 | 47 | --- 48 | 49 | Then you can use your `console.log` as usual. This should include the `SecureLog` prefix and log your value. 50 | 51 | The SecureLog Library also accepts an object. 52 | 53 | --- 54 | 55 | ```js 56 | export default interface IOptions { 57 | disableOn?: 'development' | 'production'; // You can use this to specify if you want the SecureLog library to be disabled in a specific environment 58 | disableConsoleOn?: 'development' | 'production'; // You can use this to disable the console entirely in a specific environment 59 | warnOnly?: boolean; // If this is true, secure log will only print out a warning message rather than exit the program when it detects a secret leak. 60 | forceNewInstance?: boolean; // SecureLog maintains a singleton, use this option to refresh the singleton and updating the config in the process. 61 | maskLeakedSecrets?: boolean; // Hide the value of a leaked secrets from reaching the console 62 | prefix:? string; // customize the prefix for the logs. defaults to "Onboardbase Signatures here:" 63 | globalConsoleObject:? Console // SecureLog advertently uses the standard console.log to output to the console, this option enables configuring the standard console object that is used within the library to output to the console. 64 | } 65 | ``` 66 | 67 | --- 68 | 69 | Example: 70 | 71 | --- 72 | 73 | ```js 74 | new SecureLog({ disableConsoleOn: 'development', warnOnly: true }); // This will disable the SecureLog library on development environment. 75 | console.log('sensitive secret here'); // This won't be executed. 76 | ``` 77 | 78 | --- 79 | 80 | If a secret is detected in a log message, SecureLog can either issue a warning or **exit** the process, depending on the `warnOnly` option. The default value for `warnOnly` is `false`, hence SecureLog will exit the process when it detects a secret leak. 81 | 82 | The `disableConsoleOn` option passed to the `SecureLog` library will ensure that the `console.log` statement is not executed. 83 | 84 | The `disableOn` && `disableConsoleOn` depend on your `process.env.NODE_ENV` to work perfectly. That is, it compares the environment passed from the `disableOn` || `disableConsoleOn` option with the environment in your `process.env.NODE_ENV` to know when to disable the SecureLog library or the `console` statements itself. 85 | 86 | The SecureLog library scans the `arguments` passed to the `console.log` function to check if any of the `...args` inside your `console.log` function is a potential secret. It does this by comparing the `arguments` passed to `console.log` with the values of your current environment: `process.env`. It throws an error if any potential secret is found. 87 | 88 | Example: 89 | 90 | --- 91 | 92 | ```js 93 | console.log('secret', process.env.AWS_ACCESS_KEY_ID); // Onboardbase Signatures here: ************ is a valid secret for the key: AWS_ACCESS_KEY_ID 94 | ``` 95 | 96 | --- 97 | 98 | This will throw a warning if an actual `AWS_ACCESS_KEY_ID` is found in the `process.env` to notify the user that they are logging a potential secret. 99 | 100 | Example: `React App` 101 | 102 | --- 103 | 104 | ```html 105 | 106 | 109 | 110 | ``` 111 | 112 | --- 113 | 114 | Example: `NodeJs` 115 | 116 | --- 117 | 118 | ```js 119 | const express = require('express'); 120 | const app = express(); 121 | const SecureLog = require('securelogs'); 122 | 123 | const port = 3000; 124 | new SecureLog(); 125 | 126 | app.get('/', (req, res) => { 127 | res.send('Hello World!'); 128 | }); 129 | 130 | app.listen(port, () => { 131 | console.log(`Example app listening on port ${port}`); 132 | }); 133 | ``` 134 | 135 | --- 136 | 137 | ### Supported console methods 138 | 139 | The SecureLog library currently only supports these console methods: 140 | 141 | - `console.log`, `console.clear`, `console.warn`, `console.profileEnd`, `console.debug`, `console.info`, `console.error`, `console.table` 142 | 143 | ### API 144 | 145 | #### createSecureConsolaReporter 146 | 147 | To securely log with [consola](https://github.com/unjs/consola), use the `createSecureConsolaReporter` method to create a reporter. 148 | 149 | It exposes a secure log instance with the following config: `{ warnOnly: true, forceNewInstance: true, maskLeakedSecrets: true, }` 150 | 151 | ```ts 152 | import { createSecureConsolaReporter } from 'securelogs'; 153 | const options: IOptions = {}; // override the default config used to initialize secure log instance 154 | const consola = createSecureConsolaReporter(options); 155 | process.env.NODE_ENV = 'development'; 156 | consola.log('hello there from development'); // {"date":"2024-04-12T17:46:07.099Z","args":["hello there from ***********"],"type":"log","level":2,"tag":""} 157 | ``` 158 | 159 | ### maskLeakedSecrets(data: any) : any 160 | 161 | Mask leaked secrets in a string|array|object. 162 | 163 | ```ts 164 | import { maskSecretLeaks } from 'securelogs'; 165 | 166 | // mask secrets existing in a predefined array of values 167 | const valuesIn = ['asd']; 168 | // *** 9200 *** development 169 | console.log(maskSecretLeaks('asd 9200 asd development', valuesIn)); 170 | 171 | const secrets = { PORT: '9200', NODE_ENV: 'development' }; 172 | 173 | process.env = secrets; 174 | // mask secrets in process.env 175 | // asd 9200 asd *********** 176 | console.log(maskSecretLeaks('asd 9200 asd development')); 177 | // { key: [ 'asd 9200 asd ***********' ] } 178 | console.log(maskSecretLeaks({ key: ['asd 9200 asd development'] })); 179 | // [ 'asd 9200 asd ***********' ] 180 | console.log(maskSecretLeaks(['asd 9200 asd development'])); 181 | // { nested: { env: '***********' } } 182 | console.log(maskSecretLeaks({ nested: { env: 'development' } })); 183 | ``` 184 | 185 | ### validateSecretLeak(data: any): boolean 186 | 187 | Validate if a string|object|array contains secrets 188 | 189 | ```ts 190 | import { validateSecretLeak } from 'securelogs'; 191 | 192 | const secrets = { PORT: '9200', NODE_ENV: 'development' }; 193 | 194 | process.env = secrets; 195 | 196 | console.log(validateSecretLeak('development')); // true 197 | ``` 198 | 199 | ### scanSecretsInString(rawValue: string) : string 200 | 201 | This takes in a string and checks if the strings contains a secret, if it does, it automatically masks all the secrets in the data provided and returns the data back with secrets masked 202 | 203 | ```ts 204 | import { scanSecretsInString } from 'securelogs'; 205 | 206 | const safeString = await scanSecretsInString( 207 | 'This is a very long string with AKIAKSDKDBDSDSDBD AWS secrets attached', 208 | options: { 209 | maskedValue: "*"; // that is the masked value should be represented by "*", if masked value is an empty string, all found secrets wont have a value 210 | visibleChars: 0; // that is no detected secrets should be returned 211 | } 212 | ); // This is a very long string with AWS secrets attached 213 | ``` 214 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = {}; 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "3.1.3", 3 | "license": "MIT", 4 | "main": "dist/index.js", 5 | "typings": "dist/index.d.ts", 6 | "files": [ 7 | "dist" 8 | ], 9 | "type": "commonjs", 10 | "engines": { 11 | "node": ">=10" 12 | }, 13 | "scripts": { 14 | "start": "tsdx watch", 15 | "build": "tsdx build", 16 | "test": "tsdx test", 17 | "lint": "tsdx lint", 18 | "prepare": "tsdx build", 19 | "size": "size-limit", 20 | "analyze": "size-limit --why" 21 | }, 22 | "peerDependencies": {}, 23 | "husky": { 24 | "hooks": { 25 | "pre-commit": "tsdx lint" 26 | } 27 | }, 28 | "prettier": { 29 | "printWidth": 80, 30 | "semi": true, 31 | "singleQuote": true, 32 | "trailingComma": "es5" 33 | }, 34 | "name": "securelogs", 35 | "author": "Onboardbase", 36 | "publishConfig": { 37 | "access": "public" 38 | }, 39 | "module": "dist/securelogs.esm.js", 40 | "size-limit": [ 41 | { 42 | "path": "dist/securelogs.cjs.production.min.js", 43 | "limit": "10 KB", 44 | "ignore": [ 45 | "consola" 46 | ] 47 | }, 48 | { 49 | "path": "dist/securelogs.esm.js", 50 | "limit": "10 KB", 51 | "ignore": [ 52 | "consola" 53 | ] 54 | } 55 | ], 56 | "devDependencies": { 57 | "@size-limit/esbuild": "^8.2.6", 58 | "@size-limit/esbuild-why": "^8.2.6", 59 | "@size-limit/preset-small-lib": "^8.2.6", 60 | "@types/node": "^20.12.7", 61 | "husky": "^8.0.3", 62 | "size-limit": "^8.2.6", 63 | "tsdx": "^0.14.1", 64 | "tslib": "^2.6.0", 65 | "typescript": "^5.1.6" 66 | }, 67 | "description": "A better and secure console logging experience.", 68 | "repository": { 69 | "type": "git", 70 | "url": "git+https://github.com/onboardbase/secure-log.git" 71 | }, 72 | "private": false, 73 | "bugs": { 74 | "url": "https://github.com/onboardbase/secure-log/issues" 75 | }, 76 | "licenses": [ 77 | { 78 | "url": "https://github.com/Onboardbase/secure-log/blob/main/LICENSE" 79 | } 80 | ], 81 | "homepage": "https://github.com/onboardbase/secure-log#readme", 82 | "dependencies": { 83 | "consola": "^3.2.3", 84 | "mask-sensitive-data": "^0.11.5", 85 | "node": "^18.20.2", 86 | "securelog-scan": "^3.0.13" 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/createConsolaExporter.ts: -------------------------------------------------------------------------------- 1 | import { createConsola } from 'consola'; 2 | import IOptions from './interfaces/options.interface'; 3 | import SecureLog from './secureLog'; 4 | import { maskLeakedSecrets } from './utils/maskLeakedSecrets'; 5 | 6 | export const createSecureConsolaReporter = (options?: IOptions) => { 7 | const secureLog = new SecureLog({ 8 | warnOnly: true, 9 | forceNewInstance: true, 10 | maskLeakedSecrets: true, 11 | prefix: '', 12 | ...options, 13 | }); 14 | return createConsola({ 15 | reporters: [ 16 | { 17 | log: (data: any) => { 18 | secureLog.log(JSON.stringify(data)); 19 | }, 20 | }, 21 | ], 22 | }); 23 | }; 24 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import SecureLog from './secureLog'; 2 | 3 | export default SecureLog; 4 | export * from './createConsolaExporter'; 5 | export * from './validateSecretLeak'; 6 | export * from './maskLeakedSecret'; 7 | export * from './scanString'; 8 | -------------------------------------------------------------------------------- /src/interfaces/options.interface.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Represents the options for the secure-log library. 3 | */ 4 | export default interface IOptions { 5 | /** 6 | * Specifies when to disable the secure-log functionality. 7 | * It can be set to 'development' or 'production'. 8 | */ 9 | disableOn?: 'development' | 'production'; 10 | 11 | /** 12 | * Specifies when to disable logging to the console. 13 | * It can be set to 'development' or 'production'. 14 | */ 15 | disableConsoleOn?: 'development' | 'production'; 16 | 17 | /** 18 | * Specifies whether to only log warnings instead of throwing errors. 19 | */ 20 | warnOnly?: boolean; 21 | 22 | forceNewInstance?: boolean; 23 | 24 | maskLeakedSecrets?: boolean; 25 | 26 | prefix?: string; 27 | 28 | globalConsoleObject?: Console; 29 | } 30 | -------------------------------------------------------------------------------- /src/maskLeakedSecret.ts: -------------------------------------------------------------------------------- 1 | import { maskLeakedSecrets } from './utils/maskLeakedSecrets'; 2 | 3 | export const maskSecretLeaks = (arg: any, valuesIn?: string[]) => { 4 | return maskLeakedSecrets(arg, valuesIn); 5 | }; 6 | -------------------------------------------------------------------------------- /src/scanString.ts: -------------------------------------------------------------------------------- 1 | import { processPossibleSecretsInString } from 'securelog-scan/dist/fileScanner'; 2 | 3 | export const scanSecretsInString = async ( 4 | rawValue: string, 5 | options?: { maskedValue?: string; visibleChars?: number } 6 | ) => { 7 | return await processPossibleSecretsInString({ 8 | rawValue, 9 | maskedValue: options.maskedValue, 10 | visibleChars: options.visibleChars, 11 | }); 12 | }; 13 | -------------------------------------------------------------------------------- /src/secureLog.ts: -------------------------------------------------------------------------------- 1 | import IOptions from './interfaces/options.interface'; 2 | import { maskSecretLeaks } from './maskLeakedSecret'; 3 | import { 4 | getGlobalConsoleObject, 5 | getGlobalObject, 6 | setGlobalConsoleObject, 7 | } from './utils'; 8 | import { checkForPotentialSecrets } from './utils/checkForPotentialSecrets'; 9 | import { handleSecretLeakResult } from './utils/handleSecretLeakResult'; 10 | 11 | /** 12 | * Represents a secure logging utility that wraps the console object. 13 | * It provides additional functionality for logging and ensures that sensitive information is not accidentally logged. 14 | */ 15 | class SecureLog { 16 | cachedLog: Console; 17 | disabled: boolean; 18 | Console: console.ConsoleConstructor; 19 | 20 | PREFIX = 'Onboardbase Signatures here:'; 21 | 22 | constructor(private options: IOptions = {}) { 23 | this.disabled = 24 | options?.disableOn && process.env.NODE_ENV === options?.disableOn; 25 | if (this.disabled) return; 26 | 27 | const globalObject: any = getGlobalObject(); 28 | if (options?.forceNewInstance) { 29 | // reset the global console to standard console object 30 | globalObject.console = globalObject.obbinitialized 31 | ? globalObject.console.cachedLog 32 | : console; 33 | } else if (globalObject.obbinitialized) { 34 | return globalObject.console as SecureLog; 35 | } 36 | this.cachedLog = getGlobalConsoleObject(); 37 | this.PREFIX = this.options.prefix ?? this.PREFIX; 38 | globalObject.console = this; 39 | globalObject.obbinitialized = false; 40 | } 41 | 42 | useActualConsole() { 43 | // setGlobalConsoleObject(this.cachedLog); 44 | } 45 | 46 | hasSecretLeak(...args: any) { 47 | const checkResult = checkForPotentialSecrets(args); 48 | return !!checkResult?.length; 49 | } 50 | 51 | /** 52 | * Logs the provided arguments to the console, while checking for potential secrets. 53 | * If the `disableConsoleOn` option is set and the current environment matches the value, 54 | * the console logging will be disabled. 55 | * 56 | * @param args - The arguments to be logged. 57 | */ 58 | log(...args: any) { 59 | if (this.disabled) return; 60 | 61 | const checkResult = checkForPotentialSecrets(args); 62 | handleSecretLeakResult(checkResult, this.cachedLog, this.options); 63 | const valuesIn = checkResult.map((key: string) => process.env[key]); 64 | const data = this.options.maskLeakedSecrets 65 | ? maskSecretLeaks(args, valuesIn) 66 | : args; 67 | this.cachedLog.log.apply(console, [this.PREFIX, ...data]); 68 | } 69 | 70 | clear() { 71 | // do whatever here with the passed parameters 72 | this.cachedLog.clear.apply(null); 73 | } 74 | 75 | assert(...args: any) { 76 | // do whatever here with the passed parameters 77 | this.cachedLog.assert.apply(null, args); 78 | } 79 | 80 | debug(...data: any[]): void; 81 | debug(message?: any, ...optionalParams: any[]): void; 82 | debug(...args: any): void { 83 | if (this.disabled) return; 84 | 85 | const checkResult = checkForPotentialSecrets(args); 86 | handleSecretLeakResult(checkResult, this.cachedLog); 87 | const valuesIn = checkResult.map((key: string) => process.env[key]); 88 | const data = this.options.maskLeakedSecrets 89 | ? maskSecretLeaks(args, valuesIn) 90 | : args; 91 | this.cachedLog.debug.apply(console, [this.PREFIX, ...data]); 92 | } 93 | error(...data: any[]): void; 94 | error(message?: any, ...optionalParams: any[]): void; 95 | error(...args: any): void { 96 | const modArgs = args || []; 97 | 98 | if (this.disabled) return; 99 | 100 | if (!modArgs[1]?.skipValidationCheck) { 101 | const checkResult = checkForPotentialSecrets(args); 102 | handleSecretLeakResult(checkResult, this.cachedLog, this.options); 103 | } 104 | 105 | const logValue = modArgs?.[1]?.skipValidationCheck 106 | ? [this.PREFIX, modArgs?.[0]] 107 | : [this.PREFIX, ...modArgs]; 108 | 109 | this.cachedLog.error.apply(console, logValue); 110 | } 111 | profile(label?: string): void { 112 | return this.cachedLog.profile(label); 113 | } 114 | profileEnd(label?: string): void { 115 | return this.cachedLog.profileEnd.bind(null, label); 116 | } 117 | info(...data: any[]): void; 118 | info(message?: any, ...optionalParams: any[]): void; 119 | info(...args: any): void { 120 | if (this.disabled) return; 121 | 122 | const checkResult = checkForPotentialSecrets(args); 123 | handleSecretLeakResult(checkResult, this.cachedLog, this.options); 124 | this.cachedLog.info.apply(console, [this.PREFIX, ...args]); 125 | } 126 | warn(...data: any[]): void; 127 | warn(message?: any, ...optionalParams: any[]): void; 128 | warn(...args: any): void { 129 | if (this.disabled) return; 130 | 131 | const checkResult = checkForPotentialSecrets(args); 132 | handleSecretLeakResult(checkResult, this.cachedLog, this.options); 133 | const valuesIn = checkResult.map((key: string) => process.env[key]); 134 | const data = this.options.maskLeakedSecrets 135 | ? maskSecretLeaks(args, valuesIn) 136 | : args; 137 | this.cachedLog.warn.apply(console, [this.PREFIX, ...data]); 138 | } 139 | dir(item?: any, options?: any): void; 140 | dir(obj: any): void; 141 | dir(obj?: unknown, options?: unknown): void { 142 | throw new Error('Method not implemented.'); 143 | } 144 | dirxml(...data: any[]): void; 145 | dirxml(...data: any[]): void; 146 | dirxml(...data: unknown[]): void { 147 | throw new Error('Method not implemented.'); 148 | } 149 | count(label?: string): void; 150 | count(label?: string): void; 151 | count(label?: unknown): void { 152 | throw new Error('Method not implemented.'); 153 | } 154 | countReset(label?: string): void; 155 | countReset(label?: string): void; 156 | countReset(label?: unknown): void { 157 | throw new Error('Method not implemented.'); 158 | } 159 | group(...data: any[]): void; 160 | group(...label: any[]): void; 161 | group(...label: unknown[]): void { 162 | throw new Error('Method not implemented.'); 163 | } 164 | groupCollapsed(...data: any[]): void; 165 | groupCollapsed(...label: any[]): void; 166 | groupCollapsed(...label: unknown[]): void { 167 | throw new Error('Method not implemented.'); 168 | } 169 | groupEnd(): void; 170 | groupEnd(): void; 171 | groupEnd(): void { 172 | throw new Error('Method not implemented.'); 173 | } 174 | 175 | table(tabularData?: any, properties?: string[]): void; 176 | table(tabularData: any, properties?: readonly string[]): void; 177 | table(...args: any): void { 178 | throw new Error('Method not implemented.'); 179 | } 180 | time(label?: string): void; 181 | time(label?: string): void; 182 | time(label?: unknown): void { 183 | throw new Error('Method not implemented.'); 184 | } 185 | timeEnd(label?: string): void; 186 | timeEnd(label?: string): void; 187 | timeEnd(label?: unknown): void { 188 | throw new Error('Method not implemented.'); 189 | } 190 | timeLog(label?: string, ...data: any[]): void; 191 | timeLog(label?: string, ...data: any[]): void; 192 | timeLog(label?: unknown, ...data: unknown[]): void { 193 | throw new Error('Method not implemented.'); 194 | } 195 | timeStamp(label?: string): void; 196 | timeStamp(label?: string): void; 197 | timeStamp(label?: unknown): void { 198 | throw new Error('Method not implemented.'); 199 | } 200 | trace(...data: any[]): void; 201 | trace(message?: any, ...optionalParams: any[]): void; 202 | trace(message?: unknown, ...optionalParams: unknown[]): void { 203 | throw new Error('Method not implemented.'); 204 | } 205 | } 206 | 207 | export default SecureLog; 208 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | import SecureLog, { createSecureConsolaReporter } from './index'; 2 | 3 | const secrets = { PORT: '9200', NODE_ENV: 'development' }; 4 | 5 | process.env = secrets; 6 | 7 | const secureLog = new SecureLog(); 8 | 9 | secureLog.log('hello 9200'); 10 | 11 | console.log('error development'); 12 | 13 | const consola = createSecureConsolaReporter(); 14 | consola.log('Hello'); 15 | -------------------------------------------------------------------------------- /src/utils/checkForPotentialSecrets.ts: -------------------------------------------------------------------------------- 1 | import { isArray, isObject, isString } from './utils'; 2 | import { stringOccurInObjectValues } from './stringOccurInObjectValue'; 3 | 4 | export const checkForPotentialSecrets = (data: any[]): string[] => { 5 | return data.reduce((acc: string[], argument: any) => { 6 | let result: string | string[] | null = []; 7 | 8 | if (isString(argument)) { 9 | result = stringOccurInObjectValues({ needle: argument, obj: process.env }); 10 | } else if (isObject(argument)) { 11 | result = checkForPotentialSecrets(Object.values(argument)); 12 | } else if (isArray(argument)) { 13 | result = checkForPotentialSecrets(argument); 14 | } 15 | 16 | return result ? acc.concat(result) : acc; 17 | }, []); 18 | }; 19 | -------------------------------------------------------------------------------- /src/utils/handleSecretLeakResult.ts: -------------------------------------------------------------------------------- 1 | import IOptions from '../interfaces/options.interface'; 2 | 3 | export const handleSecretLeakResult = ( 4 | leakedKeys: string[], 5 | cachedConsole: Console, 6 | secureLogOptions: IOptions = {} 7 | ) => { 8 | try { 9 | leakedKeys.map(key => { 10 | cachedConsole.warn( 11 | 'the value of the secret: "'.concat(key, '", is being leaked!') 12 | ); 13 | if (!secureLogOptions.warnOnly) { 14 | throw new Error('potential secret leak'); 15 | } 16 | }); 17 | } catch (error) { 18 | cachedConsole.error(error); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from './utils'; 2 | export * from './checkForPotentialSecrets'; 3 | export * from './handleSecretLeakResult'; 4 | export * from './maskLeakedSecrets'; 5 | export * from './stringOccurInObjectValue'; 6 | -------------------------------------------------------------------------------- /src/utils/maskLeakedSecrets.ts: -------------------------------------------------------------------------------- 1 | import { maskString } from 'mask-sensitive-data'; 2 | import { isArray, isObject, isString } from './utils'; 3 | 4 | export const maskObjectValuesInString = (data: { 5 | str: string; 6 | valuesIn: string[]; 7 | }) => { 8 | const { str, valuesIn } = data; 9 | let maskedStr = str; 10 | if (str) { 11 | valuesIn.forEach(value => { 12 | maskedStr = str.replaceAll( 13 | new RegExp(value, 'g'), 14 | `*`.repeat(value.length) 15 | ); 16 | }); 17 | } 18 | return maskedStr; 19 | }; 20 | 21 | function checkForPotentialSecretInArrayItem( 22 | argumentItem: any[], 23 | valuesIn?: string[] 24 | ) { 25 | return argumentItem.map((arrayValue: any) => { 26 | if (isObject(arrayValue)) { 27 | return maskLeakedSecrets(arrayValue, valuesIn); 28 | } 29 | 30 | if (isArray(arrayValue) || isString(arrayValue)) { 31 | return maskLeakedSecrets(arrayValue, valuesIn); 32 | } 33 | return arrayValue; 34 | }); 35 | } 36 | 37 | export const maskLeakedSecrets = (data: any, valuesIn?: string[]) => { 38 | if (!data) return null; 39 | const values = valuesIn?.length ? valuesIn : Object.values(process.env); 40 | if (isString(data)) { 41 | return maskObjectValuesInString({ 42 | str: data, 43 | valuesIn: values, 44 | }); 45 | } 46 | 47 | if (isObject(data)) { 48 | // mask and replace the values of the object keys 49 | Object.keys(data).map(key => { 50 | data[key] = maskLeakedSecrets(data[key], values); 51 | }); 52 | } 53 | if (isArray(data)) { 54 | data = checkForPotentialSecretInArrayItem(data, values); 55 | } 56 | return data; 57 | }; 58 | -------------------------------------------------------------------------------- /src/utils/stringOccurInObjectValue.ts: -------------------------------------------------------------------------------- 1 | import IOptions from '../interfaces/options.interface'; 2 | 3 | export const stringOccurInObjectValues = (data: { 4 | needle: string; 5 | obj: Record; 6 | }): string | null => { 7 | const { needle, obj } = data; 8 | if (needle) { 9 | return Object.keys(obj).find(secretKey => { 10 | const secretValue = (obj || {})[secretKey]; 11 | return secretValue.length > 1 && needle.includes(secretValue); 12 | }) ?? null; 13 | } 14 | return null; 15 | }; 16 | -------------------------------------------------------------------------------- /src/utils/utils.ts: -------------------------------------------------------------------------------- 1 | export const isString = (value: any) => typeof value === 'string'; 2 | export const isObject = (value: any) => 3 | !!value && Object.prototype.toString.call(value) === '[object Object]'; 4 | export const isArray = (value: any) => !!value && Array.isArray(value); 5 | 6 | const isBrowser = () => { 7 | try { 8 | return window && window?.navigator && !global.process; 9 | } catch (error) { 10 | return false; 11 | } 12 | }; 13 | 14 | export const getGlobalConsoleObject = () => { 15 | return isBrowser() ? window.console : global.console; 16 | }; 17 | 18 | export const setGlobalConsoleObject = (obj: Console) => { 19 | return isBrowser() ? (window.console = obj) : (global.console = obj); 20 | }; 21 | 22 | export const getGlobalObject = () => { 23 | return isBrowser() ? window : global; 24 | }; 25 | -------------------------------------------------------------------------------- /src/validateSecretLeak.ts: -------------------------------------------------------------------------------- 1 | import { checkForPotentialSecrets } from './utils'; 2 | 3 | export const validateSecretLeak = (...args: []) => { 4 | const checkResult = checkForPotentialSecrets(args); 5 | return !!checkResult?.length; 6 | }; 7 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | const SecureLog = require('./dist'); 2 | 3 | // mask secrets existing in a predefined value 4 | // console.log(SecureLog.maskSecretLeaks('asd 9200 asd development', ['asd'])); 5 | 6 | const secrets = { PORT: '9200', NODE_ENV: 'development' }; 7 | 8 | process.env = secrets; 9 | // mask secrets in process.env 10 | // console.log(SecureLog.maskSecretLeaks('asd 9200 asd development')); 11 | // console.log( 12 | // SecureLog.maskSecretLeaks({ 13 | // key: ['asd 9200 asd development'], 14 | // }) 15 | // ); 16 | 17 | // console.log(SecureLog.maskSecretLeaks(['asd 9200 asd development'])); 18 | 19 | // console.log( 20 | // SecureLog.maskSecretLeaks({ 21 | // nested: { env: 'development' }, 22 | // }) 23 | // ); 24 | 25 | const secureLog = new SecureLog.default(); 26 | 27 | secureLog.log('hello 9200'); 28 | 29 | console.log({ v: 'k', test: { null: null } }); 30 | 31 | // const consola = SecureLog.createSecureConsolaReporter({}); 32 | // consola.log('hello there development'); 33 | 34 | // console.log(secureLog.hasSecretLeak('Hey')); 35 | -------------------------------------------------------------------------------- /test/consola.test.ts: -------------------------------------------------------------------------------- 1 | import { createSecureConsolaReporter } from '../src/createConsolaExporter'; 2 | 3 | describe('Test console.log', () => { 4 | it('should create a consola reporter', () => { 5 | // TODO: this is buggy: throws a package not found error 6 | // const consola = createSecureConsolaReporter(); 7 | // const mockedLog = jest.fn(); 8 | // console.log = mockedLog; 9 | // consola.log('check log'); 10 | // expect(mockedLog).toBeCalledTimes(1); 11 | // expect(mockedLog).toBeCalledWith(''); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /test/log.test.ts: -------------------------------------------------------------------------------- 1 | import IOptions from '../src/interfaces/options.interface'; 2 | import SecureLog from '../src/secureLog'; 3 | 4 | const actualProcessEnv = Object.assign({}, process.env); 5 | 6 | const mockMethodNames = ['log', 'warn', 'error'] as const; 7 | 8 | const mockObj: { 9 | [K in typeof mockMethodNames[number]]?: jest.Mock | any; 10 | } = mockMethodNames.reduce( 11 | (accObj, key) => ({ ...accObj, [key]: jest.fn() }), 12 | {} 13 | ); 14 | 15 | const resetMocks = () => { 16 | mockMethodNames.forEach(methodName => mockObj[methodName]?.mockReset()); 17 | }; 18 | 19 | const mockConsoleMethods = () => { 20 | mockMethodNames.forEach(methodName => { 21 | const mockedMethod = mockObj[methodName]; 22 | console[methodName] = mockedMethod ?? console[methodName]; 23 | }); 24 | }; 25 | 26 | const secrets = { PORT: '9200' }; 27 | 28 | const setupConsoleMocks = () => { 29 | resetMocks(); 30 | mockConsoleMethods(); 31 | }; 32 | 33 | let secureLog: SecureLog; 34 | const setup = (options: IOptions = {}) => { 35 | setupConsoleMocks(); 36 | process.env = secrets; 37 | secureLog = new SecureLog(options); 38 | }; 39 | 40 | const cleanup = () => { 41 | secureLog.useActualConsole(); 42 | Object.assign(process.env, actualProcessEnv); 43 | }; 44 | 45 | describe('Test console.log', () => { 46 | beforeEach(() => 47 | setup({ 48 | forceNewInstance: true, 49 | globalConsoleObject: console, 50 | }) 51 | ); 52 | afterEach(() => cleanup()); 53 | 54 | it('should have called standard console.log with hello', () => { 55 | secureLog.log('hello'); 56 | expect(mockObj.log).toHaveBeenCalledWith( 57 | 'Onboardbase Signatures here:', 58 | 'hello' 59 | ); 60 | }); 61 | 62 | it('should have called console.warn with hello warn', () => { 63 | secureLog.warn('hello warn'); 64 | expect(mockObj.warn).toHaveBeenCalledWith( 65 | 'Onboardbase Signatures here:', 66 | 'hello warn' 67 | ); 68 | }); 69 | 70 | it('should have called console.error with hello error', () => { 71 | secureLog.error('hello error'); 72 | expect(mockObj.error).toHaveBeenCalledWith( 73 | 'Onboardbase Signatures here:', 74 | 'hello error' 75 | ); 76 | }); 77 | 78 | it('should mask secrets when they are part of log', () => { 79 | secureLog.log(`running on port ${secrets.PORT}`); 80 | expect(mockObj.warn).toHaveBeenCalledWith( 81 | 'the value of the secret: "PORT", is being leaked!' 82 | ); 83 | }); 84 | 85 | it('should mask secrets when they are part of an object', () => { 86 | secureLog.log('running on port', {secretPort: secrets.PORT}); 87 | expect(mockObj.warn).toHaveBeenCalledWith( 88 | 'the value of the secret: "PORT", is being leaked!' 89 | ); 90 | }); 91 | 92 | it('should mask secrets when they are part of an array', () => { 93 | secureLog.log('running on port', [secrets.PORT]); 94 | expect(mockObj.warn).toHaveBeenCalledWith( 95 | 'the value of the secret: "PORT", is being leaked!' 96 | ); 97 | }); 98 | 99 | it('should mask secrets when they are part of a nested object', () => { 100 | secureLog.log('running on port', {innerValue: {secretPort: secrets.PORT}}); 101 | expect(mockObj.warn).toHaveBeenCalledWith( 102 | 'the value of the secret: "PORT", is being leaked!' 103 | ); 104 | }); 105 | 106 | it('should mask secrets when they are part of a nested array', () => { 107 | secureLog.log('running on port', {innerValue: [secrets.PORT]}); 108 | expect(mockObj.warn).toHaveBeenCalledWith( 109 | 'the value of the secret: "PORT", is being leaked!' 110 | ); 111 | }); 112 | }); 113 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // see https://www.typescriptlang.org/tsconfig to better understand tsconfigs 3 | "include": ["src", "types"], 4 | "compilerOptions": { 5 | "module": "esnext", 6 | "lib": ["dom", "esnext"], 7 | "importHelpers": true, 8 | // output .d.ts declaration files for consumers 9 | "declaration": true, 10 | // output .js.map sourcemap files for consumers 11 | "sourceMap": true, 12 | // match output dir to input dir. e.g. dist/index instead of dist/src/index 13 | "rootDir": "./src", 14 | // stricter type-checking for stronger correctness. Recommended by TS 15 | "strict": false, 16 | // linter checks for common issues 17 | "noImplicitReturns": true, 18 | "noFallthroughCasesInSwitch": true, 19 | // noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative 20 | "noUnusedLocals": false, 21 | "noUnusedParameters": false, 22 | // use Node's module resolution algorithm, instead of the legacy TS one 23 | "moduleResolution": "node", 24 | // transpile JSX to React.createElement 25 | "jsx": "react", 26 | // interop between ESM and CJS modules. Recommended by TS 27 | "esModuleInterop": true, 28 | // significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS 29 | "skipLibCheck": true, 30 | // error out if import and file system have a casing mismatch. Recommended by TS 31 | "forceConsistentCasingInFileNames": true, 32 | // `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc` 33 | "noEmit": true 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /tsdx.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | rollup(config, options) { 3 | return config; 4 | }, 5 | }; 6 | --------------------------------------------------------------------------------