@libreflare/worker-runtime 0.0.0
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.
- package/README.md +41 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/log-handler.d.ts +23 -0
- package/dist/log-handler.d.ts.map +1 -0
- package/dist/log-handler.js +167 -0
- package/dist/log-handler.js.map +1 -0
- package/dist/rule-evaluator.d.ts +32 -0
- package/dist/rule-evaluator.d.ts.map +1 -0
- package/dist/rule-evaluator.js +1674 -0
- package/dist/rule-evaluator.js.map +1 -0
- package/package.json +49 -0
|
@@ -0,0 +1,1674 @@
|
|
|
1
|
+
// ─── Tokenizer ────────────────────────────────────────────────────────────────
|
|
2
|
+
function pushWarning(warnings, message) {
|
|
3
|
+
if (!warnings.includes(message))
|
|
4
|
+
warnings.push(message);
|
|
5
|
+
}
|
|
6
|
+
const KEYWORD_OPERATORS = new Set([
|
|
7
|
+
'eq', 'ne', 'lt', 'le', 'gt', 'ge',
|
|
8
|
+
'contains', 'matches', 'wildcard', 'in', 'exists',
|
|
9
|
+
'and', 'or', 'not', 'strict',
|
|
10
|
+
]);
|
|
11
|
+
function tokenize(source, warnings) {
|
|
12
|
+
const tokens = [];
|
|
13
|
+
let pos = 0;
|
|
14
|
+
while (pos < source.length) {
|
|
15
|
+
// Skip whitespace
|
|
16
|
+
if (/\s/.test(source[pos])) {
|
|
17
|
+
pos++;
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
const ch = source[pos];
|
|
21
|
+
// String literal
|
|
22
|
+
if (ch === '"') {
|
|
23
|
+
let value = '';
|
|
24
|
+
pos++; // skip opening "
|
|
25
|
+
while (pos < source.length && source[pos] !== '"') {
|
|
26
|
+
if (source[pos] === '\\' && source[pos + 1] === '"') {
|
|
27
|
+
value += '"';
|
|
28
|
+
pos += 2;
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
value += source[pos++];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
pos++; // skip closing "
|
|
35
|
+
tokens.push({ kind: 'String', value, pos: pos - value.length - 2 });
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
// Number (including negative) and CIDR notation (e.g. "10.0.1.0/24")
|
|
39
|
+
if (/\d/.test(ch) || (ch === '-' && /\d/.test(source[pos + 1] ?? ''))) {
|
|
40
|
+
const start = pos;
|
|
41
|
+
let num = '';
|
|
42
|
+
if (ch === '-') {
|
|
43
|
+
num += '-';
|
|
44
|
+
pos++;
|
|
45
|
+
}
|
|
46
|
+
while (pos < source.length && /[\d.]/.test(source[pos]))
|
|
47
|
+
num += source[pos++];
|
|
48
|
+
// Consume CIDR prefix (/NN) when immediately following an IP address
|
|
49
|
+
if (source[pos] === '/' && /\d/.test(source[pos + 1] ?? '')) {
|
|
50
|
+
num += source[pos++]; // '/'
|
|
51
|
+
while (pos < source.length && /\d/.test(source[pos]))
|
|
52
|
+
num += source[pos++];
|
|
53
|
+
}
|
|
54
|
+
tokens.push({ kind: 'Number', value: num, pos: start });
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
// Dollar sign prefix (list reference: $name)
|
|
58
|
+
if (ch === '$') {
|
|
59
|
+
const start = pos++;
|
|
60
|
+
let name = '$';
|
|
61
|
+
while (pos < source.length && /[\w]/.test(source[pos]))
|
|
62
|
+
name += source[pos++];
|
|
63
|
+
tokens.push({ kind: 'Identifier', value: name, pos: start });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
// Structural single characters
|
|
67
|
+
if (ch === '(') {
|
|
68
|
+
tokens.push({ kind: 'LParen', value: '(', pos });
|
|
69
|
+
pos++;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (ch === ')') {
|
|
73
|
+
tokens.push({ kind: 'RParen', value: ')', pos });
|
|
74
|
+
pos++;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (ch === '{') {
|
|
78
|
+
tokens.push({ kind: 'LBrace', value: '{', pos });
|
|
79
|
+
pos++;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (ch === '}') {
|
|
83
|
+
tokens.push({ kind: 'RBrace', value: '}', pos });
|
|
84
|
+
pos++;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (ch === '[') {
|
|
88
|
+
tokens.push({ kind: 'LBracket', value: '[', pos });
|
|
89
|
+
pos++;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (ch === ']') {
|
|
93
|
+
tokens.push({ kind: 'RBracket', value: ']', pos });
|
|
94
|
+
pos++;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (ch === '*') {
|
|
98
|
+
tokens.push({ kind: 'Star', value: '*', pos });
|
|
99
|
+
pos++;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (ch === ',') {
|
|
103
|
+
pos++;
|
|
104
|
+
continue;
|
|
105
|
+
} // commas are optional separators, skip
|
|
106
|
+
// == and !=
|
|
107
|
+
if (ch === '=' && source[pos + 1] === '=') {
|
|
108
|
+
tokens.push({ kind: 'Equals', value: '==', pos });
|
|
109
|
+
pos += 2;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (ch === '!' && source[pos + 1] === '=') {
|
|
113
|
+
tokens.push({ kind: 'NotEquals', value: '!=', pos });
|
|
114
|
+
pos += 2;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
// Identifiers and keywords (dots, underscores, hyphens allowed in field names)
|
|
118
|
+
if (/[a-zA-Z_]/.test(ch)) {
|
|
119
|
+
const start = pos;
|
|
120
|
+
let word = '';
|
|
121
|
+
while (pos < source.length && /[\w.-]/.test(source[pos]))
|
|
122
|
+
word += source[pos++];
|
|
123
|
+
if (word === 'true' || word === 'false') {
|
|
124
|
+
tokens.push({ kind: 'Boolean', value: word, pos: start });
|
|
125
|
+
}
|
|
126
|
+
else if (KEYWORD_OPERATORS.has(word)) {
|
|
127
|
+
tokens.push({ kind: 'Operator', value: word, pos: start });
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
tokens.push({ kind: 'Identifier', value: word, pos: start });
|
|
131
|
+
}
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
// Unknown character — skip with warning
|
|
135
|
+
pushWarning(warnings, `[rule-evaluator] unexpected char '${ch}' at pos ${pos}`);
|
|
136
|
+
pos++;
|
|
137
|
+
}
|
|
138
|
+
tokens.push({ kind: 'EOF', value: '', pos });
|
|
139
|
+
return tokens;
|
|
140
|
+
}
|
|
141
|
+
// ─── Parser ───────────────────────────────────────────────────────────────────
|
|
142
|
+
class Parser {
|
|
143
|
+
tokens;
|
|
144
|
+
source;
|
|
145
|
+
warnings;
|
|
146
|
+
pos = 0;
|
|
147
|
+
constructor(tokens, source, warnings) {
|
|
148
|
+
this.tokens = tokens;
|
|
149
|
+
this.source = source;
|
|
150
|
+
this.warnings = warnings;
|
|
151
|
+
}
|
|
152
|
+
parse() {
|
|
153
|
+
const node = this.parseOr();
|
|
154
|
+
if (this.peek().kind !== 'EOF') {
|
|
155
|
+
// Remaining tokens — shouldn't happen in well-formed expressions
|
|
156
|
+
pushWarning(this.warnings, '[rule-evaluator] unexpected tokens after expression end');
|
|
157
|
+
}
|
|
158
|
+
return node;
|
|
159
|
+
}
|
|
160
|
+
peek(offset = 0) {
|
|
161
|
+
const i = this.pos + offset;
|
|
162
|
+
return i < this.tokens.length ? this.tokens[i] : { kind: 'EOF', value: '', pos: -1 };
|
|
163
|
+
}
|
|
164
|
+
consume() {
|
|
165
|
+
return this.tokens[this.pos++] ?? { kind: 'EOF', value: '', pos: -1 };
|
|
166
|
+
}
|
|
167
|
+
rawSpan(startPos) {
|
|
168
|
+
const lastToken = this.tokens[this.pos - 1];
|
|
169
|
+
if (!lastToken)
|
|
170
|
+
return this.source.slice(startPos).trim();
|
|
171
|
+
const tokenLen = lastToken.kind === 'String'
|
|
172
|
+
? lastToken.value.length + 2 // account for surrounding quote characters
|
|
173
|
+
: lastToken.value.length;
|
|
174
|
+
return this.source.slice(startPos, lastToken.pos + tokenLen).trim();
|
|
175
|
+
}
|
|
176
|
+
// or_expr = and_expr ("or" and_expr)*
|
|
177
|
+
parseOr() {
|
|
178
|
+
const startPos = this.peek().pos;
|
|
179
|
+
let left = this.parseAnd();
|
|
180
|
+
while (this.peek().kind === 'Operator' && this.peek().value === 'or') {
|
|
181
|
+
this.consume(); // 'or'
|
|
182
|
+
const right = this.parseAnd();
|
|
183
|
+
const raw = this.rawSpan(startPos);
|
|
184
|
+
left = { kind: 'Or', left, right, raw };
|
|
185
|
+
}
|
|
186
|
+
return left;
|
|
187
|
+
}
|
|
188
|
+
// and_expr = not_expr ("and" not_expr)*
|
|
189
|
+
parseAnd() {
|
|
190
|
+
const startPos = this.peek().pos;
|
|
191
|
+
let left = this.parseNot();
|
|
192
|
+
while (this.peek().kind === 'Operator' && this.peek().value === 'and') {
|
|
193
|
+
this.consume(); // 'and'
|
|
194
|
+
const right = this.parseNot();
|
|
195
|
+
const raw = this.rawSpan(startPos);
|
|
196
|
+
left = { kind: 'And', left, right, raw };
|
|
197
|
+
}
|
|
198
|
+
return left;
|
|
199
|
+
}
|
|
200
|
+
// not_expr = "not" not_expr | primary
|
|
201
|
+
parseNot() {
|
|
202
|
+
const startPos = this.peek().pos;
|
|
203
|
+
if (this.peek().kind === 'Operator' && this.peek().value === 'not') {
|
|
204
|
+
// Look-ahead: if next is a function call or paren, it's logical not
|
|
205
|
+
// If current is 'not' followed by Identifier + ('exists'|comp_op), let parsePrimary handle it
|
|
206
|
+
const savedPos = this.pos;
|
|
207
|
+
this.consume(); // 'not'
|
|
208
|
+
// If next is '(' or a function name like 'any', 'starts_with', etc — logical not
|
|
209
|
+
const next = this.peek();
|
|
210
|
+
if (next.kind === 'LParen' ||
|
|
211
|
+
(next.kind === 'Identifier' && this.isFuncName(next.value)) ||
|
|
212
|
+
(next.kind === 'Operator' && next.value === 'not')) {
|
|
213
|
+
const operand = this.parseNot();
|
|
214
|
+
const raw = this.rawSpan(startPos);
|
|
215
|
+
return { kind: 'Not', operand, raw };
|
|
216
|
+
}
|
|
217
|
+
// Otherwise, it might be 'not (ip.src in $list)' — restore and let parsePrimary handle the paren
|
|
218
|
+
// Actually if next is '(' we already handle it above. If next is identifier, it could be
|
|
219
|
+
// 'not some_field exists' or 'not (expr)' — the 'not' is logical here too.
|
|
220
|
+
// Restore and re-parse as logical not around primary
|
|
221
|
+
this.pos = savedPos;
|
|
222
|
+
this.consume(); // 'not' again
|
|
223
|
+
const operand = this.parsePrimary();
|
|
224
|
+
const raw = this.rawSpan(startPos);
|
|
225
|
+
return { kind: 'Not', operand, raw };
|
|
226
|
+
}
|
|
227
|
+
return this.parsePrimary();
|
|
228
|
+
}
|
|
229
|
+
isFuncName(name) {
|
|
230
|
+
return ['any', 'all', 'starts_with', 'ends_with', 'lower', 'len',
|
|
231
|
+
'url_decode', 'concat', 'to_string', 'regex_replace', 'lookup_json_string'].includes(name);
|
|
232
|
+
}
|
|
233
|
+
// primary = "(" expr ")" | func_call | comparison | bool_field
|
|
234
|
+
parsePrimary() {
|
|
235
|
+
const startPos = this.peek().pos;
|
|
236
|
+
// Parenthesised expression
|
|
237
|
+
if (this.peek().kind === 'LParen') {
|
|
238
|
+
this.consume(); // '('
|
|
239
|
+
const node = this.parseOr();
|
|
240
|
+
if (this.peek().kind === 'RParen') {
|
|
241
|
+
this.consume(); // ')'
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
pushWarning(this.warnings, '[rule-evaluator] missing closing parenthesis');
|
|
245
|
+
}
|
|
246
|
+
return node;
|
|
247
|
+
}
|
|
248
|
+
// Function call (starts with known function name)
|
|
249
|
+
if (this.peek().kind === 'Identifier' && this.isFuncName(this.peek().value)) {
|
|
250
|
+
return this.parseFuncCall(startPos);
|
|
251
|
+
}
|
|
252
|
+
// Field reference (Identifier or known CF field)
|
|
253
|
+
if (this.peek().kind === 'Identifier' || this.peek().kind === 'Boolean') {
|
|
254
|
+
return this.parseFieldOrComparison(startPos);
|
|
255
|
+
}
|
|
256
|
+
// Boolean literal used directly (e.g., `true`)
|
|
257
|
+
if (this.peek().kind === 'Boolean') {
|
|
258
|
+
const val = this.consume().value === 'true';
|
|
259
|
+
return { kind: 'BoolField', name: String(val), raw: String(val) };
|
|
260
|
+
}
|
|
261
|
+
pushWarning(this.warnings, `[rule-evaluator] unexpected token: ${this.peek().kind} "${this.peek().value}"`);
|
|
262
|
+
this.consume();
|
|
263
|
+
return { kind: 'BoolField', name: 'false', raw: 'false' };
|
|
264
|
+
}
|
|
265
|
+
parseFieldOrComparison(startPos) {
|
|
266
|
+
const fieldNode = this.parseFieldRef();
|
|
267
|
+
// 'not exists' — two-token operator
|
|
268
|
+
if (this.peek().kind === 'Operator' && this.peek().value === 'not' &&
|
|
269
|
+
this.peek(1).kind === 'Operator' && this.peek(1).value === 'exists') {
|
|
270
|
+
this.consume();
|
|
271
|
+
this.consume();
|
|
272
|
+
const raw = this.rawSpan(startPos);
|
|
273
|
+
return { kind: 'Comparison', left: fieldNode, op: 'not_exists', raw };
|
|
274
|
+
}
|
|
275
|
+
// 'exists'
|
|
276
|
+
if (this.peek().kind === 'Operator' && this.peek().value === 'exists') {
|
|
277
|
+
this.consume();
|
|
278
|
+
const raw = this.rawSpan(startPos);
|
|
279
|
+
return { kind: 'Comparison', left: fieldNode, op: 'exists', raw };
|
|
280
|
+
}
|
|
281
|
+
// Comparison operator
|
|
282
|
+
const op = this.tryParseCompOp();
|
|
283
|
+
if (op !== null) {
|
|
284
|
+
const right = this.parseValue();
|
|
285
|
+
const raw = this.rawSpan(startPos);
|
|
286
|
+
return { kind: 'Comparison', left: fieldNode, op, right, raw };
|
|
287
|
+
}
|
|
288
|
+
// == / != (used inside any()/all())
|
|
289
|
+
if (this.peek().kind === 'Equals') {
|
|
290
|
+
this.consume();
|
|
291
|
+
const right = this.parseValue();
|
|
292
|
+
const raw = this.rawSpan(startPos);
|
|
293
|
+
return { kind: 'Comparison', left: fieldNode, op: 'eq', right, raw };
|
|
294
|
+
}
|
|
295
|
+
if (this.peek().kind === 'NotEquals') {
|
|
296
|
+
this.consume();
|
|
297
|
+
const right = this.parseValue();
|
|
298
|
+
const raw = this.rawSpan(startPos);
|
|
299
|
+
return { kind: 'Comparison', left: fieldNode, op: 'ne', right, raw };
|
|
300
|
+
}
|
|
301
|
+
// No operator — bare boolean field
|
|
302
|
+
const raw = this.rawSpan(startPos);
|
|
303
|
+
if (fieldNode.kind === 'Field') {
|
|
304
|
+
return { kind: 'BoolField', name: fieldNode.name, raw };
|
|
305
|
+
}
|
|
306
|
+
// ArrayField or MapField without operator — treat as exists
|
|
307
|
+
return { kind: 'Comparison', left: fieldNode, op: 'exists', raw };
|
|
308
|
+
}
|
|
309
|
+
parseFieldRef() {
|
|
310
|
+
const name = this.consume().value; // Identifier
|
|
311
|
+
// Optional subscript: [*] or ["key"] or [0]
|
|
312
|
+
if (this.peek().kind === 'LBracket') {
|
|
313
|
+
this.consume(); // '['
|
|
314
|
+
if (this.peek().kind === 'Star') {
|
|
315
|
+
this.consume(); // '*'
|
|
316
|
+
if (this.peek().kind === 'RBracket')
|
|
317
|
+
this.consume(); // ']'
|
|
318
|
+
return { kind: 'ArrayField', name };
|
|
319
|
+
}
|
|
320
|
+
if (this.peek().kind === 'String') {
|
|
321
|
+
const key = this.consume().value;
|
|
322
|
+
if (this.peek().kind === 'RBracket')
|
|
323
|
+
this.consume(); // ']'
|
|
324
|
+
// Check for additional [*] — e.g., headers["name"][*]
|
|
325
|
+
if (this.peek().kind === 'LBracket' && this.peek(1).kind === 'Star') {
|
|
326
|
+
this.consume();
|
|
327
|
+
this.consume(); // '[' '*'
|
|
328
|
+
if (this.peek().kind === 'RBracket')
|
|
329
|
+
this.consume();
|
|
330
|
+
return { kind: 'MapField', name, key }; // treat result as array
|
|
331
|
+
}
|
|
332
|
+
return { kind: 'MapField', name, key };
|
|
333
|
+
}
|
|
334
|
+
if (this.peek().kind === 'Number') {
|
|
335
|
+
this.consume(); // skip index — treat as plain field for simplicity
|
|
336
|
+
if (this.peek().kind === 'RBracket')
|
|
337
|
+
this.consume();
|
|
338
|
+
return { kind: 'Field', name };
|
|
339
|
+
}
|
|
340
|
+
if (this.peek().kind === 'RBracket')
|
|
341
|
+
this.consume();
|
|
342
|
+
}
|
|
343
|
+
return { kind: 'Field', name };
|
|
344
|
+
}
|
|
345
|
+
tryParseCompOp() {
|
|
346
|
+
const t = this.peek();
|
|
347
|
+
if (t.kind !== 'Operator')
|
|
348
|
+
return null;
|
|
349
|
+
switch (t.value) {
|
|
350
|
+
case 'eq':
|
|
351
|
+
this.consume();
|
|
352
|
+
return 'eq';
|
|
353
|
+
case 'ne':
|
|
354
|
+
this.consume();
|
|
355
|
+
return 'ne';
|
|
356
|
+
case 'lt':
|
|
357
|
+
this.consume();
|
|
358
|
+
return 'lt';
|
|
359
|
+
case 'le':
|
|
360
|
+
this.consume();
|
|
361
|
+
return 'le';
|
|
362
|
+
case 'gt':
|
|
363
|
+
this.consume();
|
|
364
|
+
return 'gt';
|
|
365
|
+
case 'ge':
|
|
366
|
+
this.consume();
|
|
367
|
+
return 'ge';
|
|
368
|
+
case 'contains':
|
|
369
|
+
this.consume();
|
|
370
|
+
return 'contains';
|
|
371
|
+
case 'matches':
|
|
372
|
+
this.consume();
|
|
373
|
+
return 'matches';
|
|
374
|
+
case 'wildcard':
|
|
375
|
+
this.consume();
|
|
376
|
+
return 'wildcard';
|
|
377
|
+
case 'in':
|
|
378
|
+
this.consume();
|
|
379
|
+
return 'in';
|
|
380
|
+
case 'strict':
|
|
381
|
+
if (this.peek(1).kind === 'Operator' && this.peek(1).value === 'wildcard') {
|
|
382
|
+
this.consume();
|
|
383
|
+
this.consume();
|
|
384
|
+
return 'strict_wildcard';
|
|
385
|
+
}
|
|
386
|
+
return null;
|
|
387
|
+
default: return null;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
parseValue() {
|
|
391
|
+
const t = this.peek();
|
|
392
|
+
if (t.kind === 'String') {
|
|
393
|
+
this.consume();
|
|
394
|
+
return { kind: 'StringLiteral', value: t.value };
|
|
395
|
+
}
|
|
396
|
+
if (t.kind === 'Number') {
|
|
397
|
+
this.consume();
|
|
398
|
+
return { kind: 'NumberLiteral', value: parseFloat(t.value) };
|
|
399
|
+
}
|
|
400
|
+
if (t.kind === 'Boolean') {
|
|
401
|
+
this.consume();
|
|
402
|
+
return { kind: 'BoolLiteral', value: t.value === 'true' };
|
|
403
|
+
}
|
|
404
|
+
if (t.kind === 'LBrace')
|
|
405
|
+
return this.parseSetLiteral();
|
|
406
|
+
if (t.kind === 'Identifier' && t.value.startsWith('$')) {
|
|
407
|
+
this.consume();
|
|
408
|
+
return { kind: 'ListRef', name: t.value.slice(1) };
|
|
409
|
+
}
|
|
410
|
+
// Unquoted value — treat as string (may happen with some expressions)
|
|
411
|
+
if (t.kind === 'Identifier') {
|
|
412
|
+
this.consume();
|
|
413
|
+
return { kind: 'StringLiteral', value: t.value };
|
|
414
|
+
}
|
|
415
|
+
return { kind: 'StringLiteral', value: '' };
|
|
416
|
+
}
|
|
417
|
+
parseSetLiteral() {
|
|
418
|
+
this.consume(); // '{'
|
|
419
|
+
const values = [];
|
|
420
|
+
while (this.peek().kind !== 'RBrace' && this.peek().kind !== 'EOF') {
|
|
421
|
+
const t = this.peek();
|
|
422
|
+
if (t.kind === 'String') {
|
|
423
|
+
values.push(t.value);
|
|
424
|
+
this.consume();
|
|
425
|
+
}
|
|
426
|
+
else if (t.kind === 'Number') {
|
|
427
|
+
// Keep IP addresses and CIDR notation as strings so dots and slashes are preserved.
|
|
428
|
+
// Plain integers and decimals are stored as numbers for numeric comparisons.
|
|
429
|
+
const v = t.value;
|
|
430
|
+
values.push(/[./]/.test(v) ? v : parseFloat(v));
|
|
431
|
+
this.consume();
|
|
432
|
+
}
|
|
433
|
+
else if (t.kind === 'Identifier') {
|
|
434
|
+
values.push(t.value);
|
|
435
|
+
this.consume();
|
|
436
|
+
} // unquoted
|
|
437
|
+
else {
|
|
438
|
+
pushWarning(this.warnings, `[rule-evaluator] unexpected token in set literal: ${t.kind} "${t.value}"`);
|
|
439
|
+
this.consume();
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if (this.peek().kind === 'RBrace') {
|
|
443
|
+
this.consume(); // '}'
|
|
444
|
+
}
|
|
445
|
+
else {
|
|
446
|
+
pushWarning(this.warnings, '[rule-evaluator] missing closing brace');
|
|
447
|
+
}
|
|
448
|
+
return { kind: 'SetLiteral', values };
|
|
449
|
+
}
|
|
450
|
+
// func_call = funcName "(" args ")"
|
|
451
|
+
parseFuncCall(startPos) {
|
|
452
|
+
const name = this.consume().value; // function name
|
|
453
|
+
if (this.peek().kind !== 'LParen') {
|
|
454
|
+
// Not actually a function call — treat as field
|
|
455
|
+
return this.parseFieldOrComparison(startPos);
|
|
456
|
+
}
|
|
457
|
+
this.consume(); // '('
|
|
458
|
+
if (name === 'any' || name === 'all') {
|
|
459
|
+
return this.parseAnyAll(name, startPos);
|
|
460
|
+
}
|
|
461
|
+
if (name === 'starts_with' || name === 'ends_with') {
|
|
462
|
+
// starts_with(field, "string")
|
|
463
|
+
const field = this.parseFieldRef();
|
|
464
|
+
if (this.peek().kind === 'Operator' || this.peek().kind === 'Identifier')
|
|
465
|
+
this.consume(); // optional comma already skipped
|
|
466
|
+
const str = this.parseValue();
|
|
467
|
+
if (this.peek().kind === 'RParen') {
|
|
468
|
+
this.consume();
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
pushWarning(this.warnings, `[rule-evaluator] missing closing parenthesis for function '${name}'`);
|
|
472
|
+
}
|
|
473
|
+
const raw = this.rawSpan(startPos);
|
|
474
|
+
return { kind: 'Func', name, args: [field, str], raw };
|
|
475
|
+
}
|
|
476
|
+
// lower(field), len(field), etc — used as atomic expression or left-side of comparison
|
|
477
|
+
const arg = this.parseFieldRef();
|
|
478
|
+
if (this.peek().kind === 'RParen') {
|
|
479
|
+
this.consume();
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
pushWarning(this.warnings, `[rule-evaluator] missing closing parenthesis for function '${name}'`);
|
|
483
|
+
}
|
|
484
|
+
// Check for [*] after function — lower(field[*])[*]
|
|
485
|
+
let isArray = false;
|
|
486
|
+
if (this.peek().kind === 'LBracket' && this.peek(1).kind === 'Star') {
|
|
487
|
+
this.consume();
|
|
488
|
+
this.consume();
|
|
489
|
+
if (this.peek().kind === 'RBracket')
|
|
490
|
+
this.consume();
|
|
491
|
+
isArray = true;
|
|
492
|
+
}
|
|
493
|
+
const raw = this.rawSpan(startPos);
|
|
494
|
+
const funcNode = { kind: 'Func', name, args: [arg], raw };
|
|
495
|
+
// Check if followed by a comparison operator
|
|
496
|
+
const op = this.tryParseCompOp();
|
|
497
|
+
if (op === null && this.peek().kind !== 'Equals' && this.peek().kind !== 'NotEquals') {
|
|
498
|
+
return funcNode;
|
|
499
|
+
}
|
|
500
|
+
const actualOp = op ?? (this.peek().kind === 'Equals' ? (this.consume(), 'eq') : (this.consume(), 'ne'));
|
|
501
|
+
const right = this.parseValue();
|
|
502
|
+
const compRaw = this.rawSpan(startPos);
|
|
503
|
+
// Attach isArray info via a special func node
|
|
504
|
+
const leftNode = isArray
|
|
505
|
+
? { kind: 'Func', name: name + '_array', args: [arg], raw: funcNode.raw }
|
|
506
|
+
: funcNode;
|
|
507
|
+
return { kind: 'Comparison', left: leftNode, op: actualOp, right, raw: compRaw };
|
|
508
|
+
}
|
|
509
|
+
// any(field[*] op value) or any(lower(field[*])[*] op value)
|
|
510
|
+
parseAnyAll(name, startPos) {
|
|
511
|
+
// The left side can be:
|
|
512
|
+
// arrayField[*]
|
|
513
|
+
// lower(arrayField[*])[*]
|
|
514
|
+
// mapField["key"][*]
|
|
515
|
+
let leftField;
|
|
516
|
+
if (this.peek().kind === 'Identifier' && this.isFuncName(this.peek().value)) {
|
|
517
|
+
// lower(...)[*]
|
|
518
|
+
const funcStartPos = this.peek().pos;
|
|
519
|
+
const funcName = this.consume().value;
|
|
520
|
+
if (this.peek().kind === 'LParen')
|
|
521
|
+
this.consume();
|
|
522
|
+
const innerField = this.parseFieldRef();
|
|
523
|
+
if (this.peek().kind === 'RParen') {
|
|
524
|
+
this.consume();
|
|
525
|
+
}
|
|
526
|
+
else {
|
|
527
|
+
pushWarning(this.warnings, `[rule-evaluator] missing closing parenthesis for function '${funcName}'`);
|
|
528
|
+
}
|
|
529
|
+
// [*] after function
|
|
530
|
+
if (this.peek().kind === 'LBracket' && this.peek(1).kind === 'Star') {
|
|
531
|
+
this.consume();
|
|
532
|
+
this.consume();
|
|
533
|
+
if (this.peek().kind === 'RBracket')
|
|
534
|
+
this.consume();
|
|
535
|
+
}
|
|
536
|
+
const funcRaw = this.rawSpan(funcStartPos);
|
|
537
|
+
leftField = { kind: 'Func', name: funcName + '_array', args: [innerField], raw: funcRaw };
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
leftField = this.parseFieldRef();
|
|
541
|
+
}
|
|
542
|
+
// Parse operator
|
|
543
|
+
let op;
|
|
544
|
+
if (this.peek().kind === 'Equals') {
|
|
545
|
+
this.consume();
|
|
546
|
+
op = 'eq';
|
|
547
|
+
}
|
|
548
|
+
else if (this.peek().kind === 'NotEquals') {
|
|
549
|
+
this.consume();
|
|
550
|
+
op = 'ne';
|
|
551
|
+
}
|
|
552
|
+
else {
|
|
553
|
+
op = this.tryParseCompOp() ?? 'eq';
|
|
554
|
+
}
|
|
555
|
+
const right = this.parseValue();
|
|
556
|
+
if (this.peek().kind === 'RParen') {
|
|
557
|
+
this.consume(); // ')'
|
|
558
|
+
}
|
|
559
|
+
else {
|
|
560
|
+
pushWarning(this.warnings, `[rule-evaluator] missing closing parenthesis for function '${name}'`);
|
|
561
|
+
}
|
|
562
|
+
const raw = this.rawSpan(startPos);
|
|
563
|
+
return { kind: 'Func', name, args: [leftField, { kind: 'StringLiteral', value: op }, right], raw };
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
function getCookieMap(ctx) {
|
|
567
|
+
if (ctx.cookieMap)
|
|
568
|
+
return ctx.cookieMap;
|
|
569
|
+
ctx.cookieMap = {};
|
|
570
|
+
const raw = ctx.request.headers.get('cookie') ?? '';
|
|
571
|
+
for (const part of raw.split(';')) {
|
|
572
|
+
const eq = part.indexOf('=');
|
|
573
|
+
if (eq === -1)
|
|
574
|
+
continue;
|
|
575
|
+
const k = part.slice(0, eq).trim();
|
|
576
|
+
const v = part.slice(eq + 1).trim();
|
|
577
|
+
ctx.cookieMap[k] = v;
|
|
578
|
+
}
|
|
579
|
+
return ctx.cookieMap;
|
|
580
|
+
}
|
|
581
|
+
function resolveField(name, key, ctx) {
|
|
582
|
+
const { request, url, cf } = ctx;
|
|
583
|
+
const cfExtended = cf;
|
|
584
|
+
switch (name) {
|
|
585
|
+
// ── HTTP URI fields ────────────────────────────────────────────────────
|
|
586
|
+
case 'http.host': return url.hostname;
|
|
587
|
+
case 'http.request.uri': return url.pathname + url.search;
|
|
588
|
+
case 'http.request.uri.path': return url.pathname;
|
|
589
|
+
case 'http.request.full_uri': return request.url;
|
|
590
|
+
case 'http.request.uri.query': return url.search.slice(1);
|
|
591
|
+
case 'http.request.uri.path.extension': {
|
|
592
|
+
const base = url.pathname.split('/').pop() ?? '';
|
|
593
|
+
const dot = base.lastIndexOf('.');
|
|
594
|
+
return dot >= 0 ? base.slice(dot + 1) : '';
|
|
595
|
+
}
|
|
596
|
+
case 'http.request.uri.path.basename': {
|
|
597
|
+
const base = url.pathname.split('/').pop() ?? '';
|
|
598
|
+
const dot = base.lastIndexOf('.');
|
|
599
|
+
return dot >= 0 ? base.slice(0, dot) : base;
|
|
600
|
+
}
|
|
601
|
+
case 'http.request.uri.args': {
|
|
602
|
+
if (!ctx.queryParams)
|
|
603
|
+
ctx.queryParams = url.searchParams;
|
|
604
|
+
if (key !== null)
|
|
605
|
+
return ctx.queryParams.get(key) ?? null;
|
|
606
|
+
const obj = {};
|
|
607
|
+
ctx.queryParams.forEach((v, k) => { (obj[k] = obj[k] ?? []).push(v); });
|
|
608
|
+
return JSON.stringify(obj);
|
|
609
|
+
}
|
|
610
|
+
case 'http.request.uri.args.names': {
|
|
611
|
+
if (!ctx.queryParams)
|
|
612
|
+
ctx.queryParams = url.searchParams;
|
|
613
|
+
return [...ctx.queryParams.keys()];
|
|
614
|
+
}
|
|
615
|
+
case 'http.request.uri.args.values': {
|
|
616
|
+
if (!ctx.queryParams)
|
|
617
|
+
ctx.queryParams = url.searchParams;
|
|
618
|
+
return [...ctx.queryParams.values()];
|
|
619
|
+
}
|
|
620
|
+
case 'raw.http.request.uri':
|
|
621
|
+
case 'raw.http.request.full_uri':
|
|
622
|
+
// Workers receive the post-transform request; raw fields are not available
|
|
623
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is not available in Worker context (post-transform request only)`);
|
|
624
|
+
return null;
|
|
625
|
+
case 'raw.http.request.uri.path':
|
|
626
|
+
case 'raw.http.request.uri.path.extension':
|
|
627
|
+
case 'raw.http.request.uri.query':
|
|
628
|
+
case 'raw.http.request.uri.args':
|
|
629
|
+
case 'raw.http.request.uri.args.names':
|
|
630
|
+
case 'raw.http.request.uri.args.values':
|
|
631
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is not available in Worker context (post-transform request only)`);
|
|
632
|
+
return null;
|
|
633
|
+
// ── HTTP request metadata ──────────────────────────────────────────────
|
|
634
|
+
case 'http.request.method': return request.method;
|
|
635
|
+
case 'http.request.version': return cf.httpProtocol ?? '';
|
|
636
|
+
case 'http.cookie': return request.headers.get('cookie') ?? '';
|
|
637
|
+
case 'http.referer': return request.headers.get('referer') ?? '';
|
|
638
|
+
case 'http.user_agent': return request.headers.get('user-agent') ?? '';
|
|
639
|
+
case 'http.x_forwarded_for': return request.headers.get('x-forwarded-for') ?? '';
|
|
640
|
+
// Timestamps — not in request.cf; callers should use Date.now()
|
|
641
|
+
case 'http.request.timestamp.sec':
|
|
642
|
+
case 'http.request.timestamp.msec':
|
|
643
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is not available in Worker context`);
|
|
644
|
+
return null;
|
|
645
|
+
// ── HTTP request headers ───────────────────────────────────────────────
|
|
646
|
+
case 'http.request.headers':
|
|
647
|
+
if (key !== null) {
|
|
648
|
+
if (key.toLowerCase() === 'accept-encoding') {
|
|
649
|
+
return cf.clientAcceptEncoding ?? request.headers.get('accept-encoding') ?? null;
|
|
650
|
+
}
|
|
651
|
+
// getAll() is restricted to "Set-Cookie" in Miniflare/spec; fall back to get() for others.
|
|
652
|
+
try {
|
|
653
|
+
const all = request.headers.getAll(key.toLowerCase());
|
|
654
|
+
if (all.length > 1)
|
|
655
|
+
return all;
|
|
656
|
+
}
|
|
657
|
+
catch { /* non-Set-Cookie header — fall through */ }
|
|
658
|
+
return request.headers.get(key.toLowerCase()) ?? null;
|
|
659
|
+
}
|
|
660
|
+
return null;
|
|
661
|
+
case 'http.request.headers.names': return [...request.headers.keys()];
|
|
662
|
+
case 'http.request.headers.values': return [...request.headers.values()];
|
|
663
|
+
case 'http.request.headers.truncated': return false; // Workers don't truncate
|
|
664
|
+
// ── HTTP request cookies / query args ──────────────────────────────────
|
|
665
|
+
case 'http.request.cookies':
|
|
666
|
+
if (key !== null)
|
|
667
|
+
return getCookieMap(ctx)[key] ?? null;
|
|
668
|
+
return null;
|
|
669
|
+
case 'http.request.accepted_languages': {
|
|
670
|
+
const al = request.headers.get('accept-language') ?? '';
|
|
671
|
+
return al.split(',').map(s => s.split(';')[0].trim()).filter(Boolean);
|
|
672
|
+
}
|
|
673
|
+
// ── HTTP request body — not available without consuming the body ────────
|
|
674
|
+
case 'http.request.body.form':
|
|
675
|
+
case 'http.request.body.form.names':
|
|
676
|
+
case 'http.request.body.form.values':
|
|
677
|
+
case 'http.request.body.mime':
|
|
678
|
+
case 'http.request.body.multipart':
|
|
679
|
+
case 'http.request.body.multipart.content_dispositions':
|
|
680
|
+
case 'http.request.body.multipart.content_transfer_encodings':
|
|
681
|
+
case 'http.request.body.multipart.content_types':
|
|
682
|
+
case 'http.request.body.multipart.filenames':
|
|
683
|
+
case 'http.request.body.multipart.names':
|
|
684
|
+
case 'http.request.body.multipart.values':
|
|
685
|
+
case 'http.request.body.raw':
|
|
686
|
+
case 'http.request.body.size':
|
|
687
|
+
case 'http.request.body.truncated':
|
|
688
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' requires body inspection (not available in this evaluator)`);
|
|
689
|
+
return null;
|
|
690
|
+
// ── HTTP request JWT claims — not in request.cf ───────────────────────
|
|
691
|
+
case 'http.request.jwt.claims.aud':
|
|
692
|
+
case 'http.request.jwt.claims.aud.names':
|
|
693
|
+
case 'http.request.jwt.claims.aud.values':
|
|
694
|
+
case 'http.request.jwt.claims.iat.sec':
|
|
695
|
+
case 'http.request.jwt.claims.iat.sec.names':
|
|
696
|
+
case 'http.request.jwt.claims.iat.sec.values':
|
|
697
|
+
case 'http.request.jwt.claims.iss':
|
|
698
|
+
case 'http.request.jwt.claims.iss.names':
|
|
699
|
+
case 'http.request.jwt.claims.iss.values':
|
|
700
|
+
case 'http.request.jwt.claims.jti':
|
|
701
|
+
case 'http.request.jwt.claims.jti.names':
|
|
702
|
+
case 'http.request.jwt.claims.jti.values':
|
|
703
|
+
case 'http.request.jwt.claims.nbf.sec':
|
|
704
|
+
case 'http.request.jwt.claims.nbf.sec.names':
|
|
705
|
+
case 'http.request.jwt.claims.nbf.sec.values':
|
|
706
|
+
case 'http.request.jwt.claims.sub':
|
|
707
|
+
case 'http.request.jwt.claims.sub.names':
|
|
708
|
+
case 'http.request.jwt.claims.sub.values':
|
|
709
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is not available in Worker context (JWT claims require Access/API Shield)`);
|
|
710
|
+
return null;
|
|
711
|
+
// ── HTTP response fields — not available on inbound request ────────────
|
|
712
|
+
case 'http.response.code':
|
|
713
|
+
case 'http.response.content_type.media_type':
|
|
714
|
+
case 'http.response.headers':
|
|
715
|
+
case 'http.response.headers.names':
|
|
716
|
+
case 'http.response.headers.values':
|
|
717
|
+
case 'raw.http.response.headers':
|
|
718
|
+
case 'raw.http.response.headers.names':
|
|
719
|
+
case 'raw.http.response.headers.values':
|
|
720
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is a response field (not available on inbound request)`);
|
|
721
|
+
return null;
|
|
722
|
+
// ── IP source ──────────────────────────────────────────────────────────
|
|
723
|
+
case 'ip.src': return request.headers.get('cf-connecting-ip') ?? '';
|
|
724
|
+
// GeoIP — via request.cf (ip.geoip.* are deprecated aliases for ip.src.*)
|
|
725
|
+
case 'ip.src.asnum':
|
|
726
|
+
case 'ip.geoip.asnum': return cf.asn ?? null;
|
|
727
|
+
case 'ip.src.country':
|
|
728
|
+
case 'ip.geoip.country': return cf.country ?? null;
|
|
729
|
+
case 'ip.src.continent':
|
|
730
|
+
case 'ip.geoip.continent': return cf.continent ?? null;
|
|
731
|
+
case 'ip.src.city': return cf.city ?? null;
|
|
732
|
+
case 'ip.src.is_in_european_union':
|
|
733
|
+
case 'ip.geoip.is_in_european_union': return cf.isEUCountry === '1';
|
|
734
|
+
case 'ip.src.lat': return cf.latitude ? parseFloat(cf.latitude) : null;
|
|
735
|
+
case 'ip.src.lon': return cf.longitude ? parseFloat(cf.longitude) : null;
|
|
736
|
+
case 'ip.src.subdivision_1_iso_code': return cf.regionCode ?? null;
|
|
737
|
+
case 'ip.src.subdivision_2_iso_code': return null; // not in request.cf
|
|
738
|
+
case 'ip.src.region': return cf.region ?? null;
|
|
739
|
+
case 'ip.src.region_code': return cf.regionCode ?? null;
|
|
740
|
+
case 'ip.src.metro_code': return cf.metroCode ?? null;
|
|
741
|
+
case 'ip.src.postal_code': return cf.postalCode ?? null;
|
|
742
|
+
case 'ip.src.timezone.name': return cf.timezone ?? null;
|
|
743
|
+
// ── SSL ────────────────────────────────────────────────────────────────
|
|
744
|
+
case 'ssl': return url.protocol === 'https:';
|
|
745
|
+
// ── TLS / cipher ───────────────────────────────────────────────────────
|
|
746
|
+
case 'cf.tls_version': return cf.tlsVersion ?? '';
|
|
747
|
+
case 'cf.tls_cipher': return cf.tlsCipher ?? '';
|
|
748
|
+
case 'cf.tls_client_extensions_sha1': return cfExtended.tlsClientExtensionsSha1 ?? null;
|
|
749
|
+
case 'cf.tls_client_extensions_sha1_le': return cfExtended.tlsClientExtensionsSha1Le ?? null;
|
|
750
|
+
case 'cf.tls_client_ciphers_sha1':
|
|
751
|
+
case 'cf.tls_ciphers_sha1': return cfExtended.tlsClientCiphersSha1 ?? null;
|
|
752
|
+
case 'cf.tls_client_hello_length': return cfExtended.tlsClientHelloLength ?? null;
|
|
753
|
+
case 'cf.tls_client_random': return cfExtended.tlsClientRandom ?? null;
|
|
754
|
+
// TLS client auth (mTLS) — full property set from IncomingRequestCfPropertiesTLSClientAuth
|
|
755
|
+
case 'cf.tls_client_auth.cert_presented': return cf.tlsClientAuth?.certPresented ?? null;
|
|
756
|
+
case 'cf.tls_client_auth.cert_verified': return cf.tlsClientAuth?.certVerified ?? null;
|
|
757
|
+
case 'cf.tls_client_auth.cert_revoked': return cf.tlsClientAuth?.certRevoked ?? null;
|
|
758
|
+
case 'cf.tls_client_auth.cert_issuer_dn': return cf.tlsClientAuth?.certIssuerDN ?? null;
|
|
759
|
+
case 'cf.tls_client_auth.cert_subject_dn': return cf.tlsClientAuth?.certSubjectDN ?? null;
|
|
760
|
+
case 'cf.tls_client_auth.cert_issuer_dn_rfc2253': return cf.tlsClientAuth?.certIssuerDNRFC2253 ?? null;
|
|
761
|
+
case 'cf.tls_client_auth.cert_subject_dn_rfc2253': return cf.tlsClientAuth?.certSubjectDNRFC2253 ?? null;
|
|
762
|
+
case 'cf.tls_client_auth.cert_issuer_dn_legacy': return cf.tlsClientAuth?.certIssuerDNLegacy ?? null;
|
|
763
|
+
case 'cf.tls_client_auth.cert_subject_dn_legacy': return cf.tlsClientAuth?.certSubjectDNLegacy ?? null;
|
|
764
|
+
case 'cf.tls_client_auth.cert_serial': return cf.tlsClientAuth?.certSerial ?? null;
|
|
765
|
+
case 'cf.tls_client_auth.cert_issuer_serial': return cf.tlsClientAuth?.certIssuerSerial ?? null;
|
|
766
|
+
case 'cf.tls_client_auth.cert_ski': return cf.tlsClientAuth?.certSKI ?? null;
|
|
767
|
+
case 'cf.tls_client_auth.cert_issuer_ski': return cf.tlsClientAuth?.certIssuerSKI ?? null;
|
|
768
|
+
case 'cf.tls_client_auth.cert_fingerprint_sha1': return cf.tlsClientAuth?.certFingerprintSHA1 ?? null;
|
|
769
|
+
case 'cf.tls_client_auth.cert_fingerprint_sha256': return cf.tlsClientAuth?.certFingerprintSHA256 ?? null;
|
|
770
|
+
case 'cf.tls_client_auth.cert_not_before': return cf.tlsClientAuth?.certNotBefore ?? null;
|
|
771
|
+
case 'cf.tls_client_auth.cert_not_after': return cf.tlsClientAuth?.certNotAfter ?? null;
|
|
772
|
+
// not in generated types
|
|
773
|
+
case 'cf.tls_client_auth.cert_rfc9440': return cfExtended.tlsClientAuth?.certRFC9440 ?? null;
|
|
774
|
+
case 'cf.tls_client_auth.cert_rfc9440_too_large': return cfExtended.tlsClientAuth?.certRFC9440TooLarge ?? null;
|
|
775
|
+
case 'cf.tls_client_auth.cert_chain_rfc9440': return cfExtended.tlsClientAuth?.certChainRfc9440 ?? null;
|
|
776
|
+
case 'cf.tls_client_auth.cert_chain_rfc9440_too_large': return cfExtended.tlsClientAuth?.certChainRfc9440TooLarge ?? null;
|
|
777
|
+
// ── Bot management ────────────────────────────────────────────────────
|
|
778
|
+
case 'cf.bot_management.score': return cf.botManagement?.score ?? null;
|
|
779
|
+
case 'cf.bot_management.verified_bot': return cf.botManagement?.verifiedBot ?? null;
|
|
780
|
+
case 'cf.bot_management.static_resource': return cf.botManagement?.staticResource ?? null;
|
|
781
|
+
case 'cf.bot_management.ja3_hash': return cfExtended.botManagement?.ja3Hash ?? null;
|
|
782
|
+
case 'cf.bot_management.ja4': return cfExtended.botManagement?.ja4 ?? null;
|
|
783
|
+
case 'cf.bot_management.detection_ids': return cf.botManagement?.detectionIds ?? null;
|
|
784
|
+
case 'cf.bot_management.corporate_proxy': return cf.botManagement?.corporateProxy ?? null;
|
|
785
|
+
case 'cf.bot_management.js_detection.passed': return cfExtended.botManagement?.jsDetection?.passed ?? null;
|
|
786
|
+
case 'cf.client.bot': return cf.botManagement?.verifiedBot ?? null;
|
|
787
|
+
case 'cf.verified_bot_category': return cfExtended.verifiedBotCategory ?? null;
|
|
788
|
+
// ── Edge / network ────────────────────────────────────────────────────
|
|
789
|
+
case 'cf.ray_id': return request.headers.get('cf-ray') ?? '';
|
|
790
|
+
case 'cf.edge.l4.delivery_rate': return cfExtended.edgeL4?.deliveryRate ?? null;
|
|
791
|
+
// cf.edge.client_tcp: true when client connected via TCP (HTTP/1 or HTTP/2)
|
|
792
|
+
case 'cf.edge.client_tcp': return cf.clientTcpRtt !== undefined ? true : null;
|
|
793
|
+
case 'cf.timings.client_tcp_rtt_msec': return cf.clientTcpRtt ?? null;
|
|
794
|
+
case 'cf.timings.client_quic_rtt_msec': return cfExtended.clientQuicRtt ?? null;
|
|
795
|
+
case 'cf.hostname.metadata': return cf.hostMetadata != null ? JSON.stringify(cf.hostMetadata) : null;
|
|
796
|
+
// ── Unavailable: WAF internal ─────────────────────────────────────────
|
|
797
|
+
case 'cf.threat_score':
|
|
798
|
+
case 'cf.waf.score':
|
|
799
|
+
case 'cf.waf.score.class':
|
|
800
|
+
case 'cf.waf.score.rce':
|
|
801
|
+
case 'cf.waf.score.sqli':
|
|
802
|
+
case 'cf.waf.score.xss':
|
|
803
|
+
case 'cf.waf.auth_detected':
|
|
804
|
+
case 'cf.waf.content_scan.has_failed':
|
|
805
|
+
case 'cf.waf.content_scan.has_malicious_obj':
|
|
806
|
+
case 'cf.waf.content_scan.has_obj':
|
|
807
|
+
case 'cf.waf.content_scan.num_malicious_obj':
|
|
808
|
+
case 'cf.waf.content_scan.num_obj':
|
|
809
|
+
case 'cf.waf.content_scan.obj_results':
|
|
810
|
+
case 'cf.waf.content_scan.obj_sizes':
|
|
811
|
+
case 'cf.waf.content_scan.obj_types':
|
|
812
|
+
case 'cf.waf.credential_check.password_leaked':
|
|
813
|
+
case 'cf.waf.credential_check.username_and_password_leaked':
|
|
814
|
+
case 'cf.waf.credential_check.username_leaked':
|
|
815
|
+
case 'cf.waf.credential_check.username_password_similar':
|
|
816
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is a WAF-internal field not available in Worker context`);
|
|
817
|
+
return null;
|
|
818
|
+
// ── Unavailable: API Gateway ──────────────────────────────────────────
|
|
819
|
+
case 'cf.api_gateway.auth_id_present':
|
|
820
|
+
case 'cf.api_gateway.fallthrough_detected':
|
|
821
|
+
case 'cf.api_gateway.request_violates_schema':
|
|
822
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is an API Gateway field not available in Worker context`);
|
|
823
|
+
return null;
|
|
824
|
+
// ── Unavailable: AI/LLM (AI Gateway) ─────────────────────────────────
|
|
825
|
+
case 'cf.llm.prompt.custom_topic_categories':
|
|
826
|
+
case 'cf.llm.prompt.detected':
|
|
827
|
+
case 'cf.llm.prompt.injection_score':
|
|
828
|
+
case 'cf.llm.prompt.pii_categories':
|
|
829
|
+
case 'cf.llm.prompt.pii_detected':
|
|
830
|
+
case 'cf.llm.prompt.token_count':
|
|
831
|
+
case 'cf.llm.prompt.unsafe_topic_categories':
|
|
832
|
+
case 'cf.llm.prompt.unsafe_topic_detected':
|
|
833
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is an AI Gateway LLM field not available in Worker context`);
|
|
834
|
+
return null;
|
|
835
|
+
// ── Unavailable: edge response / timing ───────────────────────────────
|
|
836
|
+
case 'cf.response.1xxx_code':
|
|
837
|
+
case 'cf.response.error_type':
|
|
838
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is a response field not available on inbound request`);
|
|
839
|
+
return null;
|
|
840
|
+
case 'cf.timings.edge_msec':
|
|
841
|
+
case 'cf.timings.origin_ttfb_msec':
|
|
842
|
+
case 'cf.timings.worker_msec':
|
|
843
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is a timing field computed after the request (not available at request time)`);
|
|
844
|
+
return null;
|
|
845
|
+
// ── Unavailable: other ────────────────────────────────────────────────
|
|
846
|
+
case 'cf.random_seed':
|
|
847
|
+
case 'cf.worker.upstream_zone':
|
|
848
|
+
case 'cf.edge.server_ip':
|
|
849
|
+
case 'cf.edge.server_port':
|
|
850
|
+
case 'cf.edge.client_port':
|
|
851
|
+
case 'cf.zone.name':
|
|
852
|
+
case 'cf.metal.id':
|
|
853
|
+
pushWarning(ctx.warnings, `[rule-evaluator] field '${name}' is not available in Worker context`);
|
|
854
|
+
return null;
|
|
855
|
+
default:
|
|
856
|
+
pushWarning(ctx.warnings, `[rule-evaluator] unknown field '${name}'`);
|
|
857
|
+
return null;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
function resolveFieldNode(node, ctx) {
|
|
861
|
+
if (node.kind === 'Field')
|
|
862
|
+
return resolveField(node.name, null, ctx);
|
|
863
|
+
if (node.kind === 'ArrayField')
|
|
864
|
+
return resolveField(node.name, null, ctx);
|
|
865
|
+
if (node.kind === 'MapField')
|
|
866
|
+
return resolveField(node.name, node.key, ctx);
|
|
867
|
+
return null;
|
|
868
|
+
}
|
|
869
|
+
function isAcceptEncodingFieldNode(node) {
|
|
870
|
+
return node.kind === 'MapField'
|
|
871
|
+
&& node.name === 'http.request.headers'
|
|
872
|
+
&& node.key.toLowerCase() === 'accept-encoding';
|
|
873
|
+
}
|
|
874
|
+
function funcUsesAcceptEncoding(node) {
|
|
875
|
+
const arg0 = node.args[0];
|
|
876
|
+
if (!arg0 || typeof arg0 !== 'object' || !('kind' in arg0))
|
|
877
|
+
return false;
|
|
878
|
+
if (arg0.kind === 'Field' || arg0.kind === 'ArrayField' || arg0.kind === 'MapField') {
|
|
879
|
+
return isAcceptEncodingFieldNode(arg0);
|
|
880
|
+
}
|
|
881
|
+
if (arg0.kind === 'Func') {
|
|
882
|
+
return funcUsesAcceptEncoding(arg0);
|
|
883
|
+
}
|
|
884
|
+
return false;
|
|
885
|
+
}
|
|
886
|
+
function parseAcceptEncodingTokens(value) {
|
|
887
|
+
if (!value)
|
|
888
|
+
return [];
|
|
889
|
+
return value
|
|
890
|
+
.split(',')
|
|
891
|
+
.map(part => part.trim())
|
|
892
|
+
.filter(Boolean);
|
|
893
|
+
}
|
|
894
|
+
function toggleZstdInAcceptEncoding(value) {
|
|
895
|
+
const tokens = parseAcceptEncodingTokens(value);
|
|
896
|
+
const hasZstd = tokens.some(token => token.split(';')[0]?.trim().toLowerCase() === 'zstd');
|
|
897
|
+
if (hasZstd) {
|
|
898
|
+
return tokens
|
|
899
|
+
.filter(token => token.split(';')[0]?.trim().toLowerCase() !== 'zstd')
|
|
900
|
+
.join(', ');
|
|
901
|
+
}
|
|
902
|
+
return [...tokens, 'zstd'].join(', ');
|
|
903
|
+
}
|
|
904
|
+
function withAcceptEncodingOverride(ctx, acceptEncoding) {
|
|
905
|
+
return {
|
|
906
|
+
...ctx,
|
|
907
|
+
cf: { ...ctx.cf, clientAcceptEncoding: acceptEncoding },
|
|
908
|
+
warnings: [],
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
function warnIfAcceptEncodingZstdSensitive(node, ctx, currentResult, evaluateWithCtx) {
|
|
912
|
+
const responseContentEncoding = ctx.response?.headers.get('content-encoding') ?? '';
|
|
913
|
+
if (parseAcceptEncodingTokens(responseContentEncoding).some(token => token === 'zstd')) {
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
const usesAcceptEncoding = node.kind === 'Comparison'
|
|
917
|
+
? (node.left.kind === 'Func' ? funcUsesAcceptEncoding(node.left) : isAcceptEncodingFieldNode(node.left))
|
|
918
|
+
: (() => {
|
|
919
|
+
if (node.name !== 'any' && node.name !== 'all')
|
|
920
|
+
return false;
|
|
921
|
+
const fieldArg = node.args[0];
|
|
922
|
+
if (!fieldArg || typeof fieldArg !== 'object' || !('kind' in fieldArg))
|
|
923
|
+
return false;
|
|
924
|
+
if (fieldArg.kind === 'Func')
|
|
925
|
+
return funcUsesAcceptEncoding(fieldArg);
|
|
926
|
+
if (fieldArg.kind === 'Field' || fieldArg.kind === 'ArrayField' || fieldArg.kind === 'MapField') {
|
|
927
|
+
return isAcceptEncodingFieldNode(fieldArg);
|
|
928
|
+
}
|
|
929
|
+
return false;
|
|
930
|
+
})();
|
|
931
|
+
if (!usesAcceptEncoding)
|
|
932
|
+
return;
|
|
933
|
+
const toggledAcceptEncoding = toggleZstdInAcceptEncoding(ctx.cf.clientAcceptEncoding ?? ctx.request.headers.get('accept-encoding') ?? '');
|
|
934
|
+
const toggledCtx = withAcceptEncodingOverride(ctx, toggledAcceptEncoding);
|
|
935
|
+
const toggledResult = evaluateWithCtx(toggledCtx);
|
|
936
|
+
if (toggledResult !== currentResult) {
|
|
937
|
+
pushWarning(ctx.warnings, `[rule-evaluator] Accept-Encoding checks may be unreliable in Workers: request.cf.clientAcceptEncoding currently drops 'zstd', and '${node.raw}' would evaluate differently if 'zstd' were toggled`);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
// ─── CIDR Matching ────────────────────────────────────────────────────────────
|
|
941
|
+
function ipToUint32(ip) {
|
|
942
|
+
const parts = ip.split('.');
|
|
943
|
+
return ((parseInt(parts[0], 10) << 24) |
|
|
944
|
+
(parseInt(parts[1], 10) << 16) |
|
|
945
|
+
(parseInt(parts[2], 10) << 8) |
|
|
946
|
+
parseInt(parts[3], 10)) >>> 0;
|
|
947
|
+
}
|
|
948
|
+
function cidrContains(cidr, ip) {
|
|
949
|
+
try {
|
|
950
|
+
const [network, prefixStr] = cidr.includes('/') ? cidr.split('/') : [cidr, '32'];
|
|
951
|
+
const bits = parseInt(prefixStr, 10);
|
|
952
|
+
const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
|
|
953
|
+
return (ipToUint32(network) & mask) === (ipToUint32(ip) & mask);
|
|
954
|
+
}
|
|
955
|
+
catch {
|
|
956
|
+
return false;
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
// ─── Wildcard → RegExp ────────────────────────────────────────────────────────
|
|
960
|
+
function wildcardToRegex(pattern, caseSensitive) {
|
|
961
|
+
const escaped = pattern
|
|
962
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
963
|
+
.replace(/\*/g, '.*')
|
|
964
|
+
.replace(/\?/g, '.');
|
|
965
|
+
return new RegExp('^' + escaped + '$', caseSensitive ? '' : 'i');
|
|
966
|
+
}
|
|
967
|
+
// ─── Operator Evaluation ─────────────────────────────────────────────────────
|
|
968
|
+
function applyOp(op, leftVal, right, warnings) {
|
|
969
|
+
if (right?.kind === 'ListRef') {
|
|
970
|
+
// Cannot resolve $list at runtime
|
|
971
|
+
return null;
|
|
972
|
+
}
|
|
973
|
+
if (op === 'exists')
|
|
974
|
+
return leftVal !== null && leftVal !== undefined && leftVal !== '';
|
|
975
|
+
if (op === 'not_exists')
|
|
976
|
+
return leftVal === null || leftVal === undefined || leftVal === '';
|
|
977
|
+
if (leftVal === null)
|
|
978
|
+
return false; // field unavailable
|
|
979
|
+
const rightVal = right ? literalValue(right) : null;
|
|
980
|
+
switch (op) {
|
|
981
|
+
case 'eq': return leftVal == rightVal; // intentional ==
|
|
982
|
+
case 'ne': return leftVal != rightVal;
|
|
983
|
+
case 'lt': return leftVal < rightVal;
|
|
984
|
+
case 'le': return leftVal <= rightVal;
|
|
985
|
+
case 'gt': return leftVal > rightVal;
|
|
986
|
+
case 'ge': return leftVal >= rightVal;
|
|
987
|
+
case 'contains': return String(leftVal).includes(String(rightVal));
|
|
988
|
+
case 'matches': {
|
|
989
|
+
try {
|
|
990
|
+
return new RegExp(String(rightVal)).test(String(leftVal));
|
|
991
|
+
}
|
|
992
|
+
catch {
|
|
993
|
+
pushWarning(warnings, `[rule-evaluator] invalid regex: ${String(rightVal)}`);
|
|
994
|
+
return false;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
case 'wildcard': return wildcardToRegex(String(rightVal), false).test(String(leftVal));
|
|
998
|
+
case 'strict_wildcard': return wildcardToRegex(String(rightVal), true).test(String(leftVal));
|
|
999
|
+
case 'in': {
|
|
1000
|
+
if (right?.kind === 'SetLiteral') {
|
|
1001
|
+
const strLeft = String(leftVal);
|
|
1002
|
+
for (const v of right.values) {
|
|
1003
|
+
const sv = String(v);
|
|
1004
|
+
if (sv.includes('/') || sv.match(/^\d+\.\d+\.\d+\.\d+$/)) {
|
|
1005
|
+
// CIDR or plain IP — use cidrContains only if leftVal looks like an IP
|
|
1006
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(strLeft) && cidrContains(sv, strLeft))
|
|
1007
|
+
return true;
|
|
1008
|
+
}
|
|
1009
|
+
else {
|
|
1010
|
+
if (strLeft === sv)
|
|
1011
|
+
return true;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
return false;
|
|
1015
|
+
}
|
|
1016
|
+
return false;
|
|
1017
|
+
}
|
|
1018
|
+
default: return false;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
function literalValue(node) {
|
|
1022
|
+
if (node.kind === 'StringLiteral')
|
|
1023
|
+
return node.value;
|
|
1024
|
+
if (node.kind === 'NumberLiteral')
|
|
1025
|
+
return node.value;
|
|
1026
|
+
if (node.kind === 'BoolLiteral')
|
|
1027
|
+
return node.value;
|
|
1028
|
+
if (node.kind === 'ListRef')
|
|
1029
|
+
return null;
|
|
1030
|
+
// SetLiteral — should not reach here as scalar
|
|
1031
|
+
return null;
|
|
1032
|
+
}
|
|
1033
|
+
function inferredExpr(raw) {
|
|
1034
|
+
return `${raw} [inferred]`;
|
|
1035
|
+
}
|
|
1036
|
+
function formatMatchChainEntry(entry) {
|
|
1037
|
+
return entry.inferred ? inferredExpr(entry.node.raw) : entry.node.raw;
|
|
1038
|
+
}
|
|
1039
|
+
function pushChainEntry(state, node, options = {}) {
|
|
1040
|
+
state.chain.push({
|
|
1041
|
+
node,
|
|
1042
|
+
inferred: options.inferred ?? false,
|
|
1043
|
+
...(options.matchedSetMember !== undefined ? { matchedSetMember: options.matchedSetMember } : {}),
|
|
1044
|
+
});
|
|
1045
|
+
}
|
|
1046
|
+
function countSubExpressions(node) {
|
|
1047
|
+
switch (node.kind) {
|
|
1048
|
+
case 'And':
|
|
1049
|
+
case 'Or':
|
|
1050
|
+
return countSubExpressions(node.left) + countSubExpressions(node.right);
|
|
1051
|
+
default:
|
|
1052
|
+
return 1;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
function findMatchingSetMember(leftVal, setLiteral) {
|
|
1056
|
+
if (leftVal === null)
|
|
1057
|
+
return null;
|
|
1058
|
+
const strLeft = String(leftVal);
|
|
1059
|
+
for (const v of setLiteral.values) {
|
|
1060
|
+
const sv = String(v);
|
|
1061
|
+
if (sv.includes('/') || sv.match(/^\d+\.\d+\.\d+\.\d+$/)) {
|
|
1062
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(strLeft) && cidrContains(sv, strLeft))
|
|
1063
|
+
return v;
|
|
1064
|
+
}
|
|
1065
|
+
else if (strLeft === sv) {
|
|
1066
|
+
return v;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
return null;
|
|
1070
|
+
}
|
|
1071
|
+
function renderMatchedSetMember(rawExpr, matchedValue) {
|
|
1072
|
+
const setStart = rawExpr.indexOf('{');
|
|
1073
|
+
const setEnd = rawExpr.lastIndexOf('}');
|
|
1074
|
+
if (setStart === -1 || setEnd === -1 || setEnd <= setStart)
|
|
1075
|
+
return String(matchedValue);
|
|
1076
|
+
const rawSet = rawExpr.slice(setStart + 1, setEnd);
|
|
1077
|
+
const candidates = typeof matchedValue === 'string'
|
|
1078
|
+
? [JSON.stringify(matchedValue), matchedValue]
|
|
1079
|
+
: [String(matchedValue)];
|
|
1080
|
+
for (const candidate of candidates) {
|
|
1081
|
+
if (rawSet.includes(candidate))
|
|
1082
|
+
return candidate;
|
|
1083
|
+
}
|
|
1084
|
+
return typeof matchedValue === 'string' ? JSON.stringify(matchedValue) : String(matchedValue);
|
|
1085
|
+
}
|
|
1086
|
+
function summarizeSetLiteralExpr(rawExpr, matchedValue) {
|
|
1087
|
+
const renderedMember = renderMatchedSetMember(rawExpr, matchedValue);
|
|
1088
|
+
return rawExpr.replace(/\{[\s\S]*\}/, `{ ... ${renderedMember} ... }`);
|
|
1089
|
+
}
|
|
1090
|
+
function summarizeMatchChainEntryForCompat(entry) {
|
|
1091
|
+
if (entry.matchedSetMember === undefined)
|
|
1092
|
+
return entry.node.raw;
|
|
1093
|
+
if (entry.node.kind === 'Comparison' && entry.node.op === 'in' && entry.node.right?.kind === 'SetLiteral') {
|
|
1094
|
+
return summarizeSetLiteralExpr(entry.node.raw, entry.matchedSetMember);
|
|
1095
|
+
}
|
|
1096
|
+
if (entry.node.kind === 'Func' && (entry.node.name === 'any' || entry.node.name === 'all')) {
|
|
1097
|
+
const op = entry.node.args[1].value;
|
|
1098
|
+
const valueNode = entry.node.args[2];
|
|
1099
|
+
if (op === 'in' && valueNode.kind === 'SetLiteral') {
|
|
1100
|
+
return summarizeSetLiteralExpr(entry.node.raw, entry.matchedSetMember);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
return entry.node.raw;
|
|
1104
|
+
}
|
|
1105
|
+
function buildCompatMatchChain(matchChain, largeNotBlockThreshold) {
|
|
1106
|
+
const largeBlocks = {};
|
|
1107
|
+
let blockIndex = 0;
|
|
1108
|
+
const matchChainCompat = matchChain.map((entry) => {
|
|
1109
|
+
let compatExpr = summarizeMatchChainEntryForCompat(entry);
|
|
1110
|
+
if (entry.node.kind === 'Not') {
|
|
1111
|
+
const subExpressionCount = countSubExpressions(entry.node.operand);
|
|
1112
|
+
if (subExpressionCount > largeNotBlockThreshold) {
|
|
1113
|
+
blockIndex += 1;
|
|
1114
|
+
const blockKey = `not-block-${blockIndex}`;
|
|
1115
|
+
largeBlocks[blockKey] = entry.node.operand.raw;
|
|
1116
|
+
compatExpr = `not (<${blockKey}>)`;
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
return `${compatExpr}${entry.inferred ? ' [inferred]' : ''}`;
|
|
1120
|
+
});
|
|
1121
|
+
return { matchChainCompat, largeBlocks };
|
|
1122
|
+
}
|
|
1123
|
+
// Returns: true = matched, false = not matched, null = uncertain (depends on $list)
|
|
1124
|
+
function evaluateNode(node, ctx, state) {
|
|
1125
|
+
switch (node.kind) {
|
|
1126
|
+
case 'BoolField': {
|
|
1127
|
+
const val = resolveField(node.name, null, ctx);
|
|
1128
|
+
if (val) {
|
|
1129
|
+
pushChainEntry(state, node);
|
|
1130
|
+
return true;
|
|
1131
|
+
}
|
|
1132
|
+
return false;
|
|
1133
|
+
}
|
|
1134
|
+
case 'Comparison': {
|
|
1135
|
+
const leftNode = node.left;
|
|
1136
|
+
let leftVal;
|
|
1137
|
+
if (leftNode.kind === 'Func') {
|
|
1138
|
+
leftVal = evaluateFuncValue(leftNode, ctx);
|
|
1139
|
+
}
|
|
1140
|
+
else {
|
|
1141
|
+
leftVal = resolveFieldNode(leftNode, ctx);
|
|
1142
|
+
}
|
|
1143
|
+
const result = applyOp(node.op, leftVal, node.right, ctx.warnings);
|
|
1144
|
+
if (result === null) {
|
|
1145
|
+
if (node.right?.kind === 'ListRef') {
|
|
1146
|
+
pushChainEntry(state, node, { inferred: true });
|
|
1147
|
+
}
|
|
1148
|
+
return null; // $list dependency
|
|
1149
|
+
}
|
|
1150
|
+
warnIfAcceptEncodingZstdSensitive(node, ctx, result, (testCtx) => {
|
|
1151
|
+
const testLeftVal = leftNode.kind === 'Func'
|
|
1152
|
+
? evaluateFuncValue(leftNode, testCtx)
|
|
1153
|
+
: resolveFieldNode(leftNode, testCtx);
|
|
1154
|
+
return applyOp(node.op, testLeftVal, node.right, testCtx.warnings);
|
|
1155
|
+
});
|
|
1156
|
+
if (result) {
|
|
1157
|
+
const matchedSetMember = node.op === 'in' && node.right?.kind === 'SetLiteral'
|
|
1158
|
+
? findMatchingSetMember(leftVal, node.right)
|
|
1159
|
+
: null;
|
|
1160
|
+
pushChainEntry(state, node, matchedSetMember !== null ? { matchedSetMember } : {});
|
|
1161
|
+
return true;
|
|
1162
|
+
}
|
|
1163
|
+
return false;
|
|
1164
|
+
}
|
|
1165
|
+
case 'Func': {
|
|
1166
|
+
const result = evaluateFuncBool(node, ctx);
|
|
1167
|
+
if (result === null) {
|
|
1168
|
+
const valueNode = node.args[2];
|
|
1169
|
+
if ((node.name === 'any' || node.name === 'all') && valueNode?.kind === 'ListRef') {
|
|
1170
|
+
pushChainEntry(state, node, { inferred: true });
|
|
1171
|
+
}
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
warnIfAcceptEncodingZstdSensitive(node, ctx, result, testCtx => evaluateFuncBool(node, testCtx));
|
|
1175
|
+
if (result) {
|
|
1176
|
+
const matchedSetMember = findMatchedSetMemberForFunc(node, ctx);
|
|
1177
|
+
pushChainEntry(state, node, matchedSetMember !== null ? { matchedSetMember } : {});
|
|
1178
|
+
return true;
|
|
1179
|
+
}
|
|
1180
|
+
return false;
|
|
1181
|
+
}
|
|
1182
|
+
case 'Not': {
|
|
1183
|
+
const subState = { chain: [], matchedOrBranch: null, nullOrBranch: null };
|
|
1184
|
+
const inner = evaluateNode(node.operand, ctx, subState);
|
|
1185
|
+
if (inner === null) {
|
|
1186
|
+
pushChainEntry(state, node, { inferred: true });
|
|
1187
|
+
state.nullOrBranch ??= subState.nullOrBranch;
|
|
1188
|
+
return null;
|
|
1189
|
+
}
|
|
1190
|
+
if (!inner) {
|
|
1191
|
+
pushChainEntry(state, node);
|
|
1192
|
+
return true;
|
|
1193
|
+
}
|
|
1194
|
+
return false;
|
|
1195
|
+
}
|
|
1196
|
+
case 'And': {
|
|
1197
|
+
const leftState = { chain: [], matchedOrBranch: null, nullOrBranch: null };
|
|
1198
|
+
const leftResult = evaluateNode(node.left, ctx, leftState);
|
|
1199
|
+
if (leftResult === false)
|
|
1200
|
+
return false; // short-circuit
|
|
1201
|
+
const rightState = { chain: [], matchedOrBranch: null, nullOrBranch: null };
|
|
1202
|
+
const rightResult = evaluateNode(node.right, ctx, rightState);
|
|
1203
|
+
if (rightResult === false)
|
|
1204
|
+
return false;
|
|
1205
|
+
// Both are true or null (leftResult and rightResult are each true | null here)
|
|
1206
|
+
if (leftResult === true && rightResult === true) {
|
|
1207
|
+
state.chain.push(...leftState.chain, ...rightState.chain);
|
|
1208
|
+
if (leftState.matchedOrBranch)
|
|
1209
|
+
state.matchedOrBranch ??= leftState.matchedOrBranch;
|
|
1210
|
+
if (rightState.matchedOrBranch)
|
|
1211
|
+
state.matchedOrBranch ??= rightState.matchedOrBranch;
|
|
1212
|
+
return true;
|
|
1213
|
+
}
|
|
1214
|
+
// At least one is null — preserve both non-false sub-chains so the caller
|
|
1215
|
+
// can see the definite predicates that held before the list-dependent
|
|
1216
|
+
// uncertainty was introduced.
|
|
1217
|
+
state.chain.push(...leftState.chain, ...rightState.chain);
|
|
1218
|
+
state.nullOrBranch ??= leftState.nullOrBranch ?? rightState.nullOrBranch;
|
|
1219
|
+
return null;
|
|
1220
|
+
}
|
|
1221
|
+
case 'Or': {
|
|
1222
|
+
const leftState = { chain: [], matchedOrBranch: null, nullOrBranch: null };
|
|
1223
|
+
const leftResult = evaluateNode(node.left, ctx, leftState);
|
|
1224
|
+
if (leftResult === true) {
|
|
1225
|
+
state.chain.push(...leftState.chain);
|
|
1226
|
+
state.matchedOrBranch ??= leftState.matchedOrBranch ?? node.left.raw;
|
|
1227
|
+
if (leftState.nullOrBranch)
|
|
1228
|
+
state.nullOrBranch ??= leftState.nullOrBranch;
|
|
1229
|
+
return true;
|
|
1230
|
+
}
|
|
1231
|
+
const rightState = { chain: [], matchedOrBranch: null, nullOrBranch: null };
|
|
1232
|
+
const rightResult = evaluateNode(node.right, ctx, rightState);
|
|
1233
|
+
if (rightResult === true) {
|
|
1234
|
+
state.chain.push(...rightState.chain);
|
|
1235
|
+
state.matchedOrBranch ??= rightState.matchedOrBranch ?? node.right.raw;
|
|
1236
|
+
if (rightState.nullOrBranch)
|
|
1237
|
+
state.nullOrBranch ??= rightState.nullOrBranch;
|
|
1238
|
+
return true;
|
|
1239
|
+
}
|
|
1240
|
+
// null or null = null; null or false = null; false or null = null
|
|
1241
|
+
if (leftResult === null || rightResult === null) {
|
|
1242
|
+
// Preserve the chain from the first list-dependent branch we would report
|
|
1243
|
+
// as the inferred match source, so logs show the definite predicates that
|
|
1244
|
+
// led up to the uncertain $list check.
|
|
1245
|
+
if (leftResult === null) {
|
|
1246
|
+
state.chain.push(...leftState.chain);
|
|
1247
|
+
}
|
|
1248
|
+
else if (rightResult === null) {
|
|
1249
|
+
state.chain.push(...rightState.chain);
|
|
1250
|
+
}
|
|
1251
|
+
state.nullOrBranch ??= leftState.nullOrBranch ?? rightState.nullOrBranch;
|
|
1252
|
+
if (leftResult === null && !state.nullOrBranch)
|
|
1253
|
+
state.nullOrBranch = node.left.raw;
|
|
1254
|
+
if (rightResult === null && !state.nullOrBranch)
|
|
1255
|
+
state.nullOrBranch = node.right.raw;
|
|
1256
|
+
return null;
|
|
1257
|
+
}
|
|
1258
|
+
return false;
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
function resolveCollectionValues(fieldArg, ctx) {
|
|
1263
|
+
if (fieldArg.kind === 'Func' && fieldArg.name === 'lower_array') {
|
|
1264
|
+
const innerField = fieldArg.args[0];
|
|
1265
|
+
const raw = resolveFieldNode(innerField, ctx);
|
|
1266
|
+
if (Array.isArray(raw))
|
|
1267
|
+
return raw.map(v => String(v).toLowerCase());
|
|
1268
|
+
return raw !== null ? [String(raw).toLowerCase()] : [];
|
|
1269
|
+
}
|
|
1270
|
+
if (fieldArg.kind === 'Field' || fieldArg.kind === 'ArrayField' || fieldArg.kind === 'MapField') {
|
|
1271
|
+
const raw = resolveFieldNode(fieldArg, ctx);
|
|
1272
|
+
if (Array.isArray(raw))
|
|
1273
|
+
return raw;
|
|
1274
|
+
return raw !== null ? [String(raw)] : [];
|
|
1275
|
+
}
|
|
1276
|
+
return [];
|
|
1277
|
+
}
|
|
1278
|
+
function findMatchedSetMemberForFunc(node, ctx) {
|
|
1279
|
+
if (node.name !== 'any' && node.name !== 'all')
|
|
1280
|
+
return null;
|
|
1281
|
+
const fieldArg = node.args[0];
|
|
1282
|
+
const op = node.args[1].value;
|
|
1283
|
+
const valueNode = node.args[2];
|
|
1284
|
+
if (op !== 'in' || valueNode.kind !== 'SetLiteral')
|
|
1285
|
+
return null;
|
|
1286
|
+
for (const v of resolveCollectionValues(fieldArg, ctx)) {
|
|
1287
|
+
const matchedValue = findMatchingSetMember(v, valueNode);
|
|
1288
|
+
if (matchedValue !== null)
|
|
1289
|
+
return matchedValue;
|
|
1290
|
+
}
|
|
1291
|
+
return null;
|
|
1292
|
+
}
|
|
1293
|
+
// Evaluate a FuncNode as a boolean (for any/all/starts_with/ends_with)
|
|
1294
|
+
function evaluateFuncBool(node, ctx) {
|
|
1295
|
+
const { name, args } = node;
|
|
1296
|
+
if (name === 'any' || name === 'all') {
|
|
1297
|
+
// args: [fieldNode, opStringLiteral, valueNode]
|
|
1298
|
+
const fieldArg = args[0];
|
|
1299
|
+
const op = args[1].value;
|
|
1300
|
+
const valueNode = args[2];
|
|
1301
|
+
const arr = resolveCollectionValues(fieldArg, ctx);
|
|
1302
|
+
if (!Array.isArray(arr))
|
|
1303
|
+
return false;
|
|
1304
|
+
const check = (v) => applyOp(op, v, valueNode, ctx.warnings);
|
|
1305
|
+
if (valueNode.kind === 'ListRef')
|
|
1306
|
+
return null;
|
|
1307
|
+
if (name === 'any')
|
|
1308
|
+
return arr.some(v => check(v) === true) || false;
|
|
1309
|
+
if (name === 'all') {
|
|
1310
|
+
// Treat empty collection as non-matching (no element satisfied the condition).
|
|
1311
|
+
if (arr.length === 0)
|
|
1312
|
+
return false;
|
|
1313
|
+
return arr.every(v => check(v) === true) || false;
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
if (name === 'starts_with') {
|
|
1317
|
+
const fieldArg = args[0];
|
|
1318
|
+
const prefixArg = args[1];
|
|
1319
|
+
const val = resolveFieldNode(fieldArg, ctx);
|
|
1320
|
+
if (val === null)
|
|
1321
|
+
return false;
|
|
1322
|
+
return String(val).startsWith(String(literalValue(prefixArg)));
|
|
1323
|
+
}
|
|
1324
|
+
if (name === 'ends_with') {
|
|
1325
|
+
const fieldArg = args[0];
|
|
1326
|
+
const suffixArg = args[1];
|
|
1327
|
+
const val = resolveFieldNode(fieldArg, ctx);
|
|
1328
|
+
if (val === null)
|
|
1329
|
+
return false;
|
|
1330
|
+
return String(val).endsWith(String(literalValue(suffixArg)));
|
|
1331
|
+
}
|
|
1332
|
+
return false;
|
|
1333
|
+
}
|
|
1334
|
+
// Evaluate a FuncNode as a scalar value (for lower/len used as left side of comparison)
|
|
1335
|
+
function evaluateFuncValue(node, ctx) {
|
|
1336
|
+
const { name, args } = node;
|
|
1337
|
+
const fieldArg = args[0];
|
|
1338
|
+
const val = resolveFieldNode(fieldArg, ctx);
|
|
1339
|
+
if (name === 'lower' || name === 'lower_array') {
|
|
1340
|
+
if (Array.isArray(val))
|
|
1341
|
+
return val.map(v => String(v).toLowerCase());
|
|
1342
|
+
return val !== null ? String(val).toLowerCase() : null;
|
|
1343
|
+
}
|
|
1344
|
+
if (name === 'len') {
|
|
1345
|
+
return val !== null ? String(val).length : null;
|
|
1346
|
+
}
|
|
1347
|
+
if (name === 'to_string') {
|
|
1348
|
+
return val !== null ? String(val) : null;
|
|
1349
|
+
}
|
|
1350
|
+
return val;
|
|
1351
|
+
}
|
|
1352
|
+
const _parseCache = new Map();
|
|
1353
|
+
function parseExpression(expr, warnings) {
|
|
1354
|
+
const cached = _parseCache.get(expr);
|
|
1355
|
+
if (cached) {
|
|
1356
|
+
if (warnings)
|
|
1357
|
+
cached.warnings.forEach(message => pushWarning(warnings, message));
|
|
1358
|
+
return cached.node;
|
|
1359
|
+
}
|
|
1360
|
+
const parseWarnings = [];
|
|
1361
|
+
const tokens = tokenize(expr, parseWarnings);
|
|
1362
|
+
const node = new Parser(tokens, expr, parseWarnings).parse();
|
|
1363
|
+
_parseCache.set(expr, { node, warnings: [...parseWarnings] });
|
|
1364
|
+
if (warnings)
|
|
1365
|
+
parseWarnings.forEach(message => pushWarning(warnings, message));
|
|
1366
|
+
return node;
|
|
1367
|
+
}
|
|
1368
|
+
export function evaluateExpression(expr, request, options = {}) {
|
|
1369
|
+
const warnings = [];
|
|
1370
|
+
const ast = parseExpression(expr, warnings);
|
|
1371
|
+
const ctx = {
|
|
1372
|
+
request,
|
|
1373
|
+
response: options.response,
|
|
1374
|
+
url: new URL(request.url),
|
|
1375
|
+
cf: (request.cf ?? {}),
|
|
1376
|
+
cookieMap: null,
|
|
1377
|
+
queryParams: null,
|
|
1378
|
+
warnings,
|
|
1379
|
+
};
|
|
1380
|
+
const state = { chain: [], matchedOrBranch: null, nullOrBranch: null };
|
|
1381
|
+
const result = evaluateNode(ast, ctx, state);
|
|
1382
|
+
const largeNotBlockThreshold = options.largeNotBlockThreshold ?? 3;
|
|
1383
|
+
const finalize = (matched, matchedBranch, chainEntries, inferredViaList) => {
|
|
1384
|
+
const matchChain = chainEntries.map(formatMatchChainEntry);
|
|
1385
|
+
const { matchChainCompat, largeBlocks } = buildCompatMatchChain(chainEntries, largeNotBlockThreshold);
|
|
1386
|
+
return {
|
|
1387
|
+
matched,
|
|
1388
|
+
matchedBranch,
|
|
1389
|
+
matchChain,
|
|
1390
|
+
matchChainCompat,
|
|
1391
|
+
largeBlocks,
|
|
1392
|
+
inferredViaList,
|
|
1393
|
+
warnings: [...warnings],
|
|
1394
|
+
};
|
|
1395
|
+
};
|
|
1396
|
+
if (result === true) {
|
|
1397
|
+
return finalize(true, state.matchedOrBranch ?? expr, state.chain, false);
|
|
1398
|
+
}
|
|
1399
|
+
if (result === null) {
|
|
1400
|
+
return finalize(true, state.nullOrBranch ?? expr, state.chain, true);
|
|
1401
|
+
}
|
|
1402
|
+
return finalize(false, '', [], false);
|
|
1403
|
+
}
|
|
1404
|
+
// ─── Field coverage export (used by tests) ────────────────────────────────────
|
|
1405
|
+
// Every field name that appears as an explicit `case` in resolveField().
|
|
1406
|
+
// Available = returns a real value; Unavailable = returns null (with a structured warning).
|
|
1407
|
+
export const KNOWN_AVAILABLE_FIELDS = new Set([
|
|
1408
|
+
'http.host',
|
|
1409
|
+
'http.request.uri',
|
|
1410
|
+
'http.request.uri.path',
|
|
1411
|
+
'http.request.full_uri',
|
|
1412
|
+
'http.request.uri.query',
|
|
1413
|
+
'http.request.uri.path.extension',
|
|
1414
|
+
'http.request.uri.path.basename',
|
|
1415
|
+
'http.request.uri.args',
|
|
1416
|
+
'http.request.uri.args.names',
|
|
1417
|
+
'http.request.uri.args.values',
|
|
1418
|
+
'http.request.method',
|
|
1419
|
+
'http.request.version',
|
|
1420
|
+
'http.cookie',
|
|
1421
|
+
'http.referer',
|
|
1422
|
+
'http.user_agent',
|
|
1423
|
+
'http.x_forwarded_for',
|
|
1424
|
+
'http.request.headers',
|
|
1425
|
+
'http.request.headers.names',
|
|
1426
|
+
'http.request.headers.values',
|
|
1427
|
+
'http.request.headers.truncated',
|
|
1428
|
+
'http.request.cookies',
|
|
1429
|
+
'http.request.accepted_languages',
|
|
1430
|
+
'ip.src',
|
|
1431
|
+
'ip.src.asnum',
|
|
1432
|
+
'ip.geoip.asnum',
|
|
1433
|
+
'ip.src.country',
|
|
1434
|
+
'ip.geoip.country',
|
|
1435
|
+
'ip.src.continent',
|
|
1436
|
+
'ip.geoip.continent',
|
|
1437
|
+
'ip.src.city',
|
|
1438
|
+
'ip.src.is_in_european_union',
|
|
1439
|
+
'ip.geoip.is_in_european_union',
|
|
1440
|
+
'ip.src.lat',
|
|
1441
|
+
'ip.src.lon',
|
|
1442
|
+
'ip.src.subdivision_1_iso_code',
|
|
1443
|
+
'ip.src.subdivision_2_iso_code',
|
|
1444
|
+
'ip.src.region',
|
|
1445
|
+
'ip.src.region_code',
|
|
1446
|
+
'ip.src.metro_code',
|
|
1447
|
+
'ip.src.postal_code',
|
|
1448
|
+
'ip.src.timezone.name',
|
|
1449
|
+
'ssl',
|
|
1450
|
+
'cf.tls_version',
|
|
1451
|
+
'cf.tls_cipher',
|
|
1452
|
+
'cf.tls_client_extensions_sha1',
|
|
1453
|
+
'cf.tls_client_extensions_sha1_le',
|
|
1454
|
+
'cf.tls_client_ciphers_sha1',
|
|
1455
|
+
'cf.tls_ciphers_sha1',
|
|
1456
|
+
'cf.tls_client_hello_length',
|
|
1457
|
+
'cf.tls_client_random',
|
|
1458
|
+
'cf.tls_client_auth.cert_presented',
|
|
1459
|
+
'cf.tls_client_auth.cert_verified',
|
|
1460
|
+
'cf.tls_client_auth.cert_revoked',
|
|
1461
|
+
'cf.tls_client_auth.cert_issuer_dn',
|
|
1462
|
+
'cf.tls_client_auth.cert_subject_dn',
|
|
1463
|
+
'cf.tls_client_auth.cert_issuer_dn_rfc2253',
|
|
1464
|
+
'cf.tls_client_auth.cert_subject_dn_rfc2253',
|
|
1465
|
+
'cf.tls_client_auth.cert_issuer_dn_legacy',
|
|
1466
|
+
'cf.tls_client_auth.cert_subject_dn_legacy',
|
|
1467
|
+
'cf.tls_client_auth.cert_serial',
|
|
1468
|
+
'cf.tls_client_auth.cert_issuer_serial',
|
|
1469
|
+
'cf.tls_client_auth.cert_ski',
|
|
1470
|
+
'cf.tls_client_auth.cert_issuer_ski',
|
|
1471
|
+
'cf.tls_client_auth.cert_fingerprint_sha1',
|
|
1472
|
+
'cf.tls_client_auth.cert_fingerprint_sha256',
|
|
1473
|
+
'cf.tls_client_auth.cert_not_before',
|
|
1474
|
+
'cf.tls_client_auth.cert_not_after',
|
|
1475
|
+
'cf.tls_client_auth.cert_rfc9440',
|
|
1476
|
+
'cf.tls_client_auth.cert_rfc9440_too_large',
|
|
1477
|
+
'cf.tls_client_auth.cert_chain_rfc9440',
|
|
1478
|
+
'cf.tls_client_auth.cert_chain_rfc9440_too_large',
|
|
1479
|
+
'cf.bot_management.score',
|
|
1480
|
+
'cf.bot_management.verified_bot',
|
|
1481
|
+
'cf.bot_management.static_resource',
|
|
1482
|
+
'cf.bot_management.ja3_hash',
|
|
1483
|
+
'cf.bot_management.ja4',
|
|
1484
|
+
'cf.bot_management.detection_ids',
|
|
1485
|
+
'cf.bot_management.corporate_proxy',
|
|
1486
|
+
'cf.bot_management.js_detection.passed',
|
|
1487
|
+
'cf.client.bot',
|
|
1488
|
+
'cf.verified_bot_category',
|
|
1489
|
+
'cf.ray_id',
|
|
1490
|
+
'cf.edge.l4.delivery_rate',
|
|
1491
|
+
'cf.edge.client_tcp',
|
|
1492
|
+
'cf.timings.client_tcp_rtt_msec',
|
|
1493
|
+
'cf.timings.client_quic_rtt_msec',
|
|
1494
|
+
'cf.hostname.metadata',
|
|
1495
|
+
]);
|
|
1496
|
+
export const KNOWN_UNAVAILABLE_FIELDS = new Set([
|
|
1497
|
+
// Raw / pre-transform
|
|
1498
|
+
'raw.http.request.uri',
|
|
1499
|
+
'raw.http.request.full_uri',
|
|
1500
|
+
'raw.http.request.uri.path',
|
|
1501
|
+
'raw.http.request.uri.path.extension',
|
|
1502
|
+
'raw.http.request.uri.query',
|
|
1503
|
+
'raw.http.request.uri.args',
|
|
1504
|
+
'raw.http.request.uri.args.names',
|
|
1505
|
+
'raw.http.request.uri.args.values',
|
|
1506
|
+
// Timestamps
|
|
1507
|
+
'http.request.timestamp.sec',
|
|
1508
|
+
'http.request.timestamp.msec',
|
|
1509
|
+
// Body
|
|
1510
|
+
'http.request.body.form',
|
|
1511
|
+
'http.request.body.form.names',
|
|
1512
|
+
'http.request.body.form.values',
|
|
1513
|
+
'http.request.body.mime',
|
|
1514
|
+
'http.request.body.multipart',
|
|
1515
|
+
'http.request.body.multipart.content_dispositions',
|
|
1516
|
+
'http.request.body.multipart.content_transfer_encodings',
|
|
1517
|
+
'http.request.body.multipart.content_types',
|
|
1518
|
+
'http.request.body.multipart.filenames',
|
|
1519
|
+
'http.request.body.multipart.names',
|
|
1520
|
+
'http.request.body.multipart.values',
|
|
1521
|
+
'http.request.body.raw',
|
|
1522
|
+
'http.request.body.size',
|
|
1523
|
+
'http.request.body.truncated',
|
|
1524
|
+
// JWT claims
|
|
1525
|
+
'http.request.jwt.claims.aud',
|
|
1526
|
+
'http.request.jwt.claims.aud.names',
|
|
1527
|
+
'http.request.jwt.claims.aud.values',
|
|
1528
|
+
'http.request.jwt.claims.iat.sec',
|
|
1529
|
+
'http.request.jwt.claims.iat.sec.names',
|
|
1530
|
+
'http.request.jwt.claims.iat.sec.values',
|
|
1531
|
+
'http.request.jwt.claims.iss',
|
|
1532
|
+
'http.request.jwt.claims.iss.names',
|
|
1533
|
+
'http.request.jwt.claims.iss.values',
|
|
1534
|
+
'http.request.jwt.claims.jti',
|
|
1535
|
+
'http.request.jwt.claims.jti.names',
|
|
1536
|
+
'http.request.jwt.claims.jti.values',
|
|
1537
|
+
'http.request.jwt.claims.nbf.sec',
|
|
1538
|
+
'http.request.jwt.claims.nbf.sec.names',
|
|
1539
|
+
'http.request.jwt.claims.nbf.sec.values',
|
|
1540
|
+
'http.request.jwt.claims.sub',
|
|
1541
|
+
'http.request.jwt.claims.sub.names',
|
|
1542
|
+
'http.request.jwt.claims.sub.values',
|
|
1543
|
+
// HTTP response
|
|
1544
|
+
'http.response.code',
|
|
1545
|
+
'http.response.content_type.media_type',
|
|
1546
|
+
'http.response.headers',
|
|
1547
|
+
'http.response.headers.names',
|
|
1548
|
+
'http.response.headers.values',
|
|
1549
|
+
'raw.http.response.headers',
|
|
1550
|
+
'raw.http.response.headers.names',
|
|
1551
|
+
'raw.http.response.headers.values',
|
|
1552
|
+
// WAF internal
|
|
1553
|
+
'cf.threat_score',
|
|
1554
|
+
'cf.waf.score',
|
|
1555
|
+
'cf.waf.score.class',
|
|
1556
|
+
'cf.waf.score.rce',
|
|
1557
|
+
'cf.waf.score.sqli',
|
|
1558
|
+
'cf.waf.score.xss',
|
|
1559
|
+
'cf.waf.auth_detected',
|
|
1560
|
+
'cf.waf.content_scan.has_failed',
|
|
1561
|
+
'cf.waf.content_scan.has_malicious_obj',
|
|
1562
|
+
'cf.waf.content_scan.has_obj',
|
|
1563
|
+
'cf.waf.content_scan.num_malicious_obj',
|
|
1564
|
+
'cf.waf.content_scan.num_obj',
|
|
1565
|
+
'cf.waf.content_scan.obj_results',
|
|
1566
|
+
'cf.waf.content_scan.obj_sizes',
|
|
1567
|
+
'cf.waf.content_scan.obj_types',
|
|
1568
|
+
'cf.waf.credential_check.password_leaked',
|
|
1569
|
+
'cf.waf.credential_check.username_and_password_leaked',
|
|
1570
|
+
'cf.waf.credential_check.username_leaked',
|
|
1571
|
+
'cf.waf.credential_check.username_password_similar',
|
|
1572
|
+
// API Gateway
|
|
1573
|
+
'cf.api_gateway.auth_id_present',
|
|
1574
|
+
'cf.api_gateway.fallthrough_detected',
|
|
1575
|
+
'cf.api_gateway.request_violates_schema',
|
|
1576
|
+
// AI / LLM
|
|
1577
|
+
'cf.llm.prompt.custom_topic_categories',
|
|
1578
|
+
'cf.llm.prompt.detected',
|
|
1579
|
+
'cf.llm.prompt.injection_score',
|
|
1580
|
+
'cf.llm.prompt.pii_categories',
|
|
1581
|
+
'cf.llm.prompt.pii_detected',
|
|
1582
|
+
'cf.llm.prompt.token_count',
|
|
1583
|
+
'cf.llm.prompt.unsafe_topic_categories',
|
|
1584
|
+
'cf.llm.prompt.unsafe_topic_detected',
|
|
1585
|
+
// Response / post-request timing
|
|
1586
|
+
'cf.response.1xxx_code',
|
|
1587
|
+
'cf.response.error_type',
|
|
1588
|
+
'cf.timings.edge_msec',
|
|
1589
|
+
'cf.timings.origin_ttfb_msec',
|
|
1590
|
+
'cf.timings.worker_msec',
|
|
1591
|
+
// Other unavailable
|
|
1592
|
+
'cf.random_seed',
|
|
1593
|
+
'cf.worker.upstream_zone',
|
|
1594
|
+
'cf.edge.server_ip',
|
|
1595
|
+
'cf.edge.server_port',
|
|
1596
|
+
'cf.edge.client_port',
|
|
1597
|
+
'cf.zone.name',
|
|
1598
|
+
'cf.metal.id',
|
|
1599
|
+
]);
|
|
1600
|
+
export function validateRuleExpressionSyntax(source) {
|
|
1601
|
+
const expression = source.trim();
|
|
1602
|
+
const errors = [];
|
|
1603
|
+
const warnings = [];
|
|
1604
|
+
if (!expression)
|
|
1605
|
+
errors.push('[rule-evaluator] rule expression is required');
|
|
1606
|
+
const parseWarnings = [];
|
|
1607
|
+
if (expression)
|
|
1608
|
+
parseExpression(expression, parseWarnings);
|
|
1609
|
+
const minified = minifyRuleExpression(expression);
|
|
1610
|
+
const minifiedParseWarnings = [];
|
|
1611
|
+
if (minified.expression)
|
|
1612
|
+
parseExpression(minified.expression, minifiedParseWarnings);
|
|
1613
|
+
for (const warning of [...parseWarnings, ...minified.warnings, ...minifiedParseWarnings]) {
|
|
1614
|
+
if (isRuleSyntaxWarning(warning))
|
|
1615
|
+
errors.push(warning);
|
|
1616
|
+
else
|
|
1617
|
+
warnings.push(warning);
|
|
1618
|
+
}
|
|
1619
|
+
return {
|
|
1620
|
+
ok: errors.length === 0,
|
|
1621
|
+
expression,
|
|
1622
|
+
minifiedExpression: minified.expression,
|
|
1623
|
+
length: expression.length,
|
|
1624
|
+
minifiedLength: minified.expression.length,
|
|
1625
|
+
errors: [...new Set(errors)],
|
|
1626
|
+
warnings: [...new Set(warnings)],
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
export function minifyRuleExpression(source) {
|
|
1630
|
+
const warnings = [];
|
|
1631
|
+
const tokens = tokenize(source, warnings).filter(token => token.kind !== 'EOF');
|
|
1632
|
+
let expression = '';
|
|
1633
|
+
let previous = null;
|
|
1634
|
+
for (const token of tokens) {
|
|
1635
|
+
const rendered = renderMinifiedToken(token);
|
|
1636
|
+
if (previous && needsMinifiedSpace(previous, token))
|
|
1637
|
+
expression += ' ';
|
|
1638
|
+
expression += rendered;
|
|
1639
|
+
previous = token;
|
|
1640
|
+
}
|
|
1641
|
+
return { expression, warnings };
|
|
1642
|
+
}
|
|
1643
|
+
function renderMinifiedToken(token) {
|
|
1644
|
+
if (token.kind === 'String')
|
|
1645
|
+
return `"${token.value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
|
|
1646
|
+
return token.value;
|
|
1647
|
+
}
|
|
1648
|
+
function isRuleSyntaxWarning(warning) {
|
|
1649
|
+
return warning.includes('unexpected') || warning.includes('missing closing');
|
|
1650
|
+
}
|
|
1651
|
+
function needsMinifiedSpace(previous, current) {
|
|
1652
|
+
if (previous.kind === 'LParen' || previous.kind === 'LBracket' || previous.kind === 'LBrace')
|
|
1653
|
+
return false;
|
|
1654
|
+
if (current.kind === 'RParen' || current.kind === 'RBracket' || current.kind === 'RBrace')
|
|
1655
|
+
return false;
|
|
1656
|
+
if (current.kind === 'LBracket' || previous.kind === 'RBracket')
|
|
1657
|
+
return false;
|
|
1658
|
+
if (previous.kind === 'Identifier' && current.kind === 'LParen')
|
|
1659
|
+
return false;
|
|
1660
|
+
if (previous.kind === 'Operator' && current.kind === 'Operator')
|
|
1661
|
+
return true;
|
|
1662
|
+
if (previous.kind === 'Operator')
|
|
1663
|
+
return isMinifiedWordLike(current);
|
|
1664
|
+
if (current.kind === 'Operator')
|
|
1665
|
+
return isMinifiedWordLike(previous);
|
|
1666
|
+
return isMinifiedAtom(previous) && isMinifiedAtom(current);
|
|
1667
|
+
}
|
|
1668
|
+
function isMinifiedAtom(token) {
|
|
1669
|
+
return token.kind === 'Identifier' || token.kind === 'String' || token.kind === 'Number' || token.kind === 'Boolean' || token.kind === 'Star';
|
|
1670
|
+
}
|
|
1671
|
+
function isMinifiedWordLike(token) {
|
|
1672
|
+
return token.kind === 'Identifier' || token.kind === 'Number' || token.kind === 'Boolean' || token.kind === 'Star';
|
|
1673
|
+
}
|
|
1674
|
+
//# sourceMappingURL=rule-evaluator.js.map
|