From 2e962ee1dcff7fd43d6efb8f1ffb0a1283e1e7be Mon Sep 17 00:00:00 2001 From: Percs <83934299+Percslol@users.noreply.github.com> Date: Mon, 17 Jun 2024 20:26:09 -0500 Subject: [PATCH] do some worker tweaks --- src/worker/index.ts | 111 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 109 insertions(+), 2 deletions(-) diff --git a/src/worker/index.ts b/src/worker/index.ts index 8129f8b..f828b05 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -64,7 +64,28 @@ self.ScramjetServiceWorker = class ScramjetServiceWorker { break; } } - + // downloads + if (request.destination === "document") { + const header = responseHeaders["content-disposition"]; + + // validate header and test for filename + if (!/\s*?((inline|attachment);\s*?)filename=/i.test(header)) { + // if filename= wasn"t specified then maybe the remote specified to download this as an attachment? + // if it"s invalid then we can still possibly test for the attachment/inline type + const type = /^\s*?attachment/i.test(header) + ? "attachment" + : "inline"; + + // set the filename + const [filename] = new URL(response.finalURL).pathname + .split("/") + .slice(-1); + + responseHeaders[ + "content-disposition" + ] = `${type}; filename=${JSON.stringify(filename)}`; + } + } if (responseHeaders["accept"] === "text/event-stream") { responseHeaders["content-type"] = "text/event-stream"; } @@ -80,8 +101,94 @@ self.ScramjetServiceWorker = class ScramjetServiceWorker { } catch (err) { if (!["document", "iframe"].includes(request.destination)) return new Response(undefined, { status: 500 }); - + console.error(err); + + return renderError(err, self.__scramjet$bundle.rewriters.url.decodeUrl(request.url)); } } } + + +function errorTemplate( + trace: string, + fetchedURL: string, +) { + // turn script into a data URI so we don"t have to escape any HTML values + const script = ` + errorTrace.value = ${JSON.stringify(trace)}; + fetchedURL.textContent = ${JSON.stringify(fetchedURL)}; + for (const node of document.querySelectorAll("#hostname")) node.textContent = ${JSON.stringify( + location.hostname + )}; + reload.addEventListener("click", () => location.reload()); + version.textContent = "0.0.1"; + ` + + return ( + ` + + + + Error + + + +

Error processing your request

+
+

Failed to load

+

Internal Server Error

+ +

Try:

+ +

If you"re the administrator of , try:

+ + +
+

Scramjet v

+ + + + ` + ); +} + +/** + * + * @param {unknown} err + * @param {string} fetchedURL + */ +function renderError(err, fetchedURL) { + const headers = { + "content-type": "text/html", + }; + if (crossOriginIsolated) { + headers["Cross-Origin-Embedd'er-Policy"] = "require-corp"; + } + + return new Response( + errorTemplate( + String(err), + fetchedURL + ), + { + status: 500, + headers: headers + } + ); +} +