@libreflare/worker-runtime 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +342 -22
- package/dist/rule-evaluator/accept-encoding.d.ts +3 -2
- package/dist/rule-evaluator/accept-encoding.d.ts.map +1 -1
- package/dist/rule-evaluator/accept-encoding.js +80 -35
- package/dist/rule-evaluator/accept-encoding.js.map +1 -1
- package/dist/rule-evaluator/access-values.d.ts +84 -1
- package/dist/rule-evaluator/access-values.d.ts.map +1 -1
- package/dist/rule-evaluator/access-values.js +165 -13
- package/dist/rule-evaluator/access-values.js.map +1 -1
- package/dist/rule-evaluator/analysis.d.ts +44 -13
- package/dist/rule-evaluator/analysis.d.ts.map +1 -1
- package/dist/rule-evaluator/analysis.js +82 -65
- package/dist/rule-evaluator/analysis.js.map +1 -1
- package/dist/rule-evaluator/ast.d.ts +165 -11
- package/dist/rule-evaluator/ast.d.ts.map +1 -1
- package/dist/rule-evaluator/ast.js +106 -3
- 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 +7 -3
- package/dist/rule-evaluator/constants.d.ts.map +1 -1
- package/dist/rule-evaluator/constants.js +8 -1
- 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 +15 -0
- package/dist/rule-evaluator/custom-lists.d.ts.map +1 -1
- package/dist/rule-evaluator/custom-lists.js +64 -1
- package/dist/rule-evaluator/custom-lists.js.map +1 -1
- package/dist/rule-evaluator/diagnostics.d.ts +10 -9
- package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
- package/dist/rule-evaluator/diagnostics.js +32 -52
- 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 +10 -3
- package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
- package/dist/rule-evaluator/evaluator.js +91 -83
- package/dist/rule-evaluator/evaluator.js.map +1 -1
- package/dist/rule-evaluator/explain.d.ts +11 -2
- package/dist/rule-evaluator/explain.d.ts.map +1 -1
- package/dist/rule-evaluator/explain.js +234 -123
- 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 +114 -1
- package/dist/rule-evaluator/field-descriptions.generated.d.ts.map +1 -1
- package/dist/rule-evaluator/field-descriptions.generated.js +261 -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 +37 -4
- package/dist/rule-evaluator/fields.d.ts.map +1 -1
- package/dist/rule-evaluator/fields.js +387 -87
- 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 +63 -7
- package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
- package/dist/rule-evaluator/function-descriptions.generated.js +122 -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 +27 -3
- package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
- package/dist/rule-evaluator/function-signature-validation.js +351 -170
- package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
- package/dist/rule-evaluator/functions.d.ts +38 -6
- package/dist/rule-evaluator/functions.d.ts.map +1 -1
- package/dist/rule-evaluator/functions.js +549 -279
- 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 +2 -6
- package/dist/rule-evaluator/minifier.d.ts.map +1 -1
- package/dist/rule-evaluator/minifier.js +24 -28
- package/dist/rule-evaluator/minifier.js.map +1 -1
- package/dist/rule-evaluator/normalizer.d.ts +2 -6
- package/dist/rule-evaluator/normalizer.d.ts.map +1 -1
- package/dist/rule-evaluator/normalizer.js +13 -13
- package/dist/rule-evaluator/normalizer.js.map +1 -1
- package/dist/rule-evaluator/operators.d.ts +30 -4
- package/dist/rule-evaluator/operators.d.ts.map +1 -1
- package/dist/rule-evaluator/operators.js +217 -132
- package/dist/rule-evaluator/operators.js.map +1 -1
- package/dist/rule-evaluator/outcome.d.ts +65 -0
- package/dist/rule-evaluator/outcome.d.ts.map +1 -0
- package/dist/rule-evaluator/outcome.js +82 -0
- package/dist/rule-evaluator/outcome.js.map +1 -0
- 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 +325 -12
- package/dist/rule-evaluator/parser.d.ts.map +1 -1
- package/dist/rule-evaluator/parser.js +1351 -340
- package/dist/rule-evaluator/parser.js.map +1 -1
- package/dist/rule-evaluator/quantifier.d.ts +2 -2
- 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 +84 -23
- package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
- package/dist/rule-evaluator/rule-language-types.js +266 -76
- 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 +49 -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 +8 -9
- package/dist/rule-evaluator/validation.d.ts.map +1 -1
- package/dist/rule-evaluator/validation.js +544 -253
- package/dist/rule-evaluator/validation.js.map +1 -1
- package/dist/rule-evaluator.d.ts +5 -5
- package/dist/rule-evaluator.d.ts.map +1 -1
- package/dist/rule-evaluator.js +1 -1
- package/dist/rule-evaluator.js.map +1 -1
- package/package.json +6 -3
- 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/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,9 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
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';
|
|
5
9
|
import { extractQuantifierPredicate } from './quantifier.js';
|
|
6
|
-
import {
|
|
10
|
+
import { urlDecode } from './url-decode.js';
|
|
11
|
+
import { collectionElementDataType, compareRuleExpressionDataTypes, formatRuleExpressionDataType, evaluatedValueType, inferFunctionInvocation, } from './rule-language-types.js';
|
|
7
12
|
const UNRELIABLE_FUNCTION_REASONS = {
|
|
8
13
|
bit_slice: 'packet bit slicing is not available in Worker request context',
|
|
9
14
|
is_jwt_present: 'Cloudflare API JWT token configurations are not available in Worker request context',
|
|
@@ -15,15 +20,90 @@ const UNRELIABLE_FUNCTION_REASONS = {
|
|
|
15
20
|
export function getUnreliableRuleExpressionFunctionReason(name) {
|
|
16
21
|
return UNRELIABLE_FUNCTION_REASONS[name];
|
|
17
22
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
return
|
|
23
|
+
/**
|
|
24
|
+
* Evaluates a field or function comparison operand. A null value is a
|
|
25
|
+
* Cloudflare missing value.
|
|
26
|
+
*/
|
|
27
|
+
export function evaluateOperand(node, ctx) {
|
|
28
|
+
return ruleValue(evaluateRuntimeOperand(node, ctx));
|
|
29
|
+
}
|
|
30
|
+
function evaluateRuntimeOperand(node, ctx) {
|
|
31
|
+
return node.kind === 'Func' ? evaluateFuncValue(node, ctx) : resolveFieldNode(node, ctx);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Narrows a value to a rule-language value. Only coalesce(), has_key(), and
|
|
35
|
+
* postfix access read maps, and validation rejects maps anywhere else, so a
|
|
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.
|
|
38
|
+
*/
|
|
39
|
+
function ruleValue(evaluated) {
|
|
40
|
+
if (isUnknown(evaluated))
|
|
41
|
+
return evaluated;
|
|
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 };
|
|
84
|
+
}
|
|
85
|
+
/** Evaluates the values an any()/all() collection yields, which can be partly known. */
|
|
86
|
+
export function evaluateCollection(fieldArg, ctx) {
|
|
87
|
+
const evaluated = evaluateRuntimeOperand(fieldArg, ctx);
|
|
88
|
+
if (isUnknown(evaluated))
|
|
89
|
+
return evaluated;
|
|
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
|
+
}
|
|
97
|
+
if (Array.isArray(value))
|
|
98
|
+
return known({ values: collectionValues(value) });
|
|
99
|
+
if (value === null)
|
|
100
|
+
return known({ values: [] });
|
|
101
|
+
if (typeof value === 'number')
|
|
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');
|
|
27
107
|
}
|
|
28
108
|
export function findMatchedSetMemberForFunc(node, ctx) {
|
|
29
109
|
if (node.name !== 'any' && node.name !== 'all')
|
|
@@ -33,170 +113,353 @@ export function findMatchedSetMemberForFunc(node, ctx) {
|
|
|
33
113
|
return null;
|
|
34
114
|
if (quantifier.op !== 'in' || quantifier.value.kind !== 'SetLiteral')
|
|
35
115
|
return null;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
116
|
+
const collection = evaluateCollection(quantifier.source, ctx);
|
|
117
|
+
if (isUnknown(collection))
|
|
118
|
+
return null;
|
|
119
|
+
for (const v of collection.value.values) {
|
|
120
|
+
const member = findMatchingSetMember(v, quantifier.value);
|
|
121
|
+
if (member !== null)
|
|
122
|
+
return member;
|
|
40
123
|
}
|
|
41
124
|
return null;
|
|
42
125
|
}
|
|
43
126
|
/**
|
|
44
|
-
* Evaluates a function node as a
|
|
127
|
+
* Evaluates a function node as a condition. A condition computed from a value
|
|
128
|
+
* this evaluator cannot resolve is unknown.
|
|
45
129
|
*/
|
|
46
|
-
export function
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
if (name === 'any') {
|
|
58
|
-
const results = arr.map(check);
|
|
59
|
-
if (results.some(result => result === true))
|
|
60
|
-
return true;
|
|
61
|
-
if (results.some(result => result === null))
|
|
62
|
-
return null;
|
|
63
|
-
return false;
|
|
64
|
-
}
|
|
65
|
-
if (name === 'all') {
|
|
66
|
-
const results = arr.map(check);
|
|
67
|
-
if (results.some(result => result === false))
|
|
68
|
-
return false;
|
|
69
|
-
if (results.some(result => result === null))
|
|
70
|
-
return null;
|
|
71
|
-
return true;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
if (name === 'starts_with' || name === 'ends_with') {
|
|
75
|
-
const val = evaluateArgValue(args[0], ctx);
|
|
76
|
-
const needle = evaluateArgValue(args[1], ctx);
|
|
77
|
-
if (val === null || needle === null)
|
|
78
|
-
return false;
|
|
79
|
-
return name === 'starts_with'
|
|
80
|
-
? String(val).startsWith(String(needle))
|
|
81
|
-
: String(val).endsWith(String(needle));
|
|
82
|
-
}
|
|
83
|
-
if (name === 'has_key') {
|
|
84
|
-
return evaluateHasKey(args[0], evaluateArgValue(args[1], ctx), ctx);
|
|
85
|
-
}
|
|
86
|
-
if (name === 'has_value') {
|
|
87
|
-
return evaluateHasValue(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx));
|
|
88
|
-
}
|
|
89
|
-
if (name === 'is_jwt_present' || name === 'is_jwt_valid' || name === 'is_timed_hmac_valid_v0') {
|
|
90
|
-
warnUnreliableFunction(ctx, name);
|
|
130
|
+
export function evaluateFuncPredicate(node, ctx) {
|
|
131
|
+
if (node.name === 'any' || node.name === 'all')
|
|
132
|
+
return evaluateQuantifier(node, ctx);
|
|
133
|
+
// Other functions match when they return true. A nil result, such as
|
|
134
|
+
// has_key() with a nil key, does not match.
|
|
135
|
+
const evaluated = evaluateFuncValue(node, ctx);
|
|
136
|
+
return isUnknown(evaluated) ? evaluated : evaluated.value === true;
|
|
137
|
+
}
|
|
138
|
+
function evaluateQuantifier(node, ctx) {
|
|
139
|
+
const quantifier = extractQuantifierPredicate(node);
|
|
140
|
+
if (!quantifier)
|
|
91
141
|
return false;
|
|
92
|
-
|
|
93
|
-
|
|
142
|
+
const collection = evaluateCollection(quantifier.source, ctx);
|
|
143
|
+
if (isUnknown(collection))
|
|
144
|
+
return collection;
|
|
145
|
+
const compare = comparatorFor(node, quantifier, ctx);
|
|
146
|
+
const outcomes = collection.value.values.map((value) => {
|
|
147
|
+
const outcome = compare(value);
|
|
148
|
+
return quantifier.negated ? negateOutcome(outcome) : outcome;
|
|
149
|
+
});
|
|
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()]);
|
|
94
157
|
}
|
|
95
|
-
|
|
158
|
+
/**
|
|
159
|
+
* Returns a comparison of collection values against the quantifier's
|
|
160
|
+
* right-hand value. A dynamic value is resolved once, when the first value is
|
|
161
|
+
* compared, so an empty collection settles any()/all() without reading it. An
|
|
162
|
+
* unknown value, or values Cloudflare would not compare, make the comparison
|
|
163
|
+
* unknown.
|
|
164
|
+
*/
|
|
165
|
+
function comparatorFor(node, quantifier, ctx) {
|
|
166
|
+
const { op, value: right } = quantifier;
|
|
167
|
+
if (right.kind === 'ListRef' || right.kind === 'SetLiteral')
|
|
168
|
+
return left => applyOp(op, left, right, ctx.customLists);
|
|
169
|
+
const elementType = collectionElementDataType(evaluatedValueType(quantifier.source))
|
|
170
|
+
?? { kind: 'unknown' };
|
|
171
|
+
const rightType = evaluatedValueType(right);
|
|
172
|
+
let operand;
|
|
173
|
+
return (left) => {
|
|
174
|
+
operand ??= isDynamicValueNode(right) ? evaluateOperand(right, ctx) : known(literalValue(right));
|
|
175
|
+
if (isUnknown(operand))
|
|
176
|
+
return operand;
|
|
177
|
+
const outcome = compareOperands(op, { value: left, type: elementType }, { value: operand.value, type: rightType }, ctx.warnings);
|
|
178
|
+
if (isUnknown(outcome) && outcome.cause.kind === 'incomparable') {
|
|
179
|
+
ctx.warnings.add(`comparison in '${node.raw}' cannot be evaluated: ${outcome.cause.reason}`);
|
|
180
|
+
}
|
|
181
|
+
return outcome;
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Evaluates a function call as a value and applies its postfix access, as for
|
|
186
|
+
* fields. The result may be a map, such as coalesce() over map fields.
|
|
187
|
+
*/
|
|
96
188
|
export function evaluateFuncValue(node, ctx) {
|
|
97
189
|
const invocation = inferFunctionInvocation(node);
|
|
98
|
-
const
|
|
190
|
+
const evaluated = invocation.mapping === 'mapped'
|
|
99
191
|
? evaluateFuncArray(node, ctx, invocation)
|
|
100
192
|
: evaluateDirectFuncValue(node, ctx, invocation);
|
|
101
|
-
|
|
193
|
+
if (isUnknown(evaluated))
|
|
194
|
+
return evaluated;
|
|
195
|
+
return applyRuntimeAccessPath(evaluated.value, node.accessPath);
|
|
102
196
|
}
|
|
103
197
|
function evaluateDirectFuncValue(node, ctx, invocation, firstArgumentValue) {
|
|
104
198
|
const { name, args } = node;
|
|
105
|
-
const
|
|
106
|
-
? firstArgumentValue
|
|
199
|
+
const runtimeArgument = (index) => index === 0 && firstArgumentValue !== undefined
|
|
200
|
+
? known(firstArgumentValue)
|
|
107
201
|
: evaluateArgValue(args[index], ctx);
|
|
202
|
+
const argument = (index) => ruleValue(runtimeArgument(index));
|
|
108
203
|
switch (name) {
|
|
204
|
+
case 'all':
|
|
205
|
+
case 'any':
|
|
206
|
+
return outcomeValue(evaluateQuantifier(node, ctx));
|
|
207
|
+
case 'coalesce':
|
|
208
|
+
// Arguments after the first present value are never read.
|
|
209
|
+
for (let index = 0; index < args.length; index++) {
|
|
210
|
+
const value = runtimeArgument(index);
|
|
211
|
+
if (isUnknown(value) || value.value !== null)
|
|
212
|
+
return value;
|
|
213
|
+
}
|
|
214
|
+
return known(null);
|
|
215
|
+
case 'has_key': {
|
|
216
|
+
// A nil key gives nil without reading the map, as Cloudflare documents.
|
|
217
|
+
const key = argument(1);
|
|
218
|
+
if (isUnknown(key) || key.value === null)
|
|
219
|
+
return key;
|
|
220
|
+
const map = runtimeArgument(0);
|
|
221
|
+
if (isUnknown(map))
|
|
222
|
+
return map;
|
|
223
|
+
if (!(map.value instanceof RuleMapValue))
|
|
224
|
+
return unavailable('a map value');
|
|
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));
|
|
253
|
+
}
|
|
254
|
+
case 'lookup_json_integer':
|
|
255
|
+
return lookupJsonValue('integer', args.length, argument);
|
|
256
|
+
case 'lookup_json_string':
|
|
257
|
+
return lookupJsonValue('string', args.length, argument);
|
|
109
258
|
case 'bit_slice':
|
|
110
|
-
|
|
111
|
-
|
|
259
|
+
case 'is_jwt_present':
|
|
260
|
+
case 'is_jwt_valid':
|
|
261
|
+
case 'is_timed_hmac_valid_v0':
|
|
262
|
+
case 'sha256':
|
|
263
|
+
case 'uuidv4':
|
|
264
|
+
return unreliableFunction(ctx, name);
|
|
265
|
+
}
|
|
266
|
+
// Other functions read every argument, so an unknown argument makes the result unknown.
|
|
267
|
+
const values = [];
|
|
268
|
+
for (let index = 0; index < args.length; index++) {
|
|
269
|
+
const value = argument(index);
|
|
270
|
+
if (isUnknown(value))
|
|
271
|
+
return value;
|
|
272
|
+
values.push(value.value);
|
|
273
|
+
}
|
|
274
|
+
const value = functionResult(name, values, invocation);
|
|
275
|
+
return value === undefined ? unavailable(functionSource(name)) : known(canonicalResult(value));
|
|
276
|
+
}
|
|
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
|
+
*/
|
|
301
|
+
function functionResult(name, values, invocation) {
|
|
302
|
+
// An omitted optional argument is null, which functions treat as absent.
|
|
303
|
+
const at = (index) => values[index] ?? null;
|
|
304
|
+
switch (name) {
|
|
112
305
|
case 'cidr':
|
|
113
|
-
return evaluateCidr(
|
|
306
|
+
return evaluateCidr(at(0), at(1), at(2));
|
|
114
307
|
case 'cidr6':
|
|
115
|
-
return evaluateCidr(
|
|
308
|
+
return evaluateCidr(at(0), 32, at(1));
|
|
116
309
|
case 'concat':
|
|
117
|
-
return concatValues(
|
|
310
|
+
return concatValues(values, invocation.argumentTypes);
|
|
118
311
|
case 'decode_base64':
|
|
119
|
-
return decodeBase64Value(
|
|
312
|
+
return decodeBase64Value(at(0));
|
|
120
313
|
case 'encode_base64':
|
|
121
|
-
return encodeBase64Value(
|
|
314
|
+
return encodeBase64Value(at(0), at(1));
|
|
315
|
+
case 'ends_with':
|
|
316
|
+
case 'starts_with':
|
|
317
|
+
return matchesAffix(name, at(0), at(1));
|
|
122
318
|
case 'join':
|
|
123
|
-
return joinValues(
|
|
124
|
-
case 'len':
|
|
125
|
-
return lengthOfValue(argValue(0));
|
|
126
|
-
case 'lookup_json_integer':
|
|
127
|
-
return lookupJsonValue(args, ctx, 'integer');
|
|
128
|
-
case 'lookup_json_string':
|
|
129
|
-
return lookupJsonValue(args, ctx, 'string');
|
|
319
|
+
return joinValues(at(0), at(1));
|
|
130
320
|
case 'lower':
|
|
131
|
-
|
|
321
|
+
// Cloudflare converts ASCII letters only.
|
|
322
|
+
return mapStringValue(at(0), value => value.replace(/[A-Z]+/g, letters => letters.toLowerCase()));
|
|
132
323
|
case 'regex_replace':
|
|
133
|
-
return regexReplace(
|
|
324
|
+
return regexReplace(at(0), at(1), at(2));
|
|
134
325
|
case 'remove_bytes':
|
|
135
|
-
return removeBytes(
|
|
326
|
+
return removeBytes(at(0), at(1));
|
|
136
327
|
case 'remove_query_args':
|
|
137
|
-
return removeQueryArgs(
|
|
138
|
-
case 'sha256':
|
|
139
|
-
warnUnreliableFunction(ctx, name);
|
|
140
|
-
return argValue(0);
|
|
328
|
+
return removeQueryArgs(at(0), values.slice(1));
|
|
141
329
|
case 'split':
|
|
142
|
-
return splitValue(
|
|
330
|
+
return splitValue(at(0), at(1), at(2));
|
|
143
331
|
case 'substring':
|
|
144
|
-
return substringValue(
|
|
332
|
+
return substringValue(at(0), at(1), at(2));
|
|
145
333
|
case 'to_string':
|
|
146
|
-
return
|
|
334
|
+
return toStringValue(at(0), invocation.argumentTypes[0] ?? undefined);
|
|
147
335
|
case 'upper':
|
|
148
|
-
return mapStringValue(
|
|
336
|
+
return mapStringValue(at(0), value => value.replace(/[a-z]+/g, letters => letters.toUpperCase()));
|
|
149
337
|
case 'url_decode':
|
|
150
|
-
return urlDecodeValue(
|
|
151
|
-
case 'uuidv4':
|
|
152
|
-
warnUnreliableFunction(ctx, name);
|
|
153
|
-
return globalThis.crypto?.randomUUID?.()
|
|
154
|
-
?? '00000000-0000-4000-8000-000000000000';
|
|
338
|
+
return urlDecodeValue(at(0), at(1));
|
|
155
339
|
case 'wildcard_replace':
|
|
156
|
-
return wildcardReplaceValue(
|
|
340
|
+
return wildcardReplaceValue(at(0), at(1), at(2), at(3));
|
|
157
341
|
default:
|
|
158
|
-
return
|
|
342
|
+
return undefined;
|
|
159
343
|
}
|
|
160
344
|
}
|
|
161
345
|
function evaluateFuncArray(node, ctx, invocation) {
|
|
162
346
|
const source = evaluateArgValue(node.args[0], ctx);
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
347
|
+
if (isUnknown(source))
|
|
348
|
+
return source;
|
|
349
|
+
const { value } = source;
|
|
350
|
+
if (value instanceof RuleMapValue)
|
|
351
|
+
return unavailable('a map value');
|
|
352
|
+
if (value === null)
|
|
353
|
+
return known([]);
|
|
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);
|
|
357
|
+
const results = [];
|
|
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;
|
|
371
|
+
}
|
|
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));
|
|
167
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
|
+
]);
|
|
168
390
|
function evaluateArgValue(arg, ctx) {
|
|
391
|
+
// An omitted optional argument is null, which functions treat as absent.
|
|
169
392
|
if (!arg || typeof arg !== 'object' || !('kind' in arg))
|
|
170
|
-
return null;
|
|
393
|
+
return known(null);
|
|
171
394
|
if (arg.kind === 'Field')
|
|
172
395
|
return resolveFieldNode(arg, ctx);
|
|
173
|
-
if (arg.kind === 'Func')
|
|
396
|
+
if (arg.kind === 'Func' && !isConditionArgument(arg))
|
|
174
397
|
return evaluateFuncValue(arg, ctx);
|
|
175
398
|
if (arg.kind === 'StringLiteral' ||
|
|
176
399
|
arg.kind === 'NumberLiteral' ||
|
|
177
400
|
arg.kind === 'IpLiteral' ||
|
|
178
|
-
arg.kind === 'BoolLiteral'
|
|
179
|
-
arg
|
|
180
|
-
return literalValue(arg);
|
|
401
|
+
arg.kind === 'BoolLiteral') {
|
|
402
|
+
return known(literalValue(arg));
|
|
181
403
|
}
|
|
182
|
-
|
|
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));
|
|
183
411
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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);
|
|
197
439
|
}
|
|
198
|
-
return null;
|
|
199
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;
|
|
451
|
+
}
|
|
452
|
+
function nonValueArgumentWarning(arg) {
|
|
453
|
+
if (arg.kind === 'ListRef')
|
|
454
|
+
return `list '$${arg.name}' can only be used with the in operator`;
|
|
455
|
+
return 'inline lists can only be used with the in operator';
|
|
456
|
+
}
|
|
457
|
+
function nonValueArgumentSource(arg) {
|
|
458
|
+
if (arg.kind === 'ListRef')
|
|
459
|
+
return `list '$${arg.name}'`;
|
|
460
|
+
return 'an inline list';
|
|
461
|
+
}
|
|
462
|
+
/** Returns nil (null) for a nil collection or value, as Cloudflare documents. */
|
|
200
463
|
function evaluateHasValue(collection, value) {
|
|
201
464
|
if (collection === null || value === null)
|
|
202
465
|
return null;
|
|
@@ -204,12 +467,20 @@ function evaluateHasValue(collection, value) {
|
|
|
204
467
|
return collection.some(item => String(item) === String(value));
|
|
205
468
|
return String(collection) === String(value);
|
|
206
469
|
}
|
|
470
|
+
/** A nil source or affix never matches. */
|
|
471
|
+
function matchesAffix(name, value, affix) {
|
|
472
|
+
if (value === null || affix === null)
|
|
473
|
+
return false;
|
|
474
|
+
return name === 'starts_with'
|
|
475
|
+
? String(value).startsWith(String(affix))
|
|
476
|
+
: String(value).endsWith(String(affix));
|
|
477
|
+
}
|
|
207
478
|
function concatValues(values, argumentTypes) {
|
|
208
479
|
if (values.length < 2)
|
|
209
480
|
return null;
|
|
210
481
|
const expectedType = argumentTypes[0];
|
|
211
482
|
if (expectedType &&
|
|
212
|
-
argumentTypes.slice(1).some(type => compareRuleExpressionDataTypes(expectedType, type) === 'different'))
|
|
483
|
+
argumentTypes.slice(1).some(type => type !== null && compareRuleExpressionDataTypes(expectedType, type) === 'different'))
|
|
213
484
|
return null;
|
|
214
485
|
const presentValues = values.filter(value => value !== null);
|
|
215
486
|
const firstValue = presentValues[0];
|
|
@@ -224,44 +495,60 @@ function concatValues(values, argumentTypes) {
|
|
|
224
495
|
return null;
|
|
225
496
|
return presentValues.join('');
|
|
226
497
|
}
|
|
498
|
+
/** Cloudflare counts the bytes of a string. */
|
|
227
499
|
function lengthOfValue(value) {
|
|
228
500
|
if (value === null)
|
|
229
501
|
return null;
|
|
230
502
|
if (Array.isArray(value))
|
|
231
503
|
return value.length;
|
|
232
|
-
return String(value)
|
|
504
|
+
return byteLength(String(value));
|
|
233
505
|
}
|
|
234
506
|
function mapStringValue(value, map) {
|
|
235
507
|
if (value === null || Array.isArray(value))
|
|
236
508
|
return null;
|
|
237
509
|
return map(String(value));
|
|
238
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
|
+
}
|
|
239
520
|
function encodeBase64Value(value, flagsValue) {
|
|
240
521
|
if (value === null)
|
|
241
522
|
return null;
|
|
242
523
|
const flags = flagsValue === null ? '' : String(flagsValue);
|
|
243
|
-
let encoded = bytesToBase64(
|
|
524
|
+
let encoded = bytesToBase64(textToBytes(String(value)));
|
|
244
525
|
if (flags.includes('u'))
|
|
245
526
|
encoded = encoded.replaceAll('+', '-').replaceAll('/', '_');
|
|
246
527
|
if (!flags.includes('p'))
|
|
247
528
|
encoded = encoded.replace(/=+$/, '');
|
|
248
529
|
return encoded;
|
|
249
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
|
+
*/
|
|
250
537
|
function decodeBase64Value(value) {
|
|
251
538
|
if (value === null)
|
|
252
539
|
return null;
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
if (padding)
|
|
256
|
-
input += '='.repeat(4 - padding);
|
|
540
|
+
const input = String(value);
|
|
541
|
+
let binary;
|
|
257
542
|
try {
|
|
258
|
-
|
|
259
|
-
const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
|
|
260
|
-
return new TextDecoder().decode(bytes);
|
|
543
|
+
binary = globalThis.atob(input);
|
|
261
544
|
}
|
|
262
545
|
catch {
|
|
263
546
|
return null;
|
|
264
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)));
|
|
265
552
|
}
|
|
266
553
|
function bytesToBase64(bytes) {
|
|
267
554
|
let binary = '';
|
|
@@ -274,34 +561,104 @@ function joinValues(items, separator) {
|
|
|
274
561
|
return null;
|
|
275
562
|
return items.map(item => String(item)).join(String(separator));
|
|
276
563
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
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
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Reads keys only while the JSON value can still be traversed, so a missing
|
|
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.
|
|
625
|
+
*/
|
|
626
|
+
function lookupJsonValue(kind, argumentCount, argument) {
|
|
627
|
+
const source = argument(0);
|
|
628
|
+
if (isUnknown(source) || source.value === null)
|
|
629
|
+
return source;
|
|
281
630
|
let current;
|
|
282
631
|
try {
|
|
283
|
-
current = JSON.parse(String(source));
|
|
632
|
+
current = JSON.parse(String(source.value));
|
|
284
633
|
}
|
|
285
634
|
catch {
|
|
286
|
-
return null;
|
|
635
|
+
return known(null);
|
|
287
636
|
}
|
|
288
|
-
for (
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
}
|
|
298
|
-
else {
|
|
299
|
-
return null;
|
|
300
|
-
}
|
|
637
|
+
for (let index = 1; index < argumentCount; index++) {
|
|
638
|
+
if (!current || typeof current !== 'object')
|
|
639
|
+
return known(null);
|
|
640
|
+
if (!Array.isArray(current) && Object.keys(current).some(name => !name.isWellFormed()))
|
|
641
|
+
return known(null);
|
|
642
|
+
const key = argument(index);
|
|
643
|
+
if (isUnknown(key) || key.value === null)
|
|
644
|
+
return key;
|
|
645
|
+
current = jsonMember(current, key.value);
|
|
301
646
|
}
|
|
302
647
|
if (kind === 'integer')
|
|
303
|
-
return typeof current === 'number' && Number.isInteger(current) ? current : null;
|
|
304
|
-
return typeof current === 'string' ? current : null;
|
|
648
|
+
return known(typeof current === 'number' && Number.isInteger(current) ? current : null);
|
|
649
|
+
return known(typeof current === 'string' && current.isWellFormed() ? current : null);
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* An array element by integer index, or an object member by key. Other
|
|
653
|
+
* JavaScript properties, such as an array's `length` or an inherited
|
|
654
|
+
* `toString`, are not JSON data.
|
|
655
|
+
*/
|
|
656
|
+
function jsonMember(container, key) {
|
|
657
|
+
if (Array.isArray(container)) {
|
|
658
|
+
return typeof key === 'number' ? container[key] : undefined;
|
|
659
|
+
}
|
|
660
|
+
const name = String(key);
|
|
661
|
+
return Object.hasOwn(container, name) ? container[name] : undefined;
|
|
305
662
|
}
|
|
306
663
|
function regexReplace(sourceValue, patternValue, replacementValue) {
|
|
307
664
|
if (sourceValue === null || patternValue === null || replacementValue === null)
|
|
@@ -317,10 +674,12 @@ function regexReplace(sourceValue, patternValue, replacementValue) {
|
|
|
317
674
|
return String(sourceValue);
|
|
318
675
|
}
|
|
319
676
|
}
|
|
677
|
+
/** Removes each listed byte wherever it appears, as Cloudflare does, so a result can split a character. */
|
|
320
678
|
function removeBytes(sourceValue, removeValue) {
|
|
321
679
|
if (sourceValue === null || removeValue === null)
|
|
322
680
|
return null;
|
|
323
|
-
|
|
681
|
+
const removed = new Set(textToBytes(String(removeValue)));
|
|
682
|
+
return bytesToText(textToBytes(String(sourceValue)).filter(byte => !removed.has(byte)));
|
|
324
683
|
}
|
|
325
684
|
function removeQueryArgs(sourceValue, argValues) {
|
|
326
685
|
if (sourceValue === null)
|
|
@@ -345,46 +704,29 @@ function splitValue(sourceValue, separatorValue, limitValue) {
|
|
|
345
704
|
return parts;
|
|
346
705
|
return [...parts.slice(0, limit - 1), parts.slice(limit - 1).join(separator)];
|
|
347
706
|
}
|
|
707
|
+
/** Cloudflare indexes bytes, so a result can split a character. */
|
|
348
708
|
function substringValue(sourceValue, startValue, endValue) {
|
|
349
709
|
if (sourceValue === null || startValue === null)
|
|
350
710
|
return null;
|
|
351
|
-
const
|
|
352
|
-
const start =
|
|
353
|
-
const end = endValue === null ?
|
|
354
|
-
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));
|
|
355
715
|
}
|
|
356
|
-
function
|
|
716
|
+
function normalizeByteIndex(length, index) {
|
|
357
717
|
if (!Number.isFinite(index))
|
|
358
718
|
return 0;
|
|
359
719
|
if (index < 0)
|
|
360
|
-
return Math.max(
|
|
361
|
-
return Math.min(index,
|
|
720
|
+
return Math.max(length + index, 0);
|
|
721
|
+
return Math.min(index, length);
|
|
362
722
|
}
|
|
363
723
|
function urlDecodeValue(sourceValue, optionsValue) {
|
|
364
724
|
if (sourceValue === null)
|
|
365
725
|
return null;
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
: value;
|
|
371
|
-
try {
|
|
372
|
-
return decodeURIComponent(withUnicode.replaceAll('+', ' '));
|
|
373
|
-
}
|
|
374
|
-
catch {
|
|
375
|
-
return withUnicode;
|
|
376
|
-
}
|
|
377
|
-
};
|
|
378
|
-
let decoded = decodeOnce(String(sourceValue));
|
|
379
|
-
if (options.includes('r')) {
|
|
380
|
-
for (let iteration = 0; iteration < 8; iteration++) {
|
|
381
|
-
const next = decodeOnce(decoded);
|
|
382
|
-
if (next === decoded)
|
|
383
|
-
break;
|
|
384
|
-
decoded = next;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
return decoded;
|
|
726
|
+
const source = String(sourceValue);
|
|
727
|
+
if (!/[%+]/.test(source))
|
|
728
|
+
return source;
|
|
729
|
+
return bytesToText(urlDecode(textToBytes(source), optionsValue === null ? '' : String(optionsValue)));
|
|
388
730
|
}
|
|
389
731
|
function wildcardReplaceValue(sourceValue, patternValue, replacementValue, flagsValue) {
|
|
390
732
|
if (sourceValue === null || patternValue === null || replacementValue === null)
|
|
@@ -392,7 +734,7 @@ function wildcardReplaceValue(sourceValue, patternValue, replacementValue, flags
|
|
|
392
734
|
return wildcardReplace(String(sourceValue), String(patternValue), String(replacementValue), flagsValue === null ? '' : String(flagsValue));
|
|
393
735
|
}
|
|
394
736
|
function wildcardReplace(source, pattern, replacement, flags) {
|
|
395
|
-
const regex =
|
|
737
|
+
const regex = wildcardToRegex(pattern, flags.includes('s'));
|
|
396
738
|
if (!regex)
|
|
397
739
|
return source;
|
|
398
740
|
const match = regex.exec(source);
|
|
@@ -400,36 +742,6 @@ function wildcardReplace(source, pattern, replacement, flags) {
|
|
|
400
742
|
return source;
|
|
401
743
|
return replaceRuleCaptureReferences(replacement, match.slice(1));
|
|
402
744
|
}
|
|
403
|
-
function wildcardPatternToRegex(pattern, caseSensitive) {
|
|
404
|
-
let source = '^';
|
|
405
|
-
let previousWildcard = false;
|
|
406
|
-
for (let index = 0; index < pattern.length; index++) {
|
|
407
|
-
const char = pattern[index];
|
|
408
|
-
if (char === '\\') {
|
|
409
|
-
const next = pattern[index + 1];
|
|
410
|
-
if (next === '*' || next === '\\') {
|
|
411
|
-
source += escapeRegexChar(next);
|
|
412
|
-
index++;
|
|
413
|
-
}
|
|
414
|
-
else {
|
|
415
|
-
source += escapeRegexChar(char);
|
|
416
|
-
}
|
|
417
|
-
previousWildcard = false;
|
|
418
|
-
continue;
|
|
419
|
-
}
|
|
420
|
-
if (char === '*') {
|
|
421
|
-
if (previousWildcard)
|
|
422
|
-
return null;
|
|
423
|
-
source += '([\\s\\S]*?)';
|
|
424
|
-
previousWildcard = true;
|
|
425
|
-
continue;
|
|
426
|
-
}
|
|
427
|
-
source += escapeRegexChar(char);
|
|
428
|
-
previousWildcard = false;
|
|
429
|
-
}
|
|
430
|
-
source += '$';
|
|
431
|
-
return new RegExp(source, caseSensitive ? '' : 'i');
|
|
432
|
-
}
|
|
433
745
|
function replaceRuleCaptureReferences(replacement, captures) {
|
|
434
746
|
return replacement.replace(/\$\$|\$\{([1-8])\}/g, (full, index) => {
|
|
435
747
|
if (full === '$$')
|
|
@@ -437,73 +749,31 @@ function replaceRuleCaptureReferences(replacement, captures) {
|
|
|
437
749
|
return captures[Number.parseInt(index ?? '0', 10) - 1]?.toString() ?? '';
|
|
438
750
|
});
|
|
439
751
|
}
|
|
440
|
-
|
|
441
|
-
return /[\\^$.*+?()[\]{}|]/.test(char) ? `\\${char}` : char;
|
|
442
|
-
}
|
|
752
|
+
/** Returns the network address, printed as Cloudflare prints IP addresses. */
|
|
443
753
|
function evaluateCidr(addressValue, ipv4BitsValue, ipv6BitsValue) {
|
|
444
754
|
if (addressValue === null)
|
|
445
755
|
return null;
|
|
446
756
|
const address = String(addressValue);
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
return truncateIpv4(address, Number(ipv4BitsValue));
|
|
450
|
-
}
|
|
451
|
-
function truncateIpv4(address, bits) {
|
|
452
|
-
const value = ipv4ToUint32(address);
|
|
453
|
-
if (value === null || !Number.isInteger(bits) || bits < 1 || bits > 32)
|
|
454
|
-
return address;
|
|
455
|
-
const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
|
|
456
|
-
const truncated = value & mask;
|
|
457
|
-
return [
|
|
458
|
-
(truncated >>> 24) & 255,
|
|
459
|
-
(truncated >>> 16) & 255,
|
|
460
|
-
(truncated >>> 8) & 255,
|
|
461
|
-
truncated & 255,
|
|
462
|
-
].join('.');
|
|
463
|
-
}
|
|
464
|
-
function ipv4ToUint32(address) {
|
|
465
|
-
const parts = address.split('.').map(part => Number.parseInt(part, 10));
|
|
466
|
-
if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255))
|
|
467
|
-
return null;
|
|
468
|
-
return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
|
|
469
|
-
}
|
|
470
|
-
function truncateIpv6(address, bits) {
|
|
471
|
-
if (!Number.isInteger(bits) || bits < 1 || bits > 128)
|
|
757
|
+
const octets = ipAddressOctets(address);
|
|
758
|
+
if (!octets)
|
|
472
759
|
return address;
|
|
473
|
-
const
|
|
474
|
-
if (!
|
|
760
|
+
const bits = Number(octets.length === 4 ? ipv4BitsValue : ipv6BitsValue);
|
|
761
|
+
if (!Number.isInteger(bits) || bits < 1 || bits > octets.length * 8)
|
|
475
762
|
return address;
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
remaining -= 16;
|
|
481
|
-
return group;
|
|
482
|
-
}
|
|
483
|
-
if (remaining <= 0)
|
|
484
|
-
return 0;
|
|
485
|
-
const mask = (0xffff << (16 - remaining)) & 0xffff;
|
|
486
|
-
remaining = 0;
|
|
487
|
-
return group & mask;
|
|
488
|
-
});
|
|
489
|
-
return truncated.map(group => group.toString(16).padStart(4, '0')).join(':');
|
|
490
|
-
}
|
|
491
|
-
function expandIpv6(address) {
|
|
492
|
-
const [headText, tailText] = address.split('::');
|
|
493
|
-
const head = headText ? headText.split(':') : [];
|
|
494
|
-
const tail = tailText ? tailText.split(':') : [];
|
|
495
|
-
if (address.includes('::')) {
|
|
496
|
-
const missing = 8 - head.length - tail.length;
|
|
497
|
-
if (missing < 0)
|
|
498
|
-
return null;
|
|
499
|
-
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;
|
|
500
767
|
}
|
|
501
|
-
return
|
|
768
|
+
return formatIpAddress(octets);
|
|
769
|
+
}
|
|
770
|
+
/** A function result this evaluator cannot reproduce is unknown. */
|
|
771
|
+
function unreliableFunction(ctx, name, reason = getUnreliableRuleExpressionFunctionReason(name)) {
|
|
772
|
+
if (reason)
|
|
773
|
+
ctx.warnings.add(`function '${name}' cannot be evaluated reliably: ${reason}`);
|
|
774
|
+
return unavailable(functionSource(name));
|
|
502
775
|
}
|
|
503
|
-
function
|
|
504
|
-
|
|
505
|
-
if (!reason)
|
|
506
|
-
return;
|
|
507
|
-
pushWarning(ctx.warnings, `function '${name}' cannot be evaluated reliably: ${reason}`);
|
|
776
|
+
function functionSource(name) {
|
|
777
|
+
return `function '${name}'`;
|
|
508
778
|
}
|
|
509
779
|
//# sourceMappingURL=functions.js.map
|