@juspay/neurolink
Version:
The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002
47 lines (46 loc) • 2.55 kB
TypeScript
import type { RegexPatternVerdict } from "../../types/index.js";
/**
* Static vetting for regular expressions that a caller hands to the
* guardrails (`badWords.regexPatterns`, `precallEvaluation.sanitizationPatterns`).
*
* Both lists are compiled and run synchronously on the event loop against the
* whole model response, so one pattern that backtracks catastrophically
* (`(a+)+$` on a run of `a`) stalls every request in the process. A timing
* probe on a short fixed string cannot find that: the cost only shows on long
* adversarial input, and it is measured after the call has already returned.
* This reads the pattern instead.
*
* The cause of every exponential case is one input that can be split between
* the parts of the pattern in many ways. A variable-length part (`a+`, `a?`,
* `a{1,3}`, `(ab)*`) is ambiguous when what can follow it may start with text
* the part itself can match. The check refuses a pattern when:
*
* - such a part sits inside a repeated group (`(a+)+`, `(a?a?)+`,
* `(a{1,30}){1,30}`), where the ways multiply on every iteration;
* - the alternatives of a repeated group may overlap (`(a|aa)+`);
* - ambiguous parts are chained: more than {@link MAX_NARROW_WAYS} ways in
* total from optional or short parts (`a?` nine times in a row), or more
* than {@link MAX_OPEN_AMBIGUITY} open-ended ones (`.*a.*b.*c.*d.*e`);
* - a repetition bound is above {@link MAX_REPETITION_BOUND}, or the pattern
* is longer than {@link MAX_REGEX_PATTERN_LENGTH}.
*
* A variable-length part that is followed by something it cannot match is
* unambiguous, so `(\d{1,3}\.){3}`, `([a-z0-9-]+\.)+` and `(?:\d[ -]?){13,16}`
* run.
*
* It is deliberately conservative, not a proof. Two classes are compared on a
* fixed sample of characters (Latin text plus a few other scripts), so a class
* that only overlaps outside the sample looks disjoint, and a back-reference
* is assumed to overlap with everything. A hard guarantee would need a time
* budget around the match itself (a `node:vm` timeout or a worker), which a
* synchronous `String.replace` cannot offer; that is a follow-up.
*/
/** Longest pattern accepted, in characters. */
export declare const MAX_REGEX_PATTERN_LENGTH = 1000;
/**
* Decide whether a caller-supplied pattern may be compiled and run.
*
* Total: it returns a verdict for any string and never throws, so a caller can
* skip a refused pattern the same way it skips an invalid one.
*/
export declare function vetRegexPattern(pattern: string): RegexPatternVerdict;