This repository has been archived by the owner on Jun 26, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateRequestHandler.ts
82 lines (72 loc) · 2.32 KB
/
createRequestHandler.ts
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
import { encodeHex } from 'https://deno.land/[email protected]/encoding/hex.ts'
import * as eszip from 'https://deno.land/x/[email protected]/mod.ts'
import { convertUrl } from './convertUrl.ts'
import { ServerOptions } from './createServer.ts'
import { respondWithError } from './respondWithError.ts'
type RequestHandler = (request: Request) => Promise<Response>
export function createRequestHandler({
allowedExtensions = /^json|wasm|js|mjs|ts|mts$/,
mustHaveExtension = false,
allowedHostnames,
disallowedHostnames,
}: ServerOptions): RequestHandler {
return async (request) => {
const url = new URL(request.url)
if (url.pathname.startsWith('/favicon')) {
return respondWithError('BAD HOSTNAME')
}
if (allowedHostnames) {
if (allowedHostnames instanceof RegExp) {
if (!allowedHostnames.test(url.hostname)) {
return respondWithError('BAD HOSTNAME')
}
} else {
if (
allowedHostnames.length > 0 &&
allowedHostnames.indexOf(url.hostname) < 0
) {
return respondWithError('BAD HOSTNAME')
}
}
}
if (disallowedHostnames) {
if (disallowedHostnames instanceof RegExp) {
if (disallowedHostnames.test(url.hostname)) {
return respondWithError('BAD HOSTNAME')
}
} else {
if (disallowedHostnames.indexOf(url.hostname) >= 0) {
return respondWithError('BAD HOSTNAME')
}
}
}
const extension = url.pathname.split('.').pop()
if (mustHaveExtension && !extension) {
return respondWithError('BAD EXTENSION')
}
if (extension && allowedExtensions) {
if (allowedExtensions instanceof RegExp) {
if (!allowedExtensions.test(extension)) {
return respondWithError('BAD EXTENSION')
}
} else {
if (allowedExtensions.indexOf(extension) >= 0) {
return respondWithError('BAD EXTENSION')
}
}
}
try {
const eszipBuf = await eszip.build([convertUrl(request.url)])
return new Response(eszipBuf, {
headers: {
'content-disposition': `attachment; filename="${
encodeHex(url.pathname)
}.eszip"`,
'cache-control': 'max-age=604800', // 7 days
},
})
} catch (_err) {
return respondWithError('BUILD FAILED', 500)
}
}
}