@libreflare/worker-runtime 0.9.5 → 0.10.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 +280 -9
- package/dist/log-handler.d.ts.map +1 -1
- package/dist/log-handler.js +3 -4
- package/dist/log-handler.js.map +1 -1
- package/dist/rule-evaluator/accept-encoding.d.ts.map +1 -1
- package/dist/rule-evaluator/accept-encoding.js +3 -0
- package/dist/rule-evaluator/accept-encoding.js.map +1 -1
- package/dist/rule-evaluator/access-values.d.ts +5 -3
- package/dist/rule-evaluator/access-values.d.ts.map +1 -1
- package/dist/rule-evaluator/access-values.js +9 -3
- package/dist/rule-evaluator/access-values.js.map +1 -1
- package/dist/rule-evaluator/country-codes.generated.js +1 -1
- package/dist/rule-evaluator/edge-evaluation.d.ts +128 -0
- package/dist/rule-evaluator/edge-evaluation.d.ts.map +1 -0
- package/dist/rule-evaluator/edge-evaluation.js +316 -0
- package/dist/rule-evaluator/edge-evaluation.js.map +1 -0
- package/dist/rule-evaluator/edge-record.d.ts +173 -0
- package/dist/rule-evaluator/edge-record.d.ts.map +1 -0
- package/dist/rule-evaluator/edge-record.js +771 -0
- package/dist/rule-evaluator/edge-record.js.map +1 -0
- package/dist/rule-evaluator/evaluator.d.ts +21 -0
- package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
- package/dist/rule-evaluator/evaluator.js +60 -3
- package/dist/rule-evaluator/evaluator.js.map +1 -1
- package/dist/rule-evaluator/explain.d.ts +6 -0
- package/dist/rule-evaluator/explain.d.ts.map +1 -1
- package/dist/rule-evaluator/explain.js +54 -20
- package/dist/rule-evaluator/explain.js.map +1 -1
- package/dist/rule-evaluator/fields.d.ts +50 -6
- package/dist/rule-evaluator/fields.d.ts.map +1 -1
- package/dist/rule-evaluator/fields.js +72 -50
- package/dist/rule-evaluator/fields.js.map +1 -1
- package/dist/rule-evaluator/functions.d.ts +18 -0
- package/dist/rule-evaluator/functions.d.ts.map +1 -1
- package/dist/rule-evaluator/functions.js +58 -4
- package/dist/rule-evaluator/functions.js.map +1 -1
- package/dist/rule-evaluator/log-sample.d.ts +23 -0
- package/dist/rule-evaluator/log-sample.d.ts.map +1 -1
- package/dist/rule-evaluator/log-sample.js +5 -3
- package/dist/rule-evaluator/log-sample.js.map +1 -1
- package/dist/rule-evaluator/match-chain.d.ts +8 -0
- package/dist/rule-evaluator/match-chain.d.ts.map +1 -1
- package/dist/rule-evaluator/match-chain.js +16 -0
- package/dist/rule-evaluator/match-chain.js.map +1 -1
- package/dist/rule-evaluator/operators.d.ts +5 -0
- package/dist/rule-evaluator/operators.d.ts.map +1 -1
- package/dist/rule-evaluator/operators.js +52 -0
- package/dist/rule-evaluator/operators.js.map +1 -1
- package/dist/rule-evaluator/query-args.d.ts +2 -2
- package/dist/rule-evaluator/query-args.d.ts.map +1 -1
- package/dist/rule-evaluator/query-args.js +11 -4
- package/dist/rule-evaluator/query-args.js.map +1 -1
- package/dist/rule-evaluator/validation.d.ts.map +1 -1
- package/dist/rule-evaluator/validation.js +30 -19
- package/dist/rule-evaluator/validation.js.map +1 -1
- package/dist/rule-evaluator.d.ts +5 -0
- package/dist/rule-evaluator.d.ts.map +1 -1
- package/dist/rule-evaluator.js +3 -0
- package/dist/rule-evaluator.js.map +1 -1
- package/dist/tools/explain-rule-miss.js +259 -10
- package/dist/tools/explain-rule-miss.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
import { mapKeys, PartialArrayValue, RuleMapValue } from './access-values.js';
|
|
2
|
+
import { acceptedLanguages, fieldSource, hostField, integerValue, pathBasename, pathExtension, queryArgMapValue, UnknownFieldValue, } from './fields.js';
|
|
3
|
+
import { isPlainRecord, jsonArray, sampleRequestCf } from './log-sample.js';
|
|
4
|
+
import { isUnknown, known, unavailable } from './outcome.js';
|
|
5
|
+
import { groupQueryArgs, readQueryArgs } from './query-args.js';
|
|
6
|
+
import { renderRuleExpressionStringLiteral } from './string-literals.js';
|
|
7
|
+
/** A record the evaluator cannot read, as opposed to a failure while evaluating one. */
|
|
8
|
+
export class EdgeRecordError extends Error {
|
|
9
|
+
name = 'EdgeRecordError';
|
|
10
|
+
}
|
|
11
|
+
const HEADER_PREFIX = 'request.headers.';
|
|
12
|
+
const COOKIE_PREFIX = 'request.headers.cookie.';
|
|
13
|
+
/**
|
|
14
|
+
* Headers the mapping copies from Logpush's standard fields, which give an
|
|
15
|
+
* empty string both for a header sent empty and for one not sent.
|
|
16
|
+
*/
|
|
17
|
+
const STANDARD_HEADERS = new Set(['user-agent', 'referer', 'x-requested-with']);
|
|
18
|
+
/** Whether a sample is a mapped edge record, which has a Ray ID under `edge`, nested or flattened. */
|
|
19
|
+
export function isEdgeRecord(sample) {
|
|
20
|
+
return stringField(sample, 'edge.ray_id') !== undefined;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Reads a mapped edge record, nested as the mapping writes it or flattened as
|
|
24
|
+
* VictoriaLogs returns it. Logpush logs only the first value of a header sent
|
|
25
|
+
* more than once, and the evaluator takes each logged header and cookie as
|
|
26
|
+
* sent once.
|
|
27
|
+
*
|
|
28
|
+
* @throws {EdgeRecordError} When the record has no `edge.ray_id`, or no http
|
|
29
|
+
* or https URL in `edge.url`.
|
|
30
|
+
*/
|
|
31
|
+
export function readEdgeRecord(sample, options = {}) {
|
|
32
|
+
const rayId = stringField(sample, 'edge.ray_id');
|
|
33
|
+
if (!rayId)
|
|
34
|
+
throw new EdgeRecordError('edge record is missing edge.ray_id');
|
|
35
|
+
const { scheme, host, rawPath, search } = readEdgeUrl(sample);
|
|
36
|
+
let origin;
|
|
37
|
+
try {
|
|
38
|
+
origin = new URL(`${scheme}://${host}/`);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new EdgeRecordError(`edge.url ${JSON.stringify(stringField(sample, 'edge.url'))} has an invalid host`);
|
|
42
|
+
}
|
|
43
|
+
const fields = readHeaders(sample);
|
|
44
|
+
// The record holds the host in lowercase, and the engine's Host header keeps the client's case.
|
|
45
|
+
fields.headers.delete('host');
|
|
46
|
+
const logged = loggedFields(fields, options.loggedFields);
|
|
47
|
+
const cf = sampleRequestCf(sample);
|
|
48
|
+
// The mapping's compact() drops these when empty: the TLS fields over plain HTTP, and the bot category for most
|
|
49
|
+
// clients. A record without request.cf has no bot category.
|
|
50
|
+
if (Object.keys(cf).length > 0)
|
|
51
|
+
cf.verifiedBotCategory ??= '';
|
|
52
|
+
if (scheme === 'http') {
|
|
53
|
+
cf.tlsVersion ??= '';
|
|
54
|
+
cf.tlsCipher ??= '';
|
|
55
|
+
}
|
|
56
|
+
// The record keeps a port and a trailing dot the client sent.
|
|
57
|
+
const hostname = hostField(origin);
|
|
58
|
+
return {
|
|
59
|
+
rayId,
|
|
60
|
+
time: edgeRecordTime(sample),
|
|
61
|
+
...customRuleIds(sample),
|
|
62
|
+
matchedRules: matchedRules(sample),
|
|
63
|
+
assumedLoggedFields: options.loggedFields === undefined,
|
|
64
|
+
urlNormalization: options.urlNormalization,
|
|
65
|
+
normalizedPaths: normalizedPathCandidates(rawPath, options.urlNormalization),
|
|
66
|
+
method: stringField(sample, 'request.method'),
|
|
67
|
+
scheme,
|
|
68
|
+
hostname,
|
|
69
|
+
origin: `${scheme}://${hostname}`,
|
|
70
|
+
rawPath,
|
|
71
|
+
search,
|
|
72
|
+
...queryFields(search),
|
|
73
|
+
clientIp: stringField(sample, 'request.client_ip'),
|
|
74
|
+
// VictoriaLogs returns numbers as text.
|
|
75
|
+
clientPort: integerValue(field(sample, 'edge.client.src_port')),
|
|
76
|
+
tcpRttMs: integerValue(field(sample, 'edge.client.tcp_rtt_ms')),
|
|
77
|
+
zoneName: stringField(sample, 'edge.zone'),
|
|
78
|
+
cf,
|
|
79
|
+
...logged,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function queryFields(search) {
|
|
83
|
+
const queryArgs = readQueryArgs(search.slice(1));
|
|
84
|
+
return { queryArgs, queryArgMap: groupQueryArgs(queryArgs) };
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The paths a mapped edge record's non-raw path fields may read with a URL
|
|
88
|
+
* normalization; see EdgeRecord.normalizedPaths.
|
|
89
|
+
*
|
|
90
|
+
* @throws {EdgeRecordError} When the record has no http or https URL in `edge.url`.
|
|
91
|
+
*/
|
|
92
|
+
export function edgeRecordPaths(sample, urlNormalization) {
|
|
93
|
+
return normalizedPathCandidates(readEdgeUrl(sample).rawPath, urlNormalization);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The parts of a record's `edge.url`, with the scheme in lowercase.
|
|
97
|
+
*
|
|
98
|
+
* @throws {EdgeRecordError} When the record has no http or https URL in `edge.url`.
|
|
99
|
+
*/
|
|
100
|
+
function readEdgeUrl(sample) {
|
|
101
|
+
const url = stringField(sample, 'edge.url');
|
|
102
|
+
if (!url)
|
|
103
|
+
throw new EdgeRecordError('edge record is missing edge.url');
|
|
104
|
+
// A `#` starts a fragment, which the rules engine and Logpush leave out.
|
|
105
|
+
const parts = /^(https?):\/\/([^/?#]+)([^?#]*)(\?[^#]*)?(?:#[^]*)?$/i.exec(url);
|
|
106
|
+
if (!parts)
|
|
107
|
+
throw new EdgeRecordError(`edge.url ${JSON.stringify(url)} is not an http or https URL`);
|
|
108
|
+
const [, scheme, host, rawPath, search = ''] = parts;
|
|
109
|
+
return { scheme: scheme.toLowerCase(), host, rawPath, search };
|
|
110
|
+
}
|
|
111
|
+
/** A field of either shape: a flattened key, or a path through nested objects. */
|
|
112
|
+
function field(sample, path) {
|
|
113
|
+
if (path in sample)
|
|
114
|
+
return sample[path];
|
|
115
|
+
let current = sample;
|
|
116
|
+
for (const part of path.split('.')) {
|
|
117
|
+
if (!isPlainRecord(current))
|
|
118
|
+
return undefined;
|
|
119
|
+
current = current[part];
|
|
120
|
+
}
|
|
121
|
+
return current;
|
|
122
|
+
}
|
|
123
|
+
function stringField(sample, path) {
|
|
124
|
+
const value = field(sample, path);
|
|
125
|
+
return typeof value === 'string' ? value : undefined;
|
|
126
|
+
}
|
|
127
|
+
/** An array, which VictoriaLogs returns as JSON text. */
|
|
128
|
+
function arrayField(sample, path) {
|
|
129
|
+
const value = field(sample, path);
|
|
130
|
+
if (typeof value === 'string')
|
|
131
|
+
return jsonArray(value);
|
|
132
|
+
return Array.isArray(value) ? value : undefined;
|
|
133
|
+
}
|
|
134
|
+
function stringArrayField(sample, path) {
|
|
135
|
+
return arrayField(sample, path)?.filter(item => typeof item === 'string');
|
|
136
|
+
}
|
|
137
|
+
/** MatchedRules, as `[{ product, rulesetId, rulesetVersion, rules: [{ id }] }]`. */
|
|
138
|
+
function matchedRules(sample) {
|
|
139
|
+
return (arrayField(sample, 'edge.security.matched_rules') ?? []).flatMap((entry) => {
|
|
140
|
+
if (!isPlainRecord(entry) || typeof entry.rulesetId !== 'string' || !Array.isArray(entry.rules))
|
|
141
|
+
return [];
|
|
142
|
+
const ruleIds = entry.rules.flatMap(rule => (isPlainRecord(rule) && typeof rule.id === 'string' ? [rule.id] : []));
|
|
143
|
+
return [{ rulesetId: entry.rulesetId, ruleIds }];
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The Custom Rules the record lists. A challenge solve lists its rule twice,
|
|
148
|
+
* as solved and as bypassed. Without sources that line up with the IDs, every
|
|
149
|
+
* listed rule counts.
|
|
150
|
+
*/
|
|
151
|
+
function customRuleIds(sample) {
|
|
152
|
+
const ids = stringArrayField(sample, 'edge.security.rule_ids') ?? [];
|
|
153
|
+
const sources = stringArrayField(sample, 'edge.security.sources');
|
|
154
|
+
const aligned = sources?.length === ids.length;
|
|
155
|
+
return {
|
|
156
|
+
customRuleIds: [...new Set(ids.filter((_, index) => !aligned || sources[index] === 'firewallCustom'))],
|
|
157
|
+
ruleSourcesAligned: aligned,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function readHeaders(sample) {
|
|
161
|
+
const headers = new Map();
|
|
162
|
+
const cookies = new Map();
|
|
163
|
+
const cookieKeys = new Map();
|
|
164
|
+
const addCookies = (values) => {
|
|
165
|
+
// Logpush keys a cookie by its name in lowercase, which a sample written by hand may not.
|
|
166
|
+
for (const [name, value] of Object.entries(values)) {
|
|
167
|
+
if (typeof value === 'string')
|
|
168
|
+
cookies.set(name.toLowerCase(), value);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
const addHeader = (name, value) => {
|
|
172
|
+
const key = name.toLowerCase();
|
|
173
|
+
if (key === 'cookie') {
|
|
174
|
+
if (isPlainRecord(value))
|
|
175
|
+
addCookies(value);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (typeof value !== 'string' || (value === '' && STANDARD_HEADERS.has(key)))
|
|
179
|
+
return;
|
|
180
|
+
headers.set(key, value);
|
|
181
|
+
};
|
|
182
|
+
const nested = field(sample, 'request.headers');
|
|
183
|
+
if (isPlainRecord(nested)) {
|
|
184
|
+
for (const [name, value] of Object.entries(nested))
|
|
185
|
+
addHeader(name, value);
|
|
186
|
+
}
|
|
187
|
+
for (const [key, value] of Object.entries(sample)) {
|
|
188
|
+
if (key.startsWith(COOKIE_PREFIX)) {
|
|
189
|
+
if (typeof value === 'string')
|
|
190
|
+
cookieKeys.set(key.slice(COOKIE_PREFIX.length).toLowerCase(), value);
|
|
191
|
+
}
|
|
192
|
+
else if (key.startsWith(HEADER_PREFIX)) {
|
|
193
|
+
addHeader(key.slice(HEADER_PREFIX.length), value);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return { headers, cookies, cookieKeys };
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The logged headers and cookies, and the record's values for them. Logpush
|
|
200
|
+
* matches a configured cookie name case-sensitively and keys its value by
|
|
201
|
+
* the name in lowercase. With the logged fields given, a header the record
|
|
202
|
+
* holds is known only when logged raw alone, while a cookie the record holds
|
|
203
|
+
* counts as logged even when they lack it: under its key when the key has no
|
|
204
|
+
* letters, and as unknown in any spelling otherwise.
|
|
205
|
+
*/
|
|
206
|
+
function loggedFields(record, given) {
|
|
207
|
+
const transformedHeaders = new Set(given?.transformedRequestHeaders?.map(name => name.toLowerCase()));
|
|
208
|
+
const loggedHeaders = new Set(STANDARD_HEADERS);
|
|
209
|
+
for (const name of given ? given.requestHeaders.map(header => header.toLowerCase()) : record.headers.keys()) {
|
|
210
|
+
if (!transformedHeaders.has(name))
|
|
211
|
+
loggedHeaders.add(name);
|
|
212
|
+
}
|
|
213
|
+
const byKey = new Map();
|
|
214
|
+
for (const name of given?.cookies ?? []) {
|
|
215
|
+
const names = byKey.get(name.toLowerCase());
|
|
216
|
+
if (!names)
|
|
217
|
+
byKey.set(name.toLowerCase(), [name]);
|
|
218
|
+
else if (!names.includes(name))
|
|
219
|
+
names.push(name);
|
|
220
|
+
}
|
|
221
|
+
// Flattened, a header named cookie.<name> and cookie <name> share a key. The logged
|
|
222
|
+
// fields tell them apart, in either form, and then whether the header's value is known.
|
|
223
|
+
const headers = new Map([...record.headers].filter(([name]) => loggedHeaders.has(name)));
|
|
224
|
+
const recordCookies = new Map(record.cookies);
|
|
225
|
+
const ambiguousHeaders = new Set();
|
|
226
|
+
const ambiguousKeys = new Set();
|
|
227
|
+
for (const [key, value] of record.cookieKeys) {
|
|
228
|
+
const header = `cookie.${key}`;
|
|
229
|
+
if (!given || (!loggedHeaders.has(header) && !transformedHeaders.has(header))) {
|
|
230
|
+
recordCookies.set(key, value);
|
|
231
|
+
}
|
|
232
|
+
else if (byKey.has(key)) {
|
|
233
|
+
loggedHeaders.delete(header);
|
|
234
|
+
ambiguousHeaders.add(header);
|
|
235
|
+
ambiguousKeys.add(key);
|
|
236
|
+
}
|
|
237
|
+
else if (loggedHeaders.has(header)) {
|
|
238
|
+
headers.set(header, value);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const cookies = new Map();
|
|
242
|
+
const ambiguousCookies = new Set();
|
|
243
|
+
const unnamedCookies = new Set();
|
|
244
|
+
for (const key of ambiguousKeys) {
|
|
245
|
+
for (const name of byKey.get(key) ?? [])
|
|
246
|
+
ambiguousCookies.add(name);
|
|
247
|
+
}
|
|
248
|
+
for (const [key, value] of recordCookies) {
|
|
249
|
+
let names = byKey.get(key);
|
|
250
|
+
if (!names) {
|
|
251
|
+
// A key the logged cookies do not name may stand for a name with uppercase letters.
|
|
252
|
+
if (key !== key.toUpperCase()) {
|
|
253
|
+
unnamedCookies.add(key);
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
byKey.set(key, names = [key]);
|
|
257
|
+
}
|
|
258
|
+
if (names.length === 1)
|
|
259
|
+
cookies.set(names[0], value);
|
|
260
|
+
else
|
|
261
|
+
for (const name of names)
|
|
262
|
+
ambiguousCookies.add(name);
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
headers,
|
|
266
|
+
loggedHeaders,
|
|
267
|
+
transformedHeaders,
|
|
268
|
+
ambiguousHeaders,
|
|
269
|
+
cookies,
|
|
270
|
+
loggedCookies: new Set([...byKey.values()].flat()),
|
|
271
|
+
ambiguousCookies,
|
|
272
|
+
unnamedCookies,
|
|
273
|
+
cookieSent: recordCookies.size > 0,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
/** A mapped edge record's time, read without the rest of the record. */
|
|
277
|
+
export function edgeRecordTime(sample) {
|
|
278
|
+
const time = stringField(sample, '_time');
|
|
279
|
+
return time === undefined ? undefined : parseEdgeTime(time);
|
|
280
|
+
}
|
|
281
|
+
const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/;
|
|
282
|
+
/**
|
|
283
|
+
* An RFC 3339 time, such as `_time` or a rule version's time, or undefined
|
|
284
|
+
* for text that is not one, such as a month 13. Fractions below a
|
|
285
|
+
* millisecond are cut, and a leap second reads as the next minute's first,
|
|
286
|
+
* as in Unix time.
|
|
287
|
+
*/
|
|
288
|
+
export function parseEdgeTime(text) {
|
|
289
|
+
const match = RFC3339.exec(text);
|
|
290
|
+
if (!match)
|
|
291
|
+
return undefined;
|
|
292
|
+
const [, year, month, day, hour, minute, second, fraction = '', sign, offsetHours = '0', offsetMinutes = '0'] = match;
|
|
293
|
+
const [hours, minutes, seconds] = [hour, minute, second].map(Number);
|
|
294
|
+
if (hours > 23 || minutes > 59 || seconds > 60 || Number(offsetHours) > 23 || Number(offsetMinutes) > 59)
|
|
295
|
+
return undefined;
|
|
296
|
+
// setUTCFullYear() takes years below 100 as they are, and carries a day out of range into the next month.
|
|
297
|
+
const date = new Date(0);
|
|
298
|
+
date.setUTCFullYear(Number(year), Number(month) - 1, Number(day));
|
|
299
|
+
if (date.getUTCMonth() !== Number(month) - 1 || date.getUTCDate() !== Number(day))
|
|
300
|
+
return undefined;
|
|
301
|
+
const offset = sign ? (sign === '-' ? -1 : 1) * (Number(offsetHours) * 60 + Number(offsetMinutes)) : 0;
|
|
302
|
+
const secondMs = date.getTime() + ((hours * 60 + minutes) * 60 + seconds) * 1000 - offset * 60_000;
|
|
303
|
+
const msec = Number(fraction.padEnd(3, '0').slice(0, 3));
|
|
304
|
+
return { epochMs: secondMs + msec, sec: secondMs / 1000, msec };
|
|
305
|
+
}
|
|
306
|
+
const UNRESERVED = /^[A-Za-z0-9._~-]$/;
|
|
307
|
+
function normalizeEscapes(path) {
|
|
308
|
+
return path.replace(/%([0-9A-Fa-f]{2})/g, (_, hex) => {
|
|
309
|
+
const char = String.fromCharCode(Number.parseInt(hex, 16));
|
|
310
|
+
return UNRESERVED.test(char) ? char : `%${hex.toUpperCase()}`;
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Resolves `.` and `..` segments as RFC 3986 does, or null where what
|
|
315
|
+
* Cloudflare does is unknown: a `..` above the root or after an empty
|
|
316
|
+
* segment, and a path that ends with a dot segment.
|
|
317
|
+
*/
|
|
318
|
+
function removeDotSegments(path) {
|
|
319
|
+
const segments = path.split('/');
|
|
320
|
+
const output = [];
|
|
321
|
+
for (let index = 1; index < segments.length; index++) {
|
|
322
|
+
const segment = segments[index];
|
|
323
|
+
if (segment !== '.' && segment !== '..') {
|
|
324
|
+
output.push(segment);
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (index === segments.length - 1)
|
|
328
|
+
return null;
|
|
329
|
+
if (segment === '..' && !output.pop())
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
return `/${output.join('/')}`;
|
|
333
|
+
}
|
|
334
|
+
const CLOUDFLARE_STEPS = [
|
|
335
|
+
normalizeEscapes,
|
|
336
|
+
path => path.replaceAll('\\', '/'),
|
|
337
|
+
path => path.replace(/\/{2,}/g, '/'),
|
|
338
|
+
removeDotSegments,
|
|
339
|
+
];
|
|
340
|
+
const RFC3986_STEPS = [normalizeEscapes, path => path.replaceAll('\\', '%5C'), removeDotSegments];
|
|
341
|
+
/** Anything a normalization type may change. */
|
|
342
|
+
const NORMALIZABLE = /[^!$&'()*+,\-./0-9:;=@A-Z[\]_a-z~]|\/\/|\/\.\.?(?:\/|$)/;
|
|
343
|
+
const INVALID_ESCAPE = /%(?![0-9A-Fa-f]{2})/;
|
|
344
|
+
/** Characters outside printable ASCII, whose normalization is unknown. */
|
|
345
|
+
const UNOBSERVED = /[^\x21-\x7e]/;
|
|
346
|
+
/** Characters both types percent-encode. No other step makes or removes one, so the order does not matter. */
|
|
347
|
+
const ENCODED = /["<>^`{|}]/g;
|
|
348
|
+
function encodeLiterals(path) {
|
|
349
|
+
return path.replace(ENCODED, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
350
|
+
}
|
|
351
|
+
function permutations(items) {
|
|
352
|
+
if (items.length <= 1)
|
|
353
|
+
return [[...items]];
|
|
354
|
+
return items.flatMap((item, index) => permutations(items.filter((_, other) => other !== index)).map(rest => [item, ...rest]));
|
|
355
|
+
}
|
|
356
|
+
const STEP_ORDERS = new Map();
|
|
357
|
+
/** Adds the path each order of the steps gives, or returns false when one is unknown. */
|
|
358
|
+
function addNormalizations(path, steps, into) {
|
|
359
|
+
let orders = STEP_ORDERS.get(steps);
|
|
360
|
+
if (!orders)
|
|
361
|
+
STEP_ORDERS.set(steps, orders = permutations(steps));
|
|
362
|
+
for (const order of orders) {
|
|
363
|
+
let result = path;
|
|
364
|
+
for (const step of order) {
|
|
365
|
+
result = step(result);
|
|
366
|
+
if (result === null)
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
into.add(result);
|
|
370
|
+
}
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
/** The paths the non-raw path fields may read; see EdgeRecord.normalizedPaths. */
|
|
374
|
+
function normalizedPathCandidates(path, type) {
|
|
375
|
+
if (type === 'off' || !NORMALIZABLE.test(path))
|
|
376
|
+
return [path];
|
|
377
|
+
if (!path.startsWith('/') || INVALID_ESCAPE.test(path) || UNOBSERVED.test(path))
|
|
378
|
+
return null;
|
|
379
|
+
const paths = new Set();
|
|
380
|
+
if (type === undefined)
|
|
381
|
+
paths.add(path);
|
|
382
|
+
const encoded = encodeLiterals(path);
|
|
383
|
+
if (type !== 'rfc3986' && !addNormalizations(encoded, CLOUDFLARE_STEPS, paths))
|
|
384
|
+
return null;
|
|
385
|
+
if (type !== 'cloudflare' && !addNormalizations(encoded, RFC3986_STEPS, paths))
|
|
386
|
+
return null;
|
|
387
|
+
return [...paths];
|
|
388
|
+
}
|
|
389
|
+
/** How many logged headers and cookies a condition may read that the record lacks; see eitherWay(). */
|
|
390
|
+
const EITHER_WAY_LIMIT = 3;
|
|
391
|
+
const NONE = new Set();
|
|
392
|
+
/** Marks a reading of the non-raw path; see eitherWay(). */
|
|
393
|
+
const PATH = 'path';
|
|
394
|
+
let carrier;
|
|
395
|
+
/** A resolver context that reads an edge record. */
|
|
396
|
+
export function edgeResolverCtx(record, options, warnings) {
|
|
397
|
+
const { normalizedPaths: paths } = record;
|
|
398
|
+
const { routePrefix, pathRewrittenBy } = options;
|
|
399
|
+
// The edge source answers every field that reads the request or the URL.
|
|
400
|
+
carrier ??= { request: new Request('https://edge-record.invalid/'), url: new URL('https://edge-record.invalid/') };
|
|
401
|
+
return {
|
|
402
|
+
request: carrier.request,
|
|
403
|
+
url: carrier.url,
|
|
404
|
+
search: record.search,
|
|
405
|
+
// Workers types isEUCountry as "1" or missing, but a Worker request's is a Boolean too.
|
|
406
|
+
cf: record.cf,
|
|
407
|
+
customLists: options.customLists,
|
|
408
|
+
cookieMap: null,
|
|
409
|
+
queryArgs: record.queryArgs,
|
|
410
|
+
queryArgMap: record.queryArgMap,
|
|
411
|
+
requestHeaders: null,
|
|
412
|
+
warnings,
|
|
413
|
+
edge: new EdgeRecordFields(record, routePrefix === undefined || !paths ? paths : paths.map(path => routePrefix + path), pathRewrittenBy, NONE, new Set()),
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Reads fields from an edge record. A logged header or cookie that the record
|
|
418
|
+
* lacks was not sent, or was sent empty, as the mapping drops empty values;
|
|
419
|
+
* a reading takes those in `sentEmpty` as sent empty, and eitherWay() tries
|
|
420
|
+
* both.
|
|
421
|
+
*/
|
|
422
|
+
class EdgeRecordFields {
|
|
423
|
+
record;
|
|
424
|
+
paths;
|
|
425
|
+
pathRewrittenBy;
|
|
426
|
+
sentEmpty;
|
|
427
|
+
read;
|
|
428
|
+
constructor(record,
|
|
429
|
+
/** The paths the non-raw path fields read; see EdgeRecord.normalizedPaths. */
|
|
430
|
+
paths,
|
|
431
|
+
/** See EdgeResolverOptions.pathRewrittenBy. */
|
|
432
|
+
pathRewrittenBy, sentEmpty,
|
|
433
|
+
/** The logged headers and cookies the record lacks that this reading looked up, and PATH if it read the path. */
|
|
434
|
+
read) {
|
|
435
|
+
this.record = record;
|
|
436
|
+
this.paths = paths;
|
|
437
|
+
this.pathRewrittenBy = pathRewrittenBy;
|
|
438
|
+
this.sentEmpty = sentEmpty;
|
|
439
|
+
this.read = read;
|
|
440
|
+
}
|
|
441
|
+
field(name) {
|
|
442
|
+
const { record } = this;
|
|
443
|
+
switch (name) {
|
|
444
|
+
case 'http.host': return record.hostname;
|
|
445
|
+
case 'http.request.method': return record.method ?? new UnknownFieldValue(`field '${name}' is unknown: the record has no request.method`);
|
|
446
|
+
case 'http.request.uri': return this.pathField(name, path => path + record.search);
|
|
447
|
+
case 'http.request.uri.path': return this.pathField(name, path => path);
|
|
448
|
+
case 'http.request.full_uri': return this.pathField(name, path => record.origin + path + record.search);
|
|
449
|
+
case 'http.request.uri.path.extension': return this.pathField(name, pathExtension);
|
|
450
|
+
case 'http.request.uri.path.basename': return this.pathField(name, pathBasename);
|
|
451
|
+
case 'raw.http.request.uri': return record.rawPath + record.search;
|
|
452
|
+
case 'raw.http.request.uri.path': return record.rawPath;
|
|
453
|
+
case 'raw.http.request.full_uri': return record.origin + record.rawPath + record.search;
|
|
454
|
+
case 'raw.http.request.uri.query': return record.search.slice(1);
|
|
455
|
+
case 'raw.http.request.uri.path.extension': return pathExtension(record.rawPath);
|
|
456
|
+
case 'raw.http.request.uri.args.names': return record.queryArgs.map(([argName]) => argName);
|
|
457
|
+
case 'raw.http.request.uri.args.values': return record.queryArgs.map(([, value]) => value);
|
|
458
|
+
case 'ssl': return record.scheme === 'https';
|
|
459
|
+
case 'http.cookie':
|
|
460
|
+
return new UnknownFieldValue(`field '${name}' is unknown: edge records hold only the logged cookies`);
|
|
461
|
+
case 'http.referer': return this.headerText(name, 'referer');
|
|
462
|
+
case 'http.user_agent': return this.headerText(name, 'user-agent');
|
|
463
|
+
case 'http.x_forwarded_for': return this.headerText(name, 'x-forwarded-for');
|
|
464
|
+
case 'http.request.accepted_languages': {
|
|
465
|
+
const value = this.headerText(name, 'accept-language');
|
|
466
|
+
return typeof value === 'string' ? acceptedLanguages(value) : value;
|
|
467
|
+
}
|
|
468
|
+
case 'http.request.timestamp.sec': return record.time?.sec ?? new UnknownFieldValue(`field '${name}' is unknown: the record has no RFC 3339 _time`);
|
|
469
|
+
case 'http.request.timestamp.msec': return record.time?.msec ?? new UnknownFieldValue(`field '${name}' is unknown: the record has no RFC 3339 _time`);
|
|
470
|
+
case 'ip.src': return record.clientIp ?? new UnknownFieldValue(`field '${name}' is unknown: the record has no request.client_ip`);
|
|
471
|
+
case 'cf.ray_id':
|
|
472
|
+
return record.cf.colo ? `${record.rayId}-${record.cf.colo}` : new UnknownFieldValue(`field '${name}' is unknown: the record has no request.cf.colo`);
|
|
473
|
+
// The edge log preset's filter leaves out Workers' subrequests.
|
|
474
|
+
case 'cf.worker.upstream_zone': return '';
|
|
475
|
+
case 'cf.client.bot':
|
|
476
|
+
return record.cf.verifiedBotCategory === undefined ? new UnknownFieldValue(`field '${name}' is unknown: the record has no request.cf`) : undefined;
|
|
477
|
+
case 'cf.edge.client_port':
|
|
478
|
+
return record.clientPort ?? new UnknownFieldValue(`field '${name}' is unknown: the record has no edge.client.src_port`);
|
|
479
|
+
case 'cf.zone.name':
|
|
480
|
+
return record.zoneName ?? new UnknownFieldValue(`field '${name}' is unknown: the record has no edge.zone`);
|
|
481
|
+
case 'cf.timings.client_tcp_rtt_msec':
|
|
482
|
+
return this.tcpRtt(name);
|
|
483
|
+
default:
|
|
484
|
+
return undefined;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
map(name, ctx) {
|
|
488
|
+
switch (name) {
|
|
489
|
+
case 'http.request.headers':
|
|
490
|
+
case 'raw.http.request.headers':
|
|
491
|
+
return this.headerMap(name, ctx);
|
|
492
|
+
case 'http.request.cookies':
|
|
493
|
+
return this.cookieMap(name, ctx);
|
|
494
|
+
case 'raw.http.request.uri.args':
|
|
495
|
+
return queryArgMapValue(this.record.queryArgMap);
|
|
496
|
+
default:
|
|
497
|
+
return undefined;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* The engine's header list holds Host and the headers the client sent,
|
|
502
|
+
* which the record holds when logged. Their places are unknown, and so are
|
|
503
|
+
* the headers the zone did not log, X-Forwarded-Proto among them:
|
|
504
|
+
* Cloudflare adds it, but not to the request it rebuilds on a challenge
|
|
505
|
+
* solve.
|
|
506
|
+
*/
|
|
507
|
+
headerArray(name, part, ctx) {
|
|
508
|
+
const { record } = this;
|
|
509
|
+
const raw = name.startsWith('raw.');
|
|
510
|
+
const protocol = record.cf.httpProtocol;
|
|
511
|
+
const keys = this.listedHeaderKeys();
|
|
512
|
+
const elements = keys.map((key) => {
|
|
513
|
+
if (part === 'values') {
|
|
514
|
+
// The record holds every listed key but Host and Cookie.
|
|
515
|
+
const value = record.headers.get(key);
|
|
516
|
+
return value !== undefined ? known(value) : unknownElement(name, key === 'host' ? HOST_HEADER_UNKNOWN : COOKIE_HEADER_UNKNOWN, ctx);
|
|
517
|
+
}
|
|
518
|
+
const spelling = headerNameSpelling(key, protocol, raw);
|
|
519
|
+
return spelling === undefined
|
|
520
|
+
? unknownElement(name, `request header names are unknown in edge records over ${protocol || 'an unknown protocol'}, where Cloudflare keeps the client's spelling`, ctx)
|
|
521
|
+
: known(spelling);
|
|
522
|
+
});
|
|
523
|
+
return known(PartialArrayValue.from(elements, this.unloggedHeaders(name, ctx)));
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Evaluates a condition with each reading of what the record leaves open:
|
|
527
|
+
* each normalized path, if it read one, and each logged header and cookie
|
|
528
|
+
* the record lacks, if it read some, as not sent and as sent empty. Its
|
|
529
|
+
* outcome is known where every reading agrees. Past EITHER_WAY_LIMIT
|
|
530
|
+
* values, it stops, and the outcome is unknown.
|
|
531
|
+
*/
|
|
532
|
+
eitherWay(evaluate, ctx) {
|
|
533
|
+
const paths = this.paths && this.paths.length > 1 ? this.paths.map(path => [path]) : [this.paths];
|
|
534
|
+
const read = new Set();
|
|
535
|
+
const base = evaluate(this.reading(ctx, paths[0], NONE, read, ctx.warnings));
|
|
536
|
+
let pathRead = read.delete(PATH);
|
|
537
|
+
const keys = [...read];
|
|
538
|
+
for (;;) {
|
|
539
|
+
const pathCount = pathRead ? paths.length : 1;
|
|
540
|
+
if (keys.length === 0 && pathCount === 1)
|
|
541
|
+
return { outcome: base, overLimit: false };
|
|
542
|
+
if (keys.length > EITHER_WAY_LIMIT)
|
|
543
|
+
return { outcome: this.undecided(keys, false, ctx), overLimit: true };
|
|
544
|
+
// A reading that reaches a value the first did not, such as past a short-circuit, adds that value's
|
|
545
|
+
// readings, and they start again.
|
|
546
|
+
const reached = new Set();
|
|
547
|
+
/** By path, then by the keys taken as sent empty. */
|
|
548
|
+
const outcomes = [];
|
|
549
|
+
readings: for (let pathIndex = 0; pathIndex < pathCount; pathIndex++) {
|
|
550
|
+
const row = [];
|
|
551
|
+
outcomes.push(row);
|
|
552
|
+
for (let mask = 0; mask < 1 << keys.length; mask++) {
|
|
553
|
+
if (pathIndex === 0 && mask === 0) {
|
|
554
|
+
row.push(base);
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
const variantRead = new Set();
|
|
558
|
+
const sentEmpty = new Set(keys.filter((_, index) => mask & (1 << index)));
|
|
559
|
+
const outcome = evaluate(this.reading(ctx, paths[pathIndex], sentEmpty, variantRead, new Set()));
|
|
560
|
+
if (variantRead.delete(PATH) && pathCount < paths.length)
|
|
561
|
+
reached.add(PATH);
|
|
562
|
+
for (const key of variantRead)
|
|
563
|
+
if (!keys.includes(key))
|
|
564
|
+
reached.add(key);
|
|
565
|
+
if (reached.size > 0)
|
|
566
|
+
break readings;
|
|
567
|
+
if (!sameOutcome(outcome, base)) {
|
|
568
|
+
if (isUnknown(base) && base.cause.kind === 'incomparable')
|
|
569
|
+
return { outcome: base, overLimit: false };
|
|
570
|
+
if (isUnknown(outcome) && outcome.cause.kind === 'incomparable')
|
|
571
|
+
return { outcome, overLimit: false };
|
|
572
|
+
}
|
|
573
|
+
row.push(outcome);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
if (reached.size === 0) {
|
|
577
|
+
// The path matters where the same keys sent empty give another outcome on another path, and the keys
|
|
578
|
+
// where they give another outcome on the same path.
|
|
579
|
+
const first = outcomes[0];
|
|
580
|
+
const pathMatters = outcomes.some(row => row.some((outcome, mask) => !sameOutcome(outcome, first[mask])));
|
|
581
|
+
const sentEmptyMatters = outcomes.some(row => row.some(outcome => !sameOutcome(outcome, row[0])));
|
|
582
|
+
const outcome = pathMatters || sentEmptyMatters ? this.undecided(sentEmptyMatters ? keys : [], pathMatters, ctx) : base;
|
|
583
|
+
return { outcome, overLimit: false };
|
|
584
|
+
}
|
|
585
|
+
pathRead ||= reached.delete(PATH);
|
|
586
|
+
keys.push(...reached);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
reading(ctx, paths, sentEmpty, read, warnings) {
|
|
590
|
+
return { ...ctx, edge: new EdgeRecordFields(this.record, paths, this.pathRewrittenBy, sentEmpty, read), warnings };
|
|
591
|
+
}
|
|
592
|
+
/** A condition that depends on what the record leaves open: the normalized path, or logged values sent empty. */
|
|
593
|
+
undecided(keys, pathMatters, ctx) {
|
|
594
|
+
const names = keys.map((key) => {
|
|
595
|
+
const separator = key.indexOf(':');
|
|
596
|
+
return `${key.slice(0, separator) === 'header' ? 'request header' : 'cookie'} '${key.slice(separator + 1)}'`;
|
|
597
|
+
});
|
|
598
|
+
if (names.length > 0) {
|
|
599
|
+
ctx.warnings.add(`${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} logged but not in the record, so not sent or sent empty, and a condition depends on which`);
|
|
600
|
+
}
|
|
601
|
+
if (pathMatters) {
|
|
602
|
+
const path = JSON.stringify(this.record.rawPath);
|
|
603
|
+
ctx.warnings.add(this.record.urlNormalization
|
|
604
|
+
? `a condition depends on the order of Cloudflare's URL normalization steps, which was not observed, for path ${path}`
|
|
605
|
+
: `a condition depends on the zone's URL normalization, which was not given, for path ${path}`);
|
|
606
|
+
}
|
|
607
|
+
return unavailable(pathMatters ? fieldSource('http.request.uri.path') : names[0]);
|
|
608
|
+
}
|
|
609
|
+
/** Whether this reading takes a logged header or cookie the record lacks as sent empty. */
|
|
610
|
+
isSentEmpty(key) {
|
|
611
|
+
this.read.add(key);
|
|
612
|
+
return this.sentEmpty.has(key);
|
|
613
|
+
}
|
|
614
|
+
pathField(name, read) {
|
|
615
|
+
const { paths, record } = this;
|
|
616
|
+
if (this.pathRewrittenBy) {
|
|
617
|
+
return new UnknownFieldValue(`field '${name}' is unknown: rewrite rule ${this.pathRewrittenBy} ran after the route's rewrite and may have set the path`);
|
|
618
|
+
}
|
|
619
|
+
this.read.add(PATH);
|
|
620
|
+
const path = JSON.stringify(record.rawPath);
|
|
621
|
+
if (!paths)
|
|
622
|
+
return new UnknownFieldValue(`field '${name}' is unknown: how Cloudflare normalizes path ${path} was not observed`);
|
|
623
|
+
const value = read(paths[0]);
|
|
624
|
+
if (paths.every(other => read(other) === value))
|
|
625
|
+
return value;
|
|
626
|
+
return new UnknownFieldValue(record.urlNormalization
|
|
627
|
+
? `field '${name}' is unknown: the order of Cloudflare's URL normalization steps, which was not observed, changes path ${path}`
|
|
628
|
+
: `field '${name}' is unknown: the zone's URL normalization, which was not given, would change path ${path}`);
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* The engine's TCP round-trip time: 0 over HTTP/3, and over TCP the
|
|
632
|
+
* record's plus 1, as a Worker's is (test/fixtures/edge-record-probes.json).
|
|
633
|
+
*/
|
|
634
|
+
tcpRtt(name) {
|
|
635
|
+
const { record } = this;
|
|
636
|
+
const protocol = record.cf.httpProtocol;
|
|
637
|
+
if (protocol === 'HTTP/3')
|
|
638
|
+
return 0;
|
|
639
|
+
if (!protocol)
|
|
640
|
+
return new UnknownFieldValue(`field '${name}' is unknown: the record has no request.cf.httpProtocol`);
|
|
641
|
+
if (record.tcpRttMs === undefined)
|
|
642
|
+
return new UnknownFieldValue(`field '${name}' is unknown: the record has no edge.client.tcp_rtt_ms`);
|
|
643
|
+
if (record.tcpRttMs === 0)
|
|
644
|
+
return new UnknownFieldValue(`field '${name}' is unknown when the record's TCP RTT is 0, which may mean under 1 ms or not measured`);
|
|
645
|
+
return record.tcpRttMs + 1;
|
|
646
|
+
}
|
|
647
|
+
/** A header's value as a scalar field reads it, which is empty both for a header sent empty and one not sent. */
|
|
648
|
+
headerText(name, key) {
|
|
649
|
+
const value = this.record.headers.get(key);
|
|
650
|
+
if (value !== undefined)
|
|
651
|
+
return value;
|
|
652
|
+
if (this.record.loggedHeaders.has(key))
|
|
653
|
+
return '';
|
|
654
|
+
return new UnknownFieldValue(`field '${name}' is unknown: request header '${key}' is unknown: ${this.unloggedHeaderReason(key)}`);
|
|
655
|
+
}
|
|
656
|
+
/** Why a request header the record does not hold as logged raw is unknown. */
|
|
657
|
+
unloggedHeaderReason(key) {
|
|
658
|
+
if (this.record.transformedHeaders.has(key))
|
|
659
|
+
return 'the zone logs it transformed, as the origin received it';
|
|
660
|
+
if (this.record.ambiguousHeaders.has(key))
|
|
661
|
+
return `flattened, cookie '${key.slice('cookie.'.length)}', which the zone logs too, has its key`;
|
|
662
|
+
return 'the zone did not log it';
|
|
663
|
+
}
|
|
664
|
+
/** The engine's header keys that the record shows: Host, Cookie, and the logged headers it holds. */
|
|
665
|
+
listedHeaderKeys() {
|
|
666
|
+
const keys = new Set(['host', ...this.record.headers.keys()]);
|
|
667
|
+
if (this.record.cookieSent)
|
|
668
|
+
keys.add('cookie');
|
|
669
|
+
return [...keys];
|
|
670
|
+
}
|
|
671
|
+
headerMap(name, ctx) {
|
|
672
|
+
const keys = mapKeys(this.listedHeaderKeys());
|
|
673
|
+
return new RuleMapValue(key => this.headerLookup(name, key, ctx), () => keys, this.unloggedHeaders(name, ctx));
|
|
674
|
+
}
|
|
675
|
+
headerLookup(name, key, ctx) {
|
|
676
|
+
const { record } = this;
|
|
677
|
+
const value = record.headers.get(key);
|
|
678
|
+
if (value !== undefined)
|
|
679
|
+
return known([value]);
|
|
680
|
+
// The engine's keys are lowercase.
|
|
681
|
+
if (key !== key.toLowerCase())
|
|
682
|
+
return known(null);
|
|
683
|
+
const source = `${name}[${renderRuleExpressionStringLiteral(key)}]`;
|
|
684
|
+
if (key === 'cookie') {
|
|
685
|
+
const unknown = unknownElement(source, COOKIE_HEADER_UNKNOWN, ctx);
|
|
686
|
+
// A cookie in the record shows the client sent the header.
|
|
687
|
+
return record.cookieSent ? known(PartialArrayValue.from([unknown], unknown)) : unknown;
|
|
688
|
+
}
|
|
689
|
+
// The engine holds one Host value.
|
|
690
|
+
if (key === 'host')
|
|
691
|
+
return known(PartialArrayValue.from([unknownElement(source, HOST_HEADER_UNKNOWN, ctx)]));
|
|
692
|
+
if (key === 'x-forwarded-proto')
|
|
693
|
+
return unknownElement(source, "request header 'x-forwarded-proto' is unknown: Cloudflare sets it, but not on a challenge solve, and the record does not hold it", ctx);
|
|
694
|
+
if (record.loggedHeaders.has(key))
|
|
695
|
+
return known(this.isSentEmpty(`header:${key}`) ? [''] : null);
|
|
696
|
+
return unknownElement(source, `request header '${key}' is unknown: ${this.unloggedHeaderReason(key)}`, ctx);
|
|
697
|
+
}
|
|
698
|
+
unloggedHeaders(name, ctx) {
|
|
699
|
+
return unknownElement(name, 'request headers the zone did not log are unknown', ctx);
|
|
700
|
+
}
|
|
701
|
+
cookieMap(name, ctx) {
|
|
702
|
+
const { record } = this;
|
|
703
|
+
const keys = mapKeys(record.cookies.keys());
|
|
704
|
+
return new RuleMapValue(cookie => {
|
|
705
|
+
const value = record.cookies.get(cookie);
|
|
706
|
+
if (value !== undefined)
|
|
707
|
+
return known([value]);
|
|
708
|
+
const source = `${name}[${renderRuleExpressionStringLiteral(cookie)}]`;
|
|
709
|
+
if (record.ambiguousCookies.has(cookie)) {
|
|
710
|
+
const header = `cookie.${cookie.toLowerCase()}`;
|
|
711
|
+
return unknownElement(source, record.ambiguousHeaders.has(header)
|
|
712
|
+
? `cookie '${cookie}' is unknown: flattened, request header '${header}', which the zone logs too, has its key`
|
|
713
|
+
: `cookie '${cookie}' is unknown: a logged cookie whose name differs only in case shares its record key`, ctx);
|
|
714
|
+
}
|
|
715
|
+
if (record.unnamedCookies.has(cookie.toLowerCase())) {
|
|
716
|
+
const reason = record.assumedLoggedFields ? 'the logged cookies were not given' : `the logged cookies do not name '${cookie.toLowerCase()}'`;
|
|
717
|
+
return unknownElement(source, `cookie '${cookie}' is unknown: ${reason}, and the record keys a cookie by its name in lowercase`, ctx);
|
|
718
|
+
}
|
|
719
|
+
if (record.loggedCookies.has(cookie))
|
|
720
|
+
return known(this.isSentEmpty(`cookie:${cookie}`) ? [''] : null);
|
|
721
|
+
return unknownElement(source, `cookie '${cookie}' is unknown: the zone did not log it`, ctx);
|
|
722
|
+
}, () => keys, unknownElement(name, 'cookies the zone did not log are unknown', ctx));
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* The engine's spelling of a header name, where the protocol fixes it, as
|
|
727
|
+
* request-headers.ts lays out each protocol's list: lowercase over HTTP/2 and
|
|
728
|
+
* HTTP/3, but for the headers the engine places itself, and the client's
|
|
729
|
+
* spelling over HTTP/1. Over HTTP/3, the raw names spelled X-Forwarded-Proto
|
|
730
|
+
* in lowercase on a challenged request, and in title case otherwise.
|
|
731
|
+
*/
|
|
732
|
+
function headerNameSpelling(key, protocol, raw) {
|
|
733
|
+
switch (protocol) {
|
|
734
|
+
case 'HTTP/3':
|
|
735
|
+
return key === 'x-forwarded-proto' && raw ? undefined : key;
|
|
736
|
+
case 'HTTP/2':
|
|
737
|
+
return HTTP2_PLACED_NAMES.get(key) ?? key;
|
|
738
|
+
case 'HTTP/1.0':
|
|
739
|
+
case 'HTTP/1.1':
|
|
740
|
+
return HTTP1_PLACED_NAMES.get(key);
|
|
741
|
+
default:
|
|
742
|
+
return undefined;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
const HTTP2_PLACED_NAMES = new Map([
|
|
746
|
+
['content-length', 'Content-Length'],
|
|
747
|
+
['host', 'Host'],
|
|
748
|
+
['x-forwarded-proto', 'X-Forwarded-Proto'],
|
|
749
|
+
]);
|
|
750
|
+
// Listed without a spread, which bundlers would keep in Workers that never use it.
|
|
751
|
+
const HTTP1_PLACED_NAMES = new Map([
|
|
752
|
+
['content-length', 'Content-Length'],
|
|
753
|
+
['host', 'Host'],
|
|
754
|
+
['x-forwarded-proto', 'X-Forwarded-Proto'],
|
|
755
|
+
['connection', 'Connection'],
|
|
756
|
+
['upgrade', 'Upgrade'],
|
|
757
|
+
]);
|
|
758
|
+
const HOST_HEADER_UNKNOWN = "request header 'host' is unknown: the record holds the host in lowercase, and the rules engine reads the header as sent";
|
|
759
|
+
const COOKIE_HEADER_UNKNOWN = "request header 'cookie' is unknown: edge records hold only the logged cookies";
|
|
760
|
+
function unknownElement(source, reason, ctx) {
|
|
761
|
+
return () => {
|
|
762
|
+
ctx.warnings.add(reason);
|
|
763
|
+
return unavailable(fieldSource(source));
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
function sameOutcome(left, right) {
|
|
767
|
+
if (!isUnknown(left) || !isUnknown(right))
|
|
768
|
+
return left === right;
|
|
769
|
+
return (left.cause.kind === 'incomparable') === (right.cause.kind === 'incomparable');
|
|
770
|
+
}
|
|
771
|
+
//# sourceMappingURL=edge-record.js.map
|