From 6c4f9cd375c9fe99268f73a31cd9fac5848691e9 Mon Sep 17 00:00:00 2001 From: hyperz111 Date: Sat, 2 Aug 2025 15:15:16 +0700 Subject: [PATCH] feat(init): validation to make sure config directory is inside cwd --- src/node/init/init.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/node/init/init.ts b/src/node/init/init.ts index 71120541..7bb8aa83 100644 --- a/src/node/init/init.ts +++ b/src/node/init/init.ts @@ -10,6 +10,7 @@ import { import fs from 'fs-extra' import template from 'lodash.template' import path from 'node:path' +import process from 'node:process' import { fileURLToPath } from 'node:url' import c from 'picocolors' import { slash } from '../shared' @@ -49,9 +50,24 @@ export async function init(root?: string) { message: 'Where should VitePress initialize the config?', initialValue: './', defaultValue: './', - validate() { - // TODO make sure directory is inside - return undefined + validate(value) { + const cwd = slash(process.cwd()) + const dir = slash(value as string) + + const cwdRE = new RegExp( + `^${dir.endsWith('/') ? `${cwd}/` : cwd}`, + 'u' + ) + // If give absolute path, use that path instead + const absolutePath = + (process.platform === 'win32' && /^[A-Z]:/i.test(dir)) || + /^\//.test(dir) + ? dir + : path.join(cwd, dir) + + return !cwdRE.test(absolutePath) + ? 'Please init your config inside this directory.' + : undefined } }) },