-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
169 lines (149 loc) · 5.88 KB
/
index.js
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
/**
* Shows how to restrict access using the HTTP "Basic" schema.
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
* @see https://tools.ietf.org/html/rfc7617
*
* A user-id containing a colon (":") character is invalid, as the
* first colon in a user-pass string separates user and password.
*/
const BASIC_USER = 'admin'
const BASIC_PASS = 'admin'
/**
* Receives a HTTP request and replies with a response.
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const { pathname } = new URL(request.url)
switch (pathname) {
case '/':
return new Response('Anyone can access the homepage!');
case '/logout':
// Invalidate the "Authorization" header by returning a HTTP 401.
// We do not send a "WWW-Authenticate" header, as this would trigger
// a popup in the browser, immediately asking for credentials again.
return new Response('Logged out.', { status: 401 })
case '/admin': {
// The "Authorization" header is sent when authenticated.
if (request.headers.has('Authorization')) {
// Throws exception when authorization fails.
const { user, pass } = basicAuthentication(request)
verifyCredentials(user, pass)
// Only returns this response when no exception is thrown.
async function gatherResponse(response) {
const { headers } = response
const contentType = headers.get("content-type") || ""
if (contentType.includes("application/json")) {
return JSON.stringify(await response.json())
}
else if (contentType.includes("application/text")) {
return response.text()
}
else if (contentType.includes("text/html")) {
return response.text()
}
else {
return response.text()
}
}
const url1 = 'https://api.gemini.com/v1/pubticker/btcusd';
const url2 = 'https://api.gemini.com/v1/pubticker/ethusd';
const responses = await Promise.all([fetch(url1), fetch(url2)])
const results = await Promise.all([
gatherResponse(responses[0]),
gatherResponse(responses[1]),
])
return new Response(results.join(), {
status: 200,
headers: {
'Cache-Control': 'no-store'
}
})
}
// Not authenticated.
return new Response('You need to login.', {
status: 401,
headers: {
// Prompts the user for credentials.
'WWW-Authenticate': 'Basic realm="my scope", charset="UTF-8"'
}
})
}
case '/favicon.ico':
case '/robots.txt':
return new Response(null, { status: 204 })
}
return new Response('Not Found.', { status: 404 })
}
/**
* Throws exception on verification failure.
* @param {string} user
* @param {string} pass
* @throws {UnauthorizedException}
*/
function verifyCredentials(user, pass) {
if (BASIC_USER !== user) {
throw new UnauthorizedException('Invalid username.')
}
if (BASIC_PASS !== pass) {
throw new UnauthorizedException('Invalid password.')
}
}
/**
* Parse HTTP Basic Authorization value.
* @param {Request} request
* @throws {BadRequestException}
* @returns {{ user: string, pass: string }}
*/
function basicAuthentication(request) {
const Authorization = request.headers.get('Authorization')
const [scheme, encoded] = Authorization.split(' ')
// The Authorization header must start with "Basic", followed by a space.
if (!encoded || scheme !== 'Basic') {
throw new BadRequestException('Malformed authorization header.')
}
// Decodes the base64 value and performs unicode normalization.
// @see https://datatracker.ietf.org/doc/html/rfc7613#section-3.3.2 (and #section-4.2.2)
// @see https://dev.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
const decoded = atob(encoded).normalize()
// The username & password are split by the first colon.
//=> example: "username:password"
const index = decoded.indexOf(':')
// The user & password are split by the first colon and MUST NOT contain control characters.
// @see https://tools.ietf.org/html/rfc5234#appendix-B.1 (=> "CTL = %x00-1F / %x7F")
if (index === -1 || /[\0-\x1F\x7F]/.test(decoded)) {
throw new BadRequestException('Invalid authorization value.')
}
return {
user: decoded.substring(0, index),
pass: decoded.substring(index + 1),
}
}
function UnauthorizedException(reason) {
this.status = 401
this.statusText = 'Unauthorized'
this.reason = reason
}
function BadRequestException(reason) {
this.status = 400
this.statusText = 'Bad Request'
this.reason = reason
}
addEventListener('fetch', event => {
event.respondWith(
handleRequest(event.request).catch(err => {
const message = err.reason || err.stack || 'Unknown Error'
return new Response(message, {
status: err.status || 500,
statusText: err.statusText || null,
headers: {
'Content-Type': 'text/plain;charset=UTF-8',
// Disables caching by default.
'Cache-Control': 'no-store',
// Returns the "Content-Length" header for HTTP HEAD requests.
'Content-Length': message.length,
}
})
})
)
})