refactor: update key handling

This commit is contained in:
Derrick Hammer 2023-07-18 06:47:54 -04:00
parent 017a71e942
commit 76fabec96a
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
2 changed files with 41 additions and 22 deletions

View File

@ -1,34 +1,32 @@
import {
addContextToErr,
bufToStr,
downloadObject,
Err,
getActivePortals,
hexToBuf,
} from "@lumeweb/libweb";
import { sendAuthUpdate } from "./util.js";
import { log, logErr } from "@lumeweb/libkernel/kernel";
import { log, logErr, sendAuthUpdate } from "./util.js";
import {
defaultKernelLink,
setBootloaderPortals,
setKernelLoaded,
setLoginComplete,
setUserKey,
} from "./vars.js";
import { getStoredUserKey } from "./storage.js";
export function boot() {
let userKeyString = window.localStorage.getItem("key");
if (userKeyString === null) {
sendAuthUpdate();
return;
}
let [decodedSeed, errHTB] = hexToBuf(userKeyString);
if (errHTB !== null) {
logErr(addContextToErr(errHTB, "seed could not be decoded from hex"));
let userKey;
try {
userKey = getStoredUserKey();
} catch (e) {
logErr(addContextToErr(e, "user key could not be fetched"));
sendAuthUpdate();
return;
}
log("user is already logged in, attempting to load kernel");
setUserKey(userKey as Uint8Array);
setLoginComplete(true);
sendAuthUpdate();
loadKernel();

View File

@ -1,4 +1,4 @@
import { addContextToErr, hexToBuf } from "@lumeweb/libweb";
import { addContextToErr, bytesToHex, hexToBytes } from "@lumeweb/libweb";
import {
getLoginComplete,
getLogoutComplete,
@ -23,18 +23,22 @@ function handleStorage(event: StorageEvent) {
}
if (event.key === "key" && !getLoginComplete()) {
let userKey = window.localStorage.getItem("key");
let userKey;
try {
userKey = getStoredUserKey();
} catch (e) {
logErr(addContextToErr(e, "user key could not be fetched"));
sendAuthUpdate();
return;
}
if (userKey === null) {
sendAuthUpdate();
return;
}
let [decodedKey, errHTB] = hexToBuf(userKey);
if (errHTB !== null) {
logErr(addContextToErr(errHTB, "seed could not be decoded from hex"));
sendAuthUpdate();
return;
}
setUserKey(decodedKey);
setUserKey(userKey);
log("user is now logged in, attempting to load kernel");
setLoginComplete(true);
@ -47,5 +51,22 @@ function handleStorage(event: StorageEvent) {
log("attempting to do a page reload");
reloadKernel();
}
window.addEventListener("storage", handleStorage);
window.addEventListener("storage", (event) => handleStorage(event));
export function saveUserKey(key: Uint8Array) {
window.localStorage.setItem("key", bytesToHex(key));
const event = new StorageEvent("storage", {
key: "key",
});
window.dispatchEvent(event);
}
export function getStoredUserKey() {
const key = window.localStorage.getItem("key");
if (key) {
return hexToBytes(key);
}
return null;
}