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
@@ -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 };
|
||||
Reference in new issue
Block a user