forked from vortexdl/aero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandle.js
194 lines (162 loc) · 5.47 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
// Routes
import routes from "./routes.js";
// Config
import { aeroPrefix, proxyPrefix, prefix, debug } from "./config.js";
// Utility
import ProxyClient from "./util/ProxyClient.js";
import handleSharedModule from "./util/handleSharedModule.js";
import getRequestUrl from "./util/getRequestUrl.js";
// Cors Emulation
import block from "./util/corsTest.js";
import headersToObject from "./util/headersToObject.js";
import unwrapImports from "./util/unwrapImports.js";
// Rewriters
import headersRewriter from "./rewriters/worker/headers.js";
import rewriteManifest from "./rewriters/worker/manifest.js";
import scope from "./rewriters/shared/scope.js";
// Separate the prefix from the url to get the proxy url isolated
const getPath = new RegExp(`^(${prefix})`, "g");
/**
* Handles the requests
* @param {FetchEvent} The event
* @param {Location} The window location
* @returns {Response} The proxified response
*/
async function handle(event) {
// Construct proxy fetch instance
const proxyClient = new ProxyClient(self.location.origin + proxyPrefix);
const reqUrl = new URL(event.request.url);
const path = reqUrl.pathname + reqUrl.search;
// Remove the module components
if (
path.startsWith(aeroPrefix + "rewriters/shared/") &&
path.endsWith(".js")
)
return await handleSharedModule(event);
// Don't rewrite requests for aero library files
else if (path.startsWith(aeroPrefix))
// Proceed with the request like normal
return await fetch(event.request.url);
var proxyOrigin;
var winUrl;
// Get the origin from the user's window
if (event.clientId !== "") {
// Get the current window
const win = await clients.get(event.clientId);
winUrl = new URL(win.url);
proxyOrigin = new URL(winUrl.pathname.replace(getPath, "")).origin;
}
// Determine if the request was made to load an html file; 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 firstReq =
event.request.mode === "navigate" &&
event.request.destination === "document";
const iFrame = event.request.destination === "iframe";
// Parse the request url to get the url to proxy
const url = getRequestUrl(
winUrl,
path,
proxyOrigin,
reqUrl.origin,
self.location.origin,
firstReq,
iFrame
);
// Ensure the request isn't blocked by CORS
if (await block(url.href))
return new Response("Blocked by CORS", { status: 500 });
if (debug.url)
console.log(
event.request.destination == ""
? `${event.request.method} ${url}`
: `${event.request.method} ${url} (${event.request.destination})`
);
let opts = {
method: event.request.method,
// TODO: Rewrite requestHeaders
headers: event.request.headers,
};
if (event.request.method === "POST") opts.body = await event.request.text();
// Make the request to the proxy
const resp = await proxyClient.fetch(url, opts);
// Rewrite the headers
const headers = headersToObject(resp.headers);
const type = headers["content-type"];
const rewrittenHeaders = headersRewriter(headers);
const html =
// Not all sites respond with a type
typeof type === "undefined" || type.startsWith("text/html");
const rewriteHtml = (firstReq || iFrame) && html;
// Rewrite the body
let body;
if (rewriteHtml) {
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="${prefix + url.origin}/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
window.$aero = {
config: {
prefix: ${prefix},
debug: ${JSON.stringify(debug)}
}
};
</script>
<!-- Injected Aero code -->
${unwrapImports(routes)}
<script>
// This is used to later copy into an iframe or innerhtml
$aero.imports = \`${unwrapImports(routes, true)}\`;
</script>
</head>
${body}
`;
}
} else if (event.request.destination === "script")
// Scope the scripts
body = scope(await resp.text());
else if (event.request.destination === "serviceworker")
// SW nesting by proxifying internal apis
body = `
if (typeof module === "undefined") {
importScripts("./nest/worker.js");
importScripts("./nest/sw.js");
} else {
// sw.js doesn't need any module imports as importScripts isn't a thing in module scripts
import { onevent, Clients.get, self.addEventListener } from "./worker.js";
}
${body}
`;
else if (event.request.destination === "manifest")
body = rewriteManifest(await resp.text());
// No rewrites are needed; proceed as normal
else body = resp.body;
// Return the response
return new Response(body, {
status: resp.status ? resp.status : 200,
headers: rewrittenHeaders,
});
}
export default handle;