rentgen/memory.ts

58 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-10-03 09:03:56 +02:00
import ExtendedRequest from "./extended-request";
import { getshorthost } from "./util";
import { EventEmitter } from "events";
2021-10-03 16:33:23 +02:00
import { RequestCluster } from "./request-cluster";
2021-10-03 09:03:56 +02:00
class Memory extends EventEmitter {
2021-11-06 21:48:25 +01:00
origin_to_history = {} as Record<string, Record<string, RequestCluster>>;
2021-10-03 09:03:56 +02:00
async register(request: ExtendedRequest) {
2021-10-04 18:51:51 +02:00
await request.init();
2021-11-06 21:48:25 +01:00
console.log("registering request for", request.origin);
if (!request.isThirdParty()) {
return;
2021-10-03 09:03:56 +02:00
}
2021-11-06 21:48:25 +01:00
if (!this.origin_to_history[request.origin]) {
this.origin_to_history[request.origin] = {};
}
const shorthost = getshorthost(new URL(request.url).host);
if (!this.origin_to_history[request.origin][shorthost]) {
const cluster = new RequestCluster(shorthost);
this.origin_to_history[request.origin][shorthost] = cluster;
}
this.origin_to_history[request.origin][shorthost].add(request);
this.emit("change");
2021-10-03 09:03:56 +02:00
}
constructor() {
super();
browser.webRequest.onBeforeSendHeaders.addListener(
async (request) => {
this.register(new ExtendedRequest(request));
},
{ urls: ["<all_urls>"] },
["requestHeaders"]
);
}
2021-11-06 21:48:25 +01:00
getClustersForOrigin(origin: string): Record<string, RequestCluster> {
return this.origin_to_history[origin] || {};
}
async removeCookiesFor(origin: string, shorthost?: string): Promise<void> {
const clusters = this.getClustersForOrigin(origin);
await Promise.all(
Object.values(clusters)
.filter((cluster) => !shorthost || cluster.id === shorthost)
.map((cluster) => cluster.removeAllCookies())
);
}
async removeRequestsFor(origin: string) {
this.origin_to_history[origin] = {};
2021-10-03 09:03:56 +02:00
}
}
const memory = new Memory();
export default memory;