This repository has been archived by the owner on Apr 3, 2024. It is now read-only.
forked from vortexdl/aero
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandle.js
383 lines (316 loc) · 10.2 KB
/
handle.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
383
// Routes
import routes from "./this/internal/routes.js";
// Dynamic Config
import getConfig from "./this/dynamic/getConfig.js";
// Standard Config
import { prefix, aeroPrefix, debug, flags } from "./config.js";
let hostUrl = location.protocol + '//' + location.host;
// Utility
import { createBareClient } from "./this/misc/bare/dist/BareClient.js";
import ProxyFetch from "./this/misc/ProxyFetch.js";
import sharedModule from "./this/misc/sharedModule.js";
import getRequestUrl from "./this/misc/getRequestUrl.js";
import headersToObject from "./this/misc/headersToObject.js";
import unwrapImports from "./this/misc/unwrapImports.js";
// Cors Emulation
import block from "./this/cors/test.js";
// Cache Emulation
import CacheManager from "./this/cors/cache.js";
// Rewriters
import rewriteReqHeaders from "./this/rewriters/reqHeaders.js";
import rewriteRespHeaders from "./this/rewriters/respHeaders.js";
import rewriteCacheManifest from "./this/rewriters/cacheManifest.js";
import rewriteManifest from "./this/rewriters/manifest.js";
import scope from "./shared/scope.js";
/**
* Handles the requests
* @param {FetchEvent} - The event
* @returns {Response} - The proxified response
*/
async function handle(event) {
const req = event.request;
// Dynamic config
const { backends, wsBackends, wrtcBackends } = getConfig();
// Separate the prefix from the url to get the proxy url isolated
const afterPrefix = url =>
url.replace(new RegExp(`^(${location.origin}${prefix})`, "g"), "");
//const useBare = BareClient || typeof BareClient === "function";
// Construct proxy fetch instance
const proxyFetch = await createBareClient(`${hostUrl}/bare/`);
const reqUrl = new URL(req.url);
const path = reqUrl.pathname + reqUrl.search;
// Remove the module components
if (path.startsWith(aeroPrefix + "shared/") && path.endsWith(".js"))
return await sharedModule(event);
// Don't rewrite requests for aero library files
if (path.startsWith(aeroPrefix))
// Proceed with the request like normal
return await fetch(req.url);
var clientUrl;
// Get the origin from the user's window
if (event.clientId !== "") {
// Get the current window
const client = await clients.get(event.clientId);
// Get the url after the prefix
clientUrl = new URL(afterPrefix(client.url));
}
// Determine if the request was made to load the homepage; this is needed so that the proxy will know when to rewrite the html files (for example, you wouldn't want it to rewrite a fetch request)
const homepage = req.mode === "navigate" && req.destination === "document";
// This is used for determining the request url
const iFrame = req.destination === "iframe";
const navigate = homepage || iFrame;
// Parse the request url to get the url to proxy
const proxyUrl = new URL(
getRequestUrl(
reqUrl.origin,
location.origin,
clientUrl,
path,
homepage,
iFrame
)
);
// Ensure the request isn't blocked by CORS
if (flags.corsEmulation && (await block(proxyUrl.href)))
return new Response("Blocked by CORS", { status: 500 });
// Log requests
if (debug.url)
console.log(
req.destination == ""
? `${req.method} ${proxyUrl.href}`
: `${req.method} ${proxyUrl.href} (${req.destination})`
);
// Rewrite the request headers
const reqHeaders = headersToObject(req.headers);
// Cache mode emulation
const cache = new CacheManager(reqHeaders);
let injectHeaders = {};
if (flags.corsEmulation) {
injectHeaders = {
// Cache Emulation
timing: reqHeaders["timing-allow-origin"],
// CORS Emulation
clear: reqHeaders["clear-site-data"]
? JSON.parse(`[${reqHeaders["clear-site-data"]}]`)
: undefined,
// TODO: Respect the permissions policy
perms: reqHeaders["permissions-policy"],
// These are parsed later in frame.js if needed
frame: reqHeaders["x-frame-options"],
// This is only used for getting the frame frameancesors for $aero.frame
csp: reqHeaders["content-security-policy"],
};
if (injectHeaders.clear)
await clear(injectHeaders.clear, event.clientId);
}
// Get the cache age before we start rewriting
const cacheAge = cache.getAge(
reqHeaders["cache-control"],
reqHeaders["expires"]
);
const cacheResp = await cache.get(reqUrl, cacheAge);
if (cacheResp) return cacheResp;
if (cache.mode === "only-if-cached")
// TODO: Properly emulate the network error
return new Response("Can't find a cache", {
status: 500,
});
const rewrittenReqHeaders = rewriteReqHeaders(
prefix,
reqHeaders,
clientUrl,
afterPrefix
);
let opts = {
method: req.method,
headers: rewrittenReqHeaders,
};
// A request body should only be created under a post request
if (req.method === "POST") opts.body = await req.text();
// Make the request to the proxy
const resp = await proxyFetch.fetch(proxyUrl.href, opts);
if (resp instanceof Error)
return new Response(resp, {
status: 500,
});
// Rewrite the response headers
const respHeaders = headersToObject(resp.headers);
const rewrittenRespHeaders = rewriteRespHeaders(
flags.corsEmulation,
respHeaders
);
const type = respHeaders["content-type"];
const html =
// Not all sites respond with a type
typeof type === "undefined" || type.startsWith("text/html");
// Rewrite the body
/** @type {string | ReadableStream} */
let body;
// For modules
const isMod = new URLSearchParams(location.search).mod === "true";
// TODO: Support XML/XSLT
if (navigate && html) {
body = await resp.text();
if (body !== "") {
body = `
<!DOCTYPE html>
<head>
<!-- Fix encoding issue -->
<meta charset="utf-8">
<!-- Favicon -->
<!--
Delete favicon if /favicon.ico isn't found
This is needed because the browser will cache the favicon from the previous site
-->
<link href="data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVRIx2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII=" rel="icon" type="image/x-icon">
<!-- If not defined already, manually set the favicon -->
<link href="/favicon.ico" rel="icon" type="image/x-icon">
<script>
// Update the service worker
navigator.serviceWorker
.register("/sw.js", {
scope: ${prefix},
// Don't cache http requests
updateViaCache: "none",
type: "module",
})
// Update service worker
.then(reg => reg.update())
.catch(err => console.error(err.message));
// Aero's global namespace
Object.defineProperty(window, "$aero", {
value: {
config: {
prefix: "${prefix}",
wsBackends: ${JSON.stringify(wsBackends)},
wrtcBackends: ${JSON.stringify(wrtcBackends)},
debug: ${JSON.stringify(debug)},
flags: ${JSON.stringify(flags)},
},
cors: ${JSON.stringify(injectHeaders)},
// This is used to later copy into an iFrame's srcdoc; this is for an edge case
imports: \`${unwrapImports(routes, true)}\`,
afterPrefix: url => url.replace(new RegExp(\`^(\${location.origin}\${$aero.config.prefix})\`, "g"), ""),
},
writable: false
});
Object.freeze($aero.config);
</script>
<script>
// Sanity check
if (!("$aero" in window)) {
// Clear site
document.head.innerHTML = "";
document.write("<h1>Unable to initalize $aero</h1>");
}
</script>
<!-- Injected Aero code -->
${unwrapImports(routes)}
<script>
Object.freeze($aero);
</script>
</head>
${body}
`;
}
} else if (
navigate &&
(text.startsWith("text/xml") || text.startsWith("application/xml"))
) {
body = await resp.text();
`
<config>
{
prefix: ${prefix}
}
</config>
<?xml-stylesheet type="text/xsl" href="/aero/browser/xml/intercept.xsl"?>
${body}
`;
} else if (req.destination === "script") {
body = "";
if (flags.corsEmulation)
// Integrity check
body += `
(async () => {
if (document.currentScript.hasAttribute("integrity")) {
const [rawAlgo, hash] = document.currentScript.integrity.split("-");
const algo = rawAlgo.replace(/^sha/g, "SHA-");
alert(algo);
const buf = new TextEncoder().encode(document.currentScript.innerHTML);
const calcHashBuf = await crypto.subtle.digest(algo, buf);
const calcHash = new TextDecoder().decode(calcHashBuf);
// If mismatched hash
const blocked = hash === calcHash;
// Exit script
if (blocked)
throw new Error("Script blocked")
}
})();
`;
// Scope the scripts
body += scope(await resp.text());
} else if (req.destination === "manifest") {
// Safari exclusive
if (flags.legacy && type.contains("text/cache-manifest")) {
const isFirefox = reqHeaders["user-agent"].includes("Firefox");
body = rewriteCacheManifest(isFirefox);
} else body = rewriteManifest(await resp.text());
}
// Nests
else if (flags.nestedWorkers && req.destination === "worker")
body = isMod
? `
import { proxyLocation } from "${aeroPrefix}worker/worker.js";
self.location = proxyLocation;
`
: `
importScripts("${aeroPrefix}worker/worker.js");
${body}
`;
else if (flags.nestedWorkers && req.destination === "sharedworker")
body = isMod
? `
import { proxyLocation } from "${aeroPrefix}worker/worker.js";
self.location = proxyLocation;
`
: `
importScripts("${aeroPrefix}worker/worker.js");
importScripts("${aeroPrefix}worker/sharedworker.js");
${body}
`;
else if (flags.nestedWorkers && req.destination === "serviceworker")
body = isMod
? `
import { proxyLocation } from "${aeroPrefix}workerApis/worker.js";
self.location = proxyLocation;
`
: `
importScripts("${aeroPrefix}worker/worker.js");
importScripts("${aeroPrefix}worker/sw.js");
${body}
`;
// No rewrites are needed; proceed as normal
else body = resp.body;
rewriteRespHeaders["x-aero-size-transfer"] = null;
rewriteRespHeaders["x-aero-size-encbody"] = null;
// TODO: x-aero-size-transfer
if (typeof body === "string") {
rewriteRespHeaders["x-aero-size-body"] = new TextEncoder().encode(
body
).length;
// TODO: x-aero-size-encbody
} else if (typeof body === "ArrayBuffer") {
rewriteRespHeaders["x-aero-size-body"] = body.byteLength;
// TODO: x-aero-size-encbody
}
const proxyResp = new Response(body, {
status: resp.status ?? 200,
headers: rewrittenRespHeaders,
});
// Cache the response
cache.set(reqUrl, proxyResp.clone());
// Return the response
return proxyResp;
}
export default handle;