- Notifications
You must be signed in to change notification settings - Fork2
/
Copy pathindex.js
382 lines (329 loc) · 10.6 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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/**
* Configurable WebPageTest Cloudflare Worker.
*
* Options (see index.html)
*/
addEventListener('fetch',(event)=>{
event.respondWith(handleRequest(event.request))
})
asyncfunctiongetResponse(request,shouldPush,shopId){
// If push of headers is not enabled, return a copy of the response
// (so we can mutate the headers).
if(!shouldPush){
constresponse=awaitfetch(request)
returnnewResponse(response.body,response)
}
// Allow for pushing HTTP headers while we wait for the response
const{ readable, writable}=newTransformStream()
// Start request in parallel
fetch(request).then((response)=>{
response.body.pipeTo(writable)
})
// Hardcode some HTTP headers
constheaders=newHeaders({
connection:'keep-alive',
'content-language':'en',
'content-security-policy':
"block-all-mixed-content; frame-ancestors 'none'; upgrade-insecure-requests;",
'content-type':'text/html; charset=utf-8',
server:'cloudflare',
'strict-transport-security':'max-age=7889238',
vary:'Accept',
'x-frame-options':'DENY',
'x-permitted-cross-domain-policies':'none',
'x-xss-protection':'1; mode=block',
'x-request-id':uuid(),// fake nginx
})
// not a typo it's x-shopid on the shopify side >.>
if(shopId)headers.append('x-shopid',shopId);
// Return a response that will eventually stream the proxied payload
returnnewResponse(readable,{
status:200,
statusText:'OK',
headers:headers,
})
}
functionzipByDecode(acc,[k,v]){
acc[k.trim()]=decodeURIComponent(v)
returnacc
}
asyncfunctionproxyFetch(qs,realRequest){
const{ odp, compression}=qs
constproxyRequestUrl=odp.replace(/^\/\//,'https://')
constrequest=newRequest(proxyRequestUrl,realRequest)
if(compression)request.headers.set('Accept-Encoding',compression)
request.headers.delete('x-host')
request.headers.delete('x-forwarded-proto')
request.headers.delete('cf-visitor')
request.headers.delete('cf-workers-preview-token')
constresponse=awaitfetch(proxyRequestUrl,{
...request,
cf:{
cacheEverything:true,
cacheTtl:5*60,// 5 minutes
},
})
constshouldTransformProxiedRequest=
!compression&&realRequest.headers.get('accept').indexOf('text/css')!==-1
if(shouldTransformProxiedRequest){
// Replace all urls in the CSS with odp urls.
const{ readable}=newReplaceStream(response.body,(s)=>
s.replace(urlRegex,replacer(compression)),
)
returnnewResponse(readable,response)
}
constreturnValue=newResponse(response.body,response)
if(qs.compression)returnValue.headers.set('cache-control','no-transform')
returnreturnValue
}
classReplaceStream{
constructor(inputStream,fn){
const{ readable, writable}=newTransformStream()
this.reader=inputStream.getReader()
this.writer=writable.getWriter()
this.readable=readable
this.decoder=newTextDecoder()
this.encoder=newTextEncoder()
this.fn=fn
this.transform().catch((e)=>console.error(e.message))
}
asynctransform(transform){
letchunk
const{ writer, reader, encoder, decoder, fn}=this
while((chunk=awaitreader.read())){
if(!chunk||chunk.done===true)returnwriter.close()
constvalue=decoder.decode(chunk.value)
consttransformedValue=fn(value)
constencodedValue=encoder.encode(transformedValue)
writer.write(encodedValue).catch(()=>{})
}
returnwriter.close()
}
}
asyncfunctionhandleRequest(request){
consturl=newURL(request.url)
// Disallow crawlers
if(url.pathname==='/robots.txt'){
returnnewResponse('User-agent: *\nDisallow: /',{status:200})
}
constqs=url.search
.slice(1)
.split('&')
.map((x)=>x.split('='))
.reduce(zipByDecode,{})
constshouldOnDomainProxy=!!qs.odp
if(shouldOnDomainProxy){
returnproxyFetch(qs,request)
}
constcookies=(request.headers.get('cookie')||'')
.split(';')
.map((x)=>x.split('='))
.reduce(zipByDecode,{})
constconfig=[
'x-host',
'x-link',
'x-async',
'x-defer',
'x-no-async-hide',
'x-bypass-transform',
'x-push',
'x-shop-id',
'x-on-domain',
'x-compression',
'x-lazyload',
'x-remove-element',
'x-append-to-head',
'x-append-to-body',
]
.map((k)=>[k,request.headers.get(k)||cookies[k]||qs[k]])
.reduce((acc,[k,v])=>{
acc[k]=v
returnacc
},{})
// When overrideHost is used in a script, WPT sets x-host to original host i.e. site we want to proxy
consthost=config['x-host']
// Error if x-host header missing
if(!host){
returnfetch('https://charlespwd.github.io/faster')
}
constrequestHost=url.hostname
url.hostname=host
constbypassTransform=config['x-bypass-transform']
constacceptHeader=request.headers.get('accept')
constshouldBypassTransform=
bypassTransform&&bypassTransform.indexOf('true')!==-1
constshouldTransform=!shouldBypassTransform
constreq=newRequest(url,request)
req.headers.delete('x-host')
req.headers.delete('x-forwarded-proto')
req.headers.delete('cf-visitor')
req.headers.delete('cf-workers-preview-token')
if(!shouldTransform){
// Just proxy the request
returnfetch(url,req)
}
constlinkHeader=config['x-link']
constasyncSelector=config['x-async']?.replace(/\+/g,' ')
constdeferSelector=config['x-defer']?.replace(/\+/g,' ')
constasyncHide=config['x-no-async-hide']==='true'
constshouldPush=config['x-push']==='true'
constshopId=config['x-shop-id']
constcompression=config['x-compression']
constdomains=config['x-on-domain']?.replace(/\+/g,' ')
constlazyloadSelector=config['x-lazyload']?.replace(/\+/g,' ')
constremoveElementSelector=config['x-remove-element']?.replace(/\+/g,' ')
constappendToHeadContent=config['x-append-to-head']
constappendToBodyContent=config['x-append-to-body']
constresponse=awaitgetResponse(req,shouldPush,shopId)
constisHtmlResponse=response.headers.get('content-type').includes('html');
if(!isHtmlResponse){
console.log('Not an HTML response',req.url);
returnresponse;
}
// Add the link header
if(linkHeader)response.headers.append('Link',linkHeader)
// Fancy pantsy way of turning on/off features and applying them on an
// HTMLRewriter. Stored as [fnName, ...args][].
constcommands=[
asyncHide&&['on','head > style',newAsyncHideHandler()],
deferSelector&&['on',deferSelector,newAttrHandler('defer',true)],
asyncSelector&&['on',asyncSelector,newAttrHandler('async',true)],
lazyloadSelector&&[
'on',
lazyloadSelector,
newAttrHandler('loading','lazy'),
],
removeElementSelector&&[
'on',
`${removeElementSelector}`,
newRemoveElementHandler(),
],
appendToHeadContent&&[
'on',
'head',
newAppendHandler(appendToHeadContent),
],
appendToBodyContent&&[
'on',
`body`,
newAppendHandler(appendToBodyContent),
],
domains&&[
'on',
'script[src],link[href][rel=stylesheet],link[href][rel=preload],link[href][rel*=icon],[src],[data-srcset],[data-src],[data-bgset]',
newOnDomainHandler(domains,url.hostname,compression),
],
domains&&[
'on',
'link[href][rel=preconnect],link[href][rel=dns-prefetch]',
newRemoveElementHandler(),
],
['transform',response],
].filter(Boolean)
// Apply all the commands on the HTMLRewriter and send.
returncommands.reduce((rewriter,[fnName, ...args])=>{
returnrewriter[fnName](...args)
},newHTMLRewriter())
}
classRemoveElementHandler{
element(element){
element.remove()
}
}
// This special regex matches two collocated regexes because special sites
// like gymshark do weird proxying of their own. It's a double proxy...
consturlRegex=/((https?:)?\/\/([-a-zA-Z0-9@:%._\+~#=]{1,256}\.)+[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=,]*)\/?)+/gm
constreplacer=(compression)=>(match)=>{
if(
/\/\/cdn\.shopify\.com\/.*(\.js|\.css)(\?.*)?$/.test(match)&&
compression
){
consturl=/\?/.test(match)
?`${match}&enable_compression=1`
:`${match}?enable_compression=1`
return`/?odp=${encodeURIComponent(url)}&compression=${compression}`
}
return`/?odp=${encodeURIComponent(match)}`
}
classAppendHandler{
constructor(content){
this.content=content
}
element(element){
element.append(this.content,{html:true})
}
}
classOnDomainHandler{
constructor(domains,host,compression){
this.replacer=replacer(compression)
this.domains=domains
.split(',')
.map(
(domain)=>newRegExp(domain.replace(/\./g,'.').replace(/\*/g,'w*')),
)
this.host=host
}
element(element){
constattrs=['href','src','srcset','data-srcset','data-src','data-bgset'].filter(
element.getAttribute.bind(element),
)
for(constattrofattrs){
constattrValue=element.getAttribute(attr)
constshouldReplace=!!this.domains.find((domain)=>
domain.test(attrValue),
)
if(!shouldReplace)return
element.setAttribute(attr,attrValue.replace(urlRegex,this.replacer))
}
}
}
classAsyncHideHandler{
text(text){
text.replace(text.text.replace(/async-hide/,'async-hide-noop'))
}
}
classAttrHandler{
constructor(attribute,value=true){
this._attribute=attribute
this._value=value
}
element(element){
element.setAttribute(this._attribute,this._value)
}
}
// uuid returns an RFC 4122 compliant universally unique
// identifier using the crypto API
//
// source: https://gist.github.com/bentranter/ed524091170137a72c1d54d641493c1f
functionuuid(){
// get sixteen unsigned 8 bit random values
constu=crypto.getRandomValues(newUint8Array(16))
// set the version bit to v4
u[6]=(u[6]&0x0f)|0x40
// set the variant bit to "don't care" (yes, the RFC
// calls it that)
u[8]=(u[8]&0xbf)|0x80
// hex encode them and add the dashes
letuid=''
uid+=u[0].toString(16)
uid+=u[1].toString(16)
uid+=u[2].toString(16)
uid+=u[3].toString(16)
uid+='-'
uid+=u[4].toString(16)
uid+=u[5].toString(16)
uid+='-'
uid+=u[6].toString(16)
uid+=u[7].toString(16)
uid+='-'
uid+=u[8].toString(16)
uid+=u[9].toString(16)
uid+='-'
uid+=u[10].toString(16)
uid+=u[11].toString(16)
uid+=u[12].toString(16)
uid+=u[13].toString(16)
uid+=u[14].toString(16)
uid+=u[15].toString(16)
returnuid
}