Import Anubis v1.28.2
Replace the tree with upstream TecharoHQ/anubis v1.28.2 (a1384fbf42e3). Masyunis customizations are re-applied in the following commits.
This commit is contained in:
1 parent
eb3e46d8d0
commit
e07de898cd
573 files changed
+35846
-6807
No files matched your search
+16
-85
@@ -1,95 +1,26 @@
|
||||
type ProgressCallback = (nonce: number) => void;
|
||||
import {
|
||||
ProgressCallback,
|
||||
ProcessOptions,
|
||||
ProcessResult,
|
||||
defaultThreads,
|
||||
runWorkers,
|
||||
} from "@lib/worker";
|
||||
|
||||
interface ProcessOptions {
|
||||
basePrefix: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
const getHardwareConcurrency = () =>
|
||||
navigator.hardwareConcurrency !== undefined
|
||||
? navigator.hardwareConcurrency
|
||||
: 1;
|
||||
|
||||
export default function process(
|
||||
export default async function process(
|
||||
options: ProcessOptions,
|
||||
data: string,
|
||||
difficulty: number = 5,
|
||||
signal: AbortSignal | null = null,
|
||||
progressCallback?: ProgressCallback,
|
||||
threads: number = Math.trunc(Math.max(getHardwareConcurrency() / 2, 1)),
|
||||
): Promise<string> {
|
||||
threads: number = defaultThreads(),
|
||||
): Promise<ProcessResult> {
|
||||
console.debug("fast algo");
|
||||
|
||||
// Choose worker based on secure context.
|
||||
// Use the WebCrypto worker if the page is a secure context; otherwise fall back to pure‑JS.
|
||||
let workerMethod: "webcrypto" | "purejs" = "purejs";
|
||||
if (window.isSecureContext) {
|
||||
workerMethod = "webcrypto";
|
||||
}
|
||||
|
||||
if (
|
||||
navigator.userAgent.includes("Firefox") ||
|
||||
navigator.userAgent.includes("Goanna")
|
||||
) {
|
||||
console.log("Firefox detected, using pure-JS fallback");
|
||||
workerMethod = "purejs";
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let webWorkerURL = `${options.basePrefix}/.within.website/x/cmd/anubis/static/js/worker/sha256-${workerMethod}.mjs?cacheBuster=${options.version}`;
|
||||
|
||||
const workers: Worker[] = [];
|
||||
let settled = false;
|
||||
|
||||
const onAbort = () => {
|
||||
console.log("PoW aborted");
|
||||
cleanup();
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
workers.forEach((w) => w.terminate());
|
||||
if (signal != null) {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
};
|
||||
|
||||
if (signal != null) {
|
||||
if (signal.aborted) {
|
||||
return onAbort();
|
||||
}
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
|
||||
for (let i = 0; i < threads; i++) {
|
||||
let worker = new Worker(webWorkerURL);
|
||||
|
||||
worker.onmessage = (event) => {
|
||||
if (typeof event.data === "number") {
|
||||
progressCallback?.(event.data);
|
||||
} else {
|
||||
cleanup();
|
||||
resolve(event.data);
|
||||
}
|
||||
};
|
||||
|
||||
worker.onerror = (event) => {
|
||||
cleanup();
|
||||
reject(event);
|
||||
};
|
||||
|
||||
worker.postMessage({
|
||||
data,
|
||||
difficulty,
|
||||
nonce: i,
|
||||
threads,
|
||||
});
|
||||
|
||||
workers.push(worker);
|
||||
}
|
||||
return runWorkers({
|
||||
webWorkerURL: `${options.basePrefix}/.within.website/x/cmd/anubis/static/js/worker/sha256.mjs?cacheBuster=${options.version}`,
|
||||
message: { data, difficulty },
|
||||
threads,
|
||||
signal,
|
||||
progressCallback,
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import fast from "./fast";
|
||||
import wasm from "./wasm";
|
||||
|
||||
export default {
|
||||
fast: fast,
|
||||
slow: fast, // XXX(Xe): slow is deprecated, but keep this around in case anything goes bad
|
||||
};
|
||||
// These names must match the ones lib/challenge/wasm registers server side.
|
||||
argon2id: wasm,
|
||||
hashx: wasm,
|
||||
sha256: wasm,
|
||||
} as Record<string, any>;
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
ProgressCallback,
|
||||
ProcessOptions,
|
||||
ProcessResult,
|
||||
defaultThreads,
|
||||
runWorkers,
|
||||
} from "@lib/worker";
|
||||
import { fetchWithBackoff } from "@lib/backoff";
|
||||
import { simd } from "wasm-feature-detect";
|
||||
import isWASMSupported from "@lib/wasm-supported";
|
||||
import wasm2js from "./wasm2js";
|
||||
|
||||
// compileModule fetches and compiles the WebAssembly module for an algorithm.
|
||||
//
|
||||
// The module comes from the same server that is already being hammered, so it
|
||||
// gets the same exponential backoff treatment as every other challenge asset.
|
||||
const compileModule = async (
|
||||
url: string,
|
||||
signal: AbortSignal | null,
|
||||
): Promise<WebAssembly.Module> => {
|
||||
const response = await fetchWithBackoff(url, { signal });
|
||||
|
||||
try {
|
||||
return await WebAssembly.compileStreaming(response.clone());
|
||||
} catch (err) {
|
||||
// XXX(Xe): compileStreaming insists on an `application/wasm` Content-Type.
|
||||
// Anubis serves that, but middleware in front of Anubis has been known to
|
||||
// rewrite it. Buffering the whole module works regardless.
|
||||
console.warn(
|
||||
"anubis: streaming WebAssembly compilation failed, buffering instead",
|
||||
err,
|
||||
);
|
||||
return await WebAssembly.compile(await response.arrayBuffer());
|
||||
}
|
||||
};
|
||||
|
||||
export default async function process(
|
||||
options: ProcessOptions,
|
||||
data: string,
|
||||
difficulty: number = 5,
|
||||
signal: AbortSignal | null = null,
|
||||
progressCallback?: ProgressCallback,
|
||||
threads: number = defaultThreads(),
|
||||
): Promise<ProcessResult> {
|
||||
const { basePrefix, version, algorithm } = options;
|
||||
|
||||
if (!isWASMSupported) {
|
||||
return wasm2js(
|
||||
options,
|
||||
data,
|
||||
difficulty,
|
||||
signal,
|
||||
progressCallback,
|
||||
threads,
|
||||
);
|
||||
}
|
||||
|
||||
const wasmFeatures = (await simd()) ? "simd128" : "baseline";
|
||||
const module = await compileModule(
|
||||
`${basePrefix}/.within.website/x/cmd/anubis/static/wasm/${wasmFeatures}/${algorithm}.wasm?cacheBuster=${version}`,
|
||||
signal,
|
||||
);
|
||||
|
||||
return runWorkers({
|
||||
webWorkerURL: `${basePrefix}/.within.website/x/cmd/anubis/static/js/worker/wasm.mjs?cacheBuster=${version}`,
|
||||
message: { data, difficulty, algorithm, module },
|
||||
threads,
|
||||
signal,
|
||||
progressCallback,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
ProgressCallback,
|
||||
ProcessOptions,
|
||||
ProcessResult,
|
||||
defaultThreads,
|
||||
runWorkers,
|
||||
} from "@lib/worker";
|
||||
|
||||
export default function process(
|
||||
options: ProcessOptions,
|
||||
data: string,
|
||||
difficulty: number = 5,
|
||||
signal: AbortSignal | null = null,
|
||||
progressCallback?: ProgressCallback,
|
||||
threads: number = defaultThreads(),
|
||||
): Promise<ProcessResult> {
|
||||
const { basePrefix, version, algorithm } = options;
|
||||
|
||||
return runWorkers({
|
||||
webWorkerURL: `${basePrefix}/.within.website/x/cmd/anubis/static/js/worker/wasm2js.mjs?cacheBuster=${version}`,
|
||||
message: { data, difficulty, algorithm },
|
||||
threads,
|
||||
signal,
|
||||
progressCallback,
|
||||
});
|
||||
}
|
||||
+4
-1
@@ -56,7 +56,10 @@ const benchmarkTrial = async (stats, difficulty, algorithm, signal) => {
|
||||
|
||||
const t0 = performance.now();
|
||||
const { hash, nonce } = await process(
|
||||
{ basePrefix: "/", version: "devel" },
|
||||
// basePrefix is joined as `${basePrefix}/.within.website/...`, so "/" here
|
||||
// produces a protocol-relative "//.within.website/..." URL rather than a
|
||||
// same-origin one.
|
||||
{ basePrefix: "", version: "devel", algorithm },
|
||||
challenge,
|
||||
Number(difficulty),
|
||||
signal,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
||||
@@ -0,0 +1,182 @@
|
||||
// Retry helpers for fetching challenge assets.
|
||||
//
|
||||
// In order to load things reliably, Anubis needs to have the ability to load
|
||||
// JavaScript and other assets using exponential backoff as the assets every
|
||||
// challenge page needs come from the same server that's also being hammered.
|
||||
// Due to facts and circumstances dating back to the legacy design of the proof
|
||||
// of work client code, any failure of loading any assets causes the entire
|
||||
// process to fail, which causes an error for the client, which makes the user
|
||||
// refresh the page, which adds yet more load.
|
||||
//
|
||||
// These helpers make those fetches survive transient failures at the cost of
|
||||
// using sleep-based exponential backoff, which is an acceptable tradeoff.
|
||||
|
||||
export interface BackoffOptions {
|
||||
attempts?: number;
|
||||
baseDelayMs?: number;
|
||||
maxDelayMs?: number;
|
||||
signal?: AbortSignal | null;
|
||||
}
|
||||
|
||||
const DEFAULT_ATTEMPTS = 5;
|
||||
const DEFAULT_BASE_DELAY_MS = 750;
|
||||
const DEFAULT_MAX_DELAY_MS = 10000;
|
||||
|
||||
// HTTP status codes that make the request work retrying. Everything else is
|
||||
// considered a permanent error and not retried.
|
||||
const RETRYABLE_STATUSES = [
|
||||
408, // Request Timeout
|
||||
425, // Too Early
|
||||
429, // Too Many Requests
|
||||
500, // Internal Server Error
|
||||
502, // Bad Gateway
|
||||
503, // Service Unavailable
|
||||
504, // Gateway Timeout
|
||||
];
|
||||
|
||||
// XXX(Xe): we need to check the exception by name rather than by
|
||||
// `instanceof DOMException` because not every engine that can abort a `fetch`
|
||||
// throws a `DOMException` to signal it. I hate it too.
|
||||
export const isAbortError = (err: unknown): boolean =>
|
||||
err != null && typeof err === "object" && (err as any).name === "AbortError";
|
||||
|
||||
const abortError = () => new DOMException("Aborted", "AbortError");
|
||||
|
||||
/** sleep resolves after ms milliseconds, or rejects early if signal aborts. */
|
||||
export const sleep = (ms: number, signal?: AbortSignal | null): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (signal != null && signal.aborted) {
|
||||
reject(abortError());
|
||||
return;
|
||||
}
|
||||
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(abortError());
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
if (signal != null) {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
resolve();
|
||||
}, ms);
|
||||
|
||||
if (signal != null) {
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* backoffDelay returns a "full jitter" exponential backoff delay.
|
||||
*
|
||||
* This ensures that clients retry actions with exponential backoff
|
||||
* including random jitter in order to avoid thundering herd problems.
|
||||
*
|
||||
* This maxes out at `maxDelayMs` so that you can set the maximum
|
||||
* delay threshold to improve user experience.
|
||||
*/
|
||||
export const backoffDelay = (
|
||||
attempt: number,
|
||||
baseDelayMs: number = DEFAULT_BASE_DELAY_MS,
|
||||
maxDelayMs: number = DEFAULT_MAX_DELAY_MS,
|
||||
): number =>
|
||||
Math.random() * Math.min(maxDelayMs, baseDelayMs * Math.pow(attempt, 2));
|
||||
|
||||
/**
|
||||
* retryAfterMs parses a Retry-After header into milliseconds, in either the
|
||||
* delta-seconds or the HTTP-date form. Returns null when absent or unparseable.
|
||||
*
|
||||
* Anubis doesn't currently return this header, but HTTP middleware in the critical
|
||||
* path may end up doing so. In order to be defensive it is better to just handle
|
||||
* this before it becomes an issue.
|
||||
*/
|
||||
const retryAfterMs = (response: Response): number | null => {
|
||||
const header = response.headers.get("Retry-After");
|
||||
if (header === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const seconds = Number(header);
|
||||
if (Number.isFinite(seconds)) {
|
||||
return Math.max(0, seconds * 1000);
|
||||
}
|
||||
|
||||
const deadline = Date.parse(header);
|
||||
if (Number.isNaN(deadline)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Math.max(0, deadline - Date.now());
|
||||
};
|
||||
|
||||
/**
|
||||
* fetchWithBackoff attempts to do a basic GET fetch of url, retrying
|
||||
* transient failures with jittered exponential backoff. It rejects with
|
||||
* the last error once attempts are exhausted, immediately on a
|
||||
* non-retryable status code, or with an AbortError if the cancellation
|
||||
* signal fires.
|
||||
*/
|
||||
export const fetchWithBackoff = async (
|
||||
url: string,
|
||||
options: BackoffOptions = {},
|
||||
): Promise<Response> => {
|
||||
// populate default options
|
||||
const attempts = options.attempts ?? DEFAULT_ATTEMPTS;
|
||||
const baseDelayMs = options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
|
||||
const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
|
||||
const signal = options.signal ?? null;
|
||||
|
||||
let lastError: Error = new Error(`anubis: ${url} could not be fetched`);
|
||||
|
||||
// If the server told us how long to wait, we wait for this number of
|
||||
// milliseconds instead of using the computed exponential backoff.
|
||||
let serverDelayMs: number | null = null;
|
||||
|
||||
for (let attempt = 0; attempt < attempts; attempt++) {
|
||||
if (attempt > 0) {
|
||||
const delay =
|
||||
serverDelayMs !== null
|
||||
? serverDelayMs
|
||||
: backoffDelay(attempt - 1, baseDelayMs, maxDelayMs);
|
||||
serverDelayMs = null;
|
||||
await sleep(delay, signal);
|
||||
}
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, signal === null ? {} : { signal });
|
||||
} catch (err) {
|
||||
if (isAbortError(err)) {
|
||||
throw err;
|
||||
}
|
||||
// If there is a network-level failure such as DNS resolution failure,
|
||||
// connection reset, or a server hang-up: this is the signature of an
|
||||
// overloaded server. Keep trying after backing off.
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
return response;
|
||||
}
|
||||
|
||||
lastError = new Error(
|
||||
`anubis: ${url} returned HTTP ${response.status} (unretryable failure)`,
|
||||
);
|
||||
|
||||
if (RETRYABLE_STATUSES.indexOf(response.status) === -1) {
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
// XXX(Xe): Honor the server's Retry-After response header but use common
|
||||
// sense: a misconfigured (or actively hostile) upstream should not be
|
||||
// able to park the client for an hour or something ridiculous like that.
|
||||
const requested = retryAfterMs(response);
|
||||
if (requested !== null) {
|
||||
serverDelayMs = Math.min(requested, maxDelayMs);
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
declare global {
|
||||
interface Window {
|
||||
// Work registered by challenge extension scripts.
|
||||
__anubisExtensions?: Promise<unknown>[];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an extension with the global Anubis extensions array.
|
||||
*
|
||||
* This makes challenge passing block on extension functions
|
||||
* finishing.
|
||||
*
|
||||
* @param ext - the async promise associated with the extension.
|
||||
*/
|
||||
export function registerExtension(ext: Promise<unknown>) {
|
||||
window.__anubisExtensions ??= [];
|
||||
window.__anubisExtensions.push(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for challenge extensions to finish work and submit data to
|
||||
* the server. Gives up after timeoutMs.
|
||||
*
|
||||
* Choose timeoutMs carefully, a longer value makes clients wait
|
||||
* longer, which can cause user complaints.
|
||||
*
|
||||
* @param [timeoutMs=5000] - the timeout for extension functions
|
||||
*/
|
||||
export async function waitForExtensions(timeoutMs: number = 5000): Promise<void> {
|
||||
const pending = window.__anubisExtensions ?? [];
|
||||
if (pending.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// XXX(Xe): Normally you'd use Promise.allSettled here, but that is
|
||||
// a Chrome 76 feature. CI tests down to Chrome 75 and for safety's
|
||||
// sake the JS is compiled with Chrome 66 in mind. As such, polyfill
|
||||
// Promise.allSettled by just mapping over the pending promises the
|
||||
// hard way.
|
||||
const settled = Promise.all(
|
||||
pending.map(p => Promise.resolve(p).catch(() => undefined))
|
||||
);
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined = undefined;
|
||||
const timeout = new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, timeoutMs);
|
||||
});
|
||||
|
||||
await Promise.race([settled, timeout]);
|
||||
clearTimeout(timer);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// https://stackoverflow.com/questions/47879864/how-can-i-check-if-a-browser-supports-webassembly
|
||||
const isWASMSupported = (() => {
|
||||
try {
|
||||
if (
|
||||
typeof WebAssembly === "object" &&
|
||||
typeof WebAssembly.instantiate === "function"
|
||||
) {
|
||||
const module = new WebAssembly.Module(
|
||||
Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00),
|
||||
);
|
||||
if (module instanceof WebAssembly.Module)
|
||||
return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
|
||||
}
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
})();
|
||||
|
||||
export default isWASMSupported;
|
||||
|
||||
export class WASMUnsupportedError extends Error {
|
||||
constructor() {
|
||||
super(
|
||||
"WebAssembly is not supported in this browser. This is not a bug in Anubis. Please contact the system administrator for help.",
|
||||
);
|
||||
this.name = "WASMUnsupportedError";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { WorkerArgs } from "./worker";
|
||||
|
||||
export interface AnubisExports {
|
||||
anubis_work: (
|
||||
difficulty: number,
|
||||
initialNonce: number,
|
||||
threads: number,
|
||||
) => number;
|
||||
data_ptr: () => number;
|
||||
result_hash_ptr: () => number;
|
||||
result_hash_size: () => number;
|
||||
set_data_length: (len: number) => void;
|
||||
memory: WebAssembly.Memory;
|
||||
}
|
||||
|
||||
export interface Args extends WorkerArgs {
|
||||
module: WebAssembly.Module;
|
||||
}
|
||||
|
||||
export interface Wasm2JSArgs extends WorkerArgs {
|
||||
algorithm: string;
|
||||
}
|
||||
|
||||
export function uint8ArrayToHex(arr: Uint8Array) {
|
||||
return Array.from(arr)
|
||||
.map((c) => c.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
export function hexToUint8Array(hexString: string): Uint8Array {
|
||||
// Remove whitespace and optional '0x' prefix
|
||||
hexString = hexString.replace(/\s+/g, "").replace(/^0x/, "");
|
||||
|
||||
// Check for valid length
|
||||
if (hexString.length % 2 !== 0) {
|
||||
throw new Error("Invalid hex string length");
|
||||
}
|
||||
|
||||
// Check for valid characters
|
||||
if (!/^[0-9a-fA-F]+$/.test(hexString)) {
|
||||
throw new Error("Invalid hex characters");
|
||||
}
|
||||
|
||||
// Convert to Uint8Array
|
||||
const byteArray = new Uint8Array(hexString.length / 2);
|
||||
for (let i = 0; i < byteArray.length; i++) {
|
||||
const byteValue = parseInt(hexString.substr(i * 2, 2), 16);
|
||||
byteArray[i] = byteValue;
|
||||
}
|
||||
|
||||
return byteArray;
|
||||
}
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
// The generated types for .wasm.js files match the C ABI for
|
||||
// the Rust modules. This makes Typescript shut up and accept it.
|
||||
|
||||
declare module "*.wasm.js" {
|
||||
type AnubisExports = import("@lib/wasm").AnubisExports;
|
||||
|
||||
export const anubis_work: AnubisExports["anubis_work"];
|
||||
export const data_ptr: AnubisExports["data_ptr"];
|
||||
export const result_hash_ptr: AnubisExports["result_hash_ptr"];
|
||||
export const result_hash_size: AnubisExports["result_hash_size"];
|
||||
export const set_data_length: AnubisExports["set_data_length"];
|
||||
export const memory: AnubisExports["memory"];
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
import { fetchWithBackoff, isAbortError } from "@lib/backoff";
|
||||
|
||||
export const getHardwareConcurrency = () =>
|
||||
navigator.hardwareConcurrency !== undefined
|
||||
? navigator.hardwareConcurrency
|
||||
: 1;
|
||||
|
||||
export type ProgressCallback = (nonce: number | string) => void;
|
||||
|
||||
export interface ProcessOptions {
|
||||
basePrefix: string;
|
||||
version: string;
|
||||
algorithm: string;
|
||||
}
|
||||
|
||||
export interface ProcessResult {
|
||||
hash: string;
|
||||
// The WASM workers don't echo the challenge data back, only the sha256
|
||||
// workers do. Nothing reads it, so it's optional rather than a lie.
|
||||
data?: string;
|
||||
difficulty: number;
|
||||
nonce: number;
|
||||
}
|
||||
|
||||
export interface WorkerArgs {
|
||||
data: string;
|
||||
difficulty: number;
|
||||
nonce: number;
|
||||
threads: number;
|
||||
}
|
||||
|
||||
// A spawner hands out workers that all run the same script. Which flavour of
|
||||
// spawner we get depends on whether we could pre-fetch the worker source.
|
||||
export interface WorkerSpawner {
|
||||
// spawn a single worker based on the template
|
||||
spawn: () => Worker;
|
||||
// demote to fallback/less efficient logic instead of using more efficient
|
||||
// logic.
|
||||
demote: () => boolean;
|
||||
// destroy this instance, manual cleanup logic so you don't leak Blob
|
||||
// instances, etc.
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
export const directSpawner = (webWorkerURL: string): WorkerSpawner => {
|
||||
return {
|
||||
spawn: () => new Worker(webWorkerURL),
|
||||
demote: () => false,
|
||||
dispose: () => {},
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* createWorkerSpawner fetches the worker source _once_ and hands back a
|
||||
* WorkerSpawner instance and hands back a spawner backed by a Blob URL
|
||||
* instead of making each worker fetch the worker code individually.
|
||||
*
|
||||
* Doing it this way prevents a single client with many threads fetching
|
||||
* the same worker source code n times for values that are fixed for the
|
||||
* entire lifetime of the deployment of Anubis at that version. The old
|
||||
* method made a client with 8 threads fetch the worker logic 8 times,
|
||||
* which made an overloaded server even more overloaded, causing spurious
|
||||
* failures, which cause challenges to fail 100% of the time. This is
|
||||
* bad for uptime.
|
||||
*
|
||||
* Annoyingly, `new Worker(url)` reports a load failure as an opaque event
|
||||
* that does not include the status code of the failed load, so there's
|
||||
* no real way to detect "503, back off and retry" from "404, you fetched
|
||||
* the wrong asset". To work around this we have to `fetch()` the contents
|
||||
* of the worker code and spawn it with a Blob.
|
||||
*
|
||||
* If anything goes wrong or the server's Content-Security-Policy (CSP)
|
||||
* forbids putting worker sources in Blobs, we fall back to the old behaviour
|
||||
* with the caveat that doing this is kinda hacky and terrible, but such is
|
||||
* life.
|
||||
*/
|
||||
export const createWorkerSpawner = async (
|
||||
webWorkerURL: string,
|
||||
signal: AbortSignal | null,
|
||||
): Promise<WorkerSpawner> => {
|
||||
const direct: WorkerSpawner = directSpawner(webWorkerURL);
|
||||
|
||||
let blobURL: string;
|
||||
try {
|
||||
const response = await fetchWithBackoff(webWorkerURL, { signal });
|
||||
blobURL = URL.createObjectURL(
|
||||
new Blob([await response.text()], { type: "text/javascript" }),
|
||||
);
|
||||
} catch (err) {
|
||||
if (isAbortError(err)) {
|
||||
throw err;
|
||||
}
|
||||
// Every retry failed. Fall through to the direct spawner anyway: the
|
||||
// browser may still have a cached copy that `fetch` did not surface, and a
|
||||
// long shot beats a guaranteed failure.
|
||||
console.warn(
|
||||
"anubis: could not pre-fetch worker source (server may be under attack) using direct spawner in the vain hope that this works",
|
||||
err,
|
||||
);
|
||||
return direct;
|
||||
}
|
||||
|
||||
let useBlob = true;
|
||||
|
||||
return {
|
||||
spawn: (): Worker => {
|
||||
if (useBlob) {
|
||||
try {
|
||||
return new Worker(blobURL);
|
||||
} catch (err) {
|
||||
// XXX(Xe): Chrome, Firefox, and WebKit won't trigger this, but it's best
|
||||
// to be defensive here.
|
||||
console.warn("anubis: blob worker rejected, using direct URL", err);
|
||||
useBlob = false;
|
||||
}
|
||||
}
|
||||
return new Worker(webWorkerURL);
|
||||
},
|
||||
demote: (): boolean => {
|
||||
if (!useBlob) {
|
||||
return false;
|
||||
}
|
||||
|
||||
console.warn(
|
||||
"anubis: blob workers are not running, falling back to loading workers from their own URL (does this site's Content-Security-Policy allow blob: in worker-src?)",
|
||||
);
|
||||
useBlob = false;
|
||||
return true;
|
||||
},
|
||||
dispose: (): void => URL.revokeObjectURL(blobURL),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* workerError pulls the error message out of a worker's failure report, or
|
||||
* returns null when the payload is an ordinary result.
|
||||
*/
|
||||
const workerError = (data: unknown): string | null => {
|
||||
if (data == null || typeof data !== "object") {
|
||||
return null;
|
||||
}
|
||||
const err = (data as { error?: unknown }).error;
|
||||
return err == null ? null : String(err);
|
||||
};
|
||||
|
||||
/** defaultThreads is how many workers a challenge spawns when not told otherwise. */
|
||||
export const defaultThreads = (): number =>
|
||||
Math.trunc(Math.max(getHardwareConcurrency() / 2, 1));
|
||||
|
||||
export interface RunWorkersOptions {
|
||||
// URL of the worker script to run.
|
||||
webWorkerURL: string;
|
||||
// Fields merged into every worker's postMessage payload. Each worker also
|
||||
// gets its own `nonce` (its lane) and the total `threads` count.
|
||||
message: Record<string, unknown>;
|
||||
threads: number;
|
||||
signal: AbortSignal | null;
|
||||
progressCallback?: ProgressCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* runWorkers fans a challenge out across `threads` workers and resolves with
|
||||
* the first solution any of them finds.
|
||||
*
|
||||
* Every challenge algorithm shares this because every one of them has the same
|
||||
* failure modes: a server too overloaded to serve the worker script, a
|
||||
* Content-Security-Policy that forbids blob: workers, and workers that die
|
||||
* partway through. Solving those once here keeps the algorithms from drifting
|
||||
* apart on the parts that decide whether a user gets through at all.
|
||||
*/
|
||||
export const runWorkers = async (
|
||||
opts: RunWorkersOptions,
|
||||
): Promise<ProcessResult> => {
|
||||
const spawner = await createWorkerSpawner(opts.webWorkerURL, opts.signal);
|
||||
|
||||
try {
|
||||
return await raceWorkers(spawner, opts);
|
||||
} finally {
|
||||
spawner.dispose();
|
||||
}
|
||||
};
|
||||
|
||||
const raceWorkers = (
|
||||
spawner: WorkerSpawner,
|
||||
{ message, threads, signal, progressCallback }: RunWorkersOptions,
|
||||
): Promise<ProcessResult> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
let workers: Worker[] = [];
|
||||
let settled = false;
|
||||
let deadWorkers = 0;
|
||||
// XXX(Xe): sentinel for workers, if this is not set then a CSP refused
|
||||
// to load scripts normally.
|
||||
let anyOutput = false;
|
||||
|
||||
const onAbort = () => {
|
||||
console.log("PoW aborted");
|
||||
cleanup();
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
};
|
||||
|
||||
const stopWorkers = () => {
|
||||
workers.forEach((w) => {
|
||||
w.onmessage = null;
|
||||
w.onerror = null;
|
||||
w.terminate();
|
||||
});
|
||||
workers = [];
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
stopWorkers();
|
||||
if (signal != null) {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
};
|
||||
|
||||
if (signal != null) {
|
||||
if (signal.aborted) {
|
||||
return onAbort();
|
||||
}
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
|
||||
const startWorkers = () => {
|
||||
deadWorkers = 0;
|
||||
|
||||
for (let i = 0; i < threads; i++) {
|
||||
let worker: Worker;
|
||||
try {
|
||||
worker = spawner.spawn();
|
||||
} catch (err) {
|
||||
// If we can't spawn workers, we're in a weird place. Throw an error
|
||||
// up the stack and kill the workers so they don't burn CPU and try
|
||||
// to send a message that won't be read.
|
||||
cleanup();
|
||||
reject(
|
||||
new Error(
|
||||
`anubis: could not start proof of work worker: ${err} (is your browser out of date?)`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
workers.push(worker);
|
||||
|
||||
worker.onmessage = (event) => {
|
||||
// Feed the watchdog.
|
||||
anyOutput = true;
|
||||
|
||||
if (typeof event.data === "number") {
|
||||
progressCallback?.(event.data);
|
||||
return;
|
||||
}
|
||||
|
||||
// XXX(Xe): Workers register `async` message handlers, and a promise
|
||||
// that rejects inside one of those surfaces as an unhandledrejection
|
||||
// in the worker, not as an `error` event on this side. Workers report
|
||||
// those failures by hand so that they can't hang the page forever.
|
||||
const err = workerError(event.data);
|
||||
if (err !== null) {
|
||||
cleanup();
|
||||
reject(new Error(`anubis: proof of work worker failed: ${err}`));
|
||||
return;
|
||||
}
|
||||
|
||||
cleanup();
|
||||
resolve(event.data);
|
||||
};
|
||||
|
||||
const workerDied = (event: unknown) => {
|
||||
// XXX(Xe): Workers should generally be inerrant. If any of them has
|
||||
// died before producing any output then they have never ran because
|
||||
// the browser explicitly rejected the worker script due to an overly
|
||||
// strict Content-Security-Policy.
|
||||
//
|
||||
// Annoyingly, this isn't something that's easy to catch and validate
|
||||
// so we just check to make sure that we've seen at least _any_ output
|
||||
// from the worker and if we haven't then try to run the fallback
|
||||
// logic that makes N requests for N = getHardwareConcurrency().
|
||||
//
|
||||
// This can cause some issues with particularly overloaded servers
|
||||
// that can't route to Anubis due to biblical amounts of load, but
|
||||
// what can you do? At that point you kinda have to pick your battles
|
||||
// between reliability and consistency. Consistency is probably the
|
||||
// better tradeoff.
|
||||
if (!anyOutput && spawner.demote()) {
|
||||
console.warn(
|
||||
"anubis: proof of work workers died without running, respawning them",
|
||||
);
|
||||
stopWorkers();
|
||||
startWorkers();
|
||||
return;
|
||||
}
|
||||
|
||||
deadWorkers++;
|
||||
console.warn(
|
||||
`anubis: proof of work worker died (${deadWorkers}/${threads})`,
|
||||
event,
|
||||
);
|
||||
|
||||
// XXX(Xe): Make sure there's at least one worker left alive.
|
||||
//
|
||||
// One way to think about how the parallelism works here is that the
|
||||
// nonce space of challenge solutions is divided into one "lane" per
|
||||
// worker. In general solutions should be "dense" enough that losing
|
||||
// a few workers should be "fine enough".
|
||||
//
|
||||
// If all workers are dead, there is no way to search the entire nonce
|
||||
// space and thus the solution attempt has failed.
|
||||
if (deadWorkers < threads) {
|
||||
return;
|
||||
}
|
||||
|
||||
cleanup();
|
||||
// XXX(Xe): If the worker fails to load, some browsers return non-error
|
||||
// Error values that we can't introspect properly. When we hit this kind
|
||||
// of horrible state, throw an actual error so that the challenge page
|
||||
// has a better error message than "undefined".
|
||||
reject(
|
||||
new Error(
|
||||
"anubis: all proof of work workers failed at runtime (file a bug?)",
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
worker.onerror = workerDied;
|
||||
|
||||
// A payload we can't deserialize is as fatal to this worker as a
|
||||
// crash, and it is silent otherwise.
|
||||
worker.onmessageerror = (event) => {
|
||||
console.warn(
|
||||
"anubis: proof of work worker sent a bad message",
|
||||
event,
|
||||
);
|
||||
workerDied(event);
|
||||
};
|
||||
|
||||
worker.postMessage({
|
||||
...message,
|
||||
nonce: i,
|
||||
threads,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
startWorkers();
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
// Type declarations for xeact.mjs, which is vendored as plain JavaScript with
|
||||
// JSDoc annotations. TypeScript resolves `import ... from "./xeact.mjs"` to
|
||||
// this file, so keep the two in sync when updating xeact.
|
||||
//
|
||||
// This file was generated by Claude Opus 5.
|
||||
|
||||
import { jsx } from "preact/jsx-runtime";
|
||||
|
||||
type Child = Node | string;
|
||||
type Children = Child | Child[];
|
||||
|
||||
/**
|
||||
* Creates a DOM element, assigns the properties of `data` to it, and appends
|
||||
* all `children`.
|
||||
*/
|
||||
export function h<K extends keyof HTMLElementTagNameMap>(
|
||||
name: K,
|
||||
data?: Partial<HTMLElementTagNameMap[K]>,
|
||||
children?: Children,
|
||||
): HTMLElementTagNameMap[K];
|
||||
export function h<P extends object, R extends Node>(
|
||||
name: (data: P) => R,
|
||||
data?: P,
|
||||
children?: Children,
|
||||
): R;
|
||||
export function h(
|
||||
name: string,
|
||||
data?: Partial<HTMLElement>,
|
||||
children?: Children,
|
||||
): HTMLElement;
|
||||
|
||||
/** Create a text node. Equivalent to `document.createTextNode(text)`. */
|
||||
export function t(text: string): Text;
|
||||
|
||||
/** Remove all child nodes from a DOM element. */
|
||||
export function x(elem: Node): void;
|
||||
|
||||
/**
|
||||
* Get the element with the given ID. Equivalent to
|
||||
* `document.getElementById(name)`, and like it returns `null` when no element
|
||||
* matches.
|
||||
*/
|
||||
export function g(name: string): HTMLElement | null;
|
||||
|
||||
/**
|
||||
* Get all elements with the given class name. Equivalent to
|
||||
* `document.getElementsByClassName(name)`.
|
||||
*/
|
||||
export function c(name: string): HTMLCollectionOf<Element>;
|
||||
|
||||
/**
|
||||
* Get all elements with the given name attribute. Equivalent to
|
||||
* `document.getElementsByName(name)`.
|
||||
*/
|
||||
export function n(name: string): NodeListOf<HTMLElement>;
|
||||
|
||||
/**
|
||||
* Get all elements matching the given selector via
|
||||
* `document.querySelectorAll(selector)`.
|
||||
*/
|
||||
export function s(selector: string): HTMLElement[];
|
||||
|
||||
/**
|
||||
* Generate a relative URL from `url`, appending all key-value pairs from
|
||||
* `params` as URL-encoded parameters.
|
||||
*/
|
||||
export function u(url?: string, params?: Record<string, string>): string;
|
||||
|
||||
/**
|
||||
* Takes a callback to run when all DOM content is loaded. Equivalent to
|
||||
* `window.addEventListener("DOMContentLoaded", callback)`.
|
||||
*/
|
||||
export function r(callback: () => void): void;
|
||||
|
||||
/**
|
||||
* Allows a stateful value to be tracked by consumers. This is the Xeact
|
||||
* version of the React useState hook.
|
||||
*/
|
||||
export function useState<T>(value: T): [() => T, (value: T) => void];
|
||||
export function useState<T = undefined>(): [
|
||||
() => T | undefined,
|
||||
(value: T | undefined) => void,
|
||||
];
|
||||
|
||||
/** Debounce an action for up to `ms` milliseconds. */
|
||||
export function d(ms: number): (f: () => void) => void;
|
||||
|
||||
/**
|
||||
* Parse a given element as JSON and return it as a bare
|
||||
* object.
|
||||
*/
|
||||
export function j(id: string): any | null;
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
Local copy of Xeact (https://github.com/Xe/Xeact). Included under the terms
|
||||
of the MIT license:
|
||||
|
||||
MIT License
|
||||
-----------
|
||||
|
||||
Copyright (c) 2021 Xe (https://christine.website)
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a DOM element, assigns the properties of `data` to it, and appends all `children`.
|
||||
*
|
||||
* @type{function(string|Function, Object=, Node|Array.<Node|string>=)}
|
||||
*/
|
||||
const h = (name, data = {}, children = []) => {
|
||||
const result =
|
||||
typeof name == "function"
|
||||
? name(data)
|
||||
: Object.assign(document.createElement(name), data);
|
||||
if (!Array.isArray(children)) {
|
||||
children = [children];
|
||||
}
|
||||
result.append(...children);
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a text node.
|
||||
*
|
||||
* Equivalent to `document.createTextNode(text)`
|
||||
*
|
||||
* @type{function(string): Text}
|
||||
*/
|
||||
const t = (text) => document.createTextNode(text);
|
||||
|
||||
/**
|
||||
* Remove all child nodes from a DOM element.
|
||||
*
|
||||
* @type{function(Node)}
|
||||
*/
|
||||
const x = (elem) => {
|
||||
while (elem.lastChild) {
|
||||
elem.removeChild(elem.lastChild);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get all elements with the given ID.
|
||||
*
|
||||
* Equivalent to `document.getElementById(name)`
|
||||
*
|
||||
* @type{function(string): HTMLElement}
|
||||
*/
|
||||
const g = (name) => document.getElementById(name);
|
||||
|
||||
/**
|
||||
* Get all elements with the given class name.
|
||||
*
|
||||
* Equivalent to `document.getElementsByClassName(name)`
|
||||
*
|
||||
* @type{function(string): HTMLCollectionOf.<Element>}
|
||||
*/
|
||||
const c = (name) => document.getElementsByClassName(name);
|
||||
|
||||
/** @type{function(string): HTMLCollectionOf.<Element>} */
|
||||
const n = (name) => document.getElementsByName(name);
|
||||
|
||||
/**
|
||||
* Get all elements matching the given HTML selector.
|
||||
*
|
||||
* Matches selectors with `document.querySelectorAll(selector)`
|
||||
*
|
||||
* @type{function(string): Array.<HTMLElement>}
|
||||
*/
|
||||
const s = (selector) => Array.from(document.querySelectorAll(selector));
|
||||
|
||||
/**
|
||||
* Generate a relative URL from `url`, appending all key-value pairs from `params` as URL-encoded parameters.
|
||||
*
|
||||
* @type{function(string=, Object=): string}
|
||||
*/
|
||||
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();
|
||||
};
|
||||
|
||||
/**
|
||||
* Takes a callback to run when all DOM content is loaded.
|
||||
*
|
||||
* Equivalent to `window.addEventListener('DOMContentLoaded', callback)`
|
||||
*
|
||||
* @type{function(function())}
|
||||
*/
|
||||
const r = (callback) => window.addEventListener("DOMContentLoaded", callback);
|
||||
|
||||
/**
|
||||
* Allows a stateful value to be tracked by consumers.
|
||||
*
|
||||
* This is the Xeact version of the React useState hook.
|
||||
*
|
||||
* @type{function(any): [function(): any, function(any): void]}
|
||||
*/
|
||||
const useState = (value = undefined) => {
|
||||
return [
|
||||
() => value,
|
||||
(x) => {
|
||||
value = x;
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Debounce an action for up to ms milliseconds.
|
||||
*
|
||||
* @type{function(number): function(function(any): void)}
|
||||
*/
|
||||
const d = (ms) => {
|
||||
let debounceTimer = null;
|
||||
return (f) => {
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(f, ms);
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse a given element as JSON and return it as a bare
|
||||
* object.
|
||||
*
|
||||
* @type{function(id): any | null}
|
||||
*/
|
||||
const j = (id) => {
|
||||
const elem = g(id);
|
||||
if (elem === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return JSON.parse(elem.textContent);
|
||||
};
|
||||
|
||||
export { h, t, x, g, c, n, u, s, r, j, useState, d };
|
||||
+62
-71
@@ -1,81 +1,64 @@
|
||||
import { waitForExtensions } from "@lib/extensions";
|
||||
import algorithms from "./algorithms";
|
||||
import { fetchWithBackoff } from "./lib/backoff";
|
||||
import { g, u, j } from "@lib/xeact.mjs";
|
||||
|
||||
// from Xeact
|
||||
const u = (url: string = "", params: Record<string, any> = {}) => {
|
||||
let result = new URL(url, window.location.href);
|
||||
Object.entries(params).forEach(([k, v]) => result.searchParams.set(k, v));
|
||||
return result.toString();
|
||||
};
|
||||
// Tell the inline bootstrap in the challenge page that this script made it off
|
||||
// the wire and started running.
|
||||
|
||||
const j = (id: string): any | null => {
|
||||
const elem = document.getElementById(id);
|
||||
if (elem === null) {
|
||||
return null;
|
||||
declare global {
|
||||
interface Window {
|
||||
__anubisBooted?: boolean;
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.parse(elem.textContent);
|
||||
};
|
||||
const alreadyBooted = window.__anubisBooted === true;
|
||||
window.__anubisBooted = true;
|
||||
|
||||
const imageURL = (mood, cacheBuster, basePrefix) =>
|
||||
const imageURL = (
|
||||
mood: string,
|
||||
cacheBuster: string,
|
||||
basePrefix: string,
|
||||
): string =>
|
||||
u(`${basePrefix}/.within.website/x/cmd/anubis/static/img/${mood}.webp`, {
|
||||
cacheBuster,
|
||||
});
|
||||
|
||||
// Detect available languages by loading the manifest
|
||||
const getAvailableLanguages = async () => {
|
||||
const basePrefix = j("anubis_base_prefix");
|
||||
if (basePrefix === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${basePrefix}/.within.website/x/cmd/anubis/static/locales/manifest.json`,
|
||||
);
|
||||
if (response.ok) {
|
||||
const manifest = await response.json();
|
||||
return manifest.supportedLanguages || ["en"];
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"Failed to load language manifest, falling back to default languages",
|
||||
);
|
||||
}
|
||||
|
||||
// Fallback to default languages if manifest loading fails
|
||||
return ["en"];
|
||||
};
|
||||
|
||||
// Use the browser language from the HTML lang attribute which is set by the server settings or request headers
|
||||
const getBrowserLanguage = async () => document.documentElement.lang;
|
||||
|
||||
// Load translations from JSON files
|
||||
const loadTranslations = async (lang) => {
|
||||
//
|
||||
// This runs before anything else on the challenge page, so it must never throw:
|
||||
// an unhandled rejection here leaves the user staring at "Loading..." forever.
|
||||
// An untranslated challenge page still passes challenges, so the last resort is
|
||||
// an empty table, which makes t() fall through to the raw key.
|
||||
const loadTranslations = async (
|
||||
lang: string,
|
||||
): Promise<Record<string, string>> => {
|
||||
const basePrefix = j("anubis_base_prefix");
|
||||
if (basePrefix === null) {
|
||||
return;
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
const response = await fetchWithBackoff(
|
||||
`${basePrefix}/.within.website/x/cmd/anubis/static/locales/${lang}.json`,
|
||||
);
|
||||
return await response.json();
|
||||
return (await response.json()) as Record<string, string>;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`Failed to load translations for ${lang}, falling back to English`,
|
||||
);
|
||||
console.warn(`Failed to load translations for ${lang}`, error);
|
||||
if (lang !== "en") {
|
||||
return await loadTranslations("en");
|
||||
}
|
||||
throw error;
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const getRedirectUrl = () => {
|
||||
const getRedirectUrl = (): string | null => {
|
||||
const publicUrl = j("anubis_public_url");
|
||||
if (publicUrl === null) {
|
||||
return;
|
||||
return "/";
|
||||
}
|
||||
if (publicUrl && window.location.href.startsWith(publicUrl)) {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
@@ -84,7 +67,7 @@ const getRedirectUrl = () => {
|
||||
return window.location.href;
|
||||
};
|
||||
|
||||
let translations = {};
|
||||
let translations: Record<string, string> = {};
|
||||
let currentLang;
|
||||
|
||||
// Initialize translations
|
||||
@@ -93,9 +76,23 @@ const initTranslations = async () => {
|
||||
translations = await loadTranslations(currentLang);
|
||||
};
|
||||
|
||||
const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
const t = (key: string): string =>
|
||||
translations[`js_${key}`] ||
|
||||
translations[key] ||
|
||||
`unknown translatable string: ${key}`;
|
||||
|
||||
interface OhNoesParams {
|
||||
titleMsg: string;
|
||||
statusMsg: string;
|
||||
imageSrc: string;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (alreadyBooted) {
|
||||
console.debug("anubis: main.mjs already running, ignoring duplicate load");
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize translations first
|
||||
await initTranslations();
|
||||
|
||||
@@ -112,18 +109,10 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
},
|
||||
];
|
||||
|
||||
const status: HTMLParagraphElement = document.getElementById(
|
||||
"status",
|
||||
) as HTMLParagraphElement;
|
||||
const image: HTMLImageElement = document.getElementById(
|
||||
"image",
|
||||
) as HTMLImageElement;
|
||||
const title: HTMLHeadingElement = document.getElementById(
|
||||
"title",
|
||||
) as HTMLHeadingElement;
|
||||
const progress: HTMLDivElement = document.getElementById(
|
||||
"progress",
|
||||
) as HTMLDivElement;
|
||||
const status: HTMLParagraphElement = g("status") as HTMLParagraphElement;
|
||||
const image: HTMLImageElement = g("image") as HTMLImageElement;
|
||||
const title: HTMLHeadingElement = g("title") as HTMLHeadingElement;
|
||||
const progress: HTMLDivElement = g("progress") as HTMLDivElement;
|
||||
|
||||
const anubisVersion = j("anubis_version");
|
||||
const basePrefix = j("anubis_base_prefix");
|
||||
@@ -138,7 +127,7 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
});
|
||||
}
|
||||
|
||||
const ohNoes = ({ titleMsg, statusMsg, imageSrc }) => {
|
||||
const ohNoes = ({ titleMsg, statusMsg, imageSrc }: OhNoesParams) => {
|
||||
title.innerHTML = titleMsg;
|
||||
status.innerHTML = statusMsg;
|
||||
image.src = imageSrc;
|
||||
@@ -186,11 +175,11 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
try {
|
||||
const t0 = Date.now();
|
||||
const { hash, nonce } = await process(
|
||||
{ basePrefix, version: anubisVersion },
|
||||
{ basePrefix, version: anubisVersion, algorithm: rules.algorithm },
|
||||
challenge.randomData,
|
||||
rules.difficulty,
|
||||
null,
|
||||
(iters) => {
|
||||
(iters: number) => {
|
||||
const delta = Date.now() - t0;
|
||||
// only update the speed every second so it's less visually distracting
|
||||
if (delta - lastSpeedUpdate > 1000) {
|
||||
@@ -205,7 +194,7 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
|
||||
const probability = Math.pow(1 - likelihood, iters);
|
||||
const distance = (1 - Math.pow(probability, 2)) * 100;
|
||||
progress["aria-valuenow"] = distance;
|
||||
progress.ariaValueNow = `${distance}`;
|
||||
if (progress.firstElementChild !== null) {
|
||||
(progress.firstElementChild as HTMLElement).style.width =
|
||||
`${distance}%`;
|
||||
@@ -223,6 +212,8 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
const t1 = Date.now();
|
||||
console.log({ hash, nonce });
|
||||
|
||||
await waitForExtensions();
|
||||
|
||||
if (userReadDetails) {
|
||||
const container: HTMLDivElement = document.getElementById(
|
||||
"progress",
|
||||
@@ -245,14 +236,14 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
container.innerHTML = t("finished_reading");
|
||||
|
||||
function onDetailsExpand() {
|
||||
const redir = getRedirectUrl();
|
||||
const redir = getRedirectUrl() ?? "/";
|
||||
window.location.replace(
|
||||
u(`${basePrefix}/.within.website/x/cmd/anubis/api/pass-challenge`, {
|
||||
id: challenge.id,
|
||||
response: hash,
|
||||
nonce,
|
||||
redir,
|
||||
elapsedTime: t1 - t0,
|
||||
elapsedTime: `${t1 - t0}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -260,18 +251,18 @@ const t = (key) => translations[`js_${key}`] || translations[key] || key;
|
||||
container.onclick = onDetailsExpand;
|
||||
setTimeout(onDetailsExpand, 30000);
|
||||
} else {
|
||||
const redir = getRedirectUrl();
|
||||
const redir = getRedirectUrl() ?? "/";
|
||||
window.location.replace(
|
||||
u(`${basePrefix}/.within.website/x/cmd/anubis/api/pass-challenge`, {
|
||||
id: challenge.id,
|
||||
response: hash,
|
||||
nonce,
|
||||
redir,
|
||||
elapsedTime: t1 - t0,
|
||||
elapsedTime: `${t1 - t0}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
} catch (err: any) {
|
||||
ohNoes({
|
||||
titleMsg: t("calculation_error"),
|
||||
statusMsg: `${t("calculation_error_msg")} ${err.message}`,
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { Sha256 } from "@aws-crypto/sha256-js";
|
||||
|
||||
const calculateSHA256 = (text) => {
|
||||
const hash = new Sha256();
|
||||
hash.update(text);
|
||||
return hash.digest();
|
||||
};
|
||||
|
||||
function toHexString(arr: Uint8Array): string {
|
||||
return Array.from(arr)
|
||||
.map((c) => c.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
addEventListener("message", async ({ data: eventData }) => {
|
||||
const { data, difficulty, threads } = eventData;
|
||||
let nonce = eventData.nonce;
|
||||
const isMainThread = nonce === 0;
|
||||
let iterations = 0;
|
||||
|
||||
const requiredZeroBytes = Math.floor(difficulty / 2);
|
||||
const isDifficultyOdd = difficulty % 2 !== 0;
|
||||
|
||||
for (;;) {
|
||||
const hashBuffer = await calculateSHA256(data + nonce);
|
||||
const hashArray = new Uint8Array(hashBuffer);
|
||||
|
||||
let isValid = true;
|
||||
for (let i = 0; i < requiredZeroBytes; i++) {
|
||||
if (hashArray[i] !== 0) {
|
||||
isValid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isValid && isDifficultyOdd) {
|
||||
if (hashArray[requiredZeroBytes] >> 4 !== 0) {
|
||||
isValid = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
const finalHash = toHexString(hashArray);
|
||||
postMessage({
|
||||
hash: finalHash,
|
||||
data,
|
||||
difficulty,
|
||||
nonce,
|
||||
});
|
||||
return; // Exit worker
|
||||
}
|
||||
|
||||
nonce += threads;
|
||||
iterations++;
|
||||
|
||||
/* Truncate the decimal portion of the nonce. This is a bit of an evil bit
|
||||
* hack, but it works reliably enough. The core of why this works is:
|
||||
*
|
||||
* > 13.4 % 1 !== 0
|
||||
* true
|
||||
* > 13 % 1 !== 0
|
||||
* false
|
||||
*/
|
||||
if (nonce % 1 !== 0) {
|
||||
nonce = Math.trunc(nonce);
|
||||
}
|
||||
|
||||
// Send a progress update from the main thread every 1024 iterations.
|
||||
if (isMainThread && (iterations & 1023) === 0) {
|
||||
postMessage(nonce);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,73 +0,0 @@
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const calculateSHA256 = async (input: string) => {
|
||||
const data = encoder.encode(input);
|
||||
return await crypto.subtle.digest("SHA-256", data);
|
||||
};
|
||||
|
||||
const toHexString = (byteArray: Uint8Array) => {
|
||||
return byteArray.reduce(
|
||||
(str, byte) => str + byte.toString(16).padStart(2, "0"),
|
||||
"",
|
||||
);
|
||||
};
|
||||
|
||||
addEventListener("message", async ({ data: eventData }) => {
|
||||
const { data, difficulty, threads } = eventData;
|
||||
let nonce = eventData.nonce;
|
||||
const isMainThread = nonce === 0;
|
||||
let iterations = 0;
|
||||
|
||||
const requiredZeroBytes = Math.floor(difficulty / 2);
|
||||
const isDifficultyOdd = difficulty % 2 !== 0;
|
||||
|
||||
for (;;) {
|
||||
const hashBuffer = await calculateSHA256(data + nonce);
|
||||
const hashArray = new Uint8Array(hashBuffer);
|
||||
|
||||
let isValid = true;
|
||||
for (let i = 0; i < requiredZeroBytes; i++) {
|
||||
if (hashArray[i] !== 0) {
|
||||
isValid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isValid && isDifficultyOdd) {
|
||||
if (hashArray[requiredZeroBytes] >> 4 !== 0) {
|
||||
isValid = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
const finalHash = toHexString(hashArray);
|
||||
postMessage({
|
||||
hash: finalHash,
|
||||
data,
|
||||
difficulty,
|
||||
nonce,
|
||||
});
|
||||
return; // Exit worker
|
||||
}
|
||||
|
||||
nonce += threads;
|
||||
iterations++;
|
||||
|
||||
/* Truncate the decimal portion of the nonce. This is a bit of an evil bit
|
||||
* hack, but it works reliably enough. The core of why this works is:
|
||||
*
|
||||
* > 13.4 % 1 !== 0
|
||||
* true
|
||||
* > 13 % 1 !== 0
|
||||
* false
|
||||
*/
|
||||
if (nonce % 1 !== 0) {
|
||||
nonce = Math.trunc(nonce);
|
||||
}
|
||||
|
||||
// Send a progress update from the main thread every 1024 iterations.
|
||||
if (isMainThread && (iterations & 1023) === 0) {
|
||||
postMessage(nonce);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { Sha256 } from "@aws-crypto/sha256-js";
|
||||
import { WorkerArgs } from "@lib/worker";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const useWebCrypto = (): boolean => {
|
||||
if (
|
||||
navigator.userAgent.includes("Firefox") ||
|
||||
navigator.userAgent.includes("Goanna")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return self.isSecureContext && typeof crypto?.subtle?.digest === "function";
|
||||
};
|
||||
|
||||
const calculateSHA256: (input: string) => Promise<Uint8Array> = useWebCrypto()
|
||||
? async (input: string) =>
|
||||
new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(input)))
|
||||
: async (input: string) => {
|
||||
const hash = new Sha256();
|
||||
hash.update(input);
|
||||
return await hash.digest();
|
||||
};
|
||||
|
||||
const toHexString = (arr: Uint8Array): string =>
|
||||
Array.from(arr)
|
||||
.map((c) => c.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
|
||||
addEventListener(
|
||||
"message",
|
||||
async ({ data: eventData }: { data: WorkerArgs }) => {
|
||||
const { data, difficulty, threads } = eventData;
|
||||
let nonce = eventData.nonce;
|
||||
const isMainThread = nonce === 0;
|
||||
let iterations = 0;
|
||||
|
||||
const requiredZeroBytes = Math.floor(difficulty / 2);
|
||||
const isDifficultyOdd = difficulty % 2 !== 0;
|
||||
|
||||
for (;;) {
|
||||
const hashBuffer = await calculateSHA256(data + nonce);
|
||||
const hashArray = new Uint8Array(hashBuffer);
|
||||
|
||||
let isValid = true;
|
||||
for (let i = 0; i < requiredZeroBytes; i++) {
|
||||
if (hashArray[i] !== 0) {
|
||||
isValid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isValid && isDifficultyOdd) {
|
||||
if (hashArray[requiredZeroBytes] >> 4 !== 0) {
|
||||
isValid = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
const finalHash = toHexString(hashArray);
|
||||
postMessage({
|
||||
hash: finalHash,
|
||||
data,
|
||||
difficulty,
|
||||
nonce,
|
||||
});
|
||||
return; // Exit worker
|
||||
}
|
||||
|
||||
nonce += threads;
|
||||
iterations++;
|
||||
|
||||
/* Truncate the decimal portion of the nonce. This is a bit of an evil bit
|
||||
* hack, but it works reliably enough. The core of why this works is:
|
||||
*
|
||||
* > 13.4 % 1 !== 0
|
||||
* true
|
||||
* > 13 % 1 !== 0
|
||||
* false
|
||||
*/
|
||||
if (nonce % 1 !== 0) {
|
||||
nonce = Math.trunc(nonce);
|
||||
}
|
||||
|
||||
// Send a progress update from the main thread every 1024 iterations.
|
||||
if (isMainThread && (iterations & 1023) === 0) {
|
||||
postMessage(nonce);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
Args,
|
||||
AnubisExports,
|
||||
uint8ArrayToHex,
|
||||
hexToUint8Array,
|
||||
} from "@lib/wasm";
|
||||
|
||||
addEventListener("message", async (event: MessageEvent<Args>) => {
|
||||
try {
|
||||
const { data, difficulty, threads, module } = event.data;
|
||||
let { nonce } = event.data;
|
||||
|
||||
const importObject = {
|
||||
anubis: {
|
||||
anubis_update_nonce: (nonce: number) => postMessage(nonce),
|
||||
},
|
||||
};
|
||||
|
||||
if (nonce !== 0) {
|
||||
importObject.anubis.anubis_update_nonce = (_) => {};
|
||||
}
|
||||
|
||||
// instantiate() resolves to an Instance (not a ResultObject) when passed a compiled Module.
|
||||
const instance = await WebAssembly.instantiate(module, importObject);
|
||||
|
||||
const {
|
||||
anubis_work,
|
||||
data_ptr,
|
||||
result_hash_ptr,
|
||||
result_hash_size,
|
||||
set_data_length,
|
||||
memory,
|
||||
} = instance.exports as unknown as AnubisExports;
|
||||
|
||||
function writeToBuffer(data: Uint8Array) {
|
||||
if (data.length > 4096) {
|
||||
throw new Error("Data exceeds buffer size");
|
||||
}
|
||||
|
||||
const offset = data_ptr();
|
||||
const buffer = new Uint8Array(memory.buffer, offset, data.length);
|
||||
|
||||
buffer.set(data);
|
||||
set_data_length(data.length);
|
||||
}
|
||||
|
||||
function readFromChallenge() {
|
||||
const offset = result_hash_ptr();
|
||||
const buffer = new Uint8Array(memory.buffer, offset, result_hash_size());
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
writeToBuffer(hexToUint8Array(data));
|
||||
|
||||
nonce = anubis_work(difficulty, nonce, threads);
|
||||
const challenge = readFromChallenge();
|
||||
const result = uint8ArrayToHex(challenge);
|
||||
|
||||
postMessage({
|
||||
hash: result,
|
||||
difficulty,
|
||||
nonce,
|
||||
});
|
||||
} catch (err) {
|
||||
// A rejection inside an async message handler shows up as an
|
||||
// unhandledrejection in this worker, never as an error event on the page.
|
||||
// Report it by hand so the challenge fails loudly instead of hanging.
|
||||
postMessage({ error: String(err) });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import * as argon2id from "../gen/wasm2js/argon2id.wasm.js";
|
||||
import * as hashx from "../gen/wasm2js/hashx.wasm.js";
|
||||
import * as sha256 from "../gen/wasm2js/sha256.wasm.js";
|
||||
|
||||
import {
|
||||
Wasm2JSArgs,
|
||||
AnubisExports,
|
||||
uint8ArrayToHex,
|
||||
hexToUint8Array,
|
||||
} from "@lib/wasm";
|
||||
|
||||
const algorithms: Record<string, AnubisExports> = {
|
||||
argon2id: argon2id,
|
||||
hashx: hashx,
|
||||
sha256: sha256,
|
||||
};
|
||||
|
||||
addEventListener("message", async (event: MessageEvent<Wasm2JSArgs>) => {
|
||||
try {
|
||||
const { data, difficulty, threads, algorithm } = event.data;
|
||||
let { nonce } = event.data;
|
||||
|
||||
const obj = algorithms[algorithm];
|
||||
if (obj == undefined) {
|
||||
throw new Error(`unknown algorithm ${algorithm}, file a bug please`);
|
||||
}
|
||||
|
||||
const {
|
||||
anubis_work,
|
||||
data_ptr,
|
||||
result_hash_ptr,
|
||||
result_hash_size,
|
||||
set_data_length,
|
||||
memory,
|
||||
} = obj;
|
||||
|
||||
// Write data to buffer
|
||||
function writeToBuffer(data: Uint8Array) {
|
||||
if (data.length > 1024) {
|
||||
throw new Error("Data exceeds buffer size");
|
||||
}
|
||||
|
||||
const offset = data_ptr();
|
||||
const buffer = new Uint8Array(memory.buffer, offset, data.length);
|
||||
|
||||
buffer.set(data);
|
||||
set_data_length(data.length);
|
||||
}
|
||||
|
||||
function readFromChallenge() {
|
||||
const offset = result_hash_ptr();
|
||||
const buffer = new Uint8Array(memory.buffer, offset, result_hash_size());
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
writeToBuffer(hexToUint8Array(data));
|
||||
|
||||
nonce = anubis_work(difficulty, nonce, threads);
|
||||
const challenge = readFromChallenge();
|
||||
const result = uint8ArrayToHex(challenge);
|
||||
|
||||
postMessage({
|
||||
hash: result,
|
||||
difficulty,
|
||||
nonce,
|
||||
});
|
||||
} catch (err) {
|
||||
// See the note in worker/wasm.ts: async handler rejections are invisible
|
||||
// to the page unless the worker reports them itself.
|
||||
postMessage({ error: String(err) });
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user