-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
211 lines (197 loc) · 5.61 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
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
/* global HTMLRewriter, FX_REDIRECT, FX_JWT_SECRET */
const FX_CUSTOMER_JWT_COOKIE = "fx.customer.jwt";
const FX_CUSTOMER_DESTINATION_COOKIE = "fx.cf.guard.destination";
// Flag that indicates that there is a login form in this page so that the user
// is not redirected out of it.
let loginTag = false;
/** Cloudflare Worker method */
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
/**
* Handles the request
*
* @param {Request} request to be handled
* @returns {Response|Promise<Response>} response
*/
async function handleRequest(request) {
loginTag = false;
const responsePromise = fetch(request);
const session = await verify(request);
if (session) {
// User is authenticated
const loginURL = new URL(FX_REDIRECT, request.url);
if (cleanURL(request.url) === cleanURL(loginURL.toString())) {
const destination = getCookie(request, FX_CUSTOMER_DESTINATION_COOKIE);
if (destination) {
// Remove destination cookie and redirect to destination
return new Response(null, {
headers: new Headers([
["location", destination],
["Set-Cookie", expireCookie(FX_CUSTOMER_DESTINATION_COOKIE)]
]),
status: 303
});
}
}
return responsePromise;
} else {
const response = await responsePromise;
const transformedResponse = new HTMLRewriter()
.on("foxy-customer-portal", new LoginFormHandler())
.on("[data-login]", new LoginFormHandler())
.on("[data-restricted]", new OmitHandler())
.on("foxy-customer-portal", new ReloadOnLoginHandler())
.transform(response);
if (!loginTag && FX_REDIRECT) {
const loginURL = new URL(FX_REDIRECT, request.url);
const loginPage = loginURL.toString();
if (cleanURL(request.url) !== cleanURL(loginPage)) {
return new Response(null, {
headers: new Headers([
["location", loginPage],
[
"Set-Cookie",
buildCookie(FX_CUSTOMER_DESTINATION_COOKIE, cleanURL(request.url))
]
]),
status: 302
});
} else {
return transformedResponse;
}
} else {
return transformedResponse;
}
}
}
/**
* Verify the request has a valid Customer Portal Foxy JWT
*
* @param {Request} request incoming Request
* @returns {Promise<boolean>} true if valid
*/
async function verify(request) {
const jwtString = getCookie(request, FX_CUSTOMER_JWT_COOKIE);
if (!jwtString) return false;
return verifySignature(jwtString);
}
/**
* Simplifies a given URL string
*
* @param {string} dirtyURL to be fixed
* @returns {string} fixed URL string
*/
function cleanURL(dirtyURL) {
return dirtyURL
.trim()
.replace(/\/$/, "")
.replace(/:\/\/+/, "://");
}
/**
* Gets the cookie with given name from the request headers
*
* @param {Request} request incoming Request
* @param {string} name of the cookie to get
* @returns {string} the cookie value
*/
function getCookie(request, name) {
let result = "";
const cookieString = request.headers.get("Cookie");
if (cookieString) {
const cookies = cookieString.split(";");
for (let c = 0; c < cookies.length; c += 1) {
const cookie = cookies[c].split("=", 2);
if (name === cookie[0].trim() && cookie.length === 2) {
result = cookie[1];
break;
}
}
}
return result;
}
/**
* Builds a cookie with Path set to /
*
* @param {string} key the cookie key.
* @param {string} value the value the cookie will be set to.
* @return {string} cookie to set
**/
function buildCookie(key, value) {
return `${key}=${value}; Path=/`;
}
/**
* Verify JWT token
*
* Uses the stored shared secret to verify a JWT token.
* Verification is done using the Cloudflare Crypto Library. It's interface is
* similar to the webworkers subtle crypto library.
*
* @param {string} token to be verified
*/
async function verifySignature(token) {
const encoder = new TextEncoder();
// Prepares the signed data to be verified.
const parts = token.split(".");
const data = encoder.encode([parts[0], parts[1]].join('.'));
// Prepares the signature.
const signature = new Uint8Array(
Array.from(
atob(parts[2].replace(/_/g, '/').replace(/-/g, '+'))
).map(c => c.charCodeAt(0)));
// Build the key.
let key;
try {
key = await crypto.subtle.importKey(
"raw",
encoder.encode(FX_JWT_SECRET),
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"]
);
} catch (e) {
if (e.name === "ReferenceError") {
console.error(e);
return false;
} else {
throw e;
}
}
const result = await crypto.subtle.verify("HMAC", key, signature, data);
return result;
}
/**
* @param {string} key to be expired
* @return {string} the expired cookie
**/
function expireCookie(key) {
return `${key}=deleted; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/ `;
}
/** A handler that sets an attribute on itself 'login' to true if any
* element is passed to it */
class LoginFormHandler {
element(el) {
if (el) loginTag = true;
}
}
/** A handler that removes any element it receives */
class OmitHandler {
element(el) {
el.remove();
}
}
/** Adds a script to reload on signout and signin events */
class ReloadOnLoginHandler {
element (el) {
el.after(`
<script>
var els = document.getElementsByTagName("${el.tagName}");
var reloadable = els[els.length -1];
if (reloadable) {
reloadable.addEventListener("signout", () => window.location.reload());
reloadable.addEventListener("signin", () => window.location.reload());
}
</script>`, { html: true}
);
}
}