@libreflare/worker-runtime 0.7.0 → 0.8.1
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 +235 -13
- package/dist/rule-evaluator/accept-encoding.d.ts +2 -2
- package/dist/rule-evaluator/accept-encoding.d.ts.map +1 -1
- package/dist/rule-evaluator/accept-encoding.js +62 -15
- package/dist/rule-evaluator/accept-encoding.js.map +1 -1
- package/dist/rule-evaluator/access-values.d.ts +77 -14
- package/dist/rule-evaluator/access-values.d.ts.map +1 -1
- package/dist/rule-evaluator/access-values.js +149 -17
- package/dist/rule-evaluator/access-values.js.map +1 -1
- package/dist/rule-evaluator/analysis.d.ts +43 -8
- package/dist/rule-evaluator/analysis.d.ts.map +1 -1
- package/dist/rule-evaluator/analysis.js +72 -29
- package/dist/rule-evaluator/analysis.js.map +1 -1
- package/dist/rule-evaluator/ast.d.ts +145 -11
- package/dist/rule-evaluator/ast.d.ts.map +1 -1
- package/dist/rule-evaluator/ast.js +102 -4
- package/dist/rule-evaluator/ast.js.map +1 -1
- package/dist/rule-evaluator/byte-strings.d.ts +23 -0
- package/dist/rule-evaluator/byte-strings.d.ts.map +1 -0
- package/dist/rule-evaluator/byte-strings.js +150 -0
- package/dist/rule-evaluator/byte-strings.js.map +1 -0
- package/dist/rule-evaluator/constants.d.ts +1 -1
- package/dist/rule-evaluator/constants.d.ts.map +1 -1
- package/dist/rule-evaluator/constants.js +1 -0
- package/dist/rule-evaluator/constants.js.map +1 -1
- package/dist/rule-evaluator/country-codes.generated.js +1 -1
- package/dist/rule-evaluator/custom-lists.d.ts +9 -0
- package/dist/rule-evaluator/custom-lists.d.ts.map +1 -1
- package/dist/rule-evaluator/custom-lists.js +43 -0
- package/dist/rule-evaluator/custom-lists.js.map +1 -1
- package/dist/rule-evaluator/diagnostics.d.ts +1 -3
- package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
- package/dist/rule-evaluator/diagnostics.js +10 -53
- package/dist/rule-evaluator/diagnostics.js.map +1 -1
- package/dist/rule-evaluator/engine-observations.d.ts +37 -0
- package/dist/rule-evaluator/engine-observations.d.ts.map +1 -0
- package/dist/rule-evaluator/engine-observations.generated.d.ts +991 -0
- package/dist/rule-evaluator/engine-observations.generated.d.ts.map +1 -0
- package/dist/rule-evaluator/engine-observations.generated.js +292 -0
- package/dist/rule-evaluator/engine-observations.generated.js.map +1 -0
- package/dist/rule-evaluator/engine-observations.js +13 -0
- package/dist/rule-evaluator/engine-observations.js.map +1 -0
- package/dist/rule-evaluator/evaluator.d.ts +1 -1
- package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
- package/dist/rule-evaluator/evaluator.js +16 -15
- package/dist/rule-evaluator/evaluator.js.map +1 -1
- package/dist/rule-evaluator/explain.d.ts.map +1 -1
- package/dist/rule-evaluator/explain.js +35 -20
- package/dist/rule-evaluator/explain.js.map +1 -1
- package/dist/rule-evaluator/field-availability.d.ts +11 -10
- package/dist/rule-evaluator/field-availability.d.ts.map +1 -1
- package/dist/rule-evaluator/field-availability.js +136 -97
- package/dist/rule-evaluator/field-availability.js.map +1 -1
- package/dist/rule-evaluator/field-descriptions.generated.d.ts +1 -1
- package/dist/rule-evaluator/field-descriptions.generated.js +1 -1
- package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
- package/dist/rule-evaluator/field-value-domains.d.ts.map +1 -1
- package/dist/rule-evaluator/field-value-domains.js +2 -4
- package/dist/rule-evaluator/field-value-domains.js.map +1 -1
- package/dist/rule-evaluator/fields.d.ts +25 -2
- package/dist/rule-evaluator/fields.d.ts.map +1 -1
- package/dist/rule-evaluator/fields.js +276 -119
- package/dist/rule-evaluator/fields.js.map +1 -1
- package/dist/rule-evaluator/function-availability.d.ts +16 -0
- package/dist/rule-evaluator/function-availability.d.ts.map +1 -0
- package/dist/rule-evaluator/function-availability.js +28 -0
- package/dist/rule-evaluator/function-availability.js.map +1 -0
- package/dist/rule-evaluator/function-descriptions.d.ts +15 -1
- package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
- package/dist/rule-evaluator/function-descriptions.generated.d.ts +50 -7
- package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
- package/dist/rule-evaluator/function-descriptions.generated.js +98 -12
- package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
- package/dist/rule-evaluator/function-descriptions.js +11 -2
- package/dist/rule-evaluator/function-descriptions.js.map +1 -1
- package/dist/rule-evaluator/function-signature-validation.d.ts +26 -2
- package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
- package/dist/rule-evaluator/function-signature-validation.js +311 -181
- package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
- package/dist/rule-evaluator/functions.d.ts +24 -5
- package/dist/rule-evaluator/functions.d.ts.map +1 -1
- package/dist/rule-evaluator/functions.js +353 -190
- package/dist/rule-evaluator/functions.js.map +1 -1
- package/dist/rule-evaluator/hash-in-range.d.ts +33 -0
- package/dist/rule-evaluator/hash-in-range.d.ts.map +1 -0
- package/dist/rule-evaluator/hash-in-range.js +72 -0
- package/dist/rule-evaluator/hash-in-range.js.map +1 -0
- package/dist/rule-evaluator/log-sample.d.ts.map +1 -1
- package/dist/rule-evaluator/log-sample.js +14 -6
- package/dist/rule-evaluator/log-sample.js.map +1 -1
- package/dist/rule-evaluator/match-chain.d.ts +3 -3
- package/dist/rule-evaluator/match-chain.d.ts.map +1 -1
- package/dist/rule-evaluator/match-chain.js +19 -13
- package/dist/rule-evaluator/match-chain.js.map +1 -1
- package/dist/rule-evaluator/minifier.d.ts.map +1 -1
- package/dist/rule-evaluator/minifier.js +16 -20
- package/dist/rule-evaluator/minifier.js.map +1 -1
- package/dist/rule-evaluator/normalizer.d.ts.map +1 -1
- package/dist/rule-evaluator/normalizer.js +6 -6
- package/dist/rule-evaluator/normalizer.js.map +1 -1
- package/dist/rule-evaluator/operators.d.ts +11 -4
- package/dist/rule-evaluator/operators.d.ts.map +1 -1
- package/dist/rule-evaluator/operators.js +62 -35
- package/dist/rule-evaluator/operators.js.map +1 -1
- package/dist/rule-evaluator/outcome.d.ts +2 -0
- package/dist/rule-evaluator/outcome.d.ts.map +1 -1
- package/dist/rule-evaluator/outcome.js +4 -0
- package/dist/rule-evaluator/outcome.js.map +1 -1
- package/dist/rule-evaluator/parse-cache.d.ts +3 -3
- package/dist/rule-evaluator/parse-cache.d.ts.map +1 -1
- package/dist/rule-evaluator/parse-cache.js +5 -13
- package/dist/rule-evaluator/parse-cache.js.map +1 -1
- package/dist/rule-evaluator/parser.d.ts +318 -11
- package/dist/rule-evaluator/parser.d.ts.map +1 -1
- package/dist/rule-evaluator/parser.js +1314 -333
- package/dist/rule-evaluator/parser.js.map +1 -1
- package/dist/rule-evaluator/quantifier.d.ts +1 -1
- package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
- package/dist/rule-evaluator/quantifier.js +1 -16
- package/dist/rule-evaluator/quantifier.js.map +1 -1
- package/dist/rule-evaluator/request-headers.d.ts +101 -0
- package/dist/rule-evaluator/request-headers.d.ts.map +1 -0
- package/dist/rule-evaluator/request-headers.js +344 -0
- package/dist/rule-evaluator/request-headers.js.map +1 -0
- package/dist/rule-evaluator/rule-language-types.d.ts +80 -21
- package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
- package/dist/rule-evaluator/rule-language-types.js +228 -67
- package/dist/rule-evaluator/rule-language-types.js.map +1 -1
- package/dist/rule-evaluator/tokenizer.d.ts +14 -4
- package/dist/rule-evaluator/tokenizer.d.ts.map +1 -1
- package/dist/rule-evaluator/tokenizer.js +24 -11
- package/dist/rule-evaluator/tokenizer.js.map +1 -1
- package/dist/rule-evaluator/transformation.d.ts.map +1 -1
- package/dist/rule-evaluator/transformation.js +10 -6
- package/dist/rule-evaluator/transformation.js.map +1 -1
- package/dist/rule-evaluator/url-decode.d.ts +8 -0
- package/dist/rule-evaluator/url-decode.d.ts.map +1 -0
- package/dist/rule-evaluator/url-decode.js +126 -0
- package/dist/rule-evaluator/url-decode.js.map +1 -0
- package/dist/rule-evaluator/validation.d.ts.map +1 -1
- package/dist/rule-evaluator/validation.js +509 -251
- package/dist/rule-evaluator/validation.js.map +1 -1
- package/dist/rule-evaluator.d.ts +2 -2
- package/dist/rule-evaluator.d.ts.map +1 -1
- package/dist/rule-evaluator.js.map +1 -1
- package/package.json +5 -2
- package/dist/rule-evaluator/comparison.d.ts +0 -16
- package/dist/rule-evaluator/comparison.d.ts.map +0 -1
- package/dist/rule-evaluator/comparison.js +0 -43
- package/dist/rule-evaluator/comparison.js.map +0 -1
- package/dist/rule-evaluator/custom-security-rule-analysis.d.ts +0 -36
- package/dist/rule-evaluator/custom-security-rule-analysis.d.ts.map +0 -1
- package/dist/rule-evaluator/custom-security-rule-analysis.js +0 -382
- package/dist/rule-evaluator/custom-security-rule-analysis.js.map +0 -1
- package/dist/rule-evaluator/values.d.ts +0 -26
- package/dist/rule-evaluator/values.d.ts.map +0 -1
- package/dist/rule-evaluator/values.js +0 -55
- package/dist/rule-evaluator/values.js.map +0 -1
- package/dist/rule-evaluator/warnings.d.ts +0 -2
- package/dist/rule-evaluator/warnings.d.ts.map +0 -1
- package/dist/rule-evaluator/warnings.js +0 -5
- package/dist/rule-evaluator/warnings.js.map +0 -1
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import { isDynamicValueNode,
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { EQUALITY_ORDERING_OPERATORS, isConditionArgument, isDynamicValueNode, unhandledNode, } from './ast.js';
|
|
2
|
+
import { applyRuntimeAccessPath, isUnknownElement, PartialArrayValue, RuleMapValue, } from './access-values.js';
|
|
3
|
+
import { byteLength, bytesToText, canonicalText, textToBytes } from './byte-strings.js';
|
|
4
|
+
import { formatIpAddress, ipAddressOctets } from './custom-lists.js';
|
|
5
|
+
import { resolveBoolField, resolveFieldNode } from './fields.js';
|
|
6
|
+
import { hashInRange } from './hash-in-range.js';
|
|
7
|
+
import { applyOp, compareOperands, findMatchingSetMember, literalValue, wildcardToRegex } from './operators.js';
|
|
8
|
+
import { andOutcome, incomparable, isUnknown, known, negateOutcome, orOutcome, outcomeValue, unavailable, valueOutcome, xorOutcome, } from './outcome.js';
|
|
6
9
|
import { extractQuantifierPredicate } from './quantifier.js';
|
|
7
|
-
import {
|
|
10
|
+
import { urlDecode } from './url-decode.js';
|
|
11
|
+
import { collectionElementDataType, compareRuleExpressionDataTypes, formatRuleExpressionDataType, evaluatedValueType, inferFunctionInvocation, } from './rule-language-types.js';
|
|
8
12
|
const UNRELIABLE_FUNCTION_REASONS = {
|
|
9
13
|
bit_slice: 'packet bit slicing is not available in Worker request context',
|
|
10
14
|
is_jwt_present: 'Cloudflare API JWT token configurations are not available in Worker request context',
|
|
@@ -21,31 +25,85 @@ export function getUnreliableRuleExpressionFunctionReason(name) {
|
|
|
21
25
|
* Cloudflare missing value.
|
|
22
26
|
*/
|
|
23
27
|
export function evaluateOperand(node, ctx) {
|
|
24
|
-
return
|
|
28
|
+
return ruleValue(evaluateRuntimeOperand(node, ctx));
|
|
29
|
+
}
|
|
30
|
+
function evaluateRuntimeOperand(node, ctx) {
|
|
31
|
+
return node.kind === 'Func' ? evaluateFuncValue(node, ctx) : resolveFieldNode(node, ctx);
|
|
25
32
|
}
|
|
26
33
|
/**
|
|
27
34
|
* Narrows a value to a rule-language value. Only coalesce(), has_key(), and
|
|
28
35
|
* postfix access read maps, and validation rejects maps anywhere else, so a
|
|
29
|
-
* map here is unknown.
|
|
36
|
+
* map here is unknown. So is a partly known array, which only any(), all(),
|
|
37
|
+
* mapped functions and postfix access can read in part.
|
|
30
38
|
*/
|
|
31
|
-
function
|
|
39
|
+
function ruleValue(evaluated) {
|
|
32
40
|
if (isUnknown(evaluated))
|
|
33
41
|
return evaluated;
|
|
34
|
-
|
|
42
|
+
if (evaluated.value instanceof RuleMapValue)
|
|
43
|
+
return unavailable('a map value');
|
|
44
|
+
if (evaluated.value instanceof PartialArrayValue)
|
|
45
|
+
return evaluated.value.unknown();
|
|
46
|
+
return known(evaluated.value);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Evaluates a comparison with Cloudflare missing-value semantics and typed
|
|
50
|
+
* equality and ordering. Operands this evaluator cannot resolve or compare,
|
|
51
|
+
* such as Worker-unavailable fields, make the result unknown.
|
|
52
|
+
*/
|
|
53
|
+
export function evaluateComparison(node, ctx) {
|
|
54
|
+
const left = evaluateOperand(node.left, ctx);
|
|
55
|
+
const right = node.right;
|
|
56
|
+
// A missing right-hand value comes from syntax recovery, not a Cloudflare missing value.
|
|
57
|
+
if (!right)
|
|
58
|
+
return { outcome: false, left };
|
|
59
|
+
if (right.kind === 'ListRef' || right.kind === 'SetLiteral') {
|
|
60
|
+
// An unknown value stays unknown even against an unresolved `$list`:
|
|
61
|
+
// list inference assumes list contents, never request values.
|
|
62
|
+
return { outcome: isUnknown(left) ? left : applyOp(node.op, left.value, right, ctx.customLists), left };
|
|
63
|
+
}
|
|
64
|
+
const dynamicRight = isDynamicValueNode(right);
|
|
65
|
+
// Cloudflare compares fields and function results only with equality and
|
|
66
|
+
// ordering operators. Never evaluate the value for other operators, such as
|
|
67
|
+
// matches, which would otherwise use a request value as a pattern.
|
|
68
|
+
if (dynamicRight && !EQUALITY_ORDERING_OPERATORS.has(node.op)) {
|
|
69
|
+
const reason = `operator '${node.op}' requires a literal value on the right side`;
|
|
70
|
+
ctx.warnings.add(`comparison '${node.raw}' cannot be evaluated: ${reason}`);
|
|
71
|
+
return { outcome: incomparable(reason), left };
|
|
72
|
+
}
|
|
73
|
+
const rightOperand = dynamicRight ? evaluateOperand(right, ctx) : known(literalValue(right));
|
|
74
|
+
const operands = { left, ...(dynamicRight ? { right: rightOperand } : {}) };
|
|
75
|
+
if (isUnknown(left))
|
|
76
|
+
return { outcome: left, ...operands };
|
|
77
|
+
if (isUnknown(rightOperand))
|
|
78
|
+
return { outcome: rightOperand, ...operands };
|
|
79
|
+
const outcome = compareOperands(node.op, { value: left.value, type: evaluatedValueType(node.left) }, { value: rightOperand.value, type: evaluatedValueType(right) }, ctx.warnings);
|
|
80
|
+
if (isUnknown(outcome) && outcome.cause.kind === 'incomparable') {
|
|
81
|
+
ctx.warnings.add(`comparison '${node.raw}' cannot be evaluated: ${outcome.cause.reason}`);
|
|
82
|
+
}
|
|
83
|
+
return { outcome, ...operands };
|
|
35
84
|
}
|
|
36
|
-
/** Evaluates the values an any()/all() collection yields. */
|
|
85
|
+
/** Evaluates the values an any()/all() collection yields, which can be partly known. */
|
|
37
86
|
export function evaluateCollection(fieldArg, ctx) {
|
|
38
|
-
const evaluated =
|
|
87
|
+
const evaluated = evaluateRuntimeOperand(fieldArg, ctx);
|
|
39
88
|
if (isUnknown(evaluated))
|
|
40
89
|
return evaluated;
|
|
41
90
|
const { value } = evaluated;
|
|
91
|
+
if (value instanceof RuleMapValue)
|
|
92
|
+
return unavailable('a map value');
|
|
93
|
+
if (value instanceof PartialArrayValue) {
|
|
94
|
+
const { values, unknown } = value.knownValues();
|
|
95
|
+
return known({ values: collectionValues(values), unknown });
|
|
96
|
+
}
|
|
42
97
|
if (Array.isArray(value))
|
|
43
|
-
return known(value
|
|
98
|
+
return known({ values: collectionValues(value) });
|
|
44
99
|
if (value === null)
|
|
45
|
-
return known([]);
|
|
100
|
+
return known({ values: [] });
|
|
46
101
|
if (typeof value === 'number')
|
|
47
|
-
return known([value]);
|
|
48
|
-
return known([String(value)]);
|
|
102
|
+
return known({ values: [value] });
|
|
103
|
+
return known({ values: [String(value)] });
|
|
104
|
+
}
|
|
105
|
+
function collectionValues(values) {
|
|
106
|
+
return values.filter((item) => typeof item === 'string' || typeof item === 'number');
|
|
49
107
|
}
|
|
50
108
|
export function findMatchedSetMemberForFunc(node, ctx) {
|
|
51
109
|
if (node.name !== 'any' && node.name !== 'all')
|
|
@@ -58,10 +116,10 @@ export function findMatchedSetMemberForFunc(node, ctx) {
|
|
|
58
116
|
const collection = evaluateCollection(quantifier.source, ctx);
|
|
59
117
|
if (isUnknown(collection))
|
|
60
118
|
return null;
|
|
61
|
-
for (const v of collection.value) {
|
|
62
|
-
const
|
|
63
|
-
if (
|
|
64
|
-
return
|
|
119
|
+
for (const v of collection.value.values) {
|
|
120
|
+
const member = findMatchingSetMember(v, quantifier.value);
|
|
121
|
+
if (member !== null)
|
|
122
|
+
return member;
|
|
65
123
|
}
|
|
66
124
|
return null;
|
|
67
125
|
}
|
|
@@ -85,11 +143,17 @@ function evaluateQuantifier(node, ctx) {
|
|
|
85
143
|
if (isUnknown(collection))
|
|
86
144
|
return collection;
|
|
87
145
|
const compare = comparatorFor(node, quantifier, ctx);
|
|
88
|
-
const outcomes = collection.value.map((value) => {
|
|
146
|
+
const outcomes = collection.value.values.map((value) => {
|
|
89
147
|
const outcome = compare(value);
|
|
90
148
|
return quantifier.negated ? negateOutcome(outcome) : outcome;
|
|
91
149
|
});
|
|
92
|
-
|
|
150
|
+
const combine = node.name === 'any' ? orOutcome : andOutcome;
|
|
151
|
+
const outcome = combine(outcomes);
|
|
152
|
+
// A known value settles any() when it matches and all() when it does not; otherwise the unknown values count too.
|
|
153
|
+
const { unknown } = collection.value;
|
|
154
|
+
if (!unknown || outcome === (node.name === 'any'))
|
|
155
|
+
return outcome;
|
|
156
|
+
return combine([outcome, unknown()]);
|
|
93
157
|
}
|
|
94
158
|
/**
|
|
95
159
|
* Returns a comparison of collection values against the quantifier's
|
|
@@ -102,9 +166,9 @@ function comparatorFor(node, quantifier, ctx) {
|
|
|
102
166
|
const { op, value: right } = quantifier;
|
|
103
167
|
if (right.kind === 'ListRef' || right.kind === 'SetLiteral')
|
|
104
168
|
return left => applyOp(op, left, right, ctx.customLists);
|
|
105
|
-
const elementType = collectionElementDataType(
|
|
169
|
+
const elementType = collectionElementDataType(evaluatedValueType(quantifier.source))
|
|
106
170
|
?? { kind: 'unknown' };
|
|
107
|
-
const rightType =
|
|
171
|
+
const rightType = evaluatedValueType(right);
|
|
108
172
|
let operand;
|
|
109
173
|
return (left) => {
|
|
110
174
|
operand ??= isDynamicValueNode(right) ? evaluateOperand(right, ctx) : known(literalValue(right));
|
|
@@ -112,7 +176,7 @@ function comparatorFor(node, quantifier, ctx) {
|
|
|
112
176
|
return operand;
|
|
113
177
|
const outcome = compareOperands(op, { value: left, type: elementType }, { value: operand.value, type: rightType }, ctx.warnings);
|
|
114
178
|
if (isUnknown(outcome) && outcome.cause.kind === 'incomparable') {
|
|
115
|
-
|
|
179
|
+
ctx.warnings.add(`comparison in '${node.raw}' cannot be evaluated: ${outcome.cause.reason}`);
|
|
116
180
|
}
|
|
117
181
|
return outcome;
|
|
118
182
|
};
|
|
@@ -123,19 +187,19 @@ function comparatorFor(node, quantifier, ctx) {
|
|
|
123
187
|
*/
|
|
124
188
|
export function evaluateFuncValue(node, ctx) {
|
|
125
189
|
const invocation = inferFunctionInvocation(node);
|
|
126
|
-
const evaluated = invocation.mapped
|
|
190
|
+
const evaluated = invocation.mapping === 'mapped'
|
|
127
191
|
? evaluateFuncArray(node, ctx, invocation)
|
|
128
192
|
: evaluateDirectFuncValue(node, ctx, invocation);
|
|
129
193
|
if (isUnknown(evaluated))
|
|
130
194
|
return evaluated;
|
|
131
|
-
return
|
|
195
|
+
return applyRuntimeAccessPath(evaluated.value, node.accessPath);
|
|
132
196
|
}
|
|
133
197
|
function evaluateDirectFuncValue(node, ctx, invocation, firstArgumentValue) {
|
|
134
198
|
const { name, args } = node;
|
|
135
199
|
const runtimeArgument = (index) => index === 0 && firstArgumentValue !== undefined
|
|
136
200
|
? known(firstArgumentValue)
|
|
137
201
|
: evaluateArgValue(args[index], ctx);
|
|
138
|
-
const argument = (index) =>
|
|
202
|
+
const argument = (index) => ruleValue(runtimeArgument(index));
|
|
139
203
|
switch (name) {
|
|
140
204
|
case 'all':
|
|
141
205
|
case 'any':
|
|
@@ -158,7 +222,34 @@ function evaluateDirectFuncValue(node, ctx, invocation, firstArgumentValue) {
|
|
|
158
222
|
return map;
|
|
159
223
|
if (!(map.value instanceof RuleMapValue))
|
|
160
224
|
return unavailable('a map value');
|
|
161
|
-
return
|
|
225
|
+
return map.value.has(String(key.value));
|
|
226
|
+
}
|
|
227
|
+
case 'has_value': {
|
|
228
|
+
const collection = runtimeArgument(0);
|
|
229
|
+
if (isUnknown(collection))
|
|
230
|
+
return collection;
|
|
231
|
+
// A partly known array's known elements can settle it, as they do any().
|
|
232
|
+
const partial = collection.value instanceof PartialArrayValue ? collection.value.knownValues() : undefined;
|
|
233
|
+
const values = partial ? known(partial.values) : ruleValue(collection);
|
|
234
|
+
if (isUnknown(values))
|
|
235
|
+
return values;
|
|
236
|
+
const value = argument(1);
|
|
237
|
+
if (isUnknown(value))
|
|
238
|
+
return value;
|
|
239
|
+
const result = evaluateHasValue(values.value, value.value);
|
|
240
|
+
return result === false && partial ? partial.unknown() : known(result);
|
|
241
|
+
}
|
|
242
|
+
case 'hash_in_range':
|
|
243
|
+
return hashInRangeValue(ctx, args, invocation.argumentTypes[2] ?? undefined, argument);
|
|
244
|
+
case 'len': {
|
|
245
|
+
const source = runtimeArgument(0);
|
|
246
|
+
if (isUnknown(source))
|
|
247
|
+
return source;
|
|
248
|
+
// Unknown elements keep their places, so only more that may follow leaves the length unknown.
|
|
249
|
+
if (source.value instanceof PartialArrayValue)
|
|
250
|
+
return source.value.more?.() ?? known(source.value.elements.length);
|
|
251
|
+
const value = ruleValue(source);
|
|
252
|
+
return isUnknown(value) ? value : known(lengthOfValue(value.value));
|
|
162
253
|
}
|
|
163
254
|
case 'lookup_json_integer':
|
|
164
255
|
return lookupJsonValue('integer', args.length, argument);
|
|
@@ -181,9 +272,32 @@ function evaluateDirectFuncValue(node, ctx, invocation, firstArgumentValue) {
|
|
|
181
272
|
values.push(value.value);
|
|
182
273
|
}
|
|
183
274
|
const value = functionResult(name, values, invocation);
|
|
184
|
-
return value === undefined ? unavailable(functionSource(name)) : known(value);
|
|
275
|
+
return value === undefined ? unavailable(functionSource(name)) : known(canonicalResult(value));
|
|
185
276
|
}
|
|
186
|
-
/**
|
|
277
|
+
/**
|
|
278
|
+
* Puts each string of a result in the one form byte-strings.ts gives its
|
|
279
|
+
* bytes, which concat() and other functions that join strings can break by
|
|
280
|
+
* joining two halves of a character.
|
|
281
|
+
*/
|
|
282
|
+
function canonicalResult(value) {
|
|
283
|
+
if (typeof value === 'string')
|
|
284
|
+
return canonicalText(value);
|
|
285
|
+
if (!Array.isArray(value))
|
|
286
|
+
return value;
|
|
287
|
+
// Copies the array only when an element changes.
|
|
288
|
+
let copy;
|
|
289
|
+
for (let index = 0; index < value.length; index++) {
|
|
290
|
+
const element = canonicalResult(value[index]);
|
|
291
|
+
if (element !== value[index])
|
|
292
|
+
(copy ??= value.slice())[index] = element;
|
|
293
|
+
}
|
|
294
|
+
return copy ?? value;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Computes a function result from its argument values, or undefined for a
|
|
298
|
+
* function this evaluator does not implement. A function in
|
|
299
|
+
* NEVER_NIL_FUNCTIONS must not give nil.
|
|
300
|
+
*/
|
|
187
301
|
function functionResult(name, values, invocation) {
|
|
188
302
|
// An omitted optional argument is null, which functions treat as absent.
|
|
189
303
|
const at = (index) => values[index] ?? null;
|
|
@@ -201,14 +315,11 @@ function functionResult(name, values, invocation) {
|
|
|
201
315
|
case 'ends_with':
|
|
202
316
|
case 'starts_with':
|
|
203
317
|
return matchesAffix(name, at(0), at(1));
|
|
204
|
-
case 'has_value':
|
|
205
|
-
return evaluateHasValue(at(0), at(1));
|
|
206
318
|
case 'join':
|
|
207
319
|
return joinValues(at(0), at(1));
|
|
208
|
-
case 'len':
|
|
209
|
-
return lengthOfValue(at(0));
|
|
210
320
|
case 'lower':
|
|
211
|
-
|
|
321
|
+
// Cloudflare converts ASCII letters only.
|
|
322
|
+
return mapStringValue(at(0), value => value.replace(/[A-Z]+/g, letters => letters.toLowerCase()));
|
|
212
323
|
case 'regex_replace':
|
|
213
324
|
return regexReplace(at(0), at(1), at(2));
|
|
214
325
|
case 'remove_bytes':
|
|
@@ -220,9 +331,9 @@ function functionResult(name, values, invocation) {
|
|
|
220
331
|
case 'substring':
|
|
221
332
|
return substringValue(at(0), at(1), at(2));
|
|
222
333
|
case 'to_string':
|
|
223
|
-
return
|
|
334
|
+
return toStringValue(at(0), invocation.argumentTypes[0] ?? undefined);
|
|
224
335
|
case 'upper':
|
|
225
|
-
return mapStringValue(at(0), value => value.toUpperCase());
|
|
336
|
+
return mapStringValue(at(0), value => value.replace(/[a-z]+/g, letters => letters.toUpperCase()));
|
|
226
337
|
case 'url_decode':
|
|
227
338
|
return urlDecodeValue(at(0), at(1));
|
|
228
339
|
case 'wildcard_replace':
|
|
@@ -232,29 +343,57 @@ function functionResult(name, values, invocation) {
|
|
|
232
343
|
}
|
|
233
344
|
}
|
|
234
345
|
function evaluateFuncArray(node, ctx, invocation) {
|
|
235
|
-
const source =
|
|
346
|
+
const source = evaluateArgValue(node.args[0], ctx);
|
|
236
347
|
if (isUnknown(source))
|
|
237
348
|
return source;
|
|
238
|
-
|
|
349
|
+
const { value } = source;
|
|
350
|
+
if (value instanceof RuleMapValue)
|
|
351
|
+
return unavailable('a map value');
|
|
352
|
+
if (value === null)
|
|
239
353
|
return known([]);
|
|
240
|
-
const
|
|
354
|
+
const elements = value instanceof PartialArrayValue ? value.elements : (Array.isArray(value) ? value : [value]).map(item => known(item));
|
|
355
|
+
const more = value instanceof PartialArrayValue ? value.more : undefined;
|
|
356
|
+
let keepsPlaces = NEVER_NIL_FUNCTIONS.has(node.name);
|
|
241
357
|
const results = [];
|
|
242
|
-
for (const
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
358
|
+
for (const element of elements) {
|
|
359
|
+
if (isUnknownElement(element)) {
|
|
360
|
+
results.push(element);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
const result = ruleValue(evaluateDirectFuncValue(node, ctx, invocation, element.value));
|
|
364
|
+
if (isUnknown(result))
|
|
365
|
+
return result;
|
|
366
|
+
if (result.value !== null)
|
|
367
|
+
results.push(result);
|
|
368
|
+
// A listed function that gives nil after all may for an unknown element too.
|
|
369
|
+
else
|
|
370
|
+
keepsPlaces = false;
|
|
248
371
|
}
|
|
249
|
-
|
|
372
|
+
if (keepsPlaces)
|
|
373
|
+
return known(PartialArrayValue.from(results, more));
|
|
374
|
+
// An unknown element may give nil, which drops it, so it leaves its place and the later ones unknown.
|
|
375
|
+
const knownResults = results.filter(result => !isUnknownElement(result));
|
|
376
|
+
return known(PartialArrayValue.from(knownResults, results.find(isUnknownElement) ?? more));
|
|
250
377
|
}
|
|
378
|
+
/**
|
|
379
|
+
* Functions that can map over an array and give every value they accept a
|
|
380
|
+
* result, never nil. An unknown element, a header value or a map key's
|
|
381
|
+
* values, is never nil either, so it keeps its place.
|
|
382
|
+
*/
|
|
383
|
+
const NEVER_NIL_FUNCTIONS = new Set([
|
|
384
|
+
'encode_base64',
|
|
385
|
+
'len',
|
|
386
|
+
'lower',
|
|
387
|
+
'upper',
|
|
388
|
+
'url_decode',
|
|
389
|
+
]);
|
|
251
390
|
function evaluateArgValue(arg, ctx) {
|
|
252
391
|
// An omitted optional argument is null, which functions treat as absent.
|
|
253
392
|
if (!arg || typeof arg !== 'object' || !('kind' in arg))
|
|
254
393
|
return known(null);
|
|
255
394
|
if (arg.kind === 'Field')
|
|
256
395
|
return resolveFieldNode(arg, ctx);
|
|
257
|
-
if (arg.kind === 'Func')
|
|
396
|
+
if (arg.kind === 'Func' && !isConditionArgument(arg))
|
|
258
397
|
return evaluateFuncValue(arg, ctx);
|
|
259
398
|
if (arg.kind === 'StringLiteral' ||
|
|
260
399
|
arg.kind === 'NumberLiteral' ||
|
|
@@ -262,24 +401,63 @@ function evaluateArgValue(arg, ctx) {
|
|
|
262
401
|
arg.kind === 'BoolLiteral') {
|
|
263
402
|
return known(literalValue(arg));
|
|
264
403
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
404
|
+
if (arg.kind === 'ListRef' || arg.kind === 'SetLiteral') {
|
|
405
|
+
// Inline lists and list references are not values. They are unknown
|
|
406
|
+
// rather than nil, which functions such as coalesce() would skip.
|
|
407
|
+
ctx.warnings.add(nonValueArgumentWarning(arg));
|
|
408
|
+
return unavailable(nonValueArgumentSource(arg));
|
|
409
|
+
}
|
|
410
|
+
return outcomeValue(evaluateConditionArgument(arg, ctx));
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Evaluates a condition used as a function argument, such as the comparison
|
|
414
|
+
* in `coalesce(has_value(...), http.host eq "x")`, as the main evaluator does
|
|
415
|
+
* but without recording a match chain. Like the main evaluator, `and` and `or`
|
|
416
|
+
* stop at the operand that decides them.
|
|
417
|
+
*/
|
|
418
|
+
function evaluateConditionArgument(node, ctx) {
|
|
419
|
+
switch (node.kind) {
|
|
420
|
+
case 'BoolField':
|
|
421
|
+
return valueOutcome(resolveBoolField(node.name, ctx));
|
|
422
|
+
case 'Comparison':
|
|
423
|
+
return evaluateComparison(node, ctx).outcome;
|
|
424
|
+
case 'Func':
|
|
425
|
+
return evaluateFuncPredicate(node, ctx);
|
|
426
|
+
case 'Not':
|
|
427
|
+
return negateOutcome(evaluateConditionArgument(node.operand, ctx));
|
|
428
|
+
case 'And':
|
|
429
|
+
return andOutcome(evaluateConditionsUntil(node.operands, false, ctx));
|
|
430
|
+
case 'Or':
|
|
431
|
+
return orOutcome(evaluateConditionsUntil(node.operands, true, ctx));
|
|
432
|
+
case 'Xor':
|
|
433
|
+
return xorOutcome(node.operands.map(operand => evaluateConditionArgument(operand, ctx)));
|
|
434
|
+
// Only an expression without syntax errors is evaluated.
|
|
435
|
+
case 'Invalid':
|
|
436
|
+
return false;
|
|
437
|
+
default:
|
|
438
|
+
return unhandledNode(node);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
/** Evaluates conditions in order, up to and including the first with the deciding outcome. */
|
|
442
|
+
function evaluateConditionsUntil(conditions, deciding, ctx) {
|
|
443
|
+
const outcomes = [];
|
|
444
|
+
for (const condition of conditions) {
|
|
445
|
+
const outcome = evaluateConditionArgument(condition, ctx);
|
|
446
|
+
outcomes.push(outcome);
|
|
447
|
+
if (outcome === deciding)
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
450
|
+
return outcomes;
|
|
269
451
|
}
|
|
270
452
|
function nonValueArgumentWarning(arg) {
|
|
271
453
|
if (arg.kind === 'ListRef')
|
|
272
454
|
return `list '$${arg.name}' can only be used with the in operator`;
|
|
273
|
-
|
|
274
|
-
return 'inline lists can only be used with the in operator';
|
|
275
|
-
return `'${arg.raw}' cannot be used as a function argument value`;
|
|
455
|
+
return 'inline lists can only be used with the in operator';
|
|
276
456
|
}
|
|
277
457
|
function nonValueArgumentSource(arg) {
|
|
278
458
|
if (arg.kind === 'ListRef')
|
|
279
459
|
return `list '$${arg.name}'`;
|
|
280
|
-
|
|
281
|
-
return 'an inline list';
|
|
282
|
-
return `'${arg.raw}'`;
|
|
460
|
+
return 'an inline list';
|
|
283
461
|
}
|
|
284
462
|
/** Returns nil (null) for a nil collection or value, as Cloudflare documents. */
|
|
285
463
|
function evaluateHasValue(collection, value) {
|
|
@@ -302,7 +480,7 @@ function concatValues(values, argumentTypes) {
|
|
|
302
480
|
return null;
|
|
303
481
|
const expectedType = argumentTypes[0];
|
|
304
482
|
if (expectedType &&
|
|
305
|
-
argumentTypes.slice(1).some(type => compareRuleExpressionDataTypes(expectedType, type) === 'different'))
|
|
483
|
+
argumentTypes.slice(1).some(type => type !== null && compareRuleExpressionDataTypes(expectedType, type) === 'different'))
|
|
306
484
|
return null;
|
|
307
485
|
const presentValues = values.filter(value => value !== null);
|
|
308
486
|
const firstValue = presentValues[0];
|
|
@@ -317,44 +495,60 @@ function concatValues(values, argumentTypes) {
|
|
|
317
495
|
return null;
|
|
318
496
|
return presentValues.join('');
|
|
319
497
|
}
|
|
498
|
+
/** Cloudflare counts the bytes of a string. */
|
|
320
499
|
function lengthOfValue(value) {
|
|
321
500
|
if (value === null)
|
|
322
501
|
return null;
|
|
323
502
|
if (Array.isArray(value))
|
|
324
503
|
return value.length;
|
|
325
|
-
return String(value)
|
|
504
|
+
return byteLength(String(value));
|
|
326
505
|
}
|
|
327
506
|
function mapStringValue(value, map) {
|
|
328
507
|
if (value === null || Array.isArray(value))
|
|
329
508
|
return null;
|
|
330
509
|
return map(String(value));
|
|
331
510
|
}
|
|
511
|
+
/** Prints an IP address as Cloudflare does, with IPv6 compressed. */
|
|
512
|
+
function toStringValue(value, type) {
|
|
513
|
+
if (typeof value === 'string' && type?.kind === 'scalar' && type.name === 'IP address') {
|
|
514
|
+
const octets = ipAddressOctets(value);
|
|
515
|
+
if (octets)
|
|
516
|
+
return formatIpAddress(octets);
|
|
517
|
+
}
|
|
518
|
+
return mapStringValue(value, text => text);
|
|
519
|
+
}
|
|
332
520
|
function encodeBase64Value(value, flagsValue) {
|
|
333
521
|
if (value === null)
|
|
334
522
|
return null;
|
|
335
523
|
const flags = flagsValue === null ? '' : String(flagsValue);
|
|
336
|
-
let encoded = bytesToBase64(
|
|
524
|
+
let encoded = bytesToBase64(textToBytes(String(value)));
|
|
337
525
|
if (flags.includes('u'))
|
|
338
526
|
encoded = encoded.replaceAll('+', '-').replaceAll('/', '_');
|
|
339
527
|
if (!flags.includes('p'))
|
|
340
528
|
encoded = encoded.replace(/=+$/, '');
|
|
341
529
|
return encoded;
|
|
342
530
|
}
|
|
531
|
+
/**
|
|
532
|
+
* Decodes standard Base64 as Cloudflare does, observed with live requests: it
|
|
533
|
+
* skips whitespace and takes input with or without padding. Other input is
|
|
534
|
+
* nil, including the URL-safe alphabet, partial padding, and nonzero bits after
|
|
535
|
+
* the last byte, which atob() would ignore.
|
|
536
|
+
*/
|
|
343
537
|
function decodeBase64Value(value) {
|
|
344
538
|
if (value === null)
|
|
345
539
|
return null;
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
if (padding)
|
|
349
|
-
input += '='.repeat(4 - padding);
|
|
540
|
+
const input = String(value);
|
|
541
|
+
let binary;
|
|
350
542
|
try {
|
|
351
|
-
|
|
352
|
-
const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
|
|
353
|
-
return new TextDecoder().decode(bytes);
|
|
543
|
+
binary = globalThis.atob(input);
|
|
354
544
|
}
|
|
355
545
|
catch {
|
|
356
546
|
return null;
|
|
357
547
|
}
|
|
548
|
+
const canonical = globalThis.btoa(binary).replace(/=+$/, '');
|
|
549
|
+
if (canonical !== input.replace(/[\t\n\f\r ]/g, '').replace(/=+$/, ''))
|
|
550
|
+
return null;
|
|
551
|
+
return bytesToText(Uint8Array.from(binary, char => char.charCodeAt(0)));
|
|
358
552
|
}
|
|
359
553
|
function bytesToBase64(bytes) {
|
|
360
554
|
let binary = '';
|
|
@@ -367,9 +561,67 @@ function joinValues(items, separator) {
|
|
|
367
561
|
return null;
|
|
368
562
|
return items.map(item => String(item)).join(String(separator));
|
|
369
563
|
}
|
|
564
|
+
/**
|
|
565
|
+
* Cloudflare accepts one seed, and a nil seed gives nil. The bounds are integer
|
|
566
|
+
* literals, read exactly since they may be beyond 2^53.
|
|
567
|
+
*/
|
|
568
|
+
function hashInRangeValue(ctx, args, seedType, argument) {
|
|
569
|
+
const seed = argument(2);
|
|
570
|
+
if (isUnknown(seed) || seed.value === null)
|
|
571
|
+
return seed;
|
|
572
|
+
const min = integerLiteralArgument(args[0]);
|
|
573
|
+
const max = integerLiteralArgument(args[1]);
|
|
574
|
+
if (min === undefined || max === undefined) {
|
|
575
|
+
return unreliableFunction(ctx, 'hash_in_range', 'its bounds are not integer literals');
|
|
576
|
+
}
|
|
577
|
+
const hashSeed = hashInRangeSeed(seed.value, seedType ?? { kind: 'unknown' });
|
|
578
|
+
return typeof hashSeed === 'string'
|
|
579
|
+
? unreliableFunction(ctx, 'hash_in_range', hashSeed)
|
|
580
|
+
: known(hashInRange(min, max, hashSeed));
|
|
581
|
+
}
|
|
582
|
+
function integerLiteralArgument(arg) {
|
|
583
|
+
return arg?.kind === 'NumberLiteral' ? arg.integer : undefined;
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Encodes a seed by its declared type, as Cloudflare does, or explains why
|
|
587
|
+
* this evaluator cannot. A string is hashed as the bytes it holds, which are
|
|
588
|
+
* Cloudflare's bytes unless a request value had bytes that are not UTF-8.
|
|
589
|
+
*/
|
|
590
|
+
function hashInRangeSeed(value, type) {
|
|
591
|
+
switch (type.kind === 'scalar' ? type.name : undefined) {
|
|
592
|
+
case 'Integer':
|
|
593
|
+
case 'Number':
|
|
594
|
+
if (typeof value !== 'number')
|
|
595
|
+
break;
|
|
596
|
+
// Every Integer source gives an integer, as fields are checked when
|
|
597
|
+
// read. One beyond 2^53 may already be rounded, and a rounded seed
|
|
598
|
+
// hashes into another bucket.
|
|
599
|
+
if (!Number.isSafeInteger(value))
|
|
600
|
+
return `integer seed ${value} is beyond 2^53, where this evaluator may have rounded it`;
|
|
601
|
+
return { kind: 'integer', value: BigInt(value) };
|
|
602
|
+
case 'String':
|
|
603
|
+
case 'Bytes':
|
|
604
|
+
if (typeof value === 'string')
|
|
605
|
+
return { kind: 'bytes', value: textToBytes(value) };
|
|
606
|
+
break;
|
|
607
|
+
case 'IP address': {
|
|
608
|
+
if (typeof value !== 'string')
|
|
609
|
+
break;
|
|
610
|
+
const octets = ipAddressOctets(value);
|
|
611
|
+
return octets ? { kind: 'ip', value: octets } : `seed ${JSON.stringify(value)} is not an IP address`;
|
|
612
|
+
}
|
|
613
|
+
default:
|
|
614
|
+
return `its seed has type ${formatRuleExpressionDataType(type)}, not Integer, Bytes or IP address`;
|
|
615
|
+
}
|
|
616
|
+
return `seed ${JSON.stringify(value)} is not of type ${formatRuleExpressionDataType(type)}`;
|
|
617
|
+
}
|
|
370
618
|
/**
|
|
371
619
|
* Reads keys only while the JSON value can still be traversed, so a missing
|
|
372
|
-
* source or path is nil whatever the remaining keys are.
|
|
620
|
+
* source or path is nil whatever the remaining keys are. Live requests showed
|
|
621
|
+
* that Cloudflare reads JSON lazily: bytes that are not UTF-8 make an object
|
|
622
|
+
* nil when they are in one of its keys, and a string nil when they are in it,
|
|
623
|
+
* but not when they are in a value the path skips. JSON.parse() reads them,
|
|
624
|
+
* and `\uDCFF` escapes, as lone surrogates.
|
|
373
625
|
*/
|
|
374
626
|
function lookupJsonValue(kind, argumentCount, argument) {
|
|
375
627
|
const source = argument(0);
|
|
@@ -385,6 +637,8 @@ function lookupJsonValue(kind, argumentCount, argument) {
|
|
|
385
637
|
for (let index = 1; index < argumentCount; index++) {
|
|
386
638
|
if (!current || typeof current !== 'object')
|
|
387
639
|
return known(null);
|
|
640
|
+
if (!Array.isArray(current) && Object.keys(current).some(name => !name.isWellFormed()))
|
|
641
|
+
return known(null);
|
|
388
642
|
const key = argument(index);
|
|
389
643
|
if (isUnknown(key) || key.value === null)
|
|
390
644
|
return key;
|
|
@@ -392,7 +646,7 @@ function lookupJsonValue(kind, argumentCount, argument) {
|
|
|
392
646
|
}
|
|
393
647
|
if (kind === 'integer')
|
|
394
648
|
return known(typeof current === 'number' && Number.isInteger(current) ? current : null);
|
|
395
|
-
return known(typeof current === 'string' ? current : null);
|
|
649
|
+
return known(typeof current === 'string' && current.isWellFormed() ? current : null);
|
|
396
650
|
}
|
|
397
651
|
/**
|
|
398
652
|
* An array element by integer index, or an object member by key. Other
|
|
@@ -420,10 +674,12 @@ function regexReplace(sourceValue, patternValue, replacementValue) {
|
|
|
420
674
|
return String(sourceValue);
|
|
421
675
|
}
|
|
422
676
|
}
|
|
677
|
+
/** Removes each listed byte wherever it appears, as Cloudflare does, so a result can split a character. */
|
|
423
678
|
function removeBytes(sourceValue, removeValue) {
|
|
424
679
|
if (sourceValue === null || removeValue === null)
|
|
425
680
|
return null;
|
|
426
|
-
|
|
681
|
+
const removed = new Set(textToBytes(String(removeValue)));
|
|
682
|
+
return bytesToText(textToBytes(String(sourceValue)).filter(byte => !removed.has(byte)));
|
|
427
683
|
}
|
|
428
684
|
function removeQueryArgs(sourceValue, argValues) {
|
|
429
685
|
if (sourceValue === null)
|
|
@@ -448,46 +704,29 @@ function splitValue(sourceValue, separatorValue, limitValue) {
|
|
|
448
704
|
return parts;
|
|
449
705
|
return [...parts.slice(0, limit - 1), parts.slice(limit - 1).join(separator)];
|
|
450
706
|
}
|
|
707
|
+
/** Cloudflare indexes bytes, so a result can split a character. */
|
|
451
708
|
function substringValue(sourceValue, startValue, endValue) {
|
|
452
709
|
if (sourceValue === null || startValue === null)
|
|
453
710
|
return null;
|
|
454
|
-
const
|
|
455
|
-
const start =
|
|
456
|
-
const end = endValue === null ?
|
|
457
|
-
return
|
|
711
|
+
const bytes = textToBytes(String(sourceValue));
|
|
712
|
+
const start = normalizeByteIndex(bytes.length, Number(startValue));
|
|
713
|
+
const end = endValue === null ? bytes.length : normalizeByteIndex(bytes.length, Number(endValue));
|
|
714
|
+
return bytesToText(bytes.subarray(start, end));
|
|
458
715
|
}
|
|
459
|
-
function
|
|
716
|
+
function normalizeByteIndex(length, index) {
|
|
460
717
|
if (!Number.isFinite(index))
|
|
461
718
|
return 0;
|
|
462
719
|
if (index < 0)
|
|
463
|
-
return Math.max(
|
|
464
|
-
return Math.min(index,
|
|
720
|
+
return Math.max(length + index, 0);
|
|
721
|
+
return Math.min(index, length);
|
|
465
722
|
}
|
|
466
723
|
function urlDecodeValue(sourceValue, optionsValue) {
|
|
467
724
|
if (sourceValue === null)
|
|
468
725
|
return null;
|
|
469
|
-
const
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
: value;
|
|
474
|
-
try {
|
|
475
|
-
return decodeURIComponent(withUnicode.replaceAll('+', ' '));
|
|
476
|
-
}
|
|
477
|
-
catch {
|
|
478
|
-
return withUnicode;
|
|
479
|
-
}
|
|
480
|
-
};
|
|
481
|
-
let decoded = decodeOnce(String(sourceValue));
|
|
482
|
-
if (options.includes('r')) {
|
|
483
|
-
for (let iteration = 0; iteration < 8; iteration++) {
|
|
484
|
-
const next = decodeOnce(decoded);
|
|
485
|
-
if (next === decoded)
|
|
486
|
-
break;
|
|
487
|
-
decoded = next;
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
return decoded;
|
|
726
|
+
const source = String(sourceValue);
|
|
727
|
+
if (!/[%+]/.test(source))
|
|
728
|
+
return source;
|
|
729
|
+
return bytesToText(urlDecode(textToBytes(source), optionsValue === null ? '' : String(optionsValue)));
|
|
491
730
|
}
|
|
492
731
|
function wildcardReplaceValue(sourceValue, patternValue, replacementValue, flagsValue) {
|
|
493
732
|
if (sourceValue === null || patternValue === null || replacementValue === null)
|
|
@@ -495,7 +734,7 @@ function wildcardReplaceValue(sourceValue, patternValue, replacementValue, flags
|
|
|
495
734
|
return wildcardReplace(String(sourceValue), String(patternValue), String(replacementValue), flagsValue === null ? '' : String(flagsValue));
|
|
496
735
|
}
|
|
497
736
|
function wildcardReplace(source, pattern, replacement, flags) {
|
|
498
|
-
const regex =
|
|
737
|
+
const regex = wildcardToRegex(pattern, flags.includes('s'));
|
|
499
738
|
if (!regex)
|
|
500
739
|
return source;
|
|
501
740
|
const match = regex.exec(source);
|
|
@@ -503,36 +742,6 @@ function wildcardReplace(source, pattern, replacement, flags) {
|
|
|
503
742
|
return source;
|
|
504
743
|
return replaceRuleCaptureReferences(replacement, match.slice(1));
|
|
505
744
|
}
|
|
506
|
-
function wildcardPatternToRegex(pattern, caseSensitive) {
|
|
507
|
-
let source = '^';
|
|
508
|
-
let previousWildcard = false;
|
|
509
|
-
for (let index = 0; index < pattern.length; index++) {
|
|
510
|
-
const char = pattern[index];
|
|
511
|
-
if (char === '\\') {
|
|
512
|
-
const next = pattern[index + 1];
|
|
513
|
-
if (next === '*' || next === '\\') {
|
|
514
|
-
source += escapeRegexChar(next);
|
|
515
|
-
index++;
|
|
516
|
-
}
|
|
517
|
-
else {
|
|
518
|
-
source += escapeRegexChar(char);
|
|
519
|
-
}
|
|
520
|
-
previousWildcard = false;
|
|
521
|
-
continue;
|
|
522
|
-
}
|
|
523
|
-
if (char === '*') {
|
|
524
|
-
if (previousWildcard)
|
|
525
|
-
return null;
|
|
526
|
-
source += '([\\s\\S]*?)';
|
|
527
|
-
previousWildcard = true;
|
|
528
|
-
continue;
|
|
529
|
-
}
|
|
530
|
-
source += escapeRegexChar(char);
|
|
531
|
-
previousWildcard = false;
|
|
532
|
-
}
|
|
533
|
-
source += '$';
|
|
534
|
-
return new RegExp(source, caseSensitive ? '' : 'i');
|
|
535
|
-
}
|
|
536
745
|
function replaceRuleCaptureReferences(replacement, captures) {
|
|
537
746
|
return replacement.replace(/\$\$|\$\{([1-8])\}/g, (full, index) => {
|
|
538
747
|
if (full === '$$')
|
|
@@ -540,74 +749,28 @@ function replaceRuleCaptureReferences(replacement, captures) {
|
|
|
540
749
|
return captures[Number.parseInt(index ?? '0', 10) - 1]?.toString() ?? '';
|
|
541
750
|
});
|
|
542
751
|
}
|
|
543
|
-
|
|
544
|
-
return /[\\^$.*+?()[\]{}|]/.test(char) ? `\\${char}` : char;
|
|
545
|
-
}
|
|
752
|
+
/** Returns the network address, printed as Cloudflare prints IP addresses. */
|
|
546
753
|
function evaluateCidr(addressValue, ipv4BitsValue, ipv6BitsValue) {
|
|
547
754
|
if (addressValue === null)
|
|
548
755
|
return null;
|
|
549
756
|
const address = String(addressValue);
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
return truncateIpv4(address, Number(ipv4BitsValue));
|
|
553
|
-
}
|
|
554
|
-
function truncateIpv4(address, bits) {
|
|
555
|
-
const value = ipv4ToUint32(address);
|
|
556
|
-
if (value === null || !Number.isInteger(bits) || bits < 1 || bits > 32)
|
|
757
|
+
const octets = ipAddressOctets(address);
|
|
758
|
+
if (!octets)
|
|
557
759
|
return address;
|
|
558
|
-
const
|
|
559
|
-
|
|
560
|
-
return [
|
|
561
|
-
(truncated >>> 24) & 255,
|
|
562
|
-
(truncated >>> 16) & 255,
|
|
563
|
-
(truncated >>> 8) & 255,
|
|
564
|
-
truncated & 255,
|
|
565
|
-
].join('.');
|
|
566
|
-
}
|
|
567
|
-
function ipv4ToUint32(address) {
|
|
568
|
-
const parts = address.split('.').map(part => Number.parseInt(part, 10));
|
|
569
|
-
if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255))
|
|
570
|
-
return null;
|
|
571
|
-
return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
|
|
572
|
-
}
|
|
573
|
-
function truncateIpv6(address, bits) {
|
|
574
|
-
if (!Number.isInteger(bits) || bits < 1 || bits > 128)
|
|
760
|
+
const bits = Number(octets.length === 4 ? ipv4BitsValue : ipv6BitsValue);
|
|
761
|
+
if (!Number.isInteger(bits) || bits < 1 || bits > octets.length * 8)
|
|
575
762
|
return address;
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
let remaining = bits;
|
|
581
|
-
const truncated = groups.map((group) => {
|
|
582
|
-
if (remaining >= 16) {
|
|
583
|
-
remaining -= 16;
|
|
584
|
-
return group;
|
|
585
|
-
}
|
|
586
|
-
if (remaining <= 0)
|
|
587
|
-
return 0;
|
|
588
|
-
const mask = (0xffff << (16 - remaining)) & 0xffff;
|
|
589
|
-
remaining = 0;
|
|
590
|
-
return group & mask;
|
|
591
|
-
});
|
|
592
|
-
return truncated.map(group => group.toString(16).padStart(4, '0')).join(':');
|
|
593
|
-
}
|
|
594
|
-
function expandIpv6(address) {
|
|
595
|
-
const [headText, tailText] = address.split('::');
|
|
596
|
-
const head = headText ? headText.split(':') : [];
|
|
597
|
-
const tail = tailText ? tailText.split(':') : [];
|
|
598
|
-
if (address.includes('::')) {
|
|
599
|
-
const missing = 8 - head.length - tail.length;
|
|
600
|
-
if (missing < 0)
|
|
601
|
-
return null;
|
|
602
|
-
return [...head, ...Array.from({ length: missing }, () => '0'), ...tail].map(group => group || '0');
|
|
763
|
+
for (let index = 0; index < octets.length; index++) {
|
|
764
|
+
// Keeps the octet's first `kept` bits.
|
|
765
|
+
const kept = Math.min(Math.max(bits - index * 8, 0), 8);
|
|
766
|
+
octets[index] &= 0xff00 >> kept;
|
|
603
767
|
}
|
|
604
|
-
return
|
|
768
|
+
return formatIpAddress(octets);
|
|
605
769
|
}
|
|
606
770
|
/** A function result this evaluator cannot reproduce is unknown. */
|
|
607
|
-
function unreliableFunction(ctx, name) {
|
|
608
|
-
const reason = getUnreliableRuleExpressionFunctionReason(name);
|
|
771
|
+
function unreliableFunction(ctx, name, reason = getUnreliableRuleExpressionFunctionReason(name)) {
|
|
609
772
|
if (reason)
|
|
610
|
-
|
|
773
|
+
ctx.warnings.add(`function '${name}' cannot be evaluated reliably: ${reason}`);
|
|
611
774
|
return unavailable(functionSource(name));
|
|
612
775
|
}
|
|
613
776
|
function functionSource(name) {
|