An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): keep agent-doc writes inside the project (#6524)
Joeye26c83bf3019
diff --git a/.changeset/cli-spec-agent-docs-confine-writes.md b/.changeset/cli-spec-agent-docs-confine-writes.mdnew file mode 100644index 0000000000..5966963410--- /dev/null+++ b/.changeset/cli-spec-agent-docs-confine-writes.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx init`, `astryx init --remove-agents` and `astryx upgrade --apply` no longer edit or delete a file outside the project through an agent file or `.claude/` directory that is a symlink pointing there. Init reports a path-safety error for that file and exits 1, `init --remove-agents` fails with `ERR_PATH_TRAVERSAL` and exits 1 instead of reporting the block removed, and upgrade reports the refresh as failed, before any file is written.++@josephfarinadiff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex f972e542ec..4b81e9a2da 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -22,11 +22,12 @@import * as fs from 'node:fs';import * as path from 'node:path';import {findCoreDir, CLI_ROOT} from '../fs/paths.mjs';-import {assertWithin} from '../fs/path-safety.mjs';+import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';import {getCliInvocation} from '../env/package-manager.mjs';import {discoverComponents} from '../discovery/component-discovery.mjs';import {Project} from '../config/project.mjs';import {humanLog} from '../response/json.mjs';+import {ERROR_CODES} from '../response/error-codes.mjs';import {AGENTS_MD,CLAUDE_MD,@@ -705,12 +706,65 @@ export function removeXdsBlock(filePath, {deleteIfEmpty = false} = {}) {return true;}+/**+ * Whether an agent-doc file already carries a managed-block marker.+ * @param {string} filePath+ * @returns {boolean}+ */+function hasManagedMarker(filePath) {+ try {+ const content = fs.readFileSync(filePath, 'utf-8');+ return content.includes(MARKER_START) || content.includes(LEGACY_MARKER_START);+ } catch {+ return false;+ }+}++/**+ * Whether `removeXdsBlock` would change `filePath`: it holds one well-formed+ * managed block.+ * @param {string} filePath+ * @returns {boolean}+ */+function hasRemovableBlock(filePath) {+ try {+ return findManagedBlock(fs.readFileSync(filePath, 'utf-8')) != null;+ } catch {+ return false;+ }+}++/**+ * Every file a run writes must resolve inside `targetDir`, symlinks+ * included. Checked for the whole write set before the first write, so an+ * escape writes nothing.+ * @param {string} targetDir+ * @param {Iterable<string>} relPaths+ */+function assertTargetsWithin(targetDir, relPaths) {+ for (const p of relPaths) {+ assertWithin(p, targetDir, {label: 'agent docs path'});+ }+}+/*** Remove Astryx section from all known agent doc files.* @param {string} targetDir+ * @throws {PathSafetyError} `ERR_PATH_TRAVERSAL` when a file it would change+ * resolves outside `targetDir`; nothing is changed.*/export function removeAgentDocs(targetDir) {const allPaths = discoverAgentDocs(targetDir);+ try {+ assertTargetsWithin(+ targetDir,+ allPaths.filter(p => hasRemovableBlock(path.join(targetDir, p))),+ );+ } catch (err) {+ // The code reaches the error envelope as is, so it must be registered.+ if (!(err instanceof PathSafetyError)) throw err;+ throw new PathSafetyError(err.message, ERROR_CODES.ERR_PATH_TRAVERSAL);+ }for (const p of allPaths) {const filePath = path.join(targetDir, p);@@ -750,6 +804,8 @@ export function removeAgentDocs(targetDir) {* @param {string} [options.renderedBlock] - Fully rendered expected block. Init* and upgrade pass one shared block to every target.* @returns {string[]} List of files written+ * @throws {import('../fs/path-safety.mjs').PathSafetyError} when a file it would+ * write resolves outside `targetDir`; nothing is written.*/export function installAgentDocs(targetDir,@@ -806,6 +862,7 @@ export function installAgentDocs(// Agent presetif (agent) {const {inject, create} = resolveAgentPaths(targetDir, agent);+ assertTargetsWithin(targetDir, [...inject, ...create]);for (const p of inject) {injectXdsBlock(path.join(targetDir, p), compressedIndex);written.push(p);@@ -833,6 +890,14 @@ export function installAgentDocs(if (existing.length > 0) {const wrappers = discoverAgentDocWrappers(targetDir, existing);const targets = existing.filter(p => !wrappers.has(p));+ // A refresh skips unmarked files and a wrapper is only written when it+ // carries a block, so only the files this run writes are checked.+ /** @param {string} p */+ const marked = p => hasManagedMarker(path.join(targetDir, p));+ assertTargetsWithin(targetDir, [+ ...targets.filter(p => !onlyReplace || marked(p)),+ ...[...wrappers].filter(marked),+ ]);for (const p of targets) {const didWrite = injectXdsBlock(path.join(targetDir, p), compressedIndex, {onlyReplace});@@ -860,6 +925,7 @@ export function installAgentDocs(if (onlyReplace) return written;const defaultPath = AGENTS_MD;+ assertTargetsWithin(targetDir, [defaultPath]);injectXdsBlock(path.join(targetDir, defaultPath), compressedIndex, {createIfMissing: true,header: `# AGENTS.md\n\nProject-specific guidance for AI coding agents.`,diff --git a/packages/cli/foundation/agent-docs/agent-docs.path-safety.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.path-safety.test.mjsindex a4800c750f..53fe0a2d2a 100644--- a/packages/cli/foundation/agent-docs/agent-docs.path-safety.test.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.path-safety.test.mjs@@ -1,22 +1,31 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Path-safety regression tests for `--agent-docs-path`.+ * @file Path-safety regression tests for agent-doc writes.** `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.+ * Auto-detected and preset files were never checked at all, so a `CLAUDE.md`+ * or `.claude/` symlinked out of the project had the block written through+ * it. Every case now throws PathSafetyError before any file is touched.+ *+ * `removeAgentDocs` (`init --remove-agents`) stripped or deleted a block+ * through the same kind of link and reported success. It now refuses with+ * `ERR_PATH_TRAVERSAL` before any file is touched.*/-import {describe, it, expect, beforeEach, afterEach} from 'vitest';+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';-import {installAgentDocs} from './agent-docs.mjs';+import {installAgentDocs, removeAgentDocs} from './agent-docs.mjs';import {PathSafetyError} from '../fs/path-safety.mjs';+import {runCli} from '../../test-utils/run-cli.mjs';++const BLOCK = '<!-- ASTRYX:START -->\nmanaged\n<!-- ASTRYX:END -->';let tmpDir;beforeEach(() => {@@ -26,6 +35,28 @@ afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});+/** A project dir plus a sibling dir outside it. */+function layout() {+ const project = path.join(tmpDir, 'project');+ const outside = path.join(tmpDir, 'outside');+ fs.mkdirSync(project, {recursive: true});+ fs.mkdirSync(outside, {recursive: true});+ return {project, outside};+}++/**+ * @param {() => unknown} fn+ * @returns {unknown} what `fn` threw+ */+function thrownBy(fn) {+ try {+ fn();+ } catch (err) {+ return err;+ }+ throw new Error('expected a throw');+}+describe('installAgentDocs path safety', () => {it('rejects --agent-docs-path that escapes the target directory', () => {const target = path.join(tmpDir, 'project');@@ -64,3 +95,234 @@ describe('installAgentDocs path safety', () => {expect(fs.existsSync(path.join(tmpDir, 'escaped.md'))).toBe(false);});});++describe('installAgentDocs never writes through a symlink out of the project', () => {+ it('refuses an auto-detected file that links outside', () => {+ const {project, outside} = layout();+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ expect(() => installAgentDocs(project, {renderedBlock: BLOCK})).toThrow(+ /outside the project root/,+ );+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ });++ it('refuses a preset file reached through a symlinked directory', () => {+ const {project, outside} = layout();+ fs.symlinkSync(outside, path.join(project, '.claude'));++ expect(() =>+ installAgentDocs(project, {agent: 'claude', renderedBlock: BLOCK}),+ ).toThrow(PathSafetyError);+ expect(fs.readdirSync(outside)).toEqual([]);+ });++ it('refuses an existing preset file that links outside', () => {+ const {project, outside} = layout();+ const shared = path.join(outside, 'rules');+ fs.writeFileSync(shared, 'rules\n');+ fs.symlinkSync(shared, path.join(project, '.cursorrules'));++ expect(() =>+ installAgentDocs(project, {agent: 'cursor', renderedBlock: BLOCK}),+ ).toThrow(PathSafetyError);+ expect(fs.readFileSync(shared, 'utf-8')).toBe('rules\n');+ });++ it('writes nothing when any file of the set escapes', () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Agents\n');+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ expect(() => installAgentDocs(project, {renderedBlock: BLOCK})).toThrow(+ PathSafetyError,+ );+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toBe(+ '# Agents\n',+ );+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ });++ it('refuses to refresh a managed block that lives outside', () => {+ const {project, outside} = layout();+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, `# Shared\n\n${BLOCK.replace('managed', 'old')}\n`);+ const before = fs.readFileSync(shared, 'utf-8');+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ expect(() =>+ installAgentDocs(project, {onlyReplace: true, renderedBlock: BLOCK}),+ ).toThrow(PathSafetyError);+ expect(fs.readFileSync(shared, 'utf-8')).toBe(before);+ });++ it('refuses to strip a duplicate block from a wrapper that links outside', () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\n${BLOCK}\n`);+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, `@AGENTS.md\n\n${BLOCK}\n`);+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ expect(() => installAgentDocs(project, {renderedBlock: BLOCK})).toThrow(+ PathSafetyError,+ );+ expect(fs.readFileSync(shared, 'utf-8')).toBe(`@AGENTS.md\n\n${BLOCK}\n`);+ });++ it('still refreshes in-project blocks beside an unmarked outside link it skips', () => {+ const {project, outside} = layout();+ fs.writeFileSync(+ path.join(project, 'AGENTS.md'),+ `# Agents\n\n${BLOCK.replace('managed', 'old')}\n`,+ );+ const shared = path.join(outside, 'rules');+ fs.writeFileSync(shared, 'rules\n');+ fs.symlinkSync(shared, path.join(project, '.cursorrules'));++ expect(+ installAgentDocs(project, {onlyReplace: true, renderedBlock: BLOCK}),+ ).toEqual(['AGENTS.md']);+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toContain(+ 'managed',+ );+ expect(fs.readFileSync(shared, 'utf-8')).toBe('rules\n');+ });++ it('writes through a symlink that stays inside the project', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Agents\n');+ fs.symlinkSync('AGENTS.md', path.join(project, 'CLAUDE.md'));++ expect(installAgentDocs(project, {renderedBlock: BLOCK})).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ ]);+ const content = fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8');+ expect(content.split('<!-- ASTRYX:START -->')).toHaveLength(2);+ });+});++describe('init --features agents with an agent doc linked outside the project', () => {+ it('writes nothing outside, reports path-safety, and exits 1 in both modes', async () => {+ const project = path.join(tmpDir, 'project');+ const outside = path.join(tmpDir, 'outside');+ fs.mkdirSync(project, {recursive: true});+ fs.mkdirSync(outside, {recursive: true});+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ const json = await runCli(['init', '--features', 'agents', '--json'], project);+ expect(json.status).toBe(1);+ const env = JSON.parse(json.stdout);+ expect(env.type).toBe('init.run');+ expect(env.data.docsError).toMatchObject({kind: 'path-safety'});++ const text = await runCli(['init', '--features', 'agents'], project);+ expect(text.status).toBe(1);++ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ }, 30_000);+});++describe('removeAgentDocs never changes a file out of the project', () => {+ beforeEach(() => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('refuses to strip a block from a file that links outside', () => {+ const {project, outside} = layout();+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, `# Shared\n\n${BLOCK}\n`);+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ const err = thrownBy(() => removeAgentDocs(project));+ expect(err).toBeInstanceOf(PathSafetyError);+ expect(err).toMatchObject({code: 'ERR_PATH_TRAVERSAL'});+ expect(fs.readFileSync(shared, 'utf-8')).toBe(`# Shared\n\n${BLOCK}\n`);+ });++ it('refuses to delete a file reached through a symlinked directory', () => {+ const {project, outside} = layout();+ const shared = path.join(outside, 'CLAUDE.md');+ const content = `# CLAUDE\n\nProject-specific guidance for AI coding agents.\n\n${BLOCK}\n`;+ fs.writeFileSync(shared, content);+ fs.symlinkSync(outside, path.join(project, '.claude'));++ expect(thrownBy(() => removeAgentDocs(project))).toMatchObject({+ code: 'ERR_PATH_TRAVERSAL',+ });+ expect(fs.readFileSync(shared, 'utf-8')).toBe(content);+ });++ it('changes nothing when any file of the set escapes', () => {+ const {project, outside} = layout();+ const agents = `# Agents\n\nkeep\n\n${BLOCK}\n`;+ fs.writeFileSync(path.join(project, 'AGENTS.md'), agents);+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, `# Shared\n\n${BLOCK}\n`);+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ expect(thrownBy(() => removeAgentDocs(project))).toBeInstanceOf(PathSafetyError);+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toBe(agents);+ expect(fs.readFileSync(shared, 'utf-8')).toBe(`# Shared\n\n${BLOCK}\n`);+ });++ it('still strips in-project blocks beside an unmarked outside link it skips', () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\nkeep\n\n${BLOCK}\n`);+ const shared = path.join(outside, 'rules');+ fs.writeFileSync(shared, 'rules\n');+ fs.symlinkSync(shared, path.join(project, '.cursorrules'));++ removeAgentDocs(project);+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toBe(+ '# Agents\n\nkeep\n',+ );+ expect(fs.readFileSync(shared, 'utf-8')).toBe('rules\n');+ });++ it('strips through a symlink that stays inside the project', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\nkeep\n\n${BLOCK}\n`);+ fs.symlinkSync('AGENTS.md', path.join(project, 'CLAUDE.md'));++ removeAgentDocs(project);+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toBe(+ '# Agents\n\nkeep\n',+ );+ });+});++describe('init --remove-agents with an agent doc linked outside the project', () => {+ it('changes nothing outside, fails with ERR_PATH_TRAVERSAL, and exits 1 in both modes', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ const shared = path.join(outside, 'CLAUDE.md');+ const content = `# Shared\n\n${BLOCK}\n`;+ fs.writeFileSync(shared, content);+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ const json = await runCli(['init', '--remove-agents', '--json'], project);+ expect(json.status).toBe(1);+ const env = JSON.parse(json.stdout);+ expect(env).toMatchObject({apiVersion: 1, code: 'ERR_PATH_TRAVERSAL'});+ expect(env.error).toMatch(/"CLAUDE\.md": resolves outside the project root/);+ expect(env).not.toHaveProperty('data');++ const text = await runCli(['init', '--remove-agents'], project);+ expect(text.status).toBe(1);+ expect(text.stderr).toMatch(/^Error: .*"CLAUDE\.md": resolves outside the project root/m);+ expect(text.stdout).not.toMatch(/removed/i);++ expect(fs.readFileSync(shared, 'utf-8')).toBe(content);+ }, 30_000);+});