ditch base32768 thing, stick to all-js-on-same-host to comply with CSP

This commit is contained in:
forest 2024-12-08 23:46:12 -06:00
parent 1a04d77a54
commit b7b983eb94
11 changed files with 281 additions and 387 deletions

View File

@ -2,7 +2,6 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>📋 Todo List</title> <title>📋 Todo List</title>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<style> <style>
@ -34,7 +33,7 @@
<input type="hidden" name="nonce" /> <input type="hidden" name="nonce" />
<input type="submit" disabled="true" value="Add" /> <input type="submit" disabled="true" value="Add" />
<div class="captcha-container" <div class="captcha-container"
data-sqr-captcha-url="{{ .CaptchaURL }}" data-sqr-captcha-url="http://localhost:8080/"
data-sqr-captcha-challenge="{{ .Challenge }}" data-sqr-captcha-challenge="{{ .Challenge }}"
data-sqr-captcha-callback="myCaptchaCallback"> data-sqr-captcha-callback="myCaptchaCallback">
</div> </div>
@ -48,6 +47,31 @@
document.querySelector("form input[type='submit']").disabled = false; document.querySelector("form input[type='submit']").disabled = false;
}; };
</script> </script>
<script src="{{ .CaptchaURL }}/static/captcha.js"></script> <script src="/static/captcha.js"></script>
<!-- <script src='./static/scrypt_wasm.js'></script>
<script>
const { scrypt } = wasm_bindgen;
async function run() {
console.log("a");
await wasm_bindgen();
console.log(scrypt(hexEncode('password in hex'), hexEncode('password in hex'), 4096, 8, 1, 16))
}
run();
function hexEncode(s){
var hex, i;
var result = "";
for (i=0; i<s.length; i++) {
hex = s.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
</script> -->
</body> </body>
</html> </html>

View File

@ -26,7 +26,6 @@ var items []string
// 5 bits of difficulty, 1 in 2^6 (1 in 32) tries will succeed on average. // 5 bits of difficulty, 1 in 2^6 (1 in 32) tries will succeed on average.
// //
// 8 bits of difficulty would be ok for apps that are never used on mobile phones, 6 is better suited for mobile apps // 8 bits of difficulty would be ok for apps that are never used on mobile phones, 6 is better suited for mobile apps
//
const captchaDifficultyLevel = 5 const captchaDifficultyLevel = 5
func main() { func main() {
@ -56,6 +55,8 @@ func main() {
panic(errors.Wrap(err, "can't start the app because can't open the template file. Are you in the right directory? ")) panic(errors.Wrap(err, "can't start the app because can't open the template file. Are you in the right directory? "))
} }
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("../static/"))))
http.HandleFunc("/", func(responseWriter http.ResponseWriter, request *http.Request) { http.HandleFunc("/", func(responseWriter http.ResponseWriter, request *http.Request) {
// The user submitted a POST request, attempting to add a new item to the list // The user submitted a POST request, attempting to add a new item to the list

View File

@ -1,7 +1,10 @@
// IN ORDER FOR CHANGES TO THIS FILE TO "TAKE" AND BE USED IN THE APP, THE BUILD IN wasm_build HAS TO BE RE-RUN // IN ORDER FOR CHANGES TO THIS FILE TO "TAKE" AND BE USED IN THE APP, THE BUILD IN wasm_build HAS TO BE RE-RUN
// scrypt and scryptPromise will be filled out by js code that gets appended below this script by the wasm_build process // scrypt and scryptPromise will be filled out by js code that gets appended below this script by the wasm_build process
// --- snip ---
let scrypt; let scrypt;
let scryptPromise; let scryptPromise;

View File

@ -135,19 +135,20 @@
if(url) { if(url) {
// https://stackoverflow.com/questions/21913673/execute-web-worker-from-different-origin/62914052#62914052 // // https://stackoverflow.com/questions/21913673/execute-web-worker-from-different-origin/62914052#62914052
const webWorkerUrlWhichIsProbablyCrossOrigin = `${url}/static/proofOfWorker.js`; // const webWorkerUrlWhichIsProbablyCrossOrigin = `${url}/static/proofOfWorker.js`;
const webWorkerPointerDataURL = URL.createObjectURL( // const webWorkerPointerDataURL = URL.createObjectURL(
new Blob( // new Blob(
[ `importScripts( "${ webWorkerUrlWhichIsProbablyCrossOrigin }" );` ], // [ `importScripts( "${ webWorkerUrlWhichIsProbablyCrossOrigin }" );` ],
{ type: "text/javascript" } // { type: "text/javascript" }
) // )
); // );
// return
let webWorkers; let webWorkers;
webWorkers = [...Array(numberOfWebWorkersToCreate)].map((_, i) => { webWorkers = [...Array(numberOfWebWorkersToCreate)].map((_, i) => {
const webWorker = new Worker(webWorkerPointerDataURL); const webWorker = new Worker('/static/proofOfWorker.js');
webWorker.onmessage = function(e) { webWorker.onmessage = function(e) {
const challengeState = challengesMap[e.data.challenge] const challengeState = challengesMap[e.data.challenge]
if(!challengeState) { if(!challengeState) {
@ -212,7 +213,7 @@
return webWorker; return webWorker;
}); });
URL.revokeObjectURL(webWorkerPointerDataURL); // URL.revokeObjectURL(webWorkerPointerDataURL);
proofOfWorker = { proofOfWorker = {
postMessage: arg => webWorkers.forEach((x, i) => { postMessage: arg => webWorkers.forEach((x, i) => {

File diff suppressed because one or more lines are too long

BIN
static/scrypt.wasm Normal file

Binary file not shown.

BIN
static/scrypt_wasm_bg.wasm Normal file

Binary file not shown.

View File

@ -29,26 +29,30 @@ fi
if [ ! -d pkg ]; then if [ ! -d pkg ]; then
printf "running Makefile for MyEtherWallet/scrypt-wasm... \n" printf "running Makefile for MyEtherWallet/scrypt-wasm... \n"
make rustup target add wasm32-unknown-unknown
cargo install wasm-pack --force
wasm-pack build --target no-modules
fi fi
cd ../ cd ../
nodejs_is_installed="$(which node | wc -l)" cp scrypt-wasm/pkg/scrypt_wasm_bg.wasm ../static/
npm_is_installed="$(which npm | wc -l)"
if [ "$nodejs_is_installed" == "0" ] || [ "$npm_is_installed" == "0" ]; then echo '
printf "nodejs and npm are required for the next step. Please install them manually 😇" // THIS FILE IS GENERATED AUTOMATICALLY
exit 1 // Dont edit this file by hand.
fi // Either edit proofOfWorkerStub.js or edit the build located in the wasm_build folder.
' > ../static/proofOfWorker.js
if [ ! -d node_modules ]; then cat ../proofOfWorkerStub.js | tail -n +6 >> ../static/proofOfWorker.js
printf "running npm install \n"
npm install
fi
node build_wasm_webworker.js > "../static/proofOfWorker.js" cat scrypt-wasm/pkg/scrypt_wasm.js >> ../static/proofOfWorker.js
printf "\n\nbuilt ../static/proofOfWorker.js successfully!\n\n" # see: https://rustwasm.github.io/docs/wasm-bindgen/examples/without-a-bundler.html
echo '
scrypt = wasm_bindgen.scrypt;
scryptPromise = wasm_bindgen({module_or_path: "/static/scrypt.wasm"});
' >> ../static/proofOfWorker.js
echo "Build successful!"

View File

@ -1,64 +0,0 @@
const base32768 = require('base32768');
const fs = require('fs');
const base32768WASM = base32768.encode(fs.readFileSync("scrypt-wasm/pkg/scrypt_wasm_bg.wasm"));
const wasmWrappperJS = fs.readFileSync("scrypt-wasm/pkg/scrypt_wasm_bg.js", { encoding: "utf8" });
let lines = wasmWrappperJS.split("\n");
// filter out the first line "import * as wasm from './scrypt_wasm_bg.wasm';"
// because we are using global namespace, not es6 modules
lines = lines.filter(line => !line.includes("scrypt_wasm_bg.wasm"))
// replace export with global namespace for the same reason.
lines = lines.map(line => {
if(line.startsWith("export function scrypt")) {
return line.replace("export function scrypt", "scrypt = function");
}
return line;
});
const customWASMWrappperJS = lines.join("\n");
// --------------------------------------------------------------------------
// Output the composited webworker JS
// first, include the warning about this file being automatically generated
console.log(`
// THIS FILE IS GENERATED AUTOMATICALLY
// Don't edit this file by hand.
// Either edit proofOfWorkerStub.js or edit the build located in the wasm_build folder.
`)
// add the actual webworker logic at the top, while filtering out comments
const stubJS = fs.readFileSync("../proofOfWorkerStub.js", { encoding: "utf8" });
console.log(stubJS.split("\n").filter(x => !x.startsWith("//")).join("\n"));
console.log(`
// Everything below this line is created by the build scripts in the wasm_build folder.
`)
// Now its time to load the wasm module.
// first, load the base32768 module into a global variable called "base32768"
console.log(fs.readFileSync("node_modules/base32768/dist/iife/base32768.js", { encoding: "utf8" }))
// now, decode the base32768 string into an ArrayBuffer and tell WebAssembly to load it
console.log(`
const base32768WASM = "${base32768WASM}";
const wasmBinary = base32768.decode(base32768WASM);
scryptPromise = WebAssembly.instantiate(wasmBinary, {}).then(instantiatedModule => {
const wasm = instantiatedModule.instance.exports;
`);
// Output the WASM wrapper JS code that came from the Rust WASM compiler,
// slightly modified to use global namespace instead of es6 modules
console.log(customWASMWrappperJS.split("\n").map(x => ` ${x}`).join("\n"));
// finish off by closing scryptPromise
console.log("});");

View File

@ -1,13 +0,0 @@
{
"name": "wasm_build",
"version": "0.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"base32768": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/base32768/-/base32768-2.0.1.tgz",
"integrity": "sha512-DfpYn6XUE8YSsooJ4rj61EiTKkPJM1exxxbJB0byWvRc39ogWDZtrOSY0PVvGQe+DI1FZt10ES7xBifxmirqwQ=="
}
}
}

View File

@ -1,14 +0,0 @@
{
"name": "wasm_build",
"version": "0.0.0",
"description": "build wasm module into webworker",
"main": "build_wasm_webworker.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "GPL-3.0-or-later",
"dependencies": {
"base32768": "^2.0.1"
}
}