├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── __tests__ └── logrocket-fuzzy-search.test.ts ├── jest.config.js ├── package-lock.json ├── package.json ├── rollup.config.js ├── src └── index.ts ├── tsconfig.json └── tslint.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .rpt2_cache -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "node" 4 | 5 | cache: npm 6 | 7 | script: 8 | - npm run lint 9 | - npm test 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Joshua Bailey 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🚀 LogRocket Fuzzy Search Sanitizer 2 | 3 | [![Build Status](https://travis-ci.com/jbailey4/logrocket-fuzzy-search-sanitizer.svg?branch=master)](https://travis-ci.com/jbailey4/logrocket-fuzzy-search-sanitizer) 4 | 5 | Optional LogRocket plugin to help sanitize data from network requests and responses. 6 | 7 | [Blog post](https://medium.com/@josh_bailey4/sanitizing-data-with-logrocket-2af1bbbe46a1) 8 | 9 | --- 10 | 11 | When initializing LogRocket's SDK you can optionally provide a `requestSanitizer` and `responseSanitizer` method within the [network option](https://docs.logrocket.com/reference#network), which are called on each network request within your app. This is useful when you need to prevent some requests/responses or sensitive data within headers, payloads, etc. being sent to LogRocket's servers and replays. 12 | 13 | This plugin provides pre-configured `requestSanitizer`/`responseSanitizer` methods which sanitize network payloads by the field names within each payload. This allows you to still capture every network request within in your app, getting the monitoring benefits provided by LogRocket, while allowing an easy way to mask the sensitive data in your app. 14 | 15 | ## Usage 16 | 17 | Note: You must have LogRocket installed and an app ID ready to use. See the [quickstart](https://docs.logrocket.com/docs/quickstart) docs. 18 | 19 | ### Steps 20 | 21 | 1. Import this plugin along with LogRocket 22 | 2. Call the setup method on this plugin, passing an array of the private field names 23 | - the setup method returns a hash with the 2 sanitizer methods 24 | 3. Init LogRocket 25 | 4. Specify a configuration with the `network` option and pass in the sanitizer methods 26 | 27 | #### Example 28 | 29 | ```es6 30 | import LogRocket from 'logrocket'; 31 | import LogrocketFuzzySanitizer from 'logrocket-fuzzy-search-sanitizer'; 32 | 33 | const { requestSanitizer, responseSanitizer } = LogrocketFuzzySanitizer.setup([...privateFieldNames]); 34 | 35 | LogRocket.init('app/id', { 36 | network: { 37 | requestSanitizer, 38 | responseSanitizer 39 | } 40 | }); 41 | ``` 42 | 43 | #### Private Field Names 44 | 45 | This is the first argument passed to the `setup` method, and should be an array of strings that represent the private field names that could potentially be found in any request/response within your app. 46 | 47 | For example, if your app obtains user sensitive data such as social security numbers, first name, date of birth, etc.: 48 | 49 | ```es6 50 | import LogRocket from 'logrocket'; 51 | import LogrocketFuzzySanitizer from 'logrocket-fuzzy-search-sanitizer'; 52 | 53 | const privateFieldNames = [ 54 | 'ssn', 55 | 'firstName', 56 | 'birthDate' 57 | ]; 58 | 59 | const { requestSanitizer, responseSanitizer } = LogrocketFuzzySanitizer.setup(privateFieldNames); 60 | LogRocket.init('app/id', { 61 | network: { 62 | requestSanitizer, 63 | responseSanitizer 64 | } 65 | }); 66 | ``` 67 | 68 | Now when requests and responses get passed through the sanitizer methods, any field name containing "ssn", "firstName", or "birthDate" will be masked and hidden from LogRocket. 69 | 70 | ## Running / Development 71 | 72 | - `npm install` 73 | - Make any changes, bug fixes, etc. 74 | - Run tests: `npm run test && npm run lint` 75 | -------------------------------------------------------------------------------- /__tests__/logrocket-fuzzy-search.test.ts: -------------------------------------------------------------------------------- 1 | import LogrocketFuzzySearch from '../src'; 2 | 3 | const networkReqRes = { 4 | body: '{}', 5 | headers: {}, 6 | method: 'POST', 7 | }; 8 | 9 | test('setup method returns request/response logrocket sanitizers', () => { 10 | const lrfs = LogrocketFuzzySearch.setup([]); 11 | 12 | expect(lrfs.requestSanitizer); 13 | expect(lrfs.responseSanitizer); 14 | }); 15 | 16 | test('passed in keynames are masked', () => { 17 | const lrfs = new LogrocketFuzzySearch(['privateKeyName']); 18 | 19 | networkReqRes.body = JSON.stringify({resource: {privateKeyName: 42, publicKeyName: 0}}); 20 | 21 | const result = lrfs.requestSanitizer(networkReqRes); 22 | 23 | expect(result.body.resource.privateKeyName).toMatch('*'); 24 | expect(result.body.resource.publicKeyName).toBe(0); 25 | }); 26 | 27 | test('GET requests are ignored', () => { 28 | const lrfs = new LogrocketFuzzySearch(['privateKeyName']); 29 | 30 | networkReqRes.method = 'GET'; 31 | 32 | const result = lrfs.requestSanitizer(networkReqRes); 33 | 34 | expect(result).toEqual(networkReqRes); 35 | }); 36 | 37 | test('type value pairs in request/request body are masked', () => { 38 | const lrfs = new LogrocketFuzzySearch(['email']); 39 | 40 | networkReqRes.body = JSON.stringify({ contact: { type: 'email', value: 'secret@ex.com'}}); 41 | 42 | const result = lrfs.responseSanitizer(networkReqRes); 43 | 44 | expect(result.body.contact.value).toMatch('*'); 45 | }); 46 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // For a detailed explanation regarding each configuration property, visit: 2 | // https://jestjs.io/docs/en/configuration.html 3 | 4 | module.exports = { 5 | // The directory where Jest should output its coverage files 6 | coverageDirectory: "coverage", 7 | 8 | // A set of global variables that need to be available in all test environments 9 | globals: { 10 | "ts-jest": { 11 | "tsConfig": "tsconfig.json" 12 | } 13 | }, 14 | 15 | // An array of file extensions your modules use 16 | moduleFileExtensions: [ 17 | "ts", 18 | "js" 19 | ], 20 | 21 | // The glob patterns Jest uses to detect test files 22 | testMatch: [ 23 | "**/__tests__/*.+(ts|js)" 24 | ], 25 | 26 | // A map from regular expressions to paths to transformers 27 | transform: { 28 | "^.+\\.(ts|tsx)$": "ts-jest" 29 | }, 30 | 31 | // Whether to use watchman for file crawling 32 | watchman: false, 33 | }; 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "logrocket-fuzzy-search-sanitizer", 3 | "version": "0.0.2", 4 | "description": "Plugin for Logrocket to mask request/response bodies by designated field names", 5 | "author": "Josh Bailey", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/jbailey4/logrocket-fuzzy-search-sanitizer" 9 | }, 10 | "bugs": "https://github.com/jbailey4/logrocket-fuzzy-search-sanitizer/issues", 11 | "main": "dist/index.js", 12 | "types": "dist/index.d.ts", 13 | "files": [ 14 | "dist/**/*" 15 | ], 16 | "scripts": { 17 | "build": "npx rollup -c", 18 | "build:watch": "npm run build -w", 19 | "test": "jest", 20 | "lint": "npx tslint --project .", 21 | "lint:fix": "npm run lint --fix", 22 | "prepare": "npm run build" 23 | }, 24 | "keywords": [ 25 | "logrocket", 26 | "logrocket plugin" 27 | ], 28 | "license": "MIT", 29 | "devDependencies": { 30 | "@types/jest": "^23.3.13", 31 | "jest": "^24.3.1", 32 | "logrocket": "^0.6.17", 33 | "rollup": "^1.1.0", 34 | "rollup-plugin-commonjs": "^9.2.0", 35 | "rollup-plugin-typescript2": "^0.19.3", 36 | "ts-jest": "^24.0.0", 37 | "tslint": "^5.12.0", 38 | "typescript": "^3.2.2" 39 | }, 40 | "dependencies": { 41 | "deparam": "^1.0.5" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from 'rollup-plugin-typescript2'; 2 | import commonjs from 'rollup-plugin-commonjs'; 3 | 4 | import pkg from './package.json'; 5 | 6 | const name = 'logrocketFuzzySearchSanitizer'; 7 | 8 | export default { 9 | input: 'src/index.ts', 10 | output: [ 11 | { 12 | file: pkg.main, 13 | format: 'umd', 14 | name 15 | }, 16 | // { 17 | // file: './demo/logrocket-fuzzy-search-sanitizer.js', 18 | // format: 'iife', 19 | // name 20 | // } 21 | ], 22 | plugins: [ 23 | commonjs(), 24 | typescript({ 25 | typescript: require('typescript') 26 | }) 27 | ] 28 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import deparam from 'deparam'; 2 | 3 | interface INetworkRequestResponse { 4 | body?: any; // POJO or a JSON stringify equalivant 5 | method: string; 6 | headers: object; 7 | } 8 | 9 | export default class LogrocketFuzzySearch { 10 | public static setup(fields: string[]) { 11 | const instance = new LogrocketFuzzySearch(fields); 12 | 13 | return { 14 | requestSanitizer: instance.requestSanitizer.bind(instance), 15 | responseSanitizer: instance.responseSanitizer.bind(instance), 16 | }; 17 | } 18 | 19 | public fields: string[] = []; 20 | 21 | constructor(privateFields: string[]) { 22 | this.fields = privateFields; 23 | } 24 | 25 | public requestSanitizer(request: INetworkRequestResponse): object | any { 26 | // avoid parsing GET requests as there will be no body 27 | if (request.method === 'GET') { 28 | return request; 29 | } 30 | 31 | return this._networkHandler(request); 32 | } 33 | 34 | public responseSanitizer(reponse: INetworkRequestResponse): object | any { 35 | return this._networkHandler(reponse); 36 | } 37 | 38 | private _networkHandler(networkRequestReponse: INetworkRequestResponse) { 39 | const { body, headers } = networkRequestReponse; 40 | const requestContentType: string = headers && (headers['Content-Type'] || ''); 41 | const isUrlEncodedRequest: boolean = requestContentType.includes('form-urlencoded'); 42 | let parsedBody: object; 43 | 44 | try { 45 | parsedBody = isUrlEncodedRequest ? deparam(body) : JSON.parse(body); 46 | 47 | this._searchBody(parsedBody); 48 | } catch (error) { 49 | return networkRequestReponse; 50 | } 51 | 52 | networkRequestReponse.body = parsedBody; 53 | 54 | return networkRequestReponse; 55 | } 56 | 57 | private _searchBody(body: any = {}) { 58 | // iterate over collection of objects ex. [{}, ...] 59 | if (body && body.constructor === Array) { 60 | body.forEach((item) => this._searchBody(item)); 61 | } else { 62 | for (const key in body) { 63 | if (body.hasOwnProperty(key)) { 64 | const keyName = body[key]; 65 | 66 | /* 67 | Objects with the following shape: 68 | { 69 | type: 'email', 70 | value: 'secret@ex.com' 71 | } 72 | where type/value keynames are generic and instead 73 | the value matching the type keyname should be masked. 74 | */ 75 | const isTypeValuePair = key === 'type' && 'value' in body; 76 | 77 | if (typeof keyName === 'object') { 78 | if (!isTypeValuePair) { 79 | this._searchBody(keyName); 80 | } 81 | } 82 | 83 | if (isTypeValuePair) { 84 | this._mask(body, body.type, 'value'); 85 | } else { 86 | this._mask(body, key); 87 | } 88 | } 89 | } 90 | } 91 | } 92 | 93 | private _mask(body: object, searchKeyName: string, maskKeyName?: string) { 94 | maskKeyName = maskKeyName || searchKeyName; 95 | 96 | const isSensitiveFieldName = this._match(searchKeyName); 97 | 98 | if (isSensitiveFieldName) { 99 | body[maskKeyName] = '*'; 100 | } 101 | } 102 | 103 | private _match(keyName: string = ''): boolean { 104 | const { fields } = this; 105 | const normalizedKeyName = keyName.toLowerCase(); 106 | 107 | return fields.some((field) => normalizedKeyName.indexOf(field.toLowerCase()) > -1); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ 5 | "module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 6 | "lib": ["es7"], /* Specify library files to be included in the compilation. */ 7 | // "allowJs": true, /* Allow javascript files to be compiled. */ 8 | // "checkJs": true, /* Report errors in .js files. */ 9 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 10 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 11 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 12 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 13 | // "outFile": "./dist/index.js", /* Concatenate and emit output to single file. */ 14 | "outDir": "./dist", /* Redirect output structure to the directory. */ 15 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 16 | // "composite": true, /* Enable project compilation */ 17 | // "removeComments": true, /* Do not emit comments to output. */ 18 | // "noEmit": true, /* Do not emit outputs. */ 19 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 20 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 21 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 22 | 23 | /* Strict Type-Checking Options */ 24 | "strict": true, /* Enable all strict type-checking options. */ 25 | "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ 26 | // "strictNullChecks": true, /* Enable strict null checks. */ 27 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 28 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 29 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 30 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 31 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 32 | 33 | /* Additional Checks */ 34 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 35 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 36 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 37 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 38 | 39 | /* Module Resolution Options */ 40 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 41 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 42 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 43 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 44 | // "typeRoots": [], /* List of folders to include type definitions from. */ 45 | // "types": [], /* Type declaration files to be included in compilation. */ 46 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 47 | // "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 48 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 49 | 50 | /* Source Map Options */ 51 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 52 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 53 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 54 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 55 | 56 | /* Experimental Options */ 57 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 58 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 59 | }, 60 | "include": [ 61 | "src/**/*" 62 | ] 63 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "extends": [ 4 | "tslint:recommended" 5 | ], 6 | "jsRules": {}, 7 | "rules": { 8 | "quotemark": [ 9 | true, 10 | "single" 11 | ] 12 | }, 13 | "rulesDirectory": [] 14 | } --------------------------------------------------------------------------------