{"version":3,"file":"matchers.cjs","sources":["../../../src/hooks/matchers.ts"],"sourcesContent":["// src/hooks/matchers.ts\n\n/**\n * Upper bound on hook-matcher pattern length. Patterns longer than this\n * are rejected outright — the goal is a cheap cap on pathological inputs\n * (repeated quantifiers, huge alternation groups) without pulling in a\n * safe-regex dependency.\n *\n * Legitimate matchers are almost always under 50 characters (tool names,\n * short alternations, simple prefix anchors); 512 leaves generous\n * headroom while preventing 10KB regexes.\n */\nexport const MAX_PATTERN_LENGTH = 512;\n\n/**\n * Upper bound on the compilation cache. Chosen to comfortably hold every\n * distinct pattern a single multi-tenant run is likely to see (tools,\n * agent types, basename filters) without growing without bound.\n *\n * Under hosts that register unique patterns per tenant, LRU eviction\n * keeps the working set bounded — cold patterns are re-compiled on next\n * use, which is the correct cost trade-off for long-running processes\n * that must not leak memory.\n */\nexport const MAX_CACHE_SIZE = 256;\n\ninterface CacheEntry {\n  regex: RegExp | null;\n}\n\n/**\n * Module-level LRU cache keyed by pattern string. Map iteration order is\n * insertion order in ECMAScript, so refreshing an entry's position means\n * \"delete then re-set\". On overflow we evict the first key (least\n * recently used).\n *\n * Failed compiles are cached as `{ regex: null }` so a malformed pattern\n * does not re-enter the compiler — and so a tenant spamming bad patterns\n * doesn't burn CPU on every call.\n */\nconst patternCache: Map<string, CacheEntry> = new Map();\n\n/**\n * Threshold above which `touchCacheEntry` actually performs the LRU\n * refresh. Below this watermark the cache has zero eviction pressure, so\n * the delete+set on every hit would be pure overhead. Above it we refresh\n * properly so hot patterns survive evictions. 75% of capacity is the\n * standard sweet spot.\n */\nconst LRU_REFRESH_THRESHOLD = Math.floor((MAX_CACHE_SIZE * 3) / 4);\n\nfunction touchCacheEntry(pattern: string, entry: CacheEntry): void {\n  if (patternCache.size < LRU_REFRESH_THRESHOLD) {\n    return;\n  }\n  patternCache.delete(pattern);\n  patternCache.set(pattern, entry);\n}\n\nfunction setCacheEntry(pattern: string, entry: CacheEntry): void {\n  if (patternCache.size >= MAX_CACHE_SIZE) {\n    const oldestKey = patternCache.keys().next().value;\n    if (oldestKey !== undefined) {\n      patternCache.delete(oldestKey);\n    }\n  }\n  patternCache.set(pattern, entry);\n}\n\ninterface QuantifierFrame {\n  hasBacktrackRisk: boolean;\n}\n\nfunction skipGroupSyntaxPrefix(pattern: string, start: number): number {\n  if (start >= pattern.length || pattern[start] !== '?') {\n    return start;\n  }\n  let i = start + 1;\n  if (i >= pattern.length) {\n    return i;\n  }\n  const modifier = pattern[i];\n  if (modifier === ':' || modifier === '=' || modifier === '!') {\n    return i + 1;\n  }\n  if (modifier !== '<') {\n    return i;\n  }\n  i++;\n  if (i < pattern.length && (pattern[i] === '=' || pattern[i] === '!')) {\n    return i + 1;\n  }\n  while (i < pattern.length && pattern[i] !== '>') {\n    i++;\n  }\n  if (i < pattern.length) {\n    i++;\n  }\n  return i;\n}\n\n/**\n * Cheap syntactic detector for the most common catastrophic-backtracking\n * shape: a quantified group that contains another quantifier (e.g.\n * `(a+)+`, `(.*)*`, `(\\w+)+$`, `(?:(a+))+`). This is the \"nested\n * quantifier\" class of ReDoS — runs in polynomial-or-worse time on\n * adversarial inputs.\n *\n * The scan walks the pattern linearly using an explicit stack of group\n * frames. For each group it tracks whether the group's contents include\n * \"backtrack risk\" — meaning a direct quantifier OR a nested group that\n * carries risk up. When a group closes with a trailing quantifier AND its\n * frame carries backtrack risk, the pattern is flagged. Risk propagates\n * to the enclosing frame when a child group closes (whether the child\n * itself was quantified or not), so `(?:(a+))+` — equivalent to `(a+)+`\n * — is flagged correctly even though the outer non-capturing wrapper is\n * one level removed from the inner quantifier.\n *\n * ## Group-syntax prefixes\n *\n * Non-capturing groups (`(?:`), lookaheads (`(?=`, `(?!`), lookbehinds\n * (`(?<=`, `(?<!`), and named groups (`(?<name>`) are skipped over at\n * the `(` so their `?` is not misread as a quantifier. Without this,\n * `(?:pre_)?tool_name` would be incorrectly rejected because the scanner\n * would see the group-syntax `?` as a quantifier at depth 1.\n *\n * ## Heuristic, not a proof\n *\n * This catches the common forms but not all. Ambiguous-alternation ReDoS\n * like `(a|a)+` is not detected. Pathologically long patterns are also\n * caught by {@link MAX_PATTERN_LENGTH}. Hosts that accept user-supplied\n * patterns must still validate upstream.\n */\nexport function hasNestedQuantifier(pattern: string): boolean {\n  const stack: QuantifierFrame[] = [];\n  let i = 0;\n  while (i < pattern.length) {\n    const ch = pattern[i];\n    if (ch === '\\\\') {\n      i += 2;\n      continue;\n    }\n    if (ch === '[') {\n      i = findCharClassEnd(pattern, i) + 1;\n      continue;\n    }\n    if (ch === '(') {\n      stack.push({ hasBacktrackRisk: false });\n      i = skipGroupSyntaxPrefix(pattern, i + 1);\n      continue;\n    }\n    if (ch === ')') {\n      const frame = stack.pop();\n      if (frame === undefined) {\n        i++;\n        continue;\n      }\n      const next = pattern[i + 1];\n      const isQuantifier =\n        next === '*' || next === '+' || next === '?' || next === '{';\n      if (isQuantifier && frame.hasBacktrackRisk) {\n        return true;\n      }\n      if (stack.length > 0 && (frame.hasBacktrackRisk || isQuantifier)) {\n        stack[stack.length - 1].hasBacktrackRisk = true;\n      }\n      i++;\n      continue;\n    }\n    if (ch === '*' || ch === '+' || ch === '?' || ch === '{') {\n      if (stack.length > 0) {\n        stack[stack.length - 1].hasBacktrackRisk = true;\n      }\n    }\n    i++;\n  }\n  return false;\n}\n\nfunction findCharClassEnd(pattern: string, start: number): number {\n  let i = start + 1;\n  while (i < pattern.length) {\n    const ch = pattern[i];\n    if (ch === '\\\\') {\n      i += 2;\n      continue;\n    }\n    if (ch === ']') {\n      return i;\n    }\n    i++;\n  }\n  return pattern.length - 1;\n}\n\nfunction compile(pattern: string): RegExp | null {\n  const cached = patternCache.get(pattern);\n  if (cached !== undefined) {\n    touchCacheEntry(pattern, cached);\n    return cached.regex;\n  }\n  if (pattern.length > MAX_PATTERN_LENGTH) {\n    setCacheEntry(pattern, { regex: null });\n    return null;\n  }\n  if (hasNestedQuantifier(pattern)) {\n    setCacheEntry(pattern, { regex: null });\n    return null;\n  }\n  try {\n    const regex = new RegExp(pattern);\n    setCacheEntry(pattern, { regex });\n    return regex;\n  } catch {\n    setCacheEntry(pattern, { regex: null });\n    return null;\n  }\n}\n\n/**\n * Tests whether a hook matcher pattern matches the given query string.\n *\n * ## Semantics\n *\n * - `undefined` or empty `pattern` matches any query (wildcard). This is\n *   the intended shape for events that do not supply a query string at\n *   all (`RunStart`, `Stop`, etc.) — register such matchers without a\n *   pattern.\n * - `undefined` or empty `query` with a non-empty `pattern` never matches.\n *   Setting a pattern on a query-less event is therefore inert: the\n *   matcher will simply never fire. This is intentional — it keeps\n *   query-based filtering out of event types where \"query\" has no meaning,\n *   and is documented on `HookMatcher.pattern`.\n * - Otherwise, the pattern is compiled once (via a bounded LRU cache) and\n *   tested against the query.\n * - Invalid regex patterns never throw — a failed compile is cached as\n *   \"never matches\" so a single malformed pattern cannot take out a whole\n *   `executeHooks` batch.\n *\n * ## ReDoS mitigations\n *\n * Patterns compile through three cheap gates before reaching `new RegExp`:\n *\n * 1. {@link MAX_PATTERN_LENGTH} length cap rejects oversized inputs.\n * 2. {@link hasNestedQuantifier} rejects the most common catastrophic-\n *    backtracking shape (quantified group containing a quantifier).\n * 3. Successful compiles are cached in a bounded LRU so repeated calls\n *    never re-enter the regex compiler.\n *\n * These are a floor, not a ceiling. Hosts that accept user-supplied\n * patterns should still validate upstream. The design report §3.8 routes\n * persistable hooks through a host-side compiler before they reach this\n * module.\n */\nexport function matchesQuery(\n  pattern: string | undefined,\n  query: string | undefined\n): boolean {\n  if (pattern === undefined || pattern === '') {\n    return true;\n  }\n  if (query === undefined || query === '') {\n    return false;\n  }\n  const regex = compile(pattern);\n  if (regex === null) {\n    return false;\n  }\n  return regex.test(query);\n}\n\n/** Clears the regex compilation cache. Intended for test isolation. */\nexport function clearMatcherCache(): void {\n  patternCache.clear();\n}\n\n/** Returns the current size of the compilation cache. Intended for tests. */\nexport function getMatcherCacheSize(): number {\n  return patternCache.size;\n}\n"],"names":[],"mappings":";;AAAA;AAEA;;;;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