Skip to content

Commit 1ed41cd

Browse files
committed
[scramjet/controller] get controller in a workable state
1 parent 4333364 commit 1ed41cd

File tree

2 files changed

+136
-83
lines changed

2 files changed

+136
-83
lines changed

packages/scramjet/packages/controller/src/index.ts

Lines changed: 135 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
import { MethodsDefinition, RpcHelper } from "@mercuryworkshop/rpc";
2-
import {
3-
codecDecode,
4-
CookieJar,
2+
import type * as ScramjetGlobal from "@mercuryworkshop/scramjet";
3+
4+
declare const $scramjet: typeof ScramjetGlobal;
5+
const {
6+
setWasm,
7+
setConfig,
8+
setInterface,
59
rewriteUrl,
610
ScramjetFetchHandler,
711
ScramjetHeaders,
8-
setConfig,
9-
type ScramjetFetchContext,
10-
} from "@mercuryworkshop/scramjet";
12+
CookieJar,
13+
} = $scramjet;
14+
1115
import { Controllerbound, SWbound } from "./types";
1216
import LibcurlClient from "@mercuryworkshop/libcurl-transport";
1317
import { BareClient } from "@mercuryworkshop/bare-mux-custom";
@@ -16,8 +20,6 @@ let lc = new LibcurlClient({
1620
wisp: "wss://anura.pro/",
1721
});
1822
const client = new BareClient(lc);
19-
console.log(lc);
20-
console.log(client);
2123

2224
const cookieJar = new CookieJar();
2325

@@ -28,9 +30,14 @@ type Config = {
2830
prefix: string;
2931
};
3032

33+
fetch("/scramjet/scramjet.wasm.wasm").then(async (resp) => {
34+
setWasm(await resp.arrayBuffer());
35+
});
36+
3137
export const config: Config = {
3238
prefix: "/~/sj",
3339
virtualWasmPath: "/scramjet.wasm.js",
40+
scramjetPath: "/scramjet/scramjet.js",
3441
};
3542

3643
const cfg = {
@@ -80,6 +87,47 @@ const cfg = {
8087

8188
setConfig(cfg);
8289

90+
const getInjectScripts = (meta, handler, cfg, cookiejar, script) => {
91+
return [
92+
script(config.scramjetPath),
93+
script(
94+
meta.prefix.href.substring(0, meta.prefix.href.length - 1) +
95+
config.virtualWasmPath
96+
),
97+
script(
98+
"data:text/javascript;base64," +
99+
btoa(`
100+
console.log("execute me twin");
101+
$scramjet.setWasm(Uint8Array.from(atob(self.WASM), (c) => c.charCodeAt(0)));
102+
delete self.WASM;
103+
104+
$scramjet.loadAndHook({
105+
interface: {
106+
getInjectScripts: ${getInjectScripts.toString()},
107+
onClientbound: async (type, msg) => {
108+
},
109+
sendServerbound: async (type, msg) => {
110+
},
111+
},
112+
config: ${JSON.stringify(cfg)},
113+
cookies: ${cookiejar.dump()},
114+
transport: null,
115+
})
116+
117+
document.currentScript.remove();
118+
`)
119+
),
120+
];
121+
};
122+
setInterface({
123+
getInjectScripts,
124+
onClientbound() {},
125+
sendServerbound(type, data) {},
126+
async fetchDataUrl(dataUrl: string) {
127+
return await fetch(dataUrl);
128+
},
129+
});
130+
83131
const frames: Record<string, Frame> = {};
84132

85133
let wasmPayload: string | null = null;
@@ -103,84 +151,90 @@ export class Controller {
103151
this.readyResolve();
104152
},
105153
request: async (data) => {
106-
console.log("REQUEST", data);
107-
let path = new URL(data.rawUrl).pathname;
108-
const frame = this.frames.find((f) => path.startsWith(f.prefix));
109-
if (!frame) throw new Error("No frame found for request");
110-
console.log("?");
111-
112-
if (path.startsWith(frame.prefix + "/" + config.virtualWasmPath)) {
113-
if (!wasmPayload) {
114-
const resp = await fetch(config.wasmPath);
115-
const buf = await resp.arrayBuffer();
116-
const b64 = btoa(
117-
new Uint8Array(buf)
118-
.reduce(
119-
(data, byte) => (data.push(String.fromCharCode(byte)), data),
120-
[] as any
121-
)
122-
.join("")
123-
);
124-
125-
let payload = "";
126-
payload +=
127-
"if ('document' in self && document.currentScript) { document.currentScript.remove(); }\n";
128-
payload += `self.WASM = '${b64}';`;
129-
wasmPayload = payload;
154+
try {
155+
let path = new URL(data.rawUrl).pathname;
156+
const frame = this.frames.find((f) => path.startsWith(f.prefix));
157+
if (!frame) throw new Error("No frame found for request");
158+
159+
console.log(path, frame.prefix + config.virtualWasmPath);
160+
if (
161+
path.startsWith(
162+
frame.prefix.substring(0, frame.prefix.length - 1) +
163+
config.virtualWasmPath
164+
)
165+
) {
166+
console.log("???");
167+
if (!wasmPayload) {
168+
const resp = await fetch(config.wasmPath);
169+
const buf = await resp.arrayBuffer();
170+
const b64 = btoa(
171+
new Uint8Array(buf)
172+
.reduce(
173+
(data, byte) => (data.push(String.fromCharCode(byte)), data),
174+
[] as any
175+
)
176+
.join("")
177+
);
178+
179+
let payload = "";
180+
payload +=
181+
"console.warn('WTF'); if ('document' in self && document.currentScript) { document.currentScript.remove(); }\n";
182+
payload += `self.WASM = '${b64}';`;
183+
wasmPayload = payload;
184+
}
185+
186+
return [
187+
{
188+
body: wasmPayload,
189+
status: 200,
190+
statusText: "OK",
191+
headers: {
192+
"Content-Type": ["application/javascript"],
193+
},
194+
},
195+
[],
196+
];
130197
}
131198

199+
let sjheaders = new ScramjetHeaders();
200+
for (let [k, v] of Object.entries(data.initialHeaders)) {
201+
for (let vv of v) {
202+
sjheaders.set(k, vv);
203+
}
204+
}
205+
206+
const fetchresponse = await frame.fetchHandler.handleFetch({
207+
initialHeaders: sjheaders,
208+
rawClientUrl: data.rawClientUrl
209+
? new URL(data.rawClientUrl)
210+
: undefined,
211+
rawUrl: new URL(data.rawUrl),
212+
destination: data.destination,
213+
method: data.method,
214+
mode: data.mode,
215+
referrer: data.referrer,
216+
forceCrossOriginIsolated: data.forceCrossOriginIsolated,
217+
body: data.body,
218+
cache: data.cache,
219+
cookieStore: this.cookieJar,
220+
});
221+
132222
return [
133223
{
134-
body: wasmPayload,
135-
status: 200,
136-
statusText: "OK",
137-
headers: {
138-
"Content-Type": ["application/javascript"],
139-
},
224+
body: fetchresponse.body,
225+
status: fetchresponse.status,
226+
statusText: fetchresponse.statusText,
227+
headers: fetchresponse.headers,
140228
},
141-
[],
229+
fetchresponse.body instanceof ReadableStream ||
230+
fetchresponse.body instanceof ArrayBuffer
231+
? [fetchresponse.body]
232+
: [],
142233
];
234+
} catch (e) {
235+
console.error("Error in controller request handler:", e);
236+
throw e;
143237
}
144-
145-
let sjheaders = new ScramjetHeaders();
146-
for (let [k, v] of Object.entries(data.initialHeaders)) {
147-
for (let vv of v) {
148-
sjheaders.set(k, vv);
149-
}
150-
}
151-
152-
console.log("fR");
153-
154-
const fetchresponse = await frame.fetchHandler.handleFetch({
155-
initialHeaders: sjheaders,
156-
rawClientUrl: data.rawClientUrl
157-
? new URL(data.rawClientUrl)
158-
: undefined,
159-
rawUrl: new URL(data.rawUrl),
160-
destination: data.destination,
161-
method: data.method,
162-
mode: data.mode,
163-
referrer: data.referrer,
164-
forceCrossOriginIsolated: data.forceCrossOriginIsolated,
165-
body: data.body,
166-
cache: data.cache,
167-
cookieStore: this.cookieJar,
168-
});
169-
170-
console.log("???");
171-
172-
return [
173-
{
174-
body: fetchresponse.body,
175-
status: fetchresponse.status,
176-
statusText: fetchresponse.statusText,
177-
headers: fetchresponse.headers,
178-
},
179-
fetchresponse.body instanceof ReadableStream ||
180-
fetchresponse.body instanceof ArrayBuffer
181-
? [fetchresponse.body]
182-
: [],
183-
];
184238
},
185239
};
186240

@@ -203,6 +257,7 @@ export class Controller {
203257
channel.port1.addEventListener("message", (e) => {
204258
this.rpc.recieve(e.data);
205259
});
260+
console.log(channel.port2);
206261
channel.port1.start();
207262

208263
serviceworker.postMessage(
@@ -243,10 +298,7 @@ class Frame {
243298
this.fetchHandler = new ScramjetFetchHandler({
244299
client,
245300
cookieJar: this.controller.cookieJar,
246-
prefix: new URL(
247-
config.prefix + "/" + this.controller.id + "/" + this.id,
248-
location.href
249-
),
301+
prefix: new URL(this.prefix, location.href),
250302
sendClientbound: (type, msg) => {},
251303
onServerbound: (type, listener) => {},
252304
});

packages/scramjet/packages/controller/src/sw.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ class Tab {
1717
port.addEventListener("message", (e) => {
1818
this.rpc.recieve(e.data);
1919
});
20+
port.onmessageerror = console.error;
2021

2122
this.rpc.call("ready", null);
2223
}

0 commit comments

Comments
 (0)