@libreflare/worker-runtime 0.10.4 → 0.10.6

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.
Files changed (100) hide show
  1. package/README.md +101 -44
  2. package/dist/rule-evaluator/access-values.d.ts +42 -27
  3. package/dist/rule-evaluator/access-values.d.ts.map +1 -1
  4. package/dist/rule-evaluator/access-values.js +123 -52
  5. package/dist/rule-evaluator/access-values.js.map +1 -1
  6. package/dist/rule-evaluator/byte-strings.d.ts.map +1 -1
  7. package/dist/rule-evaluator/byte-strings.js +27 -11
  8. package/dist/rule-evaluator/byte-strings.js.map +1 -1
  9. package/dist/rule-evaluator/constants.d.ts +1 -1
  10. package/dist/rule-evaluator/constants.d.ts.map +1 -1
  11. package/dist/rule-evaluator/constants.js +8 -0
  12. package/dist/rule-evaluator/constants.js.map +1 -1
  13. package/dist/rule-evaluator/country-codes.generated.js +1 -1
  14. package/dist/rule-evaluator/diagnostics.d.ts +1 -1
  15. package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
  16. package/dist/rule-evaluator/diagnostics.js +10 -0
  17. package/dist/rule-evaluator/diagnostics.js.map +1 -1
  18. package/dist/rule-evaluator/edge-field-gaps.d.ts +6 -4
  19. package/dist/rule-evaluator/edge-field-gaps.d.ts.map +1 -1
  20. package/dist/rule-evaluator/edge-field-gaps.js +40 -42
  21. package/dist/rule-evaluator/edge-field-gaps.js.map +1 -1
  22. package/dist/rule-evaluator/edge-record.js +2 -0
  23. package/dist/rule-evaluator/edge-record.js.map +1 -1
  24. package/dist/rule-evaluator/engine-observations.d.ts +4 -4
  25. package/dist/rule-evaluator/engine-observations.d.ts.map +1 -1
  26. package/dist/rule-evaluator/engine-observations.generated.d.ts +533 -3
  27. package/dist/rule-evaluator/engine-observations.generated.d.ts.map +1 -1
  28. package/dist/rule-evaluator/engine-observations.generated.js +406 -248
  29. package/dist/rule-evaluator/engine-observations.generated.js.map +1 -1
  30. package/dist/rule-evaluator/engine-observations.js +1 -0
  31. package/dist/rule-evaluator/engine-observations.js.map +1 -1
  32. package/dist/rule-evaluator/explain.js +12 -9
  33. package/dist/rule-evaluator/explain.js.map +1 -1
  34. package/dist/rule-evaluator/field-availability.d.ts +6 -1
  35. package/dist/rule-evaluator/field-availability.d.ts.map +1 -1
  36. package/dist/rule-evaluator/field-availability.js +16 -4
  37. package/dist/rule-evaluator/field-availability.js.map +1 -1
  38. package/dist/rule-evaluator/field-descriptions.generated.d.ts +147 -5
  39. package/dist/rule-evaluator/field-descriptions.generated.d.ts.map +1 -1
  40. package/dist/rule-evaluator/field-descriptions.generated.js +345 -5
  41. package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
  42. package/dist/rule-evaluator/fields.d.ts +0 -1
  43. package/dist/rule-evaluator/fields.d.ts.map +1 -1
  44. package/dist/rule-evaluator/fields.js +67 -8
  45. package/dist/rule-evaluator/fields.js.map +1 -1
  46. package/dist/rule-evaluator/function-availability.d.ts +7 -0
  47. package/dist/rule-evaluator/function-availability.d.ts.map +1 -1
  48. package/dist/rule-evaluator/function-availability.js +38 -0
  49. package/dist/rule-evaluator/function-availability.js.map +1 -1
  50. package/dist/rule-evaluator/function-descriptions.d.ts +12 -2
  51. package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
  52. package/dist/rule-evaluator/function-descriptions.generated.d.ts +171 -4
  53. package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
  54. package/dist/rule-evaluator/function-descriptions.generated.js +1280 -98
  55. package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
  56. package/dist/rule-evaluator/function-descriptions.js +3 -1
  57. package/dist/rule-evaluator/function-descriptions.js.map +1 -1
  58. package/dist/rule-evaluator/function-signature-validation.d.ts +13 -4
  59. package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
  60. package/dist/rule-evaluator/function-signature-validation.js +142 -28
  61. package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
  62. package/dist/rule-evaluator/functions.d.ts +10 -6
  63. package/dist/rule-evaluator/functions.d.ts.map +1 -1
  64. package/dist/rule-evaluator/functions.js +550 -167
  65. package/dist/rule-evaluator/functions.js.map +1 -1
  66. package/dist/rule-evaluator/minifier.d.ts +9 -0
  67. package/dist/rule-evaluator/minifier.d.ts.map +1 -1
  68. package/dist/rule-evaluator/minifier.js +23 -0
  69. package/dist/rule-evaluator/minifier.js.map +1 -1
  70. package/dist/rule-evaluator/operators.d.ts.map +1 -1
  71. package/dist/rule-evaluator/operators.js +15 -6
  72. package/dist/rule-evaluator/operators.js.map +1 -1
  73. package/dist/rule-evaluator/parse-cache.d.ts +3 -1
  74. package/dist/rule-evaluator/parse-cache.d.ts.map +1 -1
  75. package/dist/rule-evaluator/parse-cache.js +4 -0
  76. package/dist/rule-evaluator/parse-cache.js.map +1 -1
  77. package/dist/rule-evaluator/parser.d.ts +7 -1
  78. package/dist/rule-evaluator/parser.d.ts.map +1 -1
  79. package/dist/rule-evaluator/parser.js +14 -0
  80. package/dist/rule-evaluator/parser.js.map +1 -1
  81. package/dist/rule-evaluator/quantifier.d.ts +19 -2
  82. package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
  83. package/dist/rule-evaluator/quantifier.js +104 -12
  84. package/dist/rule-evaluator/quantifier.js.map +1 -1
  85. package/dist/rule-evaluator/replacement.d.ts +37 -0
  86. package/dist/rule-evaluator/replacement.d.ts.map +1 -0
  87. package/dist/rule-evaluator/replacement.js +54 -0
  88. package/dist/rule-evaluator/replacement.js.map +1 -0
  89. package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
  90. package/dist/rule-evaluator/rule-language-types.js +5 -0
  91. package/dist/rule-evaluator/rule-language-types.js.map +1 -1
  92. package/dist/rule-evaluator/validation.d.ts +2 -1
  93. package/dist/rule-evaluator/validation.d.ts.map +1 -1
  94. package/dist/rule-evaluator/validation.js +250 -91
  95. package/dist/rule-evaluator/validation.js.map +1 -1
  96. package/dist/rule-evaluator/wildcard.d.ts +6 -3
  97. package/dist/rule-evaluator/wildcard.d.ts.map +1 -1
  98. package/dist/rule-evaluator/wildcard.js +10 -4
  99. package/dist/rule-evaluator/wildcard.js.map +1 -1
  100. package/package.json +1 -1
@@ -3,9 +3,9 @@ import { EQUALITY_ORDERING_OPERATORS, isBooleanLiteralName, isConditionArgument,
3
3
  import { RULE_EXPRESSION_MATCH_ALL_EXPRESSION } from './constants.js';
4
4
  import { isRuleExpressionFunctionAvailable, isRuleExpressionOperatorAvailable } from './function-availability.js';
5
5
  import { getUnreliableRuleExpressionFunctionReason } from './functions.js';
6
- import { bindArguments, PREDICATE_SHAPE_TYPES, validateFunctionSignature, wildcardPatternDiagnostic, } from './function-signature-validation.js';
7
- import { minifyRuleExpression } from './minifier.js';
8
- import { parseExpression } from './parse-cache.js';
6
+ import { bindArguments, PREDICATE_SHAPE_TYPES, validateFunctionSignature, validatePresetArgumentFields, wildcardPatternDiagnostic, } from './function-signature-validation.js';
7
+ import { minifyRuleExpression, minifyRuleExpressionValue } from './minifier.js';
8
+ import { parseExpression, parseFieldOrCallExpression } from './parse-cache.js';
9
9
  import { trimRuleExpression } from './tokenizer.js';
10
10
  import { hasRuleExpressionSyntaxErrors } from './transformation.js';
11
11
  import { isKnownRuleExpressionFieldName, isRuleExpressionFieldAvailable, resolveRuleExpressionFieldAvailability, } from './field-availability.js';
@@ -15,24 +15,41 @@ import { isRuleExpressionCountryCode } from './country-codes.js';
15
15
  import { getRuleExpressionFieldValueDomain } from './field-value-domains.js';
16
16
  import { customList, isRuleExpressionIpListItem, isRuleExpressionListName, } from './custom-lists.js';
17
17
  import { collectionElementDataType, conditionShape, fieldDataType, formatRuleExpressionDataType, isArrayConditionArgument, isArrayExpandedNode, isBooleanArrayType, isBooleanType, isConcreteComparisonFamily, isFieldNode, isFuncNode, inferFunctionInvocation, inferRuleExpressionArgument, isIpAddressValueType, isStringLiteral, isUnknownRuleExpressionDataType, ruleExpressionComparisonTypeFamily, ruleExpressionValueTypes, singleValueType, } from './rule-language-types.js';
18
- import { conditionArray, isArrayCall, isArrayComparison, isArrayCondition, predicateArrays, quantifierPredicateConditions, readQuantifierPredicate, readsWholeArray, unalignedArray, unwrapMappedCalls, } from './quantifier.js';
18
+ import { conditionArray, isArrayCall, isArrayComparison, isArrayCondition, keepsPlacesWhenMapped, pairedArgumentArrays, predicateArrays, quantifierPredicateConditions, readQuantifierPredicate, readsWholeArray, unalignedArray, unwrapMappedCalls, } from './quantifier.js';
19
19
  import { renderRuleExpressionStringLiteral } from './string-literals.js';
20
20
  export const MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH = 4096;
21
21
  export const RULE_EXPRESSION_VALIDATION_PRESETS = [
22
22
  'url-rewrite-filter',
23
23
  'url-rewrite-target',
24
+ 'custom-rule',
24
25
  'logging-source-key',
25
26
  ];
27
+ /** The presets whose expressions are one field or function call that gives a String, as Cloudflare reads a rewrite target. */
28
+ const VALUE_EXPRESSION_PRESETS = new Set(['url-rewrite-target']);
26
29
  function isArgumentPosition(position) {
27
30
  return position === 'argument' || position === 'boolean-argument' || position === 'array-argument';
28
31
  }
29
- /** Functions Cloudflare accepts at most once in an expression, a limit that applies in every preset. */
30
- const SINGLE_USE_FUNCTIONS = new Set(['hash_in_range', 'regex_replace', 'uuidv4', 'wildcard_replace']);
32
+ /** How many calls of a function Cloudflare accepts in an expression, a limit that applies in every preset. */
33
+ const FUNCTION_CALL_LIMITS = new Map([
34
+ ['encode_hex', 4],
35
+ ['format_date', 4],
36
+ ['hash_in_range', 1],
37
+ ['hmac_md5', 5],
38
+ ['hmac_sha1', 5],
39
+ ['hmac_sha256', 5],
40
+ ['hmac_sha512', 5],
41
+ ['regex_replace', 1],
42
+ ['sign_sigv4_hmac_sha256', 1],
43
+ ['uuidv4', 1],
44
+ ['wildcard_replace', 1],
45
+ ]);
31
46
  /**
32
- * Functions the URL rewrite phase accepts at most once in a filter or a
33
- * rewrite target. Header transforms accept two concat() calls.
47
+ * How many calls of a function Cloudflare accepts in each preset's phase.
48
+ * Header transforms accept three concat() calls, as rewrite targets do.
34
49
  */
35
- const URL_REWRITE_SINGLE_USE_FUNCTIONS = new Set(['concat']);
50
+ const PHASE_FUNCTION_CALL_LIMITS = new Map([
51
+ ['concat', { 'url-rewrite-filter': 1, 'url-rewrite-target': 3, 'custom-rule': 1 }],
52
+ ]);
36
53
  /** Replacement functions Cloudflare does not accept inside each other, in every preset. */
37
54
  const NON_NESTABLE_REPLACEMENT_FUNCTIONS = new Set(['regex_replace', 'wildcard_replace']);
38
55
  const SUPPORTED_LIST_KIND = 'ip';
@@ -63,13 +80,14 @@ export function validateRuleExpressionSyntax(source, config = {}) {
63
80
  });
64
81
  }
65
82
  const parseDiagnostics = [];
66
- const parsedExpression = expression ? parseExpression(expression, parseDiagnostics, parseOptions) : null;
83
+ const parsedExpression = expression ? parsePresetExpression(preset, expression, parseDiagnostics, parseOptions) : null;
67
84
  // The minifier keeps an expression with a syntax error as it is, so only one without is minified.
68
85
  const minifies = minify && !hasRuleExpressionSyntaxErrors(parseDiagnostics);
69
- const minifiedExpression = minifies ? minifyRuleExpression(expression, parseOptions).expression : expression;
86
+ const minifier = VALUE_EXPRESSION_PRESETS.has(preset) ? minifyRuleExpressionValue : minifyRuleExpression;
87
+ const minifiedExpression = minifies ? minifier(expression, parseOptions).expression : expression;
70
88
  const minifiedParseDiagnostics = [];
71
89
  if (minifies && minifiedExpression)
72
- parseExpression(minifiedExpression, minifiedParseDiagnostics);
90
+ parsePresetExpression(preset, minifiedExpression, minifiedParseDiagnostics);
73
91
  const lengthCheckedExpression = minify ? minifiedExpression : expression;
74
92
  collectValidationDiagnostics(errors, diagnostics, parseDiagnostics, 'expression');
75
93
  if (parsedExpression)
@@ -140,7 +158,7 @@ export function ruleExpressionEvaluationErrors(expression) {
140
158
  const errors = [];
141
159
  const diagnostics = [];
142
160
  collectValidationDiagnostics(errors, diagnostics, parseDiagnostics, 'expression');
143
- collectSemanticValidationDiagnostics(errors, diagnostics, node, expression, {
161
+ collectSemanticValidationDiagnostics(errors, diagnostics, { kind: 'condition', node }, expression, {
144
162
  preset: null,
145
163
  fieldAvailability: null,
146
164
  rejectListReferences: false,
@@ -254,13 +272,85 @@ function collectValidationDiagnostics(errors, diagnostics, messageDiagnostics, s
254
272
  diagnostics.push(ruleExpressionDiagnostic(diagnostic, source));
255
273
  }
256
274
  }
257
- function collectSemanticValidationDiagnostics(errors, diagnostics, node, expression, context) {
258
- const rootPosition = context.preset === 'url-rewrite-target' ? 'value' : 'predicate';
259
- validateBooleanLiterals(node, errors, diagnostics);
260
- validateSemanticNode(node, new Set(), errors, diagnostics, expression, context, rootPosition);
261
- validateFunctionUsage(node, context, errors, diagnostics);
275
+ /** Parses an expression as its preset reads it. */
276
+ function parsePresetExpression(preset, expression, diagnostics, options = {}) {
277
+ return VALUE_EXPRESSION_PRESETS.has(preset)
278
+ ? { kind: 'value', node: parseFieldOrCallExpression(expression, diagnostics, options) }
279
+ : { kind: 'condition', node: parseExpression(expression, diagnostics, options) };
280
+ }
281
+ function collectSemanticValidationDiagnostics(errors, diagnostics, parsed, expression, context) {
282
+ validateBooleanLiterals(parsed.node, errors, diagnostics);
283
+ if (parsed.kind === 'value')
284
+ validateValueExpression(parsed.node, errors, diagnostics, expression, context);
285
+ else
286
+ validateSemanticNode(parsed.node, new Set(), errors, diagnostics, expression, context, 'predicate');
287
+ validateFunctionUsage(parsed.node, context, errors, diagnostics);
288
+ }
289
+ /** Checks an expression read as one field or function call, and that it gives a String. */
290
+ function validateValueExpression(node, errors, diagnostics, expression, context) {
291
+ if (node.kind === 'Invalid') {
292
+ // A field or call that recovery cut short gets its own checks, as in validateSemanticNode().
293
+ if (node.operand)
294
+ validateFieldOrFunc(node.operand, new Set(), errors, diagnostics, expression, context);
295
+ return;
296
+ }
297
+ validateFieldOrFunc(node, new Set(), errors, diagnostics, expression, context);
298
+ validateValueResultType(node, errors, diagnostics);
262
299
  }
263
- function validateSemanticNode(node, guardedHeaders, errors, diagnostics, expression, context, position) {
300
+ /**
301
+ * Reports a value expression whose result can't be a String. Cloudflare
302
+ * reports it beside the operators it rejects, as in a rewrite target of
303
+ * `any(...)`.
304
+ */
305
+ function validateValueResultType(node, errors, diagnostics) {
306
+ const info = inferRuleExpressionArgument(node);
307
+ if (info.invalid || mayBeString(info.type))
308
+ return;
309
+ // A call that may have more arguments may have lost its `)` and an access after it.
310
+ if (node.kind === 'Func' && mayHaveMoreArguments(node) && mayReachString(info.type))
311
+ return;
312
+ const actualType = formatRuleExpressionDataType(info.type);
313
+ errors.push(`expression must give a String; received ${actualType}`);
314
+ diagnostics.push({
315
+ id: 'rule_expression.result_type_mismatch',
316
+ params: { expectedType: 'String', actualType },
317
+ severity: 'error',
318
+ pos: node.pos ?? null,
319
+ length: node.length ?? 0,
320
+ source: 'expression',
321
+ });
322
+ }
323
+ /** Whether an access may take a String from a value of this type: an array's element or a map's value. */
324
+ function mayReachString(type) {
325
+ switch (type.kind) {
326
+ case 'array':
327
+ return mayBeString(type.element) || mayReachString(type.element);
328
+ case 'map':
329
+ return mayBeString(type.value) || mayReachString(type.value);
330
+ case 'union':
331
+ return type.options.some(mayReachString);
332
+ default:
333
+ return false;
334
+ }
335
+ }
336
+ /**
337
+ * Whether a type may be a String, Cloudflare's bytes type, which Bytes names
338
+ * too. An unknown type may, and so may a union with an option that may.
339
+ */
340
+ function mayBeString(type) {
341
+ switch (type.kind) {
342
+ case 'unknown':
343
+ return true;
344
+ case 'scalar':
345
+ return type.name === 'String' || type.name === 'Bytes';
346
+ case 'union':
347
+ return type.options.some(mayBeString);
348
+ default:
349
+ return false;
350
+ }
351
+ }
352
+ /** Checks a node and the ones in it. `counted` says that len() only counts the array the node gives. */
353
+ function validateSemanticNode(node, guardedHeaders, errors, diagnostics, expression, context, position, counted = false) {
264
354
  // The conditions an argument combines are arguments' conditions too, with the first one's type.
265
355
  let operandPosition = 'predicate';
266
356
  if (position === 'boolean-argument' || position === 'array-argument')
@@ -271,54 +361,54 @@ function validateSemanticNode(node, guardedHeaders, errors, diagnostics, express
271
361
  case 'And': {
272
362
  const andGuards = unionHeaderGuards(guardedHeaders, collectHeaderPresenceGuards(node));
273
363
  for (const operand of node.operands) {
274
- validateSemanticNode(operand, andGuards, errors, diagnostics, expression, context, operandPosition);
364
+ validateSemanticNode(operand, andGuards, errors, diagnostics, expression, context, operandPosition, counted);
275
365
  }
276
366
  return;
277
367
  }
278
368
  case 'Or':
279
369
  case 'Xor':
280
370
  for (const operand of node.operands) {
281
- validateSemanticNode(operand, guardedHeaders, errors, diagnostics, expression, context, operandPosition);
371
+ validateSemanticNode(operand, guardedHeaders, errors, diagnostics, expression, context, operandPosition, counted);
282
372
  }
283
373
  return;
284
374
  case 'Not':
285
- validateSemanticNode(node.operand, guardedHeaders, errors, diagnostics, expression, context, isArgumentPosition(position) ? position : 'predicate');
375
+ validateSemanticNode(node.operand, guardedHeaders, errors, diagnostics, expression, context, isArgumentPosition(position) ? position : 'predicate', counted);
286
376
  return;
287
377
  case 'Comparison':
288
- validateFieldOrFunc(node.left, guardedHeaders, errors, diagnostics, expression, context);
378
+ validateFieldOrFunc(node.left, guardedHeaders, errors, diagnostics, expression, context, counted);
289
379
  if (isDynamicValueNode(node.right)) {
290
380
  validateFieldOrFunc(node.right, guardedHeaders, errors, diagnostics, expression, context);
291
381
  }
292
382
  validateComparisonRequirements(node, errors, diagnostics, context, isArgumentPosition(position));
293
383
  return;
294
384
  case 'Func': {
295
- if (position !== 'value' && position !== 'counted')
385
+ if (position !== 'value')
296
386
  validateFunctionPredicateResult(node, position, errors, diagnostics);
297
387
  validateFunctionAvailability(node, errors, diagnostics, context);
298
388
  validateAccessPath(node, errors, diagnostics);
299
389
  const binding = bindArguments(node);
300
- const argumentsValid = validateFunctionArgRequirements(node, binding, errors, diagnostics);
390
+ const argumentsValid = validateFunctionArgRequirements(node, binding, errors, diagnostics, context);
391
+ const countsArguments = countsArrayArguments(node, counted);
301
392
  // An order warning or a dropped-header notice on a call the signature rejects would only add to its
302
393
  // error. Other errors, such as an access after the call, a missing comparison, or a rejected call
303
394
  // around it, leave the read itself valid, so it still gets them.
304
395
  if (argumentsValid) {
305
- validateHeaderOrderReads(node, diagnostics, expression);
396
+ validateHeaderOrderReads(node, diagnostics, expression, context);
306
397
  validateDroppedHeaderLookups(node, diagnostics);
398
+ validateDroppedHeaderConditions(node, countsArguments ? selectingArguments(node) : node.args, diagnostics);
307
399
  }
308
400
  if (node.name === 'coalesce')
309
401
  validateCoalesceFallbacks(node, binding, diagnostics);
310
402
  const errorCount = errors.length;
311
- // Whether len() only counts the arrays the call's arguments give.
312
- const counted = node.name === 'len' || position === 'counted';
313
403
  if (node.name === 'any' || node.name === 'all') {
314
404
  validateQuantifierPredicateArgs(node, guardedHeaders, errors, diagnostics, expression, context);
315
405
  }
316
406
  else {
317
- validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context, counted);
407
+ validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context, countsArguments);
318
408
  }
319
409
  // A pairing warning on conditions any check rejects would only add to their errors.
320
410
  if (argumentsValid && errors.length === errorCount)
321
- validateConditionPairing(node, diagnostics, expression, counted);
411
+ validateConditionPairing(node, diagnostics, expression, context, countsArguments);
322
412
  return;
323
413
  }
324
414
  case 'BoolField':
@@ -565,9 +655,9 @@ function validateLeftOperandType(node, leftFamily, errors, diagnostics) {
565
655
  case 'ge':
566
656
  if (isOrderingFamily(leftFamily))
567
657
  return true;
568
- pushComparisonTypeError(node.left, `operator '${node.op}' requires String or Number values; left side is ${leftLabel}`, errors, diagnostics, {
658
+ pushComparisonTypeError(node.left, `operator '${node.op}' requires String, Number, or IP address values; left side is ${leftLabel}`, errors, diagnostics, {
569
659
  id: 'operator.requires_type',
570
- params: { operator: node.op, side: 'left', requiredTypes: ['String', 'Number'], actualType: leftLabel },
660
+ params: { operator: node.op, side: 'left', requiredTypes: ['String', 'Number', 'IP address'], actualType: leftLabel },
571
661
  });
572
662
  return false;
573
663
  case 'contains':
@@ -587,7 +677,7 @@ function isEqualityFamily(family) {
587
677
  return family === 'string' || family === 'number' || family === 'ip';
588
678
  }
589
679
  function isOrderingFamily(family) {
590
- return family === 'string' || family === 'number';
680
+ return family === 'string' || family === 'number' || family === 'ip';
591
681
  }
592
682
  function comparisonFamilyLabel(family) {
593
683
  switch (family) {
@@ -612,8 +702,8 @@ function validateFunctionUsage(node, context, errors, diagnostics) {
612
702
  collectFunctionUsage(node, [], usage);
613
703
  for (const functionName of usage.calls.keys())
614
704
  validateFunctionSupport(functionName, diagnostics);
615
- for (const functionName of SINGLE_USE_FUNCTIONS)
616
- reportSingleUseFunction(functionName, usage, preset, errors, diagnostics);
705
+ for (const [functionName, maxCalls] of FUNCTION_CALL_LIMITS)
706
+ reportExcessCalls(functionName, maxCalls, usage, preset, errors, diagnostics);
617
707
  // Cloudflare reports a nested replacement even where it does not accept the outer function.
618
708
  for (const { node: nested, parentFunctionName } of usage.nestedReplacements) {
619
709
  pushFuncError(nested, `function '${nested.name}' cannot be nested inside '${parentFunctionName}'`, errors, diagnostics, {
@@ -621,10 +711,10 @@ function validateFunctionUsage(node, context, errors, diagnostics) {
621
711
  params: { functionName: nested.name, parentFunctionName },
622
712
  });
623
713
  }
624
- if (preset !== 'url-rewrite-filter' && preset !== 'url-rewrite-target')
714
+ if (preset === null || preset === 'logging-source-key')
625
715
  return;
626
- for (const functionName of URL_REWRITE_SINGLE_USE_FUNCTIONS)
627
- reportSingleUseFunction(functionName, usage, preset, errors, diagnostics);
716
+ for (const [functionName, maxCalls] of PHASE_FUNCTION_CALL_LIMITS)
717
+ reportExcessCalls(functionName, maxCalls[preset], usage, preset, errors, diagnostics);
628
718
  for (const { operator, node: operatorNode } of usage.operators ?? []) {
629
719
  if (isRuleExpressionOperatorAvailable(operator, preset))
630
720
  continue;
@@ -640,17 +730,25 @@ function validateFunctionUsage(node, context, errors, diagnostics) {
640
730
  }
641
731
  }
642
732
  /**
643
- * Reports every call of a function after its first. A function the preset
733
+ * Reports every call of a function past its limit. A function the preset
644
734
  * does not accept has only its availability errors, as in Cloudflare.
645
735
  */
646
- function reportSingleUseFunction(functionName, usage, preset, errors, diagnostics) {
736
+ function reportExcessCalls(functionName, maxCalls, usage, preset, errors, diagnostics) {
647
737
  if (preset && !isRuleExpressionFunctionAvailable(functionName, preset))
648
738
  return;
649
- for (const duplicate of (usage.calls.get(functionName) ?? []).slice(1)) {
650
- pushFuncError(duplicate, `function '${functionName}' can appear only once in an expression`, errors, diagnostics, {
651
- id: 'function.single_use',
652
- params: { functionName },
653
- });
739
+ for (const call of (usage.calls.get(functionName) ?? []).slice(maxCalls)) {
740
+ if (maxCalls === 1) {
741
+ pushFuncError(call, `function '${functionName}' can appear only once in an expression`, errors, diagnostics, {
742
+ id: 'function.single_use',
743
+ params: { functionName },
744
+ });
745
+ }
746
+ else {
747
+ pushFuncError(call, `function '${functionName}' can appear at most ${maxCalls} times in an expression`, errors, diagnostics, {
748
+ id: 'function.call_limit',
749
+ params: { functionName, maxCalls },
750
+ });
751
+ }
654
752
  }
655
753
  }
656
754
  /**
@@ -763,6 +861,11 @@ function validateListReference(arg, errors, diagnostics, context) {
763
861
  });
764
862
  }
765
863
  }
864
+ /**
865
+ * Checks that a list takes the left side's type. Libreflare supports only IP
866
+ * lists, so a list the config does not give is checked as one, although
867
+ * Cloudflare has lists of other kinds.
868
+ */
766
869
  function validateKnownListRefValueType(node, left, errors, diagnostics, context) {
767
870
  const listKind = customList(context.customLists, node.name)?.kind ?? SUPPORTED_LIST_KIND;
768
871
  const valueTypes = ruleExpressionValueTypes(left);
@@ -889,12 +992,12 @@ function validateFunctionSupport(functionName, diagnostics) {
889
992
  * however its result is used, as in `len(join(http.request.headers.names, ""))`,
890
993
  * which would take tracking the string it gives.
891
994
  */
892
- function validateHeaderOrderReads(node, diagnostics, expression) {
995
+ function validateHeaderOrderReads(node, diagnostics, expression, context) {
893
996
  const fields = node.name === 'join'
894
997
  ? orderedHeaderFields(node.args[0], true)
895
998
  : node.accessPath[0]?.kind === 'ArrayIndexAccess' ? resultHeaderFields(node) : [];
896
999
  for (const field of fields)
897
- pushHeaderOrderWarning(field, diagnostics, expression);
1000
+ pushHeaderOrderWarning(field, diagnostics, expression, context);
898
1001
  }
899
1002
  /**
900
1003
  * The header name or value fields whose order a value keeps whole. `first`
@@ -919,13 +1022,15 @@ function orderedHeaderFields(node, first) {
919
1022
  * The header name or value fields whose order a call's result keeps, before
920
1023
  * its own access: a call that maps over its first argument keeps that
921
1024
  * argument's order, coalesce() gives one of its arguments as is, and
922
- * concat() joins its arguments in turn.
1025
+ * concat() joins its arguments in turn. filter() keeps some of its array's
1026
+ * elements in that array's order.
923
1027
  */
924
1028
  function resultHeaderFields(node) {
925
1029
  if (node.name === 'coalesce' || node.name === 'concat') {
926
1030
  return node.args.flatMap((arg, index) => orderedHeaderFields(arg, index === 0));
927
1031
  }
928
- return inferFunctionInvocation(node).mapping === 'mapped' ? orderedHeaderFields(node.args[0], true) : [];
1032
+ const keepsOrder = node.name === 'filter' || inferFunctionInvocation(node).mapping === 'mapped';
1033
+ return keepsOrder ? orderedHeaderFields(node.args[0], true) : [];
929
1034
  }
930
1035
  /**
931
1036
  * Whether a field lists the request headers in an order Worker context may
@@ -940,8 +1045,11 @@ function isRebuiltHeaderArray(name) {
940
1045
  * Warns about a read of the request header names or values in order, which
941
1046
  * a challenge solve may get wrong. has_value(), len(), and any() and all()
942
1047
  * over arrays that line up do not depend on it; see validateConditionPairing().
1048
+ * A Custom Rule is never evaluated in Worker context, so it gets no warning.
943
1049
  */
944
- function pushHeaderOrderWarning(node, diagnostics, expression) {
1050
+ function pushHeaderOrderWarning(node, diagnostics, expression, context) {
1051
+ if (context.preset === 'custom-rule')
1052
+ return;
945
1053
  // Reads can reach a field more than once, as an index on a call and the pairing of its arguments do.
946
1054
  if (diagnostics.some(diagnostic => diagnostic.id === 'field.header_order_unreliable' && diagnostic.pos === node.pos))
947
1055
  return;
@@ -984,36 +1092,43 @@ function validateCoalesceFallbacks(node, binding, diagnostics) {
984
1092
  source: 'expression',
985
1093
  });
986
1094
  }
987
- function validateFieldOrFunc(node, guardedHeaders, errors, diagnostics, expression, context) {
1095
+ function validateFieldOrFunc(node, guardedHeaders, errors, diagnostics, expression, context, counted = false) {
988
1096
  if (isFieldNode(node)) {
989
1097
  validateFieldNode(node, guardedHeaders, errors, diagnostics, expression, context);
990
1098
  return;
991
1099
  }
992
- validateSemanticNode(node, guardedHeaders, errors, diagnostics, expression, context, 'value');
1100
+ validateSemanticNode(node, guardedHeaders, errors, diagnostics, expression, context, 'value', counted);
993
1101
  }
994
- function validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context, counted = false) {
1102
+ function validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context, countsArguments = false) {
995
1103
  for (let index = 0; index < node.args.length; index++) {
996
1104
  const arg = node.args[index];
997
1105
  if (isFieldNode(arg)) {
998
1106
  validateFieldNode(arg, guardedHeaders, errors, diagnostics, expression, context);
999
1107
  }
1000
1108
  else if (isExpressionNode(arg)) {
1001
- validateSemanticNode(arg, guardedHeaders, errors, diagnostics, expression, context, argumentPosition(node, index, counted));
1109
+ // How many elements filter() keeps depends on its conditions, and other calls have no other arrays to count.
1110
+ const counted = countsArguments && (index === 0 || node.name === 'coalesce' || node.name === 'concat');
1111
+ validateSemanticNode(arg, guardedHeaders, errors, diagnostics, expression, context, isConditionArgument(arg) ? 'argument' : 'value', counted);
1002
1112
  }
1003
1113
  else if (arg.kind === 'ListRef') {
1004
1114
  validateListReference(arg, errors, diagnostics, context);
1005
1115
  }
1006
1116
  }
1007
1117
  }
1008
- /** Where a call's argument is, where `counted` says that len() only counts the arrays its arguments give. */
1009
- function argumentPosition(node, index, counted) {
1010
- const arg = node.args[index];
1011
- if (isConditionArgument(arg))
1012
- return 'argument';
1013
- // len() takes one argument.
1014
- if (!counted || (node.name === 'len' && index > 0))
1015
- return 'value';
1016
- return isFuncNode(arg) && (arg.name === 'coalesce' || arg.name === 'concat') && arg.accessPath.length === 0 ? 'counted' : 'value';
1118
+ /** Functions whose result len() counts by counting the arrays among their arguments, without mapping over one. */
1119
+ const COUNTED_FUNCTIONS = new Set(['coalesce', 'concat', 'filter']);
1120
+ /** The arguments whose results settle how many elements a call gives: filter()'s conditions, unless it maps. */
1121
+ function selectingArguments(node) {
1122
+ return node.name === 'filter' && inferFunctionInvocation(node).mapping !== 'mapped' ? node.args.slice(1) : [];
1123
+ }
1124
+ /** Whether len() only counts the arrays among a call's arguments, where `counted` says that it only counts the call's. */
1125
+ function countsArrayArguments(node, counted) {
1126
+ const mapped = inferFunctionInvocation(node).mapping === 'mapped';
1127
+ if (node.name === 'len' && !mapped)
1128
+ return true;
1129
+ if (!counted || !readsWholeArray(node.accessPath))
1130
+ return false;
1131
+ return mapped ? keepsPlacesWhenMapped(node.name) : COUNTED_FUNCTIONS.has(node.name);
1017
1132
  }
1018
1133
  function validateQuantifierPredicateArgs(node, guardedHeaders, errors, diagnostics, expression, context) {
1019
1134
  const reading = readQuantifierPredicate(node);
@@ -1050,8 +1165,26 @@ function validateQuantifierComparisonOperands(comparison, guardedHeaders, errors
1050
1165
  if (value?.kind === 'ListRef')
1051
1166
  validateListRef(value, comparison.left, comparison.op, errors, diagnostics, context);
1052
1167
  validateComparisonWildcardPattern(comparison, errors, diagnostics);
1168
+ validateDroppedHeaderNames(comparison, diagnostics);
1169
+ }
1170
+ /** Gives a notice where a comparison an argument combines looks a request header up by name, as validateDroppedHeaderNames() does. */
1171
+ function validateDroppedHeaderConditions(node, args, diagnostics) {
1172
+ // any() and all() check their own comparisons.
1173
+ if (node.name === 'any' || node.name === 'all')
1174
+ return;
1175
+ for (const arg of args) {
1176
+ if (!isExpressionNode(arg) || !isConditionArgument(arg))
1177
+ continue;
1178
+ for (const { node: condition } of quantifierPredicateConditions(arg)) {
1179
+ if (condition.kind === 'Comparison')
1180
+ validateDroppedHeaderNames(condition, diagnostics);
1181
+ }
1182
+ }
1183
+ }
1184
+ /** Gives a notice where a comparison over the request header names looks one up by name; see pushDroppedHeaderNotice(). */
1185
+ function validateDroppedHeaderNames(comparison, diagnostics) {
1053
1186
  // Only a String compared with each whole name looks a header up, so other comparisons skip the walk.
1054
- const literals = NAME_LOOKUP_OPERATORS.has(comparison.op) ? stringLiterals(value) : [];
1187
+ const literals = NAME_LOOKUP_OPERATORS.has(comparison.op) ? stringLiterals(comparison.right) : [];
1055
1188
  const names = literals.length > 0 ? headerCollection(comparison.left) : null;
1056
1189
  if (names?.kind === 'names') {
1057
1190
  for (const literal of literals) {
@@ -1080,14 +1213,16 @@ function validateDroppedHeaderLookups(node, diagnostics) {
1080
1213
  /**
1081
1214
  * Gives a notice where a rule reads a request header that Cloudflare drops
1082
1215
  * when it rebuilds a challenged request after a solve, such as Pragma. The
1083
- * rule never sees the header on the rebuilt request, so a URL rewrite that
1084
- * depends on it no longer applies, but whether a rule's traffic is challenged
1085
- * is not known here. A read that can never match the header is left out, as a
1216
+ * rule never sees the header on the rebuilt request, so a URL rewrite or a
1217
+ * Custom Rule that depends on it no longer applies, but whether a rule's
1218
+ * traffic is challenged is not known here. A read that can never match the header is left out, as a
1086
1219
  * solve does not change its result. Only a comparison with the whole name
1087
1220
  * counts: patterns and string functions over the names, such as `contains`,
1088
1221
  * `matches`, starts_with() and join(), get no notice, as one that matches the
1089
1222
  * header's name usually matches others too, and neither do ordering
1090
- * comparisons, or reads by position, which the order warning covers.
1223
+ * comparisons, or reads by position, which the order warning covers. Nor do
1224
+ * lookups among names a call such as filter() or concat() gives, as
1225
+ * headerCollection() reads only the fields, in one case or as they are.
1091
1226
  */
1092
1227
  function pushDroppedHeaderNotice(name, node, diagnostics) {
1093
1228
  const headerName = name.toLowerCase();
@@ -1103,18 +1238,20 @@ function pushDroppedHeaderNotice(name, node, diagnostics) {
1103
1238
  });
1104
1239
  }
1105
1240
  /**
1106
- * Warns when a call's conditions pair arrays whose elements may not line up:
1107
- * a quantifier's predicate, or an argument read as a condition with a result
1108
- * for each element. Cloudflare pairs them by index and stops at the shorter
1109
- * one, so conditions on arrays from different lists rarely mean what they
1110
- * say. Such pairs also depend on the order of each array, so the request
1111
- * header names and values among them get the order warning, unless
1112
- * `counted` says that len() only counts the results.
1241
+ * Warns when a call pairs arrays whose elements may not line up: those of a
1242
+ * quantifier's predicate, or of an argument read as a condition with a result
1243
+ * for each element, or filter()'s array and those of its conditions.
1244
+ * Cloudflare pairs them by index and stops at the shorter one, so conditions
1245
+ * on arrays from different lists rarely mean what they say. Such pairs also
1246
+ * depend on the order of each array, so the request header names and values
1247
+ * among them get the order warning, unless `counted` says that len() only
1248
+ * counts the results.
1113
1249
  */
1114
- function validateConditionPairing(node, diagnostics, expression, counted) {
1115
- for (const conditions of pairingConditions(node)) {
1116
- const arrays = predicateArrays(conditions);
1117
- const unaligned = unalignedArray(arrays);
1250
+ function validateConditionPairing(node, diagnostics, expression, context, counted) {
1251
+ // A filter() that maps pairs the conditions with each array in a list, which no list lines up with.
1252
+ const mapped = node.name === 'filter' && inferFunctionInvocation(node).mapping === 'mapped';
1253
+ for (const arrays of pairedArrays(node)) {
1254
+ const unaligned = mapped ? arrays[1] : unalignedArray(arrays);
1118
1255
  if (!unaligned)
1119
1256
  continue;
1120
1257
  diagnostics.push({
@@ -1125,25 +1262,44 @@ function validateConditionPairing(node, diagnostics, expression, counted) {
1125
1262
  length: typeof unaligned.length === 'number' ? unaligned.length : 0,
1126
1263
  source: 'expression',
1127
1264
  });
1265
+ // How many results there are does not depend on the arrays' order, but how many filter() keeps depends on
1266
+ // its conditions'. Where it maps, or its result is only counted, its own array gives only their order.
1267
+ let ordered = arrays;
1128
1268
  if (counted)
1129
- continue;
1130
- for (const array of arrays) {
1269
+ ordered = selectingArguments(node).flatMap(pairedArgumentArrays);
1270
+ else if (mapped)
1271
+ ordered = node.args.slice(1).flatMap(pairedArgumentArrays);
1272
+ for (const array of ordered) {
1131
1273
  for (const field of orderedHeaderFields(array, true))
1132
- pushHeaderOrderWarning(field, diagnostics, expression);
1274
+ pushHeaderOrderWarning(field, diagnostics, expression, context);
1133
1275
  }
1134
1276
  }
1135
1277
  }
1136
- /** A call's conditions with a result for each element: a quantifier's predicate read as conditions, or such arguments. */
1137
- function pairingConditions(node) {
1278
+ /**
1279
+ * The arrays a call pairs by index, in lists of those paired with each other:
1280
+ * the arrays of a quantifier's predicate read as conditions, those of each
1281
+ * argument that is a condition with a result for each element, or all of
1282
+ * filter()'s.
1283
+ */
1284
+ function pairedArrays(node) {
1138
1285
  if (node.name === 'any' || node.name === 'all') {
1139
1286
  const reading = readQuantifierPredicate(node);
1140
- return reading?.kind === 'conditions' && !isUncertainArgument(node, 0) ? [reading.predicate] : [];
1287
+ return reading?.kind === 'conditions' && !isUncertainArgument(node, 0) ? [predicateArrays(reading.predicate)] : [];
1141
1288
  }
1142
- return node.args.filter((arg, index) => isArrayConditionArgument(arg) && !isUncertainArgument(node, index));
1143
- }
1144
- /** Reports arguments the function's signature rejects, and returns whether there were none. */
1145
- function validateFunctionArgRequirements(node, binding, errors, diagnostics) {
1146
- const signatureErrors = validateFunctionSignature(node, binding);
1289
+ if (node.name === 'filter') {
1290
+ // An invalid argument, such as one whose access failed to parse, has an error of its own.
1291
+ const uncertain = node.args.some((arg, index) => isUncertainArgument(node, index) || inferRuleExpressionArgument(arg).invalid);
1292
+ return uncertain ? [] : [node.args.flatMap(pairedArgumentArrays)];
1293
+ }
1294
+ return node.args
1295
+ .filter((arg, index) => isArrayConditionArgument(arg) && !isUncertainArgument(node, index))
1296
+ .map(predicateArrays);
1297
+ }
1298
+ /** Reports arguments the function's signature or the preset's phase rejects, and returns whether there were none. */
1299
+ function validateFunctionArgRequirements(node, binding, errors, diagnostics, context) {
1300
+ let signatureErrors = validateFunctionSignature(node, binding);
1301
+ if (signatureErrors.length === 0)
1302
+ signatureErrors = validatePresetArgumentFields(node, binding, context.preset);
1147
1303
  for (const signatureError of signatureErrors) {
1148
1304
  pushFunctionSignatureError(signatureError, errors, diagnostics);
1149
1305
  }
@@ -1178,7 +1334,7 @@ function validateFieldNode(node, guardedHeaders, errors, diagnostics, expression
1178
1334
  validateFieldAvailability(node, errors, diagnostics, expression, context);
1179
1335
  validateDeprecatedField(node, diagnostics, expression, context);
1180
1336
  if (isRebuiltHeaderArray(node.name) && node.accessPath[0]?.kind === 'ArrayIndexAccess') {
1181
- pushHeaderOrderWarning(node, diagnostics, expression);
1337
+ pushHeaderOrderWarning(node, diagnostics, expression, context);
1182
1338
  }
1183
1339
  // A guard for a rejected key would only repeat its error.
1184
1340
  if (!REQUEST_HEADER_MAPS.has(node.name) || !lowercaseKey)
@@ -1186,6 +1342,9 @@ function validateFieldNode(node, guardedHeaders, errors, diagnostics, expression
1186
1342
  const header = node.accessPath[0];
1187
1343
  if (header?.kind === 'MapKeyAccess')
1188
1344
  pushDroppedHeaderNotice(header.key, node, diagnostics);
1345
+ // A value expression holds no condition, so its guard can go only in the rule's filter, which validation doesn't see.
1346
+ if (context.preset !== null && VALUE_EXPRESSION_PRESETS.has(context.preset))
1347
+ return;
1189
1348
  // An invalid segment may have been the header's key or index, which leaves the ones after it uncertain.
1190
1349
  if (node.accessPath.some(access => access.kind === 'Invalid'))
1191
1350
  return;