From e7e8f381abd48b07df29900cc983ba71fd685718 Mon Sep 17 00:00:00 2001 From: Nebelung Date: Thu, 16 Mar 2023 01:24:31 +0000 Subject: [PATCH] Version 1.6 --- .prettierignore | 1 - CHANGELOG.md | 23 +- README.md | 3 +- package-lock.json | 2 +- package.json | 2 +- public/aero-sw.js | 13 +- public/aero/.editorconfig | 6 + public/aero/.gitignore | 2 + public/aero/.prettierrc.json | 4 + public/aero/LICENSE | 661 ++++++++++++++++++ public/aero/README.md | 88 +++ public/aero/api/document.js | 10 - public/aero/api/element.js | 1 - public/aero/api/location.js | 25 - public/aero/api/navigator.js | 3 - public/aero/api/window.js | 10 - public/aero/bare.sh | 13 + public/aero/bareClient/BareClient.js | 222 ------ public/aero/bareClient/Client.js | 24 - public/aero/bareClient/V1.js | 194 ----- public/aero/bareClient/V2.js | 209 ------ public/aero/bareClient/encodeProtocol.js | 59 -- public/aero/bareClient/gitignore.txt | 2 - public/aero/bareClient/global.js | 18 - public/aero/bareClient/md5.js | 187 ----- public/aero/bareClient/prettierrc.json | 5 - public/aero/bareClient/splitHeaderUtil.js | 85 --- public/aero/browser/api/concealer/css.js | 25 + public/aero/browser/api/concealer/element.js | 126 ++++ public/aero/browser/api/concealer/error.js | 64 ++ public/aero/browser/api/concealer/event.js | 7 + public/aero/browser/api/concealer/file.js | 10 + public/aero/browser/api/concealer/fs.js | 11 + public/aero/browser/api/concealer/http.js | 38 + public/aero/browser/api/concealer/manifest.js | 12 + .../aero/browser/api/concealer/navigation.js | 72 ++ public/aero/browser/api/concealer/payment.js | 25 + .../browser/api/concealer/presentation.js | 23 + public/aero/browser/api/concealer/push.js | 6 + .../aero/browser/api/concealer/reporting.js | 56 ++ public/aero/browser/api/concealer/scoping.js | 82 +++ public/aero/browser/api/concealer/timing.js | 66 ++ public/aero/browser/api/concealer/xml.js | 1 + public/aero/browser/api/event/messages.js | 80 +++ public/aero/browser/api/loc/contentIndex.js | 21 + .../aero/{api => browser/api/loc}/history.js | 13 +- public/aero/browser/api/loc/location.js | 9 + public/aero/browser/api/loc/navigator.js | 95 +++ public/aero/browser/api/loc/popup.js | 9 + public/aero/browser/api/req/http.js | 15 + public/aero/browser/api/req/wrtc.js | 30 + public/aero/browser/api/req/ws.js | 58 ++ public/aero/browser/api/storage/cookie.js | 54 ++ public/aero/browser/api/storage/idb.js | 18 + public/aero/browser/api/storage/sql.js | 22 + public/aero/browser/api/storage/storage.js | 51 ++ public/aero/browser/api/worker/workers.js | 45 ++ public/aero/browser/injects/dom.js | 12 + public/aero/browser/misc/clear.js | 91 +++ public/aero/browser/misc/cors.js | 5 + public/aero/browser/misc/escape.js | 1 + public/aero/browser/misc/frame.js | 50 ++ public/aero/browser/misc/perms.js | 1 + public/aero/browser/misc/proto.js | 16 + public/aero/browser/misc/proxyLocation.js | 50 ++ public/aero/browser/misc/storage.js | 33 + public/aero/browser/rewriters/cloner.js | 36 + public/aero/browser/rewriters/cors.js | 19 + public/aero/browser/rewriters/csp.js | 1 + public/aero/browser/rewriters/cspSrc.js | 42 ++ public/aero/browser/rewriters/html.js | 132 ++++ public/aero/browser/rewriters/htmlSrc.js | 20 + public/aero/browser/xml/intercept.xsl | 7 + public/aero/config.js | 55 +- public/aero/cookie.js | 13 - public/aero/corsTest.js | 20 - public/aero/dom.js | 127 ---- public/aero/getRequestUrl.js | 16 - public/aero/handle.js | 429 ++++++++++-- public/aero/headers.js | 30 - public/aero/init.js | 4 + public/aero/scope.js | 10 - public/aero/shared/cookie.js | 35 + public/aero/shared/scope.js | 195 ++++++ public/aero/shared/src.js | 27 + public/aero/tests/scoping.html | 69 ++ public/aero/this/cors/cache.js | 98 +++ public/aero/this/cors/clear.js | 17 + public/aero/this/cors/test.js | 23 + public/aero/this/dynamic/getConfig.js | 15 + public/aero/this/dynamic/getStore.js | 24 + public/aero/this/handlers/updates.js | 18 + public/aero/this/internal/routes.js | 50 ++ public/aero/this/misc/ProxyFetch.js | 58 ++ public/aero/this/misc/bare/dist/BareClient.js | 1 + public/aero/this/misc/getRequestUrl.js | 66 ++ public/aero/this/misc/headersToObject.js | 5 + public/aero/this/misc/sharedModule.js | 27 + public/aero/this/misc/unwrapImports.js | 19 + public/aero/this/rewriters/cacheManifest.js | 55 ++ public/aero/this/rewriters/manifest.js | 17 + public/aero/this/rewriters/reqHeaders.js | 29 + public/aero/this/rewriters/respHeaders.js | 55 ++ public/aero/vite.config.js | 0 public/aero/worker/normal/location.js | 3 + public/aero/worker/shared/import.js | 8 + public/aero/worker/sw/clients.js | 12 + public/aero/worker/sw/events.js | 25 + public/aero/worker/sw/fetch.js | 17 + public/index.html | 5 +- public/logo.png | Bin 3050 -> 0 bytes public/logos/logo.svg | 10 + public/logos/logo192.png | Bin 0 -> 5454 bytes public/logos/logo512.png | Bin 0 -> 19779 bytes public/manifest.json | 17 +- public/osana/client.js | 1 - public/osana/config.js | 1 - public/osana/sw.js | 1 - src/SettingsLayout.js | 2 +- src/assets/logo.svg | 20 +- src/components/head.js | 33 +- src/components/obfuscate.js | 5 + src/consts.js | 5 +- src/locales/de/index.js | 8 +- src/locales/de/title.json | 9 + src/locales/en/home.json | 4 +- src/locales/en/index.js | 4 +- src/locales/en/title.json | 9 + src/locales/es/index.js | 4 +- src/locales/es/title.json | 9 + src/locales/fr/index.js | 8 +- src/locales/fr/title.json | 9 + src/locales/zh/index.js | 8 +- src/locales/zh/title.json | 9 + src/pages/apps.js | 2 +- src/pages/credits.js | 5 +- src/pages/error.js | 2 +- src/pages/games.js | 2 +- src/pages/home.js | 10 +- src/pages/privacy.js | 2 +- src/pages/settings/search.js | 3 - src/pages/support.js | 2 +- src/proxy.js | 7 +- src/style/style.css | 42 +- src/util.js | 14 +- 145 files changed, 4020 insertions(+), 1456 deletions(-) create mode 100644 public/aero/.editorconfig create mode 100644 public/aero/.gitignore create mode 100644 public/aero/.prettierrc.json create mode 100644 public/aero/LICENSE create mode 100644 public/aero/README.md delete mode 100644 public/aero/api/document.js delete mode 100644 public/aero/api/element.js delete mode 100644 public/aero/api/location.js delete mode 100644 public/aero/api/navigator.js delete mode 100644 public/aero/api/window.js create mode 100755 public/aero/bare.sh delete mode 100644 public/aero/bareClient/BareClient.js delete mode 100644 public/aero/bareClient/Client.js delete mode 100644 public/aero/bareClient/V1.js delete mode 100644 public/aero/bareClient/V2.js delete mode 100644 public/aero/bareClient/encodeProtocol.js delete mode 100644 public/aero/bareClient/gitignore.txt delete mode 100644 public/aero/bareClient/global.js delete mode 100644 public/aero/bareClient/md5.js delete mode 100644 public/aero/bareClient/prettierrc.json delete mode 100644 public/aero/bareClient/splitHeaderUtil.js create mode 100644 public/aero/browser/api/concealer/css.js create mode 100644 public/aero/browser/api/concealer/element.js create mode 100644 public/aero/browser/api/concealer/error.js create mode 100644 public/aero/browser/api/concealer/event.js create mode 100644 public/aero/browser/api/concealer/file.js create mode 100644 public/aero/browser/api/concealer/fs.js create mode 100644 public/aero/browser/api/concealer/http.js create mode 100644 public/aero/browser/api/concealer/manifest.js create mode 100644 public/aero/browser/api/concealer/navigation.js create mode 100644 public/aero/browser/api/concealer/payment.js create mode 100644 public/aero/browser/api/concealer/presentation.js create mode 100644 public/aero/browser/api/concealer/push.js create mode 100644 public/aero/browser/api/concealer/reporting.js create mode 100644 public/aero/browser/api/concealer/scoping.js create mode 100644 public/aero/browser/api/concealer/timing.js create mode 100644 public/aero/browser/api/concealer/xml.js create mode 100644 public/aero/browser/api/event/messages.js create mode 100644 public/aero/browser/api/loc/contentIndex.js rename public/aero/{api => browser/api/loc}/history.js (57%) create mode 100644 public/aero/browser/api/loc/location.js create mode 100644 public/aero/browser/api/loc/navigator.js create mode 100644 public/aero/browser/api/loc/popup.js create mode 100644 public/aero/browser/api/req/http.js create mode 100644 public/aero/browser/api/req/wrtc.js create mode 100644 public/aero/browser/api/req/ws.js create mode 100644 public/aero/browser/api/storage/cookie.js create mode 100644 public/aero/browser/api/storage/idb.js create mode 100644 public/aero/browser/api/storage/sql.js create mode 100644 public/aero/browser/api/storage/storage.js create mode 100644 public/aero/browser/api/worker/workers.js create mode 100644 public/aero/browser/injects/dom.js create mode 100644 public/aero/browser/misc/clear.js create mode 100644 public/aero/browser/misc/cors.js create mode 100644 public/aero/browser/misc/escape.js create mode 100644 public/aero/browser/misc/frame.js create mode 100644 public/aero/browser/misc/perms.js create mode 100644 public/aero/browser/misc/proto.js create mode 100644 public/aero/browser/misc/proxyLocation.js create mode 100644 public/aero/browser/misc/storage.js create mode 100644 public/aero/browser/rewriters/cloner.js create mode 100644 public/aero/browser/rewriters/cors.js create mode 100644 public/aero/browser/rewriters/csp.js create mode 100644 public/aero/browser/rewriters/cspSrc.js create mode 100644 public/aero/browser/rewriters/html.js create mode 100644 public/aero/browser/rewriters/htmlSrc.js create mode 100644 public/aero/browser/xml/intercept.xsl delete mode 100644 public/aero/cookie.js delete mode 100644 public/aero/corsTest.js delete mode 100644 public/aero/dom.js delete mode 100644 public/aero/getRequestUrl.js delete mode 100644 public/aero/headers.js create mode 100644 public/aero/init.js delete mode 100644 public/aero/scope.js create mode 100644 public/aero/shared/cookie.js create mode 100644 public/aero/shared/scope.js create mode 100644 public/aero/shared/src.js create mode 100644 public/aero/tests/scoping.html create mode 100644 public/aero/this/cors/cache.js create mode 100644 public/aero/this/cors/clear.js create mode 100644 public/aero/this/cors/test.js create mode 100644 public/aero/this/dynamic/getConfig.js create mode 100644 public/aero/this/dynamic/getStore.js create mode 100644 public/aero/this/handlers/updates.js create mode 100644 public/aero/this/internal/routes.js create mode 100644 public/aero/this/misc/ProxyFetch.js create mode 100644 public/aero/this/misc/bare/dist/BareClient.js create mode 100644 public/aero/this/misc/getRequestUrl.js create mode 100644 public/aero/this/misc/headersToObject.js create mode 100644 public/aero/this/misc/sharedModule.js create mode 100644 public/aero/this/misc/unwrapImports.js create mode 100644 public/aero/this/rewriters/cacheManifest.js create mode 100644 public/aero/this/rewriters/manifest.js create mode 100644 public/aero/this/rewriters/reqHeaders.js create mode 100644 public/aero/this/rewriters/respHeaders.js create mode 100644 public/aero/vite.config.js create mode 100644 public/aero/worker/normal/location.js create mode 100644 public/aero/worker/shared/import.js create mode 100644 public/aero/worker/sw/clients.js create mode 100644 public/aero/worker/sw/events.js create mode 100644 public/aero/worker/sw/fetch.js delete mode 100644 public/logo.png create mode 100644 public/logos/logo.svg create mode 100644 public/logos/logo192.png create mode 100644 public/logos/logo512.png delete mode 100644 public/osana/client.js delete mode 100644 public/osana/config.js delete mode 100644 public/osana/sw.js create mode 100644 src/locales/de/title.json create mode 100644 src/locales/en/title.json create mode 100644 src/locales/es/title.json create mode 100644 src/locales/fr/title.json create mode 100644 src/locales/zh/title.json diff --git a/.prettierignore b/.prettierignore index 0195058..fbb3aea 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,6 +1,5 @@ build public/uv -public/osana public/stomp public/dip public/aero diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fbd1ff..03783c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,14 +41,27 @@ - [x] Fixed links style - [x] Fixed links underline when obfuscated +### Version 1.6 + - [x] Logo now updates color depending on the theme! + - [x] Update Aero + - [x] Translate page titles (fix) + - [x] Revert to old logo + - [x] Rework logo svg + - [x] Fix translations + - [x] Update css + - [x] Update manifest with more logos + - [x] Remove Osana + - [x] No obfuscation option in "/consts.js" + - [x] Obfuscate more text + ### Upcoming - - [ ] Translate page titles - - [ ] Obfuscate more text - - [ ] Obfuscate links (href) - - [ ] No obfuscation option in "/consts.js" + - [ ] Add a blocklist option + - [ ] Reset all settings + - [ ] Export/import settings + - [ ] Update other tabs on settings change - [ ] Update proxies - [ ] Add games - [ ] Custom themes - [ ] Change page names to 1, 2, 3 etc. - [ ] Fix discord/github links - - [ ] Local fonts + - [ ] Local fonts \ No newline at end of file diff --git a/README.md b/README.md index 5e5846c..b570978 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,8 @@ Click a button at the top of this page and follow the directions for an easy way ## Configuration ### Bare Server -Change the bare server in [`/src/consts.js`](https://github.com/Metallic-Web/Metallic/blob/main/src/consts.js) +`const obfuscation = true | false;` - Obfuscate text +`const bareServerURL = new URL(url);` - Main bare server and Stomp bare server ## Changelog View the changelog/roadmap [here](https://github.com/Metallic-Web/Metallic/blob/main/CHANGELOG.md) diff --git a/package-lock.json b/package-lock.json index 736e53b..11d740e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "metallic", - "version": "1.4", + "version": "1.6", "lockfileVersion": 2, "requires": true, "packages": { diff --git a/package.json b/package.json index 22ed731..7f4d552 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "metallic", - "version": "1.4", + "version": "1.6", "description": "A powerful web proxy build for speed and customization.", "repository": "https://github.com/Metallic-Web/Metallic.git", "license": "MIT", diff --git a/public/aero-sw.js b/public/aero-sw.js index 08984d0..c7dcda2 100644 --- a/public/aero-sw.js +++ b/public/aero-sw.js @@ -1,5 +1,10 @@ -import { handle } from "/aero/handle.js"; +import handle from "./aero/handle.js"; +import "./aero/init.js"; -self.addEventListener("fetch", (event) => - event.respondWith(handle(location, event)) -); +self.addEventListener("install", () => self.skipWaiting()); + +self.addEventListener("fetch", async event => + event.respondWith( + handle(event).catch(err => new Response(err.stack, { status: 500 })) + ) +); \ No newline at end of file diff --git a/public/aero/.editorconfig b/public/aero/.editorconfig new file mode 100644 index 0000000..79812d0 --- /dev/null +++ b/public/aero/.editorconfig @@ -0,0 +1,6 @@ +[*] +charset = utf-8 +insert_final_newline = false +end_of_line = lf +indent_style = tabs +indent_size = 4 \ No newline at end of file diff --git a/public/aero/.gitignore b/public/aero/.gitignore new file mode 100644 index 0000000..8ae05d1 --- /dev/null +++ b/public/aero/.gitignore @@ -0,0 +1,2 @@ +config.js +this/misc/bare/BareClient.js \ No newline at end of file diff --git a/public/aero/.prettierrc.json b/public/aero/.prettierrc.json new file mode 100644 index 0000000..228556b --- /dev/null +++ b/public/aero/.prettierrc.json @@ -0,0 +1,4 @@ +{ + "useTabs": true, + "arrowParens": "avoid" +} diff --git a/public/aero/LICENSE b/public/aero/LICENSE new file mode 100644 index 0000000..2b18402 --- /dev/null +++ b/public/aero/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2020-2023 Ryan Wilson + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users" freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work"s +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users" Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work"s +users, your or third parties" legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program"s source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation"s users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party"s predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor"s "contributor version". + + A contributor"s "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor"s essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient"s use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others" Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy"s +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. \ No newline at end of file diff --git a/public/aero/README.md b/public/aero/README.md new file mode 100644 index 0000000..b7fe876 --- /dev/null +++ b/public/aero/README.md @@ -0,0 +1,88 @@ +# aero + +Aero is a safe, developer friendly, and innovative interception proxy. Aero provides a good balance of excellent site support speed, while also having a clean and organized codebase. A deployable version can be found [here](https://github.com/ProxyHaven/aero-deploy) + +# How to use aero + +1. Make sure your backend serves an [aero](https://github.com/ProxyHaven/aero-backends) _recommended_ or a [TompHTTP Compatible Backend](https://github.com/tomphttp) + > If you are using bare, run bare.sh +2. Make sure you included aero into your site +3. Create a service worker like this in the topmost directory + +```js +import handle from "./aero/handle.js"; +import "./aero/init.js"; + +self.addEventListener("install", () => self.skipWaiting()); + +self.addEventListener("fetch", async event => + event.respondWith( + handle(event).catch(err => new Response(err.stack, { status: 500 })) + ) +); +``` + +4. Register the service worker in a script on your main page like this + _This example uses our [sdk](https://github.com/ProxyHaven/aero-sdk); allowing you to safely manage deployments of multiple proxies, and supports dynamic config updates_ + +```js +import { proxyApi } from "./aero/config.js"; + +import ProxyManager from "./sdk/ProxyManager.js"; + +const proxyManager = new ProxyManager(); + +proxyManager.add("/sw.js", proxyApi); +``` + +# How aero works + +## Precedence + +Previously, proxies could barely handle more than one person, this was due to all the site's code being rewritten on the backend. Because the code was being rewritten on the backend, it required having to share backend rewrite code with frontend code. This was not only slow, but also allowed the possibility of Slowloris attacks against the proxies. + +## Interception + +aero takes a different approach by not only completely avoiding rewrites, but also by doing all the rewrites on the frontend with no parsers! This allows aero to avoid speed delays. It does this by intercepting requests through a service worker, where the request is routed to the while also injecting important scripts. This prevents the need to hook into code that previously needed to be rewritten to redirect requests saving time and resources. All of its conceptual methods are optimal. + +## Extensibility + +One of our strengths is Extensibility. This is done by making aero readable and customizable by anyone. Every aspect of it is documented. Even if you are not a programmer, you can understand how aero works. There are configs to control functionality - in order to have no compromises and allow those who can't write code to easily customize it. If you are a programmer, you will appreciate all the hooks and guiding variables we have to easily modify the code. We are working on an even better way of making extensions: event-driven middleware that takes advantage of its internals. + +## HTML Interception + +HTML is intercepted and rewritten through a Mutation Observer where important elements are rewritten. Script elements with inline code and elements with integrity values set need to be cloned due to the browser's security restrictions. + +## Deep Scope Property Checking DSPC + +Location objects are replaced with a fake Location api, and also in the case of the site trying to escape the location scoping bracket property accessors for certain objects are checked using our scope function that evaluates the expression in hopes of intercepting the attempted location or window call. Additionaly, this scoping is integrated into Eval, Function Class, and Reflect interceptors. _Support for this feature is enabled in flags_ + +## Cache Emulation + +### HTTP Caches + +HTTP caches are removed and replaced by a system using aero's own cache stores. This allows us to have caches stored for a specific origin. This is important for support since Clear-Site-Data deletes every origin's cache making aero otherwise detectable. + +### Cache Manifests + +aero rewrites the paths in the cache manfiests files + +### Clear Site Data + +Whenever this header is present a script is injected to aero that handles clearing the data since it can't be done in the SW itself + +## Cors Emulation + +Unlike other proxies that simply delete the cors policy and ignore it, aero abides by the intended security features by keeping them in place. Without Cors Emulation, sites can infer either the browser doesn't support modern security standards or that a proxy is being used. This means that the site would've been lacking support; no longer with aero! _Support for this feature is enabled in flags_ + +### SW Interception + +aero has interceptors in other SWs to adhere to cache emulation and hide the fact real http caches aren't being used. + +### Cors Testing + +Aero sends an request to the site without the proxy in order to check if they would allow it + +### Trusted Types + +We support trusted types through interceptors. Aero simply do nothing because it already knows the is origin secure. diff --git a/public/aero/api/document.js b/public/aero/api/document.js deleted file mode 100644 index 17f7489..0000000 --- a/public/aero/api/document.js +++ /dev/null @@ -1,10 +0,0 @@ -// Incomplete - -Object.defineProperty(document, 'domain', { - get() { - return fakeLocation.hostname; - }, - set(value) { - return value; - } -}); \ No newline at end of file diff --git a/public/aero/api/element.js b/public/aero/api/element.js deleted file mode 100644 index 3ebeed5..0000000 --- a/public/aero/api/element.js +++ /dev/null @@ -1 +0,0 @@ -// Incomplete \ No newline at end of file diff --git a/public/aero/api/location.js b/public/aero/api/location.js deleted file mode 100644 index b0e0e18..0000000 --- a/public/aero/api/location.js +++ /dev/null @@ -1,25 +0,0 @@ -// Incomplete - -function wrap(url) { - return prefix + url; -} - -let fakeLocation = new URL(location.href.match(/(?<=\/go\/).*/g)[0]); - -const locationProxy = new Proxy({}, { - get(target, prop) { - if (typeof target[prop] === 'function') - return { - assign: url => wrap(url), - toString: url => fakeLocation.toString(), - reload: location.reload - }[prop]; - return fakeLocation[prop]; - }, - set(target, prop, value) { - if (prop === 'href') - location[prop] = config.http.prefix + fakeLocation.origin + value; - } -}); - -document._location = locationProxy; \ No newline at end of file diff --git a/public/aero/api/navigator.js b/public/aero/api/navigator.js deleted file mode 100644 index 13359a3..0000000 --- a/public/aero/api/navigator.js +++ /dev/null @@ -1,3 +0,0 @@ -// Incomplete - -navigator.registerProtocolHandler = null; \ No newline at end of file diff --git a/public/aero/api/window.js b/public/aero/api/window.js deleted file mode 100644 index 4acee04..0000000 --- a/public/aero/api/window.js +++ /dev/null @@ -1,10 +0,0 @@ -// Incomplete - -open = new Proxy(open, { - apply(target, that, args) { - if (args[0]) - args[0] = wrap(args[0]); - - return Reflect.apply(...arguments); - } -}); \ No newline at end of file diff --git a/public/aero/bare.sh b/public/aero/bare.sh new file mode 100755 index 0000000..ede5be4 --- /dev/null +++ b/public/aero/bare.sh @@ -0,0 +1,13 @@ +cd this/misc + +if [ ! -d bare ] +then + git clone https://github.com/tomphttp/bare-client bare +fi + +cd bare + +git pull + +npm install +npm run build \ No newline at end of file diff --git a/public/aero/bareClient/BareClient.js b/public/aero/bareClient/BareClient.js deleted file mode 100644 index 016eab2..0000000 --- a/public/aero/bareClient/BareClient.js +++ /dev/null @@ -1,222 +0,0 @@ -// Implements the protocol for requesting bare data from a server -// See ../Server/Send.mjs - -export * from './Client.js'; -import ClientV1 from './V1.js'; -import ClientV2 from './V2.js'; - -/** - * @typedef {object.} BareHeaders - */ - -/** - * @typedef {object} BareMeta - * @property {object} headers - */ - -/** - * @description WebSocket with an additional property. - * @typedef {object} BareWebSocketBase - * @property {Promise} meta - */ - -/** - * @typedef {WebSocket & BareWebSocketBase} BareWebSocket - */ - -/** - * @description A Response with additional properties. - * @typedef {object} BareResponseBase - * @property {Response} rawResponse - * @property {BareHeaders} rawHeaders - * @property {boolean} cached - */ - -/** - * @typedef {Response & BareResponseBase} BareResponse - */ - -/** - * @typedef {object} BareFetchInit - * @property {'GET'|'POST'|'DELETE'|'OPTIONS'|'PUT'|'PATCH'|'UPDATE'} [method] - * @property {Headers|BareHeaders} [headers] - * @property {Blob|BufferSource|FormData|URLSearchParams|ReadableStream} [body] - * @property {'default'|'no-store'|'reload'|'no-cache'|'force-cache'|'only-if-cached'} [cache] - * @property {AbortSignal} signal - * @returns {BareResponse} - */ - -export default class BareClient { - ready = false; - /** - * - * @param {string|URL} server - A full URL to theb are server. - * @param {object} [data] - The a copy of the Bare server data found in BareClient.data. If specified, this data will be loaded. Otherwise, a request will be made to the bare server (upon fetching or creating a WebSocket). - */ - constructor(server, data) { - this.server = new URL(server); - - if (typeof data === 'object') { - this.#loadData(data); - } - } - #loadData(data) { - let found = false; - - // newest-oldest - for (let constructor of [ClientV2, ClientV1]) { - if (data.versions.includes(`v${constructor.version}`)) { - this.client = new constructor(this); - found = true; - break; - } - } - - if (!found) { - throw new Error(`Unable to find compatible client version.`); - } - - this.data = data; - this.ready = true; - } - async #work() { - if (this.ready === true) { - return; - } - - const outgoing = await fetch(this.server); - - if (!outgoing.ok) { - throw new Error( - `Unable to fetch Bare meta: ${outgoing.status} ${await outgoing.text()}` - ); - } - - this.#loadData(await outgoing.json()); - } - /** - * - * @param {'GET'|'POST'|'DELETE'|'OPTIONS'|'PUT'|'PATCH'|'UPDATE'} method - * @param {BareHeaders} request_headers - * @param {Blob|BufferSource|FormData|URLSearchParams|ReadableStream} body - * @param {'http:'|'https:'} protocol - * @param {string} host - * @param {string|number} port - * @param {string} path - * @param {'default'|'no-store'|'reload'|'no-cache'|'force-cache'|'only-if-cached'} cache - * @param {AbortSignal} signal - * @returns {BareResponse} - */ - async request( - method, - request_headers, - body, - protocol, - host, - port, - path, - cache, - signal - ) { - await this.#work(); - return this.client.request( - method, - request_headers, - body, - protocol, - host, - port, - path, - cache, - signal - ); - } - /** - * - * @param {BareHeaders} request_headers - * @param {'ws:'|'wss:'} protocol - * @param {string} host - * @param {string|number} port - * @param {string} path - * @returns {BareWebSocket} - */ - async connect(request_headers, protocol, host, port, path) { - await this.#work(); - return this.client.connect(request_headers, protocol, host, port, path); - } - /** - * - * @param {string|URL} url - * @param {BareFetchInit} init - * @returns {BareResponse} - */ - async fetch(url, init = {}) { - url = new URL(url); - - let method; - - if (typeof init.method === 'string') { - method = init.method; - } else { - method = 'GET'; - } - - let body; - - if (init.body !== undefined && init.body !== null) { - body = init.body; - } - - let headers; - - if (typeof init.headers === 'object' && init.headers !== null) { - if (init.headers instanceof Headers) { - headers = Object.fromEntries(init.headers); - } else { - headers = init.headers; - } - } else { - headers = {}; - } - - headers.host = url.host; - - let cache; - - if (typeof init.cache === 'string') { - cache = init.cache; - } else { - cache = 'default'; - } - - let signal; - - if (init.signal instanceof AbortSignal) { - signal = init.signal; - } - - let port; - - if (url.port === '') { - if (url.protocol === 'https:') { - port = '443'; - } else { - port = '80'; - } - } else { - port = url.port; - } - - return this.request( - method, - headers, - body, - url.protocol, - url.hostname, - port, - url.pathname + url.search, - cache, - signal - ); - } -} diff --git a/public/aero/bareClient/Client.js b/public/aero/bareClient/Client.js deleted file mode 100644 index 33d66a8..0000000 --- a/public/aero/bareClient/Client.js +++ /dev/null @@ -1,24 +0,0 @@ -export const statusEmpty = [101, 204, 205, 304]; -export const statusCache = [304]; - -export class BareError extends Error { - constructor(status, body) { - super(body.message); - this.status = status; - this.body = body; - } -} - -export default class Client { - constructor(bare) { - this.bare = bare; - this.version = this.constructor.version; - this.base = new URL(`./v${this.version}/`, this.bare.server); - } - async request() { - throw new Error('Not implemented'); - } - async connect() { - throw new Error('Not implemented'); - } -} diff --git a/public/aero/bareClient/V1.js b/public/aero/bareClient/V1.js deleted file mode 100644 index d41a913..0000000 --- a/public/aero/bareClient/V1.js +++ /dev/null @@ -1,194 +0,0 @@ -import Client, { BareError, statusEmpty } from './Client.js'; -import { encodeProtocol } from './encodeProtocol.js'; -import global from './global.js'; - -const { fetch, WebSocket } = global; - -export default class ClientV1 extends Client { - static version = 1; - constructor(...args) { - super(...args); - - this.ws = new URL(this.base); - this.http = new URL(this.base); - this.new_meta = new URL('./ws-new-meta', this.base); - this.get_meta = new URL(`./ws-meta`, this.base); - - if (this.ws.protocol === 'https:') { - this.ws.protocol = 'wss:'; - } else { - this.ws.protocol = 'ws:'; - } - } - async connect(request_headers, protocol, host, port, path) { - const assign_meta = await fetch(this.new_meta, { method: 'GET' }); - - if (!assign_meta.ok) { - throw BareError(assign_meta.status, await assign_meta.json()); - } - - const id = await assign_meta.text(); - - const socket = new WebSocket(this.ws, [ - 'bare', - encodeProtocol( - JSON.stringify({ - remote: { - protocol, - host, - port, - path, - }, - headers: request_headers, - forward_headers: [ - 'accept-encoding', - 'accept-language', - 'sec-websocket-extensions', - 'sec-websocket-key', - 'sec-websocket-version', - ], - id, - }) - ), - ]); - - socket.meta = new Promise((resolve, reject) => { - socket.addEventListener('open', async () => { - const outgoing = await fetch(this.get_meta, { - headers: { - 'x-bare-id': id, - }, - method: 'GET', - }); - - if (!outgoing.ok) { - reject(new BareError(outgoing.status, await outgoing.json())); - } - - resolve(await outgoing.json()); - }); - - socket.addEventListener('error', reject); - }); - - return socket; - } - async request( - method, - request_headers, - body, - protocol, - host, - port, - path, - _cache, - signal - ) { - if (protocol.startsWith('blob:')) { - const response = await fetch(`blob:${location.origin}${path}`); - response.jsonHeaders = Object.fromEntries(response.headers.entries()); - return response; - } - - const bare_headers = {}; - - if (request_headers instanceof Headers) { - for (let [header, value] of request_headers) { - bare_headers[header] = value; - } - } else { - for (let header in request_headers) { - bare_headers[header] = request_headers[header]; - } - } - - const forward_headers = ['accept-encoding', 'accept-language']; - - const options = { - credentials: 'omit', - method: method, - signal, - }; - - if (body !== undefined) { - options.body = body; - } - - // bare can be an absolute path containing no origin, it becomes relative to the script - const request = new Request(this.http, options); - - this.#write_bare_request( - request, - protocol, - host, - path, - port, - bare_headers, - forward_headers - ); - - const response = await fetch(request); - - const read_response = await this.#read_bare_response(response); - - let { status, statusText, headers, rawHeaders } = read_response; - - let result; - - if (statusEmpty.includes(status)) { - result = new Response(undefined, { - status, - statusText, - headers, - }); - } else { - result = new Response(response.body, { - status, - statusText, - headers, - }); - } - - result.rawHeaders = rawHeaders; - result.rawResponse = rawResponse; - result.cached = false; - - return result; - } - async #read_bare_response(response) { - if (!response.ok) { - throw new BareError(response.status, await response.json()); - } - - const status = parseInt(response.headers.get('x-bare-status')); - const statusText = response.headers.get('x-bare-status-text'); - const rawHeaders = JSON.parse(response.headers.get('x-bare-headers')); - const headers = new Headers(rawHeaders); - - return { - status, - statusText, - rawHeaders, - headers, - }; - } - #write_bare_request( - request, - protocol, - host, - path, - port, - bare_headers, - forward_headers - ) { - request.headers.set('x-bare-protocol', protocol); - request.headers.set('x-bare-host', host); - request.headers.set('x-bare-path', path); - request.headers.set('x-bare-port', port); - request.headers.set('x-bare-headers', JSON.stringify(bare_headers)); - request.headers.set( - 'x-bare-forward-headers', - JSON.stringify(forward_headers) - ); - } -} diff --git a/public/aero/bareClient/V2.js b/public/aero/bareClient/V2.js deleted file mode 100644 index dd7513e..0000000 --- a/public/aero/bareClient/V2.js +++ /dev/null @@ -1,209 +0,0 @@ -import Client, { BareError, statusCache, statusEmpty } from './Client.js'; -import { split_headers, join_headers } from './splitHeaderUtil.js'; -import md5 from './md5.js'; -import global from './global.js'; - -const { fetch, WebSocket, Request } = global; - -export default class ClientV2 extends Client { - static version = 2; - constructor(...args) { - super(...args); - - this.ws = new URL(this.base); - this.http = new URL(this.base); - this.new_meta = new URL('./ws-new-meta', this.base); - this.get_meta = new URL(`./ws-meta`, this.base); - - if (this.ws.protocol === 'https:') { - this.ws.protocol = 'wss:'; - } else { - this.ws.protocol = 'ws:'; - } - } - async connect(request_headers, protocol, host, port, path) { - const request = new Request(this.new_meta); - - this.#write_bare_request( - request.headers, - protocol, - host, - path, - port, - request_headers - ); - - const assign_meta = await fetch(request); - - if (!assign_meta.ok) { - throw new BareError(assign_meta.status, await assign_meta.json()); - } - - const id = await assign_meta.text(); - - const socket = new WebSocket(this.ws, [id]); - - socket.meta = new Promise((resolve, reject) => { - socket.addEventListener('open', async () => { - const outgoing = await fetch(this.get_meta, { - headers: { - 'x-bare-id': id, - }, - method: 'GET', - }); - - resolve(await this.#read_bare_response(outgoing)); - }); - - socket.addEventListener('error', reject); - }); - - return socket; - } - async request( - method, - request_headers, - body, - protocol, - host, - port, - path, - cache, - signal - ) { - if (protocol.startsWith('blob:')) { - const response = await fetch(`blob:${location.origin}${path}`); - response.jsonHeaders = Object.fromEntries(response.headers.entries()); - return response; - } - - const bare_headers = {}; - - if (request_headers instanceof Headers) { - for (let [header, value] of request_headers) { - bare_headers[header] = value; - } - } else { - for (let header in request_headers) { - bare_headers[header] = request_headers[header]; - } - } - - const options = { - credentials: 'omit', - method: method, - signal, - }; - - if (cache !== 'only-if-cached') { - options.cache = cache; - } - - if (body !== undefined) { - options.body = body; - } - - const request = new Request( - this.http + '?cache=' + md5(`${protocol}${host}${port}${path}`), - options - ); - - this.#write_bare_request( - request.headers, - protocol, - host, - path, - port, - bare_headers - ); - - const response = await fetch(request); - - const read_response = await this.#read_bare_response(response); - - let { status, statusText, headers, rawHeaders } = read_response; - - let result; - - if (statusCache.includes(status)) { - status = response.status; - statusText = response.statusText; - } - - if (statusEmpty.includes(status)) { - result = new Response(undefined, { - status, - statusText, - headers, - }); - } else { - result = new Response(response.body, { - status, - statusText, - headers, - }); - } - - result.rawHeaders = rawHeaders; - result.rawResponse = response; - result.cached = statusCache.includes(read_response.status); - - return result; - } - async #read_bare_response(response) { - if (!response.ok) { - throw new BareError(response.status, await response.json()); - } - - const response_headers = join_headers(response.headers); - - if (response_headers.error) { - throw new BareError(response_headers.error); - } - - const status = parseInt(response_headers.get('x-bare-status')); - const statusText = response_headers.get('x-bare-status-text'); - const rawHeaders = JSON.parse(response_headers.get('x-bare-headers')); - const headers = new Headers(rawHeaders); - - return { - status, - statusText, - headers, - rawHeaders, - }; - } - #write_bare_request( - headers, - protocol, - host, - path, - port, - bare_headers, - forward_headers = ['cookie', 'content-security-policy', 'user-agent', 'pragma', 'x-frame-options'], - pass_headers = [], - pass_status = [] - ) { - headers.set('x-bare-protocol', protocol); - headers.set('x-bare-host', host); - headers.set('x-bare-path', path); - headers.set('x-bare-port', port); - headers.set('x-bare-headers', JSON.stringify(bare_headers)); - - for (let header of forward_headers) { - headers.append('x-bare-forward-headers', header); - } - - for (let header of pass_headers) { - headers.append('x-bare-pass-headers', header); - } - - for (let status of pass_status) { - headers.append('x-bare-pass-status', status); - } - - split_headers(headers); - - return headers; - } -} diff --git a/public/aero/bareClient/encodeProtocol.js b/public/aero/bareClient/encodeProtocol.js deleted file mode 100644 index f7f18f4..0000000 --- a/public/aero/bareClient/encodeProtocol.js +++ /dev/null @@ -1,59 +0,0 @@ -const valid_chars = - "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"; -const reserved_chars = '%'; - -export function validProtocol(protocol) { - protocol = protocol.toString(); - - for (let i = 0; i < protocol.length; i++) { - const char = protocol[i]; - - if (!valid_chars.includes(char)) { - return false; - } - } - - return true; -} - -export function encodeProtocol(protocol) { - protocol = protocol.toString(); - - let result = ''; - - for (let i = 0; i < protocol.length; i++) { - const char = protocol[i]; - - if (valid_chars.includes(char) && !reserved_chars.includes(char)) { - result += char; - } else { - const code = char.charCodeAt(); - result += '%' + code.toString(16).padStart(2, 0); - } - } - - return result; -} - -export function decodeProtocol(protocol) { - if (typeof protocol != 'string') - throw new TypeError('protocol must be a string'); - - let result = ''; - - for (let i = 0; i < protocol.length; i++) { - const char = protocol[i]; - - if (char == '%') { - const code = parseInt(protocol.slice(i + 1, i + 3), 16); - const decoded = String.fromCharCode(code); - - result += decoded; - i += 2; - } else { - result += char; - } - } - - return result; -} diff --git a/public/aero/bareClient/gitignore.txt b/public/aero/bareClient/gitignore.txt deleted file mode 100644 index bc7e829..0000000 --- a/public/aero/bareClient/gitignore.txt +++ /dev/null @@ -1,2 +0,0 @@ -/node_modules/ -/package-lock.json \ No newline at end of file diff --git a/public/aero/bareClient/global.js b/public/aero/bareClient/global.js deleted file mode 100644 index 79a4bf7..0000000 --- a/public/aero/bareClient/global.js +++ /dev/null @@ -1,18 +0,0 @@ -// Locates the global object. - -let g; - -if (typeof self === 'object' && self !== undefined) { - g = self; -} -if (typeof globalThis === 'object' && globalThis !== undefined) { - g = globalThis; -} else if (typeof window === 'object' && window !== undefined) { - g = window; -} - -/** - * @type {globalThis} - */ -let global; -export default global = g; diff --git a/public/aero/bareClient/md5.js b/public/aero/bareClient/md5.js deleted file mode 100644 index 0c14271..0000000 --- a/public/aero/bareClient/md5.js +++ /dev/null @@ -1,187 +0,0 @@ -// https://www.myersdaily.org/joseph/javascript/md5.js - -function md5cycle(x, k) { -var a = x[0], b = x[1], c = x[2], d = x[3]; - -a = ff(a, b, c, d, k[0], 7, -680876936); -d = ff(d, a, b, c, k[1], 12, -389564586); -c = ff(c, d, a, b, k[2], 17, 606105819); -b = ff(b, c, d, a, k[3], 22, -1044525330); -a = ff(a, b, c, d, k[4], 7, -176418897); -d = ff(d, a, b, c, k[5], 12, 1200080426); -c = ff(c, d, a, b, k[6], 17, -1473231341); -b = ff(b, c, d, a, k[7], 22, -45705983); -a = ff(a, b, c, d, k[8], 7, 1770035416); -d = ff(d, a, b, c, k[9], 12, -1958414417); -c = ff(c, d, a, b, k[10], 17, -42063); -b = ff(b, c, d, a, k[11], 22, -1990404162); -a = ff(a, b, c, d, k[12], 7, 1804603682); -d = ff(d, a, b, c, k[13], 12, -40341101); -c = ff(c, d, a, b, k[14], 17, -1502002290); -b = ff(b, c, d, a, k[15], 22, 1236535329); - -a = gg(a, b, c, d, k[1], 5, -165796510); -d = gg(d, a, b, c, k[6], 9, -1069501632); -c = gg(c, d, a, b, k[11], 14, 643717713); -b = gg(b, c, d, a, k[0], 20, -373897302); -a = gg(a, b, c, d, k[5], 5, -701558691); -d = gg(d, a, b, c, k[10], 9, 38016083); -c = gg(c, d, a, b, k[15], 14, -660478335); -b = gg(b, c, d, a, k[4], 20, -405537848); -a = gg(a, b, c, d, k[9], 5, 568446438); -d = gg(d, a, b, c, k[14], 9, -1019803690); -c = gg(c, d, a, b, k[3], 14, -187363961); -b = gg(b, c, d, a, k[8], 20, 1163531501); -a = gg(a, b, c, d, k[13], 5, -1444681467); -d = gg(d, a, b, c, k[2], 9, -51403784); -c = gg(c, d, a, b, k[7], 14, 1735328473); -b = gg(b, c, d, a, k[12], 20, -1926607734); - -a = hh(a, b, c, d, k[5], 4, -378558); -d = hh(d, a, b, c, k[8], 11, -2022574463); -c = hh(c, d, a, b, k[11], 16, 1839030562); -b = hh(b, c, d, a, k[14], 23, -35309556); -a = hh(a, b, c, d, k[1], 4, -1530992060); -d = hh(d, a, b, c, k[4], 11, 1272893353); -c = hh(c, d, a, b, k[7], 16, -155497632); -b = hh(b, c, d, a, k[10], 23, -1094730640); -a = hh(a, b, c, d, k[13], 4, 681279174); -d = hh(d, a, b, c, k[0], 11, -358537222); -c = hh(c, d, a, b, k[3], 16, -722521979); -b = hh(b, c, d, a, k[6], 23, 76029189); -a = hh(a, b, c, d, k[9], 4, -640364487); -d = hh(d, a, b, c, k[12], 11, -421815835); -c = hh(c, d, a, b, k[15], 16, 530742520); -b = hh(b, c, d, a, k[2], 23, -995338651); - -a = ii(a, b, c, d, k[0], 6, -198630844); -d = ii(d, a, b, c, k[7], 10, 1126891415); -c = ii(c, d, a, b, k[14], 15, -1416354905); -b = ii(b, c, d, a, k[5], 21, -57434055); -a = ii(a, b, c, d, k[12], 6, 1700485571); -d = ii(d, a, b, c, k[3], 10, -1894986606); -c = ii(c, d, a, b, k[10], 15, -1051523); -b = ii(b, c, d, a, k[1], 21, -2054922799); -a = ii(a, b, c, d, k[8], 6, 1873313359); -d = ii(d, a, b, c, k[15], 10, -30611744); -c = ii(c, d, a, b, k[6], 15, -1560198380); -b = ii(b, c, d, a, k[13], 21, 1309151649); -a = ii(a, b, c, d, k[4], 6, -145523070); -d = ii(d, a, b, c, k[11], 10, -1120210379); -c = ii(c, d, a, b, k[2], 15, 718787259); -b = ii(b, c, d, a, k[9], 21, -343485551); - -x[0] = add32(a, x[0]); -x[1] = add32(b, x[1]); -x[2] = add32(c, x[2]); -x[3] = add32(d, x[3]); - -} - -function cmn(q, a, b, x, s, t) { -a = add32(add32(a, q), add32(x, t)); -return add32((a << s) | (a >>> (32 - s)), b); -} - -function ff(a, b, c, d, x, s, t) { -return cmn((b & c) | ((~b) & d), a, b, x, s, t); -} - -function gg(a, b, c, d, x, s, t) { -return cmn((b & d) | (c & (~d)), a, b, x, s, t); -} - -function hh(a, b, c, d, x, s, t) { -return cmn(b ^ c ^ d, a, b, x, s, t); -} - -function ii(a, b, c, d, x, s, t) { -return cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -function md51(s) { -var n = s.length, -state = [1732584193, -271733879, -1732584194, 271733878], i; -for (i=64; i<=s.length; i+=64) { -md5cycle(state, md5blk(s.substring(i-64, i))); -} -s = s.substring(i-64); -var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; -for (i=0; i>2] |= s.charCodeAt(i) << ((i%4) << 3); -tail[i>>2] |= 0x80 << ((i%4) << 3); -if (i > 55) { -md5cycle(state, tail); -for (i=0; i<16; i++) tail[i] = 0; -} -tail[14] = n*8; -md5cycle(state, tail); -return state; -} - -/* there needs to be support for Unicode here, - * unless we pretend that we can redefine the MD-5 - * algorithm for multi-byte characters (perhaps - * by adding every four 16-bit characters and - * shortening the sum to 32 bits). Otherwise - * I suggest performing MD-5 as if every character - * was two bytes--e.g., 0040 0025 = @%--but then - * how will an ordinary MD-5 sum be matched? - * There is no way to standardize text to something - * like UTF-8 before transformation; speed cost is - * utterly prohibitive. The JavaScript standard - * itself needs to look at this: it should start - * providing access to strings as preformed UTF-8 - * 8-bit unsigned value arrays. - */ -function md5blk(s) { /* I figured global was faster. */ -var md5blks = [], i; /* Andy King said do it this way. */ -for (i=0; i<64; i+=4) { -md5blks[i>>2] = s.charCodeAt(i) -+ (s.charCodeAt(i+1) << 8) -+ (s.charCodeAt(i+2) << 16) -+ (s.charCodeAt(i+3) << 24); -} -return md5blks; -} - -var hex_chr = '0123456789abcdef'.split(''); - -function rhex(n) -{ -var s='', j=0; -for(; j<4; j++) -s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] -+ hex_chr[(n >> (j * 8)) & 0x0F]; -return s; -} - -function hex(x) { -for (var i=0; i> 16) + (y >> 16) + (lsw >> 16); -return (msw << 16) | (lsw & 0xFFFF); -} -} - -export default md5; \ No newline at end of file diff --git a/public/aero/bareClient/prettierrc.json b/public/aero/bareClient/prettierrc.json deleted file mode 100644 index 6f6184c..0000000 --- a/public/aero/bareClient/prettierrc.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "useTabs": true, - "arrowParens": "avoid", - "singleQuote": true -} diff --git a/public/aero/bareClient/splitHeaderUtil.js b/public/aero/bareClient/splitHeaderUtil.js deleted file mode 100644 index 1a73bb3..0000000 --- a/public/aero/bareClient/splitHeaderUtil.js +++ /dev/null @@ -1,85 +0,0 @@ -// import Headers in NodeJS environments -// this line can safely be removed in browser environments -// import { Headers } from './AbstractMessage.js'; - -/** - * - * @typedef {object} ErrorResult - * @property {{message:string,code:string,id:string}} error - */ - -/** @constant - @type {number} - @default -*/ -const MAX_HEADER_VALUE = 3072; - -/** - * - * @param {Headers} headers - * @returns {Headers} split headers - */ -export function split_headers(headers) { - headers = new Headers(headers); - - if (headers.has('x-bare-headers')) { - const value = headers.get('x-bare-headers'); - - if (value.length > MAX_HEADER_VALUE) { - headers.delete('x-bare-headers'); - - let split = 0; - - for (let i = 0; i < value.length; i += MAX_HEADER_VALUE) { - const part = value.slice(i, i + MAX_HEADER_VALUE); - - const id = split++; - headers.set(`x-bare-headers-${id}`, `;${part}`); - } - } - } - - return headers; -} - -/** - * @description Joins headers in object, according to spec - * @param {Headers} headers joined headers - */ -export function join_headers(headers) { - headers = new Headers(headers); - - const prefix = 'x-bare-headers'; - - if (headers.has(`${prefix}-0`)) { - const join = []; - - for (let [header, value] of headers) { - if (!header.startsWith(prefix)) { - continue; - } - - if (!value.startsWith(';')) { - return { - error: { - code: 'INVALID_BARE_HEADER', - id: `request.headers.${header}`, - message: `Value didn't begin with semi-colon.`, - }, - }; - } - - value = value.slice(1); - - const id = parseInt(header.slice(prefix.length + 1)); - - join[id] = value; - - headers.delete(header); - } - - headers.set(prefix, join.join('')); - } - - return headers; -} diff --git a/public/aero/browser/api/concealer/css.js b/public/aero/browser/api/concealer/css.js new file mode 100644 index 0000000..23ae631 --- /dev/null +++ b/public/aero/browser/api/concealer/css.js @@ -0,0 +1,25 @@ +// Interceptors for StyleSheet + +function getSheet(sheet) { + if (sheet.href) sheet.href = $aero.afterPrefix(sheet.href); + if (sheet.parentStyleSheet) + sheet.parentStyleSheet = getSheet(sheet.parentStyleSheet); + + return sheet; +} + +let bak = document.styleSheets; +Object.defineProperty(document, "styleSheets", { + get: () => { + // StyleSheetList is read-only so the getter itself needs to be proxified + ret.item = new Proxy(ret.item, { + apply() { + return getSheet(Reflect.apply(...arguments)); + }, + }); + + return ret; + }, +}); + +// TODO: Support XML ProcessingInstruction.sheet diff --git a/public/aero/browser/api/concealer/element.js b/public/aero/browser/api/concealer/element.js new file mode 100644 index 0000000..d47c5a9 --- /dev/null +++ b/public/aero/browser/api/concealer/element.js @@ -0,0 +1,126 @@ +// Private scope +{ + const escapeAttrs = ["href", "integrity"]; + + const escape = { + get: attr => { + return ( + attr + // TODO: Only perform the escapes on the correct element + .replace($aero.escape(escapeAttrs[0]), "_$&") + .replace($aero.escape(escapeAttrs[1]), "_$&") + ); + }, + }; + + const attr = { + apply(_target, _that, args) { + const [, name] = args; + + args[0] = escape.get(name); + + return Reflect.apply(...arguments); + }, + }; + const attrNS = { + apply(_target, _that, args) { + const [, name] = args; + + args[1] = escape.get(name); + + return Reflect.apply(...arguments); + }, + }; + const removeAttr = { + apply(_target, _that, args) { + // Remove + Reflect.apply(...arguments); + + // Remove the backup too + const [name] = args; + if (name.includes(escapeAttrs)) args[0] = `_${name}`; + + Reflect.apply(...arguments); + }, + }; + const removeAttrNS = { + apply(_target, _that, args) { + // Remove + Reflect.apply(...arguments); + + // Remove the backup too + const [, name] = args; + if (name.includes(escapeAttrs)) args[1] = `_${name}`; + + Reflect.apply(...arguments); + }, + }; + + Element.hasAttribute = new Proxy(Element.prototype.hasAttribute, attr); + Element.hasAttribute = new Proxy(Element.prototype.hasAttribute, attr); + Element.hasAttributeNS = new Proxy(Element.prototype.hasAttribute, attrNS); + Element.getAttribute = new Proxy(Element.prototype.getAttribute, attr); + Element.getAttributeNode = new Proxy( + Element.prototype.getAttributeNode, + attr + ); + Element.getAttributeNS = new Proxy(Element.prototype.getAttribute, attrNS); + Element.getAttributeNodeNS = new Proxy( + Element.prototype.getAttribute, + attrNS + ); + Element.getAttributeNames = new Proxy(Element.prototype.getAttributeNames, { + apply(target) { + return Reflect.apply(...arguments) + .filter(attr => attr === "_href") + .map(attr => + (target instanceof HTMLAnchorElement && + $aero.escape("href").test(attr)) || + (target instanceof HTMLScriptElement && + $aero.escape("integrity").test(attr)) + ? attr.slice(1) + : attr + ); + }, + }); + Element.prototype.toggleAttribute = new Proxy( + Element.prototype.toggleAttribute, + removeAttr + ); + Element.prototype.removeAttribute = new Proxy( + Element.prototype.removeAttribute, + removeAttr + ); + Element.prototype.removeAttributeNS = new Proxy( + Element.prototype.removeAttribute, + removeAttrNS + ); + + // Conceal + const concealedAttrs = ["href", "xlink:href", "integrity"]; + function valid(el, attr) { + return ( + [ + ...concealedAttrs, + ...concealedAttrs.filter(attr => `_${attr}`), + ].includes(attr) && + // href + (el instanceof HTMLAnchorElement || + el instanceof HTMLAreaElement || + // integrity + el instanceof HTMLScriptElement) + ); + } + Element = new Proxy(Element, { + get(target, prop) { + if (valid(target, prop)) prop = `_${prop}`; + + return Reflect.get(...arguments); + }, + set(target, prop) { + if (valid(target, prop)) prop = `_${prop}`; + + return Reflect.set(...arguments); + }, + }); +} diff --git a/public/aero/browser/api/concealer/error.js b/public/aero/browser/api/concealer/error.js new file mode 100644 index 0000000..5db048d --- /dev/null +++ b/public/aero/browser/api/concealer/error.js @@ -0,0 +1,64 @@ +/* +Error emulation +These properties are not standard, so functionality is different in browsers +These interceptors will probably change a lot over time +*/ +if ($aero.config.flags.nonstandard) { + Error = new Proxy(Error, { + construct() { + const ret = Reflect.construct(...arguments); + + // Firefox exclusives + // Error location + if (typeof ret.columnNumber !== "undefined") + // TODO: Get the column number of the unscoped file + // Possibly, add a data attribute with the og script + ret.columnNumber = ""; + if (typeof ret.fileName !== "undefined") + ret.fileName = $aero.afterPrefix(ret.fileName); + + // Implemented in most major browsers + if (typeof ret.stack !== "undefined") + if (navigator.userAgent.includes("Firefox")) { + const match = /Firefox\/([\d\.]+)/g.exec( + navigator.userAgent + ); + + if (match.length === 2) { + ver = parseFloat(match[1]); + + ret.stack = res.stack.replace( + new RegExp( + `^(@)(.+)(\\d+${ver >= 30 ? ":\\d+" : ""})$`, + "g" + ), + (_match, g1, g2, g3) => + g1 + $aero.afterPrefix(g2) + g3 + ); + } + } else if (navigator.userAgent.includes("Chrome")) + ret.stack = ret.stack + .split("\n") + .map(line => + line.includes( + location.origin + $aero.config.aeroPrefix + ) + ? "" + : line + ) + .join("\n") + .replace( + /^(at )([A-Za-z\.]+ )?.+(?=:\d+:\d+)/g, + (_match, g1, g2, g3) => + g1 + g2 + $aero.afterPrefix(g3) + ) + .replace( + /(?<=\().+(?=:\d+:\d+\))/g, + (_match, g1, g2) => g1 + $aero.afterPrefix(g2) + ); + // TODO: Support Safari + + return ret; + }, + }); +} diff --git a/public/aero/browser/api/concealer/event.js b/public/aero/browser/api/concealer/event.js new file mode 100644 index 0000000..70ee8fe --- /dev/null +++ b/public/aero/browser/api/concealer/event.js @@ -0,0 +1,7 @@ +EventSource = new Proxy(EventSource, { + construct() { + const ret = Reflect.construct(...arguments); + + ret.url = $aero.afterPrefix(ret.url); + }, +}); diff --git a/public/aero/browser/api/concealer/file.js b/public/aero/browser/api/concealer/file.js new file mode 100644 index 0000000..f557d2e --- /dev/null +++ b/public/aero/browser/api/concealer/file.js @@ -0,0 +1,10 @@ +File = new Proxy(File, { + get(_that, prop) { + const ret = Reflect.get(...arguments); + + if (prop === "webkitRelativePath") return $aero.afterPrefix(ret); + return ret; + }, +}); + +// TODO: Finish all interecptors for functions that create new files diff --git a/public/aero/browser/api/concealer/fs.js b/public/aero/browser/api/concealer/fs.js new file mode 100644 index 0000000..953b5b1 --- /dev/null +++ b/public/aero/browser/api/concealer/fs.js @@ -0,0 +1,11 @@ +/* +FIXME: Don't use this interface +FileSystemEntry = new Proxy(FileSystemEntry, { + construct() { + const ret = target.construct(...arguments); + + const toURL = ret.toURL; + ret.toURL = () => $aero.afterPrefix(toURL()); + }, +}); +*/ diff --git a/public/aero/browser/api/concealer/http.js b/public/aero/browser/api/concealer/http.js new file mode 100644 index 0000000..a659cdf --- /dev/null +++ b/public/aero/browser/api/concealer/http.js @@ -0,0 +1,38 @@ +// Conceal the rewritten headers + +fetch = new Proxy(fetch, { + apply() { + const ret = Reflect.target(...arguments); + + ret.headers = new Headers(ret.headers.get("x-aero-headers")); + + return ret; + }, +}); + +XMLHttpRequest.prototype.getResponseHeader = new Proxy( + XMLHttpRequest.prototype.getResponseHeader, + { + apply(target, that, args) { + [name] = args; + + return JSON.parse(target("x-aero-headers"))[name]; + }, + } +); +XMLHttpRequest.prototype.getResponseHeader = new Proxy( + XMLHttpRequest.prototype.getResponseHeader, + { + apply(target, that, args) { + let ret = ""; + + // CRLF + for (const [key, value] of Object.entries( + JSON.parse(target("x-aero-headers")) + )) + ret += `${key}: ${value}\r\n`; + + return ret; + }, + } +); diff --git a/public/aero/browser/api/concealer/manifest.js b/public/aero/browser/api/concealer/manifest.js new file mode 100644 index 0000000..f763488 --- /dev/null +++ b/public/aero/browser/api/concealer/manifest.js @@ -0,0 +1,12 @@ +if ("launchQueue" in window) + launchQueue.setConsumer = new Proxy(launchQueue.setConsumer, { + apply(_target, _that, args) { + [callback] = args; + + return params => { + params.targetUrl = $aero.afterPrefix(params.targetUrl); + + callback(params); + }; + }, + }); diff --git a/public/aero/browser/api/concealer/navigation.js b/public/aero/browser/api/concealer/navigation.js new file mode 100644 index 0000000..f38861c --- /dev/null +++ b/public/aero/browser/api/concealer/navigation.js @@ -0,0 +1,72 @@ +if ( + // Not finished + $aero.config.flags.misc && + // Only supported on Chromium + "navigation" in window +) { + Object.defineProperty($aero, "navigationEntry", { + get: () => $aero.proxyLocation.href, + }); + + // Entries + navigation.currentEntry.url = $aero.navigationEntry; + navigation.entries = new Proxy(navigation.entries, { + apply() { + const entries = Reflect.apply(...arguments); + + // We may delete some entries, so we will update the index with the new index + let i = 0; + + /** @const {string[]} */ + const newEntries = []; + + for (let entry of entries) { + const newEntry = entry; + + // The original property is a getter property, as the value will be changed dynamically + const tempBak = entry.url; + Object.defineProperty(newEntry, "url", { + get: () => tempBak.replace($aero.afterPrefix, ""), + }); + + try { + if ( + new URL(newEntry.url).origin !== + $aero.proxyLocation.origin + ) + // The site is not supposed to see this entry + continue; + } catch { + continue; + } + + Object.defineProperty(newEntry, "index", { + value: i++, + }); + + newEntries.push(newEntry); + } + + return entries; + }, + }); + + if (navigation.transition) + navigation.transition.from = $aero.navigationEntry; + + navigation.addEventListener = new Proxy(navigation.addEventListener, { + apply(_target, _that, args) { + const [type, listener] = args; + + if (type === "currententrychange") + args[1] = event => { + if (event instanceof NavigationCurrentEntryChangeEvent) + event.from.url = $aero.afterPrefix(event.from.url); + + listener(event); + }; + + return Reflect.apply(...arguments); + }, + }); +} diff --git a/public/aero/browser/api/concealer/payment.js b/public/aero/browser/api/concealer/payment.js new file mode 100644 index 0000000..ca60a20 --- /dev/null +++ b/public/aero/browser/api/concealer/payment.js @@ -0,0 +1,25 @@ +// Only supported on Chromium +if ("PaymentRequest" in window) { + PaymentRequest = new Proxy(PaymentRequest, { + construct(_target, _prop, args) { + let [methods] = args; + + args[0] = methods.map(method => $aero.rewriteSrc(method)); + + return Reflect.construct(...arguments); + }, + }); + + if ($aero.config.flags.legacy && "MerchantValidationEvent" in window) + MerchantValidationEvent = new Proxy(PaymentRequestEvent, { + get(_that, prop) { + const ret = Reflect.get(...arguments); + + if (prop === "validationURL") return $aero.afterPrefix(ret); + + return Reflect.get(...arguments); + }, + }); + + // https://w3c.github.io/payment-handler/#dom-paymentrequestevent-toporigin +} diff --git a/public/aero/browser/api/concealer/presentation.js b/public/aero/browser/api/concealer/presentation.js new file mode 100644 index 0000000..42a485b --- /dev/null +++ b/public/aero/browser/api/concealer/presentation.js @@ -0,0 +1,23 @@ +if ("Presentation" in window) { + PresentationRequest = new Proxy(PresentationRequest, { + construct(_that, args) { + // Could either be a string or an array + let [urls] = args; + + if (Array.isArray(urls)) + urls = urls.map(url => $aero.rewriteSrc(url)); + else urls = $aero.rewriteSrc(urls); + + args[0] = urls; + + return Reflect.construct(...arguments); + }, + }); + PresentationConnnection = new Proxy(PresentationConnection, { + get(target, prop) { + if (prop === "url") return $aero.afterPrefix(target.url); + + return Reflect.get(...arguments); + }, + }); +} diff --git a/public/aero/browser/api/concealer/push.js b/public/aero/browser/api/concealer/push.js new file mode 100644 index 0000000..73bc4fa --- /dev/null +++ b/public/aero/browser/api/concealer/push.js @@ -0,0 +1,6 @@ +PushSubscription = new Proxy(PushSubscription, { + get(target, prop) { + if (prop === "endpoint") return $aero.afterPrefix(target[prop]); + return Reflect.get(...arguments); + }, +}); diff --git a/public/aero/browser/api/concealer/reporting.js b/public/aero/browser/api/concealer/reporting.js new file mode 100644 index 0000000..7203110 --- /dev/null +++ b/public/aero/browser/api/concealer/reporting.js @@ -0,0 +1,56 @@ +// Only supported on chromium +// https://w3c.github.io/reporting/#dom-reportingobserver-reportingobserver +if ("ReportingObserver" in window) { + async function rewriteReports(reports) { + for (let report of reports) { + // https://w3c.github.io/reporting/#serialize-reports + const json = report.toJSON(); + report.toJSON = () => ({ + ...json, + url: $aero.afterPrefix(json.url), + }); + + if (report instanceof CSPViolationReportBody) { + // Urls + CSPViolationReportBody.blockedURL = $aero.afterPrefix( + CSPViolationReportBody.blockedURL + ); + CSPViolationReportBody.referrer = $aero.afterPrefix( + CSPViolationReportBody.referrer + ); + CSPViolationReportBody.sourceFile = $aero.afterPrefix( + CSPViolationReportBody.sourceFile + ); + + // Don't reveal the rewritten script + const resp = await fetch(CSPViolationReportBody.sourceFile); + CSPViolationReportBody.sample = (await resp.text()).slice( + 0, + resp.length + ); + } + + // Error location + report.sourceFile = $aero.afterPrefix(report.sourceFile); + // TODO: Get the column number from the line in the original script (through .lineNumber) + report.columnNumber = null; + } + return reports; + } + + ReportingObserver = new Proxy(ReportingObserver, { + construct(_that, args) { + const [callback] = args; + + args[1] = async reports => { + reports = await rewriteReports(reports); + + callback(...arguments); + }; + + const ret = Reflect.construct(...arguments); + + ret.takeRecords = async () => rewriteReports(ret.takeRecords()); + }, + }); +} diff --git a/public/aero/browser/api/concealer/scoping.js b/public/aero/browser/api/concealer/scoping.js new file mode 100644 index 0000000..10eafdd --- /dev/null +++ b/public/aero/browser/api/concealer/scoping.js @@ -0,0 +1,82 @@ +// Scope Checking +// In case a function overwrites the value of location in its parameters +$aero.isLocation = val => val === location; +$aero.check = val => (val == location ? $aero.location : val); + +// Evals +$aero.eval = new Proxy(eval, { + apply(_target, _that, args) { + args[0] = $aero.scope(args[0]); + + return Reflect.apply(...arguments); + }, +}); +Function = new Proxy(Function, { + construct(_that, args) { + let [func] = args; + + let bak = ""; + + if (typeof func === "string") { + bak = func; + func = $aero.scope(func); + } else if ( + typeof func === "function" && + !func.toString() !== `function ${func.name}() { [native code] }"` + ) { + bak = func.toString(); + func = $aero.scope(func.toString()); + } + + args[0] = func; + + const inst = Reflect.construct(...arguments); + + // Use Object.defined to conceal the getter + inst.bak = bak; + + // Hide the changes from the site + inst.toString = () => bak; + + return inst; + }, +}); + +// Reflectors +Reflect.get = new Proxy(Reflect.get, { + apply(target, _that, args) { + const [theTarget, theProp] = args; + + if (theTarget instanceof Window && theProp === "location") + return $aero.location; + if (theTarget instanceof Document) { + if (theProp === "location") return $aero.location; + if (theProp === "domain") return $aero.document.domain; + if (theProp === "URL") return $aero.document.URL; + } + if (theTarget instanceof Location) return $aero.location[theProp]; + return target(...args); + }, +}); +Reflect.set = new Proxy(Reflect.set, { + apply(target, _that, args) { + const [_target, prop, value] = args; + + if (_target instanceof Location) return ($aero.location[prop] = value); + return target(...args); + }, +}); + +// Objects +Object.getOwnPropertyDescriptor = new Proxy(Object.getOwnPropertyDescriptor, { + apply(_target, _that, args) { + let [obj, prop] = args; + + if (obj === location || (obj === window && prop === "location")) + obj = $aero.location; + + args[0] = obj; + + return Reflect.apply(...arguments); + }, +}); diff --git a/public/aero/browser/api/concealer/timing.js b/public/aero/browser/api/concealer/timing.js new file mode 100644 index 0000000..bc4f517 --- /dev/null +++ b/public/aero/browser/api/concealer/timing.js @@ -0,0 +1,66 @@ +/* +There are 2 ways to detect proxies using the Performance API +If the site was rewritten or the headers were modified, the size would be different than what is intended. You can think of this as a form of hash checking +If you make a request to two different proxy origins on the site that are both cached and one has the Clear-Site-Data clearing both proxy origins, the proxy can be detected +*/ +{ + const info = new Map(); + + const broadcast = new BroadcastChannel("resCached"); + + // Detect if cache is cached + // TODO: Broadcast this info on the sw + broadcast.onmessage = event => { + const { url, cached } = event.data.payload; + + resInfo.add(url, cached); + }; + + function isCached(url) { + return url in info.get(url); + } + + async function getHeader(name) { + const resp = await fetch(url); + + return resp.headers[name]; + } + + async function getBodySize(url) { + return await getHeader(url, "x-aero-size-body"); + } + + PerformanceResourceTiming = new Proxy(PerformanceResourceTiming, { + async get(target, prop) { + const url = target.name; + const size = target[prop]; + + const resCached = isCached(url); + const resCrossOrigin = url.startsWith($aero.upToProxyOrigin); + const isZero = + resCached || resCrossOrigin || "timing" in $aero.cors.headers; + + // These represent the size of the response + if (prop === "transferSize") { + if (isZero) return 0; + + return await getHeader(url, "x-aero-size-transfer"); + } + if (prop === "encodedBodySize") { + if (isZero) return 0; + + const decodeSize = prop.decodedBodySize; + + // There is no encoding + if (size === decodeSize) return await getBodySize(url); + else return await getHeader(url, "x-aero-size-encbody"); + } + if (prop === "decodedBodySize") { + if (isZero) return 0; + + return await getBodySize(url); + } + return Reflect.get(...arguments); + }, + }); +} diff --git a/public/aero/browser/api/concealer/xml.js b/public/aero/browser/api/concealer/xml.js new file mode 100644 index 0000000..b0cc4c4 --- /dev/null +++ b/public/aero/browser/api/concealer/xml.js @@ -0,0 +1 @@ +// TODO: Determine if XML needs to be rewritten with XML linked documents, or if it is already handled in the mutation observer diff --git a/public/aero/browser/api/event/messages.js b/public/aero/browser/api/event/messages.js new file mode 100644 index 0000000..3b39b70 --- /dev/null +++ b/public/aero/browser/api/event/messages.js @@ -0,0 +1,80 @@ +// TODO: Rename this to window.js and move it to concealer + +// Sender +postMessage = new Proxy(postMessage, { + apply(_target, _that, args) { + let [data, origin] = args; + + if (origin !== "*") { + args[1] = "*"; + + data.origin = origin; + + args[0] = data; + } + + console.log(args); + + return Reflect.apply(...arguments); + }, +}); + +function eventInterceptor(type, listener) { + if (type === "message" || type === "messageerror") + return event => { + if (event instanceof MessageEvent) + if (event.origin === $aero.proxyLocation.origin) { + event.origin = $aero.proxyLocation.origin; + listener(event); + } + }; + if (type === "storage") { + return event => { + if (event instanceof StorageEvent) { + event.url = $aero.afterPrefix(url); + + // Ensure the event isn't a clear event + if (event.key !== null) { + const proxyKey = $aero.storageKey(event.key); + + if (proxyKey !== null) event.key = proxyKey; + } + } + listener(event); + }; + } + if (type === "hashchange") { + return event => { + if (event instanceof HashChangeEvent) { + event.newURL = $aero.afterPrefix(event.newURL); + event.oldURL = $aero.afterPrefix(event.oldURL); + } + listener(event); + }; + } + + return listener; +} +function setHandler(type) { + let set; + Object.defineProperty(window, `on${type}`, { + set: listener => { + set = eventInterceptor(type, listener); + }, + get: () => set, + }); +} + +setHandler("message"); +setHandler("messageerror"); +setHandler("storage"); +setHandler("hashchange"); + +// Reciever concealer +addEventListener = new Proxy(addEventListener, { + apply(_target, _that, args) { + args[1] = eventInterceptor(...args); + + return Reflect.apply(...arguments); + }, +}); diff --git a/public/aero/browser/api/loc/contentIndex.js b/public/aero/browser/api/loc/contentIndex.js new file mode 100644 index 0000000..dd89018 --- /dev/null +++ b/public/aero/browser/api/loc/contentIndex.js @@ -0,0 +1,21 @@ +if ("serviceWorker" in navigator && "index" in ServiceWorkerRegistration) { + ServiceWorkerRegistration.index.add = new Proxy({ + apply(_target, _that, args) { + [url] = args; + + args[0] = $aero.rewriteSrc(url); + + return Reflect.apply(...argument); + }, + }); + + ServiceWorkerRegistration.index.getAll = new Proxy({ + apply() { + const ret = Reflect.target(...arguments); + + for (const desc of ret) desc.url = $aero.afterPrefix(desc.url); + + return ret; + }, + }); +} diff --git a/public/aero/api/history.js b/public/aero/browser/api/loc/history.js similarity index 57% rename from public/aero/api/history.js rename to public/aero/browser/api/loc/history.js index c6721d2..19ed5d3 100644 --- a/public/aero/api/history.js +++ b/public/aero/browser/api/loc/history.js @@ -1,12 +1,13 @@ -// Incomplete - var historyState = { - apply(target, that, args) { - let [state, title, url = ''] = args; + apply(_target, _that, args) { + const [, , url = ""] = args; + + args[2] = $aero.rewriteSrc(url); + args[3] = $aero.rewriteSrc(url); return Reflect.apply(...arguments); - } + }, }; history.pushState = new Proxy(history.pushState, historyState); -history.replaceState = new Proxy(history.replaceState, historyState); \ No newline at end of file +history.replaceState = new Proxy(history.replaceState, historyState); diff --git a/public/aero/browser/api/loc/location.js b/public/aero/browser/api/loc/location.js new file mode 100644 index 0000000..4cf893e --- /dev/null +++ b/public/aero/browser/api/loc/location.js @@ -0,0 +1,9 @@ +$aero.location = $aero.locationProxy; +$aero.location["Symbol.toStringTag"] = "Location"; + +Object.defineProperty(document, "domain", { + get: () => $aero.proxyLocation.hostname, +}); +Object.defineProperty(document, "URL", { + get: () => $aero.proxyLocation.href, +}); diff --git a/public/aero/browser/api/loc/navigator.js b/public/aero/browser/api/loc/navigator.js new file mode 100644 index 0000000..11249bf --- /dev/null +++ b/public/aero/browser/api/loc/navigator.js @@ -0,0 +1,95 @@ +Navigator.prototype.sendBeacon = new Proxy(Navigator.prototype.sendBeacon, { + apply(_target, _that, args) { + const [url] = args; + + args[0] = $aero.rewriteSrc(url); + + return Reflect.apply(...arguments); + }, +}); + +// Sandbox data to their respective origin +{ + const protoHandler = { + apply(_target, _that, args) { + const [scheme, url] = args; + + args[0] = $aero.proto.set(scheme); + args[1] = $aero.rewriteSrc(url); + + return Reflect.apply(...arguments); + }, + }; + + navigator.registerProtocolHandler = new Proxy( + navigator.registerProtocolHandler, + protoHandler + ); + navigator.unregisterProtocolHandler = new Proxy( + navigator.unregisterProtocolHandler, + protoHandler + ); +} +{ + const key = "aero.badges"; + + let badges = localStorage.getItem(key) ?? []; + + let badge; + + const found = badges.find( + badge => badge.origin === $aero.proxyLocation.origin, + (_el, i) => { + badge = badges[i]; + } + ); + + if (!found) { + badge = { + origin: $aero.proxyLocation.origin, + i: 0, + }; + + badges.push(badge); + } + + const setBak = Navigator.setAppBadge; + + function getTotal() { + let i = 0; + + for (const badge of badges) i += badge.i; + + return i; + } + function updateCount() { + badges.find( + badge => badge.origin === $aero.proxyLocation.origin, + (_el, i) => { + // Local + badges[i] = badge; + // Update + setBak(getTotal()); + // Save + localStorage.setItem(key, badge); + } + ); + } + + navigator.setAppBadge = new Proxy(navigator.clearAppBadge, { + apply(_target, _that, args) { + [contents] = args; + + badge.i = contents; + + updateCount(); + }, + }); + navigator.clearAppBadge = new Proxy(navigator.clearAppBadge, { + apply() { + badge.i = 0; + + updateCount(); + }, + }); +} diff --git a/public/aero/browser/api/loc/popup.js b/public/aero/browser/api/loc/popup.js new file mode 100644 index 0000000..b275b6c --- /dev/null +++ b/public/aero/browser/api/loc/popup.js @@ -0,0 +1,9 @@ +open = new Proxy(open, { + apply(_target, _that, args) { + const [url] = args; + + args[0] = $aero.rewriteSrc(url); + + return Reflect.apply(...arguments); + }, +}); diff --git a/public/aero/browser/api/req/http.js b/public/aero/browser/api/req/http.js new file mode 100644 index 0000000..511c5b6 --- /dev/null +++ b/public/aero/browser/api/req/http.js @@ -0,0 +1,15 @@ +fetch = new Proxy(fetch, { + apply(_target, _that, args) { + [opts] = args; + + if ( + opts.cache && + // only-if-cached requires the mode to be same origin + !(opts.mode !== "same-origin" && opts.cache === "only-if-cached") + ) + // Emulate cache mode + args[1].headers.add("x-aero-cache", opts.cache); + + return Reflect.apply(...arguments); + }, +}); diff --git a/public/aero/browser/api/req/wrtc.js b/public/aero/browser/api/req/wrtc.js new file mode 100644 index 0000000..520e680 --- /dev/null +++ b/public/aero/browser/api/req/wrtc.js @@ -0,0 +1,30 @@ +if ($aero.config.flags.wrtc) { + RTCPeerConnection = new Proxy(RTCPeerConnection, { + construct(target, args) { + let [config] = args; + + // Backup + const iceServersBak = config.iceServers; + + if (config.iceServers && $aero.config.wrtcBackends.ice.length > 0) { + config.iceServers = customIceServers; + args[0] = config; + } + + const ret = new target(...args); + + ret._iceServers = iceServersBak; + + return ret; + }, + get: (_target, prop) => + $aero.escape("iceServers").test(prop) + ? `_${prop}` + : Reflect.get(...arguments), + set: (_target, prop, value) => { + $aero.escape("iceServers").test(prop) + ? (target[`_${prop}`] = value) + : Reflect.set(...arguments); + }, + }); +} diff --git a/public/aero/browser/api/req/ws.js b/public/aero/browser/api/req/ws.js new file mode 100644 index 0000000..55d73eb --- /dev/null +++ b/public/aero/browser/api/req/ws.js @@ -0,0 +1,58 @@ +// TODO: Support WebSockets in bare mode +if ($aero.config.flags.ws) { + WebSocket = new Proxy(WebSocket, { + construct(_that, args) { + const [url] = args; + + let ret; + + for (const backend of $aero.config.wsBackends) { + const rewrittenUrl = `${ + location.protocol === "https:" ? "wss" : "ws" + }://${location.host}${$aero.rewriteSrc(backend)}?url=${url}`; + + if ($aero.config.debug.url) + console.log(`WS ${url} ➜ ${rewrittenUrl}`); + + args[0] = rewrittenUrl; + + try { + new Promise((resolve, reject) => { + const ws = Reflect.construct(...arguments); + + // TODO: Dispatch events after the return + ws.addEventListener("open", () => { + resolve(ws); + }); + ws.addEventListener("error", () => { + reject(); + }); + }) + .then(ws => (ret = ws)) + .catch(() => + console.warn(`WS Backend ${backend} is down`) + ); + } catch (err) { + if (err instanceof DOMException) + console.warn( + `Config issue: invalid backend url ${backend}` + ); + } + } + + return ret; + }, + }); + + // Only supported on Chromium + if ("WebTransport" in window) + WebTransport = new Proxy(WebTransport, { + construct(_that, args) { + const [url] = args; + + args[0] = $aero.rewriteSrc(url); + + return Reflect.construct(...arguments); + }, + }); +} diff --git a/public/aero/browser/api/storage/cookie.js b/public/aero/browser/api/storage/cookie.js new file mode 100644 index 0000000..b3a17a1 --- /dev/null +++ b/public/aero/browser/api/storage/cookie.js @@ -0,0 +1,54 @@ +if ($aero.config.flags.experimental && "cookieStore" in window) { + function getOriginalCookie(cookie) { + // Not done + return cookie; + } + + cookieStore.set = new Proxy(cookieStore.set, { + apply(_target, _that, args) { + const [cookie] = args; + + cookie.domain = location.domain; + cookie.path = locationUpToProxyOrigin + cookie.path; + + args[0] = cookie; + + return Reflect.apply(...arguments); + }, + }); + cookieStore.get = new Proxy(cookieStore.set, { + apply() { + return getOriginalCookie( + $aero.config.prefix, + Reflect.apply(...arguments) + ); + }, + }); + + cookieStore.addEventListener = new Proxy(cookieStore.addEventListener, { + apply(_target, _that, args) { + const [type, listener] = args; + + if (type === "change") + args[1] = event => { + if (event instanceof CookieChangeEvent) { + /* + TODO: Rewrite + event.changed + event.deleted + */ + } + + event.listener(event); + }; + + return Reflect.apply(...arguments); + }, + }); +} + +$aero.cookie = document.cookie; +Object.defineProperty(document, "cookie", { + get: () => $aero.rewriteGetCookie($aero.cookie), + set: value => ($aero.cookie = $aero.rewriteSetCookie(value)), +}); diff --git a/public/aero/browser/api/storage/idb.js b/public/aero/browser/api/storage/idb.js new file mode 100644 index 0000000..6c7291b --- /dev/null +++ b/public/aero/browser/api/storage/idb.js @@ -0,0 +1,18 @@ +indexedDB.open = new Proxy(indexedDB.open, $aero.storageNomenclature); +indexedDB.deleteDatabase = new Proxy( + indexedDB.deleteDatabase, + $aero.storageNomenclature +); +indexedDB.databases = new Proxy(indexedDB.databases, { + apply() { + const dbs = Reflect.apply(...arguments); + + dbs.map(db => { + if (typeof db === "error") return db; + + db.name = prefix + db.name; + + return db; + }); + }, +}); diff --git a/public/aero/browser/api/storage/sql.js b/public/aero/browser/api/storage/sql.js new file mode 100644 index 0000000..acb4f41 --- /dev/null +++ b/public/aero/browser/api/storage/sql.js @@ -0,0 +1,22 @@ +if ($aero.config.flags.legacy) { + const handler = { + apply(_target, _that, args) { + const [key] = args; + + const newKey = prefix + key; + + args[0] = newKey; + + const dbNames = localStorage.getItem("dbNames") ?? []; + if (dbNames.includes(newKey)) + localStorage.setItem("dbNames", dbNames.push(newKey)); + + return Reflect.apply(...arguments); + }, + }; + + if ("openDatabase" in window) + openDatabase = new Proxy(openDatabase, handler); + if ("openDatabaseSync" in window) + openDatabaseSync = new Proxy(openDatabaseSync, handler); +} diff --git a/public/aero/browser/api/storage/storage.js b/public/aero/browser/api/storage/storage.js new file mode 100644 index 0000000..885f80e --- /dev/null +++ b/public/aero/browser/api/storage/storage.js @@ -0,0 +1,51 @@ +// Local Storage +Storage.prototype.setItem = new Proxy( + Storage.prototype.setItem, + $aero.storageNomenclature +); +Storage.prototype.getItem = new Proxy( + Storage.prototype.getItem, + $aero.storageNomenclature +); +Storage.prototype.removeItem = new Proxy( + Storage.prototype.getItem, + $aero.storageNomenclature +); + +Storage.prototype.clear = new Proxy(Storage.prototype.clear, { + apply(target) { + for (const key of Object.keys(target)) + if (key.startsWith($aero.storagePrefix)) target.remove(key); + }, +}); + +Storage.prototype.key = new Proxy(Storage.prototype.key, { + apply(target, _that, args) { + const [i] = args; + + let proxyKeys = []; + + for (const key of Object.keys(target)) + if (key.startsWith($aero.storagePrefix)) + proxyKeys.push( + key.slice( + str.indexOf($aero.storagePrefix) + + $aero.storagePrefix.length + ) + ); + + return proxyKeys[i]; + }, +}); + +Storage = new Proxy(Storage, { + getOwnPropertyDescriptor: () => ({ + enumerable: true, + configurable: true, + }), + ownKeys(target) { + const keys = Reflect.ownKeys(target); + + return $aero.storageKeys(keys); + }, +}); diff --git a/public/aero/browser/api/worker/workers.js b/public/aero/browser/api/worker/workers.js new file mode 100644 index 0000000..c5b374f --- /dev/null +++ b/public/aero/browser/api/worker/workers.js @@ -0,0 +1,45 @@ +if ($aero.config.nestedWorkers) + if ("serviceWorker" in navigator) { + // This api is only exposed in secure contexts + navigator.serviceWorker.register = new Proxy( + navigator.serviceWorker.register, + { + apply(_target, _that, args) { + const [path, opts] = args; + + args[0] = `${$aero.rewriteSrc(path)}?mod=${ + opts.type === "module" + }`; + + console.log( + `Registering a nested service worker\n${path} ➜ ${args[0]}` + ); + + return Reflect.apply(...arguments); + }, + } + ); + + const rewriteReg = reg => + // Don't let the site see the aero sw + (reg.active.scriptURL = reg.active.scriptURL.match( + new RegExp( + `(?<=${location.origin}${prefix}${$aero.proxyLocation.origin}).*`, + "g" + ) + )[0]); + + navigator.serviceWorker.getRegistration = new Proxy( + navigator.serviceWorker.getRegistration, + { + apply: async target => + (await target()).map(reg => rewriteReg(reg)), + } + ); + navigator.serviceWorker.getRegistrations = new Proxy( + navigator.serviceWorker.getRegistrations, + { + apply: async target => rewriteReg(await target()), + } + ); + } diff --git a/public/aero/browser/injects/dom.js b/public/aero/browser/injects/dom.js new file mode 100644 index 0000000..8ea00ae --- /dev/null +++ b/public/aero/browser/injects/dom.js @@ -0,0 +1,12 @@ +new MutationObserver(mutations => { + for (let mutation of mutations) + if (mutation.type === "childList") + for (let node of mutation.addedNodes) + if (node.nodeType === Node.ELEMENT_NODE) $aero.rewrite(node); + else if (mutation.type === "attributes") + for (let attr of mutation.attributeName) + $aero.rewrite(mutation.target, attr); +}).observe(document, { + childList: true, + subtree: true, +}); diff --git a/public/aero/browser/misc/clear.js b/public/aero/browser/misc/clear.js new file mode 100644 index 0000000..806d346 --- /dev/null +++ b/public/aero/browser/misc/clear.js @@ -0,0 +1,91 @@ +// Emulates the Clear Site Data header + +if ($aero.config.flags.nonstandard) + navigator.serviceWorker.addEventListener("message", event => { + if (event.data === "clearExecutionContext") location.reload(); + }); + +// Private scope +{ + if ($aero.cors.clear) { + const clear = JSON.parse($aero.cors.clear); + + const all = clear.includes("'*'"); + + if (all || clear.includes("'cookies'")) { + function clearCookies(path) { + const cookies = document.cookie.split(";"); + + for (const cookie of cookies) { + const eqPos = cookie.indexOf("="); + + const name = + eqPos > -1 ? cookie.substring(0, eqPos) : cookie; + + document.cookie = + name + + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=" + + path + + ";"; + } + } + clearCookies($aero.upToProxyOrigin); + } + + // Storage + if (all || clear.includes("'storage'")) { + // iDB + indexedDB.databases().then(({ name }) => { + if (name.startsWith($aero.storageNomenclature)) + indexedDB.deleteDatabase(name); + }); + + // Storage + function clearStore(name) { + if (name in window) { + const storage = window[name]; + + if (storage instanceof Storage) { + for (let [key] of Object.entries(storage)) + if (key.startsWith($aero.storageNomenclature)) + storage.removeItem(key); + } + } + } + clearStore("localStorage"); + clearStore("sessionStorage"); + + // WebDatabase + if ($aero.config.flags.legacy && "openDatabase" in window) { + for (const name of localStorage.getItem("dbNames")) { + openDatabase(name).transaction(tx => { + tx.executeSql( + 'SELECT name FROM sqlite_master WHERE type="table"', + [], + (tx, data) => { + for (let i = 0; i < data.rows.length; i++) { + const name = data.rows.item(i).name; + + if (name !== "__WebKitDatabaseInfoTable__") + tx.executeSql( + `DELETE FROM ${tableName}` + ); + } + } + ); + }); + } + } + + // TODO: Clear all filesystem data + + // Service Workers + navigator.serviceWorker.getRegistrations().then(regs => { + for (const reg of regs) { + if (reg.scope.startsWith($aero.upToProxyOrigin)) + reg.unregister(); + } + }); + } + } +} diff --git a/public/aero/browser/misc/cors.js b/public/aero/browser/misc/cors.js new file mode 100644 index 0000000..3e60623 --- /dev/null +++ b/public/aero/browser/misc/cors.js @@ -0,0 +1,5 @@ +$aero.cors.csp = $aero.cors.headers.csp; +if ($aero.cors.clear) + $aero.cors.clear = JSON.parse(`[${$aero.cors.headers.clear}]`); +// TODO: Parse and use in perms.js +$aero.cors.perms = $aero.cors.perms.split(";"); diff --git a/public/aero/browser/misc/escape.js b/public/aero/browser/misc/escape.js new file mode 100644 index 0000000..fff649e --- /dev/null +++ b/public/aero/browser/misc/escape.js @@ -0,0 +1 @@ +$aero.escape = str => new RegExp(`^(?:_+)?${str}$`, "g"); diff --git a/public/aero/browser/misc/frame.js b/public/aero/browser/misc/frame.js new file mode 100644 index 0000000..4a021fe --- /dev/null +++ b/public/aero/browser/misc/frame.js @@ -0,0 +1,50 @@ +// Frame checks +if (frameElement) { + function block() { + frameElement.remove(); + } + + const parentOrigin = frameElement.parentProxyOrigin; + + if (parentOrigin) + throw new Error("The parent's proxy origin wasn't given to the frame"); + + const frameOptions = $aero.cors.headers.frame; + + if (frameOptions === "DENY") block(); + else if (frameOptions === "SAMEORIGIN") { + if ($aero.proxyLocation.origin !== parentOrigin) block(); + } else if (csp.contains("frame-ancestors")) { + const sources = $aero.cspSrc("frame-ancestors"); + + if (sources.contains("'none'")) block(); + else { + let allowed = false; + + for (source of sources) { + if ( + source === "'self'" && + parentOrigin === $aero.proxyLocation.origin + ) { + allowed = true; + break; + } + if (source === parentOrigin) { + allowed = true; + break; + } + } + + if (!allowed) block(); + } + } + // Still supported on Firefox mobile + else if ( + $aero.config.flags.legacy && + frameOptions.startsWith("ALLOW-FROM=") + ) { + const [allowedOrigin] = frameOptions.match(/ALLOW-FROM=(.+)/g); + + if (allowedOrigin) if (allowedOrigin !== parentOrigin) block(); + } +} diff --git a/public/aero/browser/misc/perms.js b/public/aero/browser/misc/perms.js new file mode 100644 index 0000000..be24e4e --- /dev/null +++ b/public/aero/browser/misc/perms.js @@ -0,0 +1 @@ +// TODO: Parse permission policy diff --git a/public/aero/browser/misc/proto.js b/public/aero/browser/misc/proto.js new file mode 100644 index 0000000..6c35342 --- /dev/null +++ b/public/aero/browser/misc/proto.js @@ -0,0 +1,16 @@ +// Custom protocols +$aero.proto = { + get(scheme) { + return scheme.replace( + new RegExp(`^(web+${$aero.proxyLocation.origin}+)`), + "web+" + ); + }, + set(scheme) { + let split = scheme.split("web+"); + + split.splice(1, 0, `${$aero.proxyLocation.origin}+`); + + return split.join(); + }, +}; diff --git a/public/aero/browser/misc/proxyLocation.js b/public/aero/browser/misc/proxyLocation.js new file mode 100644 index 0000000..0f621bc --- /dev/null +++ b/public/aero/browser/misc/proxyLocation.js @@ -0,0 +1,50 @@ +// Dynamically update location using a function getters +Object.defineProperty($aero, "proxyLocation", { + get: () => new URL($aero.afterPrefix(location.href)), +}); + +Object.defineProperty($aero, "upToProxyOrigin", { + get: () => $aero.config.prefix + $aero.proxyLocation.origin, +}); +// Private scope +{ + // Prevent detection by instanceof + let inheritedObject = {}; + Reflect.setPrototypeOf(inheritedObject, Location.prototype); + + const wrap = url => $aero.config.prefix + url; + + $aero.locationProxy = new Proxy(inheritedObject, { + get(target, prop) { + if (typeof target[prop] === "function") { + const props = { + toString: $aero.proxyLocation.toString, + assign: url => location.assign(wrap(url)), + replace: $aero.proxyLocation.replace, + }; + + return prop in props ? props[prop] : target[prop]; + } + + const fakeUrl = $aero.proxyLocation; + + const customProps = { + ancestorOrigins: location.ancestorOrigins, + }; + + if (prop in customProps) return customProps[prop]; + + if (prop in fakeUrl) return fakeUrl[prop]; + + return location[prop]; + }, + set(target, prop, value) { + if ( + prop === "pathname" || + (prop === "href" && value.startsWith("/")) + ) + target[prop] = $aero.upToProxyOrigin + value; + else target[prop] = value; + }, + }); +} diff --git a/public/aero/browser/misc/storage.js b/public/aero/browser/misc/storage.js new file mode 100644 index 0000000..93e5022 --- /dev/null +++ b/public/aero/browser/misc/storage.js @@ -0,0 +1,33 @@ +Object.defineProperty($aero, "storagePrefix", { + get: () => `${$aero.proxyLocation.origin}_`, +}); + +$aero.storageNomenclature = { + apply(_target, _that, args) { + const [key] = args; + + args[0] = $aero.config.prefix + key; + + return Reflect.apply(...arguments); + }, +}; + +$aero.storageKey = key => { + const prefixSplit = key.split($aero.config.prefix); + + if (prefixSplit[0] === $aero.config.prefix) return prefixSplit.slice(1); + else return null; +}; + +$aero.storageKeys = keys => { + let proxyKeys = []; + + for (let key of keys) { + const prefixSplit = key.split($aero.config.prefix); + + if (prefixSplit[0] === $aero.config.prefix) + proxyKeys.append(prefixSplit.slice(1)); + } + + return proxyKeys; +}; diff --git a/public/aero/browser/rewriters/cloner.js b/public/aero/browser/rewriters/cloner.js new file mode 100644 index 0000000..cb68986 --- /dev/null +++ b/public/aero/browser/rewriters/cloner.js @@ -0,0 +1,36 @@ +// In the case of CORS attributes present the original is deleted and a new clone is made because it isn't possible to modify the CORS properties internally +$aero.Cloner = class { + /** + * Clones an element without their read-only integrity attribute + * @constructor + * @param {element} - The element to be cloned + */ + constructor(el) { + let copy = document.createElement(el.tagName); + + this.el = el; + this.copy = copy; + + copy.observed = true; + + for (const name of el.getAttributeNames()) + if (name !== "integrity") copy[name] = el[name]; + + if ("innerHTML" in el && el.innerHTML !== "") + $aero.safeText(copy, el.innerHTML); + } + clone() { + // Insert + this.el.after(this.copy); + } + cleanup() { + if (this.el instanceof HTMLScriptElement) { + // Disable old script by breaking the type so it doesn't run + this.el.type = "_"; + + $aero.safeText(this.el, ""); + } + + this.el.remove(); + } +}; diff --git a/public/aero/browser/rewriters/cors.js b/public/aero/browser/rewriters/cors.js new file mode 100644 index 0000000..a770548 --- /dev/null +++ b/public/aero/browser/rewriters/cors.js @@ -0,0 +1,19 @@ +// For Cors Emulation + +/* +Trusted Types +To comply with trusted type headers if applicable +*/ +$aero.tt = trustedTypes.createPolicy("$aero", { + createHTML: str => str, + createScript: str => str, +}); + +// A safe wrapper for text to comply with trusted types +$aero.safeText = (el, str) => { + const isScript = el instanceof HTMLScriptElement; + + el.innerHTML = $aero.config.flags.corsEmulation + ? $aero.tt[isScript ? "createHTML" : "createScript"](str) + : str; +}; diff --git a/public/aero/browser/rewriters/csp.js b/public/aero/browser/rewriters/csp.js new file mode 100644 index 0000000..f9c90ad --- /dev/null +++ b/public/aero/browser/rewriters/csp.js @@ -0,0 +1 @@ +$aero.rewriteCsp = csp => ($aero.config.rewriteCSP ? csp : ""); diff --git a/public/aero/browser/rewriters/cspSrc.js b/public/aero/browser/rewriters/cspSrc.js new file mode 100644 index 0000000..17aa830 --- /dev/null +++ b/public/aero/browser/rewriters/cspSrc.js @@ -0,0 +1,42 @@ +// Gets the sources in the CSP with directive +$aero.cspSrc = dir => { + const [sources] = $aero.cors.csp.match(new RegExp(`${dir} ([^;]*)`), "g"); + + if (typeof sources === "undefined") return; + + return sources.split(" "); +}; + +// If CSP blocked +$aero.checkCsp = dir => { + const sources = $aero.cspSrc(dir); + + let blocked = false; + + if (sources) { + let allowed = false; + + if (!sources.includes("'none'")) + for (const source of sources) { + if ($aero.proxyLocation.href.startsWith(source)) { + allowed = true; + break; + } + + const wc = source.split("*"); + + if ( + // Wildcard found + wc.length > 1 && + $aero.proxyLocation.href.startsWith(wc[0]) + ) { + allowed = true; + break; + } + } + + if (!allowed) blocked = true; + } + + return blocked; +}; diff --git a/public/aero/browser/rewriters/html.js b/public/aero/browser/rewriters/html.js new file mode 100644 index 0000000..322ff97 --- /dev/null +++ b/public/aero/browser/rewriters/html.js @@ -0,0 +1,132 @@ +$aero.set = (el, attr, val) => { + // Backup element + // For Element hooks + el.setAttribute(`_${attr}`, val); + + el.setAttribute(attr, val); +}; + +/** + * Rewrite an element + * @param {Element} - The element to rewrite + * @param {String=} - If it is an attribute that is being rewritten + */ +$aero.rewrite = async (el, attr) => { + // Don't exclusively rewrite attributes or check for already observed elements + const isNew = typeof attr === "undefined"; + + if (isNew && typeof el.observed !== "undefined") return; + + const tag = el.tagName.toLowerCase(); + + // CSP Testing + function allow(dir) { + if (!$aero.config.flags.corsEmulation && $aero.checkCsp(dir)) { + el.remove(); + return false; + } + + return true; + } + + // TODO: Finish CSP emulation + if (isNew && tag === "script" && !el.rewritten) { + if (el.src) $aero.set(el, "src", $aero.rewriteHtmlSrc(el.src)); + if ( + typeof el.innerHTML === "string" && + el.innerHTML !== "" && + // Make sure the script has a js type + (el.type === "" || + el.type === "text/javascript" || + el.type === "application/javascript") + ) { + /* + FIXME: Fix safeText + el.innerHTML = $aero.safeText($aero.scope(el.innerText)); + */ + el.innerHTML = $aero.scope(el.innerText); + + // The inline code is read-only, so the element must be cloned + const cloner = new $aero.Cloner(el); + + cloner.clone(); + cloner.cleanup(); + } + } else if (tag === "a" || tag === "area" || tag === "base") { + if (el.href) $aero.set(el, "href", $aero.rewriteHtmlSrc(el.href)); + if (el.hasAttribute("xlink:href")) + $aero.set( + el, + "xlink:href", + $aero.rewriteHtmlSrc(el.getAttribute("xlink:href")) + ); + } else if ( + tag === "form" && + // Don't rewrite again + !el._action && + // Action is automatically created + el.action !== null + ) + $aero.set(el, "action", $aero.rewriteHtmlSrc(el.action)); + else if (tag === "iframe") { + if (el.csp) $aero.set(el, "csp", rewriteCSP(el.csp)); + + if (el.src && allow("frame-src")) { + // Embed the origin the origin as an attribute, so that the frame can reference it to do its checks + /// TODO: Conceal this + el.parentProxyOrigin = $aero.proxyLocation.origin; + $aero.set(el, "src"); + + // Inject aero imports if applicable then rewrite the Src + $aero.set( + el, + "src", + $aero.rewriteHtmlSrc( + el.src.replace(/data:text\/html/g, "$&" + $aero.imports) + ) + ); + } + if (el.srcdoc) + // Inject aero imports + $aero.set(el, "srcdoc", $aero.imports + el.srcdoc); + if (el.allow) + // TODO: Emulate Permissions policy using $aero.cors.perms + null; + } else if (tag === "portal" && el.src) + $el.set(el, "src", $aero.rewriteHtmlSrc(el.src)); + else if (tag === "meta") { + switch (el.httpEquiv) { + case "content-security-policy": + $aero.set(el, "content", $aero.rewriteCSP(el.content)); + break; + case "refresh": + $aero.set( + el, + "content", + el.content.replace( + /^([0-9]+)(;)(\s+)?(url=)(.*)/g, + (_match, g1, g2, g3, g4, g5) => + g1 + g2 + g3 + g4 + $aero.rewriteSrc(g5) + ) + ); + } + } else if (tag === "link" && tag.rel === "manifest") { + $aero.set(el, "href", $aero.rewriteSrc(el.href)); + } else if ($aero.config.flags.legacy && tag === "html") { + // Cache manifests + $aero.set(el, "manifest", $aero.rewriteSrc(el.manifest)); + } + + if (isNew && "integrity" in el && el.integrity !== "") { + const cloner = new $aero.Cloner(el); + + cloner.clone(); + cloner.cleanup(); + } + + // TODO: Proxify the getters and setters too + if (el.onload) $aero.set(el, "onload", $aero.scope(el.onload)); + if (el.onerror) $aero.set(el, "onerror", $aero.scope(el.onerror)); + + el.observed = true; +}; diff --git a/public/aero/browser/rewriters/htmlSrc.js b/public/aero/browser/rewriters/htmlSrc.js new file mode 100644 index 0000000..ebeb402 --- /dev/null +++ b/public/aero/browser/rewriters/htmlSrc.js @@ -0,0 +1,20 @@ +/** + * Extends src rewriting for processed html urls + * @param {string} - The url to rewrite + */ +$aero.rewriteHtmlSrc = src => { + const url = $aero.proto.get( + src.replace(new RegExp(`^(${location.origin})`, "g"), "") + ); + + if (/^javascript:/g.test(url)) return $aero.scope(url); + if ( + // Ignore data protocols + /^(about:|data:)/g.test(url) || + // Don't rewrite again + new RegExp(`^(${$aero.config.prefix})`).test(url) + ) + return url; + + return $aero.rewriteSrc(url); +}; diff --git a/public/aero/browser/xml/intercept.xsl b/public/aero/browser/xml/intercept.xsl new file mode 100644 index 0000000..825629e --- /dev/null +++ b/public/aero/browser/xml/intercept.xsl @@ -0,0 +1,7 @@ + \ No newline at end of file diff --git a/public/aero/config.js b/public/aero/config.js index 1eaed19..96c4914 100644 --- a/public/aero/config.js +++ b/public/aero/config.js @@ -1,5 +1,52 @@ -const prefix = '/go/'; -const bare = '/bare/'; -const codec = 'plain'; +const aeroPrefix = "/aero/"; +const prefix = "/go/"; -export { prefix, bare, codec }; \ No newline at end of file +const cacheKey = "httpCache"; + +const backends = ["/bare/"]; +const wsBackends = ["/fetchws"]; +// Not implemented yet +const wrtcBackends = { + // I recommend using the TURN servers from https://www.metered.ca/tools/openrelay/ + ice: ["stun:stun.l.google.com:19302"], +}; + +const dynamicConfig = { + // The database name + dbName: "aero", + // Id to differentiate message from other purposes + id: "update", +}; + +// For experimental features +const flags = { + legacy: true, // Recommended + nonstandard: true, // Browser-specific code. Recommended + dynamicUpdates: false, // Recommended + corsEmulation: true, // Recommended + wrtc: true, // Recommended + ws: true, // Recommended + misc: false, // Experimental features that haven't been tested, and aren't significant enough to earn a flag + safariSupport: false, // Safari has limited support of SW, so there may be some workarounds + nestedWorkers: false, // Not finished +}; + +// Ignore these if you are not a programmer +const debug = { + errors: true, + url: true, + src: false, + scoping: false, +}; + +export { + aeroPrefix, + prefix, + cacheKey, + backends, + wsBackends, + wrtcBackends, + dynamicConfig, + flags, + debug, +}; diff --git a/public/aero/cookie.js b/public/aero/cookie.js deleted file mode 100644 index 298f069..0000000 --- a/public/aero/cookie.js +++ /dev/null @@ -1,13 +0,0 @@ -function parse(cookie) { - -} - -function rewriteGetCookie(cookie) { - return cookie; -} - -function rewriteSetCookie(cookie) { - return cookie; -} - -export { rewriteGetCookie, rewriteSetCookie }; \ No newline at end of file diff --git a/public/aero/corsTest.js b/public/aero/corsTest.js deleted file mode 100644 index 12cd19a..0000000 --- a/public/aero/corsTest.js +++ /dev/null @@ -1,20 +0,0 @@ -function block(url) { - /* - try { - const controller = new AbortController(); - const signal = controller.signal; - - await fetch(url, { signal }); - - // Don't actually send the request. - controller.abort() - } catch (err) { - if (err.name !== 'AbortError') - return false; - } - */ - - return false; -} - -export { block }; \ No newline at end of file diff --git a/public/aero/dom.js b/public/aero/dom.js deleted file mode 100644 index 13097c1..0000000 --- a/public/aero/dom.js +++ /dev/null @@ -1,127 +0,0 @@ -// I might have to use es2020 imports -//import { scope } from './scope.js'; - -const prefix = '/go/'; - -function scope(script) { - return script; -} - -function rewriteUrl(rawUrl) { - console.log(rawUrl); - - console.log(location.href); - - let hostname = new URL(new URL(location.href).pathname.replace(new RegExp(`^(${prefix})`), '')).hostname; - - console.log(hostname); - - let url = rawUrl - // / - .replace(/^(\/)/g, `${prefix}/${hostname}/`) - // ./ - .replace(/^(\.\/)/g, `./${hostname}/`); - - if (/^(https?:\/\/)/g.test(url)) - url = prefix + url; - - return url; -} - -new MutationObserver((mutations, observer) => { - //console.table(mutations); - - for (let mutation of mutations) { - const addedNode = mutation.addedNodes[0]; - - //console.time(addedNode.tagName); - - // This is the only way to detect blocked scripts by mismatched integrity - if (addedNode instanceof HTMLScriptElement) { - /* - if (!addedNode.rewritten) { - addedNode.rewritten = true; - - // Backup - addedNode._nonce = addedNode.nonce; - addedNode._integrity = addedNode.integrity; - addedNode.removeAttribute('nonce'); - addedNode.removeAttribute('integrity'); - - // Create clone - const clone = document.createElement('script'); - - if (addedNode.src) - clone.setAttribute('src', addedNode.getAttribute('src')); - if (addedNode.type) - clone.setAttribute('type', addedNode.getAttribute('type')); - if (addedNode.async) - clone.type = addedNode.async; - - // Modify - clone.innerHTML = scope(addedNode.innerText); - - // Insert - addedNode.after(clone); - - // Remove - addedNode.remove() - } - */ - } else { - const node = mutation.target; - - if (node.integrity) { - node._integrity = node.integrity - node.removeAttribute('integrity'); - } - if (node.nonce) { - node._nonce = node.nonce - node.removeAttribute('nonce'); - } - - switch (node.tagName) { - case 'A': - if (node.href) { - // Backup - const href = node.getAttribute('href'); - - node._href = href; - - node.setAttribute('href', rewriteUrl(href)); - } - break; - case 'FORM': - if (node.action) { - // Backup - const action = node.getAttribute('action'); - - node._action = action; - - node.setAttribute('action', rewriteUrl(action)); - } - break; - case 'LINK': - if (node.rel === 'manifest' && node.href) { - // TODO: Rewrite manifest - // For now we will delete the href - href = '' - node.removeAttribute('href'); - } - break; - case 'META': - switch (node.httpEquiv) { - case 'content-security-policy': - // TODO: Rewrite - node.content = ''; - case 'refresh': - node.content = node.content.replace(/[0-9]+;url=(.*)/g, `${prefix}/$1`) - } - break; - } - } - } -}).observe(document, { - childList: true, - subtree: true -}); \ No newline at end of file diff --git a/public/aero/getRequestUrl.js b/public/aero/getRequestUrl.js deleted file mode 100644 index 964c99b..0000000 --- a/public/aero/getRequestUrl.js +++ /dev/null @@ -1,16 +0,0 @@ -import { prefix } from './config.js'; - -function getRequestUrl(rawUrl, isFirstRequest, origin) { - const url = rawUrl.split(prefix)[1] - - if (isFirstRequest) - return new URL(url); - - //const noProtogen = url.replace(/https?:\/\//g, ''); - - // return new URL(`${origin}/${noProtogen}`); - - return new URL(url); -} - -export { getRequestUrl }; \ No newline at end of file diff --git a/public/aero/handle.js b/public/aero/handle.js index c504bfb..44d238c 100644 --- a/public/aero/handle.js +++ b/public/aero/handle.js @@ -1,93 +1,386 @@ -import BareClient from './bareClient/BareClient.js'; +// Routes +import routes from "./this/internal/routes.js"; -import { bare, prefix } from './config.js'; +// Dynamic Config +import getConfig from "./this/dynamic/getConfig.js"; +// Standard Config +import { prefix, aeroPrefix, debug, flags } from "./config.js"; -import { getRequestUrl } from './getRequestUrl.js'; -import { block } from './corsTest.js'; -import { scope } from './scope.js'; -import { filterHeaders } from './headers.js'; +// Utility +import BareClient 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"; -async function handle(location, event) { - const bareClient = new BareClient(bare); +// Cors Emulation +import block from "./this/cors/test.js"; - const isFirstRequest = event.request.mode === 'navigate' && event.request.destination === 'document'; +// Cache Emulation +import CacheManager from "./this/cors/cache.js"; - const path = new URL(event.request.url).pathname; - - if (path.startsWith('/aero/')) - return await fetch(event.request.url); +// 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; + + // Construct proxy fetch instance + const proxyFetch = useBare + ? // The bare client doesn't support proxy switching + new BareClient(backends[0]) + : new ProxyFetch(backends); + + 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 origin; - if (event.clientId !== '') { + var clientUrl; + // Get the origin from the user's window + if (event.clientId !== "") { + // Get the current window const client = await clients.get(event.clientId); - origin = new URL(new URL(client.url).pathname.replace(new RegExp(`^(${prefix})`, 'g'), '')).origin; + + // Get the url after the prefix + clientUrl = new URL(afterPrefix(client.url)); } - const url = getRequestUrl(path, isFirstRequest, origin); + // 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"; - // CORS testing - if (block(url.href)) - return; + // This is used for determining the request url + const iFrame = req.destination === "iframe"; - const response = await bareClient.fetch(url); + const navigate = homepage || iFrame; - const headers = Object.fromEntries(response.headers.entries()); - - console.table(headers, ['Header', 'Value']); - - const bareHeaders = filterHeaders(headers); + // 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 + let 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 + ); + + // Backup headers to later conceal in http request api interceptors + if (req.destination === "") + rewriteGetCookie["x-aero-headers"] = JSON.stringify(respHeaders); + + const type = respHeaders["content-type"]; + + const html = + // Not all sites respond with a type + typeof type === "undefined" || type.startsWith("text/html"); - // Doesn't work on Mozilla Hubs - //const isHtml = bareHeaders['content-type'].startsWith('text/html'); - const isHtml = true; + // Rewrite the body - let text; - if (isFirstRequest && isHtml) { - text = await response.text(); - if (text !== '') - text = ` + /** @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 = ` - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + ${unwrapImports(routes)} +${body} +`; + } + } else if ( + navigate && + (text.startsWith("text/xml") || text.startsWith("application/xml")) + ) { + body = await resp.text(); + + ` + +{ + prefix: ${prefix} +} + + +${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); -${text} + 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) + // TODO: Error emulation + throw new Error("Script blocked") + } +})(); `; - } else if (event.request.destination === 'script') - text = scope(await response.text()); - else if (event.request.destination === 'serviceworker') - text = ` -// Try to find if there is a better method of detection within a service worker -if (typeof module === 'undefined') - importScripts('./gel.js'); -else - // Module imports have to be used here - console.warn('No module support'); - -${text} + // 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} `; - else - text = response.body; + // No rewrites are needed; proceed as normal + else body = resp.body; + + rewriteRespHeaders["x-aero-size-transfer"] = null; + rewriteRespHeaders["x-aero-size-encbody"] = null; - return new Response(text, { - status: response.status, - headers: bareHeaders + // 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 { handle }; \ No newline at end of file +export default handle; diff --git a/public/aero/headers.js b/public/aero/headers.js deleted file mode 100644 index 14c39de..0000000 --- a/public/aero/headers.js +++ /dev/null @@ -1,30 +0,0 @@ -import { rewriteSetCookie } from './cookie.js'; - -const delHeaders = ['cache-control', 'content-security-policy', 'content-encoding', 'content-length', 'cross-origin-opener-policy', 'cross-origin-opener-policy-report-only', 'report-to', 'strict-transport-security', 'x-content-type-options', 'x-frame-options']; - -function rewriteLocation(url) { - console.log(url); - return 'http://localhost:3000/go/https://www.google.com/'; -} - -function filterHeaders(headers) {; - return headers; - - // Type safety >:) - if (typeof headers === 'object') - for (header of headers) { - if (header in delHeaders) - delete headers[headers] - else if (header === 'location') - header = rewriteLocation(header); - //It might be better if instead of adding cookies on the site page itself the cookie data is appended to document.cookie; this would allow the use of the browser's localstorage and new async cookie api - else if (header === 'cookie') - header = rewriteGetCookie(header); - else if (header === 'set-cookie') - header = rewriteSetCookie(header); - } - - return headers; -} - -export { filterHeaders }; \ No newline at end of file diff --git a/public/aero/init.js b/public/aero/init.js new file mode 100644 index 0000000..93aa03e --- /dev/null +++ b/public/aero/init.js @@ -0,0 +1,4 @@ +// Inits all the message handlers that power aero +import dynamicUpdates from "./this/handlers/updates.js"; + +dynamicUpdates(); diff --git a/public/aero/scope.js b/public/aero/scope.js deleted file mode 100644 index 554ea7e..0000000 --- a/public/aero/scope.js +++ /dev/null @@ -1,10 +0,0 @@ -function check(value) { - return value; -} - -function scope(script) { - return script.replace(/location/g, '_$1'); - //.replace(/(this|globalThis|window|location)/g, 'check($1)'; -} - -export { scope, check }; diff --git a/public/aero/shared/cookie.js b/public/aero/shared/cookie.js new file mode 100644 index 0000000..4a889bc --- /dev/null +++ b/public/aero/shared/cookie.js @@ -0,0 +1,35 @@ +// For the SW +import * as config from "../config.js"; +if (typeof $aero === "undefined") + var $aero = { + config, + }; + +function rewriteGetCookie(cookie) { + return cookie + .replace( + new RegExp( + `(?<=path\=)${$aero.config.prefix}${$aero.location.origin}.*(?= )`, + "g" + ), + match => + match.replace( + new RegExp( + `^(${$aero.config.prefix}${$aero.location.origin})` + ), + "" + ) + ) + .replace(/_path\=.*(?= )/g, ""); +} +function rewriteSetCookie(cookie) { + return cookie.replace( + /(?<=path\=).*(?= )/g, + `${$aero.config.prefix}${$aero.location.origin}$& _path=$&` + ); +} + +$aero.rewriteGetCookie = rewriteGetCookie; +$aero.rewriteSetCookie = rewriteSetCookie; + +export { rewriteGetCookie, rewriteSetCookie }; diff --git a/public/aero/shared/scope.js b/public/aero/shared/scope.js new file mode 100644 index 0000000..955ba39 --- /dev/null +++ b/public/aero/shared/scope.js @@ -0,0 +1,195 @@ +// For the SW +import * as config from "../config.js"; +if (typeof $aero === "undefined") + var $aero = { + config, + }; + +/** + * Deep property check scoping + * @param {string} - The script to be rewritten + * @return {string} - The rewritten script + */ +$aero.scope = script => { + // ' + let iSQ = false; + // " + let iDQ = false; + // ` + let iTQ = false; + + // These need start and end since they aren't uniform + // ${...} + let sT; + // Normal start braces; This is used so we can ignore scopes which may've been confused with the end of a template quote + let sBc = []; + // This could contain either the closing braces of scopes or templates + let eBc = []; + // Brackets; This is what we are looking to rewrite + // [...] + let sBr = []; + let eBr = []; + + for (var i = 0; i < script.length; i++) { + // Previous char + const pC = script[i - 1]; + // Current char + const c = script[i]; + // Next char + const nC = script[i + 1]; + + // Check for string chars so that the scoper doesn't don't overwrite strings + if (isStrChar("'", c, pC)) iSQ = !iSQ; + else if (isStrChar('"', c, pC)) iDQ = !iDQ; + else if (isStrChar("`", c, pC)) iTQ = !iTQ; + else if (iTQ) { + // Check for templates + if (pC === "$" && c === "{") sT.push(i - 1); + else if (c === "{") sBc = i; + else if (c === "}") { + eBc.push(i); + + // If the template has properly ended + if (eBc.length === sBc.length + 1) { + // Scope what is inside of the template + var { i, script } = replace( + script, + sBc, + eBc.at(-1), + match => $aero.scope(match) + ); + + // Reset + sBc = undefined; + eBc = []; + } + } + } else if (!iSQ && !iDQ) { + // Inside code + if (isVarChar(c)) { + // Inside word + const [word, sWordI] = getCurrentWordStr(script, i); + + if (word === "location") { + // Ensure that the location in the current scope wasn't overwritten + var { i, script } = replace( + script, + sWordI, + i, + () => + "($aero.isLocation(location) ? $aero.location : location)" + ); + } else if ( + word === "document\\.domain" || + word === "document\\.url" + ) + var { i, script } = insert(script, "$aero.", sWordI); + } else { + // Check for brackets that are property accessors not destructors + if ( + c === "[" && + // Be able to match chained property accessors + nC !== "]" && + // Ensure that the starting brace is for a property accessor by checking if an object name is given + isVarChar(c) + ) + sBr.push(i); + else if ( + c === "]" && + // Ensure that the starting brace is for a property accessor not a destructor by making sure there isn't any equal sign + (() => { + for (let j = i; j < script.length; j++) + // Whitespace can be ignored we are only looking for the equals + if (j !== " ") + // Return if it is not a destructor + return j !== "="; + })() + ) { + eBr.push(i); + + // The brace and its nested braces (if applicable) have been closed + if (eBr.length === sBr.length) + // Now it's time to scope them all + // Go through all the pairs + while (eBr.length >= 0) { + // Get indices of [ and ] + const sI = sBr.pop(); + const eI = eBr.pop(); + + const [word, sWordI] = getCurrentWordStr( + script, + sI + ); + + var { i, script } = replace( + script, + sWordI, + eI, + match => `aero.scope(${word + match})` + ); + } + } + } + } + } + + return script; +}; + +// Backreferences the current char index to check what the full word is +function getCurrentWordStr(str, i) { + let word = ""; + let sWordI = i; + + for (; i >= 0; i--) { + const c = str[i]; + + if (isVarChar(c)) word = c + word; + else { + // The index behind the word + sWordI = i + 1; + break; + } + } + + return [word, sWordI]; +} + +function replace(sI, eI, str, func) { + const match = str.substring(sI, eI); + + const replace = func(match); + + // Splice can't be used on strings + return { + script: str.slice(0, sI) + replace + str.substring(eI), + // Used to offset the index to reflect the replacement + i: sI + replace.length, + }; +} + +function insert(str, add, i) { + return { + str: str.insert(add, i), + i: add.length, + }; +} + +function isStrChar(str, c, pC) { + return ( + c === str && + // Ensure that the quote isn't a terminator + pC !== "\\" + ); +} +// Checks if a char can be used as a variable name +function isVarChar(c) { + return ( + (c >= "A" && c <= "Z") || + (c >= "a" && c <= "z") || + c === "_" || + c === "$" + ); +} + +export default $aero.scope; diff --git a/public/aero/shared/src.js b/public/aero/shared/src.js new file mode 100644 index 0000000..1e5297b --- /dev/null +++ b/public/aero/shared/src.js @@ -0,0 +1,27 @@ +// For the SW +import * as config from "../config.js"; +if (typeof $aero === "undefined") + var $aero = { + config, + proxyLocation: { + href: null, + }, + }; + +/** + * This should not be used for processed html attributes, rather rewriteSrcHtml + * @param {string} - The url to rewrite + * @param {string} - The url to rewrite + */ +$aero.rewriteSrc = (url, proxyUrl = $aero.proxyLocation.href) => { + // Protocol + const rewrittenUrl = /^(https?:\/\/)/g.test(url) + ? $aero.config.prefix + url + : new URL(url, proxyUrl).href; + + if ($aero.config.debug.src) console.info(`${url} ➜ ${rewrittenUrl}`); + + return rewrittenUrl; +}; + +export default $aero; diff --git a/public/aero/tests/scoping.html b/public/aero/tests/scoping.html new file mode 100644 index 0000000..91a596d --- /dev/null +++ b/public/aero/tests/scoping.html @@ -0,0 +1,69 @@ + + + + diff --git a/public/aero/this/cors/cache.js b/public/aero/this/cors/cache.js new file mode 100644 index 0000000..a537fe0 --- /dev/null +++ b/public/aero/this/cors/cache.js @@ -0,0 +1,98 @@ +import { cacheKey } from "../../config.js"; + +export default class { + /** + * @param {headers} - Req headers used to get the cache mode + */ + constructor(headers) { + // https://fetch.spec.whatwg.org/#concept-request-cache-mode + if ( + this.mode === "default" && + headers.includes([ + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "If-Match", + "If-Range", + ]) + ) + this.mode = "no-store"; + else this.mode = headers["x-aero-cache"] ?? ""; + } + + get bypass() { + return this.mode === "no-store" || this.mode === "reload"; + } + + get #getTime() { + return Date.now() / 1000; + } + + async #getCache() { + return await caches.open(cacheKey); + } + + /** + * @param {string} - Proxy origin + */ + async clear(origin) { + const cache = await this.#getCache(); + + for (const url of await cache.keys) + if (url.startsWith(origin)) cache.delete(url); + } + /** + * @param {string} - Cache Control HTTP Header + * @param {string} - Expire HTTP Header for fallback + * @returns {number} + */ + async getAge(cacheControl, expiry) { + if (cacheControl) { + const dirs = cacheControl.split(";").map(dir => dir.trim()); + + const secs = dirs + .find(dir => dir.startsWith("max-age")) + .split("=") + .pop(); + + return secs + this.#getTime; + } else if (expiry) return Date.parse(expiry).getTime() / 1000; + return false; + } + /** + * @param {string} - Proxy path + * @param {number} - Cache age + * @returns {Response | boolean} - Cached resp + */ + async get(path, age) { + const cache = await this.#getCache(); + + if ( + // Bypass caches + this.mode !== "no-store" || + this.mode !== "reload" || + this.mode !== "no-cache" || + // Ignore freshness + this.mode === "force-cache" || + this.mode === "only-if-cached" || + // Check the freshness + age < getTime() + ) { + const resp = cache.match(path); + + return resp instanceof Response ? resp : false; + } + + return false; + } + /** + * @param {string} - Proxy path + * @param {string} - Proxy resp + */ + async set(path, resp) { + const cache = await this.#getCache(); + + if (this.mode !== "no-store" && this.mode !== "only-if-cached") + await cache.put(path, resp); + } +} diff --git a/public/aero/this/cors/clear.js b/public/aero/this/cors/clear.js new file mode 100644 index 0000000..fe9fa92 --- /dev/null +++ b/public/aero/this/cors/clear.js @@ -0,0 +1,17 @@ +export default async (clear, id) => { + if (clear.includes("'*'") || clearincludes("'cache'")) + await cache.clear(proxyUrl.origin); + // Send messages to all windows with the same origin to reload + if ( + (flags.experimental && clear.includes("'*'")) || + clear.includes("executionContexts") + ) + for (const client of await clients.get(id)) { + const clientOrigin = new URL( + client.url.replace(new RegExp(`^(${prefix})`, "g"), "") + ).origin; + + if (clientOrigin === proxyUrl.origin) + client.postMessage("clearExecutionContext"); + } +}; diff --git a/public/aero/this/cors/test.js b/public/aero/this/cors/test.js new file mode 100644 index 0000000..52e0d3a --- /dev/null +++ b/public/aero/this/cors/test.js @@ -0,0 +1,23 @@ +/** + * Tests to see if the request would be blocked due to cors rules + * @param {String} - url The url that is being tested + * @return {Boolean} The result + */ +export default async url => { + try { + const controller = new AbortController(); + const signal = controller.signal; + + await fetch(url, { + mode: "no-cors", + signal, + }); + + // Don't actually send the request. + controller.abort(); + + return false; + } catch (err) { + return err.name === "AbortError"; + } +}; diff --git a/public/aero/this/dynamic/getConfig.js b/public/aero/this/dynamic/getConfig.js new file mode 100644 index 0000000..a2032a4 --- /dev/null +++ b/public/aero/this/dynamic/getConfig.js @@ -0,0 +1,15 @@ +import * as config from "../../config.js"; + +import getStore from "./getStore.js"; + +// Dynamically retrieve the config +export default () => { + if (config.flags.dynamicUpdates) + getStore(config.dynamicUpdates.name, store => { + const dbConfig = store.getAll(); + + // Could be undefined, or worse erroneous + return typeof dbConfig === "object" ? dbConfig : config; + }); + else return config; +}; diff --git a/public/aero/this/dynamic/getStore.js b/public/aero/this/dynamic/getStore.js new file mode 100644 index 0000000..f7c036a --- /dev/null +++ b/public/aero/this/dynamic/getStore.js @@ -0,0 +1,24 @@ +// A safe astraction to get the actual config store that aero needs +export default (dbName, func) => { + const req = indexedDB.open(dbName); + + req.onsuccess = () => { + const db = req.result; + + // Error here + const transaction = db.transaction("config", "readwrite"); + + transaction.oncomplete = () => { + const store = transaction.objectStore("config"); + + if (store instanceof IDBOpenDBRequest) func(store); + else console.error(`Unable to get store for config`); + }; + }; + + req.onerror = event => { + console.error( + `Error initializing the db for dynamic config updates\n${event.target.errorCode}` + ); + }; +}; diff --git a/public/aero/this/handlers/updates.js b/public/aero/this/handlers/updates.js new file mode 100644 index 0000000..86af7cc --- /dev/null +++ b/public/aero/this/handlers/updates.js @@ -0,0 +1,18 @@ +import getStore from "../dynamic/getStore.js"; + +import { dynamicConfig, flags } from "../../config.js"; + +const { dbName, id } = dynamicConfig; + +// For dynamic config updates +export default () => { + if (flags.dynamicUpdates) + getStore(dbName, store => { + self.addEventListener("message", event => { + const config = event.data; + + if (typeof config === "object" && config.id === id) + store.add(config); + }); + }); +}; diff --git a/public/aero/this/internal/routes.js b/public/aero/this/internal/routes.js new file mode 100644 index 0000000..78eccd3 --- /dev/null +++ b/public/aero/this/internal/routes.js @@ -0,0 +1,50 @@ +export default { + // Used by both the inject code and this service worker + shared: ["cookie", "scope", "src"], + "browser/misc": [ + "escape", + "proto", + "storage", + // CORS Emulation + "frame", + "perms", + "clear", + ], + "browser/rewriters": ["cors", "csp", "cspSrc", "cloner", "htmlSrc", "html"], + // Hide the true origin + "browser/api/concealer": [ + "css", + "element", + "error", + "event", + "file", + "fs", + "http", + "manifest", + "navigation", + "payment", + "presentation", + "push", + "reporting", + "scoping", + "timing", + "xml", + ], + "browser/api/event": ["messages"], + "browser/api/loc": [ + "contentIndex", + "history", + "location", + "navigator", + "popup", + ], + // Alt protocols + "browser/api/req": ["http", "ws", "wrtc"], + "browser/api/storage": ["cookie", "idb", "sql", "storage"], + "browser/api/worker": ["workers"], + /* + Miscellaneous injected code + Don't put anything after dom + */ + "browser/injects": ["dom"], +}; diff --git a/public/aero/this/misc/ProxyFetch.js b/public/aero/this/misc/ProxyFetch.js new file mode 100644 index 0000000..17f18d9 --- /dev/null +++ b/public/aero/this/misc/ProxyFetch.js @@ -0,0 +1,58 @@ +import { debug } from "../../config.js"; + +import headersToObject from "./headersToObject.js"; + +/** + * A wrapper for Fetch that routes all requests through the proxy backend + * @constructor + * @param {string} - The backends to try + */ +export default class { + constructor(backends) { + this.backends = backends; + } + async fetch(url, opts) { + let ret = { + method: opts && "method" in opts ? opts.method : "GET", + headers: { + "x-url": url, + "x-headers": "{}", + }, + }; + + if (typeof opts !== "undefined") { + if ("body" in opts) ret.body = opts.body; + if ("headers" in opts) + ret.headers["x-headers"] = JSON.stringify( + typeof opts.headers === "object" + ? opts.headers + : headersToObject(opts.headers) + ); + } + + let resp; + + for (const backend of this.backends) + try { + // Make the request to the proxy + const attempt = await fetch(backend, ret); + + // An available backend has been found + resp = attempt; + break; + } catch (err) { + if (debug.errors && err.name === "NetworkError") + console.warn( + backend.startsWith("/") + ? "The main backend is down" + : `Backend ${new URL(backend).hostname} is down` + ); + } + + if (!resp) + return new Error( + "Can't find any available backends. You may be offline." + ); + return resp; + } +} diff --git a/public/aero/this/misc/bare/dist/BareClient.js b/public/aero/this/misc/bare/dist/BareClient.js new file mode 100644 index 0000000..ff3177b --- /dev/null +++ b/public/aero/this/misc/bare/dist/BareClient.js @@ -0,0 +1 @@ +export default true; diff --git a/public/aero/this/misc/getRequestUrl.js b/public/aero/this/misc/getRequestUrl.js new file mode 100644 index 0000000..fd14bda --- /dev/null +++ b/public/aero/this/misc/getRequestUrl.js @@ -0,0 +1,66 @@ +import { prefix } from "../../config.js"; + +/** + * Gets the url that will actually be fetched + * @param {string} - The origin of the site + * @param {string} - The origin of the service worker + * @param {string} - raw url after the proxy prefix + * @param {string} - path of the site + * @param {boolean} - the request is for the homepage + * @param {boolean} - the site is inside of an iFrame + * @returns {string} The url to proxy + */ +function getRequestUrl( + origin, + workerOrigin, + proxyUrl, + path, + isHomepage, + isIframe +) { + const noPrefix = path.split(prefix)[1]; + + // If it is the first request, there is no need to do any relative url checking + if (isHomepage) return new URL(noPrefix); + + // Don't hardcode origins + const absoluteUrl = origin !== workerOrigin; + + if (absoluteUrl) { + return origin + path; + } else { + const proxyOrigin = proxyUrl?.origin; + const proxyPath = proxyUrl?.pathname; + + if (noPrefix) { + let retUrl = noPrefix; + + const proxyPathSlashes = proxyPath?.split("/"); + const proxyEndingPath = proxyPathSlashes?.at(-1); + + // Correct relative urls that don't end with a slash; this is an edge case + if ( + proxyPathSlashes?.at(-2) !== proxyOrigin && + proxyEndingPath.length > 0 + ) { + let noPrefixSplit = noPrefix?.split("/"); + + noPrefixSplit.splice( + noPrefixSplit.length - 1, + 0, + proxyEndingPath + ); + retUrl = noPrefixSplit.join("/"); + } + + const protoSplit = noPrefix.split("https://"); + const noPrefixProto = protoSplit[1]; + + return protoSplit.length > 1 || isIframe + ? retUrl + : `${proxyOrigin}/${noPrefixProto}`; + } else return proxyOrigin + path; + } +} + +export default getRequestUrl; diff --git a/public/aero/this/misc/headersToObject.js b/public/aero/this/misc/headersToObject.js new file mode 100644 index 0000000..898e020 --- /dev/null +++ b/public/aero/this/misc/headersToObject.js @@ -0,0 +1,5 @@ +function headersToObject(headers) { + return Object.fromEntries(headers.entries()); +} + +export default headersToObject; diff --git a/public/aero/this/misc/sharedModule.js b/public/aero/this/misc/sharedModule.js new file mode 100644 index 0000000..87c6b7f --- /dev/null +++ b/public/aero/this/misc/sharedModule.js @@ -0,0 +1,27 @@ +import headersToObject from "./headersToObject.js"; + +export default async event => { + const req = event.request; + + const resp = await fetch(req.url); + + if (!resp.headers.get("content-type").startsWith("application/javascript")) + return resp; + + const body = await resp.text(); + + // Remove the last line + return new Response( + body + .split("\n") + .filter( + line => + !(line.startsWith("import") || line.startsWith("export")) + ) + .join("\n"), + { + status: resp.status, + headers: headersToObject(resp.headers), + } + ); +}; diff --git a/public/aero/this/misc/unwrapImports.js b/public/aero/this/misc/unwrapImports.js new file mode 100644 index 0000000..1bacb8b --- /dev/null +++ b/public/aero/this/misc/unwrapImports.js @@ -0,0 +1,19 @@ +import { aeroPrefix } from "../../config.js"; + +export default (cats, escape) => { + const createScript = path => + `