AGENT SKILL

regex-escape-redos-guard

暂无简介

License 许可
Apache-2.0
最近更新
2026-11-11
Stars
★ 13
Forks
1

03 SKILL.md 正文

/regex-escape-redos-guard

When to Use

  • Building regex from user input or agent-supplied strings
  • Search/replace where the pattern comes from config/user data
  • Escaping file names, URLs, or shell strings before regex use
  • Detecting and blocking catastrophically backtracking patterns

Do NOT use for

  • Sanitizing HTML/code content (use [[dompurify-xss-prevention]])
  • Validating regex syntax (use a dedicated regex linter)

Basic escaping

import escapeStringRegexp from 'escape-string-regexp'

function safeSearch(haystack: string, needle: string, flags = 'gi'): RegExpMatchArray | null {
  const escaped = escapeStringRegexp(needle)
  // All regex special chars escaped: . * + ? ^ $ { } [ ] | ( ) \
  return haystack.match(new RegExp(escaped, flags))
}

// Without escaping — DANGEROUS:
// const re = new RegExp(userInput) ← ReDoS if userInput = '(a+)+'
// With escaping — safe:
const re = new RegExp(escapeStringRegexp(userInput))

DIY escaping (no dependency)

// escape-string-regexp implementation (tiny, copy inline if preferred)
function escapeRegex(str: string): string {
  return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')
}

ReDoS patterns to reject (denylist)

// Patterns with catastrophic backtracking potential
const REDOS_PATTERNS = [
  /\(.*\+\).*\+/,    // (a+)+
  /\(.*\*\).*\*/,    // (a*)*
  /\(.*\|\).*\|/,    // alternation with empty branches
  /\.\*.*\.\*/,      // .*.* — exponential on non-matching input
]

function isReDoSSafe(pattern: string): boolean {
  return !REDOS_PATTERNS.some(r => r.test(pattern))
}

// Reject before compiling
function safeRegex(pattern: string, flags = ''): RegExp {
  if (!isReDoSSafe(pattern)) {
    throw new Error(`[regex] potentially catastrophic pattern: ${pattern}`)
  }
  return new RegExp(pattern, flags)
}

Timeout guard (Node.js worker thread)

import { Worker, isMainThread, workerData, parentPort } from 'worker_threads'

// Run regex in a worker with a timeout to kill it if it hangs
function regexWithTimeout(
  input:    string,
  pattern:  string,
  timeoutMs = 100
): Promise<string[] | null> {
  return new Promise((resolve, reject) => {
    const worker = new Worker(__filename, {
      workerData: { input, pattern }
    })
    const timer = setTimeout(() => {
      worker.terminate()
      reject(new Error('[regex] timeout — possible ReDoS'))
    }, timeoutMs)

    worker.on('message', (result) => { clearTimeout(timer); resolve(result) })
    worker.on('error',   (err)    => { clearTimeout(timer); reject(err) })
  })
}

if (!isMainThread) {
  const { input, pattern } = workerData
  const match = input.match(new RegExp(pattern, 'g'))
  parentPort!.postMessage(match)
}

Anti-Fake-Pass Checklist

❌ new RegExp(userInput) without escaping → ReDoS or injection of any pattern
❌ denylist pattern approach alone (imperfect) → pair with escaping or timeout
❌ Timeout guard kills worker but request hangs → must resolve/reject in timeout handler
❌ Flag 'g' + lastIndex not reset → regex object stateful, skips matches on second call
❌ Backslash in input not escaped → \\w in user input becomes \w (wildcard) in regex

04 同仓库更多 Skills

Horonomos-laps
Horonomos-laps/Yana-AI

openai--sentry--sentry

Use when the user asks to inspect Sentry issues or events, summarize recent production errors, or pull basic Sentry health data via the Sentry API; perform read-only queries with the bundled script and require `SENTRY_AUTH_TOKEN`.

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

ito-basket-compare

Compare Itô prediction-market baskets against a user's knowledge base, portfolio notes, financial context, watchlist, or research thesis. Use for read-only basket comparison and gap analysis without investment advice or live trading.

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

implementing-network-traffic-baselining

Build network traffic baselines from NetFlow/IPFIX data using Python pandas for statistical analysis, z-score anomaly detection, and hourly/daily traffic pattern profiling

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

detecting-evasion-techniques-in-endpoint-logs

Detects defense evasion techniques used by adversaries in endpoint logs including log tampering, timestomping, process injection, and security tool disabling. Use when investigating suspicious endpoint behavior, building detection rules for evasion tactics, or conducting threat hunting for stealthy adversary activity. Activates for requests involving evasion detection, defense evasion analysis, log tampering detection, or MITRE ATT&CK TA0005.

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

implementing-microsegmentation-with-guardicore

Implementing microsegmentation using Akamai Guardicore Segmentation to map application dependencies, create granular network policies, visualize east-west traffic flows, and enforce least-privilege communication between workloads across data centers and cloud.

★ 13
Horonomos-laps
Horonomos-laps/Yana-AI

ramdisk-tmpfs-patterns

暂无简介

★ 13