actually prettier

This commit is contained in:
Toshit Chawda 2024-07-14 16:22:34 -07:00
parent fb53b44869
commit 56767f5b31
No known key found for this signature in database
GPG key ID: 91480ED99E2B3D9D
41 changed files with 1914 additions and 1919 deletions

View file

@ -1,7 +1,7 @@
"use strict"; "use strict"
const { resolve } = require("node:path"); const { resolve } = require("node:path")
const scramjetPath = resolve(__dirname, "..", "dist"); const scramjetPath = resolve(__dirname, "..", "dist")
exports.scramjetPath = scramjetPath; exports.scramjetPath = scramjetPath

4
lib/index.d.ts vendored
View file

@ -1,3 +1,3 @@
declare const scramjetPath: string; declare const scramjetPath: string
export { scramjetPath }; export { scramjetPath }

View file

@ -1,9 +1,9 @@
import { defineConfig } from "@rspack/cli"; import { defineConfig } from "@rspack/cli"
// import { RsdoctorRspackPlugin } from "@rsdoctor/rspack-plugin"; // import { RsdoctorRspackPlugin } from "@rsdoctor/rspack-plugin";
import { join } from "path"; import { join } from "path"
import { fileURLToPath } from "url"; import { fileURLToPath } from "url"
const __dirname = fileURLToPath(new URL(".", import.meta.url)); const __dirname = fileURLToPath(new URL(".", import.meta.url))
export default defineConfig({ export default defineConfig({
// change to production when needed // change to production when needed
@ -50,4 +50,4 @@ export default defineConfig({
// }) // })
], ],
watch: true, watch: true,
}); })

View file

@ -1,84 +1,84 @@
// Dev server imports // Dev server imports
import { createBareServer } from "@tomphttp/bare-server-node"; import { createBareServer } from "@tomphttp/bare-server-node"
import { createServer } from "http"; import { createServer } from "http"
import Fastify from "fastify"; import Fastify from "fastify"
import fastifyStatic from "@fastify/static"; import fastifyStatic from "@fastify/static"
import { join } from "node:path"; import { join } from "node:path"
import { spawn } from "node:child_process"; import { spawn } from "node:child_process"
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url"
//transports //transports
import { baremuxPath } from "@mercuryworkshop/bare-mux/node"; import { baremuxPath } from "@mercuryworkshop/bare-mux/node"
import { epoxyPath } from "@mercuryworkshop/epoxy-transport"; import { epoxyPath } from "@mercuryworkshop/epoxy-transport"
import { libcurlPath } from "@mercuryworkshop/libcurl-transport"; import { libcurlPath } from "@mercuryworkshop/libcurl-transport"
import { bareModulePath } from "@mercuryworkshop/bare-as-module3"; import { bareModulePath } from "@mercuryworkshop/bare-as-module3"
const bare = createBareServer("/bare/", { const bare = createBareServer("/bare/", {
logErrors: true, logErrors: true,
}); })
const fastify = Fastify({ const fastify = Fastify({
serverFactory: (handler) => { serverFactory: (handler) => {
return createServer() return createServer()
.on("request", (req, res) => { .on("request", (req, res) => {
if (bare.shouldRoute(req)) { if (bare.shouldRoute(req)) {
bare.routeRequest(req, res); bare.routeRequest(req, res)
} else { } else {
handler(req, res); handler(req, res)
} }
}) })
.on("upgrade", (req, socket, head) => { .on("upgrade", (req, socket, head) => {
if (bare.shouldRoute(req)) { if (bare.shouldRoute(req)) {
bare.routeUpgrade(req, socket, head); bare.routeUpgrade(req, socket, head)
} else { } else {
socket.end(); socket.end()
} }
}); })
}, },
}); })
fastify.register(fastifyStatic, { fastify.register(fastifyStatic, {
root: join(fileURLToPath(new URL(".", import.meta.url)), "./static"), root: join(fileURLToPath(new URL(".", import.meta.url)), "./static"),
decorateReply: false, decorateReply: false,
}); })
fastify.register(fastifyStatic, { fastify.register(fastifyStatic, {
root: join(fileURLToPath(new URL(".", import.meta.url)), "./dist"), root: join(fileURLToPath(new URL(".", import.meta.url)), "./dist"),
prefix: "/scram/", prefix: "/scram/",
decorateReply: false, decorateReply: false,
}); })
fastify.register(fastifyStatic, { fastify.register(fastifyStatic, {
root: baremuxPath, root: baremuxPath,
prefix: "/baremux/", prefix: "/baremux/",
decorateReply: false, decorateReply: false,
}); })
fastify.register(fastifyStatic, { fastify.register(fastifyStatic, {
root: epoxyPath, root: epoxyPath,
prefix: "/epoxy/", prefix: "/epoxy/",
decorateReply: false, decorateReply: false,
}); })
fastify.register(fastifyStatic, { fastify.register(fastifyStatic, {
root: libcurlPath, root: libcurlPath,
prefix: "/libcurl/", prefix: "/libcurl/",
decorateReply: false, decorateReply: false,
}); })
fastify.register(fastifyStatic, { fastify.register(fastifyStatic, {
root: bareModulePath, root: bareModulePath,
prefix: "/baremod/", prefix: "/baremod/",
decorateReply: false, decorateReply: false,
}); })
fastify.listen({ fastify.listen({
port: process.env.PORT || 1337, port: process.env.PORT || 1337,
}); })
const watch = spawn("pnpm", ["rspack", "-w"], { const watch = spawn("pnpm", ["rspack", "-w"], {
detached: true, detached: true,
cwd: process.cwd(), cwd: process.cwd(),
}); })
watch.stdout.on("data", (data) => { watch.stdout.on("data", (data) => {
console.log(`${data}`); console.log(`${data}`)
}); })
watch.stderr.on("data", (data) => { watch.stderr.on("data", (data) => {
console.log(`${data}`); console.log(`${data}`)
}); })

View file

@ -1,9 +1,9 @@
import { encodeUrl } from "./shared"; import { encodeUrl } from "./shared"
navigator.sendBeacon = new Proxy(navigator.sendBeacon, { navigator.sendBeacon = new Proxy(navigator.sendBeacon, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
argArray[0] = encodeUrl(argArray[0]); argArray[0] = encodeUrl(argArray[0])
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })

View file

@ -1,4 +1,4 @@
import { rewriteCss } from "./shared"; import { rewriteCss } from "./shared"
const cssProperties = [ const cssProperties = [
"background", "background",
@ -10,7 +10,7 @@ const cssProperties = [
"border-image", "border-image",
"border-image-source", "border-image-source",
"cursor", "cursor",
]; ]
// const jsProperties = ["background", "backgroundImage", "mask", "maskImage", "listStyle", "listStyleImage", "borderImage", "borderImageSource", "cursor"]; // const jsProperties = ["background", "backgroundImage", "mask", "maskImage", "listStyle", "listStyleImage", "borderImage", "borderImageSource", "cursor"];
CSSStyleDeclaration.prototype.setProperty = new Proxy( CSSStyleDeclaration.prototype.setProperty = new Proxy(
@ -18,9 +18,9 @@ CSSStyleDeclaration.prototype.setProperty = new Proxy(
{ {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
if (cssProperties.includes(argArray[0])) if (cssProperties.includes(argArray[0]))
argArray[1] = rewriteCss(argArray[1]); argArray[1] = rewriteCss(argArray[1])
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}, }
); )

View file

@ -1,11 +1,11 @@
import { decodeUrl } from "../shared/rewriters/url"; import { decodeUrl } from "../shared/rewriters/url"
import { import {
encodeUrl, encodeUrl,
rewriteCss, rewriteCss,
rewriteHtml, rewriteHtml,
rewriteJs, rewriteJs,
rewriteSrcset, rewriteSrcset,
} from "./shared"; } from "./shared"
const attrObject = { const attrObject = {
nonce: [HTMLElement], nonce: [HTMLElement],
@ -25,93 +25,93 @@ const attrObject = {
srcdoc: [HTMLIFrameElement], srcdoc: [HTMLIFrameElement],
srcset: [HTMLImageElement, HTMLSourceElement], srcset: [HTMLImageElement, HTMLSourceElement],
imagesrcset: [HTMLLinkElement], imagesrcset: [HTMLLinkElement],
}; }
const attrs = Object.keys(attrObject); const attrs = Object.keys(attrObject)
for (const attr of attrs) { for (const attr of attrs) {
for (const element of attrObject[attr]) { for (const element of attrObject[attr]) {
const descriptor = Object.getOwnPropertyDescriptor(element.prototype, attr); const descriptor = Object.getOwnPropertyDescriptor(element.prototype, attr)
Object.defineProperty(element.prototype, attr, { Object.defineProperty(element.prototype, attr, {
get() { get() {
if (/src|href|data|action|formaction/.test(attr)) { if (/src|href|data|action|formaction/.test(attr)) {
return decodeUrl(descriptor.get.call(this)); return decodeUrl(descriptor.get.call(this))
} }
if (this.__origattrs[attr]) { if (this.__origattrs[attr]) {
return this.__origattrs[attr]; return this.__origattrs[attr]
} }
return descriptor.get.call(this); return descriptor.get.call(this)
}, },
set(value) { set(value) {
this.__origattrs[attr] = value; this.__origattrs[attr] = value
if (/nonce|integrity|csp/.test(attr)) { if (/nonce|integrity|csp/.test(attr)) {
return; return
} else if (/src|href|data|action|formaction/.test(attr)) { } else if (/src|href|data|action|formaction/.test(attr)) {
// @ts-expect-error // @ts-expect-error
if (value instanceof TrustedScriptURL) { if (value instanceof TrustedScriptURL) {
return; return
} }
value = encodeUrl(value); value = encodeUrl(value)
} else if (attr === "srcdoc") { } else if (attr === "srcdoc") {
value = rewriteHtml(value); value = rewriteHtml(value)
} else if (/(image)?srcset/.test(attr)) { } else if (/(image)?srcset/.test(attr)) {
value = rewriteSrcset(value); value = rewriteSrcset(value)
} }
descriptor.set.call(this, value); descriptor.set.call(this, value)
}, },
}); })
} }
} }
declare global { declare global {
interface Element { interface Element {
__origattrs: Record<string, string>; __origattrs: Record<string, string>
} }
} }
Element.prototype.__origattrs = {}; Element.prototype.__origattrs = {}
Element.prototype.getAttribute = new Proxy(Element.prototype.getAttribute, { Element.prototype.getAttribute = new Proxy(Element.prototype.getAttribute, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
if (attrs.includes(argArray[0]) && thisArg.__origattrs[argArray[0]]) { if (attrs.includes(argArray[0]) && thisArg.__origattrs[argArray[0]]) {
return thisArg.__origattrs[argArray[0]]; return thisArg.__origattrs[argArray[0]]
} }
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })
Element.prototype.setAttribute = new Proxy(Element.prototype.setAttribute, { Element.prototype.setAttribute = new Proxy(Element.prototype.setAttribute, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
if (attrs.includes(argArray[0])) { if (attrs.includes(argArray[0])) {
thisArg.__origattrs[argArray[0]] = argArray[1]; thisArg.__origattrs[argArray[0]] = argArray[1]
if (/nonce|integrity|csp/.test(argArray[0])) { if (/nonce|integrity|csp/.test(argArray[0])) {
return; return
} else if (/src|href|data|action|formaction/.test(argArray[0])) { } else if (/src|href|data|action|formaction/.test(argArray[0])) {
argArray[1] = encodeUrl(argArray[1]); argArray[1] = encodeUrl(argArray[1])
} else if (argArray[0] === "srcdoc") { } else if (argArray[0] === "srcdoc") {
argArray[1] = rewriteHtml(argArray[1]); argArray[1] = rewriteHtml(argArray[1])
} else if (/(image)?srcset/.test(argArray[0])) { } else if (/(image)?srcset/.test(argArray[0])) {
argArray[1] = rewriteSrcset(argArray[1]); argArray[1] = rewriteSrcset(argArray[1])
} else if (argArray[1] === "style") { } else if (argArray[1] === "style") {
argArray[1] = rewriteCss(argArray[1]); argArray[1] = rewriteCss(argArray[1])
} }
} }
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })
const innerHTML = Object.getOwnPropertyDescriptor( const innerHTML = Object.getOwnPropertyDescriptor(
Element.prototype, Element.prototype,
"innerHTML", "innerHTML"
); )
Object.defineProperty(Element.prototype, "innerHTML", { Object.defineProperty(Element.prototype, "innerHTML", {
set(value) { set(value) {
@ -120,14 +120,14 @@ Object.defineProperty(Element.prototype, "innerHTML", {
this instanceof HTMLScriptElement && this instanceof HTMLScriptElement &&
!(value instanceof TrustedScript) !(value instanceof TrustedScript)
) { ) {
value = rewriteJs(value); value = rewriteJs(value)
} else if (this instanceof HTMLStyleElement) { } else if (this instanceof HTMLStyleElement) {
value = rewriteCss(value); value = rewriteCss(value)
// @ts-expect-error // @ts-expect-error
} else if (!(value instanceof TrustedHTML)) { } else if (!(value instanceof TrustedHTML)) {
value = rewriteHtml(value); value = rewriteHtml(value)
} }
return innerHTML.set.call(this, value); return innerHTML.set.call(this, value)
}, },
}); })

View file

@ -1,17 +1,17 @@
import { decodeUrl } from "./shared"; import { decodeUrl } from "./shared"
window.history.pushState = new Proxy(window.history.pushState, { window.history.pushState = new Proxy(window.history.pushState, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
argArray[3] = decodeUrl(argArray[3]); argArray[3] = decodeUrl(argArray[3])
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })
window.history.replaceState = new Proxy(window.history.replaceState, { window.history.replaceState = new Proxy(window.history.replaceState, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
argArray[3] = decodeUrl(argArray[3]); argArray[3] = decodeUrl(argArray[3])
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })

View file

@ -1,21 +1,21 @@
import "./scope.ts"; import "./scope.ts"
import "./window.ts"; import "./window.ts"
import "./event.ts"; import "./event.ts"
import "./native/eval.ts"; import "./native/eval.ts"
import "./location.ts"; import "./location.ts"
import "./trustedTypes.ts"; import "./trustedTypes.ts"
import "./requests/fetch.ts"; import "./requests/fetch.ts"
import "./requests/xmlhttprequest.ts"; import "./requests/xmlhttprequest.ts"
import "./requests/websocket.ts"; import "./requests/websocket.ts"
import "./element.ts"; import "./element.ts"
import "./storage.ts"; import "./storage.ts"
import "./css.ts"; import "./css.ts"
import "./history.ts"; import "./history.ts"
import "./worker.ts"; import "./worker.ts"
import "./url.ts"; import "./url.ts"
declare global { declare global {
interface Window { interface Window {
$s: any; $s: any
} }
} }

View file

@ -1,32 +1,32 @@
// @ts-nocheck // @ts-nocheck
import { encodeUrl, decodeUrl } from "./shared"; import { encodeUrl, decodeUrl } from "./shared"
function createLocation() { function createLocation() {
const loc = new URL(decodeUrl(location.href)); const loc = new URL(decodeUrl(location.href))
loc.assign = (url: string) => location.assign(encodeUrl(url)); loc.assign = (url: string) => location.assign(encodeUrl(url))
loc.reload = () => location.reload(); loc.reload = () => location.reload()
loc.replace = (url: string) => location.replace(encodeUrl(url)); loc.replace = (url: string) => location.replace(encodeUrl(url))
loc.toString = () => loc.href; loc.toString = () => loc.href
return loc; return loc
} }
export const locationProxy = new Proxy(window.location, { export const locationProxy = new Proxy(window.location, {
get(target, prop) { get(target, prop) {
const loc = createLocation(); const loc = createLocation()
return loc[prop]; return loc[prop]
}, },
set(obj, prop, value) { set(obj, prop, value) {
const loc = createLocation(); const loc = createLocation()
if (prop === "href") { if (prop === "href") {
location.href = encodeUrl(value); location.href = encodeUrl(value)
} else { } else {
loc[prop] = value; loc[prop] = value
} }
return true; return true
}, },
}); })

View file

@ -1,34 +1,31 @@
import { rewriteJs } from "../shared"; import { rewriteJs } from "../shared"
const FunctionProxy = new Proxy(Function, { const FunctionProxy = new Proxy(Function, {
construct(target, argArray) { construct(target, argArray) {
if (argArray.length === 1) { if (argArray.length === 1) {
return Reflect.construct(target, rewriteJs(argArray[0])); return Reflect.construct(target, rewriteJs(argArray[0]))
} else { } else {
return Reflect.construct( return Reflect.construct(target, rewriteJs(argArray[argArray.length - 1]))
target,
rewriteJs(argArray[argArray.length - 1]),
);
} }
}, },
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
if (argArray.length === 1) { if (argArray.length === 1) {
return Reflect.apply(target, undefined, [rewriteJs(argArray[0])]); return Reflect.apply(target, undefined, [rewriteJs(argArray[0])])
} else { } else {
return Reflect.apply(target, undefined, [ return Reflect.apply(target, undefined, [
...argArray.map((x, index) => index === argArray.length - 1), ...argArray.map((x, index) => index === argArray.length - 1),
rewriteJs(argArray[argArray.length - 1]), rewriteJs(argArray[argArray.length - 1]),
]); ])
} }
}, },
}); })
delete window.Function; delete window.Function
window.Function = FunctionProxy; window.Function = FunctionProxy
window.eval = new Proxy(window.eval, { window.eval = new Proxy(window.eval, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
return Reflect.apply(target, thisArg, [rewriteJs(argArray[0])]); return Reflect.apply(target, thisArg, [rewriteJs(argArray[0])])
}, },
}); })

View file

@ -1,35 +1,35 @@
// ts throws an error if you dont do window.fetch // ts throws an error if you dont do window.fetch
import { encodeUrl, rewriteHeaders } from "../shared"; import { encodeUrl, rewriteHeaders } from "../shared"
window.fetch = new Proxy(window.fetch, { window.fetch = new Proxy(window.fetch, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
argArray[0] = encodeUrl(argArray[0]); argArray[0] = encodeUrl(argArray[0])
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })
Headers = new Proxy(Headers, { Headers = new Proxy(Headers, {
construct(target, argArray, newTarget) { construct(target, argArray, newTarget) {
argArray[0] = rewriteHeaders(argArray[0]); argArray[0] = rewriteHeaders(argArray[0])
return Reflect.construct(target, argArray, newTarget); return Reflect.construct(target, argArray, newTarget)
}, },
}); })
Request = new Proxy(Request, { Request = new Proxy(Request, {
construct(target, argArray, newTarget) { construct(target, argArray, newTarget) {
if (typeof argArray[0] === "string") argArray[0] = encodeUrl(argArray[0]); if (typeof argArray[0] === "string") argArray[0] = encodeUrl(argArray[0])
return Reflect.construct(target, argArray, newTarget); return Reflect.construct(target, argArray, newTarget)
}, },
}); })
Response.redirect = new Proxy(Response.redirect, { Response.redirect = new Proxy(Response.redirect, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
argArray[0] = encodeUrl(argArray[0]); argArray[0] = encodeUrl(argArray[0])
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })

View file

@ -1,5 +1,5 @@
import { BareClient } from "../shared"; import { BareClient } from "../shared"
const client = new BareClient(); const client = new BareClient()
WebSocket = new Proxy(WebSocket, { WebSocket = new Proxy(WebSocket, {
construct(target, args) { construct(target, args) {
@ -10,7 +10,7 @@ WebSocket = new Proxy(WebSocket, {
{ {
"User-Agent": navigator.userAgent, "User-Agent": navigator.userAgent,
}, },
ArrayBuffer.prototype, ArrayBuffer.prototype
); )
}, },
}); })

View file

@ -1,23 +1,23 @@
import { encodeUrl, rewriteHeaders } from "../shared"; import { encodeUrl, rewriteHeaders } from "../shared"
XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, { XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
if (argArray[1]) argArray[1] = encodeUrl(argArray[1]); if (argArray[1]) argArray[1] = encodeUrl(argArray[1])
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })
XMLHttpRequest.prototype.setRequestHeader = new Proxy( XMLHttpRequest.prototype.setRequestHeader = new Proxy(
XMLHttpRequest.prototype.setRequestHeader, XMLHttpRequest.prototype.setRequestHeader,
{ {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
let headerObject = Object.fromEntries([argArray]); let headerObject = Object.fromEntries([argArray])
headerObject = rewriteHeaders(headerObject); headerObject = rewriteHeaders(headerObject)
argArray = Object.entries(headerObject)[0]; argArray = Object.entries(headerObject)[0]
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}, }
); )

View file

@ -1,15 +1,15 @@
import { locationProxy } from "./location"; import { locationProxy } from "./location"
import { windowProxy } from "./window"; import { windowProxy } from "./window"
function scope(identifier: any) { function scope(identifier: any) {
if (identifier instanceof Window) { if (identifier instanceof Window) {
return windowProxy; return windowProxy
} else if (identifier instanceof Location) { } else if (identifier instanceof Location) {
return locationProxy; return locationProxy
} }
return identifier; return identifier
} }
// shorthand because this can get out of hand reall quickly // shorthand because this can get out of hand reall quickly
window.$s = scope; window.$s = scope

View file

@ -9,4 +9,4 @@ export const {
rewriteHeaders, rewriteHeaders,
rewriteWorkers, rewriteWorkers,
}, },
} = self.$scramjet.shared; } = self.$scramjet.shared

View file

@ -1,12 +1,12 @@
import IDBMapSync from "@webreflection/idb-map/sync"; import IDBMapSync from "@webreflection/idb-map/sync"
import { locationProxy } from "./location"; import { locationProxy } from "./location"
const store = new IDBMapSync(locationProxy.host, { const store = new IDBMapSync(locationProxy.host, {
prefix: "Storage", prefix: "Storage",
durability: "relaxed", durability: "relaxed",
}); })
await store.sync(); await store.sync()
function storageProxy(scope: Storage): Storage { function storageProxy(scope: Storage): Storage {
return new Proxy(scope, { return new Proxy(scope, {
@ -14,57 +14,57 @@ function storageProxy(scope: Storage): Storage {
switch (prop) { switch (prop) {
case "getItem": case "getItem":
return (key: string) => { return (key: string) => {
return store.get(key); return store.get(key)
}; }
case "setItem": case "setItem":
return (key: string, value: string) => { return (key: string, value: string) => {
store.set(key, value); store.set(key, value)
store.sync(); store.sync()
}; }
case "removeItem": case "removeItem":
return (key: string) => { return (key: string) => {
store.delete(key); store.delete(key)
store.sync(); store.sync()
}; }
case "clear": case "clear":
return () => { return () => {
store.clear(); store.clear()
store.sync(); store.sync()
}; }
case "key": case "key":
return (index: number) => { return (index: number) => {
store.keys()[index]; store.keys()[index]
}; }
case "length": case "length":
return store.size; return store.size
default: default:
return store.get(prop); return store.get(prop)
} }
}, },
//@ts-ignore //@ts-ignore
set(target, prop, value) { set(target, prop, value) {
store.set(prop, value); store.set(prop, value)
store.sync(); store.sync()
}, },
defineProperty(target, property, attributes) { defineProperty(target, property, attributes) {
store.set(property as string, attributes.value); store.set(property as string, attributes.value)
return true; return true
}, },
}); })
} }
const localStorageProxy = storageProxy(window.localStorage); const localStorageProxy = storageProxy(window.localStorage)
const sessionStorageProxy = storageProxy(window.sessionStorage); const sessionStorageProxy = storageProxy(window.sessionStorage)
delete window.localStorage; delete window.localStorage
delete window.sessionStorage; delete window.sessionStorage
window.localStorage = localStorageProxy; window.localStorage = localStorageProxy
window.sessionStorage = sessionStorageProxy; window.sessionStorage = sessionStorageProxy

View file

@ -1,4 +1,4 @@
import { rewriteHtml, rewriteJs, encodeUrl } from "./shared"; import { rewriteHtml, rewriteJs, encodeUrl } from "./shared"
// @ts-expect-error // @ts-expect-error
trustedTypes.createPolicy = new Proxy(trustedTypes.createPolicy, { trustedTypes.createPolicy = new Proxy(trustedTypes.createPolicy, {
@ -6,27 +6,27 @@ trustedTypes.createPolicy = new Proxy(trustedTypes.createPolicy, {
if (argArray[1].createHTML) { if (argArray[1].createHTML) {
argArray[1].createHTML = new Proxy(argArray[1].createHTML, { argArray[1].createHTML = new Proxy(argArray[1].createHTML, {
apply(target1, thisArg1, argArray1) { apply(target1, thisArg1, argArray1) {
return rewriteHtml(target1(...argArray1)); return rewriteHtml(target1(...argArray1))
}, },
}); })
} }
if (argArray[1].createScript) { if (argArray[1].createScript) {
argArray[1].createScript = new Proxy(argArray[1].createScript, { argArray[1].createScript = new Proxy(argArray[1].createScript, {
apply(target1, thisArg1, argArray1) { apply(target1, thisArg1, argArray1) {
return rewriteJs(target1(...argArray1)); return rewriteJs(target1(...argArray1))
}, },
}); })
} }
if (argArray[1].createScriptURL) { if (argArray[1].createScriptURL) {
argArray[1].createScriptURL = new Proxy(argArray[1].createScriptURL, { argArray[1].createScriptURL = new Proxy(argArray[1].createScriptURL, {
apply(target1, thisArg1, argArray1) { apply(target1, thisArg1, argArray1) {
return encodeUrl(target1(...argArray1)); return encodeUrl(target1(...argArray1))
}, },
}); })
} }
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })

View file

@ -1,13 +1,13 @@
import { encodeUrl } from "../shared/rewriters/url"; import { encodeUrl } from "../shared/rewriters/url"
export const URL = globalThis.URL; export const URL = globalThis.URL
if (globalThis.window) { if (globalThis.window) {
window.URL = new Proxy(URL, { window.URL = new Proxy(URL, {
construct(target, argArray, newTarget) { construct(target, argArray, newTarget) {
if (typeof argArray[0] === "string") argArray[0] = encodeUrl(argArray[0]); if (typeof argArray[0] === "string") argArray[0] = encodeUrl(argArray[0])
if (typeof argArray[1] === "string") argArray[1] = encodeUrl(argArray[1]); if (typeof argArray[1] === "string") argArray[1] = encodeUrl(argArray[1])
return Reflect.construct(target, argArray, newTarget); return Reflect.construct(target, argArray, newTarget)
}, },
}); })
} }

View file

@ -1,34 +1,34 @@
import { locationProxy } from "./location"; import { locationProxy } from "./location"
export const windowProxy = new Proxy(window, { export const windowProxy = new Proxy(window, {
get(target, prop) { get(target, prop) {
const propIsString = typeof prop === "string"; const propIsString = typeof prop === "string"
if (propIsString && prop === "location") { if (propIsString && prop === "location") {
return locationProxy; return locationProxy
} else if ( } else if (
propIsString && propIsString &&
["window", "top", "parent", "self", "globalThis"].includes(prop) ["window", "top", "parent", "self", "globalThis"].includes(prop)
) { ) {
return windowProxy; return windowProxy
} else if (propIsString && prop === "$scramjet") { } else if (propIsString && prop === "$scramjet") {
return; return
} else if (propIsString && prop === "addEventListener") { } else if (propIsString && prop === "addEventListener") {
console.log("addEventListener getteetetetetet"); console.log("addEventListener getteetetetetet")
return new Proxy(window.addEventListener, { return new Proxy(window.addEventListener, {
apply(target1, thisArg, argArray) { apply(target1, thisArg, argArray) {
window.addEventListener(argArray[0], argArray[1]); window.addEventListener(argArray[0], argArray[1])
}, },
}); })
} }
const value = Reflect.get(target, prop); const value = Reflect.get(target, prop)
if (typeof value === "function") { if (typeof value === "function") {
return value.bind(target); return value.bind(target)
} }
return value; return value
}, },
set(target, prop, newValue) { set(target, prop, newValue) {
@ -36,12 +36,12 @@ export const windowProxy = new Proxy(window, {
if ( if (
typeof prop === "string" && typeof prop === "string" &&
["window", "top", "parent", "self", "globalThis", "location"].includes( ["window", "top", "parent", "self", "globalThis", "location"].includes(
prop, prop
) )
) { ) {
return false; return false
} }
return Reflect.set(target, prop, newValue); return Reflect.set(target, prop, newValue)
}, },
}); })

View file

@ -1,24 +1,24 @@
import { encodeUrl } from "./shared"; import { encodeUrl } from "./shared"
Worker = new Proxy(Worker, { Worker = new Proxy(Worker, {
construct(target, argArray) { construct(target, argArray) {
argArray[0] = encodeUrl(argArray[0]); argArray[0] = encodeUrl(argArray[0])
// target is a reference to the object that you are proxying // target is a reference to the object that you are proxying
// Reflect.construct is just a wrapper for calling target // Reflect.construct is just a wrapper for calling target
// you could do new target(...argArray) and it would work the same effectively // you could do new target(...argArray) and it would work the same effectively
return Reflect.construct(target, argArray); return Reflect.construct(target, argArray)
}, },
}); })
Worklet.prototype.addModule = new Proxy(Worklet.prototype.addModule, { Worklet.prototype.addModule = new Proxy(Worklet.prototype.addModule, {
apply(target, thisArg, argArray) { apply(target, thisArg, argArray) {
argArray[0] = encodeUrl(argArray[0]); argArray[0] = encodeUrl(argArray[0])
return Reflect.apply(target, thisArg, argArray); return Reflect.apply(target, thisArg, argArray)
}, },
}); })
// broken // broken

View file

@ -1,28 +1,28 @@
/* eslint-disable */ /* eslint-disable */
var Nr = 14; var Nr = 14
var Nk = 8; var Nk = 8
var Decrypt = false; var Decrypt = false
function enc_utf8(s) { function enc_utf8(s) {
try { try {
return unescape(encodeURIComponent(s)); return unescape(encodeURIComponent(s))
} catch (e) { } catch (e) {
throw "Error on UTF-8 encode"; throw "Error on UTF-8 encode"
} }
} }
function dec_utf8(s) { function dec_utf8(s) {
try { try {
return decodeURIComponent(escape(s)); return decodeURIComponent(escape(s))
} catch (e) { } catch (e) {
throw "Bad Key"; throw "Bad Key"
} }
} }
function padBlock(byteArr) { function padBlock(byteArr) {
var array = [], var array = [],
cpad, cpad,
i; i
if (byteArr.length < 16) { if (byteArr.length < 16) {
cpad = 16 - byteArr.length; cpad = 16 - byteArr.length
array = [ array = [
cpad, cpad,
cpad, cpad,
@ -40,89 +40,89 @@ function padBlock(byteArr) {
cpad, cpad,
cpad, cpad,
cpad, cpad,
]; ]
} }
for (i = 0; i < byteArr.length; i++) { for (i = 0; i < byteArr.length; i++) {
array[i] = byteArr[i]; array[i] = byteArr[i]
} }
return array; return array
} }
function block2s(block, lastBlock) { function block2s(block, lastBlock) {
var string = "", var string = "",
padding, padding,
i; i
if (lastBlock) { if (lastBlock) {
padding = block[15]; padding = block[15]
if (padding > 16) { if (padding > 16) {
throw "Decryption error: Maybe bad key"; throw "Decryption error: Maybe bad key"
} }
if (padding === 16) { if (padding === 16) {
return ""; return ""
} }
for (i = 0; i < 16 - padding; i++) { for (i = 0; i < 16 - padding; i++) {
string += String.fromCharCode(block[i]); string += String.fromCharCode(block[i])
} }
} else { } else {
for (i = 0; i < 16; i++) { for (i = 0; i < 16; i++) {
string += String.fromCharCode(block[i]); string += String.fromCharCode(block[i])
} }
} }
return string; return string
} }
function a2h(numArr) { function a2h(numArr) {
var string = "", var string = "",
i; i
for (i = 0; i < numArr.length; i++) { for (i = 0; i < numArr.length; i++) {
string += (numArr[i] < 16 ? "0" : "") + numArr[i].toString(16); string += (numArr[i] < 16 ? "0" : "") + numArr[i].toString(16)
} }
return string; return string
} }
function h2a(s) { function h2a(s) {
var ret = []; var ret = []
s.replace(/(..)/g, function (s) { s.replace(/(..)/g, function (s) {
ret.push(parseInt(s, 16)); ret.push(parseInt(s, 16))
}); })
return ret; return ret
} }
function s2a(string, binary) { function s2a(string, binary) {
var array = [], var array = [],
i; i
if (!binary) { if (!binary) {
string = enc_utf8(string); string = enc_utf8(string)
} }
for (i = 0; i < string.length; i++) { for (i = 0; i < string.length; i++) {
array[i] = string.charCodeAt(i); array[i] = string.charCodeAt(i)
} }
return array; return array
} }
function size(newsize) { function size(newsize) {
switch (newsize) { switch (newsize) {
case 128: case 128:
Nr = 10; Nr = 10
Nk = 4; Nk = 4
break; break
case 192: case 192:
Nr = 12; Nr = 12
Nk = 6; Nk = 6
break; break
case 256: case 256:
Nr = 14; Nr = 14
Nk = 8; Nk = 8
break; break
default: default:
throw "Invalid Key Size Specified:" + newsize; throw "Invalid Key Size Specified:" + newsize
} }
} }
function randArr(num) { function randArr(num) {
var result = [], var result = [],
i; i
for (i = 0; i < num; i++) { for (i = 0; i < num; i++) {
result = result.concat(Math.floor(Math.random() * 256)); result = result.concat(Math.floor(Math.random() * 256))
} }
return result; return result
} }
function openSSLKey(passwordArr, saltArr) { function openSSLKey(passwordArr, saltArr) {
var rounds = Nr >= 12 ? 3 : 2, var rounds = Nr >= 12 ? 3 : 2,
@ -131,142 +131,142 @@ function openSSLKey(passwordArr, saltArr) {
md5_hash = [], md5_hash = [],
result = [], result = [],
data00 = passwordArr.concat(saltArr), data00 = passwordArr.concat(saltArr),
i; i
md5_hash[0] = MD5(data00); md5_hash[0] = MD5(data00)
result = md5_hash[0]; result = md5_hash[0]
for (i = 1; i < rounds; i++) { for (i = 1; i < rounds; i++) {
md5_hash[i] = MD5(md5_hash[i - 1].concat(data00)); md5_hash[i] = MD5(md5_hash[i - 1].concat(data00))
result = result.concat(md5_hash[i]); result = result.concat(md5_hash[i])
} }
key = result.slice(0, 4 * Nk); key = result.slice(0, 4 * Nk)
iv = result.slice(4 * Nk, 4 * Nk + 16); iv = result.slice(4 * Nk, 4 * Nk + 16)
return { return {
key: key, key: key,
iv: iv, iv: iv,
}; }
} }
function rawEncrypt(plaintext, key, iv) { function rawEncrypt(plaintext, key, iv) {
key = expandKey(key); key = expandKey(key)
var numBlocks = Math.ceil(plaintext.length / 16), var numBlocks = Math.ceil(plaintext.length / 16),
blocks = [], blocks = [],
i, i,
cipherBlocks = []; cipherBlocks = []
for (i = 0; i < numBlocks; i++) { for (i = 0; i < numBlocks; i++) {
blocks[i] = padBlock(plaintext.slice(i * 16, i * 16 + 16)); blocks[i] = padBlock(plaintext.slice(i * 16, i * 16 + 16))
} }
if (plaintext.length % 16 === 0) { if (plaintext.length % 16 === 0) {
blocks.push([ blocks.push([
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
]); ])
numBlocks++; numBlocks++
} }
for (i = 0; i < blocks.length; i++) { for (i = 0; i < blocks.length; i++) {
blocks[i] = blocks[i] =
i === 0 i === 0
? xorBlocks(blocks[i], iv) ? xorBlocks(blocks[i], iv)
: xorBlocks(blocks[i], cipherBlocks[i - 1]); : xorBlocks(blocks[i], cipherBlocks[i - 1])
cipherBlocks[i] = encryptBlock(blocks[i], key); cipherBlocks[i] = encryptBlock(blocks[i], key)
} }
return cipherBlocks; return cipherBlocks
} }
function rawDecrypt(cryptArr, key, iv, binary) { function rawDecrypt(cryptArr, key, iv, binary) {
key = expandKey(key); key = expandKey(key)
var numBlocks = cryptArr.length / 16, var numBlocks = cryptArr.length / 16,
cipherBlocks = [], cipherBlocks = [],
i, i,
plainBlocks = [], plainBlocks = [],
string = ""; string = ""
for (i = 0; i < numBlocks; i++) { for (i = 0; i < numBlocks; i++) {
cipherBlocks.push(cryptArr.slice(i * 16, (i + 1) * 16)); cipherBlocks.push(cryptArr.slice(i * 16, (i + 1) * 16))
} }
for (i = cipherBlocks.length - 1; i >= 0; i--) { for (i = cipherBlocks.length - 1; i >= 0; i--) {
plainBlocks[i] = decryptBlock(cipherBlocks[i], key); plainBlocks[i] = decryptBlock(cipherBlocks[i], key)
plainBlocks[i] = plainBlocks[i] =
i === 0 i === 0
? xorBlocks(plainBlocks[i], iv) ? xorBlocks(plainBlocks[i], iv)
: xorBlocks(plainBlocks[i], cipherBlocks[i - 1]); : xorBlocks(plainBlocks[i], cipherBlocks[i - 1])
} }
for (i = 0; i < numBlocks - 1; i++) { for (i = 0; i < numBlocks - 1; i++) {
string += block2s(plainBlocks[i], false); string += block2s(plainBlocks[i], false)
} }
string += block2s(plainBlocks[i], true); string += block2s(plainBlocks[i], true)
return binary ? string : dec_utf8(string); return binary ? string : dec_utf8(string)
} }
function encryptBlock(block, words) { function encryptBlock(block, words) {
Decrypt = false; Decrypt = false
var state = addRoundKey(block, words, 0), var state = addRoundKey(block, words, 0),
round; round
for (round = 1; round < Nr + 1; round++) { for (round = 1; round < Nr + 1; round++) {
state = subBytes(state); state = subBytes(state)
state = shiftRows(state); state = shiftRows(state)
if (round < Nr) { if (round < Nr) {
state = mixColumns(state); state = mixColumns(state)
} }
state = addRoundKey(state, words, round); state = addRoundKey(state, words, round)
} }
return state; return state
} }
function decryptBlock(block, words) { function decryptBlock(block, words) {
Decrypt = true; Decrypt = true
var state = addRoundKey(block, words, Nr), var state = addRoundKey(block, words, Nr),
round; round
for (round = Nr - 1; round > -1; round--) { for (round = Nr - 1; round > -1; round--) {
state = shiftRows(state); state = shiftRows(state)
state = subBytes(state); state = subBytes(state)
state = addRoundKey(state, words, round); state = addRoundKey(state, words, round)
if (round > 0) { if (round > 0) {
state = mixColumns(state); state = mixColumns(state)
} }
} }
return state; return state
} }
function subBytes(state) { function subBytes(state) {
var S = Decrypt ? SBoxInv : SBox, var S = Decrypt ? SBoxInv : SBox,
temp = [], temp = [],
i; i
for (i = 0; i < 16; i++) { for (i = 0; i < 16; i++) {
temp[i] = S[state[i]]; temp[i] = S[state[i]]
} }
return temp; return temp
} }
function shiftRows(state) { function shiftRows(state) {
var temp = [], var temp = [],
shiftBy = Decrypt shiftBy = Decrypt
? [0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3] ? [0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3]
: [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11], : [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11],
i; i
for (i = 0; i < 16; i++) { for (i = 0; i < 16; i++) {
temp[i] = state[shiftBy[i]]; temp[i] = state[shiftBy[i]]
} }
return temp; return temp
} }
function mixColumns(state) { function mixColumns(state) {
var t = [], var t = [],
c; c
if (!Decrypt) { if (!Decrypt) {
for (c = 0; c < 4; c++) { for (c = 0; c < 4; c++) {
t[c * 4] = t[c * 4] =
G2X[state[c * 4]] ^ G2X[state[c * 4]] ^
G3X[state[1 + c * 4]] ^ G3X[state[1 + c * 4]] ^
state[2 + c * 4] ^ state[2 + c * 4] ^
state[3 + c * 4]; state[3 + c * 4]
t[1 + c * 4] = t[1 + c * 4] =
state[c * 4] ^ state[c * 4] ^
G2X[state[1 + c * 4]] ^ G2X[state[1 + c * 4]] ^
G3X[state[2 + c * 4]] ^ G3X[state[2 + c * 4]] ^
state[3 + c * 4]; state[3 + c * 4]
t[2 + c * 4] = t[2 + c * 4] =
state[c * 4] ^ state[c * 4] ^
state[1 + c * 4] ^ state[1 + c * 4] ^
G2X[state[2 + c * 4]] ^ G2X[state[2 + c * 4]] ^
G3X[state[3 + c * 4]]; G3X[state[3 + c * 4]]
t[3 + c * 4] = t[3 + c * 4] =
G3X[state[c * 4]] ^ G3X[state[c * 4]] ^
state[1 + c * 4] ^ state[1 + c * 4] ^
state[2 + c * 4] ^ state[2 + c * 4] ^
G2X[state[3 + c * 4]]; G2X[state[3 + c * 4]]
} }
} else { } else {
for (c = 0; c < 4; c++) { for (c = 0; c < 4; c++) {
@ -274,42 +274,42 @@ function mixColumns(state) {
GEX[state[c * 4]] ^ GEX[state[c * 4]] ^
GBX[state[1 + c * 4]] ^ GBX[state[1 + c * 4]] ^
GDX[state[2 + c * 4]] ^ GDX[state[2 + c * 4]] ^
G9X[state[3 + c * 4]]; G9X[state[3 + c * 4]]
t[1 + c * 4] = t[1 + c * 4] =
G9X[state[c * 4]] ^ G9X[state[c * 4]] ^
GEX[state[1 + c * 4]] ^ GEX[state[1 + c * 4]] ^
GBX[state[2 + c * 4]] ^ GBX[state[2 + c * 4]] ^
GDX[state[3 + c * 4]]; GDX[state[3 + c * 4]]
t[2 + c * 4] = t[2 + c * 4] =
GDX[state[c * 4]] ^ GDX[state[c * 4]] ^
G9X[state[1 + c * 4]] ^ G9X[state[1 + c * 4]] ^
GEX[state[2 + c * 4]] ^ GEX[state[2 + c * 4]] ^
GBX[state[3 + c * 4]]; GBX[state[3 + c * 4]]
t[3 + c * 4] = t[3 + c * 4] =
GBX[state[c * 4]] ^ GBX[state[c * 4]] ^
GDX[state[1 + c * 4]] ^ GDX[state[1 + c * 4]] ^
G9X[state[2 + c * 4]] ^ G9X[state[2 + c * 4]] ^
GEX[state[3 + c * 4]]; GEX[state[3 + c * 4]]
} }
} }
return t; return t
} }
function addRoundKey(state, words, round) { function addRoundKey(state, words, round) {
var temp = [], var temp = [],
i; i
for (i = 0; i < 16; i++) { for (i = 0; i < 16; i++) {
temp[i] = state[i] ^ words[round][i]; temp[i] = state[i] ^ words[round][i]
} }
return temp; return temp
} }
function xorBlocks(block1, block2) { function xorBlocks(block1, block2) {
var temp = [], var temp = [],
i; i
for (i = 0; i < 16; i++) { for (i = 0; i < 16; i++) {
temp[i] = block1[i] ^ block2[i]; temp[i] = block1[i] ^ block2[i]
} }
return temp; return temp
} }
function expandKey(key) { function expandKey(key) {
var w = [], var w = [],
@ -318,188 +318,188 @@ function expandKey(key) {
r, r,
t, t,
flat = [], flat = [],
j; j
for (i = 0; i < Nk; i++) { for (i = 0; i < Nk; i++) {
r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]; r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]
w[i] = r; w[i] = r
} }
for (i = Nk; i < 4 * (Nr + 1); i++) { for (i = Nk; i < 4 * (Nr + 1); i++) {
w[i] = []; w[i] = []
for (t = 0; t < 4; t++) { for (t = 0; t < 4; t++) {
temp[t] = w[i - 1][t]; temp[t] = w[i - 1][t]
} }
if (i % Nk === 0) { if (i % Nk === 0) {
temp = subWord(rotWord(temp)); temp = subWord(rotWord(temp))
temp[0] ^= Rcon[i / Nk - 1]; temp[0] ^= Rcon[i / Nk - 1]
} else if (Nk > 6 && i % Nk === 4) { } else if (Nk > 6 && i % Nk === 4) {
temp = subWord(temp); temp = subWord(temp)
} }
for (t = 0; t < 4; t++) { for (t = 0; t < 4; t++) {
w[i][t] = w[i - Nk][t] ^ temp[t]; w[i][t] = w[i - Nk][t] ^ temp[t]
} }
} }
for (i = 0; i < Nr + 1; i++) { for (i = 0; i < Nr + 1; i++) {
flat[i] = []; flat[i] = []
for (j = 0; j < 4; j++) { for (j = 0; j < 4; j++) {
flat[i].push( flat[i].push(
w[i * 4 + j][0], w[i * 4 + j][0],
w[i * 4 + j][1], w[i * 4 + j][1],
w[i * 4 + j][2], w[i * 4 + j][2],
w[i * 4 + j][3], w[i * 4 + j][3]
); )
} }
} }
return flat; return flat
} }
function subWord(w) { function subWord(w) {
for (var i = 0; i < 4; i++) { for (var i = 0; i < 4; i++) {
w[i] = SBox[w[i]]; w[i] = SBox[w[i]]
} }
return w; return w
} }
function rotWord(w) { function rotWord(w) {
var tmp = w[0], var tmp = w[0],
i; i
for (i = 0; i < 3; i++) { for (i = 0; i < 3; i++) {
w[i] = w[i + 1]; w[i] = w[i + 1]
} }
w[3] = tmp; w[3] = tmp
return w; return w
} }
function strhex(str, size) { function strhex(str, size) {
var i, var i,
ret = []; ret = []
for (i = 0; i < str.length; i += size) { for (i = 0; i < str.length; i += size) {
ret[i / size] = parseInt(str.substr(i, size), 16); ret[i / size] = parseInt(str.substr(i, size), 16)
} }
return ret; return ret
} }
function invertArr(arr) { function invertArr(arr) {
var i, var i,
ret = []; ret = []
for (i = 0; i < arr.length; i++) { for (i = 0; i < arr.length; i++) {
ret[arr[i]] = i; ret[arr[i]] = i
} }
return ret; return ret
} }
function Gxx(a, b) { function Gxx(a, b) {
var i, ret; var i, ret
ret = 0; ret = 0
for (i = 0; i < 8; i++) { for (i = 0; i < 8; i++) {
ret = (b & 1) === 1 ? ret ^ a : ret; ret = (b & 1) === 1 ? ret ^ a : ret
a = a > 0x7f ? 0x11b ^ (a << 1) : a << 1; a = a > 0x7f ? 0x11b ^ (a << 1) : a << 1
b >>>= 1; b >>>= 1
} }
return ret; return ret
} }
function Gx(x) { function Gx(x) {
var i, var i,
r = []; r = []
for (i = 0; i < 256; i++) { for (i = 0; i < 256; i++) {
r[i] = Gxx(x, i); r[i] = Gxx(x, i)
} }
return r; return r
} }
var SBox = strhex( var SBox = strhex(
"637c777bf26b6fc53001672bfed7ab76ca82c97dfa5947f0add4a2af9ca472c0b7fd9326363ff7cc34a5e5f171d8311504c723c31896059a071280e2eb27b27509832c1a1b6e5aa0523bd6b329e32f8453d100ed20fcb15b6acbbe394a4c58cfd0efaafb434d338545f9027f503c9fa851a3408f929d38f5bcb6da2110fff3d2cd0c13ec5f974417c4a77e3d645d197360814fdc222a908846eeb814de5e0bdbe0323a0a4906245cc2d3ac629195e479e7c8376d8dd54ea96c56f4ea657aae08ba78252e1ca6b4c6e8dd741f4bbd8b8a703eb5664803f60e613557b986c11d9ee1f8981169d98e949b1e87e9ce5528df8ca1890dbfe6426841992d0fb054bb16", "637c777bf26b6fc53001672bfed7ab76ca82c97dfa5947f0add4a2af9ca472c0b7fd9326363ff7cc34a5e5f171d8311504c723c31896059a071280e2eb27b27509832c1a1b6e5aa0523bd6b329e32f8453d100ed20fcb15b6acbbe394a4c58cfd0efaafb434d338545f9027f503c9fa851a3408f929d38f5bcb6da2110fff3d2cd0c13ec5f974417c4a77e3d645d197360814fdc222a908846eeb814de5e0bdbe0323a0a4906245cc2d3ac629195e479e7c8376d8dd54ea96c56f4ea657aae08ba78252e1ca6b4c6e8dd741f4bbd8b8a703eb5664803f60e613557b986c11d9ee1f8981169d98e949b1e87e9ce5528df8ca1890dbfe6426841992d0fb054bb16",
2, 2
); )
var SBoxInv = invertArr(SBox); var SBoxInv = invertArr(SBox)
var Rcon = strhex( var Rcon = strhex(
"01020408102040801b366cd8ab4d9a2f5ebc63c697356ad4b37dfaefc591", "01020408102040801b366cd8ab4d9a2f5ebc63c697356ad4b37dfaefc591",
2, 2
); )
var G2X = Gx(2); var G2X = Gx(2)
var G3X = Gx(3); var G3X = Gx(3)
var G9X = Gx(9); var G9X = Gx(9)
var GBX = Gx(0xb); var GBX = Gx(0xb)
var GDX = Gx(0xd); var GDX = Gx(0xd)
var GEX = Gx(0xe); var GEX = Gx(0xe)
function enc(string, pass, binary) { function enc(string, pass, binary) {
var salt = randArr(8), var salt = randArr(8),
pbe = openSSLKey(s2a(pass, binary), salt), pbe = openSSLKey(s2a(pass, binary), salt),
key = pbe.key, key = pbe.key,
iv = pbe.iv, iv = pbe.iv,
cipherBlocks, cipherBlocks,
saltBlock = [[83, 97, 108, 116, 101, 100, 95, 95].concat(salt)]; saltBlock = [[83, 97, 108, 116, 101, 100, 95, 95].concat(salt)]
string = s2a(string, binary); string = s2a(string, binary)
cipherBlocks = rawEncrypt(string, key, iv); cipherBlocks = rawEncrypt(string, key, iv)
cipherBlocks = saltBlock.concat(cipherBlocks); cipherBlocks = saltBlock.concat(cipherBlocks)
return Base64.encode(cipherBlocks); return Base64.encode(cipherBlocks)
} }
function dec(string, pass, binary) { function dec(string, pass, binary) {
var cryptArr = Base64.decode(string), var cryptArr = Base64.decode(string),
salt = cryptArr.slice(8, 16), salt = cryptArr.slice(8, 16),
pbe = openSSLKey(s2a(pass, binary), salt), pbe = openSSLKey(s2a(pass, binary), salt),
key = pbe.key, key = pbe.key,
iv = pbe.iv; iv = pbe.iv
cryptArr = cryptArr.slice(16, cryptArr.length); cryptArr = cryptArr.slice(16, cryptArr.length)
string = rawDecrypt(cryptArr, key, iv, binary); string = rawDecrypt(cryptArr, key, iv, binary)
return string; return string
} }
function MD5(numArr) { function MD5(numArr) {
function rotateLeft(lValue, iShiftBits) { function rotateLeft(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits))
} }
function addUnsigned(lX, lY) { function addUnsigned(lX, lY) {
var lX4, lY4, lX8, lY8, lResult; var lX4, lY4, lX8, lY8, lResult
lX8 = lX & 0x80000000; lX8 = lX & 0x80000000
lY8 = lY & 0x80000000; lY8 = lY & 0x80000000
lX4 = lX & 0x40000000; lX4 = lX & 0x40000000
lY4 = lY & 0x40000000; lY4 = lY & 0x40000000
lResult = (lX & 0x3fffffff) + (lY & 0x3fffffff); lResult = (lX & 0x3fffffff) + (lY & 0x3fffffff)
if (lX4 & lY4) { if (lX4 & lY4) {
return lResult ^ 0x80000000 ^ lX8 ^ lY8; return lResult ^ 0x80000000 ^ lX8 ^ lY8
} }
if (lX4 | lY4) { if (lX4 | lY4) {
if (lResult & 0x40000000) { if (lResult & 0x40000000) {
return lResult ^ 0xc0000000 ^ lX8 ^ lY8; return lResult ^ 0xc0000000 ^ lX8 ^ lY8
} else { } else {
return lResult ^ 0x40000000 ^ lX8 ^ lY8; return lResult ^ 0x40000000 ^ lX8 ^ lY8
} }
} else { } else {
return lResult ^ lX8 ^ lY8; return lResult ^ lX8 ^ lY8
} }
} }
function f(x, y, z) { function f(x, y, z) {
return (x & y) | (~x & z); return (x & y) | (~x & z)
} }
function g(x, y, z) { function g(x, y, z) {
return (x & z) | (y & ~z); return (x & z) | (y & ~z)
} }
function h(x, y, z) { function h(x, y, z) {
return x ^ y ^ z; return x ^ y ^ z
} }
function funcI(x, y, z) { function funcI(x, y, z) {
return y ^ (x | ~z); return y ^ (x | ~z)
} }
function ff(a, b, c, d, x, s, ac) { function ff(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac)); a = addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac))
return addUnsigned(rotateLeft(a, s), b); return addUnsigned(rotateLeft(a, s), b)
} }
function gg(a, b, c, d, x, s, ac) { function gg(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac)); a = addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac))
return addUnsigned(rotateLeft(a, s), b); return addUnsigned(rotateLeft(a, s), b)
} }
function hh(a, b, c, d, x, s, ac) { function hh(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac)); a = addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac))
return addUnsigned(rotateLeft(a, s), b); return addUnsigned(rotateLeft(a, s), b)
} }
function ii(a, b, c, d, x, s, ac) { function ii(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(funcI(b, c, d), x), ac)); a = addUnsigned(a, addUnsigned(addUnsigned(funcI(b, c, d), x), ac))
return addUnsigned(rotateLeft(a, s), b); return addUnsigned(rotateLeft(a, s), b)
} }
function convertToWordArray(numArr) { function convertToWordArray(numArr) {
@ -511,31 +511,31 @@ function MD5(numArr) {
lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16, lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16,
lWordArray = [], lWordArray = [],
lBytePosition = 0, lBytePosition = 0,
lByteCount = 0; lByteCount = 0
while (lByteCount < lMessageLength) { while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4; lWordCount = (lByteCount - (lByteCount % 4)) / 4
lBytePosition = (lByteCount % 4) * 8; lBytePosition = (lByteCount % 4) * 8
lWordArray[lWordCount] = lWordArray[lWordCount] =
lWordArray[lWordCount] | (numArr[lByteCount] << lBytePosition); lWordArray[lWordCount] | (numArr[lByteCount] << lBytePosition)
lByteCount++; lByteCount++
} }
lWordCount = (lByteCount - (lByteCount % 4)) / 4; lWordCount = (lByteCount - (lByteCount % 4)) / 4
lBytePosition = (lByteCount % 4) * 8; lBytePosition = (lByteCount % 4) * 8
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition)
lWordArray[lNumberOfWords - 2] = lMessageLength << 3; lWordArray[lNumberOfWords - 2] = lMessageLength << 3
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29
return lWordArray; return lWordArray
} }
function wordToHex(lValue) { function wordToHex(lValue) {
var lByte, var lByte,
lCount, lCount,
wordToHexArr = []; wordToHexArr = []
for (lCount = 0; lCount <= 3; lCount++) { for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255; lByte = (lValue >>> (lCount * 8)) & 255
wordToHexArr = wordToHexArr.concat(lByte); wordToHexArr = wordToHexArr.concat(lByte)
} }
return wordToHexArr; return wordToHexArr
} }
var x = [], var x = [],
@ -550,92 +550,92 @@ function MD5(numArr) {
d, d,
rnd = strhex( rnd = strhex(
"67452301efcdab8998badcfe10325476d76aa478e8c7b756242070dbc1bdceeef57c0faf4787c62aa8304613fd469501698098d88b44f7afffff5bb1895cd7be6b901122fd987193a679438e49b40821f61e2562c040b340265e5a51e9b6c7aad62f105d02441453d8a1e681e7d3fbc821e1cde6c33707d6f4d50d87455a14eda9e3e905fcefa3f8676f02d98d2a4c8afffa39428771f6816d9d6122fde5380ca4beea444bdecfa9f6bb4b60bebfbc70289b7ec6eaa127fad4ef308504881d05d9d4d039e6db99e51fa27cf8c4ac5665f4292244432aff97ab9423a7fc93a039655b59c38f0ccc92ffeff47d85845dd16fa87e4ffe2ce6e0a30143144e0811a1f7537e82bd3af2352ad7d2bbeb86d391", "67452301efcdab8998badcfe10325476d76aa478e8c7b756242070dbc1bdceeef57c0faf4787c62aa8304613fd469501698098d88b44f7afffff5bb1895cd7be6b901122fd987193a679438e49b40821f61e2562c040b340265e5a51e9b6c7aad62f105d02441453d8a1e681e7d3fbc821e1cde6c33707d6f4d50d87455a14eda9e3e905fcefa3f8676f02d98d2a4c8afffa39428771f6816d9d6122fde5380ca4beea444bdecfa9f6bb4b60bebfbc70289b7ec6eaa127fad4ef308504881d05d9d4d039e6db99e51fa27cf8c4ac5665f4292244432aff97ab9423a7fc93a039655b59c38f0ccc92ffeff47d85845dd16fa87e4ffe2ce6e0a30143144e0811a1f7537e82bd3af2352ad7d2bbeb86d391",
8, 8
); )
x = convertToWordArray(numArr); x = convertToWordArray(numArr)
a = rnd[0]; a = rnd[0]
b = rnd[1]; b = rnd[1]
c = rnd[2]; c = rnd[2]
d = rnd[3]; d = rnd[3]
for (k = 0; k < x.length; k += 16) { for (k = 0; k < x.length; k += 16) {
AA = a; AA = a
BB = b; BB = b
CC = c; CC = c
DD = d; DD = d
a = ff(a, b, c, d, x[k + 0], 7, rnd[4]); a = ff(a, b, c, d, x[k + 0], 7, rnd[4])
d = ff(d, a, b, c, x[k + 1], 12, rnd[5]); d = ff(d, a, b, c, x[k + 1], 12, rnd[5])
c = ff(c, d, a, b, x[k + 2], 17, rnd[6]); c = ff(c, d, a, b, x[k + 2], 17, rnd[6])
b = ff(b, c, d, a, x[k + 3], 22, rnd[7]); b = ff(b, c, d, a, x[k + 3], 22, rnd[7])
a = ff(a, b, c, d, x[k + 4], 7, rnd[8]); a = ff(a, b, c, d, x[k + 4], 7, rnd[8])
d = ff(d, a, b, c, x[k + 5], 12, rnd[9]); d = ff(d, a, b, c, x[k + 5], 12, rnd[9])
c = ff(c, d, a, b, x[k + 6], 17, rnd[10]); c = ff(c, d, a, b, x[k + 6], 17, rnd[10])
b = ff(b, c, d, a, x[k + 7], 22, rnd[11]); b = ff(b, c, d, a, x[k + 7], 22, rnd[11])
a = ff(a, b, c, d, x[k + 8], 7, rnd[12]); a = ff(a, b, c, d, x[k + 8], 7, rnd[12])
d = ff(d, a, b, c, x[k + 9], 12, rnd[13]); d = ff(d, a, b, c, x[k + 9], 12, rnd[13])
c = ff(c, d, a, b, x[k + 10], 17, rnd[14]); c = ff(c, d, a, b, x[k + 10], 17, rnd[14])
b = ff(b, c, d, a, x[k + 11], 22, rnd[15]); b = ff(b, c, d, a, x[k + 11], 22, rnd[15])
a = ff(a, b, c, d, x[k + 12], 7, rnd[16]); a = ff(a, b, c, d, x[k + 12], 7, rnd[16])
d = ff(d, a, b, c, x[k + 13], 12, rnd[17]); d = ff(d, a, b, c, x[k + 13], 12, rnd[17])
c = ff(c, d, a, b, x[k + 14], 17, rnd[18]); c = ff(c, d, a, b, x[k + 14], 17, rnd[18])
b = ff(b, c, d, a, x[k + 15], 22, rnd[19]); b = ff(b, c, d, a, x[k + 15], 22, rnd[19])
a = gg(a, b, c, d, x[k + 1], 5, rnd[20]); a = gg(a, b, c, d, x[k + 1], 5, rnd[20])
d = gg(d, a, b, c, x[k + 6], 9, rnd[21]); d = gg(d, a, b, c, x[k + 6], 9, rnd[21])
c = gg(c, d, a, b, x[k + 11], 14, rnd[22]); c = gg(c, d, a, b, x[k + 11], 14, rnd[22])
b = gg(b, c, d, a, x[k + 0], 20, rnd[23]); b = gg(b, c, d, a, x[k + 0], 20, rnd[23])
a = gg(a, b, c, d, x[k + 5], 5, rnd[24]); a = gg(a, b, c, d, x[k + 5], 5, rnd[24])
d = gg(d, a, b, c, x[k + 10], 9, rnd[25]); d = gg(d, a, b, c, x[k + 10], 9, rnd[25])
c = gg(c, d, a, b, x[k + 15], 14, rnd[26]); c = gg(c, d, a, b, x[k + 15], 14, rnd[26])
b = gg(b, c, d, a, x[k + 4], 20, rnd[27]); b = gg(b, c, d, a, x[k + 4], 20, rnd[27])
a = gg(a, b, c, d, x[k + 9], 5, rnd[28]); a = gg(a, b, c, d, x[k + 9], 5, rnd[28])
d = gg(d, a, b, c, x[k + 14], 9, rnd[29]); d = gg(d, a, b, c, x[k + 14], 9, rnd[29])
c = gg(c, d, a, b, x[k + 3], 14, rnd[30]); c = gg(c, d, a, b, x[k + 3], 14, rnd[30])
b = gg(b, c, d, a, x[k + 8], 20, rnd[31]); b = gg(b, c, d, a, x[k + 8], 20, rnd[31])
a = gg(a, b, c, d, x[k + 13], 5, rnd[32]); a = gg(a, b, c, d, x[k + 13], 5, rnd[32])
d = gg(d, a, b, c, x[k + 2], 9, rnd[33]); d = gg(d, a, b, c, x[k + 2], 9, rnd[33])
c = gg(c, d, a, b, x[k + 7], 14, rnd[34]); c = gg(c, d, a, b, x[k + 7], 14, rnd[34])
b = gg(b, c, d, a, x[k + 12], 20, rnd[35]); b = gg(b, c, d, a, x[k + 12], 20, rnd[35])
a = hh(a, b, c, d, x[k + 5], 4, rnd[36]); a = hh(a, b, c, d, x[k + 5], 4, rnd[36])
d = hh(d, a, b, c, x[k + 8], 11, rnd[37]); d = hh(d, a, b, c, x[k + 8], 11, rnd[37])
c = hh(c, d, a, b, x[k + 11], 16, rnd[38]); c = hh(c, d, a, b, x[k + 11], 16, rnd[38])
b = hh(b, c, d, a, x[k + 14], 23, rnd[39]); b = hh(b, c, d, a, x[k + 14], 23, rnd[39])
a = hh(a, b, c, d, x[k + 1], 4, rnd[40]); a = hh(a, b, c, d, x[k + 1], 4, rnd[40])
d = hh(d, a, b, c, x[k + 4], 11, rnd[41]); d = hh(d, a, b, c, x[k + 4], 11, rnd[41])
c = hh(c, d, a, b, x[k + 7], 16, rnd[42]); c = hh(c, d, a, b, x[k + 7], 16, rnd[42])
b = hh(b, c, d, a, x[k + 10], 23, rnd[43]); b = hh(b, c, d, a, x[k + 10], 23, rnd[43])
a = hh(a, b, c, d, x[k + 13], 4, rnd[44]); a = hh(a, b, c, d, x[k + 13], 4, rnd[44])
d = hh(d, a, b, c, x[k + 0], 11, rnd[45]); d = hh(d, a, b, c, x[k + 0], 11, rnd[45])
c = hh(c, d, a, b, x[k + 3], 16, rnd[46]); c = hh(c, d, a, b, x[k + 3], 16, rnd[46])
b = hh(b, c, d, a, x[k + 6], 23, rnd[47]); b = hh(b, c, d, a, x[k + 6], 23, rnd[47])
a = hh(a, b, c, d, x[k + 9], 4, rnd[48]); a = hh(a, b, c, d, x[k + 9], 4, rnd[48])
d = hh(d, a, b, c, x[k + 12], 11, rnd[49]); d = hh(d, a, b, c, x[k + 12], 11, rnd[49])
c = hh(c, d, a, b, x[k + 15], 16, rnd[50]); c = hh(c, d, a, b, x[k + 15], 16, rnd[50])
b = hh(b, c, d, a, x[k + 2], 23, rnd[51]); b = hh(b, c, d, a, x[k + 2], 23, rnd[51])
a = ii(a, b, c, d, x[k + 0], 6, rnd[52]); a = ii(a, b, c, d, x[k + 0], 6, rnd[52])
d = ii(d, a, b, c, x[k + 7], 10, rnd[53]); d = ii(d, a, b, c, x[k + 7], 10, rnd[53])
c = ii(c, d, a, b, x[k + 14], 15, rnd[54]); c = ii(c, d, a, b, x[k + 14], 15, rnd[54])
b = ii(b, c, d, a, x[k + 5], 21, rnd[55]); b = ii(b, c, d, a, x[k + 5], 21, rnd[55])
a = ii(a, b, c, d, x[k + 12], 6, rnd[56]); a = ii(a, b, c, d, x[k + 12], 6, rnd[56])
d = ii(d, a, b, c, x[k + 3], 10, rnd[57]); d = ii(d, a, b, c, x[k + 3], 10, rnd[57])
c = ii(c, d, a, b, x[k + 10], 15, rnd[58]); c = ii(c, d, a, b, x[k + 10], 15, rnd[58])
b = ii(b, c, d, a, x[k + 1], 21, rnd[59]); b = ii(b, c, d, a, x[k + 1], 21, rnd[59])
a = ii(a, b, c, d, x[k + 8], 6, rnd[60]); a = ii(a, b, c, d, x[k + 8], 6, rnd[60])
d = ii(d, a, b, c, x[k + 15], 10, rnd[61]); d = ii(d, a, b, c, x[k + 15], 10, rnd[61])
c = ii(c, d, a, b, x[k + 6], 15, rnd[62]); c = ii(c, d, a, b, x[k + 6], 15, rnd[62])
b = ii(b, c, d, a, x[k + 13], 21, rnd[63]); b = ii(b, c, d, a, x[k + 13], 21, rnd[63])
a = ii(a, b, c, d, x[k + 4], 6, rnd[64]); a = ii(a, b, c, d, x[k + 4], 6, rnd[64])
d = ii(d, a, b, c, x[k + 11], 10, rnd[65]); d = ii(d, a, b, c, x[k + 11], 10, rnd[65])
c = ii(c, d, a, b, x[k + 2], 15, rnd[66]); c = ii(c, d, a, b, x[k + 2], 15, rnd[66])
b = ii(b, c, d, a, x[k + 9], 21, rnd[67]); b = ii(b, c, d, a, x[k + 9], 21, rnd[67])
a = addUnsigned(a, AA); a = addUnsigned(a, AA)
b = addUnsigned(b, BB); b = addUnsigned(b, BB)
c = addUnsigned(c, CC); c = addUnsigned(c, CC)
d = addUnsigned(d, DD); d = addUnsigned(d, DD)
} }
return wordToHex(a).concat(wordToHex(b), wordToHex(c), wordToHex(d)); return wordToHex(a).concat(wordToHex(b), wordToHex(c), wordToHex(d))
} }
// function encString (plaintext, key, iv) { // function encString (plaintext, key, iv) {
// var i; // var i;
@ -751,55 +751,55 @@ const Base64 = {
b64 = "", b64 = "",
i, i,
broken_b64, broken_b64,
totalChunks = Math.floor((b.length * 16) / 3); totalChunks = Math.floor((b.length * 16) / 3)
for (i = 0; i < b.length * 16; i++) { for (i = 0; i < b.length * 16; i++) {
flatArr.push(b[Math.floor(i / 16)][i % 16]); flatArr.push(b[Math.floor(i / 16)][i % 16])
} }
for (i = 0; i < flatArr.length; i = i + 3) { for (i = 0; i < flatArr.length; i = i + 3) {
b64 += chars[flatArr[i] >> 2]; b64 += chars[flatArr[i] >> 2]
b64 += chars[((flatArr[i] & 3) << 4) | (flatArr[i + 1] >> 4)]; b64 += chars[((flatArr[i] & 3) << 4) | (flatArr[i + 1] >> 4)]
if (flatArr[i + 1] !== undefined) { if (flatArr[i + 1] !== undefined) {
b64 += chars[((flatArr[i + 1] & 15) << 2) | (flatArr[i + 2] >> 6)]; b64 += chars[((flatArr[i + 1] & 15) << 2) | (flatArr[i + 2] >> 6)]
} else { } else {
b64 += "="; b64 += "="
} }
if (flatArr[i + 2] !== undefined) { if (flatArr[i + 2] !== undefined) {
b64 += chars[flatArr[i + 2] & 63]; b64 += chars[flatArr[i + 2] & 63]
} else { } else {
b64 += "="; b64 += "="
} }
} }
broken_b64 = b64.slice(0, 64) + "\n"; broken_b64 = b64.slice(0, 64) + "\n"
for (i = 1; i < Math.ceil(b64.length / 64); i++) { for (i = 1; i < Math.ceil(b64.length / 64); i++) {
broken_b64 += broken_b64 +=
b64.slice(i * 64, i * 64 + 64) + b64.slice(i * 64, i * 64 + 64) +
(Math.ceil(b64.length / 64) === i + 1 ? "" : "\n"); (Math.ceil(b64.length / 64) === i + 1 ? "" : "\n")
} }
return broken_b64; return broken_b64
}, },
decode: function (string) { decode: function (string) {
string = string.replace(/\n/g, ""); string = string.replace(/\n/g, "")
var _chars = var _chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
chars = _chars.split(""), chars = _chars.split(""),
flatArr = [], flatArr = [],
c = [], c = [],
b = [], b = [],
i; i
for (i = 0; i < string.length; i = i + 4) { for (i = 0; i < string.length; i = i + 4) {
c[0] = _chars.indexOf(string.charAt(i)); c[0] = _chars.indexOf(string.charAt(i))
c[1] = _chars.indexOf(string.charAt(i + 1)); c[1] = _chars.indexOf(string.charAt(i + 1))
c[2] = _chars.indexOf(string.charAt(i + 2)); c[2] = _chars.indexOf(string.charAt(i + 2))
c[3] = _chars.indexOf(string.charAt(i + 3)); c[3] = _chars.indexOf(string.charAt(i + 3))
b[0] = (c[0] << 2) | (c[1] >> 4); b[0] = (c[0] << 2) | (c[1] >> 4)
b[1] = ((c[1] & 15) << 4) | (c[2] >> 2); b[1] = ((c[1] & 15) << 4) | (c[2] >> 2)
b[2] = ((c[2] & 3) << 6) | c[3]; b[2] = ((c[2] & 3) << 6) | c[3]
flatArr.push(b[0], b[1], b[2]); flatArr.push(b[0], b[1], b[2])
} }
flatArr = flatArr.slice(0, flatArr.length - (flatArr.length % 16)); flatArr = flatArr.slice(0, flatArr.length - (flatArr.length % 16))
return flatArr; return flatArr
}, },
}; }
export { enc, dec }; export { enc, dec }

View file

@ -1,48 +1,48 @@
import { enc, dec } from "./aes"; import { enc, dec } from "./aes"
// for some reason eslint was parsing the type inside of the function params as a variable // for some reason eslint was parsing the type inside of the function params as a variable
export interface Codec { export interface Codec {
// eslint-disable-next-line // eslint-disable-next-line
encode: (str: string | undefined) => string; encode: (str: string | undefined) => string
// eslint-disable-next-line // eslint-disable-next-line
decode: (str: string | undefined) => string; decode: (str: string | undefined) => string
} }
const xor = { const xor = {
encode: (str: string | undefined, key: number = 2) => { encode: (str: string | undefined, key: number = 2) => {
if (!str) return str; if (!str) return str
return encodeURIComponent( return encodeURIComponent(
str str
.split("") .split("")
.map((e, i) => .map((e, i) =>
i % key ? String.fromCharCode(e.charCodeAt(0) ^ key) : e, i % key ? String.fromCharCode(e.charCodeAt(0) ^ key) : e
)
.join("")
) )
.join(""),
);
}, },
decode: (str: string | undefined, key: number = 2) => { decode: (str: string | undefined, key: number = 2) => {
if (!str) return str; if (!str) return str
return decodeURIComponent(str) return decodeURIComponent(str)
.split("") .split("")
.map((e, i) => (i % key ? String.fromCharCode(e.charCodeAt(0) ^ key) : e)) .map((e, i) => (i % key ? String.fromCharCode(e.charCodeAt(0) ^ key) : e))
.join(""); .join("")
}, },
}; }
const plain = { const plain = {
encode: (str: string | undefined) => { encode: (str: string | undefined) => {
if (!str) return str; if (!str) return str
return encodeURIComponent(str); return encodeURIComponent(str)
}, },
decode: (str: string | undefined) => { decode: (str: string | undefined) => {
if (!str) return str; if (!str) return str
return decodeURIComponent(str); return decodeURIComponent(str)
}, },
}; }
/* /*
const aes = { const aes = {
@ -62,28 +62,28 @@ const aes = {
const none = { const none = {
encode: (str: string | undefined) => str, encode: (str: string | undefined) => str,
decode: (str: string | undefined) => str, decode: (str: string | undefined) => str,
}; }
const base64 = { const base64 = {
encode: (str: string | undefined) => { encode: (str: string | undefined) => {
if (!str) return str; if (!str) return str
return decodeURIComponent(btoa(str)); return decodeURIComponent(btoa(str))
}, },
decode: (str: string | undefined) => { decode: (str: string | undefined) => {
if (!str) return str; if (!str) return str
return atob(str); return atob(str)
}, },
}; }
if (!self.$scramjet) { if (!self.$scramjet) {
//@ts-expect-error really dumb workaround //@ts-expect-error really dumb workaround
self.$scramjet = {}; self.$scramjet = {}
} }
self.$scramjet.codecs = { self.$scramjet.codecs = {
none, none,
plain, plain,
base64, base64,
xor, xor,
}; }

View file

@ -1,6 +1,6 @@
if (!self.$scramjet) { if (!self.$scramjet) {
//@ts-expect-error really dumb workaround //@ts-expect-error really dumb workaround
self.$scramjet = {}; self.$scramjet = {}
} }
self.$scramjet.config = { self.$scramjet.config = {
prefix: "/scramjet/", prefix: "/scramjet/",
@ -10,4 +10,4 @@ self.$scramjet.config = {
worker: "/scram/scramjet.worker.js", worker: "/scram/scramjet.worker.js",
client: "/scram/scramjet.client.js", client: "/scram/scramjet.client.js",
codecs: "/scram/scramjet.codecs.js", codecs: "/scram/scramjet.codecs.js",
}; }

View file

@ -1,15 +1,15 @@
import { encodeUrl, decodeUrl } from "./rewriters/url"; import { encodeUrl, decodeUrl } from "./rewriters/url"
import { rewriteCss } from "./rewriters/css"; import { rewriteCss } from "./rewriters/css"
import { rewriteHtml, rewriteSrcset } from "./rewriters/html"; import { rewriteHtml, rewriteSrcset } from "./rewriters/html"
import { rewriteJs } from "./rewriters/js"; import { rewriteJs } from "./rewriters/js"
import { rewriteHeaders } from "./rewriters/headers"; import { rewriteHeaders } from "./rewriters/headers"
import { rewriteWorkers } from "./rewriters/worker"; import { rewriteWorkers } from "./rewriters/worker"
import { isScramjetFile } from "./rewriters/html"; import { isScramjetFile } from "./rewriters/html"
import { BareClient } from "@mercuryworkshop/bare-mux"; import { BareClient } from "@mercuryworkshop/bare-mux"
if (!self.$scramjet) { if (!self.$scramjet) {
//@ts-expect-error really dumb workaround //@ts-expect-error really dumb workaround
self.$scramjet = {}; self.$scramjet = {}
} }
self.$scramjet.shared = { self.$scramjet.shared = {
util: { util: {
@ -28,4 +28,4 @@ self.$scramjet.shared = {
rewriteHeaders, rewriteHeaders,
rewriteWorkers, rewriteWorkers,
}, },
}; }

View file

@ -1,11 +1,11 @@
// This CSS rewriter uses code from Meteor // This CSS rewriter uses code from Meteor
// You can find the original source code at https://github.com/MeteorProxy/Meteor // You can find the original source code at https://github.com/MeteorProxy/Meteor
import { encodeUrl } from "./url"; import { encodeUrl } from "./url"
export function rewriteCss(css: string, origin?: URL) { export function rewriteCss(css: string, origin?: URL) {
const regex = const regex =
/(@import\s+(?!url\())?\s*url\(\s*(['"]?)([^'")]+)\2\s*\)|@import\s+(['"])([^'"]+)\4/g; /(@import\s+(?!url\())?\s*url\(\s*(['"]?)([^'")]+)\2\s*\)|@import\s+(['"])([^'"]+)\4/g
return css.replace( return css.replace(
regex, regex,
@ -15,20 +15,20 @@ export function rewriteCss(css: string, origin?: URL) {
urlQuote, urlQuote,
urlContent, urlContent,
importQuote, importQuote,
importContent, importContent
) => { ) => {
const url = urlContent || importContent; const url = urlContent || importContent
const encodedUrl = encodeUrl(url.trim(), origin); const encodedUrl = encodeUrl(url.trim(), origin)
if (importStatement) { if (importStatement) {
return `@import url(${urlQuote}${encodedUrl}${urlQuote})`; return `@import url(${urlQuote}${encodedUrl}${urlQuote})`
} }
if (importQuote) { if (importQuote) {
return `@import ${importQuote}${encodedUrl}${importQuote}`; return `@import ${importQuote}${encodedUrl}${importQuote}`
} }
return `url(${urlQuote}${encodedUrl}${urlQuote})`; return `url(${urlQuote}${encodedUrl}${urlQuote})`
}, }
); )
} }

View file

@ -1,5 +1,5 @@
import { encodeUrl } from "./url"; import { encodeUrl } from "./url"
import { BareHeaders } from "@mercuryworkshop/bare-mux"; import { BareHeaders } from "@mercuryworkshop/bare-mux"
const cspHeaders = [ const cspHeaders = [
"cross-origin-embedder-policy", "cross-origin-embedder-policy",
"cross-origin-opener-policy", "cross-origin-opener-policy",
@ -20,31 +20,31 @@ const cspHeaders = [
// This needs to be emulated, but for right now it isn't that important of a feature to be worried about // This needs to be emulated, but for right now it isn't that important of a feature to be worried about
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
"clear-site-data", "clear-site-data",
]; ]
const urlHeaders = ["location", "content-location", "referer"]; const urlHeaders = ["location", "content-location", "referer"]
export function rewriteHeaders(rawHeaders: BareHeaders, origin?: URL) { export function rewriteHeaders(rawHeaders: BareHeaders, origin?: URL) {
const headers = {}; const headers = {}
for (const key in rawHeaders) { for (const key in rawHeaders) {
headers[key.toLowerCase()] = rawHeaders[key]; headers[key.toLowerCase()] = rawHeaders[key]
} }
cspHeaders.forEach((header) => { cspHeaders.forEach((header) => {
delete headers[header]; delete headers[header]
}); })
urlHeaders.forEach((header) => { urlHeaders.forEach((header) => {
if (headers[header]) if (headers[header])
headers[header] = encodeUrl(headers[header] as string, origin); headers[header] = encodeUrl(headers[header] as string, origin)
}); })
if (headers["link"]) { if (headers["link"]) {
headers["link"] = headers["link"].replace(/<(.*?)>/gi, (match) => headers["link"] = headers["link"].replace(/<(.*?)>/gi, (match) =>
encodeUrl(match, origin), encodeUrl(match, origin)
); )
} }
return headers; return headers
} }

View file

@ -1,28 +1,28 @@
import { Parser } from "htmlparser2"; import { Parser } from "htmlparser2"
import { DomHandler, Element } from "domhandler"; import { DomHandler, Element } from "domhandler"
import { hasAttrib } from "domutils"; import { hasAttrib } from "domutils"
import render from "dom-serializer"; import render from "dom-serializer"
import { encodeUrl } from "./url"; import { encodeUrl } from "./url"
import { rewriteCss } from "./css"; import { rewriteCss } from "./css"
import { rewriteJs } from "./js"; import { rewriteJs } from "./js"
export function isScramjetFile(src: string) { export function isScramjetFile(src: string) {
let bool = false; let bool = false
["codecs", "client", "shared", "worker", "config"].forEach((file) => { ;["codecs", "client", "shared", "worker", "config"].forEach((file) => {
if (src === self.$scramjet.config[file]) bool = true; if (src === self.$scramjet.config[file]) bool = true
}); })
return bool; return bool
} }
export function rewriteHtml(html: string, origin?: URL) { export function rewriteHtml(html: string, origin?: URL) {
const handler = new DomHandler((err, dom) => dom); const handler = new DomHandler((err, dom) => dom)
const parser = new Parser(handler); const parser = new Parser(handler)
parser.write(html); parser.write(html)
parser.end(); parser.end()
return render(traverseParsedHtml(handler.root, origin)); return render(traverseParsedHtml(handler.root, origin))
} }
// i need to add the attributes in during rewriting // i need to add the attributes in during rewriting
@ -31,93 +31,93 @@ function traverseParsedHtml(node, origin?: URL) {
/* csp attributes */ /* csp attributes */
for (const cspAttr of ["nonce", "integrity", "csp"]) { for (const cspAttr of ["nonce", "integrity", "csp"]) {
if (hasAttrib(node, cspAttr)) { if (hasAttrib(node, cspAttr)) {
node.attribs[`data-${cspAttr}`] = node.attribs[cspAttr]; node.attribs[`data-${cspAttr}`] = node.attribs[cspAttr]
delete node.attribs[cspAttr]; delete node.attribs[cspAttr]
} }
} }
/* url attributes */ /* url attributes */
for (const urlAttr of ["src", "href", "data", "action", "formaction"]) { for (const urlAttr of ["src", "href", "data", "action", "formaction"]) {
if (hasAttrib(node, urlAttr) && !isScramjetFile(node.attribs[urlAttr])) { if (hasAttrib(node, urlAttr) && !isScramjetFile(node.attribs[urlAttr])) {
const value = node.attribs[urlAttr]; const value = node.attribs[urlAttr]
node.attribs[`data-${urlAttr}`] = value; node.attribs[`data-${urlAttr}`] = value
node.attribs[urlAttr] = encodeUrl(value, origin); node.attribs[urlAttr] = encodeUrl(value, origin)
} }
} }
/* other */ /* other */
for (const srcsetAttr of ["srcset", "imagesrcset"]) { for (const srcsetAttr of ["srcset", "imagesrcset"]) {
if (hasAttrib(node, srcsetAttr)) { if (hasAttrib(node, srcsetAttr)) {
const value = node.attribs[srcsetAttr]; const value = node.attribs[srcsetAttr]
node.attribs[`data-${srcsetAttr}`] = value; node.attribs[`data-${srcsetAttr}`] = value
node.attribs[srcsetAttr] = rewriteSrcset(value, origin); node.attribs[srcsetAttr] = rewriteSrcset(value, origin)
} }
} }
if (hasAttrib(node, "srcdoc")) if (hasAttrib(node, "srcdoc"))
node.attribs.srcdoc = rewriteHtml(node.attribs.srcdoc, origin); node.attribs.srcdoc = rewriteHtml(node.attribs.srcdoc, origin)
if (hasAttrib(node, "style")) if (hasAttrib(node, "style"))
node.attribs.style = rewriteCss(node.attribs.style, origin); node.attribs.style = rewriteCss(node.attribs.style, origin)
if (node.name === "style" && node.children[0] !== undefined) if (node.name === "style" && node.children[0] !== undefined)
node.children[0].data = rewriteCss(node.children[0].data, origin); node.children[0].data = rewriteCss(node.children[0].data, origin)
if ( if (
node.name === "script" && node.name === "script" &&
/(application|text)\/javascript|importmap|undefined/.test( /(application|text)\/javascript|importmap|undefined/.test(
node.attribs.type, node.attribs.type
) && ) &&
node.children[0] !== undefined node.children[0] !== undefined
) )
node.children[0].data = rewriteJs(node.children[0].data, origin); node.children[0].data = rewriteJs(node.children[0].data, origin)
if (node.name === "meta" && hasAttrib(node, "http-equiv")) { if (node.name === "meta" && hasAttrib(node, "http-equiv")) {
if (node.attribs["http-equiv"] === "content-security-policy") { if (node.attribs["http-equiv"] === "content-security-policy") {
node = {}; node = {}
} else if ( } else if (
node.attribs["http-equiv"] === "refresh" && node.attribs["http-equiv"] === "refresh" &&
node.attribs.content.includes("url") node.attribs.content.includes("url")
) { ) {
const contentArray = node.attribs.content.split("url="); const contentArray = node.attribs.content.split("url=")
contentArray[1] = encodeUrl(contentArray[1].trim(), origin); contentArray[1] = encodeUrl(contentArray[1].trim(), origin)
node.attribs.content = contentArray.join("url="); node.attribs.content = contentArray.join("url=")
} }
} }
if (node.name === "head") { if (node.name === "head") {
const scramjetScripts = []; const scramjetScripts = []
["codecs", "config", "shared", "client"].forEach((script) => { ;["codecs", "config", "shared", "client"].forEach((script) => {
scramjetScripts.push( scramjetScripts.push(
new Element("script", { new Element("script", {
src: self.$scramjet.config[script], src: self.$scramjet.config[script],
"data-scramjet": "", "data-scramjet": "",
}), })
); )
}); })
node.children.unshift(...scramjetScripts); node.children.unshift(...scramjetScripts)
} }
if (node.childNodes) { if (node.childNodes) {
for (const childNode in node.childNodes) { for (const childNode in node.childNodes) {
node.childNodes[childNode] = traverseParsedHtml( node.childNodes[childNode] = traverseParsedHtml(
node.childNodes[childNode], node.childNodes[childNode],
origin, origin
); )
} }
} }
return node; return node
} }
export function rewriteSrcset(srcset: string, origin?: URL) { export function rewriteSrcset(srcset: string, origin?: URL) {
const urls = srcset.split(/ [0-9]+x,? ?/g); const urls = srcset.split(/ [0-9]+x,? ?/g)
if (!urls) return ""; if (!urls) return ""
const sufixes = srcset.match(/ [0-9]+x,? ?/g); const sufixes = srcset.match(/ [0-9]+x,? ?/g)
if (!sufixes) return ""; if (!sufixes) return ""
const rewrittenUrls = urls.map((url, i) => { const rewrittenUrls = urls.map((url, i) => {
if (url && sufixes[i]) { if (url && sufixes[i]) {
return encodeUrl(url, origin) + sufixes[i]; return encodeUrl(url, origin) + sufixes[i]
} }
}); })
return rewrittenUrls.join(""); return rewrittenUrls.join("")
} }

View file

@ -1,8 +1,8 @@
import { parseModule } from "meriyah"; import { parseModule } from "meriyah"
import { generate } from "astring"; import { generate } from "astring"
import { makeTraveler } from "astravel"; import { makeTraveler } from "astravel"
import { encodeUrl } from "./url"; import { encodeUrl } from "./url"
import * as ESTree from "estree"; import * as ESTree from "estree"
// i am a cat. i like to be petted. i like to be fed. i like to be // i am a cat. i like to be petted. i like to be fed. i like to be
@ -17,13 +17,13 @@ import * as ESTree from "estree";
// parent // parent
export function rewriteJs(js: string, origin?: URL) { export function rewriteJs(js: string, origin?: URL) {
const htmlcomment = /<!--[\s\S]*?-->/g; const htmlcomment = /<!--[\s\S]*?-->/g
js = js.replace(htmlcomment, ""); js = js.replace(htmlcomment, "")
try { try {
const ast = parseModule(js, { const ast = parseModule(js, {
module: true, module: true,
webcompat: true, webcompat: true,
}); })
const identifierList = [ const identifierList = [
"window", "window",
@ -33,32 +33,32 @@ export function rewriteJs(js: string, origin?: URL) {
"parent", "parent",
"top", "top",
"location", "location",
]; ]
const customTraveler = makeTraveler({ const customTraveler = makeTraveler({
ImportDeclaration: (node: ESTree.ImportDeclaration) => { ImportDeclaration: (node: ESTree.ImportDeclaration) => {
node.source.value = encodeUrl(node.source.value as string, origin); node.source.value = encodeUrl(node.source.value as string, origin)
}, },
ImportExpression: (node: ESTree.ImportExpression) => { ImportExpression: (node: ESTree.ImportExpression) => {
if (node.source.type === "Literal") { if (node.source.type === "Literal") {
node.source.value = encodeUrl(node.source.value as string, origin); node.source.value = encodeUrl(node.source.value as string, origin)
} else if (node.source.type === "Identifier") { } else if (node.source.type === "Identifier") {
// this is for things that import something like // this is for things that import something like
// const moduleName = "name"; // const moduleName = "name";
// await import(moduleName); // await import(moduleName);
node.source.name = `__wrapImport(${node.source.name})`; node.source.name = `__wrapImport(${node.source.name})`
} }
}, },
ExportAllDeclaration: (node: ESTree.ExportAllDeclaration) => { ExportAllDeclaration: (node: ESTree.ExportAllDeclaration) => {
node.source.value = encodeUrl(node.source.value as string, origin); node.source.value = encodeUrl(node.source.value as string, origin)
}, },
ExportNamedDeclaration: (node: ESTree.ExportNamedDeclaration) => { ExportNamedDeclaration: (node: ESTree.ExportNamedDeclaration) => {
// strings are Literals in ESTree syntax but these will always be strings // strings are Literals in ESTree syntax but these will always be strings
if (node.source) if (node.source)
node.source.value = encodeUrl(node.source.value as string, origin); node.source.value = encodeUrl(node.source.value as string, origin)
}, },
MemberExpression: (node: ESTree.MemberExpression) => { MemberExpression: (node: ESTree.MemberExpression) => {
@ -66,7 +66,7 @@ export function rewriteJs(js: string, origin?: URL) {
node.object.type === "Identifier" && node.object.type === "Identifier" &&
identifierList.includes(node.object.name) identifierList.includes(node.object.name)
) { ) {
node.object.name = `globalThis.$s(${node.object.name})`; node.object.name = `globalThis.$s(${node.object.name})`
} }
}, },
@ -75,14 +75,14 @@ export function rewriteJs(js: string, origin?: URL) {
node.left.type === "Identifier" && node.left.type === "Identifier" &&
identifierList.includes(node.left.name) identifierList.includes(node.left.name)
) { ) {
node.left.name = `globalThis.$s(${node.left.name})`; node.left.name = `globalThis.$s(${node.left.name})`
} }
if ( if (
node.right.type === "Identifier" && node.right.type === "Identifier" &&
identifierList.includes(node.right.name) identifierList.includes(node.right.name)
) { ) {
node.right.name = `globalThis.$s(${node.right.name})`; node.right.name = `globalThis.$s(${node.right.name})`
} }
}, },
@ -92,18 +92,18 @@ export function rewriteJs(js: string, origin?: URL) {
node.init.type === "Identifier" && node.init.type === "Identifier" &&
identifierList.includes(node.init.name) identifierList.includes(node.init.name)
) { ) {
node.init.name = `globalThis.$s(${node.init.name})`; node.init.name = `globalThis.$s(${node.init.name})`
} }
}, },
}); })
customTraveler.go(ast); customTraveler.go(ast)
return generate(ast); return generate(ast)
} catch (e) { } catch (e) {
console.error(e); console.error(e)
console.log(js); console.log(js)
return js; return js
} }
} }

View file

@ -1,58 +1,58 @@
import { URL } from "../../client/url"; import { URL } from "../../client/url"
import { rewriteJs } from "./js"; import { rewriteJs } from "./js"
function canParseUrl(url: string, origin?: URL) { function canParseUrl(url: string, origin?: URL) {
try { try {
new URL(url, origin); new URL(url, origin)
return true; return true
} catch { } catch {
return false; return false
} }
} }
// something is broken with this but i didn't debug it // something is broken with this but i didn't debug it
export function encodeUrl(url: string | URL, origin?: URL) { export function encodeUrl(url: string | URL, origin?: URL) {
if (url instanceof URL) { if (url instanceof URL) {
return url.toString(); return url.toString()
} }
if (!origin) { if (!origin) {
origin = new URL( origin = new URL(
self.$scramjet.config.codec.decode( self.$scramjet.config.codec.decode(
location.href.slice( location.href.slice(
(location.origin + self.$scramjet.config.prefix).length, (location.origin + self.$scramjet.config.prefix).length
), )
), )
); )
} }
if (url.startsWith("javascript:")) { if (url.startsWith("javascript:")) {
return "javascript:" + rewriteJs(url.slice("javascript:".length)); return "javascript:" + rewriteJs(url.slice("javascript:".length))
} else if (/^(#|mailto|about|data)/.test(url)) { } else if (/^(#|mailto|about|data)/.test(url)) {
return url; return url
} else if (canParseUrl(url, origin)) { } else if (canParseUrl(url, origin)) {
return ( return (
location.origin + location.origin +
self.$scramjet.config.prefix + self.$scramjet.config.prefix +
self.$scramjet.config.codec.encode(new URL(url, origin).href) self.$scramjet.config.codec.encode(new URL(url, origin).href)
); )
} }
} }
// something is also broken with this but i didn't debug it // something is also broken with this but i didn't debug it
export function decodeUrl(url: string | URL) { export function decodeUrl(url: string | URL) {
if (url instanceof URL) { if (url instanceof URL) {
return url.toString(); return url.toString()
} }
if (/^(#|about|data|mailto|javascript)/.test(url)) { if (/^(#|about|data|mailto|javascript)/.test(url)) {
return url; return url
} else if (canParseUrl(url)) { } else if (canParseUrl(url)) {
return self.$scramjet.config.codec.decode( return self.$scramjet.config.codec.decode(
url.slice((location.origin + self.$scramjet.config.prefix).length), url.slice((location.origin + self.$scramjet.config.prefix).length)
); )
} else { } else {
return url; return url
} }
} }

View file

@ -1,12 +1,12 @@
import { rewriteJs } from "./js"; import { rewriteJs } from "./js"
export function rewriteWorkers(js: string, origin?: URL) { export function rewriteWorkers(js: string, origin?: URL) {
let str = new String().toString()[ let str = new String().toString()[
//@ts-expect-error //@ts-expect-error
("codecs", "config", "shared", "client") ("codecs", "config", "shared", "client")
].forEach((script) => { ].forEach((script) => {
str += `import "${self.$scramjet.config[script]}"\n`; str += `import "${self.$scramjet.config[script]}"\n`
}); })
str += rewriteJs(js, origin); str += rewriteJs(js, origin)
return str; return str
} }

74
src/types.d.ts vendored
View file

@ -1,49 +1,49 @@
import { encodeUrl, decodeUrl } from "./shared/rewriters/url"; import { encodeUrl, decodeUrl } from "./shared/rewriters/url"
import { rewriteCss } from "./shared/rewriters/css"; import { rewriteCss } from "./shared/rewriters/css"
import { rewriteHtml, rewriteSrcset } from "./shared/rewriters/html"; import { rewriteHtml, rewriteSrcset } from "./shared/rewriters/html"
import { rewriteJs } from "./shared/rewriters/js"; import { rewriteJs } from "./shared/rewriters/js"
import { rewriteHeaders } from "./shared/rewriters/headers"; import { rewriteHeaders } from "./shared/rewriters/headers"
import { rewriteWorkers } from "./shared/rewriters/worker"; import { rewriteWorkers } from "./shared/rewriters/worker"
import { isScramjetFile } from "./shared/rewriters/html"; import { isScramjetFile } from "./shared/rewriters/html"
import type { Codec } from "./codecs"; import type { Codec } from "./codecs"
import { BareClient } from "@mercuryworkshop/bare-mux"; import { BareClient } from "@mercuryworkshop/bare-mux"
declare global { declare global {
interface Window { interface Window {
$scramjet: { $scramjet: {
shared: { shared: {
url: { url: {
encodeUrl: typeof encodeUrl; encodeUrl: typeof encodeUrl
decodeUrl: typeof decodeUrl; decodeUrl: typeof decodeUrl
}; }
rewrite: { rewrite: {
rewriteCss: typeof rewriteCss; rewriteCss: typeof rewriteCss
rewriteHtml: typeof rewriteHtml; rewriteHtml: typeof rewriteHtml
rewriteSrcset: typeof rewriteSrcset; rewriteSrcset: typeof rewriteSrcset
rewriteJs: typeof rewriteJs; rewriteJs: typeof rewriteJs
rewriteHeaders: typeof rewriteHeaders; rewriteHeaders: typeof rewriteHeaders
rewriteWorkers: typeof rewriteWorkers; rewriteWorkers: typeof rewriteWorkers
}; }
util: { util: {
BareClient: typeof BareClient; BareClient: typeof BareClient
isScramjetFile: typeof isScramjetFile; isScramjetFile: typeof isScramjetFile
}; }
}; }
config: { config: {
prefix: string; prefix: string
codec: Codec; codec: Codec
config: string; config: string
shared: string; shared: string
worker: string; worker: string
client: string; client: string
codecs: string; codecs: string
}; }
codecs: { codecs: {
none: Codec; none: Codec
plain: Codec; plain: Codec
base64: Codec; base64: Codec
xor: Codec; xor: Codec
}; }
}; }
} }
} }

View file

@ -1,52 +1,52 @@
import { BareResponseFetch } from "@mercuryworkshop/bare-mux"; import { BareResponseFetch } from "@mercuryworkshop/bare-mux"
import IDBMap from "@webreflection/idb-map"; import IDBMap from "@webreflection/idb-map"
declare global { declare global {
interface Window { interface Window {
ScramjetServiceWorker; ScramjetServiceWorker
} }
} }
self.ScramjetServiceWorker = class ScramjetServiceWorker { self.ScramjetServiceWorker = class ScramjetServiceWorker {
client: typeof self.$scramjet.shared.util.BareClient.prototype; client: typeof self.$scramjet.shared.util.BareClient.prototype
config: typeof self.$scramjet.config; config: typeof self.$scramjet.config
constructor(config = self.$scramjet.config) { constructor(config = self.$scramjet.config) {
this.client = new self.$scramjet.shared.util.BareClient(); this.client = new self.$scramjet.shared.util.BareClient()
if (!config.prefix) config.prefix = "/scramjet/"; if (!config.prefix) config.prefix = "/scramjet/"
this.config = config; this.config = config
} }
route({ request }: FetchEvent) { route({ request }: FetchEvent) {
if (request.url.startsWith(location.origin + this.config.prefix)) if (request.url.startsWith(location.origin + this.config.prefix))
return true; return true
else return false; else return false
} }
async fetch({ request }: FetchEvent) { async fetch({ request }: FetchEvent) {
const urlParam = new URLSearchParams(new URL(request.url).search); const urlParam = new URLSearchParams(new URL(request.url).search)
const { encodeUrl, decodeUrl } = self.$scramjet.shared.url; const { encodeUrl, decodeUrl } = self.$scramjet.shared.url
const { const {
rewriteHeaders, rewriteHeaders,
rewriteHtml, rewriteHtml,
rewriteJs, rewriteJs,
rewriteCss, rewriteCss,
rewriteWorkers, rewriteWorkers,
} = self.$scramjet.shared.rewrite; } = self.$scramjet.shared.rewrite
if (urlParam.has("url")) { if (urlParam.has("url")) {
return Response.redirect( return Response.redirect(
encodeUrl(urlParam.get("url"), new URL(urlParam.get("url"))), encodeUrl(urlParam.get("url"), new URL(urlParam.get("url")))
); )
} }
try { try {
const url = new URL(decodeUrl(request.url)); const url = new URL(decodeUrl(request.url))
const cookieStore = new IDBMap(url.host, { const cookieStore = new IDBMap(url.host, {
durability: "relaxed", durability: "relaxed",
prefix: "Cookies", prefix: "Cookies",
}); })
const response: BareResponseFetch = await this.client.fetch(url, { const response: BareResponseFetch = await this.client.fetch(url, {
method: request.method, method: request.method,
@ -58,41 +58,41 @@ self.ScramjetServiceWorker = class ScramjetServiceWorker {
redirect: request.redirect, redirect: request.redirect,
//@ts-ignore why the fuck is this not typed mircosoft //@ts-ignore why the fuck is this not typed mircosoft
duplex: "half", duplex: "half",
}); })
let responseBody; let responseBody
const responseHeaders = rewriteHeaders(response.rawHeaders, url); const responseHeaders = rewriteHeaders(response.rawHeaders, url)
for (const cookie of (responseHeaders["set-cookie"] || []) as string[]) { for (const cookie of (responseHeaders["set-cookie"] || []) as string[]) {
let cookieParsed = cookie.split(";").map((x) => x.trim().split("=")); let cookieParsed = cookie.split(";").map((x) => x.trim().split("="))
let [key, value] = cookieParsed.shift(); let [key, value] = cookieParsed.shift()
value = value.replace('"', ""); value = value.replace('"', "")
const hostArg = cookieParsed.find( const hostArg = cookieParsed.find(
(x) => x[0].toLowerCase() === "domain", (x) => x[0].toLowerCase() === "domain"
); )
cookieParsed = cookieParsed.filter( cookieParsed = cookieParsed.filter(
(x) => x[0].toLowerCase() !== "domain", (x) => x[0].toLowerCase() !== "domain"
); )
let host = hostArg ? hostArg[1] : undefined; let host = hostArg ? hostArg[1] : undefined
if (host && host !== url.host) { if (host && host !== url.host) {
if (host.startsWith(".")) host = host.slice(1); if (host.startsWith(".")) host = host.slice(1)
const cookieStore = new IDBMap(host, { const cookieStore = new IDBMap(host, {
durability: "relaxed", durability: "relaxed",
prefix: "Cookies", prefix: "Cookies",
}); })
cookieStore.set(key, { value: value, args: cookieParsed }); cookieStore.set(key, { value: value, args: cookieParsed })
} else { } else {
cookieStore.set(key, { value: value, args: cookieParsed }); cookieStore.set(key, { value: value, args: cookieParsed })
} }
} }
for (let header in responseHeaders) { for (let header in responseHeaders) {
// flatten everything past here // flatten everything past here
if (responseHeaders[header] instanceof Array) if (responseHeaders[header] instanceof Array)
responseHeaders[header] = responseHeaders[header][0]; responseHeaders[header] = responseHeaders[header][0]
} }
if (response.body) { if (response.body) {
@ -104,69 +104,67 @@ self.ScramjetServiceWorker = class ScramjetServiceWorker {
?.toString() ?.toString()
?.startsWith("text/html") ?.startsWith("text/html")
) { ) {
responseBody = rewriteHtml(await response.text(), url); responseBody = rewriteHtml(await response.text(), url)
} else { } else {
responseBody = response.body; responseBody = response.body
} }
break; break
case "script": case "script":
responseBody = rewriteJs(await response.text(), url); responseBody = rewriteJs(await response.text(), url)
break; break
case "style": case "style":
responseBody = rewriteCss(await response.text(), url); responseBody = rewriteCss(await response.text(), url)
break; break
case "sharedworker": case "sharedworker":
case "worker": case "worker":
responseBody = rewriteWorkers(await response.text(), url); responseBody = rewriteWorkers(await response.text(), url)
break; break
default: default:
responseBody = response.body; responseBody = response.body
break; break
} }
} }
// downloads // downloads
if (["document", "iframe"].includes(request.destination)) { if (["document", "iframe"].includes(request.destination)) {
const header = responseHeaders["content-disposition"]; const header = responseHeaders["content-disposition"]
// validate header and test for filename // validate header and test for filename
if (!/\s*?((inline|attachment);\s*?)filename=/i.test(header)) { if (!/\s*?((inline|attachment);\s*?)filename=/i.test(header)) {
// if filename= wasn"t specified then maybe the remote specified to download this as an attachment? // if filename= wasn"t specified then maybe the remote specified to download this as an attachment?
// if it"s invalid then we can still possibly test for the attachment/inline type // if it"s invalid then we can still possibly test for the attachment/inline type
const type = /^\s*?attachment/i.test(header) const type = /^\s*?attachment/i.test(header) ? "attachment" : "inline"
? "attachment"
: "inline";
// set the filename // set the filename
const [filename] = new URL(response.finalURL).pathname const [filename] = new URL(response.finalURL).pathname
.split("/") .split("/")
.slice(-1); .slice(-1)
responseHeaders["content-disposition"] = responseHeaders["content-disposition"] =
`${type}; filename=${JSON.stringify(filename)}`; `${type}; filename=${JSON.stringify(filename)}`
} }
} }
if (responseHeaders["accept"] === "text/event-stream") { if (responseHeaders["accept"] === "text/event-stream") {
responseHeaders["content-type"] = "text/event-stream"; responseHeaders["content-type"] = "text/event-stream"
} }
if (crossOriginIsolated) { if (crossOriginIsolated) {
responseHeaders["Cross-Origin-Embedder-Policy"] = "require-corp"; responseHeaders["Cross-Origin-Embedder-Policy"] = "require-corp"
} }
return new Response(responseBody, { return new Response(responseBody, {
headers: responseHeaders as HeadersInit, headers: responseHeaders as HeadersInit,
status: response.status, status: response.status,
statusText: response.statusText, statusText: response.statusText,
}); })
} catch (err) { } catch (err) {
if (!["document", "iframe"].includes(request.destination)) if (!["document", "iframe"].includes(request.destination))
return new Response(undefined, { status: 500 }); return new Response(undefined, { status: 500 })
console.error(err); console.error(err)
return renderError(err, decodeUrl(request.url)); return renderError(err, decodeUrl(request.url))
} }
} }
}; }
function errorTemplate(trace: string, fetchedURL: string) { function errorTemplate(trace: string, fetchedURL: string) {
// turn script into a data URI so we don"t have to escape any HTML values // turn script into a data URI so we don"t have to escape any HTML values
@ -174,11 +172,11 @@ function errorTemplate(trace: string, fetchedURL: string) {
errorTrace.value = ${JSON.stringify(trace)}; errorTrace.value = ${JSON.stringify(trace)};
fetchedURL.textContent = ${JSON.stringify(fetchedURL)}; fetchedURL.textContent = ${JSON.stringify(fetchedURL)};
for (const node of document.querySelectorAll("#hostname")) node.textContent = ${JSON.stringify( for (const node of document.querySelectorAll("#hostname")) node.textContent = ${JSON.stringify(
location.hostname, location.hostname
)}; )};
reload.addEventListener("click", () => location.reload()); reload.addEventListener("click", () => location.reload());
version.textContent = "0.0.1"; version.textContent = "0.0.1";
`; `
return `<!DOCTYPE html> return `<!DOCTYPE html>
<html> <html>
@ -217,7 +215,7 @@ function errorTemplate(trace: string, fetchedURL: string) {
}"></script> }"></script>
</body> </body>
</html> </html>
`; `
} }
/** /**
@ -228,13 +226,13 @@ function errorTemplate(trace: string, fetchedURL: string) {
function renderError(err, fetchedURL) { function renderError(err, fetchedURL) {
const headers = { const headers = {
"content-type": "text/html", "content-type": "text/html",
}; }
if (crossOriginIsolated) { if (crossOriginIsolated) {
headers["Cross-Origin-Embedder-Policy"] = "require-corp"; headers["Cross-Origin-Embedder-Policy"] = "require-corp"
} }
return new Response(errorTemplate(String(err), fetchedURL), { return new Response(errorTemplate(String(err), fetchedURL), {
status: 500, status: 500,
headers: headers, headers: headers,
}); })
} }

View file

@ -2,19 +2,19 @@ importScripts(
"/scram/scramjet.codecs.js", "/scram/scramjet.codecs.js",
"/scram/scramjet.config.js", "/scram/scramjet.config.js",
"/scram/scramjet.shared.js", "/scram/scramjet.shared.js",
"/scram/scramjet.worker.js", "/scram/scramjet.worker.js"
); )
const scramjet = new ScramjetServiceWorker(); const scramjet = new ScramjetServiceWorker()
async function handleRequest(event) { async function handleRequest(event) {
if (scramjet.route(event)) { if (scramjet.route(event)) {
return scramjet.fetch(event); return scramjet.fetch(event)
} }
return fetch(event.request); return fetch(event.request)
} }
self.addEventListener("fetch", (event) => { self.addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event)); event.respondWith(handleRequest(event))
}); })

View file

@ -3,15 +3,15 @@ navigator.serviceWorker
scope: $scramjet.config.prefix, scope: $scramjet.config.prefix,
}) })
.then((reg) => { .then((reg) => {
reg.update(); reg.update()
}); })
const connection = new BareMux.BareMuxConnection("/baremux/worker.js"); const connection = new BareMux.BareMuxConnection("/baremux/worker.js")
const flex = css` const flex = css`
display: flex; display: flex;
`; `
const col = css` const col = css`
flex-direction: column; flex-direction: column;
`; `
const store = $store( const store = $store(
{ {
url: "https://google.com", url: "https://google.com",
@ -22,11 +22,11 @@ const store = $store(
location.host + location.host +
"/bare/", "/bare/",
}, },
{ ident: "settings", backing: "localstorage", autosave: "auto" }, { ident: "settings", backing: "localstorage", autosave: "auto" }
); )
connection.setTransport("/baremod/index.mjs", [store.bareurl]); connection.setTransport("/baremod/index.mjs", [store.bareurl])
function App() { function App() {
this.urlencoded = ""; this.urlencoded = ""
this.css = ` this.css = `
width: 100%; width: 100%;
height: 100%; height: 100%;
@ -84,7 +84,7 @@ function App() {
outline: none; outline: none;
padding: 0.45em; padding: 0.45em;
} }
`; `
return html` return html`
<div> <div>
@ -106,9 +106,9 @@ function App() {
<input class="bar" bind:value=${use(store.url)} on:input=${(e) => (store.url = e.target.value)} on:keyup=${(e) => e.keyCode == 13 && console.log((this.urlencoded = $scramjet.config.prefix + $scramjet.config.codec.encode(e.target.value)))}></input> <input class="bar" bind:value=${use(store.url)} on:input=${(e) => (store.url = e.target.value)} on:keyup=${(e) => e.keyCode == 13 && console.log((this.urlencoded = $scramjet.config.prefix + $scramjet.config.codec.encode(e.target.value)))}></input>
<iframe src=${use(this.urlencoded)}></iframe> <iframe src=${use(this.urlencoded)}></iframe>
</div> </div>
`; `
} }
window.addEventListener("load", () => { window.addEventListener("load", () => {
document.body.appendChild(h(App)); document.body.appendChild(h(App))
}); })

View file

@ -1,7 +1,7 @@
<head></head> <head></head>
<script> <script>
function f() { function f() {
location = "http://www.google.com"; location = "http://www.google.com"
} }
</script> </script>
<button onclick="f()">Google</button> <button onclick="f()">Google</button>