An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): theme build writes only inside the working directory (#7496)
Joey405bb94ca7c4
diff --git a/.changeset/theme-build-confine-outputs.md b/.changeset/theme-build-confine-outputs.mdnew file mode 100644index 0000000000..adaf4cdfaa--- /dev/null+++ b/.changeset/theme-build-confine-outputs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx theme build` and `themeBuild()` now write only inside the working directory (`cwd` for the API), as `architecture:cli-surface/INV10` requires; under `architecture:cli-surface/INV10a` the refusal is a compatible fix. Each of these now fails with `ERR_PATH_TRAVERSAL` before anything is written, and `--check` refuses the same paths: an absolute `--out` path outside the working directory, a theme file outside it whose outputs would go beside it, and `--family` with its root theme file outside it. Paths inside the working directory still build, including through a symlink. To migrate, run the build from a folder that holds the theme file and its outputs, or pass an `--out` path inside that folder; API callers pass a `cwd` that holds them.++@josephfarinadiff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.mdindex c12f662764..72a69e7342 100644--- a/docs/architecture/cli-surface.md+++ b/docs/architecture/cli-surface.md@@ -126,6 +126,21 @@ and remains available through explicit Core package selection.- **INV10 — Every write is confined.** Output paths pass `assertWithin`, whichcanonicalises symlinks and rejects a NUL byte; an escape is`ERR_PATH_TRAVERSAL`. Bounded inputs are capped rather than trusted.+- **INV10a — Refusing a write outside its confined root is a compatible fix.**+ When a current record already confines the writes of a CLI operation (a+ command or its programmatic API) to a root, a change that makes the operation+ refuse a write outside that root, before writing anything, is a compatible+ `[fix]` and patch-eligible under the `spec:AST-017` release process. This+ holds for every route the write takes (a traversal segment, an absolute path,+ a symlink, or a default location derived from an input outside the root), and+ even when the latest stable release accepted the input and its documentation+ did not forbid the write: a write outside the confined root is not a supported+ workflow, so a caller that relied on it is not a released victim. The+ Changeset cites the confinement rule the released behavior violated, names+ each input that is now refused and how it fails, and gives the migration.+ Inputs whose writes stay inside the root keep working. Refusing one of them,+ moving outputs instead of refusing, or confining an operation that no current+ record confines is classified like any other change.- **INV11 — A broken integration degrades a command run, it does not failit.** The `Project` seam loads each integration independently and recordsthe failure, and the command's own work proceeds without that integration's@@ -384,6 +399,25 @@ on a broken integration (a read or a build stops for a problem it can workaround); counting only the integrations that happened to load (a package setaside or replaced by the package being authored would vanish from the count).+### DEC-3 — Refusing a write outside its confined root is a fix++**Decider:** `josephfarina`, `2026-10-15`++A write outside the confined root lands wherever its path points, with the+caller's file permissions, and can replace a file the caller never named as an+output: source, configuration, or another project's files. Agents run the CLI+unattended and pass generated paths, so one wrong path loses work with nothing+to undo. Holding the refusal for a minor, or warning while the write still+happens, keeps that exposure open to protect a use the confinement already+forbids, so the refusal ships as a `[fix]` (INV10a). The boundary is narrow:+the confinement is already current, the refusal comes before any write, the+Changeset names each refused input and its migration, and writes inside the+root keep working.++Rejected: a patch warning with the refusal held for a minor (the warning prints+after the file is replaced); and letting every current invariant outrank+released documentation (any correction could then claim the patch tier).+## Verification| Invariant | Evidence | Failure signal |diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsindex 98f4b9d23c..b43456d0aa 100644--- a/packages/cli/api/integration/pack-check.mjs+++ b/packages/cli/api/integration/pack-check.mjs@@ -660,11 +660,10 @@ async function validateIncompleteThemeExports(const expectedCss = path.join(expectedDir, `${localTheme.slug}.css`);try {if (outputs.some(output => output.kind !== 'font stylesheet')) {- const receipt = await themeBuild(- source,- {out: expectedCss},- {cwd: packageDir},- );+ // The scratch directory is the write root; the package stays the cwd,+ // so the build selects the package's Core and its paths as before.+ const scratchBuild = {out: expectedCss, __writeRoot: expectedDir};+ const receipt = await themeBuild(source, scratchBuild, {cwd: packageDir});if (receipt == null || receipt.type !== 'theme.build') {throw new Error('the theme build produced no complete receipt');}@@ -847,11 +846,12 @@ async function validatePackedThemeExports();const expectedCss = path.join(expectedDir, `${localTheme.slug}.css`);try {- const receipt = await themeBuild(- source,- {out: expectedCss},- {cwd: localIntegration.__packageDir},- );+ // The scratch directory is the write root; the package stays the cwd,+ // so the build selects the package's Core and its paths as before.+ const scratchBuild = {out: expectedCss, __writeRoot: expectedDir};+ const receipt = await themeBuild(source, scratchBuild, {+ cwd: localIntegration.__packageDir,+ });if (receipt == null || receipt.type !== 'theme.build') {issues.push(error(diff --git a/packages/cli/api/theme/build/build.family.test.mjs b/packages/cli/api/theme/build/build.family.test.mjsindex 4de79e13d3..a85c49e95c 100644--- a/packages/cli/api/theme/build/build.family.test.mjs+++ b/packages/cli/api/theme/build/build.family.test.mjs@@ -252,6 +252,22 @@ describe('themeBuildFamily()', () => {expect(fs.existsSync(dtsPath)).toBe(false);});+ it('refuses family outputs outside cwd before checking or writing', async () => {+ const dir = makeDir();+ const files = writeFamily(dir).map(file => path.join(dir, file));+ const app = path.join(dir, 'app');+ fs.mkdirSync(app);++ for (const check of [false, true]) {+ await expect(+ themeBuildFamily(files, {familyKey: FAMILY_KEY, check}, {cwd: app}),+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});+ }+ for (const output of OUTPUTS) {+ expect(fs.existsSync(path.join(dir, 'themes', output))).toBe(false);+ }+ });+it('fails without publishing a mixed trio when staging a write fails', async () => {const dir = makeDir();const files = writeFamily(dir);diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex d8b7911486..ae50d49e25 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -27,6 +27,8 @@* files; an internal callback lets the CLI make only the process status fail.* Human progress is emitted through the shared `logger` (silent by default), so* the CLI keeps its exact output while a programmatic caller stays quiet.+ * Every output, explicit or beside the theme file, stays inside `cwd`+ * (`ERR_PATH_TRAVERSAL` otherwise), in check mode too.** The installed `@astryxdesign/core` is an independently versioned optional* peer, so it can be older than the CLI. A theme that uses only baseline@@ -270,6 +272,25 @@ function realOrSelf(file) {}}+/**+ * `target` spelled through real directories: the deepest ancestor that exists+ * is resolved through its symlinks, and the missing rest is appended as given.+ * @param {string} target absolute path+ * @returns {string}+ */+function realLocation(target) {+ /** @type {string[]} */+ const missing = [];+ let existing = target;+ while (!fs.existsSync(existing)) {+ const parent = path.dirname(existing);+ if (parent === existing) break;+ missing.unshift(path.basename(existing));+ existing = parent;+ }+ return path.join(realOrSelf(existing), ...missing);+}+/*** The Core the project at `cwd` installed, when it differs from the one the* CLI's own import found and loads. The app's `<Theme>` runs on the app's@@ -506,6 +527,47 @@ function checkedBuildOutputs(writes, cwd) {.map(write => path.relative(cwd, write.dest));}+/** Remedies that end a confinement error, by where the output path came from. */+const OUT_REMEDY = 'Pass an --out path inside it.';+const SOURCE_REMEDY =+ 'Without --out the outputs go beside the theme file, so run the build from a directory that contains the theme file, or pass an --out path inside the working directory.';+const FAMILY_REMEDY =+ "Family outputs go beside the family's root theme file, so run the build from a directory that contains it.";++/**+ * Refuse an output outside `root`: every write is confined, whether `out` names+ * the path or it defaults to the theme file's directory (architecture:cli-surface+ * INV10). Both sides are compared by real location, so an absolute path that+ * reaches the working directory through a symlink is inside it, and a symlink+ * inside it that leads elsewhere is not.+ * @param {string} dest absolute output path+ * @param {string} root the directory writes stay inside: the working directory+ * @param {string} remedy what to do instead; ends the error message+ * @param {string} [shown] the path as the caller wrote it, for the message+ */+function confineOutput(dest, root, remedy, shown = dest) {+ try {+ assertWithin(realLocation(dest), realOrSelf(path.resolve(root)), {+ allowAbsolute: true,+ label: 'output path',+ });+ } catch (err) {+ if (!(err instanceof PathSafetyError)) throw err;+ throw new AstryxError(+ err.code === ERROR_CODES.ERR_PATH_TRAVERSAL+ ? `Output path "${shown}" is outside the working directory (${root}). ${remedy}`+ : err.message,+ undefined,+ ERROR_CODES.ERR_PATH_TRAVERSAL,+ );+ }+}++/** @param {Array<{dest: string}>} writes @param {string} root @param {string} remedy */+function confineOutputs(writes, root, remedy) {+ for (const write of writes) confineOutput(write.dest, root, remedy);+}+/** @param {Array<{dest: string, content: string}>} writes */function writeBuildOutputs(writes) {if (writes.length === 0) return;@@ -2344,9 +2406,10 @@ function validateHeadingTypeAugmentationSupport(themeDef) {* `logger` (silent by default).** @param {string} file - Theme file path, resolved against `cwd`.- * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any, __onPrivateVarError?: () => void}} [options] -+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any, __onPrivateVarError?: () => void, __writeRoot?: string}} [options] -* `out` overrides the output CSS path; `check` compares against on-disk outputs- * instead of writing. `iconsSpecifier` overrides the icon registry import+ * instead of writing. `__writeRoot` replaces `cwd` as the directory every+ * output must stay inside, for a CLI-internal scratch build. `iconsSpecifier` overrides the icon registry import* specifier in the generated module (e.g. `./icons.mjs`); when omitted, the* direct registry specifiers from the theme source are emitted unchanged.* @param {{cwd?: string}} [ctx]@@ -2791,25 +2854,14 @@ async function themeBuildInternal(// 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;+ // Every write stays inside cwd. A CLI-internal caller that renders into a+ // scratch directory it creates and removes names that directory instead.+ const writeRoot = options.__writeRoot ?? cwd;let outPath;if (options.out) {+ // Relative or absolute, the explicit output stays inside the write root.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)) {- try {- assertWithin(options.out, cwd, {label: 'output path'});- } catch (err) {- if (err instanceof PathSafetyError) {- throw new AstryxError(- err.message,- undefined,- ERROR_CODES.ERR_PATH_TRAVERSAL,- );- }- throw err;- }- }+ confineOutput(outPath, writeRoot, OUT_REMEDY, options.out);} else {outPath = path.join(path.dirname(filePath), `${baseName}.css`);}@@ -2905,6 +2957,11 @@ async function themeBuildInternal(writes.push({dest: variantDtsPath, content: variantContent});}+ // Every output stays inside cwd, including the defaults beside the theme+ // file. Check mode refuses the same paths, so it never passes outputs that a+ // build would refuse to write.+ confineOutputs(writes, writeRoot, options.out ? OUT_REMEDY : SOURCE_REMEDY);+// Check mode: compare generated content against what's on disk instead of// writing. A file is "stale" if it's missing or its content differs once the// volatile @generated `Command:` line is ignored. Returns a@@ -3449,6 +3506,8 @@ export async function themeBuildFamily(js: path.relative(cwd, jsPath),dts: path.relative(cwd, dtsPath),};+ // The family's outputs stay inside cwd too, in check mode as well.+ confineOutputs(writes, cwd, FAMILY_REMEDY);if (options.check) {const stale = staleBuildOutputs(writes, cwd);const upToDate = stale.length === 0;diff --git a/packages/cli/api/theme/themeBuild.doc.mjs b/packages/cli/api/theme/themeBuild.doc.mjsindex 100f4e88db..efe5c39884 100644--- a/packages/cli/api/theme/themeBuild.doc.mjs+++ b/packages/cli/api/theme/themeBuild.doc.mjs@@ -58,7 +58,7 @@ export const doc = {name: 'options.out',type: 'string',description:- 'Override the output CSS path. The .js, .d.ts and any .variants.d.ts are written in the same directory, named after the theme (<name>.js), not after the CSS file. A relative path must stay within cwd.',+ 'Override the output CSS path, relative or absolute; it must resolve inside cwd. The .js, .d.ts and any .variants.d.ts are written in the same directory, named after the theme (<name>.js), not after the CSS file.',},{name: 'options.check',@@ -77,7 +77,7 @@ export const doc = {name: 'ctx.cwd',type: 'string',description:- 'Directory the theme file, a relative out path, and the returned output paths resolve against.',+ 'Directory the theme file, a relative out path, and the returned output paths resolve against. Every output is written inside it, including the default outputs beside the theme file.',default: 'process.cwd()',},],@@ -105,7 +105,7 @@ export const doc = {},{code: 'ERR_PATH_TRAVERSAL',- when: 'the theme name contains a path separator or traversal marker, or a relative `out` path resolves outside cwd (including through a symlink)',+ when: 'the theme name contains a path separator or traversal marker, or an output resolves outside cwd (including through a symlink): an `out` path, relative or absolute, or the default outputs beside a theme file outside cwd (also rejected in check mode)',},{code: 'ERR_CORE_NOT_FOUND',diff --git a/packages/cli/clients/cli/commands/build-theme.path-safety.test.mjs b/packages/cli/clients/cli/commands/build-theme.path-safety.test.mjsindex 9b04ab2199..14181c1b45 100644--- a/packages/cli/clients/cli/commands/build-theme.path-safety.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.path-safety.test.mjs@@ -9,6 +9,9 @@* - Multi-file write is atomic: if one file fails, none are left behind.* - An `--out` escape, or an output directory that cannot be created, fails* with a registered error code.+ * - Every output stays inside the working directory: an absolute `--out`+ * path or a theme file outside it fails before anything is written, while+ * absolute paths inside it build, also through a symlinked spelling.** Runs the CLI in-process (shared runCli harness) against a tiny synthetic theme file.*/@@ -129,6 +132,68 @@ describe('theme build output-path failures carry registered codes', () => {expect(fs.existsSync(path.join(tmpDir, 'escaped.css'))).toBe(false);});+ it('reports an absolute --out path outside the project as ERR_PATH_TRAVERSAL, with --check too', async () => {+ const project = path.join(tmpDir, 'project');+ const outside = path.join(tmpDir, 'outside');+ fs.mkdirSync(outside, {recursive: true});+ const themeFile = writeTheme(path.join(project, 'themes'), 'ocean');+ const out = path.join(outside, 'ocean.css');++ for (const extra of [[], ['--check']]) {+ const {result, envelope} = await buildJson(+ [path.relative(project, themeFile), '--out', out, ...extra],+ project,+ );++ expect(result.code).toBe(1);+ expect(envelope.code).toBe(ERROR_CODES.ERR_PATH_TRAVERSAL);+ }+ expect(fs.readdirSync(outside)).toEqual([]);+ });++ it('reports a theme file outside the project as ERR_PATH_TRAVERSAL, because its outputs go beside it', async () => {+ const project = path.join(tmpDir, 'project');+ fs.mkdirSync(project, {recursive: true});+ const shared = path.join(tmpDir, 'shared');+ const themeFile = writeTheme(shared, 'ocean');++ for (const file of [themeFile, path.relative(project, themeFile)]) {+ const {result, envelope} = await buildJson([file], project);++ expect(result.code).toBe(1);+ expect(envelope.code).toBe(ERROR_CODES.ERR_PATH_TRAVERSAL);+ }+ expect(fs.readdirSync(shared)).toEqual(['theme.mjs']);+ });++ it('builds absolute paths inside the project, also when they reach it through a symlink', async () => {+ const project = path.join(tmpDir, 'project');+ const themeFile = writeTheme(path.join(project, 'themes'), 'ocean');+ const alias = path.join(tmpDir, 'alias');+ fs.symlinkSync(project, alias, 'dir');++ for (const [args, written] of [+ [+ [themeFile, '--out', path.join(project, 'dist', 'direct.css')],+ path.join(project, 'dist', 'direct.css'),+ ],+ [+ [themeFile, '--out', path.join(alias, 'dist', 'aliased.css')],+ path.join(project, 'dist', 'aliased.css'),+ ],+ [+ [path.join(alias, 'themes', 'theme.mjs')],+ path.join(project, 'themes', 'ocean.css'),+ ],+ ]) {+ const {result, envelope} = await buildJson(args, project);++ expect(result.code).toBe(0);+ expect(envelope.type).toBe('theme.build');+ expect(fs.existsSync(written)).toBe(true);+ }+ });+it('reports an --out path that escapes through a symlink as ERR_PATH_TRAVERSAL', async () => {const project = path.join(tmpDir, 'project');const outside = path.join(tmpDir, 'outside');@@ -177,4 +242,23 @@ describe('theme build output-path failures carry registered codes', () => {code: ERROR_CODES.ERR_PATH_TRAVERSAL,});});++ it('themeBuild() rejects an output outside cwd: an absolute out path, or the default beside a theme file outside cwd', async () => {+ const project = path.join(tmpDir, 'project');+ const inside = writeTheme(path.join(project, 'themes'), 'ocean');+ const shared = path.join(tmpDir, 'shared');+ const outsideTheme = writeTheme(shared, 'ocean');+ const outDir = path.join(tmpDir, 'out');++ for (const [file, options] of [+ [path.relative(project, inside), {out: path.join(outDir, 'ocean.css')}],+ [outsideTheme, {}],+ ]) {+ await expect(+ themeBuild(file, options, {cwd: project}),+ ).rejects.toMatchObject({code: ERROR_CODES.ERR_PATH_TRAVERSAL});+ }+ expect(fs.existsSync(outDir)).toBe(false);+ expect(fs.readdirSync(shared)).toEqual(['theme.mjs']);+ });});diff --git a/packages/cli/clients/cli/commands/build-theme.registry.test.mjs b/packages/cli/clients/cli/commands/build-theme.registry.test.mjsindex 93a5970cbb..383f7a0ef5 100644--- a/packages/cli/clients/cli/commands/build-theme.registry.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.registry.test.mjs@@ -126,7 +126,10 @@ describe('theme build emits a live TextInput selector (#4109)', () => {`};\n`,);- const result = await runCli(['theme', 'build', themeFile, '-o', outFile]);+ const result = await runCli(+ ['theme', 'build', themeFile, '-o', outFile],+ tmpDir,+ );const css = fs.readFileSync(outFile, 'utf8');expect(result.status).toBe(0);@@ -148,7 +151,7 @@ describe('theme build emits a live TextInput selector (#4109)', () => {`};\n`,);- await runCli(['theme', 'build', themeFile, '-o', outFile]);+ await runCli(['theme', 'build', themeFile, '-o', outFile], tmpDir);const css = fs.readFileSync(outFile, 'utf8');expect(css).toContain('.astryx-text-input');diff --git a/packages/cli/clients/cli/commands/theme-build.doc.mjs b/packages/cli/clients/cli/commands/theme-build.doc.mjsindex a1c86a6ab1..a601a15989 100644--- a/packages/cli/clients/cli/commands/theme-build.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-build.doc.mjs@@ -30,7 +30,7 @@ export const doc = {{flag: '--family',description:- 'Build the selected extension family into one keyed CSS, JS, and declaration set. Requires --family-key; refused with --out or --watch (ERR_THEME_INVALID)',+ 'Build the selected extension family into one keyed CSS, JS, and declaration set, written beside the family root theme file, which must be inside the working directory (ERR_PATH_TRAVERSAL). Requires --family-key; refused with --out or --watch (ERR_THEME_INVALID)',},{flag: '--family-key <key>',@@ -41,7 +41,7 @@ export const doc = {flag: '-o, --out <path>',param: 'options.out',description:- 'Output CSS file path; the .js and .d.ts are written beside it (default: <theme name>.css next to the source). A relative path must stay inside the working directory. Single theme only: refused with more than one file or with --family (ERR_THEME_INVALID)',+ 'Output CSS file path, relative or absolute; the .js and .d.ts are written beside it (default: <theme name>.css next to the source). Every output must resolve inside the working directory, the defaults beside the source too (ERR_PATH_TRAVERSAL). Single theme only: refused with more than one file or with --family (ERR_THEME_INVALID)',},{flag: '--icons-specifier <specifier>',