Skip to content

Conversation

@andrewjschuang
Copy link
Contributor

@andrewjschuang andrewjschuang commented May 21, 2025

WHY

Summary by CodeRabbit

  • New Features
    • Introduced a new action enabling users to extract text matches from input using multiple regular expressions, delivering detailed results including matched text, capture groups, and positions in both map and list formats.

@vercel
Copy link

vercel bot commented May 21, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview May 21, 2025 1:54pm
pipedream-docs ⬜️ Ignored (Inspect) May 21, 2025 1:54pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) May 21, 2025 1:54pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 21, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

A new Pipedream action module was introduced to extract matches from a text input using a list of regular expressions. The module defines input properties, processes each regex, collects match details, and returns results in both map and list formats, including match text, groups, and positions. Additionally, the package version was incremented.

Changes

File(s) Change Summary
components/pipedream_utils/actions/extract-by-regular-expressions-list/extract-by-regular-expressions-list.mjs Added a new Pipedream action module to extract matches from input text using multiple regex patterns, returning detailed match information.
components/pipedream_utils/package.json Incremented package version from 0.0.3 to 0.0.4 without other changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PipedreamAction

    User->>PipedreamAction: Provide input text and list of regex strings
    PipedreamAction->>PipedreamAction: For each regex, compile and match against input
    PipedreamAction->>PipedreamAction: Collect matches (text, groups, positions)
    PipedreamAction->>User: Return results as map and list with summary
Loading

Poem

In regex fields where patterns play,
A bunny hops to parse the way.
Each string is searched, each match is found,
With groups and spots all neatly bound.
Now data’s sorted, crisp and clear—
Regex magic, bunny cheer! 🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 877ee2a and 4c389cc.

📒 Files selected for processing (1)
  • components/pipedream_utils/package.json (1 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
components/pipedream_utils/actions/extract-by-regular-expressions-list/extract-by-regular-expressions-list.mjs (1)

75-79: Consider adding match examples in the returned output.

For improved user experience, consider including a few example matches in the summary or adding a separate field with sample matches to help users verify their regex patterns are working as expected.

 return {
   map: resultMap,
   list: resultList,
+  examples: totalMatches ? getSampleMatches(resultList, 3) : []
 };

You could implement a helper method like:

getSampleMatches(resultList, count) {
  const samples = [];
  for (const matches of resultList) {
    if (matches.length > 0) {
      samples.push(matches[0].match);
      if (samples.length >= count) break;
    }
  }
  return samples;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 7918c48 and 877ee2a.

📒 Files selected for processing (1)
  • components/pipedream_utils/actions/extract-by-regular-expressions-list/extract-by-regular-expressions-list.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Publish TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Lint Code Base
  • GitHub Check: Verify TypeScript components
🔇 Additional comments (5)
components/pipedream_utils/actions/extract-by-regular-expressions-list/extract-by-regular-expressions-list.mjs (5)

1-8: Component metadata and imports look appropriate.

The action is well-named and descriptive, following Pipedream's naming conventions. Version 0.0.1 is correct for a new component.


9-21: Props definitions are comprehensive.

The prop definitions provide helpful descriptions and appropriate types. The regex description includes a link to documentation which is a nice touch for users.


27-33: Good handling of empty or invalid regex strings.

The code correctly handles empty regex strings by pushing an empty array to preserve the order in the results list, which is important for consistency.


41-48: Thorough match extraction with detailed information.

The code efficiently uses matchAll() and effectively extracts all relevant information including the matched text, capture groups, and positions. The null coalescing operator for groups is a nice touch for handling cases where no named groups exist.


60-74: Robust output summary implementation.

The summary export provides useful information about the number of matches found, with appropriate handling for both match and no-match scenarios.

Comment on lines +35 to +39
const re = rStr.startsWith("/")
? buildRegExp(rStr, [
"g",
])
: new RegExp(rStr, "g");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding RegExp validation and error handling.

The code handles different regex formats but doesn't protect against invalid regex patterns that might throw exceptions.

 const re = rStr.startsWith("/")
   ? buildRegExp(rStr, [
     "g",
   ])
   : new RegExp(rStr, "g");
+ 
+ // Add try/catch to handle invalid regex patterns

Consider wrapping the RegExp creation in a try/catch block to gracefully handle syntax errors in user-provided regex patterns:

try {
  const re = rStr.startsWith("/")
    ? buildRegExp(rStr, ["g"])
    : new RegExp(rStr, "g");
  
  // Process matches...
} catch (error) {
  console.log(`Invalid regex pattern: ${rStr}. Error: ${error.message}`);
  resultMap[rStr] = [];
  resultList.push([]);
  continue;
}
🤖 Prompt for AI Agents
In
components/pipedream_utils/actions/extract-by-regular-expressions-list/extract-by-regular-expressions-list.mjs
around lines 35 to 39, the RegExp creation does not handle invalid regex
patterns which can throw exceptions. Wrap the RegExp creation code in a
try/catch block to catch syntax errors from user-provided regex strings. In the
catch block, log the error message indicating the invalid pattern, assign an
empty array to the corresponding resultMap entry, push an empty array to
resultList, and continue processing the next regex pattern.

Comment on lines +1 to +80
import buildRegExp from "../../common/text/buildRegExp.mjs";
import pipedream_utils from "../../pipedream_utils.app.mjs";
export default {
name: "Formatting - [Text] Extract by Regular Expressions List (Regex)",
description: "Find matches for regular expressions. Returns all matched groups with start and end position.",
key: "pipedream_utils-extract-by-regular-expressions-list",
version: "0.0.1",
type: "action",
props: {
pipedream_utils,
input: {
type: "string",
label: "Input",
description: "Text you would like to find a pattern from",
},
regExpStrings: {
type: "string[]",
label: "Regular Expressions",
description: "An array of [regex strings](https://www.w3schools.com/js/js_regexp.asp) (e.g. `/foo/g`, `/bar/i`)",
},
},
methods: {
getAllResults(input) {
const resultMap = {};
const resultList = [];

for (const rStr of this.regExpStrings) {
if (typeof rStr !== "string" || !rStr.length) {
// still push an empty array to preserve order
resultMap[rStr] = [];
resultList.push([]);
continue;
}

const re = rStr.startsWith("/")
? buildRegExp(rStr, [
"g",
])
: new RegExp(rStr, "g");

const matches = [
...input.matchAll(re),
].map((m) => ({
match: m[0],
groups: m.groups ?? {},
startPosition: m.index,
endPosition: m.index + m[0].length,
}));

resultMap[rStr] = matches;
resultList.push(matches);
}

return {
resultMap,
resultList,
};
},
},
async run({ $ }) {
const {
resultMap,
resultList,
} = this.getAllResults(this.input);

const totalMatches = resultList.reduce((sum, arr) => sum + arr.length, 0);

$.export(
"$summary",
totalMatches
? `Found ${totalMatches} matches across ${Object.keys(resultMap).length} patterns`
: "No matches found",
);

return {
map: resultMap,
list: resultList,
};
},
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Consider adding protection against ReDoS attacks.

Regular expressions provided by users could potentially cause Regular Expression Denial of Service (ReDoS) attacks if they contain patterns with catastrophic backtracking.

Consider implementing:

  1. A timeout mechanism for regex execution
  2. Complexity analysis of user-provided regexes
  3. A maximum limit on input length for large regex lists

🌐 Web query:

What are best practices to prevent ReDoS (Regular Expression Denial of Service) attacks in JavaScript?

💡 Result:

Best Practices to Prevent ReDoS Attacks in JavaScript

Regular Expression Denial of Service (ReDoS) vulnerabilities occur when poorly structured regular expressions allow attackers to supply input that causes excessive backtracking. This can hang or crash JavaScript applications, especially in single-threaded Node.js environments[3][4].

Below are the best practices to prevent and mitigate ReDoS attacks in JavaScript:


1. Avoid Vulnerable Patterns

  • Do not nest quantifiers: Patterns like (a+)+, (a|a)+, and similar possess exponential worst-case behavior and are the most notorious for catastrophic backtracking[3].
  • Avoid quantified overlapping disjunctions: For example, (a|b|ab)+ can be problematic when input allows ambiguous matches[3].
  • Be wary of adjacent quantified patterns: Patterns like (\d+\d+) can also cause issues[3].

2. Use Bounded Quantifiers and Possessive Patterns

  • Bound repetitions: Always prefer quantifiers like {min,max} over unlimited + or *. For example, /a{1,5}/ is safer than /a+/[7].
  • Use possessive quantifiers or atomic groups: In regex engines that support them, these prevent backtracking within certain subpatterns. While JavaScript’s regex does not natively support possessive quantifiers, structuring patterns to avoid ambiguous matches helps[7].

3. Validate and Sanitize Input Used in Regex Construction

  • Never include untrusted user input directly in a regex pattern. If you must, always escape special characters using libraries like lodash.escaperegexp[5].
  • Sanitize and filter user input: Remove or encode regex metacharacters to prevent injection attacks[5].

4. Limit Input Length

  • Restrict the length of user-provided data processed by regexes. This lessens the potential impact of any slow pattern match[5].

5. Use Proven and Reviewed Patterns

  • Rely on regexes from trusted sources: Use vetted patterns, such as from the [OWASP Validation Regex Repository][3].
  • Regularly audit third-party dependencies: Many open source packages include regexes that might be exploitable[4].

6. Set Timeouts or Monitor Execution

  • Implement regular expression timeouts: In environments that support it, abort regex matches that take too long[6]. While JavaScript engines often lack built-in timeout controls for regex, you can run regex operations in Web Workers or separate processes, kill them after a threshold, or use libraries that provide safer execution environments.

7. Test and Visualize Regex Performance

  • Bench test critical regexes: Use fuzzers or input generators to test regexes with increasingly long inputs to detect performance cliffs[8].
  • Visualize or lint regexes: Use regex debuggers or linters to spot problematic patterns.

8. Educate Developers and Review Regular Expressions

  • Train teams to recognize “evil regex” patterns.
  • Code review should include scrutiny of regexes for both correctness and performance concerns.

Summary Table: Common ReDoS Mitigation Strategies

Strategy Description
Avoid nested/ambiguous quantifiers Prevents exponential backtracking
Bound repetitions Use {min,max} quantifiers
Escape user input in regexes Prevents injection attacks
Limit input length Reduces surface for DoS
Use vetted regex patterns Reduces likelihood of vulnerabilities
Set regex execution timeouts Mitigates impact if match runs too long
Audit and test regexes Ensures performance and avoids vulnerable patterns

Key Takeaway:
Avoid complex, nested, or ambiguous regex patterns, escape and sanitize all user input used in regex construction, limit the size of input, and prefer reviewed, bounded, and safe regexes. Regularly test and audit regex use—and remember that in JavaScript’s single-threaded environment, a problematic regex can block your entire app[3][4][5][7].

Citations:


I’d like to inspect how buildRegExp constructs regexes to confirm if it includes any sanitization or limits:


🏁 Script executed:

#!/bin/bash
# Locate and display the buildRegExp implementation
fd buildRegExp.mjs

Length of output: 75


🏁 Script executed:

#!/bin/bash
# Display the contents of buildRegExp to check for sanitization or safety mechanisms
sed -n '1,200p' components/pipedream_utils/common/text/buildRegExp.mjs

Length of output: 522


Mitigate ReDoS Risks in User-Supplied Regexes

The current implementation in
components/pipedream_utils/actions/extract-by-regular-expressions-list/extract-by-regular-expressions-list.mjs
and its use of buildRegExp allows arbitrary, unchecked patterns to be executed via String.prototype.matchAll(). In a single-threaded environment, a malicious or pathological regex (e.g. nested quantifiers) can trigger catastrophic backtracking and block the event loop.

Suggested fixes:

  • Enforce a maximum input length (e.g. 10 KB) in run() or getAllResults() before any matching.
  • Pre-validate each regExpStrings entry against a simple complexity check (reject patterns with nested quantifiers like (a+)+).
  • Offload heavy regex matching into a worker or separate process with a timeout/abort controller to kill long-running matches.
  • (Optional) Escape or whitelist safe patterns when possible, using a library like lodash.escapeRegExp for literal inputs.

File locations to update:

  • components/pipedream_utils/actions/extract-by-regular-expressions-list/extract-by-regular-expressions-list.mjs
  • components/pipedream_utils/common/text/buildRegExp.mjs
🤖 Prompt for AI Agents
In
components/pipedream_utils/actions/extract-by-regular-expressions-list/extract-by-regular-expressions-list.mjs
lines 1 to 80, the current code executes user-provided regexes without
safeguards, risking ReDoS attacks. To fix this, add a maximum input length check
(e.g., 10 KB) in the run() or getAllResults() method to reject overly large
inputs. Implement a pre-validation step on each regex string to detect and
reject patterns with nested quantifiers or other high-complexity constructs.
Consider offloading regex matching to a worker or separate process with a
timeout to abort long-running matches. Optionally, sanitize or escape regex
strings when possible to avoid injection of unsafe patterns.

@andrewjschuang andrewjschuang merged commit 5784a41 into master May 21, 2025
9 of 11 checks passed
@andrewjschuang andrewjschuang deleted the utils-regexes branch May 21, 2025 13:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants