@posthog/core 1.69.6 → 1.69.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,14 @@
1
1
  import type { Properties } from '@posthog/types';
2
2
  import type { PropertyFilters, PropertyOperator } from '../types';
3
3
  export declare const isValidRegex: (pattern: string) => boolean;
4
+ /**
5
+ * Detects repeated groups that can backtrack exponentially or polynomially, which would stall the
6
+ * synchronous capture path. A group repeated more than once that contains a variable-length term, as in
7
+ * `(a+)+` or `(a{1,3}){20}`, is flagged unless a required delimiter that no other term can match splits
8
+ * every iteration, as in `(?:/[^/]+)*` or `([0-9]{1,3}\.){3}`.
9
+ * Overlapping alternation such as `(a|a)*` is not detected.
10
+ */
11
+ export declare const hasNestedQuantifier: (pattern: string) => boolean;
4
12
  export declare const isMatchingRegex: (value: string, pattern: string) => boolean;
5
13
  export declare const propertyComparisons: Record<PropertyOperator, (targets: string[], values: string[]) => boolean>;
6
14
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"property-matching.d.ts","sourceRoot":"","sources":["../../src/surveys/property-matching.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAEhD,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAEjE,eAAO,MAAM,YAAY,YAAa,MAAM,KAAG,OAO9C,CAAA;AAED,eAAO,MAAM,eAAe,UAAW,MAAM,WAAW,MAAM,KAAG,OAUhE,CAAA;AAID,eAAO,MAAM,mBAAmB,EAAE,MAAM,CAAC,gBAAgB,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,OAAO,CAmB1G,CAAA;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,eAAe,EAAE,UAAU,GAAG,SAAS,GACtC,OAAO,CAmBT"}
1
+ {"version":3,"file":"property-matching.d.ts","sourceRoot":"","sources":["../../src/surveys/property-matching.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAEhD,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAEjE,eAAO,MAAM,YAAY,YAAa,MAAM,KAAG,OAO9C,CAAA;AAkKD;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,YAAa,MAAM,KAAG,OAoGrD,CAAA;AA8DD,eAAO,MAAM,eAAe,UAAW,MAAM,WAAW,MAAM,KAAG,OAWhE,CAAA;AAID,eAAO,MAAM,mBAAmB,EAAE,MAAM,CAAC,gBAAgB,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,OAAO,CAqB1G,CAAA;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,eAAe,EAAE,UAAU,GAAG,SAAS,GACtC,OAAO,CAmBT"}
@@ -35,10 +35,267 @@ const isValidRegex = (pattern)=>{
35
35
  }
36
36
  return true;
37
37
  };
38
+ const quantifierAt = (pattern, index)=>{
39
+ const character = pattern[index];
40
+ if ('*' === character) return {
41
+ length: 1,
42
+ min: 0,
43
+ max: 1 / 0
44
+ };
45
+ if ('+' === character) return {
46
+ length: 1,
47
+ min: 1,
48
+ max: 1 / 0
49
+ };
50
+ if ('?' === character) return {
51
+ length: 1,
52
+ min: 0,
53
+ max: 1
54
+ };
55
+ if ('{' !== character) return null;
56
+ const repetition = /^\{(\d+)(,(\d*))?\}/.exec(pattern.slice(index));
57
+ if (!repetition) return null;
58
+ const min = Number(repetition[1]);
59
+ const max = repetition[2] ? '' === repetition[3] ? 1 / 0 : Number(repetition[3]) : min;
60
+ return {
61
+ length: repetition[0].length,
62
+ min,
63
+ max
64
+ };
65
+ };
66
+ const newGroup = (flags)=>({
67
+ atoms: [],
68
+ variable: false,
69
+ complex: false,
70
+ flags
71
+ });
72
+ const MODIFIER_GROUP_PREFIX = /^\(\?([ims]*)(?:-([ims]*))?:/;
73
+ const applyModifiers = (flags, added, removed)=>[
74
+ 'i',
75
+ 's'
76
+ ].filter((flag)=>removed.indexOf(flag) < 0 && (flags + added).indexOf(flag) >= 0).join('');
77
+ const ESCAPED_CONTROL_CHARACTERS = {
78
+ n: '\n',
79
+ r: '\r',
80
+ t: '\t',
81
+ f: '\f',
82
+ v: '\v'
83
+ };
84
+ const isRequiredLiteral = (atom)=>void 0 !== atom.literal && atom.min === atom.max && atom.min > 0;
85
+ const MAX_DELIMITER_CHECKS = 10000;
86
+ const spellings = (character, ignoreCase)=>ignoreCase ? [
87
+ character,
88
+ character.toUpperCase()
89
+ ] : [
90
+ character
91
+ ];
92
+ const collectGroupFacts = (group, ignoreCase)=>{
93
+ const facts = {
94
+ delimiterPositions: Object.create(null),
95
+ optionalLiterals: Object.create(null),
96
+ literalsBySpelling: Object.create(null),
97
+ nonLiteralSources: [],
98
+ variableTermsBefore: [],
99
+ variableTerms: 0
100
+ };
101
+ const seenSources = Object.create(null);
102
+ group.atoms.forEach((atom, position)=>{
103
+ facts.variableTermsBefore.push(facts.variableTerms);
104
+ if (atom.max > atom.min) facts.variableTerms++;
105
+ const literal = atom.literal;
106
+ if (void 0 === literal) {
107
+ if (!atom.zeroWidth && !seenSources[atom.source]) {
108
+ seenSources[atom.source] = true;
109
+ facts.nonLiteralSources.push(atom.source);
110
+ }
111
+ return;
112
+ }
113
+ if (isRequiredLiteral(atom)) (facts.delimiterPositions[literal] ||= []).push(position);
114
+ else facts.optionalLiterals[literal] = true;
115
+ spellings(literal, ignoreCase).forEach((spelling)=>{
116
+ const owner = facts.literalsBySpelling[spelling];
117
+ facts.literalsBySpelling[spelling] = void 0 === owner || owner === literal ? literal : null;
118
+ });
119
+ });
120
+ return facts;
121
+ };
122
+ const compileAtomTests = (sources, flags)=>sources.map((source)=>{
123
+ try {
124
+ return new RegExp(`^(?:${source})$`, flags);
125
+ } catch {
126
+ return /[^]/;
127
+ }
128
+ });
129
+ const isSoleMatchOf = (delimiter, facts, ignoreCase, atomTests)=>!facts.optionalLiterals[delimiter] && spellings(delimiter, ignoreCase).every((spelling)=>facts.literalsBySpelling[spelling] === delimiter) && !atomTests.some((atomTest)=>atomTest.test(delimiter));
130
+ const hasAtMostOneVariableTermPerSegment = (occurrences, facts)=>{
131
+ const before = facts.variableTermsBefore;
132
+ for(let i = 0; i < occurrences.length; i++){
133
+ const end = i + 1 < occurrences.length ? before[occurrences[i + 1]] : facts.variableTerms + before[occurrences[0]];
134
+ if (end - before[occurrences[i]] > 1) return false;
135
+ }
136
+ return true;
137
+ };
138
+ const isDelimiterSplit = (group)=>{
139
+ if (group.complex) return false;
140
+ const ignoreCase = group.flags.indexOf('i') >= 0;
141
+ const facts = collectGroupFacts(group, ignoreCase);
142
+ const delimiters = Object.keys(facts.delimiterPositions);
143
+ if (0 === delimiters.length || facts.nonLiteralSources.length * delimiters.length > MAX_DELIMITER_CHECKS) return false;
144
+ const atomTests = compileAtomTests(facts.nonLiteralSources, group.flags);
145
+ return delimiters.some((delimiter)=>isSoleMatchOf(delimiter, facts, ignoreCase, atomTests) && hasAtMostOneVariableTermPerSegment(facts.delimiterPositions[delimiter], facts));
146
+ };
147
+ const hasNestedQuantifier = (pattern)=>{
148
+ const groups = [
149
+ newGroup('')
150
+ ];
151
+ let closedGroup;
152
+ let lastAtom;
153
+ let previousWasQuantifier = false;
154
+ for(let index = 0; index < pattern.length; index++){
155
+ const character = pattern[index];
156
+ const justClosed = closedGroup;
157
+ const atomBefore = lastAtom;
158
+ const isLazyModifier = previousWasQuantifier && '?' === character;
159
+ closedGroup = void 0;
160
+ lastAtom = void 0;
161
+ previousWasQuantifier = false;
162
+ const current = groups[groups.length - 1];
163
+ if (isLazyModifier) continue;
164
+ const quantifier = justClosed || atomBefore ? quantifierAt(pattern, index) : null;
165
+ if (quantifier) {
166
+ if (justClosed && quantifier.max > 1 && justClosed.variable && !isDelimiterSplit(justClosed)) return true;
167
+ if (atomBefore) {
168
+ atomBefore.min *= quantifier.min;
169
+ atomBefore.max *= quantifier.max;
170
+ }
171
+ current.variable ||= quantifier.max > quantifier.min;
172
+ index += quantifier.length - 1;
173
+ previousWasQuantifier = true;
174
+ continue;
175
+ }
176
+ let atom;
177
+ if ('\\' === character) {
178
+ const escaped = pattern[index + 1] ?? '';
179
+ index++;
180
+ if (/[uxckpP0-9]/.test(escaped)) {
181
+ current.complex = true;
182
+ atom = {
183
+ source: '[^]',
184
+ min: 1,
185
+ max: 1
186
+ };
187
+ } else atom = 'b' === escaped || 'B' === escaped ? {
188
+ source: '',
189
+ zeroWidth: true,
190
+ min: 1,
191
+ max: 1
192
+ } : /[dDwWsS]/.test(escaped) ? {
193
+ source: `\\${escaped}`,
194
+ min: 1,
195
+ max: 1
196
+ } : {
197
+ source: `\\${escaped}`,
198
+ literal: ESCAPED_CONTROL_CHARACTERS[escaped] ?? escaped,
199
+ min: 1,
200
+ max: 1
201
+ };
202
+ } else if ('[' === character) {
203
+ const start = index;
204
+ for(index++; index < pattern.length && ']' !== pattern[index]; index++)if ('\\' === pattern[index]) index++;
205
+ atom = {
206
+ source: pattern.slice(start, index + 1),
207
+ min: 1,
208
+ max: 1
209
+ };
210
+ } else if ('(' === character) {
211
+ const group = newGroup(current.flags);
212
+ if ('?' === pattern[index + 1]) {
213
+ const rest = pattern.slice(index);
214
+ const prefix = /^\(\?(?::|=|!|<=|<!|<[^>]*>)/.exec(rest);
215
+ const modifiers = prefix ? null : MODIFIER_GROUP_PREFIX.exec(rest);
216
+ if (prefix) {
217
+ index += prefix[0].length - 1;
218
+ group.complex = /^\(\?<?[=!]/.test(prefix[0]);
219
+ } else if (modifiers) {
220
+ index += modifiers[0].length - 1;
221
+ group.complex = true;
222
+ group.flags = applyModifiers(current.flags, modifiers[1], modifiers[2] ?? '');
223
+ } else {
224
+ index++;
225
+ group.complex = true;
226
+ }
227
+ }
228
+ groups.push(group);
229
+ } else if (')' === character) {
230
+ if (groups.length > 1) {
231
+ const group = groups.pop();
232
+ const parent = groups[groups.length - 1];
233
+ parent.variable ||= group.variable;
234
+ parent.complex = true;
235
+ closedGroup = group;
236
+ }
237
+ } else if ('|' === character) current.complex = true;
238
+ else atom = '^' === character || '$' === character ? {
239
+ source: '',
240
+ zeroWidth: true,
241
+ min: 1,
242
+ max: 1
243
+ } : '.' === character ? {
244
+ source: '.',
245
+ min: 1,
246
+ max: 1
247
+ } : {
248
+ source: character,
249
+ literal: character,
250
+ min: 1,
251
+ max: 1
252
+ };
253
+ if (atom) {
254
+ current.atoms.push(atom);
255
+ lastAtom = atom;
256
+ }
257
+ }
258
+ return false;
259
+ };
260
+ const MAX_COMPILED_PATTERNS = 100;
261
+ const INVALID = 'invalid';
262
+ const UNSAFE = 'unsafe';
263
+ const compiledPatterns = new Map();
264
+ const warnedPatterns = new Set();
265
+ const warnRejectedPattern = (pattern)=>{
266
+ try {
267
+ let warn = "u" > typeof console ? console.warn : void 0;
268
+ while('function' == typeof warn && '__rrweb_original__' in warn)warn = warn.__rrweb_original__;
269
+ if ('function' == typeof warn) warn.call(console, '[PostHog]', `Ignoring regex "${pattern}": a repeated group containing repetition can stall matching, so filters using it never match.`);
270
+ } catch {}
271
+ };
272
+ const compilePattern = (pattern)=>{
273
+ if ('string' != typeof pattern) return INVALID;
274
+ const cached = compiledPatterns.get(pattern);
275
+ if (void 0 !== cached) return cached;
276
+ let compiled;
277
+ try {
278
+ compiled = new RegExp(pattern);
279
+ } catch {
280
+ compiled = INVALID;
281
+ }
282
+ if (compiled !== INVALID && hasNestedQuantifier(pattern)) {
283
+ compiled = UNSAFE;
284
+ if (!warnedPatterns.has(pattern) && warnedPatterns.size < MAX_COMPILED_PATTERNS) {
285
+ warnedPatterns.add(pattern);
286
+ warnRejectedPattern(pattern);
287
+ }
288
+ }
289
+ if (compiledPatterns.size >= MAX_COMPILED_PATTERNS) compiledPatterns.clear();
290
+ compiledPatterns.set(pattern, compiled);
291
+ return compiled;
292
+ };
293
+ const isUnsafePattern = (pattern)=>compilePattern(pattern) === UNSAFE;
38
294
  const isMatchingRegex = (value, pattern)=>{
39
- if (!isValidRegex(pattern)) return false;
295
+ const regex = compilePattern(pattern);
296
+ if (regex === INVALID || regex === UNSAFE) return false;
40
297
  try {
41
- return new RegExp(pattern).test(value);
298
+ return regex.test(value);
42
299
  } catch {
43
300
  return false;
44
301
  }
@@ -48,7 +305,7 @@ const propertyComparisons = {
48
305
  exact: (targets, values)=>values.some((value)=>targets.some((target)=>value === target)),
49
306
  is_not: (targets, values)=>values.every((value)=>targets.every((target)=>value !== target)),
50
307
  regex: (targets, values)=>values.some((value)=>targets.some((target)=>isMatchingRegex(value, target))),
51
- not_regex: (targets, values)=>values.every((value)=>targets.every((target)=>!isMatchingRegex(value, target))),
308
+ not_regex: (targets, values)=>!targets.some(isUnsafePattern) && values.every((value)=>targets.every((target)=>!isMatchingRegex(value, target))),
52
309
  icontains: (targets, values)=>values.map(toLowerCase).some((value)=>targets.map(toLowerCase).some((target)=>value.includes(target))),
53
310
  not_icontains: (targets, values)=>values.map(toLowerCase).every((value)=>targets.map(toLowerCase).every((target)=>!value.includes(target))),
54
311
  gt: (targets, values)=>values.some((value)=>{
@@ -75,15 +332,18 @@ function matchPropertyFilters(propertyFilters, eventProperties) {
75
332
  __webpack_require__.d(__webpack_exports__, {
76
333
  matchPropertyFilters: ()=>matchPropertyFilters
77
334
  }, {
335
+ hasNestedQuantifier: hasNestedQuantifier,
78
336
  isMatchingRegex: isMatchingRegex,
79
337
  isValidRegex: isValidRegex,
80
338
  propertyComparisons: propertyComparisons
81
339
  });
340
+ exports.hasNestedQuantifier = __webpack_exports__.hasNestedQuantifier;
82
341
  exports.isMatchingRegex = __webpack_exports__.isMatchingRegex;
83
342
  exports.isValidRegex = __webpack_exports__.isValidRegex;
84
343
  exports.matchPropertyFilters = __webpack_exports__.matchPropertyFilters;
85
344
  exports.propertyComparisons = __webpack_exports__.propertyComparisons;
86
345
  for(var __rspack_i in __webpack_exports__)if (-1 === [
346
+ "hasNestedQuantifier",
87
347
  "isMatchingRegex",
88
348
  "isValidRegex",
89
349
  "matchPropertyFilters",
@@ -6,10 +6,267 @@ const isValidRegex = (pattern)=>{
6
6
  }
7
7
  return true;
8
8
  };
9
+ const quantifierAt = (pattern, index)=>{
10
+ const character = pattern[index];
11
+ if ('*' === character) return {
12
+ length: 1,
13
+ min: 0,
14
+ max: 1 / 0
15
+ };
16
+ if ('+' === character) return {
17
+ length: 1,
18
+ min: 1,
19
+ max: 1 / 0
20
+ };
21
+ if ('?' === character) return {
22
+ length: 1,
23
+ min: 0,
24
+ max: 1
25
+ };
26
+ if ('{' !== character) return null;
27
+ const repetition = /^\{(\d+)(,(\d*))?\}/.exec(pattern.slice(index));
28
+ if (!repetition) return null;
29
+ const min = Number(repetition[1]);
30
+ const max = repetition[2] ? '' === repetition[3] ? 1 / 0 : Number(repetition[3]) : min;
31
+ return {
32
+ length: repetition[0].length,
33
+ min,
34
+ max
35
+ };
36
+ };
37
+ const newGroup = (flags)=>({
38
+ atoms: [],
39
+ variable: false,
40
+ complex: false,
41
+ flags
42
+ });
43
+ const MODIFIER_GROUP_PREFIX = /^\(\?([ims]*)(?:-([ims]*))?:/;
44
+ const applyModifiers = (flags, added, removed)=>[
45
+ 'i',
46
+ 's'
47
+ ].filter((flag)=>removed.indexOf(flag) < 0 && (flags + added).indexOf(flag) >= 0).join('');
48
+ const ESCAPED_CONTROL_CHARACTERS = {
49
+ n: '\n',
50
+ r: '\r',
51
+ t: '\t',
52
+ f: '\f',
53
+ v: '\v'
54
+ };
55
+ const isRequiredLiteral = (atom)=>void 0 !== atom.literal && atom.min === atom.max && atom.min > 0;
56
+ const MAX_DELIMITER_CHECKS = 10000;
57
+ const spellings = (character, ignoreCase)=>ignoreCase ? [
58
+ character,
59
+ character.toUpperCase()
60
+ ] : [
61
+ character
62
+ ];
63
+ const collectGroupFacts = (group, ignoreCase)=>{
64
+ const facts = {
65
+ delimiterPositions: Object.create(null),
66
+ optionalLiterals: Object.create(null),
67
+ literalsBySpelling: Object.create(null),
68
+ nonLiteralSources: [],
69
+ variableTermsBefore: [],
70
+ variableTerms: 0
71
+ };
72
+ const seenSources = Object.create(null);
73
+ group.atoms.forEach((atom, position)=>{
74
+ facts.variableTermsBefore.push(facts.variableTerms);
75
+ if (atom.max > atom.min) facts.variableTerms++;
76
+ const literal = atom.literal;
77
+ if (void 0 === literal) {
78
+ if (!atom.zeroWidth && !seenSources[atom.source]) {
79
+ seenSources[atom.source] = true;
80
+ facts.nonLiteralSources.push(atom.source);
81
+ }
82
+ return;
83
+ }
84
+ if (isRequiredLiteral(atom)) (facts.delimiterPositions[literal] ||= []).push(position);
85
+ else facts.optionalLiterals[literal] = true;
86
+ spellings(literal, ignoreCase).forEach((spelling)=>{
87
+ const owner = facts.literalsBySpelling[spelling];
88
+ facts.literalsBySpelling[spelling] = void 0 === owner || owner === literal ? literal : null;
89
+ });
90
+ });
91
+ return facts;
92
+ };
93
+ const compileAtomTests = (sources, flags)=>sources.map((source)=>{
94
+ try {
95
+ return new RegExp(`^(?:${source})$`, flags);
96
+ } catch {
97
+ return /[^]/;
98
+ }
99
+ });
100
+ const isSoleMatchOf = (delimiter, facts, ignoreCase, atomTests)=>!facts.optionalLiterals[delimiter] && spellings(delimiter, ignoreCase).every((spelling)=>facts.literalsBySpelling[spelling] === delimiter) && !atomTests.some((atomTest)=>atomTest.test(delimiter));
101
+ const hasAtMostOneVariableTermPerSegment = (occurrences, facts)=>{
102
+ const before = facts.variableTermsBefore;
103
+ for(let i = 0; i < occurrences.length; i++){
104
+ const end = i + 1 < occurrences.length ? before[occurrences[i + 1]] : facts.variableTerms + before[occurrences[0]];
105
+ if (end - before[occurrences[i]] > 1) return false;
106
+ }
107
+ return true;
108
+ };
109
+ const isDelimiterSplit = (group)=>{
110
+ if (group.complex) return false;
111
+ const ignoreCase = group.flags.indexOf('i') >= 0;
112
+ const facts = collectGroupFacts(group, ignoreCase);
113
+ const delimiters = Object.keys(facts.delimiterPositions);
114
+ if (0 === delimiters.length || facts.nonLiteralSources.length * delimiters.length > MAX_DELIMITER_CHECKS) return false;
115
+ const atomTests = compileAtomTests(facts.nonLiteralSources, group.flags);
116
+ return delimiters.some((delimiter)=>isSoleMatchOf(delimiter, facts, ignoreCase, atomTests) && hasAtMostOneVariableTermPerSegment(facts.delimiterPositions[delimiter], facts));
117
+ };
118
+ const hasNestedQuantifier = (pattern)=>{
119
+ const groups = [
120
+ newGroup('')
121
+ ];
122
+ let closedGroup;
123
+ let lastAtom;
124
+ let previousWasQuantifier = false;
125
+ for(let index = 0; index < pattern.length; index++){
126
+ const character = pattern[index];
127
+ const justClosed = closedGroup;
128
+ const atomBefore = lastAtom;
129
+ const isLazyModifier = previousWasQuantifier && '?' === character;
130
+ closedGroup = void 0;
131
+ lastAtom = void 0;
132
+ previousWasQuantifier = false;
133
+ const current = groups[groups.length - 1];
134
+ if (isLazyModifier) continue;
135
+ const quantifier = justClosed || atomBefore ? quantifierAt(pattern, index) : null;
136
+ if (quantifier) {
137
+ if (justClosed && quantifier.max > 1 && justClosed.variable && !isDelimiterSplit(justClosed)) return true;
138
+ if (atomBefore) {
139
+ atomBefore.min *= quantifier.min;
140
+ atomBefore.max *= quantifier.max;
141
+ }
142
+ current.variable ||= quantifier.max > quantifier.min;
143
+ index += quantifier.length - 1;
144
+ previousWasQuantifier = true;
145
+ continue;
146
+ }
147
+ let atom;
148
+ if ('\\' === character) {
149
+ const escaped = pattern[index + 1] ?? '';
150
+ index++;
151
+ if (/[uxckpP0-9]/.test(escaped)) {
152
+ current.complex = true;
153
+ atom = {
154
+ source: '[^]',
155
+ min: 1,
156
+ max: 1
157
+ };
158
+ } else atom = 'b' === escaped || 'B' === escaped ? {
159
+ source: '',
160
+ zeroWidth: true,
161
+ min: 1,
162
+ max: 1
163
+ } : /[dDwWsS]/.test(escaped) ? {
164
+ source: `\\${escaped}`,
165
+ min: 1,
166
+ max: 1
167
+ } : {
168
+ source: `\\${escaped}`,
169
+ literal: ESCAPED_CONTROL_CHARACTERS[escaped] ?? escaped,
170
+ min: 1,
171
+ max: 1
172
+ };
173
+ } else if ('[' === character) {
174
+ const start = index;
175
+ for(index++; index < pattern.length && ']' !== pattern[index]; index++)if ('\\' === pattern[index]) index++;
176
+ atom = {
177
+ source: pattern.slice(start, index + 1),
178
+ min: 1,
179
+ max: 1
180
+ };
181
+ } else if ('(' === character) {
182
+ const group = newGroup(current.flags);
183
+ if ('?' === pattern[index + 1]) {
184
+ const rest = pattern.slice(index);
185
+ const prefix = /^\(\?(?::|=|!|<=|<!|<[^>]*>)/.exec(rest);
186
+ const modifiers = prefix ? null : MODIFIER_GROUP_PREFIX.exec(rest);
187
+ if (prefix) {
188
+ index += prefix[0].length - 1;
189
+ group.complex = /^\(\?<?[=!]/.test(prefix[0]);
190
+ } else if (modifiers) {
191
+ index += modifiers[0].length - 1;
192
+ group.complex = true;
193
+ group.flags = applyModifiers(current.flags, modifiers[1], modifiers[2] ?? '');
194
+ } else {
195
+ index++;
196
+ group.complex = true;
197
+ }
198
+ }
199
+ groups.push(group);
200
+ } else if (')' === character) {
201
+ if (groups.length > 1) {
202
+ const group = groups.pop();
203
+ const parent = groups[groups.length - 1];
204
+ parent.variable ||= group.variable;
205
+ parent.complex = true;
206
+ closedGroup = group;
207
+ }
208
+ } else if ('|' === character) current.complex = true;
209
+ else atom = '^' === character || '$' === character ? {
210
+ source: '',
211
+ zeroWidth: true,
212
+ min: 1,
213
+ max: 1
214
+ } : '.' === character ? {
215
+ source: '.',
216
+ min: 1,
217
+ max: 1
218
+ } : {
219
+ source: character,
220
+ literal: character,
221
+ min: 1,
222
+ max: 1
223
+ };
224
+ if (atom) {
225
+ current.atoms.push(atom);
226
+ lastAtom = atom;
227
+ }
228
+ }
229
+ return false;
230
+ };
231
+ const MAX_COMPILED_PATTERNS = 100;
232
+ const INVALID = 'invalid';
233
+ const UNSAFE = 'unsafe';
234
+ const compiledPatterns = new Map();
235
+ const warnedPatterns = new Set();
236
+ const warnRejectedPattern = (pattern)=>{
237
+ try {
238
+ let warn = "u" > typeof console ? console.warn : void 0;
239
+ while('function' == typeof warn && '__rrweb_original__' in warn)warn = warn.__rrweb_original__;
240
+ if ('function' == typeof warn) warn.call(console, '[PostHog]', `Ignoring regex "${pattern}": a repeated group containing repetition can stall matching, so filters using it never match.`);
241
+ } catch {}
242
+ };
243
+ const compilePattern = (pattern)=>{
244
+ if ('string' != typeof pattern) return INVALID;
245
+ const cached = compiledPatterns.get(pattern);
246
+ if (void 0 !== cached) return cached;
247
+ let compiled;
248
+ try {
249
+ compiled = new RegExp(pattern);
250
+ } catch {
251
+ compiled = INVALID;
252
+ }
253
+ if (compiled !== INVALID && hasNestedQuantifier(pattern)) {
254
+ compiled = UNSAFE;
255
+ if (!warnedPatterns.has(pattern) && warnedPatterns.size < MAX_COMPILED_PATTERNS) {
256
+ warnedPatterns.add(pattern);
257
+ warnRejectedPattern(pattern);
258
+ }
259
+ }
260
+ if (compiledPatterns.size >= MAX_COMPILED_PATTERNS) compiledPatterns.clear();
261
+ compiledPatterns.set(pattern, compiled);
262
+ return compiled;
263
+ };
264
+ const isUnsafePattern = (pattern)=>compilePattern(pattern) === UNSAFE;
9
265
  const isMatchingRegex = (value, pattern)=>{
10
- if (!isValidRegex(pattern)) return false;
266
+ const regex = compilePattern(pattern);
267
+ if (regex === INVALID || regex === UNSAFE) return false;
11
268
  try {
12
- return new RegExp(pattern).test(value);
269
+ return regex.test(value);
13
270
  } catch {
14
271
  return false;
15
272
  }
@@ -19,7 +276,7 @@ const propertyComparisons = {
19
276
  exact: (targets, values)=>values.some((value)=>targets.some((target)=>value === target)),
20
277
  is_not: (targets, values)=>values.every((value)=>targets.every((target)=>value !== target)),
21
278
  regex: (targets, values)=>values.some((value)=>targets.some((target)=>isMatchingRegex(value, target))),
22
- not_regex: (targets, values)=>values.every((value)=>targets.every((target)=>!isMatchingRegex(value, target))),
279
+ not_regex: (targets, values)=>!targets.some(isUnsafePattern) && values.every((value)=>targets.every((target)=>!isMatchingRegex(value, target))),
23
280
  icontains: (targets, values)=>values.map(toLowerCase).some((value)=>targets.map(toLowerCase).some((target)=>value.includes(target))),
24
281
  not_icontains: (targets, values)=>values.map(toLowerCase).every((value)=>targets.map(toLowerCase).every((target)=>!value.includes(target))),
25
282
  gt: (targets, values)=>values.some((value)=>{
@@ -43,4 +300,4 @@ function matchPropertyFilters(propertyFilters, eventProperties) {
43
300
  ]);
44
301
  });
45
302
  }
46
- export { isMatchingRegex, isValidRegex, matchPropertyFilters, propertyComparisons };
303
+ export { hasNestedQuantifier, isMatchingRegex, isValidRegex, matchPropertyFilters, propertyComparisons };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/core",
3
- "version": "1.69.6",
3
+ "version": "1.69.7",
4
4
  "bugs": {
5
5
  "url": "https://github.com/PostHog/posthog-js/issues"
6
6
  },
@@ -1,5 +1,12 @@
1
+ import type { MockInstance } from 'vitest'
1
2
  import type { PropertyFilters, PropertyOperator } from '../types'
2
- import { isMatchingRegex, isValidRegex, matchPropertyFilters, propertyComparisons } from './property-matching'
3
+ import {
4
+ hasNestedQuantifier,
5
+ isMatchingRegex,
6
+ isValidRegex,
7
+ matchPropertyFilters,
8
+ propertyComparisons,
9
+ } from './property-matching'
3
10
 
4
11
  const operators: PropertyOperator[] = [
5
12
  'exact',
@@ -28,6 +35,357 @@ describe('shared property matching contract', () => {
28
35
  expect(isValidRegex('[invalid')).toBe(false)
29
36
  expect(isMatchingRegex('anything', '[invalid')).toBe(false)
30
37
  })
38
+
39
+ it.each([
40
+ ['^/docs/.*', '/docs/a', true],
41
+ ['^(foo|bar)+$', 'foobarfoo', true],
42
+ ['^(?:ab)+$', 'ababab', true],
43
+ ['^a+b*$', 'aab', true],
44
+ ['\\(a+\\)+', '(aa)))', true],
45
+ ['[(a+)]+', 'a+)', true],
46
+ ['^(a+)?b$', 'aab', true],
47
+ ['^(a+){1}$', 'aaa', true],
48
+ ['example\\.com', 'admin@example.org', false],
49
+ ['^foo$', 'foo\n', false],
50
+ ])('keeps matching for safe pattern %s against %j', (pattern, value, expected) => {
51
+ expect(isMatchingRegex(value, pattern)).toBe(expected)
52
+ expect(isMatchingRegex(value, pattern)).toBe(expected)
53
+ })
54
+ })
55
+
56
+ describe('nested quantifier guard', () => {
57
+ let warnSpy: MockInstance<Parameters<typeof console.warn>, void>
58
+
59
+ // The shared setup fakes timers, which freezes Date.now and would make the timing checks vacuous.
60
+ beforeAll(() => {
61
+ vi.useRealTimers()
62
+ })
63
+
64
+ afterAll(() => {
65
+ vi.useFakeTimers()
66
+ })
67
+
68
+ beforeEach(() => {
69
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
70
+ })
71
+
72
+ afterEach(() => {
73
+ warnSpy.mockRestore()
74
+ })
75
+
76
+ it.each([
77
+ '^(a+)+$',
78
+ '(a*)*',
79
+ '(?:x+y?)+',
80
+ '((ab)+)+',
81
+ '(a+){2,}',
82
+ '(a+){2}',
83
+ '^(a?a?)+$',
84
+ '^(a{0,1}a{0,1})+$',
85
+ '(a{2,3})+',
86
+ '(a+?)+',
87
+ '(a{2,3}?)+',
88
+ '^(a+){3}$',
89
+ '^(a+){0,3}$',
90
+ '(?:.+/)+',
91
+ '([^/]+/?)+',
92
+ '(a|b+)+',
93
+ '(x+x+)+',
94
+ '(?:[^:]+)+',
95
+ '(?:a[^/]*/[^/]*)+',
96
+ '(?:/[^/]+.)+',
97
+ '(\\u0041[A-Z]+)+',
98
+ '(?=a+)+',
99
+ '(a{1,2})+',
100
+ '^(a?){26}a{26}$',
101
+ '^(a{1,10}){10}$',
102
+ '^(?:a{1,3}){20}$',
103
+ '^(\\w{1,8}){10}$',
104
+ '^(a{1,10}){1,10}$',
105
+ '^(\\d{1,3}\\d{1,3}){1,5}$',
106
+ '(?:a?){24}b',
107
+ '(?:a{1,2}){30}b',
108
+ '(?:a{0,2}){20}b',
109
+ '(?:[a-z]{1,3}){15}!',
110
+ ])('flags %s', (pattern) => {
111
+ expect(hasNestedQuantifier(pattern)).toBe(true)
112
+ })
113
+
114
+ it.each([
115
+ '^(a+)?$',
116
+ '(a+){1}',
117
+ '(a)+',
118
+ '(a+)b+',
119
+ '\\(a+\\)+',
120
+ '[(a+)]+',
121
+ '(a|a)*',
122
+ '(?<n>a)+',
123
+ '(a+)?',
124
+ 'a+?',
125
+ '(ab){2}',
126
+ '^(\\d{3})+$',
127
+ '(a{2})+',
128
+ '(a{2,2})+',
129
+ '(a)+?',
130
+ '(\\d+\\.)+',
131
+ '(a[)]+)+',
132
+ '^https://example\\.com/admin(?:/[^/]+)*$',
133
+ '^https?://([a-z0-9-]+\\.)+example\\.com$',
134
+ '^([0-9]{1,3}\\.){3}[0-9]{1,3}$',
135
+ '^(\\d{1,2}/){2}\\d{4}$',
136
+ '^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,3}$',
137
+ '(?<seg>/[^/]+)*',
138
+ ])('does not flag %s', (pattern) => {
139
+ expect(hasNestedQuantifier(pattern)).toBe(false)
140
+ })
141
+
142
+ it.each([
143
+ ['^(?:/[^/]+/?)+$', true],
144
+ ['^(?:/[^/]+/{0})+$', true],
145
+ ['^(?:/[^/]+[^/]+/)+$', true],
146
+ ['^(?:[^/]+//[^/]+)+$', true],
147
+ ['^(?:/[^/]+/[^/]+)+$', false],
148
+ ['^(?:/[^/]*/[^/]*)+$', false],
149
+ ])('counts variable terms between every pair of delimiters in %s', (pattern, expected) => {
150
+ expect(hasNestedQuantifier(pattern)).toBe(expected)
151
+ })
152
+
153
+ describe('guard cost on long patterns', () => {
154
+ const distinctLiterals = (count: number, from = 0x4e00): string[] =>
155
+ Array.from({ length: count }, (_, i) => String.fromCharCode(from + i))
156
+
157
+ const countRegExpConstructions = (run: () => void): number => {
158
+ const OriginalRegExp = globalThis.RegExp
159
+ let constructions = 0
160
+ globalThis.RegExp = new Proxy(OriginalRegExp, {
161
+ construct(target, args, newTarget) {
162
+ constructions++
163
+ return Reflect.construct(target, args, newTarget)
164
+ },
165
+ })
166
+ try {
167
+ run()
168
+ } finally {
169
+ globalThis.RegExp = OriginalRegExp
170
+ }
171
+ return constructions
172
+ }
173
+
174
+ it.each([
175
+ ['a long repeated literal run', '^(' + 'ab'.repeat(1000) + '.*)+$', true],
176
+ ['a long single-literal run', '^(' + 'a'.repeat(16000) + '.*)+$', true],
177
+ ['thousands of distinct literals', '^(' + distinctLiterals(3000).join('') + '.*)+$', true],
178
+ [
179
+ 'thousands of paired literals',
180
+ '^(' +
181
+ distinctLiterals(2000)
182
+ .map((literal) => literal + literal)
183
+ .join('') +
184
+ '[0-9]*[0-9]*)+$',
185
+ true,
186
+ ],
187
+ ['a long delimiter-split group', '^(' + 'ab'.repeat(1000) + '[^/]+/)+$', false],
188
+ ])('compiles each distinct term once for %s', (_, pattern, expected) => {
189
+ let flagged: boolean | undefined
190
+ const constructions = countRegExpConstructions(() => {
191
+ flagged = hasNestedQuantifier(pattern)
192
+ })
193
+ expect(flagged).toBe(expected)
194
+ expect(constructions).toBeLessThanOrEqual(1)
195
+ })
196
+
197
+ it('still matches a long delimiter-split group', () => {
198
+ expect(isMatchingRegex('ab'.repeat(1000) + 'z/', '^(' + 'ab'.repeat(1000) + '[^/]+/)+$')).toBe(true)
199
+ })
200
+
201
+ it('rejects a delimiter-split group once its checks exceed the budget', () => {
202
+ const pattern = (ranges: number): string =>
203
+ '^(?:' +
204
+ distinctLiterals(ranges)
205
+ .map((end) => `[\\u4e00-${end}]`)
206
+ .join('') +
207
+ distinctLiterals(100, 0x100).join('') +
208
+ '\\d+)+$'
209
+
210
+ expect(hasNestedQuantifier(pattern(99))).toBe(false)
211
+ expect(hasNestedQuantifier(pattern(100))).toBe(true)
212
+ })
213
+ })
214
+
215
+ it('matches delimiter-split patterns without Array.prototype.findIndex', async () => {
216
+ // A fresh module has an empty compile cache, so the guard really runs without findIndex.
217
+ const isMatching = await freshIsMatchingRegex()
218
+ const originalFindIndex = Array.prototype.findIndex
219
+ try {
220
+ ;(Array.prototype as { findIndex?: unknown }).findIndex = undefined
221
+ expect(isMatching('https://example.com/admin/users', '^https://example\\.com/admin(?:/[^/]+)*$')).toBe(true)
222
+ expect(isMatching('192.168.1.10', '^([0-9]{1,3}\\.){3}[0-9]{1,3}$')).toBe(true)
223
+ } finally {
224
+ Array.prototype.findIndex = originalFindIndex
225
+ }
226
+ })
227
+
228
+ it.each([
229
+ ['^(?i:(?:a[A-Z]+)+)$', true],
230
+ ['^(?s:(?:\\n.+)+)x$', true],
231
+ ['^(?i-s:(?:a[A-Z]+)+)$', true],
232
+ ['^(?s-i:(?:\\n.+)+)x$', true],
233
+ ['^(?i:(?:(?:a[A-Z]+)+)+)$', true],
234
+ ['(?i:a[A-Z]+)+', true],
235
+ ['^(?-i:(?:a[A-Z]+)+)$', false],
236
+ ['^(?i:(?-i:(?:a[A-Z]+)+))$', false],
237
+ ['^(?m:(?:a[A-Z]+)+)$', false],
238
+ ['^(?i:(?:/[^/]+)*)$', false],
239
+ ['^(?:a[A-Z]+)+(?i:b)$', false],
240
+ ])('checks delimiters of %s under its inline modifiers', (pattern, expected) => {
241
+ expect(hasNestedQuantifier(pattern)).toBe(expected)
242
+ })
243
+
244
+ it('treats case variants of a delimiter as other terms that can match it under the i modifier', () => {
245
+ expect(hasNestedQuantifier('^(?:a[^a]+A)+$')).toBe(false)
246
+ expect(hasNestedQuantifier('^(?i:(?:a[^a]+A)+)$')).toBe(true)
247
+ })
248
+
249
+ it('returns no match quickly for catastrophic backtracking input', () => {
250
+ const start = Date.now()
251
+ expect(isMatchingRegex('a'.repeat(40) + '!', '^(a+)+$')).toBe(false)
252
+ expect(propertyComparisons.regex(['^(b+)+$'], ['b'.repeat(40) + '!'])).toBe(false)
253
+ expect(propertyComparisons.not_regex(['^(c+)+$'], ['c'.repeat(40) + '!'])).toBe(false)
254
+ expect(Date.now() - start).toBeLessThan(500)
255
+ })
256
+
257
+ it('returns no match quickly for catastrophic backtracking through optional terms', () => {
258
+ const start = Date.now()
259
+ expect(isMatchingRegex('a'.repeat(30) + '!', '^(a?a?)+$')).toBe(false)
260
+ expect(Date.now() - start).toBeLessThan(500)
261
+ })
262
+
263
+ it.each([
264
+ ['^([0-9]{1,3}\\.){3}[0-9]{1,3}$', '192.168.1.10', true],
265
+ ['^([0-9]{1,3}\\.){3}[0-9]{1,3}$', '1'.repeat(5000) + '.', false],
266
+ ['^https://example\\.com/admin(?:/[^/]+)*$', 'https://example.com/admin/users/42', true],
267
+ ['^https://example\\.com/admin(?:/[^/]+)*$', 'https://example.com/admin' + '/aaaa'.repeat(5000) + '/', false],
268
+ ['^https?://([a-z0-9-]+\\.)+example\\.com$', 'https://app.eu.example.com', true],
269
+ ['^https?://([a-z0-9-]+\\.)+example\\.com$', 'https://' + 'a.'.repeat(5000) + 'example.co', false],
270
+ ['^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,3}$', 'en-US', true],
271
+ ['^(\\d{1,2}/){2}\\d{4}$', '12/31/2026', true],
272
+ ])('matches bounded or delimiter-split pattern %s quickly', (pattern, value, expected) => {
273
+ const start = Date.now()
274
+ expect(isMatchingRegex(value, pattern)).toBe(expected)
275
+ expect(Date.now() - start).toBeLessThan(500)
276
+ })
277
+
278
+ it('returns no match quickly for a bounded repeat of a variable-length group', () => {
279
+ const start = Date.now()
280
+ expect(isMatchingRegex('a'.repeat(30) + '!', '^(\\w{1,8}){10}$')).toBe(false)
281
+ expect(Date.now() - start).toBeLessThan(500)
282
+ })
283
+
284
+ it('lets not_regex pass for a delimiter-split pattern that does not match', () => {
285
+ expect(
286
+ propertyComparisons.not_regex(['^https://example\\.com/admin(?:/[^/]+)*$'], ['https://example.com/pricing'])
287
+ ).toBe(true)
288
+ })
289
+
290
+ it('never lets an unsafe not_regex target pass, even with no values', () => {
291
+ expect(propertyComparisons.not_regex(['^(a+)+$'], [])).toBe(false)
292
+ expect(propertyComparisons.not_regex([], [])).toBe(true)
293
+ expect(propertyComparisons.not_regex([], ['value'])).toBe(true)
294
+ })
295
+
296
+ it.each([null, undefined, 42, /^(a+)+$/])('treats a non-string pattern %s as invalid', (pattern) => {
297
+ expect(() => isMatchingRegex('aa', pattern as unknown as string)).not.toThrow()
298
+ expect(isMatchingRegex('aa', pattern as unknown as string)).toBe(false)
299
+ expect(isMatchingRegex('Desktop', pattern as unknown as string)).toBe(false)
300
+ })
301
+
302
+ it('never lets a rejected pattern pass a regex or not_regex filter', () => {
303
+ expect(isMatchingRegex('dd', '^(d+)+$')).toBe(false)
304
+ expect(propertyComparisons.regex(['^(d+)+$'], ['dd'])).toBe(false)
305
+ expect(propertyComparisons.not_regex(['^(d+)+$'], ['dd'])).toBe(false)
306
+ expect(propertyComparisons.not_regex(['^(d+)+$'], ['zz'])).toBe(false)
307
+ })
308
+
309
+ it('does not let a rejected pattern pass not_regex on a protected URL', () => {
310
+ const pattern = '^https://example\\.com/admin(?:/.+)*$'
311
+ expect(new RegExp(pattern).test('https://example.com/admin/customer')).toBe(true)
312
+ expect(propertyComparisons.not_regex([pattern], ['https://example.com/admin/customer'])).toBe(false)
313
+ })
314
+
315
+ it('keeps invalid patterns as non-matches that pass not_regex', () => {
316
+ expect(propertyComparisons.regex(['('], ['value'])).toBe(false)
317
+ expect(propertyComparisons.not_regex(['('], ['value'])).toBe(true)
318
+ })
319
+
320
+ // Warning suppression is module state, so each test needs a fresh module.
321
+ const freshIsMatchingRegex = async (): Promise<typeof isMatchingRegex> => {
322
+ vi.resetModules()
323
+ return (await import('./property-matching')).isMatchingRegex
324
+ }
325
+
326
+ it('warns once per rejected pattern', async () => {
327
+ const isMatching = await freshIsMatchingRegex()
328
+
329
+ isMatching('x', '^(warn\\w+)+$')
330
+ isMatching('y', '^(warn\\w+)+$')
331
+ isMatching('z', '^(other\\w+)+$')
332
+
333
+ expect(warnSpy).toHaveBeenCalledTimes(2)
334
+ expect(warnSpy).toHaveBeenCalledWith('[PostHog]', expect.stringContaining('^(warn\\w+)+$'))
335
+ })
336
+
337
+ it('keeps warning suppression independent of cache eviction and bounded to 100 warnings', async () => {
338
+ vi.resetModules()
339
+ const { propertyComparisons: fresh } = await import('./property-matching')
340
+ const patterns = Array.from({ length: 101 }, (_, i) => `^https://customer\\.example/(?:segment${i}\\w+)+$`)
341
+ const cumulativeWarnings: number[] = []
342
+
343
+ for (let sweep = 0; sweep < 3; sweep++) {
344
+ patterns.forEach((pattern) => fresh.regex([pattern], ['https://customer.example/x']))
345
+ cumulativeWarnings.push(warnSpy.mock.calls.length)
346
+ }
347
+
348
+ expect(cumulativeWarnings).toEqual([100, 100, 100])
349
+ })
350
+
351
+ it('does not throw when console methods are missing', async () => {
352
+ const originalDebug = console.debug
353
+ const originalWarn = console.warn
354
+ try {
355
+ ;(console as { debug?: unknown }).debug = undefined
356
+ ;(console as { warn?: unknown }).warn = undefined
357
+ const isMatching = await freshIsMatchingRegex()
358
+ expect(() => isMatching('x', '^(nodebug\\w+)+$')).not.toThrow()
359
+ expect(isMatching('x', '^(nodebug\\w+)+$')).toBe(false)
360
+ } finally {
361
+ console.debug = originalDebug
362
+ console.warn = originalWarn
363
+ }
364
+ })
365
+
366
+ it('warns through the original console method behind __rrweb_original__ wrappers', async () => {
367
+ const wrapper = Object.assign(vi.fn(), { __rrweb_original__: warnSpy })
368
+ const originalWarn = console.warn
369
+ console.warn = wrapper as unknown as typeof console.warn
370
+ try {
371
+ const isMatching = await freshIsMatchingRegex()
372
+ isMatching('x', '^(wrapped\\w+)+$')
373
+ } finally {
374
+ console.warn = originalWarn
375
+ }
376
+
377
+ expect(wrapper).not.toHaveBeenCalled()
378
+ expect(warnSpy).toHaveBeenCalledWith('[PostHog]', expect.stringContaining('^(wrapped\\w+)+$'))
379
+ })
380
+
381
+ it('does not warn for invalid or safe patterns', async () => {
382
+ const isMatching = await freshIsMatchingRegex()
383
+
384
+ isMatching('x', '[invalid')
385
+ isMatching('x', '^x+$')
386
+
387
+ expect(warnSpy).not.toHaveBeenCalled()
388
+ })
31
389
  })
32
390
 
33
391
  describe('property comparisons', () => {
@@ -11,13 +11,343 @@ export const isValidRegex = (pattern: string): boolean => {
11
11
  return true
12
12
  }
13
13
 
14
+ interface Quantifier {
15
+ length: number
16
+ min: number
17
+ max: number
18
+ }
19
+
20
+ const quantifierAt = (pattern: string, index: number): Quantifier | null => {
21
+ const character = pattern[index]
22
+ if (character === '*') {
23
+ return { length: 1, min: 0, max: Infinity }
24
+ }
25
+ if (character === '+') {
26
+ return { length: 1, min: 1, max: Infinity }
27
+ }
28
+ if (character === '?') {
29
+ return { length: 1, min: 0, max: 1 }
30
+ }
31
+ if (character !== '{') {
32
+ return null
33
+ }
34
+ const repetition = /^\{(\d+)(,(\d*))?\}/.exec(pattern.slice(index))
35
+ if (!repetition) {
36
+ return null
37
+ }
38
+ const min = Number(repetition[1])
39
+ const max = repetition[2] ? (repetition[3] === '' ? Infinity : Number(repetition[3])) : min
40
+ return { length: repetition[0].length, min, max }
41
+ }
42
+
43
+ interface Atom {
44
+ source: string
45
+ literal?: string
46
+ zeroWidth?: boolean
47
+ min: number
48
+ max: number
49
+ }
50
+
51
+ interface Group {
52
+ atoms: Atom[]
53
+ variable: boolean
54
+ // Alternation, nested groups and escapes we can't evaluate rule out the delimiter exemption.
55
+ complex: boolean
56
+ // The `i` and `s` flags that inline modifier groups such as `(?i:...)` switch on for this group.
57
+ flags: string
58
+ }
59
+
60
+ const newGroup = (flags: string): Group => ({ atoms: [], variable: false, complex: false, flags })
61
+
62
+ const MODIFIER_GROUP_PREFIX = /^\(\?([ims]*)(?:-([ims]*))?:/
63
+
64
+ const applyModifiers = (flags: string, added: string, removed: string): string =>
65
+ ['i', 's'].filter((flag) => removed.indexOf(flag) < 0 && (flags + added).indexOf(flag) >= 0).join('')
66
+
67
+ const ESCAPED_CONTROL_CHARACTERS: Record<string, string> = { n: '\n', r: '\r', t: '\t', f: '\f', v: '\v' }
68
+
69
+ const isRequiredLiteral = (atom: Atom): boolean => atom.literal !== undefined && atom.min === atom.max && atom.min > 0
70
+
71
+ // Caps the regex tests one group may cost, so a long pattern can't make the guard itself slow.
72
+ const MAX_DELIMITER_CHECKS = 10000
73
+
74
+ interface GroupFacts {
75
+ delimiterPositions: Record<string, number[]>
76
+ optionalLiterals: Record<string, boolean>
77
+ // Each spelling maps to the one literal that can take it, or null when several literals share it.
78
+ literalsBySpelling: Record<string, string | null>
79
+ nonLiteralSources: string[]
80
+ variableTermsBefore: number[]
81
+ variableTerms: number
82
+ }
83
+
84
+ // A superset of the characters the engine treats as equal under `i`, which compares upper-cased
85
+ // characters; two characters that share a spelling may collide and so are kept apart.
86
+ const spellings = (character: string, ignoreCase: boolean): string[] =>
87
+ ignoreCase ? [character, character.toUpperCase()] : [character]
88
+
89
+ const collectGroupFacts = (group: Group, ignoreCase: boolean): GroupFacts => {
90
+ const facts: GroupFacts = {
91
+ delimiterPositions: Object.create(null),
92
+ optionalLiterals: Object.create(null),
93
+ literalsBySpelling: Object.create(null),
94
+ nonLiteralSources: [],
95
+ variableTermsBefore: [],
96
+ variableTerms: 0,
97
+ }
98
+ const seenSources: Record<string, boolean> = Object.create(null)
99
+ group.atoms.forEach((atom, position) => {
100
+ facts.variableTermsBefore.push(facts.variableTerms)
101
+ if (atom.max > atom.min) {
102
+ facts.variableTerms++
103
+ }
104
+ const literal = atom.literal
105
+ if (literal === undefined) {
106
+ if (!atom.zeroWidth && !seenSources[atom.source]) {
107
+ seenSources[atom.source] = true
108
+ facts.nonLiteralSources.push(atom.source)
109
+ }
110
+ return
111
+ }
112
+ if (isRequiredLiteral(atom)) {
113
+ ;(facts.delimiterPositions[literal] ||= []).push(position)
114
+ } else {
115
+ facts.optionalLiterals[literal] = true
116
+ }
117
+ spellings(literal, ignoreCase).forEach((spelling) => {
118
+ const owner = facts.literalsBySpelling[spelling]
119
+ facts.literalsBySpelling[spelling] = owner === undefined || owner === literal ? literal : null
120
+ })
121
+ })
122
+ return facts
123
+ }
124
+
125
+ const compileAtomTests = (sources: string[], flags: string): RegExp[] =>
126
+ sources.map((source) => {
127
+ try {
128
+ return new RegExp(`^(?:${source})$`, flags)
129
+ } catch {
130
+ // A term we can't compile is assumed to match any delimiter.
131
+ return /[^]/
132
+ }
133
+ })
134
+
135
+ const isSoleMatchOf = (delimiter: string, facts: GroupFacts, ignoreCase: boolean, atomTests: RegExp[]): boolean =>
136
+ !facts.optionalLiterals[delimiter] &&
137
+ spellings(delimiter, ignoreCase).every((spelling) => facts.literalsBySpelling[spelling] === delimiter) &&
138
+ !atomTests.some((atomTest) => atomTest.test(delimiter))
139
+
140
+ // Walks the segments between consecutive occurrences, including the one that wraps into the next iteration.
141
+ const hasAtMostOneVariableTermPerSegment = (occurrences: number[], facts: GroupFacts): boolean => {
142
+ const before = facts.variableTermsBefore
143
+ for (let i = 0; i < occurrences.length; i++) {
144
+ const end = i + 1 < occurrences.length ? before[occurrences[i + 1]] : facts.variableTerms + before[occurrences[0]]
145
+ if (end - before[occurrences[i]] > 1) {
146
+ return false
147
+ }
148
+ }
149
+ return true
150
+ }
151
+
152
+ /**
153
+ * A repeated group is linear when one required literal splits every iteration and no other term can
154
+ * match it, with at most one variable term between consecutive occurrences, as in `(?:/[^/]+)*`.
155
+ */
156
+ const isDelimiterSplit = (group: Group): boolean => {
157
+ if (group.complex) {
158
+ return false
159
+ }
160
+ const ignoreCase = group.flags.indexOf('i') >= 0
161
+ const facts = collectGroupFacts(group, ignoreCase)
162
+ const delimiters = Object.keys(facts.delimiterPositions)
163
+ if (delimiters.length === 0 || facts.nonLiteralSources.length * delimiters.length > MAX_DELIMITER_CHECKS) {
164
+ return false
165
+ }
166
+ const atomTests = compileAtomTests(facts.nonLiteralSources, group.flags)
167
+ return delimiters.some(
168
+ (delimiter) =>
169
+ isSoleMatchOf(delimiter, facts, ignoreCase, atomTests) &&
170
+ hasAtMostOneVariableTermPerSegment(facts.delimiterPositions[delimiter], facts)
171
+ )
172
+ }
173
+
174
+ /**
175
+ * Detects repeated groups that can backtrack exponentially or polynomially, which would stall the
176
+ * synchronous capture path. A group repeated more than once that contains a variable-length term, as in
177
+ * `(a+)+` or `(a{1,3}){20}`, is flagged unless a required delimiter that no other term can match splits
178
+ * every iteration, as in `(?:/[^/]+)*` or `([0-9]{1,3}\.){3}`.
179
+ * Overlapping alternation such as `(a|a)*` is not detected.
180
+ */
181
+ export const hasNestedQuantifier = (pattern: string): boolean => {
182
+ const groups: Group[] = [newGroup('')]
183
+ let closedGroup: Group | undefined
184
+ let lastAtom: Atom | undefined
185
+ let previousWasQuantifier = false
186
+
187
+ for (let index = 0; index < pattern.length; index++) {
188
+ const character = pattern[index]
189
+ const justClosed = closedGroup
190
+ const atomBefore = lastAtom
191
+ const isLazyModifier = previousWasQuantifier && character === '?'
192
+ closedGroup = undefined
193
+ lastAtom = undefined
194
+ previousWasQuantifier = false
195
+ const current = groups[groups.length - 1]
196
+
197
+ if (isLazyModifier) {
198
+ continue
199
+ }
200
+
201
+ const quantifier = justClosed || atomBefore ? quantifierAt(pattern, index) : null
202
+ if (quantifier) {
203
+ if (justClosed && quantifier.max > 1 && justClosed.variable && !isDelimiterSplit(justClosed)) {
204
+ return true
205
+ }
206
+ if (atomBefore) {
207
+ atomBefore.min *= quantifier.min
208
+ atomBefore.max *= quantifier.max
209
+ }
210
+ current.variable ||= quantifier.max > quantifier.min
211
+ index += quantifier.length - 1
212
+ previousWasQuantifier = true
213
+ continue
214
+ }
215
+
216
+ let atom: Atom | undefined
217
+ if (character === '\\') {
218
+ const escaped = pattern[index + 1] ?? ''
219
+ index++
220
+ if (/[uxckpP0-9]/.test(escaped)) {
221
+ current.complex = true
222
+ atom = { source: '[^]', min: 1, max: 1 }
223
+ } else if (escaped === 'b' || escaped === 'B') {
224
+ atom = { source: '', zeroWidth: true, min: 1, max: 1 }
225
+ } else if (/[dDwWsS]/.test(escaped)) {
226
+ atom = { source: `\\${escaped}`, min: 1, max: 1 }
227
+ } else {
228
+ atom = { source: `\\${escaped}`, literal: ESCAPED_CONTROL_CHARACTERS[escaped] ?? escaped, min: 1, max: 1 }
229
+ }
230
+ } else if (character === '[') {
231
+ const start = index
232
+ for (index++; index < pattern.length && pattern[index] !== ']'; index++) {
233
+ if (pattern[index] === '\\') {
234
+ index++
235
+ }
236
+ }
237
+ atom = { source: pattern.slice(start, index + 1), min: 1, max: 1 }
238
+ } else if (character === '(') {
239
+ const group = newGroup(current.flags)
240
+ if (pattern[index + 1] === '?') {
241
+ const rest = pattern.slice(index)
242
+ const prefix = /^\(\?(?::|=|!|<=|<!|<[^>]*>)/.exec(rest)
243
+ const modifiers = prefix ? null : MODIFIER_GROUP_PREFIX.exec(rest)
244
+ if (prefix) {
245
+ index += prefix[0].length - 1
246
+ group.complex = /^\(\?<?[=!]/.test(prefix[0])
247
+ } else if (modifiers) {
248
+ index += modifiers[0].length - 1
249
+ group.complex = true
250
+ group.flags = applyModifiers(current.flags, modifiers[1], modifiers[2] ?? '')
251
+ } else {
252
+ index++
253
+ group.complex = true
254
+ }
255
+ }
256
+ groups.push(group)
257
+ } else if (character === ')') {
258
+ if (groups.length > 1) {
259
+ const group = groups.pop() as Group
260
+ const parent = groups[groups.length - 1]
261
+ parent.variable ||= group.variable
262
+ parent.complex = true
263
+ closedGroup = group
264
+ }
265
+ } else if (character === '|') {
266
+ current.complex = true
267
+ } else if (character === '^' || character === '$') {
268
+ atom = { source: '', zeroWidth: true, min: 1, max: 1 }
269
+ } else if (character === '.') {
270
+ atom = { source: '.', min: 1, max: 1 }
271
+ } else {
272
+ atom = { source: character, literal: character, min: 1, max: 1 }
273
+ }
274
+
275
+ if (atom) {
276
+ current.atoms.push(atom)
277
+ lastAtom = atom
278
+ }
279
+ }
280
+ return false
281
+ }
282
+
283
+ const MAX_COMPILED_PATTERNS = 100
284
+ const INVALID = 'invalid'
285
+ const UNSAFE = 'unsafe'
286
+ type CompiledPattern = RegExp | typeof INVALID | typeof UNSAFE
287
+ const compiledPatterns = new Map<string, CompiledPattern>()
288
+ const warnedPatterns = new Set<string>()
289
+
290
+ // Reads console.warn at call time and skips console plugins (session replay, logs capture) that
291
+ // mark their wrappers with `__rrweb_original__`, so the warning never becomes a captured customer log.
292
+ const warnRejectedPattern = (pattern: string): void => {
293
+ try {
294
+ let warn: unknown = typeof console !== 'undefined' ? console.warn : undefined
295
+ while (typeof warn === 'function' && '__rrweb_original__' in warn) {
296
+ warn = (warn as { __rrweb_original__?: unknown }).__rrweb_original__
297
+ }
298
+ if (typeof warn === 'function') {
299
+ warn.call(
300
+ console,
301
+ '[PostHog]',
302
+ `Ignoring regex "${pattern}": a repeated group containing repetition can stall matching, so filters using it never match.`
303
+ )
304
+ }
305
+ } catch {
306
+ // Logging must never interrupt matching.
307
+ }
308
+ }
309
+
310
+ const compilePattern = (pattern: string): CompiledPattern => {
311
+ if (typeof pattern !== 'string') {
312
+ return INVALID
313
+ }
314
+ const cached = compiledPatterns.get(pattern)
315
+ if (cached !== undefined) {
316
+ return cached
317
+ }
318
+
319
+ let compiled: CompiledPattern
320
+ try {
321
+ compiled = new RegExp(pattern)
322
+ } catch {
323
+ compiled = INVALID
324
+ }
325
+ if (compiled !== INVALID && hasNestedQuantifier(pattern)) {
326
+ compiled = UNSAFE
327
+ if (!warnedPatterns.has(pattern) && warnedPatterns.size < MAX_COMPILED_PATTERNS) {
328
+ warnedPatterns.add(pattern)
329
+ warnRejectedPattern(pattern)
330
+ }
331
+ }
332
+
333
+ // Map.prototype.keys is unavailable in IE11, so drop the whole cache instead of the oldest entry.
334
+ if (compiledPatterns.size >= MAX_COMPILED_PATTERNS) {
335
+ compiledPatterns.clear()
336
+ }
337
+ compiledPatterns.set(pattern, compiled)
338
+ return compiled
339
+ }
340
+
341
+ const isUnsafePattern = (pattern: string): boolean => compilePattern(pattern) === UNSAFE
342
+
14
343
  export const isMatchingRegex = (value: string, pattern: string): boolean => {
15
- if (!isValidRegex(pattern)) {
344
+ const regex = compilePattern(pattern)
345
+ if (regex === INVALID || regex === UNSAFE) {
16
346
  return false
17
347
  }
18
348
 
19
349
  try {
20
- return new RegExp(pattern).test(value)
350
+ return regex.test(value)
21
351
  } catch {
22
352
  return false
23
353
  }
@@ -29,7 +359,9 @@ export const propertyComparisons: Record<PropertyOperator, (targets: string[], v
29
359
  exact: (targets, values) => values.some((value) => targets.some((target) => value === target)),
30
360
  is_not: (targets, values) => values.every((value) => targets.every((target) => value !== target)),
31
361
  regex: (targets, values) => values.some((value) => targets.some((target) => isMatchingRegex(value, target))),
32
- not_regex: (targets, values) => values.every((value) => targets.every((target) => !isMatchingRegex(value, target))),
362
+ not_regex: (targets, values) =>
363
+ !targets.some(isUnsafePattern) &&
364
+ values.every((value) => targets.every((target) => !isMatchingRegex(value, target))),
33
365
  icontains: (targets, values) =>
34
366
  values.map(toLowerCase).some((value) => targets.map(toLowerCase).some((target) => value.includes(target))),
35
367
  not_icontains: (targets, values) =>