Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): prevent path traversal and safer file writes (#2459)

Joey5c59ee038f22
diff --git a/packages/cli/src/api/template.mjs b/packages/cli/src/api/template.mjs
index 46782ff88c..62075d5dec 100644
--- a/packages/cli/src/api/template.mjs
+++ b/packages/cli/src/api/template.mjs
@@ -7,6 +7,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {CLI_ROOT, discoverExternalPackages} from '../utils/paths.mjs';
+import {assertWithin, isFilePathArg, PathSafetyError} from '../utils/path-safety.mjs';
import {XDSError} from './error.mjs';
import {loadConfig} from '../lib/config.mjs';
@@ -455,14 +456,44 @@ export async function template(name, options = {}) {
};
}
- const outputDir = path.resolve(cwd, targetPath);
- const outputFileName = match.type === 'block'
- ? path.basename(match.filePath)
- : 'page.tsx';
+ // Path-safety: resolve the user-supplied targetPath relative to cwd,
+ // rejecting absolute paths and any traversal that escapes the project
+ // root. This guard runs BEFORE any mkdir/copyFile so we never create
+ // directories outside the root just to fail on the file write.
+ let resolvedTarget;
+ try {
+ resolvedTarget = assertWithin(targetPath, cwd, {
+ label: 'template target path',
+ });
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ throw new XDSError(err.message);
+ }
+ throw err;
+ }
+
+ // If targetPath looks like a file (e.g. `./foo.tsx`), write directly to
+ // it. Previously this path was treated as a directory and the file was
+ // written as `./foo.tsx/page.tsx`, which is wrong and surprising.
+ let outputDir;
+ let outputFileName;
+ let outputFilePath;
+ if (isFilePathArg(targetPath)) {
+ outputDir = path.dirname(resolvedTarget);
+ outputFileName = path.basename(resolvedTarget);
+ outputFilePath = resolvedTarget;
+ } else {
+ outputDir = resolvedTarget;
+ outputFileName = match.type === 'block'
+ ? path.basename(match.filePath)
+ : 'page.tsx';
+ outputFilePath = path.join(outputDir, outputFileName);
+ }
+
fs.mkdirSync(outputDir, {recursive: true});
- fs.copyFileSync(match.filePath, path.join(outputDir, outputFileName));
+ fs.copyFileSync(match.filePath, outputFilePath);
- const relOutput = path.relative(cwd, outputDir);
+ const relOutput = path.relative(cwd, outputDir) || '.';
return {
type: 'template.copy',
data: {template: name, outputDir: relOutput, fileName: outputFileName, filesCopied: 1},
diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjs
index 1ee1a9c4f5..345f787547 100644
--- a/packages/cli/src/commands/agent-docs.mjs
+++ b/packages/cli/src/commands/agent-docs.mjs
@@ -20,6 +20,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {findCoreDir, CLI_ROOT} from '../utils/paths.mjs';
+import {assertWithin, PathSafetyError} from '../utils/path-safety.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
import {discoverComponents} from '../lib/component-discovery.mjs';
import {discoverHooks} from '../lib/hook-discovery.mjs';
@@ -338,6 +339,12 @@ export function installAgentDocs(targetDir, {zh = false, lang, agent, paths, onl
// Explicit paths override everything
if (paths && paths.length > 0) {
+ // Path-safety: each --agent-docs-path entry must resolve inside the
+ // target directory. Reject absolute paths (silent re-rooting via
+ // path.join hides intent) and `..` traversal.
+ for (const p of paths) {
+ assertWithin(p, targetDir, {label: 'agent docs path'});
+ }
for (const p of paths) {
const filePath = path.join(targetDir, p);
const dir = path.dirname(filePath);
@@ -438,12 +445,22 @@ export function registerAgentDocs(program) {
: [options.agentDocsPath]
: undefined;
- const targets = installAgentDocs(targetDir, {
- zh,
- lang,
- agent: options.agent,
- paths: explicitPaths,
- });
+ let targets;
+ try {
+ targets = installAgentDocs(targetDir, {
+ zh,
+ lang,
+ agent: options.agent,
+ paths: explicitPaths,
+ });
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ console.error(`Error: ${err.message}`);
+ process.exitCode = 1;
+ return;
+ }
+ throw err;
+ }
const runPrefix = getRunPrefix(targetDir);
const run = `${runPrefix} xds`;
diff --git a/packages/cli/src/commands/agent-docs.path-safety.test.mjs b/packages/cli/src/commands/agent-docs.path-safety.test.mjs
new file mode 100644
index 0000000000..ce08ef9920
--- /dev/null
+++ b/packages/cli/src/commands/agent-docs.path-safety.test.mjs
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Path-safety regression tests for `--agent-docs-path`.
+ *
+ * `installAgentDocs(targetDir, {paths})` previously joined each path
+ * onto `targetDir` with no validation, so:
+ * - `../OUT.md` wrote outside `targetDir`
+ * - `/tmp/x.md` was silently re-rooted under `targetDir`
+ *
+ * Both cases now throw PathSafetyError before any file is touched.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {installAgentDocs} from './agent-docs.mjs';
+import {PathSafetyError} from '../utils/path-safety.mjs';
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-agent-docs-paths-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('installAgentDocs path safety', () => {
+ it('rejects --agent-docs-path that escapes the target directory', () => {
+ const target = path.join(tmpDir, 'project');
+ const outside = path.join(tmpDir, 'outside');
+ fs.mkdirSync(target, {recursive: true});
+ fs.mkdirSync(outside, {recursive: true});
+
+ expect(() =>
+ installAgentDocs(target, {paths: ['../OUT.md']}),
+ ).toThrow(PathSafetyError);
+
+ expect(fs.existsSync(path.join(tmpDir, 'OUT.md'))).toBe(false);
+ expect(fs.readdirSync(outside)).toEqual([]);
+ });
+
+ it('rejects an absolute --agent-docs-path with a clear error', () => {
+ const target = path.join(tmpDir, 'project');
+ fs.mkdirSync(target, {recursive: true});
+ const absPath = path.join(tmpDir, 'absolute.md');
+
+ expect(() =>
+ installAgentDocs(target, {paths: [absPath]}),
+ ).toThrow(/absolute paths are not allowed/i);
+
+ expect(fs.existsSync(absPath)).toBe(false);
+ });
+
+ it('rejects deeper traversal segments', () => {
+ const target = path.join(tmpDir, 'a', 'b', 'c');
+ fs.mkdirSync(target, {recursive: true});
+
+ expect(() =>
+ installAgentDocs(target, {paths: ['../../../escaped.md']}),
+ ).toThrow(PathSafetyError);
+
+ expect(fs.existsSync(path.join(tmpDir, 'escaped.md'))).toBe(false);
+ });
+});
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index cdb123232d..1c67ca9a93 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -18,6 +18,7 @@ import {createRequire} from 'node:module';
import {pathToFileURL, fileURLToPath} from 'node:url';
import {createJiti} from 'jiti';
import {getRunPrefix} from '../utils/package-manager.mjs';
+import {sanitizeName, PathSafetyError} from '../utils/path-safety.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
// Import shared theme processing from core — ensures build and runtime
@@ -1015,6 +1016,21 @@ export function registerTheme(program) {
process.exit(1);
}
+ // Path-safety: the theme name is used to derive output filenames
+ // (e.g. `${name}.css`, `${name}.js`). Reject names containing path
+ // separators or traversal markers — `../../escaped` would otherwise
+ // write JS modules outside the input directory.
+ try {
+ sanitizeName(themeDef.name, {label: 'theme name'});
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ if (json) return jsonError(err.message);
+ console.error(`Error: ${err.message}`);
+ process.exit(1);
+ }
+ throw err;
+ }
+
// Validate component overrides
const warnings = validateComponentOverrides(themeDef);
const warningMessages = [];
@@ -1123,47 +1139,81 @@ export function registerTheme(program) {
? path.resolve(process.cwd(), options.out)
: filePath.replace(/\.(ts|tsx|js|jsx|mjs)$/, '.css');
- // Write CSS with @generated header
- fs.mkdirSync(path.dirname(outPath), {recursive: true});
- fs.writeFileSync(outPath, generatedHeader(sourceRelative, 'css', buildCommand) + css);
-
const displayTheme = resolvedTheme || themeDef;
const tokenCount = displayTheme.tokens ? Object.keys(displayTheme.tokens).length : 0;
const componentCount = displayTheme.components ? Object.keys(displayTheme.components).length : 0;
const size = (Buffer.byteLength(css) / 1024).toFixed(1);
- if (!json) {
- humanLog(`\n✓ ${path.relative(process.cwd(), outPath)}`);
- humanLog(` ${tokenCount} token overrides, ${componentCount} component overrides`);
- humanLog(` ${size} KB`);
- }
-
- // Always generate JS module + types alongside CSS
+ // Compute all output paths up front so we can validate them as a
+ // group BEFORE writing anything. Previously the CSS would be written
+ // first; if the JS write failed (e.g. ENOENT, permission), the CSS
+ // was left as orphaned half-built output. Stage-then-commit avoids
+ // that.
const outDir = path.dirname(outPath);
const baseName = themeDef.name;
-
const jsPath = path.join(outDir, `${baseName}.js`);
const dtsPath = path.join(outDir, `${baseName}.d.ts`);
const iconInfo = extractIconInfo(filePath);
- fs.writeFileSync(jsPath, generatedHeader(sourceRelative, 'js', buildCommand) + generateBuiltModule(resolvedTheme || themeDef, iconInfo));
- fs.writeFileSync(dtsPath, generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo));
+ // Generate all file contents in memory first.
+ const cssContent = generatedHeader(sourceRelative, 'css', buildCommand) + css;
+ const jsContent = generatedHeader(sourceRelative, 'js', buildCommand) + generateBuiltModule(resolvedTheme || themeDef, iconInfo);
+ const dtsContent = generatedHeader(sourceRelative, 'ts', buildCommand) + generateBuiltTypes(themeDef, iconInfo);
+
+ // Type augmentation .d.ts if theme has custom prop values
+ const augmentationSource = resolvedTheme || themeDef;
+ const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);
+ const variantDtsPath = variantDecl ? path.join(outDir, `${baseName}.variants.d.ts`) : null;
+ const variantContent = variantDecl
+ ? generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl
+ : null;
+
+ // Atomic-ish write: stage every file as `<dest>.tmp`, then rename
+ // each into place. If any stage step fails we clean up partials and
+ // exit; if a rename fails mid-way we still have the originals (or
+ // nothing) — never a half-built output set.
+ const writes = [
+ {dest: outPath, content: cssContent},
+ {dest: jsPath, content: jsContent},
+ {dest: dtsPath, content: dtsContent},
+ ];
+ if (variantDtsPath) {
+ writes.push({dest: variantDtsPath, content: variantContent});
+ }
+
+ fs.mkdirSync(outDir, {recursive: true});
+ const staged = [];
+ try {
+ for (const w of writes) {
+ const tmp = `${w.dest}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, w.content);
+ staged.push({tmp, dest: w.dest});
+ }
+ for (const s of staged) {
+ fs.renameSync(s.tmp, s.dest);
+ }
+ } catch (err) {
+ // Roll back any temp files we managed to create.
+ for (const s of staged) {
+ try { fs.rmSync(s.tmp, {force: true}); } catch { /* best-effort */ }
+ }
+ const msg = `Failed to write theme outputs: ${err.message}`;
+ if (json) return jsonError(msg);
+ console.error(`Error: ${msg}`);
+ process.exit(1);
+ }
if (!json) {
+ humanLog(`\n✓ ${path.relative(process.cwd(), outPath)}`);
+ humanLog(` ${tokenCount} token overrides, ${componentCount} component overrides`);
+ humanLog(` ${size} KB`);
humanLog(`✓ ${path.relative(process.cwd(), jsPath)}`);
humanLog(`✓ ${path.relative(process.cwd(), dtsPath)}`);
- }
-
- // Generate type augmentation .d.ts if theme has custom prop values
- const augmentationSource = resolvedTheme || themeDef;
- const variantDecl = await generateVariantDeclarationsAsync(augmentationSource);
- let variantDtsPath;
- if (variantDecl) {
- variantDtsPath = path.join(outDir, `${baseName}.variants.d.ts`);
- fs.writeFileSync(variantDtsPath, generatedHeader(sourceRelative, 'ts', buildCommand) + variantDecl);
- const augCount = (variantDecl.match(/': true;/g) || []).length;
- if (!json) humanLog(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
+ if (variantDtsPath) {
+ const augCount = (variantDecl.match(/': true;/g) || []).length;
+ humanLog(`✓ ${path.relative(process.cwd(), variantDtsPath)} (${augCount} type augmentations)`);
+ }
}
if (json) {
diff --git a/packages/cli/src/commands/build-theme.path-safety.test.mjs b/packages/cli/src/commands/build-theme.path-safety.test.mjs
new file mode 100644
index 0000000000..e712769a86
--- /dev/null
+++ b/packages/cli/src/commands/build-theme.path-safety.test.mjs
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Path-safety regression tests for `xds theme build`.
+ *
+ * Covers:
+ * - Theme name with `..` segments cannot escape the output directory.
+ * - Theme name with `/` is rejected with a clear error (vs. ENOENT).
+ * - Multi-file write is atomic: if one file fails, none are left behind.
+ *
+ * Runs the CLI via execFileSync against a tiny synthetic theme file.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI_BIN = path.resolve(__dirname, '../../bin/xds.mjs');
+
+function runCli(args, cwd) {
+ try {
+ const out = execFileSync('node', [CLI_BIN, ...args], {
+ cwd,
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: {...process.env, FORCE_COLOR: '0'},
+ });
+ return {code: 0, stdout: out, stderr: ''};
+ } catch (e) {
+ return {
+ code: e.status ?? 1,
+ stdout: e.stdout?.toString() ?? '',
+ stderr: e.stderr?.toString() ?? '',
+ };
+ }
+}
+
+function writeTheme(dir, name) {
+ fs.mkdirSync(dir, {recursive: true});
+ const file = path.join(dir, 'theme.mjs');
+ // Plain object literal so the legacy regex+eval path can parse it
+ // without needing jiti / TS, and without depending on @xds/core being
+ // built. The eval path explicitly supports this shape.
+ fs.writeFileSync(
+ file,
+ `export default { name: ${JSON.stringify(name)}, tokens: { '--color-bg': '#fff' } };\n`,
+ );
+ return file;
+}
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-build-theme-paths-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('theme build path safety', () => {
+ it('rejects a theme name containing ../ traversal and writes no JS outside the input dir', () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const outside = path.join(tmpDir, 'outside');
+ fs.mkdirSync(outside, {recursive: true});
+
+ const themeFile = writeTheme(themesDir, '../../escaped');
+
+ const result = runCli(
+ ['theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr + result.stdout).toMatch(/path separator|invalid theme name/i);
+
+ // The traversal target must not exist.
+ expect(fs.existsSync(path.join(tmpDir, 'escaped.js'))).toBe(false);
+ expect(fs.existsSync(path.join(tmpDir, 'escaped.css'))).toBe(false);
+ expect(fs.readdirSync(outside)).toEqual([]);
+ });
+
+ it('rejects a theme name containing /', () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+
+ const themeFile = writeTheme(themesDir, 'bad/name');
+
+ const result = runCli(
+ ['theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr + result.stdout).toMatch(/path separator/i);
+
+ // No partial output — neither bad nor bad/name files should exist.
+ expect(fs.existsSync(path.join(themesDir, 'bad.js'))).toBe(false);
+ expect(fs.existsSync(path.join(themesDir, 'bad', 'name.js'))).toBe(false);
+ });
+
+ it('does not leave partial output (no CSS without JS) on a sanitized rejection', () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+
+ const themeFile = writeTheme(themesDir, '../leak');
+
+ runCli(['theme', 'build', path.relative(project, themeFile)], project);
+
+ // Neither the CSS nor any sibling JS should have been written.
+ const entries = fs.readdirSync(themesDir).sort();
+ expect(entries).toEqual(['theme.mjs']);
+ });
+});
diff --git a/packages/cli/src/commands/init.mjs b/packages/cli/src/commands/init.mjs
index 00d2a5631e..9468cc8be8 100644
--- a/packages/cli/src/commands/init.mjs
+++ b/packages/cli/src/commands/init.mjs
@@ -17,6 +17,7 @@ import * as p from '@clack/prompts';
import * as path from 'node:path';
import * as fs from 'node:fs';
import {CLI_ROOT} from '../utils/paths.mjs';
+import {PathSafetyError} from '../utils/path-safety.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
import {installAgentDocs, removeAgentDocs} from './agent-docs.mjs';
import {listTemplates} from './template.mjs';
@@ -50,7 +51,20 @@ function runAgents(targetDir, {interactive = true, agent, agentDocsPath} = {}) {
} else {
humanLog(`✓ AI agent docs installed → ${summary}`);
}
- } catch {
+ } catch (err) {
+ // PathSafetyError carries a precise, user-actionable message —
+ // surface it instead of the generic "could not install" warning so
+ // misconfigured --agent-docs-path values aren't silently swallowed.
+ if (err instanceof PathSafetyError) {
+ const msg = `Error: ${err.message}`;
+ if (interactive) {
+ p.log.error(msg);
+ } else {
+ console.error(msg);
+ }
+ process.exitCode = 1;
+ return;
+ }
const msg = `Could not install agent docs. Try again with \`${run} xds init --features agents\`.`;
if (interactive) {
p.log.warning(msg);
diff --git a/packages/cli/src/commands/swizzle-gap-safety.test.mjs b/packages/cli/src/commands/swizzle-gap-safety.test.mjs
index 7bd44701c3..5026b8d307 100644
--- a/packages/cli/src/commands/swizzle-gap-safety.test.mjs
+++ b/packages/cli/src/commands/swizzle-gap-safety.test.mjs
@@ -20,7 +20,7 @@
* called `gh issue create` with no confirmation.
*/
-import {describe, it, expect, beforeAll, afterAll} from 'vitest';
+import {describe, it, expect, beforeAll, afterAll, beforeEach, afterEach} from 'vitest';
import {spawnSync} from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
@@ -178,12 +178,29 @@ describe('gap-report: dry-run by default in non-interactive mode', () => {
});
describe('swizzle --gap respects safety gates', () => {
+ // swizzle's --output is path-safety guarded: absolute paths and `..`
+ // traversal are rejected (see swizzle.path-safety.test.mjs). These gap
+ // tests only care about the gh-call / status gates, so they write into a
+ // *relative* output dir created under the repo root (a valid, in-root
+ // target) and clean it up afterward. The CLI still resolves @xds/core via
+ // findCoreDir walking up from the cwd.
+ let swizzleOutDir;
+ beforeEach(() => {
+ swizzleOutDir = fs.mkdtempSync(path.join(repoRoot, '.xds-swizzle-gap-test-'));
+ });
+ afterEach(() => {
+ if (swizzleOutDir) fs.rmSync(swizzleOutDir, {recursive: true, force: true});
+ });
+ // Relative path into the temp dir, so it passes the path-safety guard
+ // (cwd === repoRoot for runXds by default).
+ const relOut = () => path.relative(repoRoot, swizzleOutDir);
+
it('swizzle --gap in non-TTY → dry-run, no gh call', () => {
const r = runXds([
'swizzle',
'Button',
'--output',
- path.join(os.tmpdir(), 'xds-swizzle-test-' + Date.now()),
+ relOut(),
'--gap',
'Need a compact variant',
'--gap-category',
@@ -195,12 +212,11 @@ describe('swizzle --gap respects safety gates', () => {
});
it('swizzle --gap --no-report → never engages gap reporting at all', () => {
- const outDir = path.join(os.tmpdir(), 'xds-swizzle-noreport-' + Date.now());
const r = runXds([
'swizzle',
'Button',
'--output',
- outDir,
+ relOut(),
'--gap',
'Should be suppressed entirely',
'--gap-category',
@@ -217,13 +233,12 @@ describe('swizzle --gap respects safety gates', () => {
it('swizzle --gap --no-report --commit → STILL no gh call (no-report wins)', () => {
// Critical regression test: --no-report must beat --commit for the
// --gap auto-file path. Otherwise CI scripts could file issues.
- const outDir = path.join(os.tmpdir(), 'xds-swizzle-norep2-' + Date.now());
const r = runXds(
[
'swizzle',
'Button',
'--output',
- outDir,
+ relOut(),
'--gap',
'should never file',
'--gap-category',
@@ -238,13 +253,12 @@ describe('swizzle --gap respects safety gates', () => {
});
it('swizzle --gap with XDS_GAP_REPORT=off → no gh call', () => {
- const outDir = path.join(os.tmpdir(), 'xds-swizzle-envoff-' + Date.now());
const r = runXds(
[
'swizzle',
'Button',
'--output',
- outDir,
+ relOut(),
'--gap',
'should be disabled by env',
'--gap-category',
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index 3944ae3257..71c45d520e 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -15,6 +15,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as p from '@clack/prompts';
import {findCoreDir, listComponents} from '../utils/paths.mjs';
+import {assertWithin, PathSafetyError, isNonInteractive} from '../utils/path-safety.mjs';
import {isInteractive} from '../utils/interactive.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {
@@ -78,6 +79,7 @@ export function registerSwizzle(program) {
'--commit',
'For --gap: actually file the issue. Required in non-interactive mode.',
)
+ .option('-f, --overwrite', 'Overwrite existing files without prompting')
.action(async (component, options) => {
const coreDir = findCoreDir(process.cwd());
const json = program.opts().json || false;
@@ -115,7 +117,59 @@ export function registerSwizzle(program) {
process.exit(1);
}
- const outputDir = path.resolve(process.cwd(), options.output, dirName);
+ // Path-safety: --output must resolve inside cwd. Reject absolute
+ // paths and `..` traversal up front, before any directory is created.
+ let outputBase;
+ try {
+ outputBase = assertWithin(options.output, process.cwd(), {
+ label: 'output directory',
+ });
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ if (json) return jsonError(err.message);
+ console.error(`Error: ${err.message}`);
+ process.exit(1);
+ }
+ throw err;
+ }
+ const outputDir = path.join(outputBase, dirName);
+
+ // Pre-flight overwrite check: collect files we'd write and detect
+ // collisions before mkdir/writeFile so we never half-clobber.
+ const sourceFiles = fs.readdirSync(componentDir).filter(file => {
+ if (file.includes('.test.') || file === 'README.md') return false;
+ const stat = fs.statSync(path.join(componentDir, file));
+ return stat.isFile();
+ });
+
+ const existingFiles = sourceFiles.filter(f =>
+ fs.existsSync(path.join(outputDir, f)),
+ );
+
+ if (existingFiles.length > 0 && !options.overwrite) {
+ const relOutputForMsg = path.relative(process.cwd(), outputDir) || '.';
+ if (json || isNonInteractive({json})) {
+ const msg =
+ `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +
+ `Re-run with --overwrite (or -f) to replace them.`;
+ if (json) return jsonError(msg);
+ console.error(`Error: ${msg}`);
+ process.exit(1);
+ }
+ const confirmed = isCancel(
+ await p.confirm({
+ message:
+ `Overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/? ` +
+ `(${existingFiles.slice(0, 3).join(', ')}${existingFiles.length > 3 ? ', …' : ''})`,
+ initialValue: false,
+ }),
+ );
+ if (!confirmed) {
+ humanLog('Aborted. Re-run with --overwrite to replace files.');
+ return;
+ }
+ }
+
fs.mkdirSync(outputDir, {recursive: true});
// Copy all non-test, non-README files
diff --git a/packages/cli/src/commands/swizzle.path-safety.test.mjs b/packages/cli/src/commands/swizzle.path-safety.test.mjs
new file mode 100644
index 0000000000..3020e15c43
--- /dev/null
+++ b/packages/cli/src/commands/swizzle.path-safety.test.mjs
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Path-traversal regression tests for `xds swizzle --output`.
+ *
+ * Spawns the CLI bin with a fake monorepo as cwd and asserts that
+ * `--output ../escaped` is rejected with a clear error AND that no
+ * file is created outside the project root.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CLI_BIN = path.resolve(__dirname, '../../bin/xds.mjs');
+
+// Build a minimal fake monorepo: <root>/project/ contains a
+// node_modules/@xds/core/src/Button so findCoreDir succeeds, and
+// <root>/outside/ is the would-be traversal target.
+function buildFakeRepo(tmpDir) {
+ const project = path.join(tmpDir, 'project');
+ const outside = path.join(tmpDir, 'outside');
+ const core = path.join(project, 'node_modules', '@xds', 'core');
+ const buttonDir = path.join(core, 'src', 'Button');
+ fs.mkdirSync(buttonDir, {recursive: true});
+ fs.mkdirSync(outside, {recursive: true});
+ fs.writeFileSync(
+ path.join(buttonDir, 'Button.tsx'),
+ `// fake source\nexport const Button = () => null;\n`,
+ );
+ // Make findCoreDir's heuristic (or its node_modules branch) succeed by
+ // also creating packages/core symlink-style structure if needed:
+ fs.writeFileSync(path.join(core, 'package.json'), '{"name":"@xds/core"}');
+ return {project, outside};
+}
+
+function runCli(args, cwd) {
+ try {
+ const out = execFileSync('node', [CLI_BIN, ...args], {
+ cwd,
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: {...process.env, FORCE_COLOR: '0'},
+ });
+ return {code: 0, stdout: out, stderr: ''};
+ } catch (e) {
+ return {
+ code: e.status ?? 1,
+ stdout: e.stdout?.toString() ?? '',
+ stderr: e.stderr?.toString() ?? '',
+ };
+ }
+}
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-swizzle-paths-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('swizzle path safety', () => {
+ it('rejects --output with ../ traversal and writes no file outside root', () => {
+ const {project, outside} = buildFakeRepo(tmpDir);
+
+ const result = runCli(
+ ['swizzle', 'Button', '--output', '../outside-project', '--no-report'],
+ project,
+ );
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr + result.stdout).toMatch(/traversal|outside the project root/i);
+
+ // Hard check: nothing was written outside the project.
+ expect(fs.readdirSync(outside)).toEqual([]);
+ const escaped = path.join(tmpDir, 'outside-project');
+ expect(fs.existsSync(escaped)).toBe(false);
+ });
+
+ it('rejects --output with absolute path', () => {
+ const {project} = buildFakeRepo(tmpDir);
+ const absTarget = path.join(tmpDir, 'absolute-target');
+
+ const result = runCli(
+ ['swizzle', 'Button', '--output', absTarget, '--no-report'],
+ project,
+ );
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr + result.stdout).toMatch(/absolute paths are not allowed/i);
+ expect(fs.existsSync(absTarget)).toBe(false);
+ });
+
+ it('requires --overwrite in non-interactive mode when files already exist', () => {
+ const {project} = buildFakeRepo(tmpDir);
+ const outDir = path.join(project, 'components', 'xds', 'Button');
+ fs.mkdirSync(outDir, {recursive: true});
+ const existingPath = path.join(outDir, 'Button.tsx');
+ fs.writeFileSync(existingPath, '// my customizations\n');
+
+ // Use --json to force non-interactive mode.
+ const result = runCli(
+ ['--json', 'swizzle', 'Button', '--no-report'],
+ project,
+ );
+
+ expect(result.code).not.toBe(0);
+ expect(result.stderr + result.stdout).toMatch(/overwrite/i);
+ // Existing file unchanged
+ expect(fs.readFileSync(existingPath, 'utf-8')).toBe('// my customizations\n');
+ });
+});
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index e71e5be344..2d43109ec9 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -5,12 +5,23 @@
*/
import * as path from 'node:path';
+import * as fs from 'node:fs';
+import * as p from '@clack/prompts';
import {CLI_ROOT} from '../utils/paths.mjs';
+import {isNonInteractive} from '../utils/path-safety.mjs';
import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
import {template as templateApi, getTemplateById} from '../api/template.mjs';
export {discoverTemplates, listTemplates, getTemplateById} from '../api/template.mjs';
+function isCancel(value) {
+ if (p.isCancel(value)) {
+ p.cancel('Cancelled.');
+ process.exit(0);
+ }
+ return value;
+}
+
export function registerTemplate(program) {
const templateCmd = program
.command('template [name] [path]')
@@ -18,9 +29,43 @@ export function registerTemplate(program) {
.option('--list', 'List available templates')
.option('--type <type>', 'Filter by template type: page or block')
.option('--skeleton', 'Show layout skeleton with spatial annotations (padding, gap, nesting)')
+ .option('-f, --overwrite', 'Overwrite existing files without prompting')
.action(async (name, targetPath, options) => {
const json = program.opts().json || false;
+ // Pre-flight overwrite check (only when we'd actually copy a file).
+ // The API resolves the destination; we need to mirror its logic
+ // narrowly enough to detect collisions before invoking it.
+ if (
+ name &&
+ targetPath &&
+ !options.list &&
+ !options.skeleton
+ ) {
+ const collision = await detectTemplateCollision(name, targetPath);
+ if (collision && !options.overwrite) {
+ const rel = path.relative(process.cwd(), collision) || collision;
+ if (json || isNonInteractive({json})) {
+ const msg =
+ `Refusing to overwrite existing file ${rel}. ` +
+ `Re-run with --overwrite (or -f) to replace it.`;
+ if (json) return jsonError(msg);
+ console.error(`Error: ${msg}`);
+ process.exit(1);
+ }
+ const confirmed = isCancel(
+ await p.confirm({
+ message: `Overwrite existing file ${rel}?`,
+ initialValue: false,
+ }),
+ );
+ if (!confirmed) {
+ humanLog('Aborted. Re-run with --overwrite to replace the file.');
+ return;
+ }
+ }
+ }
+
let result;
try {
result = await templateApi(name, {
@@ -110,3 +155,45 @@ export function registerTemplate(program) {
humanLog(result.data.source);
});
}
+
+/**
+ * Mirror the destination-resolution logic in api/template.mjs so we can
+ * detect a clobber before invoking the API.
+ *
+ * Returns the absolute destination file path if it already exists, or
+ * `null` otherwise (template missing, no collision, or list/skeleton mode).
+ *
+ * Path-safety enforcement happens inside the API; here we only need
+ * enough precision to check existence — a false negative just means the
+ * API will catch the issue and abort.
+ */
+async function detectTemplateCollision(name, targetPath) {
+ const {discoverTemplates} = await import('../api/template.mjs');
+ let templates;
+ try {
+ templates = await discoverTemplates();
+ } catch {
+ return null;
+ }
+ const match = templates.find(t => t.dirName === name);
+ if (!match) return null;
+
+ // Resolve target as the API will. We can't call assertWithin here
+ // because the API does it itself; we just need to know "is there a
+ // file at the destination?".
+ const resolved = path.resolve(process.cwd(), targetPath);
+
+ // File-arg branch: targetPath looks like `./foo.tsx`.
+ const {isFilePathArg} = await import('../utils/path-safety.mjs');
+ let dest;
+ if (isFilePathArg(targetPath)) {
+ dest = resolved;
+ } else {
+ const fileName = match.type === 'block'
+ ? path.basename(match.filePath)
+ : 'page.tsx';
+ dest = path.join(resolved, fileName);
+ }
+
+ return fs.existsSync(dest) ? dest : null;
+}
diff --git a/packages/cli/src/commands/template.path-safety.test.mjs b/packages/cli/src/commands/template.path-safety.test.mjs
new file mode 100644
index 0000000000..3daf3d3723
--- /dev/null
+++ b/packages/cli/src/commands/template.path-safety.test.mjs
@@ -0,0 +1,82 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Path-traversal regression tests for `xds template <name> <path>`.
+ *
+ * Drives the template API directly (it owns destination resolution +
+ * path-safety enforcement). Spawning the CLI bin is unnecessary because
+ * `template()` resolves and writes to disk itself.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+
+let tmpDir;
+let templateApi;
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-template-paths-'));
+ templateApi = (await import('../api/template.mjs')).template;
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ vi.restoreAllMocks();
+});
+
+describe('template path safety', () => {
+ it('rejects targetPath with ../ traversal and writes no file outside cwd', async () => {
+ const cwd = path.join(tmpDir, 'project');
+ const outside = path.join(tmpDir, 'outside');
+ fs.mkdirSync(cwd, {recursive: true});
+ fs.mkdirSync(outside, {recursive: true});
+
+ await expect(
+ templateApi('blank', {targetPath: '../outside/leaked', cwd}),
+ ).rejects.toThrow(/traversal|outside the project root/i);
+
+ // Nothing escaped.
+ expect(fs.readdirSync(outside)).toEqual([]);
+ });
+
+ it('rejects absolute targetPath', async () => {
+ const cwd = path.join(tmpDir, 'project');
+ fs.mkdirSync(cwd, {recursive: true});
+ const absTarget = path.join(tmpDir, 'absolute-out');
+
+ await expect(
+ templateApi('blank', {targetPath: absTarget, cwd}),
+ ).rejects.toThrow(/absolute paths are not allowed/i);
+
+ expect(fs.existsSync(absTarget)).toBe(false);
+ });
+
+ it('treats targetPath with .tsx extension as a file, not a directory', async () => {
+ const cwd = path.join(tmpDir, 'project');
+ fs.mkdirSync(cwd, {recursive: true});
+
+ // Use a real template name from the discovered set.
+ const {discoverTemplates} = await import('../api/template.mjs');
+ const all = await discoverTemplates();
+ const page = all.find(t => t.type === 'page');
+ if (!page) {
+ // No page templates packaged in this checkout — skip without failing the suite.
+ return;
+ }
+
+ const result = await templateApi(page.dirName, {
+ targetPath: './foo.tsx',
+ cwd,
+ });
+
+ // The file MUST be at ./foo.tsx, not ./foo.tsx/page.tsx.
+ expect(result.type).toBe('template.copy');
+ expect(result.data.fileName).toBe('foo.tsx');
+
+ expect(fs.existsSync(path.join(cwd, 'foo.tsx'))).toBe(true);
+ expect(fs.statSync(path.join(cwd, 'foo.tsx')).isFile()).toBe(true);
+ // The bad-old behavior would have left foo.tsx as a directory.
+ expect(fs.statSync(path.join(cwd, 'foo.tsx')).isDirectory()).toBe(false);
+ });
+});
diff --git a/packages/cli/src/utils/path-safety.mjs b/packages/cli/src/utils/path-safety.mjs
new file mode 100644
index 0000000000..f12842f49e
--- /dev/null
+++ b/packages/cli/src/utils/path-safety.mjs
@@ -0,0 +1,185 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Path safety helpers.
+ *
+ * Centralizes path-traversal defenses, name sanitization, and
+ * file-vs-directory detection used by CLI commands that write to
+ * user-controlled output paths.
+ *
+ * Commands should use these helpers instead of constructing paths
+ * directly with `path.resolve` / `path.join`, which silently re-root
+ * absolute paths or allow traversal via `..`.
+ */
+
+import * as path from 'node:path';
+
+/**
+ * Error thrown by path-safety guards. Carries a stable `code`
+ * so callers (CLI handlers) can render a friendly message and
+ * exit cleanly without leaking stack traces.
+ */
+export class PathSafetyError extends Error {
+ /**
+ * @param {string} message
+ * @param {string} code
+ */
+ constructor(message, code = 'PATH_UNSAFE') {
+ super(message);
+ this.name = 'PathSafetyError';
+ this.code = code;
+ }
+}
+
+/**
+ * Resolve `targetPath` (relative to `rootDir`) and assert that the
+ * result stays inside `rootDir`. Rejects:
+ *
+ * - Absolute paths (e.g. `/tmp/x`) — re-rooted by `path.join` is silent;
+ * better to fail loudly. Pass `{allowAbsolute: true}` to opt in.
+ * - Paths that escape via `..` segments.
+ *
+ * Returns the resolved absolute path on success.
+ *
+ * @param {string} targetPath - User-provided path (relative or absolute).
+ * @param {string} rootDir - Absolute path of the directory to constrain into.
+ * @param {object} [options]
+ * @param {boolean} [options.allowAbsolute=false] - If true, absolute paths
+ * are accepted *as long as* they resolve inside `rootDir`.
+ * @param {string} [options.label='path'] - Human-readable name of the arg
+ * being checked (used in error messages, e.g. 'output directory').
+ * @returns {string} Absolute resolved path inside `rootDir`.
+ * @throws {PathSafetyError}
+ */
+export function assertWithin(targetPath, rootDir, options = {}) {
+ const {allowAbsolute = false, label = 'path'} = options;
+
+ if (typeof targetPath !== 'string' || targetPath.length === 0) {
+ throw new PathSafetyError(`Invalid ${label}: must be a non-empty string`, 'PATH_INVALID');
+ }
+
+ if (path.isAbsolute(targetPath) && !allowAbsolute) {
+ throw new PathSafetyError(
+ `Invalid ${label} "${targetPath}": absolute paths are not allowed. ` +
+ `Use a path relative to the project root.`,
+ 'PATH_ABSOLUTE',
+ );
+ }
+
+ const absRoot = path.resolve(rootDir);
+ const resolved = path.resolve(absRoot, targetPath);
+
+ // Canonicalize for the "is inside" comparison. Use normalized paths
+ // with a trailing separator so /root/foo doesn't match /rootbar.
+ const rootWithSep = absRoot.endsWith(path.sep) ? absRoot : absRoot + path.sep;
+ if (resolved !== absRoot && !resolved.startsWith(rootWithSep)) {
+ throw new PathSafetyError(
+ `Invalid ${label} "${targetPath}": resolves outside the project root ` +
+ `(${absRoot}). Path traversal is not allowed.`,
+ 'PATH_TRAVERSAL',
+ );
+ }
+
+ return resolved;
+}
+
+/**
+ * Validate a "name" argument (e.g. theme name, component name) that will
+ * be embedded in a generated filename. Rejects names containing path
+ * separators, parent-segment markers, NUL bytes, leading dots, or any
+ * character outside a conservative allow-list.
+ *
+ * Use this at the entry point of any command whose name arg flows into
+ * `path.join(outDir, name + '.css')` etc.
+ *
+ * @param {string} name
+ * @param {object} [options]
+ * @param {string} [options.label='name']
+ * @returns {string} The name (unchanged on success).
+ * @throws {PathSafetyError}
+ */
+export function sanitizeName(name, options = {}) {
+ const {label = 'name'} = options;
+
+ if (typeof name !== 'string' || name.length === 0) {
+ throw new PathSafetyError(`Invalid ${label}: must be a non-empty string`, 'NAME_INVALID');
+ }
+
+ if (name.includes('\0')) {
+ throw new PathSafetyError(`Invalid ${label}: contains a NUL byte`, 'NAME_INVALID');
+ }
+
+ // Reject any path-segment characters. We don't try to rewrite — silent
+ // sanitization hides intent. Fail loudly with a clear hint instead.
+ if (/[\\/]/.test(name)) {
+ throw new PathSafetyError(
+ `Invalid ${label} "${name}": must not contain path separators ('/' or '\\\\').`,
+ 'NAME_HAS_SEPARATOR',
+ );
+ }
+
+ if (name === '.' || name === '..' || name.startsWith('..')) {
+ throw new PathSafetyError(
+ `Invalid ${label} "${name}": must not be '.' or start with '..'.`,
+ 'NAME_TRAVERSAL',
+ );
+ }
+
+ // Conservative allow-list: alphanumerics, dot, underscore, hyphen.
+ // Theme/component names in this codebase already conform to this.
+ if (!/^[A-Za-z0-9._-]+$/.test(name)) {
+ throw new PathSafetyError(
+ `Invalid ${label} "${name}": only letters, digits, '.', '_', and '-' are allowed.`,
+ 'NAME_BAD_CHARS',
+ );
+ }
+
+ return name;
+}
+
+const FILE_EXTENSIONS = new Set([
+ '.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs',
+ '.css', '.scss', '.json', '.md', '.html',
+]);
+
+/**
+ * Heuristic: does this CLI argument look like a file path (vs a directory)?
+ *
+ * Used by `xds template <name> <path>` so that
+ * `xds template blank ./foo.tsx`
+ * writes to `./foo.tsx` as a file, not `./foo.tsx/page.tsx` (the old bug).
+ *
+ * Returns true when the basename has a known source/asset extension.
+ * Conservative on purpose — unknown extensions still fall through to the
+ * directory branch, matching pre-existing behavior for things like
+ * `./out` or `./src/pages`.
+ *
+ * @param {string} pathArg
+ * @returns {boolean}
+ */
+export function isFilePathArg(pathArg) {
+ if (typeof pathArg !== 'string' || pathArg.length === 0) return false;
+ // Trailing slash → explicit directory.
+ if (/[\\/]$/.test(pathArg)) return false;
+ const base = path.basename(pathArg);
+ const ext = path.extname(base).toLowerCase();
+ return ext.length > 0 && FILE_EXTENSIONS.has(ext);
+}
+
+/**
+ * True when the process is running non-interactively (no TTY) or when the
+ * caller has signaled JSON / scripted use. Commands consult this before
+ * prompting for confirmation; in scripted mode they require an explicit
+ * `--overwrite` flag instead.
+ *
+ * @param {object} [options]
+ * @param {boolean} [options.json] - Caller's --json flag.
+ * @returns {boolean}
+ */
+export function isNonInteractive({json = false} = {}) {
+ if (json) return true;
+ // stdin not a TTY means piped input or scripted execution.
+ if (process.stdin && process.stdin.isTTY === false) return true;
+ if (process.stdout && process.stdout.isTTY === false) return true;
+ return false;
+}
diff --git a/packages/cli/src/utils/path-safety.test.mjs b/packages/cli/src/utils/path-safety.test.mjs
new file mode 100644
index 0000000000..de87903cd5
--- /dev/null
+++ b/packages/cli/src/utils/path-safety.test.mjs
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {
+ assertWithin,
+ sanitizeName,
+ isFilePathArg,
+ PathSafetyError,
+} from './path-safety.mjs';
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-path-safety-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('assertWithin', () => {
+ it('accepts a relative path that stays inside root', () => {
+ const result = assertWithin('subdir/file.txt', tmpDir);
+ expect(result).toBe(path.join(tmpDir, 'subdir', 'file.txt'));
+ });
+
+ it('accepts the root itself', () => {
+ expect(assertWithin('.', tmpDir)).toBe(path.resolve(tmpDir));
+ });
+
+ it('rejects ../ traversal', () => {
+ expect(() => assertWithin('../escaped', tmpDir)).toThrow(PathSafetyError);
+ expect(() => assertWithin('../escaped', tmpDir)).toThrow(/traversal|outside/i);
+ });
+
+ it('rejects deep ../../ traversal', () => {
+ expect(() => assertWithin('a/b/../../../c', tmpDir)).toThrow(PathSafetyError);
+ });
+
+ it('rejects absolute paths by default', () => {
+ expect(() => assertWithin('/tmp/elsewhere', tmpDir)).toThrow(/absolute paths are not allowed/i);
+ });
+
+ it('accepts absolute paths inside root when allowAbsolute', () => {
+ const inside = path.join(tmpDir, 'x.txt');
+ expect(assertWithin(inside, tmpDir, {allowAbsolute: true})).toBe(inside);
+ });
+
+ it('rejects absolute paths outside root even when allowAbsolute', () => {
+ expect(() =>
+ assertWithin('/etc/passwd', tmpDir, {allowAbsolute: true}),
+ ).toThrow(PathSafetyError);
+ });
+
+ it('does not match sibling-prefix paths', () => {
+ // /tmp/foo should not be accepted as inside /tmp/foobar
+ const root = path.join(tmpDir, 'foo');
+ fs.mkdirSync(root);
+ expect(() => assertWithin('../foobar/x', root)).toThrow(PathSafetyError);
+ });
+
+ it('rejects empty / non-string input', () => {
+ expect(() => assertWithin('', tmpDir)).toThrow(/non-empty/i);
+ expect(() => assertWithin(null, tmpDir)).toThrow();
+ });
+});
+
+describe('sanitizeName', () => {
+ it('accepts simple names', () => {
+ expect(sanitizeName('button')).toBe('button');
+ expect(sanitizeName('Default-Theme_2')).toBe('Default-Theme_2');
+ expect(sanitizeName('theme.v1')).toBe('theme.v1');
+ });
+
+ it('rejects names with /', () => {
+ expect(() => sanitizeName('foo/bar')).toThrow(PathSafetyError);
+ expect(() => sanitizeName('foo/bar')).toThrow(/path separator/i);
+ });
+
+ it('rejects names with \\', () => {
+ expect(() => sanitizeName('foo\\bar')).toThrow(PathSafetyError);
+ });
+
+ it('rejects ..', () => {
+ expect(() => sanitizeName('..')).toThrow(PathSafetyError);
+ expect(() => sanitizeName('../escaped')).toThrow(PathSafetyError);
+ });
+
+ it('rejects . and leading dots that look traversal-y', () => {
+ expect(() => sanitizeName('.')).toThrow(PathSafetyError);
+ });
+
+ it('rejects NUL bytes', () => {
+ expect(() => sanitizeName('foo\0bar')).toThrow(PathSafetyError);
+ });
+
+ it('rejects empty/non-string', () => {
+ expect(() => sanitizeName('')).toThrow(PathSafetyError);
+ expect(() => sanitizeName(null)).toThrow(PathSafetyError);
+ });
+
+ it('rejects characters outside the allow-list', () => {
+ expect(() => sanitizeName('foo bar')).toThrow(PathSafetyError);
+ expect(() => sanitizeName('foo$bar')).toThrow(PathSafetyError);
+ });
+});
+
+describe('isFilePathArg', () => {
+ it('returns true for known source extensions', () => {
+ expect(isFilePathArg('foo.tsx')).toBe(true);
+ expect(isFilePathArg('./foo.tsx')).toBe(true);
+ expect(isFilePathArg('./src/page.jsx')).toBe(true);
+ expect(isFilePathArg('out.js')).toBe(true);
+ expect(isFilePathArg('out.mjs')).toBe(true);
+ expect(isFilePathArg('out.css')).toBe(true);
+ });
+
+ it('returns false for plain directory names', () => {
+ expect(isFilePathArg('out')).toBe(false);
+ expect(isFilePathArg('./components/xds')).toBe(false);
+ expect(isFilePathArg('src/pages')).toBe(false);
+ });
+
+ it('returns false for trailing slash even with extension-like name', () => {
+ expect(isFilePathArg('foo.tsx/')).toBe(false);
+ });
+
+ it('returns false for unknown extensions', () => {
+ expect(isFilePathArg('archive.zip')).toBe(false);
+ });
+
+ it('returns false for empty/invalid', () => {
+ expect(isFilePathArg('')).toBe(false);
+ expect(isFilePathArg(null)).toBe(false);
+ });
+});