Page MenuHomeSealhub

proxy.ts
No OneTemporary

Authored By
Unknown
Size
5 KB
Referenced Files
None
Subscribers
None

proxy.ts

/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/consistent-type-assertions */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import express from "express";
import type { Server } from "node:http";
import type { Request, Response, Express } from "express";
import { createProxyMiddleware, responseInterceptor } from "http-proxy-middleware";
import { HTMLRewriter } from "html-rewriter-wasm";
import type TheApp from "./app.js";
import { htmlUnescape } from "escape-goat";
import { promisify } from "util";
import { SIGNING_SECRET, PROXY_TARGET, PROXY_HOST } from "src/back/config.js";
import { assetProxy } from "./asset-proxy.js";
import { toBase64 } from "./util.js";
import { getCache } from "./services/filru/filru.js";
import { sha512digest } from "./utils/sha512digest.js";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export default class Proxy {
express_app: Express;
server: Server;
constructor(public app: TheApp) {}
async start() {
this.express_app = express();
console.log("Starting proxy...");
const { items: rules } = await this.app.collections.rules
.suList()
.format({ code: "original" })
.filter({ active: true })
.fetch();
const code = rules
.map((rule) => `{${htmlUnescape(rule.get("code") || "")}}`)
.join("\n");
console.log("The code to run is");
console.log(code);
const proxyMiddleware = createProxyMiddleware<Request, Response>({
target: PROXY_TARGET,
changeOrigin: true,
selfHandleResponse: true,
on: {
error: (err) => {
console.error(err);
this.app.metrics.upstream_failed.labels().inc();
},
// eslint-disable-next-line @typescript-eslint/no-misused-promises
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req) => {
if (!proxyRes.headers["content-type"]?.includes("html")) {
// only rewrite html
return responseBuffer;
}
const response = responseBuffer.toString("utf8"); // convert buffer to string
let output = "";
const rewriter = new HTMLRewriter((outputChunk) => {
output += decoder.decode(outputChunk);
});
assetProxy(rewriter);
try {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const url = req.url; // to make it available in eval
eval(code);
await this.app.collections.logs.suCreate({
content: "success",
timestamp: new Date().getTime(),
url: req.url,
});
} catch (e) {
const message = e instanceof Error ? e.message : "";
console.error(e);
await this.app.collections.logs.suCreate({
content: message,
timestamp: new Date().getTime(),
url: req.url,
});
rewriter.free();
return responseBuffer;
}
try {
await rewriter.write(encoder.encode(response));
await rewriter.end();
} catch (e) {
console.error(e);
return responseBuffer;
} finally {
rewriter.free(); // Remember to free memory
}
return output;
}),
},
});
this.express_app.get("/assetproxy/", async (req: Request, res) => {
try {
const url = req.query.url;
if (!url || typeof url !== "string") {
throw new Error("Missing url param");
}
const signature = await sha512digest(`${url}${SIGNING_SECRET}`);
const signatureString = toBase64(signature);
const cache = getCache();
if (signatureString !== req.query.signature) {
res.status(403).send("Invalid signature");
return;
}
const cachedData = await cache.get(signatureString);
const full_url = `${url.startsWith("/") ? PROXY_TARGET : ""}${url}`;
if (!cachedData) {
const fetchRes = await fetch(full_url);
const body = await fetchRes.arrayBuffer();
const headers = Object.fromEntries(
// @ts-ignore - typescript does not seem to know about the entries method here
fetchRes.headers.entries()
);
delete headers.connection;
delete headers["transfer-encoding"];
delete headers["content-encoding"];
await cache.set(
signatureString,
Buffer.from(
JSON.stringify({
headers,
body: toBase64(body),
})
)
);
res.status(fetchRes.status);
res.set({ ...headers, "transfer-encoding": undefined });
res.send(Buffer.from(body));
return;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const cachedDataJson = JSON.parse(cachedData.toString());
const headers = { ...cachedDataJson.headers } as Record<string, string>;
delete headers.connection;
delete headers["transfer-encoding"];
delete headers["content-encoding"];
res.status(200);
res.set("Content-Type", headers["content-type"]);
const bodyBuffer = Buffer.from(
cachedDataJson.body as unknown as string,
"base64"
);
res.writeHead(200, headers);
res.end(bodyBuffer);
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
this.express_app.use("/", proxyMiddleware);
const port = PROXY_HOST.split(":")[2];
this.server = this.express_app.listen(port);
console.log(
`Proxy started. Target URL is ${PROXY_TARGET}. Listening on :${port}`
);
}
stop() {
console.log("Stopping proxy...");
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-argument, @typescript-eslint/consistent-type-assertions
return promisify(this.server.close.bind(this.server)).bind(
this.server
)() as Promise<void>;
}
}
let instance: Proxy;
export function getProxy(app: TheApp): Proxy {
if (!instance) {
instance = new Proxy(app);
}
return instance;
}

File Metadata

Mime Type
application/javascript
Expires
Fri, Nov 27, 17:12 (1 d, 15 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1224972
Default Alt Text
proxy.ts (5 KB)

Event Timeline