feat: implement a simple dynamic message system from the background script to the bootloader/kernel

This commit is contained in:
Derrick Hammer 2023-07-18 08:51:18 -04:00
parent 76fabec96a
commit f3f0a8374a
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
2 changed files with 54 additions and 1 deletions

View File

@ -13,4 +13,28 @@ browser.runtime.onInstalled.addListener(() => {
}); });
}); });
browser.runtime.onMessage.addListener(async (request, sender) => {
if (sender.id !== browser.runtime.id) {
return Promise.reject("access denied");
}
if (!("method" in request)) {
return Promise.reject("method required");
}
if (!("data" in request)) {
return Promise.reject("data required");
}
const ret = await queryKernel({
method: request.method,
data: request.data,
});
if (ret?.err) {
throw new Error(ret.err);
}
return ret;
});
boot(); boot();

View File

@ -1,4 +1,6 @@
import { boot } from "./bootloader/kernel.js"; import { boot } from "./bootloader/kernel.js";
import exchangeCommunicationKeys from "./bootloader/messages/exchangeCommunicationKeys.js";
import setLoginKey from "./bootloader/messages/setLoginKey.js";
declare var browser: any; // tsc declare var browser: any; // tsc
@ -8,7 +10,12 @@ header.textContent =
"Something went wrong! You should not be visiting this page, this page should only be accessed via an invisible iframe."; "Something went wrong! You should not be visiting this page, this page should only be accessed via an invisible iframe.";
document.body.appendChild(header); document.body.appendChild(header);
function handleIncomingMessage(event: MessageEvent) { const kernelMessageHandlers = {
exchangeCommunicationKeys,
setLoginKey,
};
async function handleIncomingMessage(event: MessageEvent) {
if (event.source === null) { if (event.source === null) {
return; return;
} }
@ -39,6 +46,28 @@ function handleIncomingMessage(event: MessageEvent) {
); );
return; return;
} }
if (event.data.method in kernelMessageHandlers) {
let response;
try {
response = await kernelMessageHandlers[event.data.method](
event.data.data,
);
} catch (e: any) {
response = { err: (e as Error).message };
}
(event.source as WindowProxy).postMessage(
{
nonce: event.data.nonce,
data: response,
},
event.origin,
);
return;
}
(event.source as WindowProxy).postMessage( (event.source as WindowProxy).postMessage(
{ {
nonce: event.data.nonce, nonce: event.data.nonce,