|
| 1 | +const path = require("path") |
| 2 | + |
| 3 | +const { z } = require("zod") |
| 4 | +const { fromError } = require("zod-validation-error") |
| 5 | + |
| 6 | +class OptionsError extends Error { |
| 7 | + constructor(message) { |
| 8 | + super(message) |
| 9 | + this.name = "OptionsError" |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +const optionsSchema = z.object({ |
| 14 | + basePath: z |
| 15 | + .string() |
| 16 | + .refine( |
| 17 | + (basePath) => |
| 18 | + basePath === path.resolve(basePath) && path.isAbsolute(basePath), |
| 19 | + "The base path must be an absolute path" |
| 20 | + ), |
| 21 | +}) |
| 22 | + |
| 23 | +const isSafePath = (absPath, basePath) => { |
| 24 | + // check for poison null bytes |
| 25 | + if (absPath.indexOf("\0") !== -1) { |
| 26 | + return false |
| 27 | + } |
| 28 | + // check for backslashes |
| 29 | + if (absPath.indexOf("\\") !== -1) { |
| 30 | + return false |
| 31 | + } |
| 32 | + |
| 33 | + // check for dot segments, even if they don't normalize to anything |
| 34 | + if (absPath.includes("..")) { |
| 35 | + return false |
| 36 | + } |
| 37 | + |
| 38 | + // check if the normalized path is within the provided 'safe' base path |
| 39 | + if (path.resolve(basePath, path.relative(basePath, absPath)) !== absPath) { |
| 40 | + return false |
| 41 | + } |
| 42 | + if (absPath.indexOf(basePath) !== 0) { |
| 43 | + return false |
| 44 | + } |
| 45 | + return true |
| 46 | +} |
| 47 | + |
| 48 | +const createValidationSchema = (options) => |
| 49 | + z |
| 50 | + .string() |
| 51 | + // resolve the path relative to the Node process's current working directory |
| 52 | + // since that's what fs operations will be relative to |
| 53 | + .transform((untrustedPath) => path.resolve(untrustedPath)) |
| 54 | + // resolvedPath is now an absolute path |
| 55 | + .refine((resolvedPath) => isSafePath(resolvedPath, options.basePath), { |
| 56 | + message: "The provided path is unsafe.", |
| 57 | + }) |
| 58 | + |
| 59 | +const toSchema = (options) => |
| 60 | + z.string().trim().pipe(createValidationSchema(options)) |
| 61 | + |
| 62 | +/** |
| 63 | + * Create a schema that validates user-supplied pathnames for filesystem operations. |
| 64 | + * |
| 65 | + * @param options - The options to use for validation |
| 66 | + * @throws {@link OptionsError} If the options are invalid |
| 67 | + * @returns A Zod schema that validates paths. |
| 68 | + * |
| 69 | + * @public |
| 70 | + */ |
| 71 | +const createPathSchema = (options) => { |
| 72 | + const result = optionsSchema.safeParse(options) |
| 73 | + if (result.success) { |
| 74 | + return toSchema(result.data) |
| 75 | + } |
| 76 | + throw new OptionsError(fromError(result.error).toString()) |
| 77 | +} |
| 78 | + |
| 79 | +module.exports = { |
| 80 | + createPathSchema, |
| 81 | +} |
0 commit comments