-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathrequest.ts
More file actions
434 lines (399 loc) · 12.5 KB
/
Copy pathrequest.ts
File metadata and controls
434 lines (399 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/* eslint-disable @typescript-eslint/no-explicit-any */
// Define prototype for lightweight pseudo Request object
import type { IncomingMessage } from 'node:http'
import { Http2ServerRequest } from 'node:http2'
import { Readable } from 'node:stream'
import type { ReadableStreamDefaultReader } from 'node:stream/web'
import type { TLSSocket } from 'node:tls'
export class RequestError extends Error {
constructor(
message: string,
options?: {
cause?: unknown
}
) {
super(message, options)
this.name = 'RequestError'
}
}
export const toRequestError = (e: unknown): RequestError => {
if (e instanceof RequestError) {
return e
}
return new RequestError((e as Error).message, { cause: e })
}
export const GlobalRequest = global.Request
export class Request extends GlobalRequest {
constructor(input: string | Request, options?: RequestInit) {
if (typeof input === 'object' && getRequestCache in input) {
input = (input as any)[getRequestCache]()
}
// Check if body is ReadableStream like. This makes it compatbile with ReadableStream polyfills.
if (typeof (options?.body as ReadableStream)?.getReader !== 'undefined') {
// node 18 fetch needs half duplex mode when request body is stream
// if already set, do nothing since a Request object was passed to the options or explicitly set by the user.
;(options as any).duplex ??= 'half'
}
super(input, options)
}
}
const newHeadersFromIncoming = (incoming: IncomingMessage | Http2ServerRequest) => {
const headerRecord: [string, string][] = []
const rawHeaders = incoming.rawHeaders
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders
if (key.charCodeAt(0) !== /*:*/ 0x3a) {
headerRecord.push([key, value])
}
}
return new Headers(headerRecord)
}
export type IncomingMessageWithWrapBodyStream = IncomingMessage & { [wrapBodyStream]: boolean }
export const wrapBodyStream = Symbol('wrapBodyStream')
const newRequestFromIncoming = (
method: string,
url: string,
headers: Headers,
incoming: IncomingMessage | Http2ServerRequest,
abortController: AbortController
): Request => {
const init = {
method: method,
headers,
signal: abortController.signal,
} as RequestInit
if (method === 'TRACE') {
init.method = 'GET'
const req = new Request(url, init)
Object.defineProperty(req, 'method', {
get() {
return 'TRACE'
},
})
return req
}
if (!(method === 'GET' || method === 'HEAD')) {
if ('rawBody' in incoming && incoming.rawBody instanceof Buffer) {
// In some environments (e.g. firebase functions), the body is already consumed.
// So we need to re-read the request body from `incoming.rawBody` if available.
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody)
controller.close()
},
})
} else if ((incoming as IncomingMessageWithWrapBodyStream)[wrapBodyStream]) {
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= Readable.toWeb(incoming).getReader()
const { done, value } = await reader.read()
if (done) {
controller.close()
} else {
controller.enqueue(value)
}
} catch (error) {
controller.error(error)
}
},
})
} else {
// lazy-consume request body
init.body = Readable.toWeb(incoming) as ReadableStream<Uint8Array>
}
}
return new Request(url, init)
}
const getRequestCache = Symbol('getRequestCache')
const requestCache = Symbol('requestCache')
const incomingKey = Symbol('incomingKey')
const urlKey = Symbol('urlKey')
const headersKey = Symbol('headersKey')
export const abortControllerKey = Symbol('abortControllerKey')
export const getAbortController = Symbol('getAbortController')
const bodyBufferKey = Symbol('bodyBuffer')
const readBodyDirect = (incoming: IncomingMessage | Http2ServerRequest): Promise<Buffer> => {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = []
incoming.on('data', (chunk: Buffer) => chunks.push(chunk))
incoming.on('end', () => resolve(chunks.length === 1 ? chunks[0] : Buffer.concat(chunks)))
incoming.on('error', reject)
})
}
const requestPrototype: Record<string | symbol, any> = {
get method() {
return this[incomingKey].method || 'GET'
},
get url() {
return this[urlKey]
},
get headers() {
return (this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]))
},
[getAbortController]() {
this[getRequestCache]()
return this[abortControllerKey]
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController()
if (this[requestCache]) {
return this[requestCache]
}
// If body was already read directly, use cached buffer instead of re-reading stream
const incoming = this[incomingKey]
if (this[bodyBufferKey] && !(incoming.method === 'GET' || incoming.method === 'HEAD')) {
const buf = this[bodyBufferKey] as Buffer
const init = {
method: incoming.method,
headers: this.headers,
signal: this[abortControllerKey].signal,
body: new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(buf))
controller.close()
},
}),
} as RequestInit
;(init as any).duplex = 'half'
return (this[requestCache] = new Request(this[urlKey], init))
}
return (this[requestCache] = newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
))
},
}
;[
'body',
'bodyUsed',
'cache',
'credentials',
'destination',
'integrity',
'mode',
'redirect',
'referrer',
'referrerPolicy',
'signal',
'keepalive',
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k]
},
})
})
;['clone', 'formData'].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function () {
return this[getRequestCache]()[k]()
},
})
})
// Direct body reading: bypass getRequestCache() → new AbortController() → newHeadersFromIncoming()
// → new Request(url, init) → Readable.toWeb() chain. Read directly from Node.js IncomingMessage.
Object.defineProperty(requestPrototype, 'text', {
value: function (): Promise<string> {
if (this[requestCache]) {
return this[requestCache].text()
}
const incoming = this[incomingKey] as IncomingMessage | Http2ServerRequest
if (incoming.method === 'GET' || incoming.method === 'HEAD') {
return Promise.resolve('')
}
if ('rawBody' in incoming && (incoming as any).rawBody instanceof Buffer) {
return Promise.resolve((incoming as any).rawBody.toString())
}
return readBodyDirect(incoming).then((buf) => {
this[bodyBufferKey] = buf
return buf.toString()
})
},
})
Object.defineProperty(requestPrototype, 'json', {
value: function (): Promise<any> {
if (this[requestCache]) {
return this[requestCache].json()
}
return this.text().then(JSON.parse)
},
})
Object.defineProperty(requestPrototype, 'arrayBuffer', {
value: function (): Promise<ArrayBuffer> {
if (this[requestCache]) {
return this[requestCache].arrayBuffer()
}
const incoming = this[incomingKey] as IncomingMessage | Http2ServerRequest
if (incoming.method === 'GET' || incoming.method === 'HEAD') {
return Promise.resolve(new ArrayBuffer(0))
}
if ('rawBody' in incoming && (incoming as any).rawBody instanceof Buffer) {
const raw = (incoming as any).rawBody as Buffer
return Promise.resolve(
raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength) as ArrayBuffer
)
}
return readBodyDirect(incoming).then((buf) => {
this[bodyBufferKey] = buf
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer
})
},
})
Object.defineProperty(requestPrototype, 'blob', {
value: function (): Promise<Blob> {
if (this[requestCache]) {
return this[requestCache].blob()
}
return this.arrayBuffer().then((buf: ArrayBuffer) => new Blob([buf]))
},
})
Object.setPrototypeOf(requestPrototype, Request.prototype)
const isPathDelimiter = (charCode: number): boolean =>
charCode === 0x2f || charCode === 0x3f || charCode === 0x23
// `/.`, `/..` (including `%2e` variants, which are handled by `%` detection) are normalized by `new URL()`.
const hasDotSegment = (url: string, dotIndex: number): boolean => {
const prev = dotIndex === 0 ? 0x2f : url.charCodeAt(dotIndex - 1)
if (prev !== 0x2f) {
return false
}
const nextIndex = dotIndex + 1
if (nextIndex === url.length) {
return true
}
const next = url.charCodeAt(nextIndex)
if (isPathDelimiter(next)) {
return true
}
if (next !== 0x2e) {
return false
}
const nextNextIndex = dotIndex + 2
if (nextNextIndex === url.length) {
return true
}
return isPathDelimiter(url.charCodeAt(nextNextIndex))
}
const allowedRequestUrlChar = new Uint8Array(128)
for (let c = 0x30; c <= 0x39; c++) {
allowedRequestUrlChar[c] = 1
}
for (let c = 0x41; c <= 0x5a; c++) {
allowedRequestUrlChar[c] = 1
}
for (let c = 0x61; c <= 0x7a; c++) {
allowedRequestUrlChar[c] = 1
}
;(() => {
const chars = '-./:?#[]@!$&\'()*+,;=~_'
for (let i = 0; i < chars.length; i++) {
allowedRequestUrlChar[chars.charCodeAt(i)] = 1
}
})()
const safeHostChar = new Uint8Array(128)
// 0-9
for (let c = 0x30; c <= 0x39; c++) {
safeHostChar[c] = 1
}
// a-z
for (let c = 0x61; c <= 0x7a; c++) {
safeHostChar[c] = 1
}
;(() => {
const chars = '.-_'
for (let i = 0; i < chars.length; i++) {
safeHostChar[chars.charCodeAt(i)] = 1
}
})()
export const newRequest = (
incoming: IncomingMessage | Http2ServerRequest,
defaultHostname?: string
) => {
const req = Object.create(requestPrototype)
req[incomingKey] = incoming
const incomingUrl = incoming.url || ''
// handle absolute URL in request.url
if (
incomingUrl[0] !== '/' && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith('http://') || incomingUrl.startsWith('https://'))
) {
if (incoming instanceof Http2ServerRequest) {
throw new RequestError('Absolute URL for :path is not allowed in HTTP/2') // RFC 9113 8.3.1.
}
try {
const url = new URL(incomingUrl)
req[urlKey] = url.href
} catch (e) {
throw new RequestError('Invalid absolute URL', { cause: e })
}
return req
}
// Otherwise, relative URL
const host =
(incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) ||
defaultHostname
if (!host) {
throw new RequestError('Missing host header')
}
let scheme: string
if (incoming instanceof Http2ServerRequest) {
scheme = incoming.scheme
if (!(scheme === 'http' || scheme === 'https')) {
throw new RequestError('Unsupported scheme')
}
} else {
scheme = incoming.socket && (incoming.socket as TLSSocket).encrypted ? 'https' : 'http'
}
req[urlKey] = `${scheme}://${host}${incomingUrl}`
let needsHostValidationByURL = false
for (let i = 0, len = host.length; i < len; i++) {
const c = host.charCodeAt(i)
if (c > 0x7f || safeHostChar[c] === 0) {
needsHostValidationByURL = true
break
}
}
if (needsHostValidationByURL) {
let urlObj: URL
try {
urlObj = new URL(req[urlKey])
} catch (e) {
throw new RequestError('Invalid URL', { cause: e })
}
// if suspicious, check by host. host header sometimes contains port.
if (
urlObj.hostname.length !== host.length &&
urlObj.hostname !== (host.includes(':') ? host.replace(/:\d+$/, '') : host).toLowerCase()
) {
throw new RequestError('Invalid host header')
}
req[urlKey] = urlObj.href
} else if (incomingUrl.length === 0) {
req[urlKey] += '/'
} else {
if (incomingUrl.charCodeAt(0) !== 0x2f) {
// '/'
throw new RequestError('Invalid URL')
}
for (let i = 1, len = incomingUrl.length; i < len; i++) {
const c = incomingUrl.charCodeAt(i)
if (
c > 0x7f ||
allowedRequestUrlChar[c] === 0 ||
(c === 0x2e && hasDotSegment(incomingUrl, i))
) {
try {
req[urlKey] = new URL(req[urlKey]).href
} catch (e) {
throw new RequestError('Invalid URL', { cause: e })
}
break
}
}
}
return req
}