Potential fix for code scanning alert no. 8: Regular expression injection #1081
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Potential fix for https://github.com/ffflorian/node-packages/security/code-scanning/8
In general, to fix regex injection you must ensure any user‑controlled string embedded into a
RegExppattern is first escaped so all regex metacharacters lose their special meaning. That means either (a) using a well‑tested escaping helper (for exampleescape-string-regexpor lodash’sescapeRegExp), or (b) writing a small local escaping function.Here, the single best fix is to escape
this.dirToFlattenright before using it to constructdirToFlattenRegex. We can add a small local helper function inPublishFlat(or a top‑level function in the same file) that escapes regex meta‑characters, and then build the regex from the escaped value. This preserves all existing semantics (we still match directory prefixes followed by/or\) while preventing users from injecting arbitrary regex fragments.Concretely, in
packages/publish-flat/src/PublishFlat.ts:escapeRegExpthat replaces all regex metacharacters ([.*+?^${}()|[\]\\]) with escaped versions.this.dirToFlatten = this.cleanDirName(...), callthis.escapeRegExp(this.dirToFlatten)and use that escaped string when constructingthis.dirToFlattenRegex.cli.ts; it will continue to pass the raw argument, which is now safely escaped insidePublishFlat.No new imports are necessary because the escaping can be implemented in a few lines.
Suggested fixes powered by Copilot Autofix. Review carefully before merging.