Created
June 22, 2023 20:34
-
-
Save dfkaye/f36fac99ea557985291ee78cc799cb58 to your computer and use it in GitHub Desktop.
worker that enforces access by address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 21 June 2023 | |
// poc: create a worker that enforces access by address | |
var source = ` | |
self.address; | |
self.onmessage = function (e) { | |
console.warn("init"); | |
if (e.data.action !== 'init') { | |
return console.error("must call init before any other action,", e.data.action); | |
} | |
var blob = new Blob([Date.now()], { type: "text/plain" }); | |
self.address = URL.createObjectURL(blob); | |
self.postMessage(Object.assign({}, { address })); | |
self.onmessage = self.onrequest; | |
} | |
self.onrequest = function (request) { | |
var { action, value = "", address } = Object(request.data); | |
console.log('inside worker', { action, value, address }, address === self.address); | |
if (address !== self.address) { | |
return console.error("invalid request, address does not match,", { action, value, address }); | |
} | |
console.log("correct address for", action); | |
var result = typeof self.actions[action] == 'function' | |
? self.actions[action](value) | |
: ""; | |
if (result) { | |
self.postMessage(Object.assign({ action }, result)); | |
} | |
} | |
self.actions = { | |
echo(value) { | |
console.log('echo:', value); | |
return { value }; | |
} | |
} | |
`; | |
var blob = new Blob([source], { type: "text/javascript" }) | |
var url = URL.createObjectURL(blob); | |
var worker = new Worker(url); | |
URL.revokeObjectURL(url); | |
var address; | |
var oninit = function (e) { | |
console.info("message from worker"); | |
console.warn(e.data.address); | |
address = e.data.address; | |
worker.onmessage = onresponse; | |
} | |
var onresponse = function (response) { | |
console.info("response from worker"); | |
console.warn(response.data); | |
} | |
worker.onmessage = oninit; | |
worker.postMessage({action: 'poke'}); | |
worker.postMessage({action: 'init'}); | |
worker.postMessage({action: 'init'}); | |
worker.postMessage({action: 'init'}); | |
worker.postMessage({action: 'init'}); | |
setTimeout(() => { | |
worker.postMessage({action: 'init'}); | |
worker.postMessage({action: 'echo', value: Date.now(), address}); | |
}, 500); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment