Skip to content

fix(cli): codemod output validation, CI verification, and fix #910 - #912

Merged
cixzhang merged 1 commit into
mainfrom
navi/fix/codemod-validation
Mar 27, 2026
Merged

cixzhang merged 1 commit into
mainfrom
navi/fix/codemod-validation

Conversation

@cixzhang

@cixzhang cixzhang commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

What

Three layers of codemod safety, plus two bug fixes:

1. Runner output validation (self-healing)

Before writing any transformed file to disk, the runner now:

  • Re-parses the output through jscodeshift — catches syntax-breaking corruption
  • Scans for known corruption patterns — [native code] injection from prototype pollution

If validation fails, the file is not written and a clear error is reported. Other files continue processing.

2. CI codemod verification workflow

New codemod-verify.yml workflow that triggers when a PR modifies packages/cli/src/codemods/. It:

  1. Detects which codemod versions were added/modified
  2. Finds consumer files also changed in the PR (apps/storybook, apps/sandbox, e2e)
  3. Reverts consumer files to the base branch state
  4. Runs the codemods from source
  5. Verifies the output matches the PR's committed changes

Enforces the rule: callsite updates must be produced by the codemod, not hand-edited.

3. Fix #910 — token rename prototype pollution

migrate-token-renames.mjs used bare IDENTIFIER_MAP[name] which returns Object.prototype.toString for .toString() calls. Fixed with Object.hasOwn() guard.

4. Fix import dedup for rename-to-existing

When the IDENTIFIER_MAP renames an import specifier (e.g. lineHeightDefaults → typeScaleDefaults) and the target already exists in the same import declaration, the old specifier is removed instead of renamed. Prevents duplicate identifier declarations.

Found during integration testing: theme-editor/page.tsx imports both lineHeightDefaults and typeScaleDefaults — the old codemod would create two typeScaleDefaults imports.

Testing

Unit tests: 251 passing (244 existing + 7 new)

  • 4 regression tests for prototype pollution (.toString(), .toLocaleString(), .hasOwnProperty(), .valueOf())
  • 3 tests for import dedup (dual import, single import, lineHeightVars variant)

Integration test: Reverted all 15 storybook/sandbox files from #894 (token rename PR), ran the fixed codemod:

  • 17 files processed, 0 validation blocks, 0 corruption
  • 12/15 files match committed version exactly (modulo jscodeshift quote formatting)
  • 3 files have minor whitespace/ordering diffs from jscodeshift toSource() — no semantic differences
  • All 4 .toString() calls in theme-editor preserved correctly

Closes #910

@cixzhang
cixzhang requested a review from josephfarina as a code owner March 27, 2026 01:38
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 27, 2026
@github-actions

github-actions Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

No new or modified components detected.

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@xds/core 11.2KB 17.7KB 2.8KB

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

@cixzhang
cixzhang force-pushed the navi/fix/codemod-validation branch from 57b95cc to eef12f9 Compare March 27, 2026 01:52
Three changes to make codemods safer:

1. **Runner output validation** — before writing any file, the runner now
   re-parses the transformed output and checks for known corruption patterns
   ([native code] injection from prototype pollution). Invalid transforms
   are blocked from writing to disk with a clear error message.

2. **CI codemod verification workflow** — when a PR adds/modifies codemods
   AND touches consumer code (apps/storybook, apps/sandbox, e2e), CI reverts
   the consumer files to base, runs the codemods, and verifies the output
   matches the committed changes. This enforces the rule: callsite updates
   must be produced by the codemod, not hand-edited.

3. **Fix #910** — migrate-token-renames IDENTIFIER_MAP used bare object
   lookup which hit Object.prototype.toString/hasOwnProperty/valueOf.
   Fixed with Object.hasOwn() guard. Added 4 regression tests.

248 tests passing (244 existing + 4 new regression).

Co-authored-by: Navi <[email protected]>
@cixzhang
cixzhang force-pushed the navi/fix/codemod-validation branch from eef12f9 to 3e8e03d Compare March 27, 2026 02:32
@cixzhang
cixzhang merged commit 8fee2ec into main Mar 27, 2026
15 checks passed
@cixzhang
cixzhang deleted the navi/fix/codemod-validation branch April 9, 2026 14:32
josephfarina added a commit that referenced this pull request Aug 1, 2026
…ed docs (F4/F7/F12)

- docs _adapter: use Object.create(null) for the topic lookup map so
  __proto__/constructor don't bypass the unknown-topic guard and leak
  ERR_INVALID_ARG_TYPE. Same pattern as #912.

- sandbox generate-cli-registry: CLI_SRC repointed from the deleted
  packages/cli/src to packages/cli/clients/cli. The script was silently
  writing a degenerate cliRegistry.ts with all commands '(failed to load)'.

- getting-started + working-with-ai docs: fix the consumer bin path
  from bin/astryx.mjs (deleted) to clients/cli/bin/astryx.mjs (real).
  Consumers copy this into their package.json scripts.
josephfarina added a commit that referenced this pull request Aug 1, 2026
…ed docs (F4/F7/F12)

- docs _adapter: use Object.create(null) for the topic lookup map so
  __proto__/constructor don't bypass the unknown-topic guard and leak
  ERR_INVALID_ARG_TYPE. Same pattern as #912.

- sandbox generate-cli-registry: CLI_SRC repointed from the deleted
  packages/cli/src to packages/cli/clients/cli. The script was silently
  writing a degenerate cliRegistry.ts with all commands '(failed to load)'.

- getting-started + working-with-ai docs: fix the consumer bin path
  from bin/astryx.mjs (deleted) to clients/cli/bin/astryx.mjs (real).
  Consumers copy this into their package.json scripts.
josephfarina added a commit that referenced this pull request Aug 1, 2026
…ed docs (F4/F7/F12)

- docs _adapter: use Object.create(null) for the topic lookup map so
  __proto__/constructor don't bypass the unknown-topic guard and leak
  ERR_INVALID_ARG_TYPE. Same pattern as #912.

- sandbox generate-cli-registry: CLI_SRC repointed from the deleted
  packages/cli/src to packages/cli/clients/cli. The script was silently
  writing a degenerate cliRegistry.ts with all commands '(failed to load)'.

- getting-started + working-with-ai docs: fix the consumer bin path
  from bin/astryx.mjs (deleted) to clients/cli/bin/astryx.mjs (real).
  Consumers copy this into their package.json scripts.
josephfarina added a commit that referenced this pull request Aug 1, 2026
…ed docs (F4/F7/F12)

- docs _adapter: use Object.create(null) for the topic lookup map so
  __proto__/constructor don't bypass the unknown-topic guard and leak
  ERR_INVALID_ARG_TYPE. Same pattern as #912.

- sandbox generate-cli-registry: CLI_SRC repointed from the deleted
  packages/cli/src to packages/cli/clients/cli. The script was silently
  writing a degenerate cliRegistry.ts with all commands '(failed to load)'.

- getting-started + working-with-ai docs: fix the consumer bin path
  from bin/astryx.mjs (deleted) to clients/cli/bin/astryx.mjs (real).
  Consumers copy this into their package.json scripts.
josephfarina added a commit that referenced this pull request Aug 3, 2026
…ths (#4637)

* fix(cli): confine user-controlled paths with assertWithin (F5/F8/F15)

Close four path-confinement gaps found by chaos testing:

- theme build --out: options.out was passed to path.resolve with no guard,
  allowing writes outside the project root (../ESCAPE.css). Now uses
  assertWithin (parity with theme add).
- theme build <file>: the input file path was similarly unconfined, allowing
  reads of arbitrary files. Now confined.
- validate-integration manifest roots: components/templates/codemods root
  values from an integration manifest were resolved against the package dir
  with no confinement — a manifest could point codemods at '../OUTCM' and
  the validator would import+execute files outside the package (RCE).
  Now guarded with assertWithin; escapes report a 'root_outside_package'
  validation issue instead of executing.
- Same fix in foundation/integrations/integrations.mjs (the load path used
  by upgrade --integration).
- layout --file: readFileSync accepted any path (including /dev/zero →
  OOM). Now confined + size-capped at 5 MB, rejects non-files.

assertWithin already existed and was used by theme-add, swizzle, template,
init, and upgrade --path — these were the unguarded outliers.

* fix(cli): close resource-exhaustion DoS vectors (F9/F13/F14/F15)

- levenshtein: early-exit when |len(a)-len(b)| > 3 (all callers use
  thresholds ≤5, so the sentinel 999 is safe). Drops search@10k from ~17s
  to <1s while preserving real typo suggestions. Closes the DoS where a
  3k+ char query caused multi-second CPU spins (8,860 lev calls per search).

- XLE parseValue: add depth counter (MAX_VALUE_DEPTH=64) to prevent stack
  overflow on deeply nested attribute values ({a:{a:{a:...}}}). The existing
  MAX_COMPACT_DEPTH guard covers tree nesting but missed parseValue recursion.

- XLE expand: cap repeat count at MAX_REPEAT=10000 to prevent heap OOM on
  B*999999999. The parser accepts any *N but the expander now clamps it.

- layout --file: size-cap (5MB) and reject non-files before readFileSync,
  preventing OOM from /dev/zero (already confined by PR1's assertWithin).

* fix(cli): docs proto-pollution + sandbox registry + bin path in shipped docs (F4/F7/F12)

- docs _adapter: use Object.create(null) for the topic lookup map so
  __proto__/constructor don't bypass the unknown-topic guard and leak
  ERR_INVALID_ARG_TYPE. Same pattern as #912.

- sandbox generate-cli-registry: CLI_SRC repointed from the deleted
  packages/cli/src to packages/cli/clients/cli. The script was silently
  writing a degenerate cliRegistry.ts with all commands '(failed to load)'.

- getting-started + working-with-ai docs: fix the consumer bin path
  from bin/astryx.mjs (deleted) to clients/cli/bin/astryx.mjs (real).
  Consumers copy this into their package.json scripts.

* fix(cli): widen levenshtein short-circuit to the hook threshold + add changeset

The DoS early-exit used |m-n| > 3, but the hook suggester keeps matches at
distance <= 5, so a hook name 4-5 edits away was dropped from suggestions.
Widen the cutoff to > 5 (still O(1), same DoS protection) and pin it with
tests. Add the missing changeset for this consumer-facing CLI fix.
josephfarina added a commit that referenced this pull request Aug 3, 2026
#4639)

* fix(cli): confine user-controlled paths with assertWithin (F5/F8/F15)

Close four path-confinement gaps found by chaos testing:

- theme build --out: options.out was passed to path.resolve with no guard,
  allowing writes outside the project root (../ESCAPE.css). Now uses
  assertWithin (parity with theme add).
- theme build <file>: the input file path was similarly unconfined, allowing
  reads of arbitrary files. Now confined.
- validate-integration manifest roots: components/templates/codemods root
  values from an integration manifest were resolved against the package dir
  with no confinement — a manifest could point codemods at '../OUTCM' and
  the validator would import+execute files outside the package (RCE).
  Now guarded with assertWithin; escapes report a 'root_outside_package'
  validation issue instead of executing.
- Same fix in foundation/integrations/integrations.mjs (the load path used
  by upgrade --integration).
- layout --file: readFileSync accepted any path (including /dev/zero →
  OOM). Now confined + size-capped at 5 MB, rejects non-files.

assertWithin already existed and was used by theme-add, swizzle, template,
init, and upgrade --path — these were the unguarded outliers.

* fix(cli): close resource-exhaustion DoS vectors (F9/F13/F14/F15)

- levenshtein: early-exit when |len(a)-len(b)| > 3 (all callers use
  thresholds ≤5, so the sentinel 999 is safe). Drops search@10k from ~17s
  to <1s while preserving real typo suggestions. Closes the DoS where a
  3k+ char query caused multi-second CPU spins (8,860 lev calls per search).

- XLE parseValue: add depth counter (MAX_VALUE_DEPTH=64) to prevent stack
  overflow on deeply nested attribute values ({a:{a:{a:...}}}). The existing
  MAX_COMPACT_DEPTH guard covers tree nesting but missed parseValue recursion.

- XLE expand: cap repeat count at MAX_REPEAT=10000 to prevent heap OOM on
  B*999999999. The parser accepts any *N but the expander now clamps it.

- layout --file: size-cap (5MB) and reject non-files before readFileSync,
  preventing OOM from /dev/zero (already confined by PR1's assertWithin).

* fix(cli): docs proto-pollution + sandbox registry + bin path in shipped docs (F4/F7/F12)

- docs _adapter: use Object.create(null) for the topic lookup map so
  __proto__/constructor don't bypass the unknown-topic guard and leak
  ERR_INVALID_ARG_TYPE. Same pattern as #912.

- sandbox generate-cli-registry: CLI_SRC repointed from the deleted
  packages/cli/src to packages/cli/clients/cli. The script was silently
  writing a degenerate cliRegistry.ts with all commands '(failed to load)'.

- getting-started + working-with-ai docs: fix the consumer bin path
  from bin/astryx.mjs (deleted) to clients/cli/bin/astryx.mjs (real).
  Consumers copy this into their package.json scripts.

* fix(cli): widen levenshtein short-circuit to the hook threshold + add changeset

The DoS early-exit used |m-n| > 3, but the hook suggester keeps matches at
distance <= 5, so a hook name 4-5 edits away was dropped from suggestions.
Widen the cutoff to > 5 (still O(1), same DoS protection) and pin it with
tests. Add the missing changeset for this consumer-facing CLI fix.

* fix(cli): rename search/build boolean --detail to --verbose (F10)

The global `--detail <level>` option (component/hook/docs verbosity) takes a
value, so it shadowed search's and build's boolean `--detail` flag: `astryx
search button --detail` errored with 'option --detail <level> argument
missing' and the verbose import/match output was unreachable. Rename the
boolean flag to `--verbose` so it no longer collides; the global `--detail
<level>` is unchanged. Add a CLI regression test for `search --verbose`
(the flag had no test, which is why the collision went unnoticed).

* fix(cli): regenerate stale bundled CLI themes + add drift guard (F11)

The bundled themes under packages/cli/assets/templates/themes/ (used by
`astryx theme add` to scaffold without the package installed) had drifted from
source, and nothing guarded against it. The neutral bundle was missing the WCAG
light-mode text-secondary fix (neutral-500 #737373 -> neutral-600 #525252, which
clears AA 1.4.3 on the T95 body) and a StatusDot override block, so
`astryx theme add neutral` scaffolded a theme below AA contrast.

- Regenerate via `pnpm bundle:cli-themes` (verbatim copy of source) so every
  bundle byte-matches its packages/themes/<slug>/src source.
- Make the chocolate source Prettier-clean. It was the one theme source that
  wasn't, so the verbatim bundle copy couldn't stay byte-identical once
  lint-staged reformatted it — the drift guard below would fight formatting
  forever. Clean source keeps copy == source stable.
- Add scripts/check-cli-theme-bundle.test.mjs: fails loudly if any bundled
  theme (or its icons) drifts from source, so a future theme edit that skips
  `pnpm bundle:cli-themes` is caught in CI instead of shipping stale.

* fix(cli): unwrap-factories codemod handles shorthand type + no-arg calls (U1/U2)

Two edge cases in the v0.3.0 unwrap-authoring-factories codemod produced broken
output:

- U1 (shorthand `type`): `createComponentDoc({name, type})` where `type` is a
  local binding is a shorthand property. Overwriting only its .value left
  shorthand:true, so it printed `{name, 'component'}` — invalid syntax. Force
  the explicit `type: '<kind>'` form (clear shorthand, reset the key).

- U2 (no-arg call): `createConfig()` / `createComponentDoc()` were left in
  place, but the factory import is removed in the same pass — leaving a dangling
  reference to a deleted binding. Replace a no-arg call with the object the
  factory produced from no input: `{}` for config/integration, `{type: '<kind>'}`
  for the stamping factories.

Add regression tests for both.

* test(cli): pin that upgrade reaches the authoring codemods (F6)

The v0.3.0 authoring codemods are registered at the codemod registry's top
version and only run when installed @astryxdesign/core has reached that version.
Because core ships in the same fixed-version release group as the CLI, a
released core does reach it — but nothing pinned that invariant, so a future
registry entry above the shipped core version would silently strand the
migration (the chaos-test 'codemods unreachable' finding). This test drives
`astryx upgrade` against a project whose installed core is at the registry
latest and asserts an old-surface authoring file is rewritten, plus that
latestVersion tracks the top registry version.

* docs(cli): fix stale comments left by the authoring/surface reorg

Three JSDoc comments described the pre-reorg layout or the removed create*
factories:
- build-theme.mjs: said the module lives at src/commands/ and resolves the bin
  via ../../bin/astryx.mjs; it is at clients/cli/commands/ and correctly uses
  ../bin/astryx.mjs.
- integration-runner.mjs / runner.mjs: referenced createCodemod /
  createConfigCodemod, which v0.3.0 removed. Codemods are now plain objects
  stamped type: 'code' | type: 'config'.

Comment-only; no behavior change.

* docs(changeset): add changeset for the CLI verbose/themes/codemod fixes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(upgrade): token rename codemod corrupts .toString() and .toLocaleString() calls

1 participant