diff options
| author | Yulian Kuncheff <670212+daegalus@users.noreply.github.com> | 2025-03-22 23:44:49 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-03-22 18:44:49 -0400 |
| commit | 6156d3d7293a1757725b1d36a89a61ede1ffe850 (patch) | |
| tree | 770109d49181f582fed54ca787ebf959791f1b56 /web/js | |
| parent | af6f05554fe8da112599f30d32524c28a4078cac (diff) | |
| download | anubis-6156d3d7293a1757725b1d36a89a61ede1ffe850.tar.xz anubis-6156d3d7293a1757725b1d36a89a61ede1ffe850.zip | |
Refactor and split out things into cmd and lib (#77)
* Refactor anubis to split business logic into a lib, and cmd to just be direct usage.
* Post-rebase fixes.
* Update changelog, remove unnecessary one.
* lib: refactor this
This is mostly based on my personal preferences for how Go code should
be laid out. I'm not sold on the package name "lib" (I'd call it anubis
but that would stutter), but people are probably gonna import it as
libanubis so it's likely fine.
Packages have been "flattened" to centralize implementation with area of
concern. This goes against the Java-esque style that many people like,
but I think this helps make things simple.
Most notably: the dnsbl client (which is a hack) is an internal package
until it's made more generic. Then it can be made external.
I also fixed the logic such that `go generate` works and rebased on
main.
* internal/test: run tests iff npx exists and DONT_USE_NETWORK is not set
Signed-off-by: Xe Iaso <me@xeiaso.net>
* internal/test: install deps
Signed-off-by: Xe Iaso <me@xeiaso.net>
* .github/workflows: verbose go tests?
Signed-off-by: Xe Iaso <me@xeiaso.net>
* internal/test: sleep 2
Signed-off-by: Xe Iaso <me@xeiaso.net>
* internal/test: nix this test so CI works
Signed-off-by: Xe Iaso <me@xeiaso.net>
* internal/test: warmup per browser?
Signed-off-by: Xe Iaso <me@xeiaso.net>
* internal/test: disable for now :(
Signed-off-by: Xe Iaso <me@xeiaso.net>
* lib/anubis: do not apply bot rules if address check fails
Closes #83
---------
Signed-off-by: Xe Iaso <me@xeiaso.net>
Co-authored-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'web/js')
| -rw-r--r-- | web/js/main.mjs | 89 | ||||
| -rw-r--r-- | web/js/proof-of-work-slow.mjs | 63 | ||||
| -rw-r--r-- | web/js/proof-of-work.mjs | 93 | ||||
| -rw-r--r-- | web/js/video.mjs | 16 |
4 files changed, 261 insertions, 0 deletions
diff --git a/web/js/main.mjs b/web/js/main.mjs new file mode 100644 index 0000000..297f16f --- /dev/null +++ b/web/js/main.mjs @@ -0,0 +1,89 @@ +import processFast from "./proof-of-work.mjs"; +import processSlow from "./proof-of-work-slow.mjs"; +import { testVideo } from "./video.mjs"; + +const algorithms = { + "fast": processFast, + "slow": processSlow, +} + +// from Xeact +const u = (url = "", params = {}) => { + let result = new URL(url, window.location.href); + Object.entries(params).forEach((kv) => { + let [k, v] = kv; + result.searchParams.set(k, v); + }); + return result.toString(); +}; + +const imageURL = (mood, cacheBuster) => + u(`/.within.website/x/cmd/anubis/static/img/${mood}.webp`, { cacheBuster }); + +(async () => { + const status = document.getElementById('status'); + const image = document.getElementById('image'); + const title = document.getElementById('title'); + const spinner = document.getElementById('spinner'); + const anubisVersion = JSON.parse(document.getElementById('anubis_version').textContent); + + // const testarea = document.getElementById('testarea'); + + // const videoWorks = await testVideo(testarea); + // console.log(`videoWorks: ${videoWorks}`); + + // if (!videoWorks) { + // title.innerHTML = "Oh no!"; + // status.innerHTML = "Checks failed. Please check your browser's settings and try again."; + // image.src = imageURL("sad"); + // spinner.innerHTML = ""; + // spinner.style.display = "none"; + // return; + // } + + status.innerHTML = 'Calculating...'; + + const { challenge, rules } = await fetch("/.within.website/x/cmd/anubis/api/make-challenge", { method: "POST" }) + .then(r => { + if (!r.ok) { + throw new Error("Failed to fetch config"); + } + return r.json(); + }) + .catch(err => { + title.innerHTML = "Oh no!"; + status.innerHTML = `Failed to fetch config: ${err.message}`; + image.src = imageURL("sad", anubisVersion); + spinner.innerHTML = ""; + spinner.style.display = "none"; + throw err; + }); + + const process = algorithms[rules.algorithm]; + if (!process) { + title.innerHTML = "Oh no!"; + status.innerHTML = `Failed to resolve check algorithm. You may want to reload the page.`; + image.src = imageURL("sad", anubisVersion); + spinner.innerHTML = ""; + spinner.style.display = "none"; + return; + } + + status.innerHTML = `Calculating...<br/>Difficulty: ${rules.report_as}`; + + const t0 = Date.now(); + const { hash, nonce } = await process(challenge, rules.difficulty); + const t1 = Date.now(); + console.log({ hash, nonce }); + + title.innerHTML = "Success!"; + status.innerHTML = `Done! Took ${t1 - t0}ms, ${nonce} iterations`; + image.src = imageURL("happy", anubisVersion); + spinner.innerHTML = ""; + spinner.style.display = "none"; + + setTimeout(() => { + const redir = window.location.href; + window.location.href = u("/.within.website/x/cmd/anubis/api/pass-challenge", { response: hash, nonce, redir, elapsedTime: t1 - t0 }); + }, 250); +})();
\ No newline at end of file diff --git a/web/js/proof-of-work-slow.mjs b/web/js/proof-of-work-slow.mjs new file mode 100644 index 0000000..e30dc21 --- /dev/null +++ b/web/js/proof-of-work-slow.mjs @@ -0,0 +1,63 @@ +// https://dev.to/ratmd/simple-proof-of-work-in-javascript-3kgm + +export default function process(data, difficulty = 5, _threads = 1) { + console.debug("slow algo"); + return new Promise((resolve, reject) => { + let webWorkerURL = URL.createObjectURL(new Blob([ + '(', processTask(), ')()' + ], { type: 'application/javascript' })); + + let worker = new Worker(webWorkerURL); + + worker.onmessage = (event) => { + worker.terminate(); + resolve(event.data); + }; + + worker.onerror = (event) => { + worker.terminate(); + reject(); + }; + + worker.postMessage({ + data, + difficulty + }); + + URL.revokeObjectURL(webWorkerURL); + }); +} + +function processTask() { + return function () { + const sha256 = (text) => { + const encoded = new TextEncoder().encode(text); + return crypto.subtle.digest("SHA-256", encoded.buffer) + .then((result) => + Array.from(new Uint8Array(result)) + .map((c) => c.toString(16).padStart(2, "0")) + .join(""), + ); + }; + + addEventListener('message', async (event) => { + let data = event.data.data; + let difficulty = event.data.difficulty; + + let hash; + let nonce = 0; + do { + hash = await sha256(data + nonce++); + } while (hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')); + + nonce -= 1; // last nonce was post-incremented + + postMessage({ + hash, + data, + difficulty, + nonce, + }); + }); + }.toString(); +}
\ No newline at end of file diff --git a/web/js/proof-of-work.mjs b/web/js/proof-of-work.mjs new file mode 100644 index 0000000..b4f9c53 --- /dev/null +++ b/web/js/proof-of-work.mjs @@ -0,0 +1,93 @@ +export default function process(data, difficulty = 5, threads = (navigator.hardwareConcurrency || 1)) { + console.debug("fast algo"); + return new Promise((resolve, reject) => { + let webWorkerURL = URL.createObjectURL(new Blob([ + '(', processTask(), ')()' + ], { type: 'application/javascript' })); + + const workers = []; + + for (let i = 0; i < threads; i++) { + let worker = new Worker(webWorkerURL); + + worker.onmessage = (event) => { + workers.forEach(worker => worker.terminate()); + worker.terminate(); + resolve(event.data); + }; + + worker.onerror = (event) => { + worker.terminate(); + reject(); + }; + + worker.postMessage({ + data, + difficulty, + nonce: i, + threads, + }); + + workers.push(worker); + } + + URL.revokeObjectURL(webWorkerURL); + }); +} + +function processTask() { + return function () { + const sha256 = (text) => { + const encoded = new TextEncoder().encode(text); + return crypto.subtle.digest("SHA-256", encoded.buffer); + }; + + function uint8ArrayToHexString(arr) { + return Array.from(arr) + .map((c) => c.toString(16).padStart(2, "0")) + .join(""); + } + + addEventListener('message', async (event) => { + let data = event.data.data; + let difficulty = event.data.difficulty; + let hash; + let nonce = event.data.nonce; + let threads = event.data.threads; + + while (true) { + const currentHash = await sha256(data + nonce); + const thisHash = new Uint8Array(currentHash); + let valid = true; + + for (let j = 0; j < difficulty; j++) { + const byteIndex = Math.floor(j / 2); // which byte we are looking at + const nibbleIndex = j % 2; // which nibble in the byte we are looking at (0 is high, 1 is low) + + let nibble = (thisHash[byteIndex] >> (nibbleIndex === 0 ? 4 : 0)) & 0x0F; // Get the nibble + + if (nibble !== 0) { + valid = false; + break; + } + } + + if (valid) { + hash = uint8ArrayToHexString(thisHash); + console.log(hash); + break; + } + + nonce += threads; + } + + postMessage({ + hash, + data, + difficulty, + nonce, + }); + }); + }.toString(); +} + diff --git a/web/js/video.mjs b/web/js/video.mjs new file mode 100644 index 0000000..59cde1e --- /dev/null +++ b/web/js/video.mjs @@ -0,0 +1,16 @@ +const videoElement = `<video id="videotest" width="0" height="0" src="/.within.website/x/cmd/anubis/static/testdata/black.mp4"></video>`; + +export const testVideo = async (testarea) => { + testarea.innerHTML = videoElement; + return (await new Promise((resolve) => { + const video = document.getElementById('videotest'); + video.oncanplay = () => { + testarea.style.display = "none"; + resolve(true); + }; + video.onerror = (ev) => { + testarea.style.display = "none"; + resolve(false); + }; + })); +};
\ No newline at end of file |
