Diffinery

homeflare/celldpublic

celld/crates/celld/js/headers.js
338 lines · 12.3 KBRaw History
1const _tokenRe = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
2// Token validation is memoized by name: a Worker sends the same handful of
3// header names on every subrequest, so the regex would run once per header
4// per request forever. The cache is a null-prototype object because the key
5// is an attacker-controlled header name -- see the note on `_newList` -- and it
6// is emptied wholesale at a bound so a caller that invents a fresh name per
7// request cannot grow it without limit.
8let _nameCache = { __proto__: null };
9let _nameCacheSize = 0;
10const _nameCacheMax = 4096;
11function _checkName(name) {
12 name = String(name);
13 let valid = _nameCache[name];
14 if (valid === undefined) {
15 valid = _tokenRe.test(name);
16 if (_nameCacheSize > _nameCacheMax) {
17 _nameCache = { __proto__: null };
18 _nameCacheSize = 0;
19 }
20 _nameCacheSize++;
21 _nameCache[name] = valid;
22 }
23 if (!valid)
24 throw new TypeError(
25 "Invalid header name: " + name);
26 // The name is returned as written. Lower-casing here would put celld's
27 // spelling on the wire instead of the author's, which anything that
28 // canonicalizes over the received bytes can see -- an AWS SigV4 signer
29 // over `SignedHeaders` being the case that breaks.
30 return name;
31}
32// Only a validated token reaches this, and the token production is ASCII, so
33// `toLowerCase` cannot fold a name onto a different one here.
34function _lower(name) {
35 return name.toLowerCase();
36}
37// Byte sequence, minus NUL/LF/CR. Strip HTTP
38// whitespace (HT/LF/CR/SP) from both ends first per
39// WHATWG fetch -- trailing LF/CR are permitted input.
40function _checkValue(value) {
41 value = String(value).replace(
42 /^[\t\n\r ]+|[\t\n\r ]+$/g, '');
43 for (let i = 0; i < value.length; i++) {
44 const c = value.charCodeAt(i);
45 if (c === 0 || c === 0x0A || c === 0x0D
46 || c > 0xFF)
47 throw new TypeError(
48 "Invalid header value");
49 }
50 return value;
51}
52
53// Enumerable function-valued brand, shared by
54// every instance: V8's structured clone throws
55// on functions, so a Headers can never silently
56// flatten into a plain object -- RPC
57// serialization lifts it natively instead.
58const _noClone = () => {};
59
60// The spec's header list, plus the sorted pair list derived from it.
61//
62// `list` is a flat array of `[name, value]` pairs in insertion order, with
63// each name exactly as it was written. `lower` is a parallel array holding
64// the lower-cased form of `list[i][0]`, and it exists only so a comparison
65// never lower-cases a name again. Both arrays are always mutated together --
66// an entry with no matching `lower` slot would silently stop being findable.
67//
68// Two things forced this shape over a name-keyed structure. First, the list
69// is what goes on the wire, and only a list can carry the author's casing,
70// insertion order, and repeats. Second, header names are attacker-controlled
71// and the token production admits `_`, so `__proto__` and `constructor` are
72// valid names: a plain object keyed by a name answered both out of
73// `Object.prototype`, which made `has("constructor")` true for a header
74// nobody sent and turned the first `request.headers` read of a request
75// carrying a `__proto__:` header into a TypeError. An array holds no such
76// key, so the casing fix and the prototype fix are the same change. The
77// `Map` this replaces fixed only the second one.
78//
79// `pairs` is the memo the iterator reads. Every mutator clears it, so a step
80// after a mutation re-derives the list and iteration stays live, while an
81// unmutated iteration sorts once instead of once per step.
82function _newList() {
83 return { list: [], lower: [], pairs: null };
84}
85
86// The iteration view, which is not the list: lower-cased, combined, and
87// sorted by name, with `set-cookie` split one entry per value.
88function _pairs(state) {
89 if (state.pairs !== null) return state.pairs;
90 const pairs = [];
91 // Combining by a single pass needs a name-keyed index. A null-prototype
92 // object is the only name-keyed object allowed here, for the reason on
93 // `_newList` -- `seen["constructor"]` must be undefined, not a function.
94 const seen = { __proto__: null };
95 for (let i = 0; i < state.list.length; i++) {
96 const name = state.lower[i];
97 const value = state.list[i][1];
98 // Only `set-cookie` keeps its values apart; every other name joins.
99 if (name === "set-cookie") {
100 pairs.push([name, value]);
101 continue;
102 }
103 const at = seen[name];
104 if (at !== undefined) {
105 pairs[at][1] += ", " + value;
106 } else {
107 seen[name] = pairs.length;
108 pairs.push([name, value]);
109 }
110 }
111 // Stable, so repeated `set-cookie` values stay in insertion order.
112 pairs.sort((a, b) =>
113 a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
114 state.pairs = pairs;
115 return pairs;
116}
117
118class Headers {
119 #list = _newList();
120
121 #checkMutable() {
122 if (this._immutable)
123 throw new TypeError("Can't modify immutable headers.");
124 }
125
126 #push(name, v) {
127 const state = this.#list;
128 const lower = _lower(name);
129 // A repeated name takes the casing already in the list, per the WHATWG
130 // "header list append" operation, which reuses the name of the first
131 // matching header, so one header never reaches the wire under two
132 // spellings.
133 for (let i = 0; i < state.lower.length; i++) {
134 if (state.lower[i] === lower) {
135 name = state.list[i][0];
136 break;
137 }
138 }
139 state.list.push([name, v]);
140 state.lower.push(lower);
141 state.pairs = null;
142 }
143
144 constructor(init) {
145 this.__celldHost = _noClone;
146 if (init === undefined) return;
147 if (init === null || typeof init !== "object")
148 throw new TypeError("Invalid Headers init");
149 // Sequence-like (includes Headers with its default
150 // iterator or any user-overridden one) takes precedence
151 // over record so custom iterators are honored.
152 if (typeof init[Symbol.iterator] === "function") {
153 for (const pair of init) {
154 if (!pair || typeof pair !== "object"
155 || pair.length !== 2)
156 throw new TypeError(
157 "Headers init entry must be a 2-tuple");
158 this.append(pair[0], pair[1]);
159 }
160 } else {
161 // Record: explicit Reflect walk so Proxy handlers
162 // see the WebIDL es-to-record trace exactly --
163 // ownKeys -> for each key, getOwnPropertyDescriptor;
164 // if enumerable, coerce key to ByteString (throws
165 // for Symbols), then [[Get]], then validate value.
166 for (const k of Reflect.ownKeys(init)) {
167 const desc = Reflect
168 .getOwnPropertyDescriptor(init, k);
169 if (!desc || !desc.enumerable) continue;
170 if (typeof k === "symbol")
171 throw new TypeError(
172 "Headers init key must be a string");
173 const ck = _checkName(k);
174 const v = Reflect.get(init, k, init);
175 const cv = _checkValue(v);
176 this.#push(ck, cv);
177 }
178 }
179 }
180
181 append(name, value) {
182 this.#checkMutable();
183 const k = _checkName(name);
184 const v = _checkValue(value);
185 this.#push(k, v);
186 }
187 get(name) {
188 const lower = _lower(_checkName(name));
189 const state = this.#list;
190 let value = null;
191 for (let i = 0; i < state.lower.length; i++) {
192 if (state.lower[i] !== lower) continue;
193 value = value === null ? state.list[i][1]
194 : value + ", " + state.list[i][1];
195 }
196 return value;
197 }
198 set(name, value) {
199 this.#checkMutable();
200 name = _checkName(name);
201 const v = _checkValue(value);
202 const lower = _lower(name);
203 const state = this.#list;
204 // Compact in place: the first match takes the new value and keeps its
205 // position and its casing, every later match is dropped. Rebuilding the
206 // list instead would move the header to the end.
207 let writeIdx = 0;
208 let added = false;
209 for (let i = 0; i < state.lower.length; i++) {
210 if (state.lower[i] === lower) {
211 if (added) continue;
212 const entry = state.list[i];
213 entry[1] = v;
214 state.list[writeIdx] = entry;
215 added = true;
216 } else {
217 state.list[writeIdx] = state.list[i];
218 }
219 state.lower[writeIdx] = state.lower[i];
220 writeIdx++;
221 }
222 if (!added) {
223 state.list.push([name, v]);
224 state.lower.push(lower);
225 } else if (writeIdx !== state.list.length) {
226 state.list.length = writeIdx;
227 state.lower.length = writeIdx;
228 }
229 state.pairs = null;
230 }
231 has(name) {
232 const lower = _lower(_checkName(name));
233 return this.#list.lower.includes(lower);
234 }
235 delete(name) {
236 this.#checkMutable();
237 const lower = _lower(_checkName(name));
238 const state = this.#list;
239 let writeIdx = 0;
240 for (let i = 0; i < state.lower.length; i++) {
241 if (state.lower[i] === lower) continue;
242 state.list[writeIdx] = state.list[i];
243 state.lower[writeIdx] = state.lower[i];
244 writeIdx++;
245 }
246 if (writeIdx === state.list.length) return;
247 state.list.length = writeIdx;
248 state.lower.length = writeIdx;
249 state.pairs = null;
250 }
251 getSetCookie() {
252 const state = this.#list;
253 const out = [];
254 for (let i = 0; i < state.lower.length; i++)
255 if (state.lower[i] === "set-cookie")
256 out.push(state.list[i][1]);
257 return out;
258 }
259 // The verbatim header list every outbound path serializes: insertion
260 // order, original casing, one entry per append. The iteration view above
261 // is lossy for a wire request -- it lower-cases, sorts, and combines -- so
262 // this is a second, deliberately different view, not a convenience.
263 //
264 // A class accessor, so it is non-enumerable and a record walk over a
265 // `Headers` never picks it up. Fresh pairs, so a caller that writes into
266 // what it received cannot rewrite the header list or desynchronize it
267 // from the parallel lower-cased names.
268 get __celldHeaderList() {
269 const list = this.#list.list;
270 const out = new Array(list.length);
271 for (let i = 0; i < list.length; i++)
272 out[i] = [list[i][0], list[i][1]];
273 return out;
274 }
275 // Iteration: per WHATWG the header list stays live,
276 // so each step reads the current list -- see the
277 // `pairs` memo above. Uses a hand-rolled iterator so
278 // `next` has enumerable=true per WebIDL (generators
279 // would be enumerable=false).
280 entries() { return _makeHeadersIter(this.#list, 2); }
281 keys() { return _makeHeadersIter(this.#list, 0); }
282 values() { return _makeHeadersIter(this.#list, 1); }
283 [Symbol.iterator]() { return this.entries(); }
284 forEach(cb, thisArg) {
285 if (typeof cb !== "function")
286 throw new TypeError(
287 "forEach callback must be a function");
288 for (const [k, v] of this.entries())
289 cb.call(thisArg, v, k, this);
290 }
291}
292
293// Headers iterator prototype -- chained to
294// %IteratorPrototype% so prototype-chain checks pass.
295// kind: 0=keys, 1=values, 2=entries.
296const _headersIterProto = Object.create(
297 Object.getPrototypeOf(
298 Object.getPrototypeOf([][Symbol.iterator]())));
299Object.defineProperty(_headersIterProto, "next", {
300 configurable: true, enumerable: true, writable: true,
301 value: function next() {
302 // The index into the current pair list is all the
303 // iterator carries, so a name added after the
304 // cursor is emitted and a name deleted before it
305 // shifts the rest back -- the WHATWG live-list
306 // semantics the plain-object version also had.
307 const pairs = _pairs(this._list);
308 if (this._cnt >= pairs.length)
309 return { value: undefined, done: true };
310 const [k, v] = pairs[this._cnt++];
311 // A fresh pair per step: `pairs` outlives the step
312 // now, so handing the memo's array to a caller
313 // would let the caller rewrite the header list.
314 const value = this._kind === 0 ? k
315 : this._kind === 1 ? v : [k, v];
316 return { value, done: false };
317 },
318});
319Object.defineProperty(_headersIterProto,
320 Symbol.iterator, { value() { return this; } });
321function _makeHeadersIter(list, kind) {
322 const it = Object.create(_headersIterProto);
323 it._list = list; it._cnt = 0; it._kind = kind;
324 return it;
325}
326
327// Coerce a Request/Response body init to one of the
328// `BodyInit` member types or null. Pre-fix
329// `new Request(url, {body: 42})` stored 42 as the
330// body and then `.text()` ran TextDecoder on it,
331// producing 42 NUL bytes (V8 interprets a number
332// passed to TextDecoder.decode as a BufferSource of
333// that byte length). Per Web IDL union conversion,
334// the BodyInit dictionary member's USVString branch
335// accepts any non-BodyInit value via ToString. Match
336// that here so primitives go through cleanly.
337
338globalThis.Headers = Headers;