-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
269 lines (231 loc) · 9.33 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
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
/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run `npm run dev` in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run `npm run deploy` to publish your worker
*
* Learn more at https://developers.cloudflare.com/workers/
*/
import { gridAwarePower } from '@greenweb/grid-aware-websites';
import { getLocation, savePageToKv, fetchPageFromKv, saveDataToKv, fetchDataFromKv } from '@greenweb/gaw-plugin-cloudflare-workers';
// Spammy paths that I don't want to serve the content for.
const spammyPaths = [
'/wp-includes/',
'/wp-content/',
'/wp-admin/',
'/contact?',
'.php?',
'/ueditor/',
'/Ueditor/',
'/php-cgi/',
'/wp-json/',
'.php',
'.php7',
];
// This helper function runs the code to modify, cache, and return the HTML page to the user if the grid-aware flag is triggered.
async function gridAwareness(response, request, env, optionalHeaders = {}) {
// First, check if we've already got a cached response for the request URL. We do this using the Cloudflare Workers plugin.
const cachedResponse = await fetchPageFromKv(env, request.url);
// If there's a cached response, return it with the additional headers.
if (cachedResponse) {
return new Response(cachedResponse, {
...response,
headers: {
...response.headers,
'Content-Type': 'text/html;charset=UTF-8',
'GAW-cached-page': 'true',
'Set-Cookie': 'gaw-hourly-session=enabled; Domain=.fershad.com; max-age=3600',
...optionalHeaders
},
});
}
// If there's no cached response, we'll modify the HTML page.
/*
Here you can use the HTMLRewriter API, or you can
use other methods such as redirecting the user to a different page,
or using a regular expression to change the CSS file used by the page.
You can also import other libraries like Cheerio or JSDOM to modify the page
if you are more comfortable with those.
*/
// For my website, I'm using the HTMLRewriter API to remove elements with the data-gaw-remove attribute.
// I'm also adding a class to the body to deglitch the page.
const modifyHTML = new HTMLRewriter()
.on('[data-gaw-remove]', {
element(element) {
element.remove();
},
})
.on('body', {
element(element) {
element.setAttribute('class', 'deglitch');
},
});
// Transform the response using the HTMLRewriter API.
let modifiedResponse = new Response(modifyHTML.transform(response).body, {
...response,
headers: {
...response.headers,
'Content-Type': 'text/html;charset=UTF-8',
'GAW-cached-page': 'false',
'Set-Cookie': 'gaw-hourly-session=enabled; Domain=.fershad.com; max-age=3600',
...optionalHeaders
},
});
// Store the modified response in the KV for 24 hours
// We'll use the Cloudflare Workers plugin to perform this action. The plugin sets an expirationTtl of 24 hours by default, but this can be changed
await savePageToKv(env, request.url, modifiedResponse.clone());
return modifiedResponse;
}
// This helper function returns the regular page response to the user.
async function returnResponse(response, headers = {}) {
return new Response(response.body, {
...response,
headers: {
...headers,
...response.headers,
},
});
}
// This is the main function that fetches the user's location, fetches the grid data, and determines what page (regular or grid-aware) to return the to the user.
export default {
async fetch(request, env, ctx) {
// Get the request URL
const requestUrl = request.url;
// Check if the request URL contains any of the spammy paths & return a 404 response.
if (spammyPaths.some((path) => requestUrl.includes(path))) {
return new Response(null, { status: 404 });
}
// Fetch the request URL
const response = await fetch(requestUrl, {
method: 'GET',
});
if (requestUrl.includes('/og/?') ||
requestUrl.includes('/img/') ||
requestUrl.endsWith('.xml')) {
return returnResponse(response, {
'Grid-aware': 'excluded',
"Content-Encoding": "gzip",
"Cache-Control": "public, max-age=86400",
});
};
if (requestUrl.includes('/api/')) {
return returnResponse(response, {
'Grid-aware': 'excluded',
"Content-Encoding": "gzip",
"cache-control": "no-cache",
});
};
try {
const contentType = response.headers.get('content-type');
// Check if the content type is HTML.
// If not, return the response as is.
if (!contentType || !contentType.includes('text/html')) {
return returnResponse(response, {
"Content-Encoding": "gzip",
"Cache-Control": "public, max-age=86400",
});
}
// Okay, we've got an HTML response.
// Let's check if the user has opted out of the grid-aware website.
// We do this by looking for a cookie named "gaw-status" with the value "disable".
const COOKIE_NAME_REJECT = 'gaw-status';
const COOKIE_NAME_SESSION = 'gaw-hourly-session';
const cookie = request.headers.get('cookie');
// If either cookie is found, or the request URL contains "/og/?" or "/api/" or "/img/", then return the response as is.
// We don't want to modify the content for these requests.
if (cookie && cookie.includes(`${COOKIE_NAME_SESSION}=disabled`)) {
return returnResponse(response, {
'Grid-aware': 'session-disabled',
"Content-Encoding": "gzip",
"Cache-Control": "public, max-age=86400",
});
};
if (cookie && cookie.includes(`${COOKIE_NAME_REJECT}=disable`)) {
return returnResponse(response, {
'Grid-aware': 'opt-out',
"Content-Encoding": "gzip",
"Cache-Control": "public, max-age=86400",
});
}
if (cookie && cookie.includes(`${COOKIE_NAME_SESSION}=enabled`)) {
return gridAwareness(response, request, env);
}
// Since there's no opt-out, we can now check the user's location to determine the grid data.
// We'll use the Cloudflare Workers plugin (@greenweb/gaw-plugin-cloudflare-workers) to get the user's country.
const cfData = await getLocation(request, {
mode: 'country',
});
let { country } = cfData;
// If the country is not found, return the response as is.
if (!country) {
return new Response(response.body, response);
}
// Check to see if we've already got the grid data for the country in a Cloudflare Workers KV.
// Again, we'll use the Cloudflare Workers plugin to perform this check.
let gridData = await fetchDataFromKv(env, country).then((data) => {
return JSON.parse(data);
});
// If we've got cached data that is an error, return the response as is, with additional headers.
// We'd likely get an error message if we're checking for a country that Electricity Maps has no data for.
if (gridData?.status === 'error') {
return returnResponse(response, {
'GAW-Status': 'error',
'GAW-Error': gridData.message,
'GAW-Cached-Data': 'true',
});
}
// If we don't have cached data, fetch the grid data for the country using the @greenweb/grid-aware-websites package.
if (!gridData) {
// The grid data is fetched using the gridAwarePower function from the @greenweb/grid-aware-websites package.
// That function also runs some logic to determine if the current status of the user's energy grid warrants activating the grid-aware flag.
gridData = await gridAwarePower(country, env.EMAPS_API_KEY, {
mode: 'low-carbon',
});
// If the grid data is not found, return the response as is.
if (gridData.status === 'error') {
return returnResponse(response, {
'GAW-Status': 'error',
'GAW-Error': gridData.message,
'GAW-Cached-Data': 'true',
});
}
// Save the grid data to the Cloudflare Workers KV for 1 hours.
// We'll use the Cloudflare Workers plugin to perform this action. The plugin sets an expirationTtl of 1 hour by default, but this can be changed.
await saveDataToKv(env, country, JSON.stringify(gridData));
}
// This is a bit of extra (optional) code that adds headers to the response based on the grid data.
let gawHeaders = {
'GAW-grid-aware': gridData.gridAware,
'GAW-region': gridData.region,
'GAW-mode': gridData.data.mode,
};
if (gridData.data.mode === 'renewable' || gridData.data.mode === 'low-carbon') {
gawHeaders['GAW-Percentage'] = gridData.data.renewablePercentage || gridData.data.lowCarbonPercentage;
gawHeaders['GAW-Minimum'] = gridData.data.minimumPercentage;
} else if (gridData.data.mode === 'average') {
gawHeaders['GAW-Current-Intensity'] = gridData.data.carbonIntensity;
gawHeaders['GAW-Average-Intensity'] = gridData.data.averageIntensity;
} else if (gridData.data.mode === 'limit') {
gawHeaders['GAW-Current-Intensity'] = gridData.data.carbonIntensity;
gawHeaders['GAW-Minimum-Intensity'] = gridData.data.minimumIntensity;
}
// If the grid aware flag is triggered (gridAware === true), then we'll return a modified HTML page to the user.
if (gridData.gridAware) {
return gridAwareness(response, request, env, gawHeaders);
}
// If the gridAware value is set to false, then return the response as is.
return returnResponse(response, {
'Set-Cookie': 'gaw-hourly-session=disabled; Domain=.fershad.com; max-age=3600',
...gawHeaders,
});
} catch (error) {
// If there's an error, return the response as is with an additional header.
console.error(error);
return returnResponse(response, {
'GAW-Status': 'error',
'GAW-Error': 'Fatal error',
});
}
},
};