path-sanitizer 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,32 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - '**'
7
+ pull_request:
8
+ branches:
9
+ - '**'
10
+
11
+ jobs:
12
+ test:
13
+ runs-on: ubuntu-latest
14
+
15
+ steps:
16
+ - name: Checkout code
17
+ uses: actions/checkout@v3
18
+
19
+ - name: Setup Node.js
20
+ uses: actions/setup-node@v3
21
+ with:
22
+ node-version: 18
23
+ cache: 'pnpm'
24
+
25
+ - name: Install pnpm
26
+ run: npm install -g pnpm
27
+
28
+ - name: Install dependencies
29
+ run: pnpm install
30
+
31
+ - name: Run tests
32
+ run: pnpm test
package/README.md CHANGED
@@ -1,9 +1,11 @@
1
1
  # path-sanitizer
2
- A simple leightweight node.js package for sanitizing paths to prevent Path Traversal
2
+ A simple lightweight npm package for sanitizing paths to prevent Path Traversal
3
3
 
4
4
  # Usage
5
5
  ```js
6
- const sanitize = require('path-sanitizer')
6
+ import sanitize from 'path-sanitizer'
7
+ // or
8
+ const sanitize = require('path-sanitizer').default
7
9
 
8
10
  console.log(sanitize('path/to/file.txt'))
9
11
  ```
@@ -17,21 +19,21 @@ const path = require('path')
17
19
  function routeHandler (myPath) {
18
20
  // Lets just assume that the path was extracted from the request
19
21
  // We want to read a file in the C:\Users\user\Desktop\myApp\ directory
20
- // But the user should be able to access C:\Users\user\Desktop\
22
+ // But the user should not be able to access C:\Users\user\Desktop\
21
23
  // So we need to sanitize the path
22
24
 
23
25
  const APP_DIR = 'C:\\Users\\user\\Desktop\\myApp\\'
24
26
  const sanitized = path.join(APP_DIR, sanitize(myPath))
25
27
 
26
- // Now we would usally read the file
27
- // But in this case we just gonna print the path
28
+ // Now we would usually read the file
29
+ // But in this case we will just print the path
28
30
  console.log(sanitized)
29
31
  }
30
32
 
31
- routeHandler('myvideo.mp4') // Just fine...
33
+ routeHandler('my-video.mp4') // Just fine...
32
34
  routeHandler('../../Documents/grades.docx') // But what if we try to access a file outside the app directory?
33
35
  routeHandler('/hello.txt') // What if the path starts with a slash, and we try to use an absolute path?
34
- routeHandler('////////a\\\\../hhuio.txt') // What if the path is not valid?
36
+ routeHandler('////////a\\\\../hi.txt') // What if the path is not valid?
35
37
  routeHandler(500) // What if the path is not a string?
36
38
  routeHandler('/:11^^') // What if the path contains not allowed characters (like ":")?
37
39
  ```
@@ -0,0 +1,31 @@
1
+ export interface SanitizeOptions {
2
+ decode?: ({
3
+ regex: RegExp;
4
+ replacement: string;
5
+ })[];
6
+ /**
7
+ * RegEx that filters out stuff like \..\ or /../
8
+ */
9
+ parentDirectoryRegEx?: RegExp;
10
+ /**
11
+ * Characters to be removed from paths because the file system doesn't support these.
12
+ */
13
+ notAllowedRegEx?: RegExp;
14
+ }
15
+ interface SanitizeOptionsComplete {
16
+ decode: ({
17
+ regex: RegExp;
18
+ replacement: string;
19
+ })[];
20
+ /**
21
+ * RegEx that filters out stuff like \..\ or /../
22
+ */
23
+ parentDirectoryRegEx: RegExp;
24
+ /**
25
+ * Characters to be removed from paths because the file system doesn't support these.
26
+ */
27
+ notAllowedRegEx: RegExp;
28
+ }
29
+ export declare const DEFAULT_OPTIONS: SanitizeOptionsComplete;
30
+ export default function sanitize(pathstr: string, options?: SanitizeOptions): string;
31
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_OPTIONS = void 0;
4
+ exports.default = sanitize;
5
+ const node_path_1 = require("node:path");
6
+ exports.DEFAULT_OPTIONS = {
7
+ decode: [
8
+ {
9
+ regex: /%2e/g,
10
+ replacement: '.'
11
+ },
12
+ {
13
+ regex: /%2f/g,
14
+ replacement: '/'
15
+ },
16
+ {
17
+ regex: /%5c/g,
18
+ replacement: '\\'
19
+ }
20
+ ],
21
+ parentDirectoryRegEx: /[\/\\]\.\.[\/\\]/g,
22
+ notAllowedRegEx: /:|\$|!|'|"|@|\+|`|\||=/g
23
+ };
24
+ function sanitize(pathstr, options = exports.DEFAULT_OPTIONS) {
25
+ if (!options)
26
+ options = exports.DEFAULT_OPTIONS;
27
+ if (typeof options !== 'object')
28
+ throw new Error('options must be an object');
29
+ if (!Array.isArray(options.decode))
30
+ options.decode = exports.DEFAULT_OPTIONS.decode;
31
+ if (!options.parentDirectoryRegEx)
32
+ options.parentDirectoryRegEx = exports.DEFAULT_OPTIONS.parentDirectoryRegEx;
33
+ if (!options.notAllowedRegEx)
34
+ options.notAllowedRegEx = exports.DEFAULT_OPTIONS.notAllowedRegEx;
35
+ if (typeof pathstr !== 'string') {
36
+ // Stringify the path
37
+ pathstr = `${pathstr}`;
38
+ }
39
+ let sanitizedPath = pathstr;
40
+ // ################################################################################################################
41
+ // Decode
42
+ options.decode.forEach(decode => {
43
+ sanitizedPath = sanitizedPath.replace(decode.regex, decode.replacement);
44
+ });
45
+ // Remove not allowed characters
46
+ sanitizedPath = sanitizedPath.replace(options.notAllowedRegEx, '');
47
+ // Replace backslashes with normal slashes
48
+ sanitizedPath = sanitizedPath.replace(/[\\]/g, '/');
49
+ // Replace /../ with /
50
+ sanitizedPath = sanitizedPath.replace(options.parentDirectoryRegEx, '/');
51
+ // Remove ../ at pos 0 and /.. at end
52
+ sanitizedPath = sanitizedPath.replace(/^\.\.[\/\\]/g, '/');
53
+ sanitizedPath = sanitizedPath.replace(/[\/\\]\.\.$/g, '/');
54
+ // Replace double (back)slashes with a single slash
55
+ sanitizedPath = sanitizedPath.replace(/[\/\\]+/g, '/');
56
+ // Normalize path
57
+ sanitizedPath = (0, node_path_1.normalize)(sanitizedPath);
58
+ // Remove / or \ in the end
59
+ while (sanitizedPath.endsWith('/') || sanitizedPath.endsWith('\\')) {
60
+ sanitizedPath = sanitizedPath.slice(0, -1);
61
+ }
62
+ // Remove / or \ in the beginning
63
+ while (sanitizedPath.startsWith('/') || sanitizedPath.startsWith('\\')) {
64
+ sanitizedPath = sanitizedPath.slice(1);
65
+ }
66
+ // Validate path
67
+ sanitizedPath = (0, node_path_1.join)('', sanitizedPath);
68
+ // Remove not allowed characters
69
+ sanitizedPath = sanitizedPath.replace(options.notAllowedRegEx, '');
70
+ // Again change all \ to /
71
+ sanitizedPath = sanitizedPath.replace(/[\\]/g, '/');
72
+ // Replace double (back)slashes with a single slash
73
+ sanitizedPath = sanitizedPath.replace(/[\/\\]+/g, '/');
74
+ return sanitizedPath;
75
+ }
package/package.json CHANGED
@@ -1,25 +1,26 @@
1
1
  {
2
- "name": "path-sanitizer",
3
- "version": "2.0.0",
4
- "description": "A simple node.js package for sanitizing paths to prevent Path Traversal",
5
- "main": "sanitize.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "repository": {
10
- "type": "git",
11
- "url": "git+https://github.com/greencoder001/path-sanitizer.git"
12
- },
13
- "keywords": [
14
- "path",
15
- "sanitize",
16
- "sanitizer",
17
- "path-sanitizer"
18
- ],
19
- "author": "greencoder001",
20
- "license": "MIT",
21
- "bugs": {
22
- "url": "https://github.com/greencoder001/path-sanitizer/issues"
23
- },
24
- "homepage": "https://github.com/greencoder001/path-sanitizer#readme"
25
- }
2
+ "name": "path-sanitizer",
3
+ "version": "3.0.0",
4
+ "description": "A simple lightweight npm package for sanitizing paths to prevent Path Traversal",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "test": "vitest"
8
+ },
9
+ "keywords": [],
10
+ "author": "Cabra (https://github.com/cabraviva)",
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/cabraviva/path-sanitizer.git"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/cabraviva/path-sanitizer/issues"
18
+ },
19
+ "homepage": "https://github.com/cabraviva/path-sanitizer#readme",
20
+ "types": "dist/index.d.ts",
21
+ "devDependencies": {
22
+ "@types/node": "^22.9.3",
23
+ "typescript": "^5.7.2",
24
+ "vitest": "^2.1.5"
25
+ }
26
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNEXT",
4
+ "module": "commonjs",
5
+ "declaration": true,
6
+ "outDir": "./dist",
7
+ "strict": true
8
+ },
9
+ "include": [
10
+ "lib/*.ts"
11
+ ],
12
+ "exclude": [
13
+ "lib/*.test.ts"
14
+ ]
15
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Green_Lab
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.
package/sanitize.js DELETED
@@ -1,72 +0,0 @@
1
- const path = require('path')
2
-
3
- const DEFAULT_OPTIONS = {
4
- decode: [
5
- {
6
- regex: /%2e/g,
7
- replacement: '.'
8
- },
9
- {
10
- regex: /%2f/g,
11
- replacement: '/'
12
- },
13
- {
14
- regex: /%5c/g,
15
- replacement: '\\'
16
- }
17
- ],
18
- parentDirectoryRegEx: /[\/\\]\.\.[\/\\]/g,
19
- notAllowedRegEx: /:|\$|!|'|"|@|\+|`|\||=/g
20
- }
21
-
22
- function sanitize (pathToSanitize, options = DEFAULT_OPTIONS) {
23
- if (!options) options = DEFAULT_OPTIONS
24
- if (typeof options !== 'object') throw new Error('options must be an object')
25
- if (!options.decode) options.decode = DEFAULT_OPTIONS.decode
26
- if (!options.parentDirectoryRegEx) options.parentDirectoryRegEx = DEFAULT_OPTIONS.parentDirectoryRegEx
27
- if (!options.notAllowedRegEx) options.notAllowedRegEx = DEFAULT_OPTIONS.notAllowedRegEx
28
-
29
- if (typeof pathToSanitize !== 'string') {
30
- // Stringify the path
31
- pathToSanitize = `${pathToSanitize}`
32
- }
33
-
34
- let sanitizedPath = pathToSanitize
35
-
36
- // Decode
37
- options.decode.forEach(decode => {
38
- sanitizedPath = sanitizedPath.replace(decode.regex, decode.replacement)
39
- })
40
-
41
- // Replace first (back)slash with a normal slash
42
- sanitizedPath = sanitizedPath.replace(/^[\/\\]?/, '/')
43
-
44
- // Replace /../ with /
45
- sanitizedPath = sanitizedPath.replace(options.parentDirectoryRegEx, '/')
46
-
47
- // Replace double (back)slashes with a single slash
48
- sanitizedPath = sanitizedPath.replace(/[\/\\]+/g, '/')
49
-
50
- // Normalize path
51
- sanitizedPath = path.normalize(sanitizedPath)
52
-
53
- // Remove / or \ in the end
54
- while (sanitizedPath.endsWith('/') || sanitizedPath.endsWith('\\')) {
55
- sanitizedPath = sanitizedPath.slice(0, -1)
56
- }
57
-
58
- // Remove / or \ in the beginning
59
- while (sanitizedPath.startsWith('/') || sanitizedPath.startsWith('\\')) {
60
- sanitizedPath = sanitizedPath.slice(1)
61
- }
62
-
63
- // Validate path
64
- sanitizedPath = path.join('', sanitizedPath)
65
-
66
- // Remove not allowed characters
67
- sanitizedPath = sanitizedPath.replace(options.notAllowedRegEx, '')
68
-
69
- return sanitizedPath
70
- }
71
-
72
- module.exports = sanitize