Skip to content

Commit

Permalink
move cookie logic to cookie.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
wearrrrr committed Oct 15, 2024
1 parent ca427c8 commit d3337de
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 21 deletions.
19 changes: 19 additions & 0 deletions src/shared/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,24 @@ export type Cookie = {

export class CookieStore {
private cookies: Record<string, Cookie> = {};
private db: IDBDatabase;

constructor() {
// TOOD: Something is seriously broken with this system, I'm not sure what, but mutating multiple cookies on the same domain seems to break things?
const request = indexedDB.open("$scramjet", 1);

request.onsuccess = () => {
this.db = request.result;

const tx = this.db.transaction("cookies", "readonly");
const store = tx.objectStore("cookies");
const req = store.get("cookies");

req.onsuccess = () => {
if (req.result) this.cookies = req.result;
};
};
}

async setCookies(cookies: string[], url: URL) {
for (const str of cookies) {
Expand All @@ -35,6 +53,7 @@ export class CookieStore {

const id = `${cookie.domain}@${cookie.path}@${cookie.name}`;
this.cookies[id] = cookie;
this.db.transaction("cookies", "readwrite").objectStore("cookies").put(this.cookies, "cookies");
}
}

Expand Down
22 changes: 1 addition & 21 deletions src/worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,6 @@ export class ScramjetServiceWorker extends EventTarget {
super();
this.client = new $scramjet.shared.util.BareClient();

const db = indexedDB.open("$scramjet", 1);

db.onsuccess = () => {
const res = db.result;
const tx = res.transaction("cookies", "readonly");
const store = tx.objectStore("cookies");
const cookies = store.get("cookies");

cookies.onsuccess = () => {
if (cookies.result) {
this.cookieStore.load(cookies.result);
dbg.log("Loaded cookies from IDB!");
}
};
};

addEventListener("message", async ({ data }: { data: MessageC2W }) => {
if (!("scramjet$type" in data)) return;

Expand All @@ -45,11 +29,7 @@ export class ScramjetServiceWorker extends EventTarget {
}

if (data.scramjet$type === "cookie") {
await this.cookieStore.setCookies([data.cookie], new URL(data.url));
const res = db.result;
const tx = res.transaction("cookies", "readwrite");
const store = tx.objectStore("cookies");
store.put(this.cookieStore.dump(), "cookies");
this.cookieStore.setCookies([data.cookie], new URL(data.url));
}
});
}
Expand Down

0 comments on commit d3337de

Please sign in to comment.