path-sanitizer 1.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,2 +1,39 @@
1
1
  # path-sanitizer
2
- A simple node.js package for sanitizing paths to prevent Path Traversal
2
+ A simple lightweight npm package for sanitizing paths to prevent Path Traversal
3
+
4
+ # Usage
5
+ ```js
6
+ import sanitize from 'path-sanitizer'
7
+ // or
8
+ const sanitize = require('path-sanitizer').default
9
+
10
+ console.log(sanitize('path/to/file.txt'))
11
+ ```
12
+
13
+ Or here is a more complex example:
14
+ ```js
15
+ const sanitize = require('../sanitize')
16
+ const path = require('path')
17
+
18
+ // Real scenario:
19
+ function routeHandler (myPath) {
20
+ // Lets just assume that the path was extracted from the request
21
+ // We want to read a file in the C:\Users\user\Desktop\myApp\ directory
22
+ // But the user should not be able to access C:\Users\user\Desktop\
23
+ // So we need to sanitize the path
24
+
25
+ const APP_DIR = 'C:\\Users\\user\\Desktop\\myApp\\'
26
+ const sanitized = path.join(APP_DIR, sanitize(myPath))
27
+
28
+ // Now we would usually read the file
29
+ // But in this case we will just print the path
30
+ console.log(sanitized)
31
+ }
32
+
33
+ routeHandler('my-video.mp4') // Just fine...
34
+ routeHandler('../../Documents/grades.docx') // But what if we try to access a file outside the app directory?
35
+ routeHandler('/hello.txt') // What if the path starts with a slash, and we try to use an absolute path?
36
+ routeHandler('////////a\\\\../hi.txt') // What if the path is not valid?
37
+ routeHandler(500) // What if the path is not a string?
38
+ routeHandler('/:11^^') // What if the path contains not allowed characters (like ":")?
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": "1.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,5 +0,0 @@
1
- function sanitize () {
2
-
3
- }
4
-
5
- module.exports = sanitize