An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): confine user paths, close DoS vectors, and repair broken paths (#4637)
Joeyddda8bf9886a
diff --git a/.changeset/cli-path-confinement-dos.md b/.changeset/cli-path-confinement-dos.mdnew file mode 100644index 0000000000..9e517b0cf7--- /dev/null+++ b/.changeset/cli-path-confinement-dos.md@@ -0,0 +1,11 @@+---+'@astryxdesign/cli': patch+---++[fix] cli — confine user-controlled file paths, close DoS vectors, and repair paths broken by the authoring reorg (#4637)++- `theme build --out`/`<file>`, the `validate-integration` manifest roots (`components`/`templates`/`codemods`), and `layout --file` are now confined with `assertWithin`. An escaping integration root reports a validation issue instead of importing and executing files outside the package; `layout --file` is also size-capped (5 MB) and rejects non-files, so a stream like `/dev/zero` can't exhaust memory.+- Fuzzy-match (Levenshtein), the layout value parser, and the layout expander gained bounds — a very long search query, a deeply nested attribute value, and a huge repeat count (`Box*999999999`) can no longer spin the CPU, blow the stack, or exhaust the heap.+- Docs topic lookup uses a null-prototype map so `__proto__`/`constructor` as a topic name can't bypass the unknown-topic guard. The shipped getting-started docs and the sandbox registry generator point at the current CLI source path again (both broke in the authoring reorg).++@josephfarinadiff --git a/apps/sandbox/scripts/generate-cli-registry.mjs b/apps/sandbox/scripts/generate-cli-registry.mjsindex cfa17b8ddc..2f479bf728 100644--- a/apps/sandbox/scripts/generate-cli-registry.mjs+++ b/apps/sandbox/scripts/generate-cli-registry.mjs@@ -15,7 +15,7 @@ import {fileURLToPath} from 'node:url';const __dirname = path.dirname(fileURLToPath(import.meta.url));const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');-const CLI_SRC = path.join(REPO_ROOT, 'packages', 'cli', 'src');+const CLI_SRC = path.join(REPO_ROOT, 'packages', 'cli', 'clients', 'cli');const OUT_DIR = path.resolve(__dirname, '..', 'src', 'generated');const OUT_FILE = path.join(OUT_DIR, 'cliRegistry.ts');diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjsindex 5ddb0cb7c4..d2e3540888 100644--- a/packages/cli/api/docs/_adapter.mjs+++ b/packages/cli/api/docs/_adapter.mjs@@ -25,7 +25,7 @@ const DOCS_DIR = path.join(CLI_ROOT, 'assets', 'docs');*/export function discoverTopics() {/** @type {Record<string, string>} */- const topics = {};+ const topics = Object.create(null);if (!fs.existsSync(DOCS_DIR)) return topics;for (const file of fs.readdirSync(DOCS_DIR)) {const match = file.match(/^([\w-]+)\.doc\.mjs$/);diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex abb1b588b8..05b5fb63d2 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -24,6 +24,7 @@import * as fs from 'node:fs';import * as path from 'node:path';+import {assertWithin} from '../../foundation/fs/path-safety.mjs';import {findManifestPaths,loadManifestObject,@@ -261,8 +262,20 @@ async function validateAtPackageDir(packageDir, identity) {}/** @param {string | null | undefined} value */- const resolveRoot = value =>- value == null ? undefined : path.resolve(packageDir, value);+ const resolveRoot = (value, kind = 'contribution root') => {+ if (value == null) return undefined;+ try {+ return assertWithin(value, packageDir, {label: kind});+ } catch {+ // If the root escapes the package, report an issue instead of crashing.+ result.issues.push({+ code: 'root_outside_package',+ severity: 'error',+ message: `The ${kind} "${value}" resolves outside the integration package directory. Contribution roots must stay within the package.`,+ });+ return undefined;+ }+ };const loaded = {name: identity.name,diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex 53b715b6a9..d2c5ff25e4 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -33,6 +33,7 @@ import {createJiti} from 'jiti';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';import {+ assertWithin,sanitizeName,PathSafetyError,} from '../../../foundation/fs/path-safety.mjs';@@ -1130,9 +1131,17 @@ export async function themeBuild(// Derive the default CSS name from the theme name so .css/.js/.d.ts// share one scheme; an explicit --out still wins.const baseName = themeDef.name;- const outPath = options.out- ? path.resolve(cwd, options.out)- : path.join(path.dirname(filePath), `${baseName}.css`);+ let outPath;+ if (options.out) {+ outPath = path.resolve(cwd, options.out);+ // Guard: relative paths must not escape cwd via `../`. Absolute paths are+ // trusted (the user explicitly controls where output goes, like gcc -o).+ if (!path.isAbsolute(options.out)) {+ assertWithin(options.out, cwd, {label: 'output path'});+ }+ } else {+ outPath = path.join(path.dirname(filePath), `${baseName}.css`);+ }const displayTheme = resolvedTheme || themeDef;const tokenCount = displayTheme.tokensdiff --git a/packages/cli/assets/docs/getting-started.doc.mjs b/packages/cli/assets/docs/getting-started.doc.mjsindex cd49239187..a2c7277ec7 100644--- a/packages/cli/assets/docs/getting-started.doc.mjs+++ b/packages/cli/assets/docs/getting-started.doc.mjs@@ -165,7 +165,7 @@ pnpm dev`,lang: 'json',label: 'package.json',code: `"scripts": {- "astryx": "node node_modules/@astryxdesign/cli/bin/astryx.mjs"+ "astryx": "node node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs"}`,},{diff --git a/packages/cli/assets/docs/working-with-ai.doc.mjs b/packages/cli/assets/docs/working-with-ai.doc.mjsindex faab6800d3..1c07146573 100644--- a/packages/cli/assets/docs/working-with-ai.doc.mjs+++ b/packages/cli/assets/docs/working-with-ai.doc.mjs@@ -125,7 +125,7 @@ If you don't know all three, run \`npx @astryxdesign/cli init --features agents\lang: 'json',label: 'package.json',code: `"scripts": {- "astryx": "node node_modules/@astryxdesign/cli/bin/astryx.mjs"+ "astryx": "node node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs"}`,},{diff --git a/packages/cli/clients/cli/commands/layout.mjs b/packages/cli/clients/cli/commands/layout.mjsindex 30735ce6e8..df49a4c138 100644--- a/packages/cli/clients/cli/commands/layout.mjs+++ b/packages/cli/clients/cli/commands/layout.mjs@@ -13,6 +13,7 @@*/import * as fs from 'node:fs';+import * as path from 'node:path';import {jsonOut, humanLog} from '../../../foundation/response/json.mjs';import {cliError} from '../lib/cli-error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';@@ -52,8 +53,26 @@ import {layoutExpand, layoutCheck, layoutGrammar} from '../../../api/layout/layo*/async function readExpression(expr, options = {}) {if (options.file) {+ // Validate the file exists + is a regular file + is reasonably sized.+ // We intentionally do NOT confine the read path (the user running the CLI+ // controls --file; this is a read, not a write). The size cap prevents OOM+ // from infinite streams like /dev/zero.+ const filePath = path.resolve(process.cwd(), options.file);+ const stat = fs.statSync(filePath, {throwIfNoEntry: false});+ if (!stat || !stat.isFile()) {+ cliError(`File not found: ${options.file}`, {+ code: ERROR_CODES.ERR_FILE_NOT_FOUND,+ });+ }+ const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB+ if (stat.size > MAX_FILE_SIZE) {+ cliError(+ `File "${options.file}" is too large (${(stat.size / 1024 / 1024).toFixed(1)} MB, max 5 MB)`,+ {code: ERROR_CODES.ERR_FILE_NOT_FOUND},+ );+ }try {- return fs.readFileSync(options.file, 'utf-8');+ return fs.readFileSync(filePath, 'utf-8');} catch (e) {const errno = /** @type {NodeJS.ErrnoException} */ (e);if (errno && errno.code === 'ENOENT') {diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex e0b3bba9e8..2c897e4ce8 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -12,6 +12,7 @@import * as fs from 'node:fs';import * as path from 'node:path';+import {assertWithin} from '../fs/path-safety.mjs';import {parseIntegration} from '../../authoring/integration/parse.mjs';import {loadModuleWithParser, findPresentFiles} from '../fs/module-loader.mjs';@@ -170,8 +171,15 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {}/** @param {string | null | undefined} value */- const resolveRoot = value =>- value == null ? undefined : path.resolve(packageDir, value);+ const resolveRoot = value => {+ if (value == null) return undefined;+ try {+ return assertWithin(value, packageDir, {label: 'contribution root'});+ } catch {+ // Root escapes the package — skip silently (logged by validate-integration).+ return undefined;+ }+ };integrations.push({name: pkg.name ?? spec,diff --git a/packages/cli/foundation/text/levenshtein.mjs b/packages/cli/foundation/text/levenshtein.mjsindex 16635eeb77..9f373a3058 100644--- a/packages/cli/foundation/text/levenshtein.mjs+++ b/packages/cli/foundation/text/levenshtein.mjs@@ -20,6 +20,12 @@*/export function levenshteinDistance(a, b) {const m = a.length, n = b.length;+ // Early exit: the distance is always ≥ |m − n|, so once the length gap+ // exceeds the loosest fuzzy-match threshold any caller uses (the hook+ // suggester keeps distance ≤ 5) the pair can never match — skip the O(m·n)+ // DP entirely. Closes the DoS surface where a long query (>3k chars) caused+ // multi-second CPU spins (8,860 calls × O(n²) per search).+ if (Math.abs(m - n) > 5) return 999;/** @type {number[][]} */const dp = Array.from({length: m + 1}, () => Array(n + 1).fill(0));for (let i = 0; i <= m; i++) dp[i][0] = i;diff --git a/packages/cli/foundation/text/levenshtein.test.mjs b/packages/cli/foundation/text/levenshtein.test.mjsindex f2d493cbdc..7d4a915fd0 100644--- a/packages/cli/foundation/text/levenshtein.test.mjs+++ b/packages/cli/foundation/text/levenshtein.test.mjs@@ -37,4 +37,17 @@ describe('levenshteinDistance', () => {it('handles unicode', () => {expect(d('café', 'cafe')).toBe(1);});++ it('short-circuits pairs whose length gap exceeds every caller threshold', () => {+ // The DoS guard bails out with a large sentinel once |m − n| > 5, so a+ // pathological long query never runs the O(m·n) DP.+ expect(d('a', 'a'.repeat(10_000))).toBe(999);+ });++ it('still computes the true distance up to a length gap of 5', () => {+ // The gap must stay ≥ the loosest caller threshold (hook suggester = 5),+ // so a real 5-away typo isn't dropped by the short-circuit.+ expect(d('use', 'useMedia')).toBe(5); // 5 pure insertions+ });});+diff --git a/packages/cli/foundation/xle/expand.mjs b/packages/cli/foundation/xle/expand.mjsindex 9bff7b847d..b51d9d5999 100644--- a/packages/cli/foundation/xle/expand.mjs+++ b/packages/cli/foundation/xle/expand.mjs@@ -20,6 +20,7 @@ import {PAYLOAD_PROPS} from './validate.mjs';import {mergeImports, renderImport, prepareSpliceModule} from './splice.mjs';const INDENT = ' ';+const MAX_REPEAT = 10000;/** @param {string | null | undefined} text */function slugify(text) {@@ -312,7 +313,7 @@ class Emitter {const lines = [];for (const item of items) {if (item.kind === 'group') {- const count = item.repeat || 1;+ const count = Math.min(item.repeat || 1, MAX_REPEAT);for (let i = 1; i <= count; i++) {for (const child of item.children) {const clone = count > 1 ? cloneItem(child) : child;@@ -322,7 +323,7 @@ class Emitter {}continue;}- const count = item.repeat || 1;+ const count = Math.min(item.repeat || 1, MAX_REPEAT);for (let i = 1; i <= count; i++) {const clone = count > 1 ? /** @type {import('./xle-ast').XLENode} */ (cloneItem(item)) : item;if (count > 1) {diff --git a/packages/cli/foundation/xle/parse.mjs b/packages/cli/foundation/xle/parse.mjsindex 68c84aa3ed..98504c07ea 100644--- a/packages/cli/foundation/xle/parse.mjs+++ b/packages/cli/foundation/xle/parse.mjs@@ -131,7 +131,20 @@ function tokenize(str, line, startCol) {* @param {string} raw* @returns {import('./xle-ast').XLEValue}*/-export function parseValue(raw) {+const MAX_VALUE_DEPTH = 64;++/**+ * @param {string} raw+ * @param {number} [_depth]+ * @returns {import('./xle-ast').XLEValue}+ */+export function parseValue(raw, _depth = 0) {+ if (_depth > MAX_VALUE_DEPTH) {+ throw new XLEParseError(+ `Attribute value nested too deeply (limit ${MAX_VALUE_DEPTH})`,+ 0, 0,+ );+ }const s = raw.trim();if (/^(['"]).*\1$/.test(s)) return s.slice(1, -1);if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);@@ -144,14 +157,14 @@ export function parseValue(raw) {for (const part of splitTop(s.slice(1, -1), ',')) {const idx = part.indexOf(':');if (idx === -1) obj[part.trim()] = true;- else obj[part.slice(0, idx).trim()] = parseValue(part.slice(idx + 1));+ else obj[part.slice(0, idx).trim()] = parseValue(part.slice(idx + 1), _depth + 1);}return obj;}if (s.startsWith('[') && s.endsWith(']')) {- return splitTop(s.slice(1, -1), ',').map(parseValue);+ return splitTop(s.slice(1, -1), ',').map(v => parseValue(v, _depth + 1));}- if (s.includes(',')) return splitTop(s, ',').map(parseValue);+ if (s.includes(',')) return splitTop(s, ',').map(v => parseValue(v, _depth + 1));return s; // bare ident — enum string}