-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlerViewerRequest.js
More file actions
317 lines (284 loc) · 9.28 KB
/
handlerViewerRequest.js
File metadata and controls
317 lines (284 loc) · 9.28 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
"use strict";
const helpers = require("./helpers/misc");
const http_helpers = require("./helpers/http");
require("source-map-support").install();
module.exports.viewerRequest = async (event) => {
let request = event.Records[0].cf.request;
try {
// Environment Setup
const APIDomain = "CROWDHANDLER_API_DOMAIN";
// If failtrust is false, users that fail to check-in with CrowdHandler will be sent to waiting room.
// If true, users that fail to check-in with CrowdHandler will be trusted.
const failTrust = true;
const publicKey = "CROWDHANDLER_PUBLIC_KEY";
// Set slug of fallback waiting room for users that fail to check-in with CrowdHandler.
let safetyNetSlug;
// Set whitelabel to true to redirect users to a waiting room on your site domain. See setup guide for more info.
const whitelabel = true;
// Extract request Meta Information
let requestHeaders = request.headers;
const host = requestHeaders.host[0].value;
// Forward api endpoint and public key value as headers so our viewer response function has them at hand to use
requestHeaders["x-ch-api-endpoint"] = [
{
key: "x-ch-api-endpoint",
value: APIDomain,
},
];
requestHeaders["x-ch-public-key"] = [
{
key: "x-ch-public-key",
value: publicKey,
},
];
// Used to determine request/response total time.
let requestStartTime = Date.now();
requestHeaders["x-ch-request-time"] = [
{
key: "x-ch-request-time",
value: `${requestStartTime}`,
},
];
// Requested URI
const uri = request.uri;
// User Agent
const userAgent = requestHeaders["user-agent"]?.[0]?.value || null;
// Make best effort to determine language
let language = null;
try {
language = requestHeaders["accept-language"][0].value.split(",")[0];
} catch (error) {
// Accept-language header not present - not critical
}
// Full URL of the protected domain.
const FQDN = `https://${host}${uri}`;
// Don't try and queue static assets
let fileExtension = uri.split(".").pop();
// No need to execute anymore of this script if the request is for a static file.
const creativeAssetExtensions = helpers.creativeAssetExtensions;
if (creativeAssetExtensions.indexOf(fileExtension) !== -1) {
return request;
}
let queryString = helpers.queryStringParse(request.querystring, "object");
// Destructure special params from query string if they exist.
let {
"ch-code": chCode,
"ch-fresh": chFresh,
"ch-id": chID,
"ch-id-signature": chIDSignature,
"ch-public-key": chPublicKey,
"ch-requested": chRequested,
} = queryString || {};
// This is the right most address found in the x-forwarded-for header and can be trusted as it was discovered via the TCP connection.
const IPAddress = request.clientIp || null;
// Make sure we don't try and use undefined or null in parameters
if (!chCode || chCode === "undefined" || chCode === "null") {
chCode = "";
}
// Remove special params from the queryString object now that we don't need them anymore
if (queryString) {
delete queryString["ch-code"];
delete queryString["ch-fresh"]
delete queryString["ch-id"];
delete queryString["ch-id-signature"];
delete queryString["ch-public-key"];
delete queryString["ch-requested"];
}
// Stringify queryString
queryString = helpers.queryStringParse(queryString, "string");
// Prepend & to the query string if it's not empty as we're always going to need to chain it to ?${FQDN}
if (queryString) {
//Update the querystring to remove special CH parameters
request.querystring = queryString;
queryString = `?${queryString}`;
}
//URL encode the targetURL to be used later in redirects
let targetURL;
if (queryString) {
targetURL = encodeURIComponent(FQDN + queryString);
} else {
targetURL = encodeURIComponent(FQDN);
}
// Parse cookies
const parsedCookies = helpers.parseCookies(requestHeaders);
let crowdhandlerCookieValue = parsedCookies["crowdhandler"];
// Prioritise tokens in the ch-id parameter and fallback to ones found in the cookie.
let freshlyPromoted;
let token;
let tokenSource;
if (chID) {
freshlyPromoted = true;
token = chID;
tokenSource = 'param';
} else if (crowdhandlerCookieValue) {
token = crowdhandlerCookieValue;
tokenSource = 'cookie';
} else {
token = null;
tokenSource = 'new';
}
// Validate token format - must contain at least one digit
const validToken = /(.*\d+.*)/;
if (token && !validToken.test(token)) {
token = null;
tokenSource = 'new';
}
if (freshlyPromoted) {
let redirectLocation
if (queryString) {
redirectLocation = `${FQDN}${queryString}`
} else {
redirectLocation = FQDN
}
return http_helpers.redirect302Response(redirectLocation, token);
}
// Check in with CrowdHandler
async function checkStatus() {
let headers = {
"Content-Type": "application/json",
"x-api-key": publicKey,
};
let response;
let timeoutHandle;
const timeoutPromise = new Promise((_, reject) => {
timeoutHandle = setTimeout(() => {
reject(new Error('API Communication Timed Out!'));
}, http_helpers.API_TIMEOUT_MS);
});
try {
let apiCall;
if (token) {
apiCall = http_helpers.httpGET({
headers: headers,
hostname: APIDomain,
method: "GET",
path: `/v1/requests/${token}?url=${targetURL}&agent=${encodeURIComponent(userAgent)}&ip=${encodeURIComponent(
IPAddress
)}&lang=${encodeURIComponent(language)}`,
port: 443,
});
} else {
apiCall = http_helpers.httpPOST(
{
headers: headers,
hostname: APIDomain,
method: "POST",
path: "/v1/requests",
port: 443,
},
JSON.stringify({
url: FQDN + queryString,
ip: IPAddress,
agent: userAgent,
lang: language,
})
);
}
response = await Promise.race([apiCall, timeoutPromise]);
} catch (error) {
console.error('CrowdHandler API call failed:', error.message || error);
response = error;
} finally {
clearTimeout(timeoutHandle);
return response;
}
}
let response = await checkStatus();
let result;
try {
result = JSON.parse(response).result;
} catch (error) {
console.error("Failed to parse API response:", error);
// Fallback result triggers failTrust logic
result = {
status: 2,
promoted: null,
token: null,
slug: null,
responseID: null,
};
}
let redirect;
let redirectLocation;
let WREndpoint;
// Alter queue endpoint based on whitelabel flag value
switch (whitelabel) {
case true:
WREndpoint = `${host}/ch`;
break;
case false: {
WREndpoint = `wait.crowdhandler.com`;
break;
}
default:
WREndpoint = `wait.crowdhandler.com`;
break;
}
// Normal healthy response
if (result.promoted !== 1 && result.status !== 2) {
redirect = true;
redirectLocation = `https://${WREndpoint}/${result.slug}?url=${targetURL}&ch-code=${chCode}&ch-id=${result.token}&ch-public-key=${publicKey}`;
// 4xx client error - always redirect to safety net (ignore failTrust)
} else if (result.clientError === true) {
console.error('[CH] API returned 4xx client error - redirecting to safety net');
redirect = true;
if (safetyNetSlug) {
redirectLocation = `https://${WREndpoint}/${safetyNetSlug}?url=${targetURL}&ch-code=${chCode}&ch-id=${token}&ch-public-key=${publicKey}`;
} else {
redirectLocation = `https://${WREndpoint}/?url=${targetURL}&ch-code=${chCode}&ch-id=${token}&ch-public-key=${publicKey}`;
}
// 5xx server error - respect failTrust setting
} else if (
failTrust !== true &&
result.promoted !== 1 &&
result.status === 2
) {
redirect = true;
if (safetyNetSlug) {
// Your custom slug
redirectLocation = `https://${WREndpoint}/${safetyNetSlug}?url=${targetURL}&ch-code=${chCode}&ch-id=${token}&ch-public-key=${publicKey}`;
} else {
// Generic fallback room
redirectLocation = `https://${WREndpoint}/?url=${targetURL}&ch-code=${chCode}&ch-id=${token}&ch-public-key=${publicKey}`;
}
// User is promoted
} else {
redirect = false;
}
switch (redirect) {
case true: {
console.log(`[CH] ${host}${uri} | src:${tokenSource} | action:redirect | token:${result.token || token || 'none'}`);
return http_helpers.redirect302Response(redirectLocation, result.token);
}
case false: {
console.log(`[CH] ${host}${uri} | src:${tokenSource} | action:allow | token:${result.token || 'none'}`);
break;
}
default: {
break;
}
}
// This code only executes if a redirect hasn't been triggered.
// Pass information required by the response handler.
if (result.token) {
requestHeaders["x-ch-crowdhandler-token"] = [
{
key: "x-ch-crowdhandler-token",
value: result.token,
},
];
}
if (result.responseID) {
requestHeaders["x-ch-responseID"] = [
{
key: "x-ch-responseID",
value: result.responseID,
},
];
}
return request;
} catch (error) {
console.error('[CH] Unhandled error in viewerRequest - failing open:', error);
return request;
}
};