feat: add shared typescript utility methods, and stores for ui layer

This commit is contained in:
Derrick Hammer 2023-07-25 11:52:32 -04:00
parent af1a34e510
commit 7a729934dd
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
3 changed files with 92 additions and 0 deletions

46
shared/keys.ts Normal file
View File

@ -0,0 +1,46 @@
import { x25519 } from "@noble/curves/ed25519";
import {
getCommunicationKey,
getRemoteCommunicationKey,
setCommunicationKey,
setRemoteCommunicationKey,
} from "./vars.js";
import { queryBackground } from "./util.js";
import { bytesToHex, hexToBytes, randomBytes } from "@lumeweb/libweb";
import { secretbox } from "@noble/ciphers/salsa";
export function generateCommunicationKey() {
return x25519.utils.randomPrivateKey();
}
export async function exchangeCommunicationKeys() {
if (!getCommunicationKey()) {
setCommunicationKey(generateCommunicationKey());
}
const pubKey = await queryBackground(
"exchangeCommunicationKeys",
bytesToHex(x25519.getPublicKey(getCommunicationKey())),
);
if (!pubKey) {
throw new Error("could not get communication key");
}
setRemoteCommunicationKey(hexToBytes(pubKey));
}
export async function setLoginKey(key: Uint8Array) {
const privKey = getCommunicationKey();
const pubKey = getRemoteCommunicationKey();
const secret = x25519.getSharedSecret(privKey, pubKey);
const nonce = randomBytes(24);
const box = secretbox(secret, nonce);
const ciphertext = box.seal(key);
await queryBackground("setLoginKey", {
data: bytesToHex(ciphertext),
nonce: bytesToHex(nonce),
});
}

29
shared/util.ts Normal file
View File

@ -0,0 +1,29 @@
import browser from "webextension-polyfill";
import { createClient } from "@lumeweb/kernel-swarm-client";
let swarmClient = createClient();
export async function queryBackground(method: string, data = {}) {
let resp;
try {
resp = await browser.runtime.sendMessage({
method,
data,
});
} catch (e) {
throw e;
}
return resp;
}
export async function waitForBoot() {
await queryBackground("waitForBoot");
}
export async function waitForConnected(cb?: Function) {
await waitForBoot();
await swarmClient.ready();
await cb?.();
}

17
shared/vars.ts Normal file
View File

@ -0,0 +1,17 @@
let communicationKey: Uint8Array;
let remoteCommunicationKey: Uint8Array;
export function setCommunicationKey(key: Uint8Array) {
communicationKey = key;
}
export function getCommunicationKey() {
return communicationKey;
}
export function setRemoteCommunicationKey(key: Uint8Array) {
remoteCommunicationKey = key;
}
export function getRemoteCommunicationKey() {
return remoteCommunicationKey;
}