diff --git a/README.md b/README.md index 9178f50..4964e78 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,19 @@ browser --TLS (Moshpit CA leaf)--> edge --HTTP--> any healthy c0mpute gateway -- that announce a gateway URL), re-checked every minute; the last good list is kept when discovery fails. No c0mpute server is on the path: any gateway can serve any site. +- Only our own gateways (`C0MPUTE_GATEWAYS`, `C0MPUTE_TRUSTED_GATEWAYS`) are + proxied as they answer. Any c0mpute node can announce a gateway, so a + discovered one is a stranger's and gives only verified reads: the edge asks it + for `/hosting/v1/sites//resolve?path=...` (the owner-signed record, the + manifest and the file the path resolves to) and checks the ed25519 signature, + the site id, the manifest and parts by blake3, the path resolution (no + skipped candidate) and every chunk (`/hosting/v1/sites//chunks/`, + from any gateway) against its hash, the same rules as c0mpute's + `hosting/site.rs`. A record older than the highest seq already verified for + the site is refused (rollback). A gateway without those routes (c0mpute + before 0.3.5) or that fails a check sits out verified reads; the edge never + falls back to its unverified bytes. Verified responses carry + `x-c0mpute-verified: 1`; verified chunks are cached on disk by hash. - When every gateway fails, the edge retries the round on a Fibonacci schedule (0.5, 0.5, 1, 1.5, 2.5, 4 s), long enough to ride out a gateway restart or self-update. If they are still down it serves the last good copy of the page @@ -295,6 +308,9 @@ browser --TLS (Moshpit CA leaf)--> edge --HTTP--> any healthy c0mpute gateway -- | `MOSHPIT_API_KEY` | | the edge account's key; required to issue leaves | | `MOSHPIT_REGISTRY_BASE` | `https://pit.moshcode.sh` | | | `C0MPUTE_GATEWAYS` | | seed gateways, comma-separated (`http://host:7777`) | +| `C0MPUTE_TRUSTED_GATEWAYS` | | more gateways of ours, served without verification | +| `C0MPUTE_VERIFY_ALL` | off | `1`: verify our own gateways too | +| `EDGE_CHUNK_DIR` | `$EDGE_CERT_DIR/chunks` | verified chunk cache (1 GiB); `off` disables | | `C0MPUTE_NODES_URL` | `https://c0mpute.com/api/nodes` | gateway discovery; empty disables | | `EDGE_CERT_DIR` | `/var/lib/moshpit/c0mpute-edge` | | | `EDGE_HTTPS_PORT` / `EDGE_HTTP_PORT` | `443` / `80` | `EDGE_HTTP_PORT=0` disables http | diff --git a/bin/moshpit-c0mpute-edge.ts b/bin/moshpit-c0mpute-edge.ts index d12f29d..ce88dc6 100644 --- a/bin/moshpit-c0mpute-edge.ts +++ b/bin/moshpit-c0mpute-edge.ts @@ -6,6 +6,7 @@ import { realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { CertStore, GatewayPool, LastGood, SiteLookup, startEdge } from "../lib/c0mpute-edge.ts"; +import { ChunkCache, SeqGuard } from "../lib/c0mpute-verify.ts"; /** `host:port` or `[v6]:port`, or null. */ export function hostPort(v: string | undefined): { host: string; port: number } | null { @@ -24,7 +25,12 @@ export function edgeConfig(env: Record = process.env registryBase: env.MOSHPIT_REGISTRY_BASE || "https://pit.moshcode.sh", apiKey: env.MOSHPIT_API_KEY || "", certDir: env.EDGE_CERT_DIR || "/var/lib/moshpit/c0mpute-edge", + // Our own gateways: served from as they answer. Every gateway discovered + // from the node list is a stranger's and only ever gives verified reads. seeds: (env.C0MPUTE_GATEWAYS || "").split(/[\s,]+/).filter(Boolean), + trusted: (env.C0MPUTE_TRUSTED_GATEWAYS || "").split(/[\s,]+/).filter(Boolean), + // Verify every gateway, ours included. + verifyAll: /^(1|true|yes|on)$/i.test(env.C0MPUTE_VERIFY_ALL || ""), // The public node list, for gateways that announce a URL. Empty disables // discovery and the edge uses the seeds alone. nodesUrl: env.C0MPUTE_NODES_URL === undefined ? "https://c0mpute.com/api/nodes" : env.C0MPUTE_NODES_URL || null, @@ -36,6 +42,10 @@ export function edgeConfig(env: Record = process.env // Last good copy of every page, served stale when every gateway is down. // On disk so it survives a restart of the edge; "off" keeps it in memory only. staleDir: env.EDGE_STALE_DIR === "off" ? null : env.EDGE_STALE_DIR || `${env.EDGE_CERT_DIR || "/var/lib/moshpit/c0mpute-edge"}/stale`, + // Verified chunks (immutable, by hash) and the highest verified seq per + // site, so a restart neither refetches everything nor forgets the rollback floor. + chunkDir: env.EDGE_CHUNK_DIR === "off" ? null : env.EDGE_CHUNK_DIR || `${env.EDGE_CERT_DIR || "/var/lib/moshpit/c0mpute-edge"}/chunks`, + seqFile: `${env.EDGE_CERT_DIR || "/var/lib/moshpit/c0mpute-edge"}/site-seqs.json`, }; } @@ -44,7 +54,7 @@ async function main() { const log = (line: string) => console.log(line); if (!cfg.apiKey) log("[edge] warning: MOSHPIT_API_KEY is not set; only certificates already on disk can be served"); - const gateways = new GatewayPool({ seeds: cfg.seeds, nodesUrl: cfg.nodesUrl }); + const gateways = new GatewayPool({ seeds: cfg.seeds, trusted: cfg.trusted, nodesUrl: cfg.nodesUrl }); await gateways.refresh(); if (!gateways.size) log("[edge] warning: no c0mpute gateways known yet (set C0MPUTE_GATEWAYS)"); const timer = setInterval(() => { void gateways.refresh(); }, cfg.refreshMs); @@ -52,10 +62,14 @@ async function main() { const lastGood = new LastGood({ dir: cfg.staleDir }); await lastGood.load(); + const chunks = new ChunkCache({ dir: cfg.chunkDir }); + await chunks.load(); + const seqs = new SeqGuard({ file: cfg.seqFile }); + await seqs.load(); const sites = new SiteLookup({ registryBase: cfg.registryBase }); const certs = new CertStore({ dir: cfg.certDir, registryBase: cfg.registryBase, apiKey: cfg.apiKey, log }); await startEdge({ sites, gateways, certs, host: cfg.host, httpsPort: cfg.httpsPort, httpPort: cfg.httpPort, - proxyProtocol: cfg.proxyProtocol, fallback: cfg.fallback, lastGood, log }); + proxyProtocol: cfg.proxyProtocol, fallback: cfg.fallback, lastGood, chunks, seqs, verifyAll: cfg.verifyAll, log }); log(`[edge] serving c0mpute sites on https :${cfg.httpsPort}${cfg.httpPort ? ` and http :${cfg.httpPort}` : ""}; ${gateways.size} gateway(s) known${cfg.fallback ? `; other names to ${cfg.fallback.host}:${cfg.fallback.port}` : ""}`); } diff --git a/lib/c0mpute-edge.ts b/lib/c0mpute-edge.ts index 2cff010..0cf04f5 100644 --- a/lib/c0mpute-edge.ts +++ b/lib/c0mpute-edge.ts @@ -22,6 +22,12 @@ // discovered from seeds and from the public node list (nodes that announce a // gateway URL), and the last good list is kept when discovery fails. // +// Any c0mpute node may announce a gateway, so only our own (the seeds and +// C0MPUTE_TRUSTED_GATEWAYS) are proxied as they answer. A discovered gateway is +// a stranger's: from it the edge serves only what it has checked against the +// site owner's signature (lib/c0mpute-verify.ts), and a gateway that cannot +// give a verified read is skipped, never served from unverified. +// // When every gateway fails a request the edge does not give up at once: it // retries the round a few times on a Fibonacci schedule (a gateway restarting // or re-executing for an update is back within seconds), then serves the last @@ -40,6 +46,7 @@ import type { SecureContext, TLSSocket } from "node:tls"; import { join } from "node:path"; import type { Server as NetServer } from "node:net"; import { createSniFront } from "./sni-front.ts"; +import { ChunkCache, SeqGuard, VerifyError, chunkLength, entryEtag, verifyChunk, verifyResolve } from "./c0mpute-verify.ts"; import { promisify } from "node:util"; const run = promisify(execFile); @@ -107,7 +114,12 @@ export function gatewaysFromNodes(payload: unknown): string[] { type GatewayState = { url: string; healthy: boolean; rttMs: number; failures: number; downUntil: number }; export interface GatewayPoolOptions { + /** Gateways to start from. Trusted (served from without verification) unless `trustSeeds` is false. */ seeds?: string[]; + /** More gateways that are ours and served from without verification. */ + trusted?: string[]; + /** Default true: the seeds are our own gateways. */ + trustSeeds?: boolean; /** A node list to discover gateways from; null disables discovery. */ nodesUrl?: string | null; fetchImpl?: typeof fetch; @@ -126,6 +138,7 @@ export interface GatewayPoolOptions { export class GatewayPool { private states = new Map(); private seeds: string[]; + private trusted: Set; private nodesUrl: string | null; private fetchImpl: typeof fetch; private timeoutMs: number; @@ -133,7 +146,10 @@ export class GatewayPool { private turn = 0; constructor(opts: GatewayPoolOptions = {}) { - this.seeds = (opts.seeds ?? []).map(normalizeGateway).filter((u): u is string => Boolean(u)); + const norm = (list: string[] | undefined) => (list ?? []).map(normalizeGateway).filter((u): u is string => Boolean(u)); + const extra = norm(opts.trusted); + this.seeds = [...new Set([...norm(opts.seeds), ...extra])]; + this.trusted = new Set([...(opts.trustSeeds === false ? [] : norm(opts.seeds)), ...extra]); this.nodesUrl = opts.nodesUrl ?? null; this.fetchImpl = opts.fetchImpl ?? fetch; this.timeoutMs = opts.timeoutMs ?? 3000; @@ -152,6 +168,13 @@ export class GatewayPool { get size(): number { return this.states.size; } + /** + * True for our own gateways (seeds and C0MPUTE_TRUSTED_GATEWAYS). Anything + * discovered from the node list is a stranger's, and the edge serves its + * bytes only after checking them against the site owner's signature. + */ + isTrusted(url: string): boolean { return this.trusted.has(url); } + /** Rediscover and re-check every gateway. Never throws; a failed discovery keeps the old list. */ async refresh(): Promise { if (this.nodesUrl) { @@ -390,7 +413,18 @@ const PASS_HEADERS = ["content-type", "content-length", "etag", "last-modified", export interface EdgeHandlerOptions { sites: Pick; - gateways: Pick; + /** + * `isTrusted` says which gateways are ours; a pool without it is taken to be + * all ours (the edge before any node could be a gateway). + */ + gateways: Pick & Partial>; + /** Verify trusted gateways too (C0MPUTE_VERIFY_ALL). */ + verifyAll?: boolean; + /** Highest verified seq per site (rollback guard). In memory by default. */ + seqs?: SeqGuard; + /** Verified chunks by hash. None (no cache) by default. */ + chunks?: ChunkCache; + now?: () => number; fetchImpl?: typeof fetch; timeoutMs?: number; attempts?: number; @@ -532,6 +566,19 @@ export function createEdgeHandler(opts: EdgeHandlerOptions) { const sleep = opts.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); const lastGood = opts.lastGood === undefined ? new LastGood() : opts.lastGood; const log = opts.log ?? (() => {}); + const now = opts.now ?? Date.now; + const verifyAll = Boolean(opts.verifyAll); + const seqs = opts.seqs ?? new SeqGuard(); + const chunks = opts.chunks ?? new ChunkCache(); + // Gateways that cannot do verified reads just now (no resolve route yet, or + // caught lying), and until when they sit those out. + const unverifiable = new Map(); + const trusted = (gw: string) => !verifyAll && (opts.gateways.isTrusted ? opts.gateways.isTrusted(gw) : true); + const sittingOut = (gw: string) => (unverifiable.get(gw) ?? 0) > now(); + const sitOut = (gw: string, ms: number, why: string) => { + if (!sittingOut(gw)) log(`[edge] ${gw}: no verified reads for ${Math.round(ms / 1000)} s: ${why}`); + unverifiable.set(gw, now() + ms); + }; return async function handle(req: IncomingMessage, res: ServerResponse): Promise { const send = (status: number, text: string) => { @@ -564,7 +611,14 @@ export function createEdgeHandler(opts: EdgeHandlerOptions) { // One pass over the gateways; true when a response was sent. const tryRound = async (): Promise => { - for (const gw of opts.gateways.pick(attempts)) { + // Gateways that cannot serve a verified read just now are passed over, + // not counted against `attempts`. + const order = opts.gateways.pick(64).filter((gw) => trusted(gw) || !sittingOut(gw)).slice(0, attempts); + for (const gw of order) { + if (!trusted(gw)) { + if (await serveVerified(gw, order)) return true; + continue; + } let upstream: Response; try { upstream = await fetchImpl(upstreamUrl(gw, site, path), { @@ -624,6 +678,135 @@ export function createEdgeHandler(opts: EdgeHandlerOptions) { return false; }; + // A stranger's gateway: take nothing from it on its word. Ask for the + // owner-signed evidence, check it (lib/c0mpute-verify.ts) and send only + // bytes whose hashes the signed manifest names. False when nothing was + // sent and the next gateway should be tried. + async function serveVerified(gw: string, others: string[]): Promise { + const reqPath = path.split(/[?#]/)[0] || "/"; + let answer: unknown; + try { + const r = await fetchImpl(`${gw}/hosting/v1/sites/${site}/resolve?path=${encodeURIComponent(reqPath)}`, { + redirect: "manual", signal: AbortSignal.timeout(timeoutMs), + }); + if (r.status >= 500) { + await r.body?.cancel(); + opts.gateways.failed(gw); + log(`[edge] ${host} via ${gw} (verified): ${r.status}`); + return false; + } + if (r.status !== 200) { + // 404: a gateway older than the resolve route (c0mpute < 0.3.5), or + // one that does not know the site. Either way, no verified read. + await r.body?.cancel(); + sitOut(gw, 300_000, `resolve answered ${r.status}`); + return false; + } + answer = await r.json(); + } catch (e) { + if (e instanceof SyntaxError) { sitOut(gw, 300_000, "resolve answer is not JSON"); return false; } + opts.gateways.failed(gw); + log(`[edge] ${host} via ${gw} (verified): ${(e as Error).message}`); + return false; + } + let resolved: ReturnType; + try { + resolved = verifyResolve(site!, reqPath, answer, seqs.min(site!)); + } catch (e) { + const msg = e instanceof VerifyError ? e.message : String(e); + log(`[edge] ${host}${reqPath} via ${gw}: REJECTED: ${msg}`); + sitOut(gw, 600_000, `failed verification (${msg})`); + return false; + } + opts.gateways.succeeded(gw); + seqs.note(site!, resolved.record.seq); + + const base: Record = { + "x-c0mpute-gateway": new URL(gw).host, + "x-c0mpute-verified": "1", + "x-content-type-options": "nosniff", + }; + const entry = resolved.entry; + if (!entry) { + res.writeHead(404, { ...base, "content-type": "text/plain; charset=utf-8", "cache-control": "public, max-age=60" }); + res.end(req.method === "HEAD" ? undefined : "not found"); + return true; + } + const etag = entryEtag(entry); + const headers: Record = { + ...base, + "content-type": /^[\x20-\x7e]{1,255}$/.test(entry.content_type) ? entry.content_type : "application/octet-stream", + "content-length": String(entry.size), + etag, + "cache-control": "public, max-age=60", + }; + if (resolved.status === 200 && conditional && String(req.headers["if-none-match"]).split(/\s*,\s*/).includes(etag)) { + delete headers["content-length"]; + res.writeHead(304, headers); + res.end(); + return true; + } + if (req.method === "HEAD") { + res.writeHead(resolved.status, headers); + res.end(); + return true; + } + + // Chunks from anywhere: the hash makes the source irrelevant. The + // gateway that resolved first, then the others still in the running. + const sources = [gw, ...others, ...opts.gateways.pick(64)] + .filter((o, i, all) => all.indexOf(o) === i && !sittingOut(o)); + const chunk = async (i: number): Promise => { + const hash = entry.chunks[i]; + const want = chunkLength(entry.size, i); + const cached = await chunks.get(hash); + if (cached && cached.length === want) return cached; + for (const src of sources) { + if (sittingOut(src)) continue; + try { + const r = await fetchImpl(`${src}/hosting/v1/sites/${site}/chunks/${hash}`, { redirect: "manual", signal: AbortSignal.timeout(timeoutMs) }); + if (r.status !== 200) { await r.body?.cancel(); continue; } + const bytes = Buffer.from(await r.arrayBuffer()); + verifyChunk(bytes, hash, want); + chunks.put(hash, bytes); + return bytes; + } catch (e) { + if (e instanceof VerifyError) { + log(`[edge] ${host}${reqPath} chunk from ${src}: REJECTED: ${e.message}`); + sitOut(src, 600_000, `served a bad chunk (${e.message})`); + } + } + } + return null; + }; + + // The first chunk before the status line, so a file whose chunks cannot + // be had falls through to the next gateway (and then the stale copy). + const first = await chunk(0); + if (!first) { + log(`[edge] ${host}${reqPath}: no gateway had a good copy of chunk 0 of ${resolved.path}`); + return false; + } + res.writeHead(resolved.status, headers); + const keep = lastGood && resolved.status === 200 && entry.size <= lastGood.maxEntryBytes ? [first] : null; + if (!res.write(first)) await new Promise((r) => res.once("drain", r)); + for (let i = 1; i < entry.chunks.length; i++) { + const next = await chunk(i); + if (!next) { + // Every byte sent so far was checked; the rest cannot be had. Cut + // the response short rather than send anything unverified. + log(`[edge] ${host}${reqPath}: chunk ${i} of ${resolved.path} unavailable mid-file`); + res.destroy(); + return true; + } + keep?.push(next); + if (!res.write(next)) await new Promise((r) => res.once("drain", r)); + } + res.end(); + if (keep) lastGood!.put(key, 200, headers, Buffer.concat(keep)); + return true; + } + if (await tryRound()) return; for (const ms of delays) { if (res.destroyed || req.socket.destroyed) return; diff --git a/lib/c0mpute-verify.ts b/lib/c0mpute-verify.ts new file mode 100644 index 0000000..c330b2d --- /dev/null +++ b/lib/c0mpute-verify.ts @@ -0,0 +1,467 @@ +// Verified reads of a c0mpute site from a gateway the edge does not trust. +// +// Any c0mpute node may announce itself as a public gateway, so the edge can +// no longer assume the gateway it asks is honest. For those gateways it does +// not take `/s//` bytes at all. It asks for the evidence instead: +// +// GET {gw}/hosting/v1/sites/{site}/resolve?path= +// -> the owner's signed record, the manifest chunk (and, for a parted site, +// the manifest parts consulted), and which file the gateway says the +// path resolves to; +// GET {gw}/hosting/v1/sites/{site}/chunks/{hex} +// -> one chunk, by its blake3 hash. +// +// and checks every link of the chain the site owner signed: ed25519 signature +// over the record, site id derived from the owner key and name, manifest by its +// blake3, parts by theirs, the path resolution itself (a gateway must not skip +// a candidate that exists), and every chunk by its hash. Rollback to an older +// signed version is refused by remembering the highest seq seen per site. +// +// Every rule mirrors c0mpute `node/crates/c0mpute-core/src/hosting/site.rs` +// (profullstack/c0mpute); a change there must change here. + +import { createPublicKey, verify as edVerify } from "node:crypto"; +import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { blake3 } from "../vendor/noble-hashes/blake3.js"; + +/** Files are cut into chunks of this size (site.rs FILE_CHUNK_BYTES). */ +export const FILE_CHUNK_BYTES = 1024 * 1024; +/** Largest site (site.rs MAX_SITE_BYTES). */ +export const MAX_SITE_BYTES = 1024 * 1024 * 1024; +const MAX_FILES = 10_000_000; +const MAX_INLINE_FILES = 10_000; +const PART_FILES = 4_000; + +const HASH_RE = /^[0-9a-f]{64}$/; +const KEY_RE = /^[0-9a-f]{64}$/; +const SIG_RE = /^[0-9a-f]{128}$/; +const SITE_RE = /^[0-9a-f]{20}$/; +const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/; + +export class VerifyError extends Error {} + +function fail(msg: string): never { throw new VerifyError(msg); } + +/** blake3 of `bytes`, lowercase hex. */ +export function blake3hex(bytes: Uint8Array | string): string { + const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes; + return Buffer.from(blake3(data)).toString("hex"); +} + +/** Compare as Rust compares `String`s: by UTF-8 bytes. */ +export function cmpPath(a: string, b: string): number { + return Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8")); +} + +/* -------------------------------------------------------------- records */ + +export interface SiteRecord { + v: number; + site_id: string; + name: string; + owner: string; + manifest: string; + seq: number; + size: number; + domains: string[]; + preferred_hosts?: string[]; + price_per_gib_month?: string | null; + payer?: string | null; + sig: string; +} + +/** The bytes the owner signs (site.rs SiteRecord::signing_bytes). */ +export function signingBytes(r: SiteRecord): Buffer { + const base = `${r.v >= 2 ? "c0mpute-hosting-v2" : "c0mpute-hosting-v1"}\n${r.site_id}\n${r.name}\n${r.owner}\n${r.manifest}\n${r.seq}\n${r.size}\n${(r.domains ?? []).join(",")}`; + if (r.v < 2) return Buffer.from(base, "utf8"); + return Buffer.from(`${base}\n${(r.preferred_hosts ?? []).join(",")}\n${r.price_per_gib_month ?? ""}\n${r.payer ?? ""}`, "utf8"); +} + +/** The id a site with this owner and name always has (site.rs site_id_for). */ +export function siteIdFor(ownerHex: string, name: string): string { + return blake3hex(`c0mpute-site\n${ownerHex}\n${name}`).slice(0, 20); +} + +const SPKI_ED25519 = Buffer.from("302a300506032b6570032100", "hex"); + +/** ed25519 over raw 32-byte key and 64-byte signature, both hex. */ +export function ed25519Verify(ownerHex: string, sigHex: string, message: Uint8Array): boolean { + if (!KEY_RE.test(ownerHex) || !SIG_RE.test(sigHex)) return false; + try { + const key = createPublicKey({ key: Buffer.concat([SPKI_ED25519, Buffer.from(ownerHex, "hex")]), format: "der", type: "spki" }); + return edVerify(null, message, key, Buffer.from(sigHex, "hex")); + } catch { + return false; + } +} + +const isStrArray = (v: unknown): v is string[] => Array.isArray(v) && v.every((s) => typeof s === "string"); +const isU64 = (v: unknown): v is number => typeof v === "number" && Number.isSafeInteger(v) && v >= 0; + +/** + * Check a record is well formed, is the site asked for, and that its owner + * signed it. Returns the record typed; throws VerifyError otherwise. + */ +export function verifyRecord(input: unknown, siteId: string): SiteRecord { + const r = input as SiteRecord; + if (!r || typeof r !== "object") fail("record is not an object"); + if (r.v !== 1 && r.v !== 2) fail(`unsupported record version ${String(r.v)}`); + if (typeof r.site_id !== "string" || typeof r.name !== "string" || typeof r.owner !== "string" + || typeof r.manifest !== "string" || typeof r.sig !== "string") fail("record fields missing"); + if (!isU64(r.seq) || !isU64(r.size)) fail("record seq/size is not a safe integer"); + const domains = r.domains ?? []; + if (!isStrArray(domains)) fail("record domains malformed"); + if (r.v === 1) { + if ((r.preferred_hosts?.length ?? 0) > 0 || (r.price_per_gib_month ?? null) !== null || (r.payer ?? null) !== null) { + fail("a v1 record carries no marketplace terms"); + } + } else { + if (!isStrArray(r.preferred_hosts ?? [])) fail("record preferred_hosts malformed"); + if (r.price_per_gib_month != null && typeof r.price_per_gib_month !== "string") fail("record price malformed"); + if (r.payer != null && !(typeof r.payer === "string" && KEY_RE.test(r.payer))) fail("record payer malformed"); + } + if (!NAME_RE.test(r.name)) fail("bad site name"); + if (!KEY_RE.test(r.owner)) fail("owner is not a hex ed25519 key"); + if (!HASH_RE.test(r.manifest)) fail("manifest is not a hash"); + if (r.size > MAX_SITE_BYTES) fail("site is over the size cap"); + if (!SITE_RE.test(siteId) || r.site_id !== siteId) fail("record is for another site"); + if (siteIdFor(r.owner, r.name) !== r.site_id) fail("site id does not match owner and name"); + if (!ed25519Verify(r.owner, r.sig, signingBytes({ ...r, domains }))) fail("bad record signature"); + return { ...r, domains }; +} + +/* ------------------------------------------------------------ manifests */ + +export interface FileEntry { size: number; content_type: string; chunks: string[] } +export interface PartRef { first: string; hash: string; files: number; bytes: number } +export type Manifest = + | { kind: "inline"; name: string; files: Map } + | { kind: "parted"; name: string; files: number; bytes: number; parts: PartRef[] }; + +/** A manifest path (site.rs valid_path). */ +export function validPath(p: string): boolean { + return p.length > 0 && Buffer.byteLength(p) <= 1024 && !p.startsWith("/") && !p.includes("\\") + && p.split("/").every((s) => s !== "" && s !== "." && s !== "..") + // eslint-disable-next-line no-control-regex + && !/[\u0000-\u001f\u007f-\u009f]/.test(p); +} + +/** Chunks a file of `size` bytes is cut into. */ +export function chunkCount(size: number): number { + return Math.max(1, Math.ceil(size / FILE_CHUNK_BYTES)); +} + +function checkEntry(path: string, e: unknown): FileEntry { + const f = e as FileEntry; + if (!validPath(path)) fail(`invalid path in manifest: ${JSON.stringify(path)}`); + if (!f || typeof f !== "object" || !isU64(f.size) || typeof f.content_type !== "string" || !isStrArray(f.chunks)) { + fail(`file ${JSON.stringify(path)} is malformed`); + } + if (f.chunks.length !== chunkCount(f.size) || !f.chunks.every((h) => HASH_RE.test(h))) { + fail(`file ${JSON.stringify(path)} has a bad chunk list`); + } + return { size: f.size, content_type: f.content_type, chunks: [...f.chunks] }; +} + +function filesMap(files: unknown, max: number): Map { + if (!files || typeof files !== "object" || Array.isArray(files)) fail("manifest files malformed"); + const keys = Object.keys(files); + if (keys.length > max) fail("manifest lists too many files"); + const out = new Map(); + for (const k of keys) out.set(k, checkEntry(k, (files as Record)[k])); + return out; +} + +function parseJson(bytes: Uint8Array, what: string): Record { + let v: unknown; + try { v = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch { fail(`${what} is not JSON`); } + if (!v || typeof v !== "object" || Array.isArray(v)) fail(`${what} is not an object`); + return v as Record; +} + +/** Parse and check the manifest chunk a verified record pins. */ +export function verifyManifest(bytes: Uint8Array, record: SiteRecord): Manifest { + if (blake3hex(bytes) !== record.manifest) fail("manifest does not match the record's hash"); + const m = parseJson(bytes, "manifest"); + if (m.name !== record.name) fail("manifest is for another site name"); + if (m.v === 1) { + const files = filesMap(m.files, MAX_INLINE_FILES); + let total = 0; + for (const f of files.values()) total += f.size; + if (total > MAX_SITE_BYTES) fail("site is over the size cap"); + return { kind: "inline", name: m.name as string, files }; + } + if (m.v === 2) { + const parts = m.parts as PartRef[]; + if (!isU64(m.files) || !isU64(m.bytes) || !Array.isArray(parts) || parts.length === 0) fail("manifest root malformed"); + if ((m.files as number) > MAX_FILES || (m.bytes as number) > MAX_SITE_BYTES) fail("manifest root out of bounds"); + if (parts.length > Math.ceil(MAX_FILES / PART_FILES)) fail("manifest has too many parts"); + let files = 0, total = 0; + for (const p of parts) { + if (!p || typeof p.first !== "string" || typeof p.hash !== "string" || !isU64(p.files) || !isU64(p.bytes) + || !HASH_RE.test(p.hash) || !validPath(p.first)) fail("manifest parts are malformed"); + files += p.files; + total += p.bytes; + } + if (files !== m.files || total !== m.bytes) fail("manifest parts do not add up"); + for (let i = 1; i < parts.length; i++) if (cmpPath(parts[i - 1].first, parts[i].first) >= 0) fail("manifest parts out of order"); + return { kind: "parted", name: m.name as string, files: m.files as number, bytes: m.bytes as number, + parts: parts.map((p) => ({ first: p.first, hash: p.hash, files: p.files, bytes: p.bytes })) }; + } + fail(`unsupported manifest version ${String(m.v)}`); +} + +/** Parse and check one part of a parted manifest against the ref naming it. */ +export function verifyPart(bytes: Uint8Array, ref: PartRef): Map { + if (blake3hex(bytes) !== ref.hash) fail("manifest part does not match its hash"); + const p = parseJson(bytes, "manifest part"); + if (p.v !== 2) fail("manifest part version"); + const files = filesMap(p.files, PART_FILES); + if (files.size !== ref.files) fail("manifest part does not match the root"); + let first: string | null = null, total = 0; + for (const [k, f] of files) { + if (first === null || cmpPath(k, first) < 0) first = k; + total += f.size; + } + if (first !== ref.first) fail("manifest part starts at the wrong path"); + if (total !== ref.bytes) fail("manifest part size does not match the root"); + return files; +} + +/** The part that would hold `path`: the last whose first path <= it. */ +export function partFor(parts: PartRef[], path: string): PartRef | null { + let found: PartRef | null = null; + for (const p of parts) { + if (cmpPath(p.first, path) <= 0) found = p; else break; + } + return found; +} + +/* ------------------------------------------------------------ resolving */ + +function percentDecode(s: string): string { + const bytes = Buffer.from(s, "utf8"); + const out: number[] = []; + const hex = (b: number) => (b >= 48 && b <= 57 ? b - 48 : b >= 97 && b <= 102 ? b - 87 : b >= 65 && b <= 70 ? b - 55 : -1); + for (let i = 0; i < bytes.length; i++) { + if (bytes[i] === 37 && i + 2 < bytes.length) { + const h = hex(bytes[i + 1]), l = hex(bytes[i + 2]); + if (h >= 0 && l >= 0) { out.push(h * 16 + l); i += 2; continue; } + } + out.push(bytes[i]); + } + return new TextDecoder("utf-8").decode(Uint8Array.from(out)); +} + +/** The manifest paths a request path may map to, in order (site.rs candidates). */ +export function candidates(request: string): string[] { + const p = request.replace(/^\/+/, "").split(/[?#]/)[0] ?? ""; + const decoded = percentDecode(p); + if (decoded === "" || decoded.endsWith("/")) return [`${decoded}index.html`]; + const out = [decoded]; + const last = decoded.slice(decoded.lastIndexOf("/") + 1); + if (!last.includes(".")) out.push(`${decoded}.html`, `${decoded}/index.html`); + return out; +} + +/** What a gateway's resolve route answers, as sent. */ +export interface ResolveAnswer { + v: number; + record: unknown; + manifest: string; + parts?: string[]; + path: string | null; + status: number; + entry: FileEntry | null; +} + +export interface Resolved { + record: SiteRecord; + /** The manifest path served, or null for a plain 404. */ + path: string | null; + status: 200 | 404; + entry: FileEntry | null; +} + +const b64 = (s: unknown, what: string): Buffer => { + if (typeof s !== "string" || !/^[A-Za-z0-9+/_-]*={0,2}$/.test(s)) fail(`${what} is not base64`); + return Buffer.from(s, "base64"); +}; + +/** + * Check a gateway's resolve answer for `requestPath` of `siteId`, end to end. + * `minSeq` is the highest seq already verified for the site (rollback guard). + */ +export function verifyResolve(siteId: string, requestPath: string, answer: unknown, minSeq = 0): Resolved { + const a = answer as ResolveAnswer; + if (!a || typeof a !== "object" || a.v !== 1) fail("resolve answer malformed"); + const record = verifyRecord(a.record, siteId); + if (record.seq < minSeq) fail(`rollback: seq ${record.seq} is older than ${minSeq}`); + const manifest = verifyManifest(b64(a.manifest, "manifest"), record); + + let lookup: (path: string) => FileEntry | null; + if (manifest.kind === "inline") { + lookup = (path) => manifest.files.get(path) ?? null; + } else { + const given = new Map>(); + if (a.parts !== undefined && !Array.isArray(a.parts)) fail("resolve parts malformed"); + for (const raw of a.parts ?? []) { + const bytes = b64(raw, "manifest part"); + const hash = blake3hex(bytes); + const ref = manifest.parts.find((p) => p.hash === hash); + if (!ref) fail("a manifest part the root does not name"); + given.set(hash, verifyPart(bytes, ref)); + } + lookup = (path) => { + const ref = partFor(manifest.parts, path); + if (!ref) return null; + const files = given.get(ref.hash); + if (!files) fail(`the gateway left out the manifest part for ${JSON.stringify(path)}`); + return files.get(path) ?? null; + }; + } + + // What the site actually serves for this path, worked out here, not taken + // from the gateway: the first candidate present, else 404.html as a 404. + let want: { path: string; status: 200 | 404; entry: FileEntry } | null = null; + for (const c of candidates(requestPath)) { + const e = lookup(c); + if (e) { want = { path: c, status: 200, entry: e }; break; } + } + if (!want) { + const e = lookup("404.html"); + if (e) want = { path: "404.html", status: 404, entry: e }; + } + + if (!want) { + if (a.path !== null || a.status !== 404) fail("the gateway claims a file the site does not resolve to"); + return { record, path: null, status: 404, entry: null }; + } + if (a.path !== want.path) fail(`the gateway resolved ${JSON.stringify(a.path)}, the site resolves ${JSON.stringify(want.path)}`); + if (a.status !== want.status) fail("the gateway's status does not match the site's"); + const e = a.entry; + if (!e || e.size !== want.entry.size || e.content_type !== want.entry.content_type || !Array.isArray(e.chunks) + || e.chunks.length !== want.entry.chunks.length || e.chunks.some((h, i) => h !== want!.entry.chunks[i])) { + fail("the gateway's entry does not match the manifest"); + } + return { record, path: want.path, status: want.status, entry: want.entry }; +} + +/** Check one chunk against the hash the manifest gives it. */ +export function verifyChunk(bytes: Uint8Array, hash: string, expectedLength?: number): void { + if (expectedLength !== undefined && bytes.length !== expectedLength) fail(`chunk ${hash.slice(0, 12)} is ${bytes.length} bytes, want ${expectedLength}`); + if (blake3hex(bytes) !== hash) fail(`chunk ${hash.slice(0, 12)} does not match its hash`); +} + +/** The length chunk `i` of a file of `size` bytes must have. */ +export function chunkLength(size: number, i: number): number { + return Math.max(0, Math.min(FILE_CHUNK_BYTES, size - i * FILE_CHUNK_BYTES)); +} + +/** The ETag a gateway gives a file (mod.rs Hosting::serve). */ +export function entryEtag(entry: FileEntry): string { + return `"${blake3hex(entry.chunks.join(",")).slice(0, 32)}"`; +} + +/* ------------------------------------------------------- rollback guard */ + +/** + * The highest verified seq per site. A record with a lower seq, from any + * gateway, is a rollback to an older signed version and is refused. Kept on + * disk (one JSON file) when given a path. + */ +export class SeqGuard { + private seqs = new Map(); + private file: string | null; + private dirty = false; + private writing: Promise | null = null; + + constructor(opts: { file?: string | null } = {}) { this.file = opts.file ?? null; } + + async load(): Promise { + if (!this.file) return; + try { + const raw = JSON.parse(await readFile(this.file, "utf8")) as Record; + for (const [k, v] of Object.entries(raw)) if (SITE_RE.test(k) && isU64(v)) this.seqs.set(k, v); + } catch { /* none yet */ } + } + + min(site: string): number { return this.seqs.get(site) ?? 0; } + + note(site: string, seq: number): void { + if (seq <= this.min(site)) return; + this.seqs.set(site, seq); + if (!this.file) return; + this.dirty = true; + if (!this.writing) this.writing = this.drain().finally(() => { this.writing = null; }); + } + + /** Wait until every noted seq is on disk. */ + async flush(): Promise { + while (this.writing) await this.writing; + if (this.dirty) await this.drain(); + } + + private async drain(): Promise { + if (!this.file) return; + while (this.dirty) { + this.dirty = false; + const tmp = `${this.file}.${process.pid}.tmp`; + try { + await writeFile(tmp, JSON.stringify(Object.fromEntries(this.seqs))); + await rename(tmp, this.file); + } catch { unlink(tmp).catch(() => {}); } + } + } +} + +/* ---------------------------------------------------------- chunk cache */ + +/** + * Verified chunks on disk, by hash. Chunks are immutable, so a cached one is + * good forever; it is re-hashed on read anyway (a disk can rot). Pruned oldest + * first past `maxDiskBytes` on `load()`. + */ +export class ChunkCache { + private dir: string | null; + readonly maxDiskBytes: number; + + constructor(opts: { dir?: string | null; maxDiskBytes?: number } = {}) { + this.dir = opts.dir ?? null; + this.maxDiskBytes = opts.maxDiskBytes ?? 1024 * 1024 * 1024; + } + + async load(): Promise { + if (!this.dir) return; + try { + await mkdir(this.dir, { recursive: true }); + const files = await Promise.all((await readdir(this.dir)).filter((f) => HASH_RE.test(f)) + .map(async (f) => ({ f, st: await stat(join(this.dir!, f)) }))); + files.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs); + let total = 0; + for (const { f, st } of files) { + total += st.size; + if (total > this.maxDiskBytes) await unlink(join(this.dir, f)).catch(() => {}); + } + } catch { /* no disk cache */ } + } + + async get(hash: string): Promise { + if (!this.dir || !HASH_RE.test(hash)) return null; + try { + const bytes = await readFile(join(this.dir, hash)); + if (blake3hex(bytes) === hash) return bytes; + await unlink(join(this.dir, hash)).catch(() => {}); + } catch { /* not cached */ } + return null; + } + + /** Only ever called with bytes already checked against `hash`. */ + put(hash: string, bytes: Uint8Array): void { + if (!this.dir || !HASH_RE.test(hash)) return; + const file = join(this.dir, hash); + const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}`; + writeFile(tmp, bytes).then(() => rename(tmp, file)).catch(() => { unlink(tmp).catch(() => {}); }); + } +} diff --git a/package.json b/package.json index df1f487..4f0721a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@profullstack/moshpit-proxy", - "version": "0.2.0", + "version": "0.3.0", "private": true, "type": "module", "license": "Apache-2.0", diff --git a/tests/c0mpute-verify.test.ts b/tests/c0mpute-verify.test.ts new file mode 100644 index 0000000..3aad040 --- /dev/null +++ b/tests/c0mpute-verify.test.ts @@ -0,0 +1,452 @@ +// Verified reads from untrusted c0mpute gateways. Fixtures are built here in +// the exact formats c0mpute's hosting/site.rs produces (serde_json, BTreeMap +// key order, ed25519 over the same signing bytes), plus real records signed by +// the Rust node as golden vectors. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { generateKeyPairSync, sign as edSign } from "node:crypto"; +import type { KeyObject } from "node:crypto"; +import { createServer, request as httpRequest } from "node:http"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import type { AddressInfo } from "node:net"; +import { join } from "node:path"; + +import { + ChunkCache, + FILE_CHUNK_BYTES, + SeqGuard, + blake3hex, + candidates, + chunkLength, + cmpPath, + partFor, + signingBytes, + siteIdFor, + verifyChunk, + verifyRecord, + verifyResolve, +} from "../lib/c0mpute-verify.ts"; +import type { FileEntry, ResolveAnswer, SiteRecord } from "../lib/c0mpute-verify.ts"; +import { createEdgeHandler, GatewayPool } from "../lib/c0mpute-edge.ts"; +import { tempDir } from "./helpers.ts"; + +/* ------------------------------------------------------------ fixtures */ + +type Key = { owner: string; priv: KeyObject }; + +function newKey(): Key { + const { publicKey, privateKey } = generateKeyPairSync("ed25519"); + return { owner: publicKey.export({ format: "der", type: "spki" }).subarray(12).toString("hex"), priv: privateKey }; +} + +function signRecord(key: Key, r: Omit): SiteRecord { + const rec = { ...r, sig: "" } as SiteRecord; + rec.sig = edSign(null, signingBytes(rec), key.priv).toString("hex"); + return rec; +} + +interface Site { + id: string; + key: Key; + record: SiteRecord; + manifestBytes: Buffer; + /** Manifest parts by hash (v2 only), and the root's refs. */ + parts: Map; + refs: { first: string; hash: string; files: number; bytes: number }[]; + entries: Map; + chunks: Map; +} + +/** A site as `c0mpute hosting publish` would make it. `partFiles` > 0 makes a v2 (parted) manifest. */ +function makeSite(files: Record, opts: { name?: string; key?: Key; seq?: number; partFiles?: number; recordV?: 1 | 2 } = {}): Site { + const key = opts.key ?? newKey(); + const name = opts.name ?? "demo"; + const chunks = new Map(); + const entries = new Map(); + const paths = Object.keys(files).sort(cmpPath); + for (const p of paths) { + const body = Buffer.from(files[p]); + const hashes: string[] = []; + for (let off = 0; off === 0 || off < body.length; off += FILE_CHUNK_BYTES) { + const c = body.subarray(off, off + FILE_CHUNK_BYTES); + const h = blake3hex(c); + chunks.set(h, Buffer.from(c)); + hashes.push(h); + } + entries.set(p, { size: body.length, content_type: p.endsWith(".html") ? "text/html; charset=utf-8" : "application/octet-stream", chunks: hashes }); + } + // serde_json of a BTreeMap: keys in byte order, compact. + const obj = (ps: string[]) => Object.fromEntries(ps.map((p) => [p, entries.get(p)!])); + const total = paths.reduce((n, p) => n + entries.get(p)!.size, 0); + const parts = new Map(); + const refs: Site["refs"] = []; + let manifestBytes: Buffer; + if (opts.partFiles) { + for (let i = 0; i < paths.length; i += opts.partFiles) { + const ps = paths.slice(i, i + opts.partFiles); + const bytes = Buffer.from(JSON.stringify({ v: 2, files: obj(ps) })); + const hash = blake3hex(bytes); + parts.set(hash, bytes); + refs.push({ first: ps[0], hash, files: ps.length, bytes: ps.reduce((n, p) => n + entries.get(p)!.size, 0) }); + } + manifestBytes = Buffer.from(JSON.stringify({ v: 2, name, files: paths.length, bytes: total, parts: refs })); + } else { + manifestBytes = Buffer.from(JSON.stringify({ v: 1, name, files: obj(paths) })); + } + const id = siteIdFor(key.owner, name); + const base = { site_id: id, name, owner: key.owner, manifest: blake3hex(manifestBytes), seq: opts.seq ?? 1_794_000_000_000, size: total, domains: [] as string[] }; + const record = opts.recordV === 2 + ? signRecord(key, { v: 2, ...base, preferred_hosts: ["12D3KooWFTsCjAVPKYnak1H8N7By5UpgeipVScmuAyGeRzzsLwSu"], price_per_gib_month: "0.004" }) + : signRecord(key, { v: 1, ...base }); + return { id, key, record, manifestBytes, parts, refs, entries, chunks }; +} + +/** What an honest gateway's resolve route answers. */ +function honestAnswer(site: Site, reqPath: string): ResolveAnswer { + const consulted = new Set(); + const lookup = (p: string): FileEntry | null => { + if (site.refs.length) { + const ref = partFor(site.refs, p); + if (!ref) return null; + consulted.add(ref.hash); + } + return site.entries.get(p) ?? null; + }; + let path: string | null = null, status = 404; + for (const c of candidates(reqPath)) if (lookup(c)) { path = c; status = 200; break; } + if (!path && lookup("404.html")) path = "404.html"; + return { + v: 1, + record: site.record, + manifest: site.manifestBytes.toString("base64"), + parts: [...consulted].map((h) => site.parts.get(h)!.toString("base64")), + path, + status, + entry: path ? site.entries.get(path)! : null, + }; +} + +const PAGES = { "index.html": "

The Future of Hosting

", "og.png": "PNGDATA", "404.html": "lost", "foo": "raw foo", "foo.html": "foo page", "docs/index.html": "docs" }; + +/* -------------------------------------------------- golden: the Rust node */ + +test("records signed by the Rust node verify (v1 and v2), and site ids match the node's", () => { + const v1 = { v: 1, site_id: "1d9a7ea0594aaad346a6", name: "git-demo", owner: "827265f7d4362299c288a4eb17ae4cbf44e9932e883487adea3ed8d80f8aa299", manifest: "2df48aab981cba003363bc00743b145ede38649b297c1f797a6d77b12bb01e07", seq: 1794221463133, size: 3400, domains: [], sig: "8b9ec5b65429607ea8df7f27a22ab7810a7fe03b8d1fef8234c62f091927e6a2f6d8fb76c0ae1b9d8dda1f8dce4501f349d4aca99181206a464d37a1f291bc06" }; + const v2 = { v: 2, site_id: "37072519c7c3c8b3317b", name: "market", owner: "08107c499b722f28b24fe74b147e7ab6d154dfa95104d7f75e2afb587848c971", manifest: "e47db91a01f24e2c10f0eb39bbace65a60c76152de1c5bbaafe751cc7dbacf5c", seq: 1, size: 5242901, domains: [], preferred_hosts: ["12D3KooWFTsCjAVPKYnak1H8N7By5UpgeipVScmuAyGeRzzsLwSu", "12D3KooWPqGuuupmQnZUKnK4pBPxoMeMiNCFf2sHndTKH2Mif2TQ"], price_per_gib_month: "1", sig: "c03bee448306d731811a2f4958ea4bbc9e37d1126cf270e602574956605c1a1540d5bcee71cf0cbe49f37e7736e9613b92d450d0a970df1383f418e3c3ce1300" }; + assert.equal(verifyRecord(v1, v1.site_id).seq, 1794221463133); + assert.equal(verifyRecord(v2, v2.site_id).v, 2); + assert.throws(() => verifyRecord({ ...v2, price_per_gib_month: "2" }, v2.site_id), /signature/, "terms are signed"); + assert.equal(siteIdFor("07f84b7788e3f76ea66e865d594e99d495a432d651643b3837a4f08daa94cf1b", "ads-radio"), "c8dfa86eb28cfce56754"); + assert.equal(blake3hex(new Uint8Array()), "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"); +}); + +test("candidates mirror site.rs", () => { + assert.deepEqual(candidates("/"), ["index.html"]); + assert.deepEqual(candidates("/docs/"), ["docs/index.html"]); + assert.deepEqual(candidates("/foo"), ["foo", "foo.html", "foo/index.html"]); + assert.deepEqual(candidates("/a/b.css?x=1#y"), ["a/b.css"]); + assert.deepEqual(candidates("/hello%20world"), ["hello world", "hello world.html", "hello world/index.html"]); + assert.deepEqual(candidates("/caf%C3%A9.txt"), ["café.txt"]); +}); + +/* ------------------------------------------------------ verifyResolve */ + +test("an honest answer verifies: index, extensionless .html, directory index, 404.html", () => { + const s = makeSite(PAGES); + const r = verifyResolve(s.id, "/", honestAnswer(s, "/")); + assert.equal(r.path, "index.html"); + assert.equal(r.status, 200); + assert.equal(verifyResolve(s.id, "/foo", honestAnswer(s, "/foo")).path, "foo"); + assert.equal(verifyResolve(s.id, "/docs/", honestAnswer(s, "/docs/")).path, "docs/index.html"); + assert.equal(verifyResolve(s.id, "/docs", honestAnswer(s, "/docs")).path, "docs/index.html"); + const nf = verifyResolve(s.id, "/missing.css", honestAnswer(s, "/missing.css")); + assert.deepEqual([nf.path, nf.status], ["404.html", 404]); + const plain = makeSite({ "index.html": "x" }); + const none = verifyResolve(plain.id, "/nope", honestAnswer(plain, "/nope")); + assert.deepEqual([none.path, none.status, none.entry], [null, 404, null]); +}); + +test("a wrong signature, a tampered field, or a forged record is refused", () => { + const s = makeSite(PAGES); + const a = honestAnswer(s, "/"); + const flip = (hex: string) => (hex[0] === "0" ? "1" : "0") + hex.slice(1); + assert.throws(() => verifyResolve(s.id, "/", { ...a, record: { ...s.record, sig: flip(s.record.sig) } }), /signature/); + assert.throws(() => verifyResolve(s.id, "/", { ...a, record: { ...s.record, seq: s.record.seq + 1 } }), /signature/); + // A stranger signs a record for this site id with their own key. + const mallory = newKey(); + const forged = signRecord(mallory, { ...s.record, owner: mallory.owner }); + assert.throws(() => verifyResolve(s.id, "/", { ...a, record: forged }), /site id/); +}); + +test("a record for another site is refused", () => { + const s = makeSite(PAGES); + const other = makeSite(PAGES, { name: "other" }); + assert.throws(() => verifyResolve(s.id, "/", honestAnswer(other, "/")), /another site/); +}); + +test("rollback: a record older than the highest seq verified is refused", () => { + const key = newKey(); + const v1 = makeSite({ "index.html": "old" }, { key, seq: 100 }); + const v2 = makeSite({ "index.html": "new" }, { key, seq: 200 }); + assert.equal(v1.id, v2.id); + assert.equal(verifyResolve(v2.id, "/", honestAnswer(v2, "/"), 200).record.seq, 200); + assert.throws(() => verifyResolve(v1.id, "/", honestAnswer(v1, "/"), 200), /rollback/); +}); + +test("a tampered manifest, or one for another name, is refused", () => { + const s = makeSite(PAGES); + const a = honestAnswer(s, "/"); + const bad = Buffer.from(s.manifestBytes.toString().replace("The", "the")); + assert.throws(() => verifyResolve(s.id, "/", { ...a, manifest: Buffer.from(s.manifestBytes.toString().replace('"og.png"', '"og.PNG"')).toString("base64") }), /manifest does not match/); + assert.throws(() => verifyResolve(s.id, "/", { ...a, manifest: bad.toString("base64") + "AA" }), /manifest/); +}); + +test("candidate skipping: the gateway may not serve a later candidate when an earlier one exists", () => { + const s = makeSite(PAGES); + const honest = honestAnswer(s, "/foo"); + const lie = { ...honest, path: "foo.html", entry: s.entries.get("foo.html")! }; + assert.throws(() => verifyResolve(s.id, "/foo", lie), /resolved "foo.html", the site resolves "foo"/); + // Nor claim a page does not exist when it does, nor pass 404.html off as 200. + assert.throws(() => verifyResolve(s.id, "/", { ...honestAnswer(s, "/"), path: null, status: 404, entry: null }), /resolved null/); + assert.throws(() => verifyResolve(s.id, "/nope.css", { ...honestAnswer(s, "/nope.css"), status: 200 }), /status/); + // Nor swap in another file's entry under the right path. + assert.throws(() => verifyResolve(s.id, "/", { ...honestAnswer(s, "/"), entry: s.entries.get("og.png")! }), /entry/); + assert.throws(() => verifyResolve(s.id, "/", { ...honestAnswer(s, "/"), entry: { ...s.entries.get("index.html")!, content_type: "text/javascript" } }), /entry/); +}); + +test("404.html is served as a 404, and claiming a plain 404 when 404.html exists is refused", () => { + const s = makeSite(PAGES); + const r = verifyResolve(s.id, "/gone", honestAnswer(s, "/gone")); + assert.deepEqual([r.path, r.status, r.entry!.size], ["404.html", 404, 4]); + assert.throws(() => verifyResolve(s.id, "/gone", { ...honestAnswer(s, "/gone"), path: null, entry: null }), /resolved null/); +}); + +test("v2 parted sites: parts verified by hash, a left-out part is refused, skipping across parts is caught", () => { + const files: Record = {}; + for (let i = 0; i < 20; i++) files[`p/f${String(i).padStart(2, "0")}.txt`] = `file ${i}`; + Object.assign(files, { "index.html": "root", "zz/foo": "raw", "zz/foo.html": "page" }); + const s = makeSite(files, { partFiles: 3, recordV: 2 }); + assert.ok(s.refs.length >= 7); + const r = verifyResolve(s.id, "/p/f13.txt", honestAnswer(s, "/p/f13.txt")); + assert.equal(r.entry!.size, 7); + assert.equal(verifyResolve(s.id, "/", honestAnswer(s, "/")).path, "index.html"); + + const a = honestAnswer(s, "/p/f13.txt"); + assert.throws(() => verifyResolve(s.id, "/p/f13.txt", { ...a, parts: [] }), /left out the manifest part/); + const tampered = Buffer.from(Buffer.from(a.parts![0], "base64").toString().replace("file", "fil3")).toString("base64"); + assert.throws(() => verifyResolve(s.id, "/p/f13.txt", { ...a, parts: [tampered] }), /does not name/); + + // zz/foo and zz/foo.html: claim the .html, hand over only the part holding it. + const honest = honestAnswer(s, "/zz/foo"); + assert.equal(honest.path, "zz/foo"); + const fooHtmlPart = partFor(s.refs, "zz/foo.html")!; + const lie = { ...honest, path: "zz/foo.html", entry: s.entries.get("zz/foo.html")!, parts: [s.parts.get(fooHtmlPart.hash)!.toString("base64")] }; + assert.throws(() => verifyResolve(s.id, "/zz/foo", lie), /resolved|left out/); +}); + +test("chunks: hash and length checked", () => { + const body = Buffer.alloc(FILE_CHUNK_BYTES + 10, 7); + const s = makeSite({ "big.bin": body }); + const e = s.entries.get("big.bin")!; + assert.equal(e.chunks.length, 2); + assert.equal(chunkLength(e.size, 1), 10); + verifyChunk(s.chunks.get(e.chunks[1])!, e.chunks[1], 10); + const bad = Buffer.from(s.chunks.get(e.chunks[1])!); bad[0] ^= 1; + assert.throws(() => verifyChunk(bad, e.chunks[1], 10), /does not match/); + assert.throws(() => verifyChunk(s.chunks.get(e.chunks[0])!, e.chunks[1], 10), /bytes/); +}); + +test("SeqGuard keeps the floor across a restart", async () => { + const dir = await tempDir(); + const file = join(dir, "seqs.json"); + const g = new SeqGuard({ file }); + g.note("0123456789abcdef0123", 5); + g.note("0123456789abcdef0123", 3); + await g.flush(); + const g2 = new SeqGuard({ file }); + await g2.load(); + assert.equal(g2.min("0123456789abcdef0123"), 5); +}); + +/* ------------------------------------------------------ through the edge */ + +interface FakeGateway { + url: string; + site: Site; + /** Resolve route present (c0mpute >= 0.3.5). */ + routes?: boolean; + tamperChunk?: boolean; + /** /s/ requests seen: an untrusted gateway must never get one. */ + sSeen?: number; +} + +function gatewayFetch(gws: FakeGateway[], seen: string[] = []): typeof fetch { + return (async (input: string | URL | Request) => { + const url = new URL(String(input)); + seen.push(url.href); + const gw = gws.find((g) => g.url === url.origin); + if (!gw) throw new Error(`connect ECONNREFUSED ${url.origin}`); + const m = url.pathname.match(/^\/hosting\/v1\/sites\/([0-9a-f]{20})\/(resolve|chunks\/([0-9a-f]{64}))$/); + if (url.pathname.startsWith("/s/")) { + gw.sSeen = (gw.sSeen ?? 0) + 1; + return new Response("UNVERIFIED BYTES", { status: 200, headers: { "content-type": "text/html" } }); + } + if (!m || gw.routes === false) return new Response("not found", { status: 404 }); + if (m[2] === "resolve") return Response.json(honestAnswer(gw.site, url.searchParams.get("path") ?? "/")); + const c = gw.site.chunks.get(m[3]); + if (!c) return new Response("no", { status: 404 }); + const out = Buffer.from(c); + if (gw.tamperChunk) out[0] ^= 0xff; + return new Response(out); + }) as typeof fetch; +} + +function pool(urls: string[], trusted: string[] = []) { + return { pick: () => urls, succeeded: () => {}, failed: () => {}, isTrusted: (u: string) => trusted.includes(u) }; +} + +async function serve(handler: (req: IncomingMessage, res: ServerResponse) => Promise) { + const server = createServer((req, res) => { void handler(req, res); }); + await new Promise((r) => server.listen(0, "127.0.0.1", () => r())); + const port = (server.address() as AddressInfo).port; + const call = (path: string, method = "GET", headers: Record = {}) => + new Promise<{ status: number; body: Buffer; headers: Record }>((resolve, reject) => { + const req = httpRequest({ host: "127.0.0.1", port, method, path, headers: { host: "blue.eggs", ...headers } }, (res) => { + const parts: Buffer[] = []; + res.on("data", (d) => parts.push(d)); + res.on("end", () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(parts), headers: res.headers })); + res.on("error", reject); + }); + req.on("error", reject); + req.end(); + }); + return { call, close: () => server.close() }; +} + +const quiet = { sleep: async () => {}, retries: 0, lastGood: null } as const; + +test("edge: an untrusted gateway is served from only after verification; multi-chunk files stream", async (t) => { + const big = Buffer.alloc(2 * FILE_CHUNK_BYTES + 123); + for (let i = 0; i < big.length; i++) big[i] = (i * 31) & 0xff; + const s = makeSite({ ...PAGES, "big.bin": big }); + const g: FakeGateway = { url: "http://stranger:7777", site: s }; + const handler = createEdgeHandler({ ...quiet, sites: { site: async () => s.id }, gateways: pool([g.url]), fetchImpl: gatewayFetch([g]) }); + const srv = await serve(handler); + t.after(srv.close); + + const home = await srv.call("/"); + assert.equal(home.status, 200); + assert.equal(home.body.toString(), PAGES["index.html"]); + assert.equal(home.headers["x-c0mpute-verified"], "1"); + assert.equal(home.headers["content-type"], "text/html; charset=utf-8"); + const b = await srv.call("/big.bin"); + assert.equal(b.status, 200); + assert.ok(b.body.equals(big)); + const nf = await srv.call("/nope.css"); + assert.deepEqual([nf.status, nf.body.toString()], [404, "lost"]); + const head = await srv.call("/og.png", "HEAD"); + assert.deepEqual([head.status, head.headers["content-length"], head.body.length], [200, "7", 0]); + const etag = String(home.headers.etag); + assert.equal((await srv.call("/", "GET", { "if-none-match": etag })).status, 304); + assert.equal(g.sSeen ?? 0, 0, "never asked an untrusted gateway for raw /s/ bytes"); +}); + +test("edge: a tampered chunk is never served; an honest source supplies it, else the request fails", async (t) => { + const s = makeSite(PAGES); + const liar: FakeGateway = { url: "http://liar:7777", site: s, tamperChunk: true }; + const honest: FakeGateway = { url: "http://honest:7777", site: s }; + const logs: string[] = []; + const h1 = createEdgeHandler({ ...quiet, log: (l) => logs.push(l), sites: { site: async () => s.id }, gateways: pool([liar.url, honest.url]), fetchImpl: gatewayFetch([liar, honest]) }); + const srv1 = await serve(h1); + t.after(srv1.close); + const ok = await srv1.call("/"); + assert.equal(ok.status, 200); + assert.equal(ok.body.toString(), PAGES["index.html"]); + assert.ok(logs.some((l) => /REJECTED/.test(l) && l.includes("liar"))); + + const h2 = createEdgeHandler({ ...quiet, sites: { site: async () => s.id }, gateways: pool([liar.url]), fetchImpl: gatewayFetch([liar]) }); + const srv2 = await serve(h2); + t.after(srv2.close); + const bad = await srv2.call("/"); + assert.equal(bad.status, 503); + assert.ok(!bad.body.toString().includes("Future"), "no tampered or unverified bytes"); +}); + +test("edge: an untrusted gateway without the resolve route (c0mpute < 0.3.5) is skipped, never proxied", async (t) => { + const s = makeSite(PAGES); + const old: FakeGateway = { url: "http://old:7777", site: s, routes: false }; + const ours: FakeGateway = { url: "http://127.0.0.1:7777", site: s }; + const seen: string[] = []; + const h = createEdgeHandler({ ...quiet, sites: { site: async () => s.id }, gateways: pool([old.url, ours.url], [ours.url]), fetchImpl: gatewayFetch([old, ours], seen) }); + const srv = await serve(h); + t.after(srv.close); + const r = await srv.call("/"); + assert.equal(r.status, 200); + assert.equal(r.body.toString(), "UNVERIFIED BYTES", "our own gateway is proxied as before"); + assert.equal(r.headers["x-c0mpute-gateway"], "127.0.0.1:7777"); + assert.equal(old.sSeen ?? 0, 0); + // Sitting out now: the next request does not even ask it. + const before = seen.filter((u) => u.startsWith(old.url)).length; + await srv.call("/og.png"); + assert.equal(seen.filter((u) => u.startsWith(old.url)).length, before); + + const alone = createEdgeHandler({ ...quiet, sites: { site: async () => s.id }, gateways: pool([old.url]), fetchImpl: gatewayFetch([old]) }); + const srv2 = await serve(alone); + t.after(srv2.close); + assert.equal((await srv2.call("/")).status, 503); + assert.equal(old.sSeen ?? 0, 0); +}); + +test("edge: rollback to an older record is refused across gateways", async (t) => { + const key = newKey(); + const newer = makeSite({ "index.html": "new" }, { key, seq: 200 }); + const older = makeSite({ "index.html": "old" }, { key, seq: 100 }); + const a: FakeGateway = { url: "http://a:7777", site: newer }; + const b: FakeGateway = { url: "http://b:7777", site: older }; + let order = [a.url]; + const gws = { pick: () => order, succeeded: () => {}, failed: () => {}, isTrusted: () => false }; + const h = createEdgeHandler({ ...quiet, sites: { site: async () => newer.id }, gateways: gws, fetchImpl: gatewayFetch([a, b]) }); + const srv = await serve(h); + t.after(srv.close); + assert.equal((await srv.call("/")).body.toString(), "new"); + order = [b.url]; + const r = await srv.call("/"); + assert.equal(r.status, 503); + assert.notEqual(r.body.toString(), "old"); +}); + +test("edge: C0MPUTE_VERIFY_ALL verifies our own gateways too; the pool trusts seeds, not discoveries", async (t) => { + const s = makeSite(PAGES); + const ours: FakeGateway = { url: "http://127.0.0.1:7777", site: s }; + const h = createEdgeHandler({ ...quiet, verifyAll: true, sites: { site: async () => s.id }, gateways: pool([ours.url], [ours.url]), fetchImpl: gatewayFetch([ours]) }); + const srv = await serve(h); + t.after(srv.close); + const r = await srv.call("/"); + assert.equal(r.body.toString(), PAGES["index.html"]); + assert.equal(r.headers["x-c0mpute-verified"], "1"); + assert.equal(ours.sSeen ?? 0, 0); + + const p = new GatewayPool({ + seeds: ["http://127.0.0.1:7777"], trusted: ["https://gw.example"], nodesUrl: "http://nodes/api", + fetchImpl: (async (u: string) => (String(u) === "http://nodes/api" + ? Response.json({ nodes: [{ gateway: "http://2.56.246.141:7777" }] }) : new Response("ok"))) as typeof fetch, + }); + await p.refresh(); + assert.equal(p.size, 3); + assert.ok(p.isTrusted("http://127.0.0.1:7777")); + assert.ok(p.isTrusted("https://gw.example")); + assert.ok(!p.isTrusted("http://2.56.246.141:7777"), "discovered from /api/nodes: a stranger's"); +}); + +test("ChunkCache returns only bytes that still hash right", async () => { + const dir = await tempDir(); + const c = new ChunkCache({ dir }); + await c.load(); + const bytes = Buffer.from("chunk"); + const h = blake3hex(bytes); + c.put(h, bytes); + await new Promise((r) => setTimeout(r, 50)); + assert.ok((await c.get(h))?.equals(bytes)); + assert.equal(await c.get(blake3hex("other")), null); +}); diff --git a/vendor/noble-hashes/LICENSE b/vendor/noble-hashes/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/vendor/noble-hashes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +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. \ No newline at end of file diff --git a/vendor/noble-hashes/README.md b/vendor/noble-hashes/README.md new file mode 100644 index 0000000..b2395fd --- /dev/null +++ b/vendor/noble-hashes/README.md @@ -0,0 +1,5 @@ +Unmodified files from `@noble/hashes` 2.4.0 (npm, MIT, Paul Miller): `blake3.js` +and what it imports, with their type declarations (only the sourceMappingURL +comments dropped). Vendored so the c0mpute edge keeps running from a plain +checkout with no `npm install` on the host. To update: `npm pack +@noble/hashes@` and copy the same files over. diff --git a/vendor/noble-hashes/_blake.d.ts b/vendor/noble-hashes/_blake.d.ts new file mode 100644 index 0000000..f55a44b --- /dev/null +++ b/vendor/noble-hashes/_blake.d.ts @@ -0,0 +1,20 @@ +/** + * Internal helpers for blake hash. + * @module + */ +import { type TRet } from './utils.ts'; +/** + * Internal blake permutation table. + * Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also + * reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows + * `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants. + */ +export declare const BSIGMA: TRet; +export type Num4 = { + a: number; + b: number; + c: number; + d: number; +}; +export declare function G1s(a: number, b: number, c: number, d: number, x: number): Num4; +export declare function G2s(a: number, b: number, c: number, d: number, x: number): Num4; diff --git a/vendor/noble-hashes/_blake.js b/vendor/noble-hashes/_blake.js new file mode 100644 index 0000000..2e70d9f --- /dev/null +++ b/vendor/noble-hashes/_blake.js @@ -0,0 +1,59 @@ +/** + * Internal helpers for blake hash. + * @module + */ +import { rotr } from "./utils.js"; +// Unrealized speed-up: a file-local copy of rotr measured ~1-2% faster blake2s/blake256/blake3 +// on Node 24 (V8 does not inline it into G1s/G2s across the module boundary). Reused from +// utils for deduplication. +/** + * Internal blake permutation table. + * Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also + * reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows + * `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants. + */ +// prettier-ignore +export const BSIGMA = /* @__PURE__ */ Uint8Array.from([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + // Blake1, unused in others + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, +]); +// Unrealized speed-up: G1s/G2s return a fresh {a,b,c,d} per call (160×/blake2s block), which +// V8's escape analysis does not eliminate when G stays a real call. Writing into one reused +// module-level slot instead measured +4-6% blake2s/blake256 1MB throughput on Node 24 — but +// ~2% slower blake3 (whose profile inlines G and scalar-replaces the fresh object) and no +// difference on 32-byte inputs. Kept simple. +// 32-bit / BLAKE2s first half of G, with the fixed `(16, 12)` rotation pair. +// Parameter `x` is the RFC 7693 first-half message word, or Blake1's pre-mixed +// `m[sigma[r][2i]] ^ u[sigma[r][2i+1]]` addend in the 32-bit path. +export function G1s(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} +// 32-bit / BLAKE2s second half of G. +// Parameter `x` is the RFC 7693 second-half (`y`) message word, or Blake1's pre-mixed +// `m[sigma[r][2i + 1]] ^ u[sigma[r][2i]]` addend in the 32-bit path. +export function G2s(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} diff --git a/vendor/noble-hashes/_md.d.ts b/vendor/noble-hashes/_md.d.ts new file mode 100644 index 0000000..40be220 --- /dev/null +++ b/vendor/noble-hashes/_md.d.ts @@ -0,0 +1,95 @@ +import { type Hash, type TArg, type TRet } from './utils.ts'; +/** + * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`. + * Returns bits from `b` when `a` is set, otherwise from `c`. + * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never + * set the same bit. + * @param a - selector word + * @param b - word chosen when selector bit is set + * @param c - word chosen when selector bit is clear + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit choice primitive. + * ```ts + * Chi(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export declare function Chi(a: number, b: number, c: number): number; +/** + * Shared 32-bit majority primitive reused by SHA-256 and SHA-1. + * Returns bits shared by at least two inputs. + * @param a - first input word + * @param b - second input word + * @param c - third input word + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit majority primitive. + * ```ts + * Maj(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export declare function Maj(a: number, b: number, c: number): number; +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit + * strings with partial-byte tails. + * @param blockLen - internal block size in bytes + * @param outputLen - digest size in bytes + * @param padOffset - trailing length field size in bytes + * @param isLE - whether length and state words are encoded in little-endian + * @example + * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow. + * ```ts + * import { _SHA1 } from '@noble/hashes/legacy.js'; + * const hash = new _SHA1(); + * hash.update(new Uint8Array([97, 98, 99])); + * hash.digest(); + * ``` + */ +export declare abstract class HashMD> implements Hash { + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract _cloneInto(to?: T): T; + abstract destroy(): void; + protected abstract roundClean(): void; + readonly blockLen: number; + readonly outputLen: number; + readonly canXOF = false; + readonly padOffset: number; + readonly isLE: boolean; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: TArg): this; + digestInto(out: TArg): void; + digest(): TRet; + protected _cloneIntoMeta(to: T): T; + clone(): T; +} +/** + * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53. + * Check out `test/misc/sha2-gen-iv.js` for recomputation guide. + */ +/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the + * square roots of the first eight prime numbers. Exported as a shared table; callers must treat + * it as read-only because constructors copy words from it by index. */ +export declare const SHA256_IV: TRet; +/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must + * treat it as read-only because constructors copy words from it by index. */ +export declare const SHA224_IV: TRet; +/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth + * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only + * because constructors copy halves from it by index. */ +export declare const SHA384_IV: TRet; +/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first + * eight prime numbers. Exported as a shared table; callers must treat it as read-only because + * constructors copy halves from it by index. */ +export declare const SHA512_IV: TRet; diff --git a/vendor/noble-hashes/_md.js b/vendor/noble-hashes/_md.js new file mode 100644 index 0000000..13049ff --- /dev/null +++ b/vendor/noble-hashes/_md.js @@ -0,0 +1,209 @@ +/** + * Internal Merkle-Damgard hash utils. + * @module + */ +import { setU64FromNum } from "./_u64.js"; +import { abytes, aexists, aoutput, createView } from "./utils.js"; +/** + * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`. + * Returns bits from `b` when `a` is set, otherwise from `c`. + * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never + * set the same bit. + * @param a - selector word + * @param b - word chosen when selector bit is set + * @param c - word chosen when selector bit is clear + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit choice primitive. + * ```ts + * Chi(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export function Chi(a, b, c) { + return (a & b) ^ (~a & c); +} +/** + * Shared 32-bit majority primitive reused by SHA-256 and SHA-1. + * Returns bits shared by at least two inputs. + * @param a - first input word + * @param b - second input word + * @param c - third input word + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit majority primitive. + * ```ts + * Maj(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export function Maj(a, b, c) { + return (a & b) ^ (a & c) ^ (b & c); +} +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit + * strings with partial-byte tails. + * @param blockLen - internal block size in bytes + * @param outputLen - digest size in bytes + * @param padOffset - trailing length field size in bytes + * @param isLE - whether length and state words are encoded in little-endian + * @example + * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow. + * ```ts + * import { _SHA1 } from '@noble/hashes/legacy.js'; + * const hash = new _SHA1(); + * hash.update(new Uint8Array([97, 98, 99])); + * hash.digest(); + * ``` + */ +export class HashMD { + blockLen; + outputLen; + canXOF = false; + padOffset; + isLE; + // For partial updates less than block size + buffer; + view; + finished = false; + length = 0; + pos = 0; + destroyed = false; + constructor(blockLen, outputLen, padOffset, isLE) { + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + const { view, buffer, blockLen } = this; + const len = data.length; + let processed = false; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path only when there is no buffered partial block: `take === blockLen` implies + // `this.pos === 0`, so we can process full blocks directly from the input view. + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + processed = true; + continue; + } + // When the whole input is buffered in one go (common for short messages), passing `data` + // directly avoids allocating a subarray view. + buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + processed = true; + } + } + this.length += data.length; + // Shared schedule buffers only pick up input-derived words inside process(); if everything + // was buffered without processing, there is nothing to zero. + if (processed) + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message, then zero-pad the rest of the block + buffer[pos++] = 0b10000000; + buffer.fill(0, pos); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + buffer.fill(0); + } + // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from + // the padding fill above, and JS will overflow before user input can make that half non-zero. + // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an + // integer below 2**53, so the split inside the helper stays exact). + setU64FromNum(view, blockLen - 8, this.length * 8, isLE); + this.process(view, 0); + // The final block above is processed outside update(), so the shared message-schedule + // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest(). + this.roundClean(); + // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one. + const oview = out === buffer ? view : createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT + const outLen = len / 4; + const state = this.get(); + // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state. + if (len % 4 || outLen > state.length) + throw new Error('invalid outputLen'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return + // fresh bytes to the caller. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneIntoMeta(to) { + const { buffer, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and + // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it. + if (pos) + to.buffer.set(buffer); // Avoid a hot modulo guard. + return to; + } + clone() { + return this._cloneInto(); + } +} +/** + * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53. + * Check out `test/misc/sha2-gen-iv.js` for recomputation guide. + */ +/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the + * square roots of the first eight prime numbers. Exported as a shared table; callers must treat + * it as read-only because constructors copy words from it by index. */ +export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]); +/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must + * treat it as read-only because constructors copy words from it by index. */ +export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4, +]); +/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth + * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only + * because constructors copy halves from it by index. */ +export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([ + 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4, +]); +/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first + * eight prime numbers. Exported as a shared table; callers must treat it as read-only because + * constructors copy halves from it by index. */ +export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([ + 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179, +]); diff --git a/vendor/noble-hashes/_u64.d.ts b/vendor/noble-hashes/_u64.d.ts new file mode 100644 index 0000000..3af8043 --- /dev/null +++ b/vendor/noble-hashes/_u64.d.ts @@ -0,0 +1,36 @@ +/** + * Internal helpers for u64. + * BigUint64Array is too slow as per 2026, so we implement it using + * Uint32Array. + * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588} + * @module + */ +import type { TRet } from './utils.ts'; +declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +declare function split(lst: bigint[], le?: boolean): TRet; +declare const toBig: (h: number, l: number) => bigint; +declare const fromNumH: (n: number) => number; +declare const fromNumL: (n: number) => number; +declare function setU64FromNum(view: DataView, byteOffset: number, n: number, isLE: boolean): void; +declare const shrSH: (h: number, _l: number, s: number) => number; +declare const shrSL: (h: number, l: number, s: number) => number; +declare const rotrSH: (h: number, l: number, s: number) => number; +declare const rotrSL: (h: number, l: number, s: number) => number; +declare const rotrBH: (h: number, l: number, s: number) => number; +declare const rotrBL: (h: number, l: number, s: number) => number; +declare const rotr32H: (_h: number, l: number) => number; +declare const rotr32L: (h: number, _l: number) => number; +declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const add3L: (Al: number, Bl: number, Cl: number) => number; +declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; +declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; +declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; +declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; +export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig }; diff --git a/vendor/noble-hashes/_u64.js b/vendor/noble-hashes/_u64.js new file mode 100644 index 0000000..a57c31c --- /dev/null +++ b/vendor/noble-hashes/_u64.js @@ -0,0 +1,77 @@ +const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))(); +const _32n = /* @__PURE__ */ BigInt(32); +// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high +// }` to match little-endian word order rather than the property names. +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array +// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`. +function split(lst, le = false) { + const len = lst.length; + let Ah = new Uint32Array(len); + let Al = new Uint32Array(len); + for (let i = 0; i < len; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS +// bitwise results back to uint32 first, and little-endian callers must swap. +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers +// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below +// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes). +const fromNumH = (n) => (n / 2 ** 32) | 0; +const fromNumL = (n) => n >>> 0; +// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call +// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`. +function setU64FromNum(view, byteOffset, n, isLE) { + const h = fromNumH(n); + const l = fromNumL(n); + view.setUint32(byteOffset, isLE ? l : h, isLE); + view.setUint32(byteOffset + 4, isLE ? h : l, isLE); +} +// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`. +const shrSH = (h, _l, s) => h >>> s; +// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`. +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`. +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`. +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half. +const rotr32H = (_h, l) => l; +// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half. +const rotr32L = (h, _l) => h; +// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps +// local copies so V8 inlines them into keccakP. +// Add two split 64-bit words and return the split `{ h, l }` sum. +// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out +// of the low sum and instead use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`. +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`. +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`. +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`. +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`. +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`. +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig }; diff --git a/vendor/noble-hashes/blake2.d.ts b/vendor/noble-hashes/blake2.d.ts new file mode 100644 index 0000000..9637116 --- /dev/null +++ b/vendor/noble-hashes/blake2.d.ts @@ -0,0 +1,203 @@ +import { type CHash, type Hash, type TArg, type TRet } from './utils.ts'; +/** + * Blake hash options. + * `dkLen` is output length. `key` is used in MAC mode. `salt` is used in + * KDF mode. + */ +export type Blake2Opts = { + /** Desired digest length in bytes. RFC 7693 uses 1..64 for blake2b and 1..32 for blake2s. */ + dkLen?: number; + /** Optional MAC key. */ + key?: Uint8Array; + /** Optional salt mixed into initialization. */ + salt?: Uint8Array; + /** Optional personalization bytes. */ + personalization?: Uint8Array; +}; +/** Internal base class for BLAKE2. */ +export declare abstract class _BLAKE2> implements Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected finished: boolean; + protected destroyed: boolean; + protected length: number; + protected pos: number; + readonly blockLen: number; + readonly outputLen: number; + readonly canXOF: boolean; + constructor(blockLen: number, outputLen: number); + update(data: TArg): this; + digestInto(out: TArg): void; + digest(): TRet; + _cloneInto(to?: T): T; + clone(): T; +} +/** Internal blake2b hash class with state stored as LE u32 low/high halves. */ +export declare class _BLAKE2b extends _BLAKE2<_BLAKE2b> { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: Blake2Opts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present, + * must be 16 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2b. + * ```ts + * blake2b(new Uint8Array([97, 98, 99])); + * ``` + * @example + * Hash a message with Blake2b while selecting output, MAC, salt, and personalization settings. + * ```ts + * blake2b(new Uint8Array([97, 98, 99]), { + * dkLen: 32, + * key: new Uint8Array(32), + * salt: new Uint8Array(16), + * personalization: new Uint8Array(16), + * }); + * ``` + */ +export declare const blake2b: TRet>; +/** Internal type, 16 numbers. */ +export type _Num16 = { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +/** + * BLAKE2-compress core method. + * Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15` + * and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves. + * @param s - flattened sigma schedule bytes + * @param offset - starting word offset inside `msg`, not a byte offset + * @param msg - message words + * @param rounds - round count to execute + * @param v0 - state word 0 + * @param v1 - state word 1 + * @param v2 - state word 2 + * @param v3 - state word 3 + * @param v4 - state word 4 + * @param v5 - state word 5 + * @param v6 - state word 6 + * @param v7 - state word 7 + * @param v8 - state word 8 + * @param v9 - state word 9 + * @param v10 - state word 10 + * @param v11 - state word 11 + * @param v12 - state word 12 + * @param v13 - state word 13 + * @param v14 - state word 14 + * @param v15 - state word 15 + * @returns Updated compression state words. + * @example + * Run the BLAKE2 compression core on zeroed state and message words. + * ```ts + * import { _compress } from '@noble/hashes/blake2.js'; + * const state = _compress( + * new Uint8Array(16), + * 0, + * new Uint32Array(16), + * 1, + * 0, 0, 0, 0, 0, 0, 0, 0, + * 0, 0, 0, 0, 0, 0, 0, 0 + * ); + * state.v0; + * ``` + */ +export declare function _compress(s: TArg, offset: number, msg: TArg, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): _Num16; +/** Internal blake2s hash class. */ +export declare class _BLAKE2s extends _BLAKE2<_BLAKE2s> { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: Blake2Opts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present, + * must be 8 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2s. + * ```ts + * blake2s(new Uint8Array([97, 98, 99])); + * ``` + * @example + * Hash a message with Blake2s while selecting output, MAC, salt, and personalization settings. + * ```ts + * blake2s(new Uint8Array([97, 98, 99]), { + * dkLen: 16, + * key: new Uint8Array(32), + * salt: new Uint8Array(8), + * personalization: new Uint8Array(8), + * }); + * ``` + */ +export declare const blake2s: TRet>; diff --git a/vendor/noble-hashes/blake2.js b/vendor/noble-hashes/blake2.js new file mode 100644 index 0000000..38ead2e --- /dev/null +++ b/vendor/noble-hashes/blake2.js @@ -0,0 +1,573 @@ +/** + * blake2b (64-bit) & blake2s (8 to 32-bit) hash functions. + * b could have been faster, but there is no fast u64 in js, so s is 1.5x faster. + * @module + */ +import { BSIGMA, G1s, G2s } from "./_blake.js"; +import { SHA256_IV } from "./_md.js"; +import * as u64 from "./_u64.js"; +// prettier-ignore +import { abytes, aexists, anumber, aoutput, checkOpts, clean, copyBytes, createHasher, swap32IfBE, swap8IfBE, u32 } from "./utils.js"; +// Same IV words as `SHA512_IV`, but endian-swapped into LE u32 low/high halves +// for the BLAKE2b u64 helpers below. +const B2B_IV = /* @__PURE__ */ Uint32Array.from([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19, +]); +// Shared synchronous BLAKE2b work vector as LE u32 low/high halves. +const BBUF = /* @__PURE__ */ new Uint32Array(32); +// BLAKE2b G mix split into two half-rounds over LE u32 low/high limbs. +function G1b(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + const ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + let xh = Dh ^ Ah, xl = Dl ^ Al; // prettier-ignore + Dh = u64.rotr32H(xh, xl); + Dl = u64.rotr32L(xh, xl); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + xh = Bh ^ Ch; + xl = Bl ^ Cl; + Bh = u64.rotrSH(xh, xl, 24); + Bl = u64.rotrSL(xh, xl, 24); + BBUF[2 * a] = Al; + BBUF[2 * a + 1] = Ah; + BBUF[2 * b] = Bl; + BBUF[2 * b + 1] = Bh; + BBUF[2 * c] = Cl; + BBUF[2 * c + 1] = Ch; + BBUF[2 * d] = Dl; + BBUF[2 * d + 1] = Dh; +} +// Second half-round of the same LE-limb BLAKE2b G mix; `x` is the message word offset. +function G2b(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + const ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + let xh = Dh ^ Ah, xl = Dl ^ Al; // prettier-ignore + Dh = u64.rotrSH(xh, xl, 16); + Dl = u64.rotrSL(xh, xl, 16); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + xh = Bh ^ Ch; + xl = Bl ^ Cl; + Bh = u64.rotrBH(xh, xl, 63); + Bl = u64.rotrBL(xh, xl, 63); + BBUF[2 * a] = Al; + BBUF[2 * a + 1] = Ah; + BBUF[2 * b] = Bl; + BBUF[2 * b + 1] = Bh; + BBUF[2 * c] = Cl; + BBUF[2 * c + 1] = Ch; + BBUF[2 * d] = Dl; + BBUF[2 * d + 1] = Dh; +} +function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) { + anumber(keyLen); + // RFC 7693 §2.1 requires digest length nn in 1..keyLen (keyLen doubles as + // the per-variant max for both key and digest lengths: 64 for b, 32 for s). + if (outputLen <= 0 || outputLen > keyLen) + throw new Error('"dkLen" must be 1..' + keyLen + ', got ' + outputLen); + const { key, salt, personalization } = opts; + // This API uses `undefined` for the RFC 7693 `kk = 0` case, so a provided key must be non-empty. + if (key !== undefined && (key.length < 1 || key.length > keyLen)) + throw new Error('"key" expected to be undefined or of length=1..' + keyLen); + if (salt !== undefined) + abytes(salt, saltLen, 'salt'); + if (personalization !== undefined) + abytes(personalization, persLen, 'personalization'); +} +/** Internal base class for BLAKE2. */ +export class _BLAKE2 { + buffer; + buffer32; + finished = false; + destroyed = false; + length = 0; + pos = 0; + blockLen; + outputLen; + canXOF = false; + constructor(blockLen, outputLen) { + anumber(blockLen); + anumber(outputLen); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.buffer = new Uint8Array(blockLen); + this.buffer32 = u32(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + swap32IfBE(buffer32); + this.compress(buffer32, 0, false); + swap32IfBE(buffer32); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // Zero-copy only for full, 4-byte-aligned, non-final blocks. + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + swap32IfBE(data32); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + swap32IfBE(data32); + continue; + } + // When the whole input is buffered in one go (common for short messages), passing `data` + // directly avoids allocating a subarray view. + buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + // Reject unaligned views explicitly instead of hiding them behind a full scratch copy. + if (out.byteOffset & 3) + throw new RangeError('"output" expected 4-byte aligned byteOffset, got ' + out.byteOffset); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + this.buffer.fill(0, pos); + swap32IfBE(buffer32); + this.compress(buffer32, 0, true); + swap32IfBE(buffer32); + const state = this.get(); + // digest() passes our own `buffer` as `out`; reuse its cached u32 view instead of allocating. + const out32 = out === this.buffer ? buffer32 : u32(out); + const full = Math.floor(this.outputLen / 4); + for (let i = 0; i < full; i++) + out32[i] = swap8IfBE(state[i]); + const tail = this.outputLen % 4; + if (!tail) + return; + const off = full * 4; + const word = state[full]; + for (let i = 0; i < tail; i++) + out[off + i] = word >>> (8 * i); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Return a copy so callers do not alias the instance scratch buffer used during finalization. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + // Recreate only `dkLen`; key/salt/personalization are already absorbed into the copied state. + to ||= new this.constructor({ dkLen: outputLen }); + to.set(...this.get()); + // Last-block-aware lazy compression keeps the pending block live even when full. + to.buffer.set(buffer); + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + // @ts-ignore + to.outputLen = outputLen; + return to; + } + clone() { + return this._cloneInto(); + } +} +/** Internal blake2b hash class with state stored as LE u32 low/high halves. */ +export class _BLAKE2b extends _BLAKE2 { + // Same IV words as SHA-512 / BLAKE2b, encoded as LE u32 low/high halves. + v0l = B2B_IV[0] | 0; + v0h = B2B_IV[1] | 0; + v1l = B2B_IV[2] | 0; + v1h = B2B_IV[3] | 0; + v2l = B2B_IV[4] | 0; + v2h = B2B_IV[5] | 0; + v3l = B2B_IV[6] | 0; + v3h = B2B_IV[7] | 0; + v4l = B2B_IV[8] | 0; + v4h = B2B_IV[9] | 0; + v5l = B2B_IV[10] | 0; + v5h = B2B_IV[11] | 0; + v6l = B2B_IV[12] | 0; + v6h = B2B_IV[13] | 0; + v7l = B2B_IV[14] | 0; + v7h = B2B_IV[15] | 0; + constructor(opts = {}) { + opts = checkOpts({}, opts); + const olen = opts.dkLen === undefined ? 64 : opts.dkLen; + super(128, olen); + checkBlake2Opts(olen, opts, 64, 16, 16); + let { key, personalization, salt } = opts; + let keyLength = 0; + if (key !== undefined) { + abytes(key, undefined, 'key'); + keyLength = key.length; + } + // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` into the low 32 bits of `h[0]`; + // the high 32 bits stay at `IV[0]`. + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (salt !== undefined) { + abytes(salt, undefined, 'salt'); + // Copy: u32() would throw on views with byteOffset not divisible by 4. + const slt = u32(copyBytes(salt)); + this.v4l ^= swap8IfBE(slt[0]); + this.v4h ^= swap8IfBE(slt[1]); + this.v5l ^= swap8IfBE(slt[2]); + this.v5h ^= swap8IfBE(slt[3]); + } + if (personalization !== undefined) { + abytes(personalization, undefined, 'personalization'); + // Copy: u32() would throw on views with byteOffset not divisible by 4. + const pers = u32(copyBytes(personalization)); + this.v6l ^= swap8IfBE(pers[0]); + this.v6h ^= swap8IfBE(pers[1]); + this.v7l ^= swap8IfBE(pers[2]); + this.v7h ^= swap8IfBE(pers[3]); + } + if (key !== undefined) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(key); + this.update(tmp); + // The padded copy holds key material; buffer/state keep what they need. + clean(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + // First half from state. Direct writes: get() would allocate an array + + // closure per block. + // prettier-ignore + const { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + // prettier-ignore + { + BBUF[0] = v0l; + BBUF[1] = v0h; + BBUF[2] = v1l; + BBUF[3] = v1h; + BBUF[4] = v2l; + BBUF[5] = v2h; + BBUF[6] = v3l; + BBUF[7] = v3h; + BBUF[8] = v4l; + BBUF[9] = v4h; + BBUF[10] = v5l; + BBUF[11] = v5h; + BBUF[12] = v6l; + BBUF[13] = v6h; + BBUF[14] = v7l; + BBUF[15] = v7h; + } + BBUF.set(B2B_IV, 16); // Second half from IV. + const l = u64.fromNumL(this.length); + const h = u64.fromNumH(this.length); + BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset. + BBUF[25] = B2B_IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BBUF[28] = ~BBUF[28]; + BBUF[29] = ~BBUF[29]; + } + let j = 0; + const s = BSIGMA; + // SIGMA selects 64-bit message words; multiply by 2 because `msg` stores + // each word as [low32, high32]. + for (let i = 0; i < 12; i++) { + G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BBUF[0] ^ BBUF[16]; + this.v0h ^= BBUF[1] ^ BBUF[17]; + this.v1l ^= BBUF[2] ^ BBUF[18]; + this.v1h ^= BBUF[3] ^ BBUF[19]; + this.v2l ^= BBUF[4] ^ BBUF[20]; + this.v2h ^= BBUF[5] ^ BBUF[21]; + this.v3l ^= BBUF[6] ^ BBUF[22]; + this.v3h ^= BBUF[7] ^ BBUF[23]; + this.v4l ^= BBUF[8] ^ BBUF[24]; + this.v4h ^= BBUF[9] ^ BBUF[25]; + this.v5l ^= BBUF[10] ^ BBUF[26]; + this.v5h ^= BBUF[11] ^ BBUF[27]; + this.v6l ^= BBUF[12] ^ BBUF[28]; + this.v6h ^= BBUF[13] ^ BBUF[29]; + this.v7l ^= BBUF[14] ^ BBUF[30]; + this.v7h ^= BBUF[15] ^ BBUF[31]; + clean(BBUF); + } + destroy() { + this.destroyed = true; + clean(this.buffer32); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present, + * must be 16 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2b. + * ```ts + * blake2b(new Uint8Array([97, 98, 99])); + * ``` + * @example + * Hash a message with Blake2b while selecting output, MAC, salt, and personalization settings. + * ```ts + * blake2b(new Uint8Array([97, 98, 99]), { + * dkLen: 32, + * key: new Uint8Array(32), + * salt: new Uint8Array(16), + * personalization: new Uint8Array(16), + * }); + * ``` + */ +export const blake2b = /* @__PURE__ */ createHasher((opts) => new _BLAKE2b(opts)); +/** + * BLAKE2-compress core method. + * Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15` + * and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves. + * @param s - flattened sigma schedule bytes + * @param offset - starting word offset inside `msg`, not a byte offset + * @param msg - message words + * @param rounds - round count to execute + * @param v0 - state word 0 + * @param v1 - state word 1 + * @param v2 - state word 2 + * @param v3 - state word 3 + * @param v4 - state word 4 + * @param v5 - state word 5 + * @param v6 - state word 6 + * @param v7 - state word 7 + * @param v8 - state word 8 + * @param v9 - state word 9 + * @param v10 - state word 10 + * @param v11 - state word 11 + * @param v12 - state word 12 + * @param v13 - state word 13 + * @param v14 - state word 14 + * @param v15 - state word 15 + * @returns Updated compression state words. + * @example + * Run the BLAKE2 compression core on zeroed state and message words. + * ```ts + * import { _compress } from '@noble/hashes/blake2.js'; + * const state = _compress( + * new Uint8Array(16), + * 0, + * new Uint32Array(16), + * 1, + * 0, 0, 0, 0, 0, 0, 0, 0, + * 0, 0, 0, 0, 0, 0, 0, 0 + * ); + * state.v0; + * ``` + */ +// prettier-ignore +export function _compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +// Blake2s reuses the SHA-256 IV words as-is. +const B2S_IV = /* @__PURE__ */ SHA256_IV.slice(); +/** Internal blake2s hash class. */ +export class _BLAKE2s extends _BLAKE2 { + // Internal state, same as SHA-256 + v0 = B2S_IV[0] | 0; + v1 = B2S_IV[1] | 0; + v2 = B2S_IV[2] | 0; + v3 = B2S_IV[3] | 0; + v4 = B2S_IV[4] | 0; + v5 = B2S_IV[5] | 0; + v6 = B2S_IV[6] | 0; + v7 = B2S_IV[7] | 0; + constructor(opts = {}) { + opts = checkOpts({}, opts); + const olen = opts.dkLen === undefined ? 32 : opts.dkLen; + super(64, olen); + checkBlake2Opts(olen, opts, 32, 8, 8); + let { key, personalization, salt } = opts; + let keyLength = 0; + if (key !== undefined) { + abytes(key, undefined, 'key'); + keyLength = key.length; + } + // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` directly into `h[0]`, since + // BLAKE2s stores each state word as one `u32`. + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (salt !== undefined) { + abytes(salt, undefined, 'salt'); + // Copy: u32() would throw on views with byteOffset not divisible by 4. + const slt = u32(copyBytes(salt)); + this.v4 ^= swap8IfBE(slt[0]); + this.v5 ^= swap8IfBE(slt[1]); + } + if (personalization !== undefined) { + abytes(personalization, undefined, 'personalization'); + // Copy: u32() would throw on views with byteOffset not divisible by 4. + const pers = u32(copyBytes(personalization)); + this.v6 ^= swap8IfBE(pers[0]); + this.v7 ^= swap8IfBE(pers[1]); + } + if (key !== undefined) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(key); + this.update(tmp); + // The padded copy holds key material; buffer/state keep what they need. + clean(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const l = u64.fromNumL(this.length); + const h = u64.fromNumH(this.length); + // Seed v8..v15 from the IV, xor the low/high 32-bit byte counter into + // v12/v13, and invert v14 on the final block. + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + clean(this.buffer32); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present, + * must be 8 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2s. + * ```ts + * blake2s(new Uint8Array([97, 98, 99])); + * ``` + * @example + * Hash a message with Blake2s while selecting output, MAC, salt, and personalization settings. + * ```ts + * blake2s(new Uint8Array([97, 98, 99]), { + * dkLen: 16, + * key: new Uint8Array(32), + * salt: new Uint8Array(8), + * personalization: new Uint8Array(8), + * }); + * ``` + */ +export const blake2s = /* @__PURE__ */ createHasher((opts) => new _BLAKE2s(opts)); diff --git a/vendor/noble-hashes/blake3.d.ts b/vendor/noble-hashes/blake3.d.ts new file mode 100644 index 0000000..449077e --- /dev/null +++ b/vendor/noble-hashes/blake3.d.ts @@ -0,0 +1,68 @@ +import { _BLAKE2 } from './blake2.ts'; +import { type CHashXOF, type HashXOF, type TArg, type TRet } from './utils.ts'; +/** + * Ensure to use EITHER `key` OR `context`, not both. + * + * * `key`: 32-byte MAC key. + * * `context`: caller-encoded KDF context bytes. If your protocol defines a + * string context, encode it before passing it here. + * A good default format for the original context string is + * "[application] [commit timestamp] [purpose]". + */ +export type Blake3Opts = { + /** Desired digest length in bytes. The BLAKE3 spec allows 0..2^64-1 bytes of output. */ + dkLen?: number; + /** Optional 32-byte MAC key. */ + key?: Uint8Array; + /** Optional KDF context bytes. */ + context?: Uint8Array; +}; +/** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */ +export declare class _BLAKE3 extends _BLAKE2<_BLAKE3> implements HashXOF<_BLAKE3> { + readonly canXOF = true; + private chunkPos; + private chunksDone; + private flags; + private IV; + private state; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): []; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: _BLAKE3): _BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: TArg): TRet; + xof(bytes: number): TRet; + digestInto(out: TArg): void; + digest(): TRet; +} +/** + * BLAKE3 hash function. Can be used as MAC and KDF. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, or KDF configuration. `key` must be + * exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be + * 0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}. + * @returns Digest bytes. + * @example + * Hash, MAC, or derive key material with BLAKE3. + * ```ts + * import { blake3 } from '@noble/hashes/blake3.js'; + * import { utf8ToBytes } from '@noble/hashes/utils.js'; + * const data = new Uint8Array(32); + * const hash = blake3(data); + * const mac = blake3(data, { key: new Uint8Array(32) }); + * const kdf = blake3(data, { context: utf8ToBytes('application name') }); + * const xof = blake3(data, { dkLen: 64 }); + * ``` + */ +export declare const blake3: TRet>; diff --git a/vendor/noble-hashes/blake3.js b/vendor/noble-hashes/blake3.js new file mode 100644 index 0000000..58fd3a4 --- /dev/null +++ b/vendor/noble-hashes/blake3.js @@ -0,0 +1,310 @@ +/** + * Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF. + * + * It is advertised as "the fastest cryptographic hash". However, it isn't true in JS. + * Why is this so slow? While it must be 6x faster than blake2b, perf diff is only 20%: + * + * * There is only 30% reduction in number of rounds from blake2s + * * Speed-up comes from tree structure, which is parallelized using SIMD & threading. + * These features are not present in JS, so we only get overhead from trees. + * * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs. + * * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm + * @module + */ +import { SHA256_IV } from "./_md.js"; +import { fromNumH, fromNumL } from "./_u64.js"; +import { _BLAKE2, _compress } from "./blake2.js"; +// prettier-ignore +import { abytes, aexists, anumber, aoutput, checkOpts, clean, copyBytes, createHasher, swap32IfBE, u32, u8 } from "./utils.js"; +// Constructor-time mode flags (`KEYED_HASH`, `DERIVE_*`) plus per-node tree +// flags (`CHUNK_*`, `PARENT`, `ROOT`). +const B3_Flags = { + CHUNK_START: 0b1, + CHUNK_END: 0b10, + PARENT: 0b100, + ROOT: 0b1000, + KEYED_HASH: 0b10000, + DERIVE_KEY_CONTEXT: 0b100000, + DERIVE_KEY_MATERIAL: 0b1000000, +}; +// Default BLAKE3 IV, cloned from the shared BLAKE2s / SHA-256 IV basis. +const B3_IV = /* @__PURE__ */ SHA256_IV.slice(); +// Seven 16-word rounds of BLAKE3 message schedule, generated by repeatedly +// permuting the identity row. +const B3_SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +/** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */ +export class _BLAKE3 extends _BLAKE2 { + canXOF = true; + chunkPos = 0; // Position of current block in chunk + // How many chunks we already have; exact while this stays within + // JS's safe-integer range. + chunksDone = 0; + flags = 0 | 0; + IV; + state; + stack = []; + // Output + posOut = 0; + bufferOut32 = new Uint32Array(16); + bufferOut; + // Index of output chunk; exact while this stays within JS's + // safe-integer range. + chunkOut = 0; + enableXOF = true; + constructor(opts = {}, flags = 0) { + opts = checkOpts({}, opts); + super(64, opts.dkLen === undefined ? 32 : opts.dkLen); + const { key, context } = opts; + const hasContext = context !== undefined; + if (key !== undefined) { + if (hasContext) + throw new Error('cannot use both "key" and "context"'); + abytes(key, 32, 'key'); + const k = copyBytes(key); + this.IV = u32(k); + swap32IfBE(this.IV); + this.flags = flags | B3_Flags.KEYED_HASH; + } + else if (hasContext) { + abytes(context, undefined, 'context'); + const ctx = context; + const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT) + .update(ctx) + .digest(); + this.IV = u32(contextKey); + swap32IfBE(this.IV); + this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL; + } + else { + this.IV = B3_IV; // Share the module-private immutable default IV. + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // _BLAKE2's scalar-state hooks are unused here: BLAKE3 keeps its tree/XOF state in arrays and + // copies it directly in _cloneInto(). + get() { + return []; + } + set() { } + // Truncated chunk/parent compression: seed v8..v15 as IV[0..3], t0, t1, + // block length, and flags, then keep only the first 8 output words. + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const t0 = fromNumL(counter); + const t1 = fromNumH(counter); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], t0, t1, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= B3_Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) + flags |= B3_Flags.CHUNK_END; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // Chunks are used as a binary tree where the current stack is the path. + // Zero means the current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + // Reading the low bit is safe for parity, but keep division full-width: shifting would + // truncate the safe-integer chunk counter to 32 bits. + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks = Math.floor(chunks / 2)) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + // Overriding hides _BLAKE2's flat implementation, which would otherwise be inherited + // and silently miss the tree state (CV stack, chunk counters; get()/set() are stubs here). + _cloneInto(to) { + const staleOutput = !!to && to.finished && !to.destroyed; // Save before super copies lifecycle. + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state); + // Clone each CV stack entry by value so extending or destroying the clone + // cannot alias the source tree state. + to.stack = stack.map((i) => Uint32Array.from(i)); + if (IV === B3_IV) { + if (to.IV !== B3_IV) + clean(to.IV); + to.IV = B3_IV; // Share immutable default; configured IVs stay private. + } + else if (to.IV === B3_IV) { + to.IV = IV.slice(); + } + else { + to.IV.set(IV); + } + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + if (this.finished) { + to.bufferOut32.set(this.bufferOut32); + } + else if (staleOutput) { + clean(to.bufferOut32); // Wipe stale output; finish() overwrites scratch. + } + return to; + } + destroy() { + this.destroyed = true; + clean(this.state, this.buffer32, this.bufferOut32); + if (this.IV !== B3_IV) + clean(this.IV); + clean(...this.stack); + } + // Root/XOF compression: rerun the same ROOT inputs with incrementing output + // counter `t` and materialize all 16 output words. + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const outCounter = this.chunkOut++; + const t0 = fromNumL(outCounter); + const t1 = fromNumH(outCounter); + swap32IfBE(buffer32); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], t0, t1, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + swap32IfBE(buffer32); + swap32IfBE(out32); + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + this.buffer.fill(0, this.pos); + // Process last chunk + let flags = this.flags | B3_Flags.ROOT; + if (this.stack.length) { + // Finalize the current chunk first, then rerun the last parent + // compression as ROOT with t = 0 and b = 64. + flags |= B3_Flags.PARENT; + swap32IfBE(this.buffer32); + this.compress(this.buffer32, 0, true); + swap32IfBE(this.buffer32); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + aexists(this, false); + abytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('no XOF after digest()'); + return this.writeInto(out); + } + xof(bytes) { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + // `aoutput(...)` allows oversized buffers; digestInto() must fill only the configured digest. + this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen)); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.outputLen); + this.digestInto(out); + return out; + } +} +/** + * BLAKE3 hash function. Can be used as MAC and KDF. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, or KDF configuration. `key` must be + * exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be + * 0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}. + * @returns Digest bytes. + * @example + * Hash, MAC, or derive key material with BLAKE3. + * ```ts + * import { blake3 } from '@noble/hashes/blake3.js'; + * import { utf8ToBytes } from '@noble/hashes/utils.js'; + * const data = new Uint8Array(32); + * const hash = blake3(data); + * const mac = blake3(data, { key: new Uint8Array(32) }); + * const kdf = blake3(data, { context: utf8ToBytes('application name') }); + * const xof = blake3(data, { dkLen: 64 }); + * ``` + */ +export const blake3 = /* @__PURE__ */ createHasher((opts = {}) => new _BLAKE3(opts)); diff --git a/vendor/noble-hashes/utils.d.ts b/vendor/noble-hashes/utils.d.ts new file mode 100644 index 0000000..c8440cd --- /dev/null +++ b/vendor/noble-hashes/utils.d.ts @@ -0,0 +1,560 @@ +/** + * Utilities for hex, bytes, CSPRNG. + * @module + */ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array ? ReturnType : T extends BigUint64Array ? ReturnType : T extends Float32Array ? ReturnType : T extends Float64Array ? ReturnType : T extends Int16Array ? ReturnType : T extends Int32Array ? ReturnType : T extends Int8Array ? ReturnType : T extends Uint16Array ? ReturnType : T extends Uint32Array ? ReturnType : T extends Uint8ClampedArray ? ReturnType : T extends Uint8Array ? ReturnType : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = T | ([TypedArg] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TRet; +}) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; +} : T extends [infer A, ...infer R] ? [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends readonly [infer A, ...infer R] ? readonly [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends (infer A)[] ? TArg[] : T extends readonly (infer A)[] ? readonly TArg[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TArg; +} : T : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown ? T & ([TypedRet] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TArg; +}) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; +} : T extends [infer A, ...infer R] ? [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends readonly [infer A, ...infer R] ? readonly [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends (infer A)[] ? TRet[] : T extends readonly (infer A)[] ? readonly TRet[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TRet; +} : T : TypedRet) : never; +/** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - value to test + * @returns `true` when the value is a Uint8Array-compatible view. + * @example + * Check whether a value is a Uint8Array-compatible view. + * ```ts + * isBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function isBytes(a: unknown): a is Uint8Array; +/** + * Asserts something is a non-negative integer. + * @param n - number to validate + * @param title - label included in thrown errors + * @returns The validated number. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a non-negative integer option. + * ```ts + * anumber(32, 'length'); + * ``` + */ +export declare function anumber(n: number, title?: string): number; +/** + * Asserts something is a boolean. + * @param value - value to validate + * @param title - label included in thrown errors + * @returns The validated boolean. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate a boolean option. + * ```ts + * abool(true, 'enableXOF'); + * ``` + */ +export declare function abool(value: boolean, title?: string): boolean; +/** + * Asserts something is Uint8Array. + * @param value - value to validate + * @param length - optional exact length constraint + * @param title - label included in thrown errors + * @returns The validated byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate that a value is a byte array. + * ```ts + * abytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function abytes(value: TArg, length?: number, title?: string): TRet; +/** + * Copies bytes into a fresh Uint8Array. + * Buffer-style slices can alias the same backing store, so callers that need ownership should copy. + * @param bytes - source bytes to clone + * @returns Freshly allocated copy of `bytes`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Clone a byte array before mutating it. + * ```ts + * const copy = copyBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function copyBytes(bytes: TArg): TRet; +/** + * Asserts something is a wrapped hash constructor. + * @param h - hash constructor to validate + * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError} + * @throws On invalid hash metadata ranges or values. {@link RangeError} + * @throws If the hash metadata allows empty outputs or block sizes. {@link Error} + * @example + * Validate a callable hash wrapper. + * ```ts + * import { ahash } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * ahash(sha256); + * ``` + */ +export declare function ahash(h: TArg): void; +/** + * Asserts a hash instance has not been destroyed or finished. + * @param instance - hash instance to validate + * @param checkFinished - whether to reject finalized instances + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Validate that a hash instance is still usable. + * ```ts + * import { aexists } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aexists(hash); + * ``` + */ +export declare function aexists(instance: any, checkFinished?: boolean): void; +/** + * Asserts output is a sufficiently-sized byte array. + * @param out - destination buffer + * @param instance - hash instance providing output length + * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a caller-provided digest buffer. + * ```ts + * import { aoutput } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aoutput(new Uint8Array(hash.outputLen), hash); + * ``` + */ +export declare function aoutput(out: any, instance: any): void; +/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +/** + * Casts a typed array view to Uint8Array. + * @param arr - source typed array + * @returns Uint8Array view over the same buffer. + * @example + * Reinterpret a typed array as bytes. + * ```ts + * u8(new Uint32Array([1, 2])); + * ``` + */ +export declare function u8(arr: TArg): TRet; +/** + * Casts a typed array view to Uint32Array. + * `arr.byteOffset` must already be 4-byte aligned or the platform + * Uint32Array constructor will throw. + * @param arr - source typed array + * @returns Uint32Array view over the same buffer. + * @example + * Reinterpret a byte array as 32-bit words. + * ```ts + * u32(new Uint8Array(8)); + * ``` + */ +export declare function u32(arr: TArg): TRet; +/** + * Zeroizes typed arrays in place. Warning: JS provides no guarantees. + * @param arrays - arrays to overwrite with zeros + * @example + * Zeroize sensitive buffers in place. + * ```ts + * clean(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function clean(...arrays: TArg): void; +/** + * Creates a DataView for byte-level manipulation. + * @param arr - source typed array + * @returns DataView over the same buffer region. + * @example + * Create a DataView over an existing buffer. + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ +export declare function createView(arr: TArg): DataView; +/** + * Rotate-right operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the right. + * ```ts + * rotr(0x12345678, 8); + * ``` + */ +export declare function rotr(word: number, shift: number): number; +/** + * Rotate-left operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the left. + * ```ts + * rotl(0x12345678, 8); + * ``` + */ +export declare function rotl(word: number, shift: number): number; +/** Whether the current platform is little-endian. */ +export declare const isLE: boolean; +/** + * Byte-swap operation for uint32 values. + * @param word - source word + * @returns Word with reversed byte order. + * @example + * Reverse the byte order of a 32-bit word. + * ```ts + * byteSwap(0x11223344); + * ``` + */ +export declare function byteSwap(word: number): number; +/** + * Conditionally byte-swaps one 32-bit word on big-endian platforms. + * @param n - source word + * @returns Original or byte-swapped word depending on platform endianness. + * @example + * Normalize a 32-bit word for host endianness. + * ```ts + * swap8IfBE(0x11223344); + * ``` + */ +export declare const swap8IfBE: (n: number) => number; +/** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - array to mutate + * @returns The same array after mutation; callers pass live state arrays here. + * @example + * Reverse the byte order of every word in place. + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ +export declare function byteSwap32(arr: TArg): TRet; +/** + * Conditionally byte-swaps a Uint32Array on big-endian platforms. + * @param u - array to normalize for host endianness + * @returns Original or byte-swapped array depending on platform endianness. + * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`. + * @example + * Normalize a word array for host endianness. + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ +export declare const swap32IfBE: (u: TArg) => TRet; +/** + * Convert byte array to hex string. + * Uses the built-in function when available and assumes it matches the tested + * fallback semantics. + * @param bytes - bytes to encode + * @returns Lowercase hexadecimal string. + * @throws On wrong argument types. {@link TypeError} + * @example + * Convert bytes to lowercase hexadecimal. + * ```ts + * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' + * ``` + */ +export declare function bytesToHex(bytes: TArg): string; +/** + * Convert hex string to byte array. Uses built-in function, when available. + * @param hex - hexadecimal string to decode + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Decode lowercase hexadecimal into bytes. + * ```ts + * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + * ``` + */ +export declare function hexToBytes(hex: string): TRet; +/** + * Yields to the host task scheduler so timers, I/O, and rendering can make progress. + * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback. + * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so + * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while + * still allowing other event-loop work to proceed. + * @param onReject - optional cleanup invoked only if the host yield fails + * @example + * Yield to the next scheduler tick. + * ```ts + * await nextTick(); + * ``` + */ +export declare function nextTick(onReject?: () => void): Promise; +/** + * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops. + * @param iters - number of loop iterations to run + * @param tick - maximum time slice in milliseconds + * @param cb - callback executed on each iteration + * @param onReject - optional cleanup invoked only if a host yield fails + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Run a loop that periodically yields back to the event loop. + * ```ts + * await asyncLoop(2, 0, () => {}); + * ``` + */ +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void, onReject?: () => void): Promise; +/** + * Converts string to bytes using UTF8 encoding. + * Built-in doesn't validate input to be string: we do the check. + * Non-ASCII details are delegated to the platform `TextEncoder`. + * @param str - string to encode + * @returns UTF-8 encoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encode a string as UTF-8 bytes. + * ```ts + * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99]) + * ``` + */ +export declare function utf8ToBytes(str: string): TRet; +/** KDFs can accept string or Uint8Array for user convenience. */ +export type KDFInput = string | Uint8Array; +/** + * Helper for KDFs: consumes Uint8Array or string. + * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer. + * @param data - user-provided KDF input + * @param errorTitle - label included in thrown errors + * @returns Byte representation of the input. + * @throws On wrong argument types. {@link TypeError} + * @example + * Normalize KDF input to bytes. + * ```ts + * kdfInputToBytes('password'); + * ``` + */ +export declare function kdfInputToBytes(data: TArg, errorTitle?: string): TRet; +/** + * Copies several Uint8Arrays into one. + * @param arrays - arrays to concatenate + * @returns Concatenated byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Concatenate multiple byte arrays. + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +export declare function concatBytes(...arrays: TArg): TRet; +type EmptyObj = {}; +/** + * Validates declared required and optional field types on a plain object. + * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct + * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead. + * @param object - object to validate + * @param fields - map of required field names to expected types + * @param optFields - map of optional field names to expected types + * @param title - label included in thrown errors + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate required and optional option fields. + * ```ts + * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' }); + * ``` + */ +export declare const validateObject: (object: Record, fields?: Record, optFields?: Record, title?: string) => void; +/** + * Merges default options and passed options. + * @param defaults - base option object + * @param opts - user overrides + * @param title - label included in thrown override errors + * @returns Fresh merged option object with a null prototype. + * @throws On wrong argument types. {@link TypeError} + * @example + * Merge user overrides onto default options. + * ```ts + * checkOpts({ dkLen: 32 }, { asyncTick: 10 }); + * ``` + */ +export declare function checkOpts(defaults: T1, opts?: T2, title?: string): T1 & T2; +/** Common interface for all hash instances. */ +export interface Hash { + /** Bytes processed per compression block. */ + blockLen: number; + /** Bytes produced by `digest()`. */ + outputLen: number; + /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */ + canXOF: boolean; + /** + * Absorbs more message bytes into the running hash state. + * @param buf - message chunk to absorb + * @returns The same hash instance for chaining. + */ + update(buf: TArg): this; + /** + * Finalizes the hash into a caller-provided buffer. + * @param buf - destination buffer + * @returns Nothing. Implementations write into `buf` in place. + */ + digestInto(buf: TArg): void; + /** + * Finalizes the hash and returns a freshly allocated digest. + * @returns Digest bytes. + */ + digest(): TRet; + /** Wipes internal state and makes the instance unusable. */ + destroy(): void; + /** + * Copies the current hash state into an existing or new instance. + * @param to - Optional destination instance to reuse. + * @returns Cloned hash state. + */ + _cloneInto(to?: T): T; + /** + * Creates an independent copy of the current hash state. + * @returns Cloned hash instance. + */ + clone(): T; +} +/** + * The pseudorandom number generator doesn't wipe current state: + * instead, it generates new one based on previous state + entropy. + * Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes, + * which is in fact `reseed`, since it changes counter too. + */ +export interface PRG { + /** + * Mixes fresh entropy into the current generator state. + * @param seed - Non-empty entropy bytes to absorb. When omitted, the implementation uses its + * system RNG. + */ + addEntropy(seed?: TArg): void; + /** + * Produces a requested number of pseudorandom bytes. + * @param bytesLength - Number of bytes to generate. + * @returns Random byte array. + */ + randomBytes(bytesLength: number): TRet; + /** Destroys the generator state. */ + clean(): void; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + /** + * Reads more bytes from the XOF stream. + * @param bytes - number of bytes to read + * @returns Requested digest bytes. + */ + xof(bytes: number): TRet; + /** + * Reads more bytes from the XOF stream into a caller-provided buffer. + * @param buf - destination buffer + * @returns Filled output buffer. + */ + xofInto(buf: TArg): TRet; +}; +/** Hash constructor or factory type. */ +export type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T; +/** Optional hash metadata. */ +export type HashInfo = { + /** DER-encoded object identifier bytes for the hash algorithm. */ + oid?: TRet; +}; +/** Callable hash function type. */ +export type CHash = Hash, Opts = undefined> = { + /** Digest size in bytes. */ + outputLen: number; + /** Input block size in bytes. */ + blockLen: number; + /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */ + canXOF: boolean; +} & HashInfo & (Opts extends undefined ? { + (msg: TArg): TRet; + create(): T; +} : { + (msg: TArg, opts?: TArg): TRet; + create(opts?: Opts): T; +}); +/** Callable extendable-output hash function type. */ +export type CHashXOF = HashXOF, Opts = undefined> = CHash; +/** + * Creates a callable hash function from a stateful class constructor. + * @param hashCons - hash constructor or factory + * @param info - optional metadata such as DER OID + * @returns Frozen callable hash wrapper with `.create()`. + * Wrapper construction eagerly calls `hashCons(undefined)` once to read + * `outputLen` / `blockLen`, so constructor side effects happen at module + * init time. + * @throws On wrong argument types. {@link TypeError} + * @example + * Wrap a stateful hash constructor into a callable helper. + * ```ts + * import { createHasher } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const wrapped = createHasher(sha256.create, { oid: sha256.oid }); + * wrapped(new Uint8Array([1])); + * ``` + */ +export declare function createHasher, Opts = undefined>(hashCons: HasherCons, info?: TArg): TRet>; +/** + * Cryptographically secure PRNG backed by `crypto.getRandomValues`. + * @param bytesLength - number of random bytes to generate + * @returns Random bytes. + * The platform `getRandomValues()` implementation still defines any + * single-call length cap, and this helper rejects oversize requests + * with a stable library `RangeError` instead of host-specific errors. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error} + * @example + * Generate a fresh random key or nonce. + * ```ts + * const key = randomBytes(16); + * ``` + */ +export declare function randomBytes(bytesLength?: number): TRet; +/** + * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`. + * @param suffix - final OID byte for the selected hash. + * The helper accepts any byte even though only the documented NIST hash + * suffixes are meaningful downstream. + * @returns Object containing the DER-encoded OID. + * @example + * Build OID metadata for a NIST hash. + * ```ts + * oidNist(0x01); + * ``` + */ +export declare const oidNist: (suffix: number) => TRet>; +export {}; diff --git a/vendor/noble-hashes/utils.js b/vendor/noble-hashes/utils.js new file mode 100644 index 0000000..8ba8827 --- /dev/null +++ b/vendor/noble-hashes/utils.js @@ -0,0 +1,687 @@ +/** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - value to test + * @returns `true` when the value is a Uint8Array-compatible view. + * @example + * Check whether a value is a Uint8Array-compatible view. + * ```ts + * isBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function isBytes(a) { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. + // The fallback still requires a real ArrayBuffer view, so plain + // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and + // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views. + return (a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1)); +} +// Shared error-message prefix builder. Only called on throw paths, so assert +// success paths never pay for the string concatenation. +const atitle = (title) => (title ? `"${title}" ` : ''); +/** + * Asserts something is a non-negative integer. + * @param n - number to validate + * @param title - label included in thrown errors + * @returns The validated number. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a non-negative integer option. + * ```ts + * anumber(32, 'length'); + * ``` + */ +export function anumber(n, title = '') { + if (typeof n !== 'number') + throw new TypeError(atitle(title) + 'expected number, got ' + typeof n); + if (!Number.isSafeInteger(n) || n < 0) + throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n); + return n; +} +/** + * Asserts something is a boolean. + * @param value - value to validate + * @param title - label included in thrown errors + * @returns The validated boolean. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate a boolean option. + * ```ts + * abool(true, 'enableXOF'); + * ``` + */ +export function abool(value, title = '') { + if (typeof value !== 'boolean') + throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value); + return value; +} +/** + * Asserts something is Uint8Array. + * @param value - value to validate + * @param length - optional exact length constraint + * @param title - label included in thrown errors + * @returns The validated byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate that a value is a byte array. + * ```ts + * abytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function abytes(value, length, title = '') { + // Success path first: this runs at the start of every update() / digestInto(), and the + // common `abytes(data)` form must not pay for length handling it does not use. + if (isBytes(value) && (length === undefined || value.length === length)) + return value; + // Error path: recompute freely to build the exact message. + if (length !== undefined) + anumber(length, 'length'); + const bytes = isBytes(value); + const ofLen = length !== undefined ? ` of length ${length}` : ''; + const got = bytes ? `length=${value.length}` : `type=${typeof value}`; + const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); +} +/** + * Copies bytes into a fresh Uint8Array. + * Buffer-style slices can alias the same backing store, so callers that need ownership should copy. + * @param bytes - source bytes to clone + * @returns Freshly allocated copy of `bytes`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Clone a byte array before mutating it. + * ```ts + * const copy = copyBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function copyBytes(bytes) { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)); +} +/** + * Asserts something is a wrapped hash constructor. + * @param h - hash constructor to validate + * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError} + * @throws On invalid hash metadata ranges or values. {@link RangeError} + * @throws If the hash metadata allows empty outputs or block sizes. {@link Error} + * @example + * Validate a callable hash wrapper. + * ```ts + * import { ahash } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * ahash(sha256); + * ``` + */ +export function ahash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new TypeError('expected hash wrapped by utils.createHasher'); + anumber(h.outputLen); + anumber(h.blockLen); + // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass + // validation and can produce empty outputs instead of failing fast. + if (h.outputLen < 1 || h.blockLen < 1) + throw new Error('hash blockLen / outputLen must be >= 1'); +} +const aobject = (value, label) => { + if (value === null || typeof value !== 'object' || Array.isArray(value)) + throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value); +}; +const aopts = (value, label) => { + aobject(value, label); + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) + throw new TypeError(`"${label}" expected plain object`); + // Object.assign() treats an own "__proto__" source key as a write to the target's legacy + // prototype setter. Reject it before merging so inherited option values cannot be injected. + if (Object.hasOwn(value, '__proto__')) + throw new TypeError(`"${label}.__proto__" is not allowed`); +}; +/** + * Asserts a hash instance has not been destroyed or finished. + * @param instance - hash instance to validate + * @param checkFinished - whether to reject finalized instances + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Validate that a hash instance is still usable. + * ```ts + * import { aexists } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aexists(hash); + * ``` + */ +export function aexists(instance, checkFinished = true) { + // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their + // truthiness is checked - re-validating their type per call was pure hot-path overhead. + if (instance.destroyed) + throw new Error('hash was destroyed'); + if (checkFinished && instance.finished) + throw new Error('digest() was already called'); +} +/** + * Asserts output is a sufficiently-sized byte array. + * @param out - destination buffer + * @param instance - hash instance providing output length + * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a caller-provided digest buffer. + * ```ts + * import { aoutput } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aoutput(new Uint8Array(hash.outputLen), hash); + * ``` + */ +export function aoutput(out, instance) { + abytes(out, undefined, 'output'); + // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast + // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call. + const min = instance.outputLen; + if (!(out.length >= min)) { + throw new RangeError('"output" expected length >= ' + min); + } +} +/** + * Casts a typed array view to Uint8Array. + * @param arr - source typed array + * @returns Uint8Array view over the same buffer. + * @example + * Reinterpret a typed array as bytes. + * ```ts + * u8(new Uint32Array([1, 2])); + * ``` + */ +export function u8(arr) { + return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +} +/** + * Casts a typed array view to Uint32Array. + * `arr.byteOffset` must already be 4-byte aligned or the platform + * Uint32Array constructor will throw. + * @param arr - source typed array + * @returns Uint32Array view over the same buffer. + * @example + * Reinterpret a byte array as 32-bit words. + * ```ts + * u32(new Uint8Array(8)); + * ``` + */ +export function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +/** + * Zeroizes typed arrays in place. Warning: JS provides no guarantees. + * @param arrays - arrays to overwrite with zeros + * @example + * Zeroize sensitive buffers in place. + * ```ts + * clean(new Uint8Array([1, 2, 3])); + * ``` + */ +export function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +/** + * Creates a DataView for byte-level manipulation. + * @param arr - source typed array + * @returns DataView over the same buffer region. + * @example + * Create a DataView over an existing buffer. + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ +export function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +/** + * Rotate-right operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the right. + * ```ts + * rotr(0x12345678, 8); + * ``` + */ +export function rotr(word, shift) { + return (word << (32 - shift)) | (word >>> shift); +} +/** + * Rotate-left operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the left. + * ```ts + * rotl(0x12345678, 8); + * ``` + */ +export function rotl(word, shift) { + return (word << shift) | ((word >>> (32 - shift)) >>> 0); +} +/** Whether the current platform is little-endian. */ +export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)(); +/** + * Byte-swap operation for uint32 values. + * @param word - source word + * @returns Word with reversed byte order. + * @example + * Reverse the byte order of a 32-bit word. + * ```ts + * byteSwap(0x11223344); + * ``` + */ +export function byteSwap(word) { + return (((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff)); +} +/** + * Conditionally byte-swaps one 32-bit word on big-endian platforms. + * @param n - source word + * @returns Original or byte-swapped word depending on platform endianness. + * @example + * Normalize a 32-bit word for host endianness. + * ```ts + * swap8IfBE(0x11223344); + * ``` + */ +export const swap8IfBE = isLE + ? (n) => n + : (n) => byteSwap(n) >>> 0; +/** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - array to mutate + * @returns The same array after mutation; callers pass live state arrays here. + * @example + * Reverse the byte order of every word in place. + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ +export function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } + return arr; +} +/** + * Conditionally byte-swaps a Uint32Array on big-endian platforms. + * @param u - array to normalize for host endianness + * @returns Original or byte-swapped array depending on platform endianness. + * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`. + * @example + * Normalize a word array for host endianness. + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ +export const swap32IfBE = isLE + ? (u) => u + : byteSwap32; +// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex +const hasHexBuiltin = /* @__PURE__ */ (() => +// @ts-ignore +typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')(); +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * Convert byte array to hex string. + * Uses the built-in function when available and assumes it matches the tested + * fallback semantics. + * @param bytes - bytes to encode + * @returns Lowercase hexadecimal string. + * @throws On wrong argument types. {@link TypeError} + * @example + * Convert bytes to lowercase hexadecimal. + * ```ts + * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' + * ``` + */ +export function bytesToHex(bytes) { + abytes(bytes); + // @ts-ignore + if (hasHexBuiltin) + return bytes.toHex(); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined. +// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102. +// prettier-ignore +function asciiToBase16(ch) { + return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48 + : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10) + : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10) + : undefined; +} +/** + * Convert hex string to byte array. Uses built-in function, when available. + * @param hex - hexadecimal string to decode + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Decode lowercase hexadecimal into bytes. + * ```ts + * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + * ``` + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new TypeError('hex string expected, got ' + typeof hex); + if (hasHexBuiltin) { + try { + return Uint8Array.fromHex(hex); + } + catch (error) { + if (error instanceof SyntaxError) + throw new RangeError(error.message); + throw error; + } + } + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new RangeError('hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16 + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9 + } + return array; +} +/** + * Yields to the host task scheduler so timers, I/O, and rendering can make progress. + * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback. + * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so + * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while + * still allowing other event-loop work to proceed. + * @param onReject - optional cleanup invoked only if the host yield fails + * @example + * Yield to the next scheduler tick. + * ```ts + * await nextTick(); + * ``` + */ +export function nextTick(onReject) { + const host = globalThis; + if (typeof host.scheduler?.yield === 'function') { + const promise = host.scheduler.yield(); + // Keep the original scheduler rejection; this handler exists only for cleanup. + if (onReject) + promise.catch(onReject); + return promise; + } + return new Promise((resolve) => host.setTimeout(resolve, 0)); +} +/** + * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops. + * @param iters - number of loop iterations to run + * @param tick - maximum time slice in milliseconds + * @param cb - callback executed on each iteration + * @param onReject - optional cleanup invoked only if a host yield fails + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Run a loop that periodically yields back to the event loop. + * ```ts + * await asyncLoop(2, 0, () => {}); + * ``` + */ +export async function asyncLoop(iters, tick, cb, onReject) { + anumber(iters, 'iters'); + anumber(tick, 'tick'); + if (typeof cb !== 'function') + throw new TypeError('callback must be a function'); + // Callback is synchronous by contract; asyncLoop only yields between sync work windows. + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(onReject); + // Track only synchronous work time; scheduler delay after yielding is outside our budget. + ts = Date.now(); + } +} +/** + * Converts string to bytes using UTF8 encoding. + * Built-in doesn't validate input to be string: we do the check. + * Non-ASCII details are delegated to the platform `TextEncoder`. + * @param str - string to encode + * @returns UTF-8 encoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encode a string as UTF-8 bytes. + * ```ts + * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99]) + * ``` + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new TypeError('string expected'); + const encoded = new TextEncoder().encode(str); + try { + // Copy into the current realm for Firefox extension contexts. Callers that own the returned + // buffer can then wipe it independently of TextEncoder's temporary result. + return new Uint8Array(encoded); // https://bugzil.la/1681809 + } + finally { + clean(encoded); + } +} +/** + * Helper for KDFs: consumes Uint8Array or string. + * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer. + * @param data - user-provided KDF input + * @param errorTitle - label included in thrown errors + * @returns Byte representation of the input. + * @throws On wrong argument types. {@link TypeError} + * @example + * Normalize KDF input to bytes. + * ```ts + * kdfInputToBytes('password'); + * ``` + */ +export function kdfInputToBytes(data, errorTitle = '') { + if (typeof data === 'string') + return utf8ToBytes(data); + return abytes(data, undefined, errorTitle); +} +/** + * Copies several Uint8Arrays into one. + * @param arrays - arrays to concatenate + * @returns Concatenated byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Concatenate multiple byte arrays. + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +export function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +/** + * Validates declared required and optional field types on a plain object. + * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct + * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead. + * @param object - object to validate + * @param fields - map of required field names to expected types + * @param optFields - map of optional field names to expected types + * @param title - label included in thrown errors + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate required and optional option fields. + * ```ts + * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' }); + * ``` + */ +export const validateObject = (object, fields = {}, optFields = {}, title = 'object') => { + aobject(object, title); + aobject(fields, 'fields'); + aobject(optFields, 'optFields'); + function checkField(fieldName, expectedType, isOpt) { + const label = title === 'object' ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`; + // Config fields must be explicit own properties. Optional inherited values are rejected too + // because callers keep reading the same options object after validation. + const val = object[fieldName]; + // Runtime objects such as Field instances intentionally satisfy required method slots + // via their shared prototype. + if (!Object.hasOwn(object, fieldName) && + (isOpt ? val !== undefined : expectedType !== 'function')) { + throw new TypeError(`${label} is invalid: expected own property`); + } + if (isOpt && val === undefined) + return; + const current = typeof val; + if (current !== expectedType || val === null) + throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`); + } + const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt)); + iter(fields, false); + iter(optFields, true); +}; +/** + * Merges default options and passed options. + * @param defaults - base option object + * @param opts - user overrides + * @param title - label included in thrown override errors + * @returns Fresh merged option object with a null prototype. + * @throws On wrong argument types. {@link TypeError} + * @example + * Merge user overrides onto default options. + * ```ts + * checkOpts({ dkLen: 32 }, { asyncTick: 10 }); + * ``` + */ +export function checkOpts(defaults, opts, title = 'opts') { + aopts(defaults, 'defaults'); + if (opts !== undefined) + aopts(opts, title); + // Callers read optional fields directly, so omitted values must not fall through to ambient + // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output). + const merged = Object.assign(Object.create(null), defaults, opts); + return merged; +} +/** + * Creates a callable hash function from a stateful class constructor. + * @param hashCons - hash constructor or factory + * @param info - optional metadata such as DER OID + * @returns Frozen callable hash wrapper with `.create()`. + * Wrapper construction eagerly calls `hashCons(undefined)` once to read + * `outputLen` / `blockLen`, so constructor side effects happen at module + * init time. + * @throws On wrong argument types. {@link TypeError} + * @example + * Wrap a stateful hash constructor into a callable helper. + * ```ts + * import { createHasher } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const wrapped = createHasher(sha256.create, { oid: sha256.oid }); + * wrapped(new Uint8Array([1])); + * ``` + */ +export function createHasher(hashCons, info = {}) { + if (typeof hashCons !== 'function') + throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons); + info = checkOpts({}, info, 'info'); + const hashC = (msg, opts) => hashCons(opts) + .update(msg) + .digest(); + const tmp = hashCons(undefined); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts) => hashCons(opts); + Object.assign(hashC, info); + return Object.freeze(hashC); +} +/** + * Cryptographically secure PRNG backed by `crypto.getRandomValues`. + * @param bytesLength - number of random bytes to generate + * @returns Random bytes. + * The platform `getRandomValues()` implementation still defines any + * single-call length cap, and this helper rejects oversize requests + * with a stable library `RangeError` instead of host-specific errors. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error} + * @example + * Generate a fresh random key or nonce. + * ```ts + * const key = randomBytes(16); + * ``` + */ +export function randomBytes(bytesLength = 32) { + // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion. + anumber(bytesLength, 'bytesLength'); + const cr = typeof globalThis === 'object' ? globalThis.crypto : null; + if (typeof cr?.getRandomValues !== 'function') + throw new Error('crypto.getRandomValues must be defined'); + // Web Cryptography API Level 2 §10.1.1: + // if `byteLength > 65536`, throw `QuotaExceededError`. + // Keep the guard explicit so callers can see the quota in code + // instead of discovering it by reading the spec or host errors. + // This wrapper surfaces the same quota as a stable library RangeError. + if (bytesLength > 65536) + throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`); + return cr.getRandomValues(new Uint8Array(bytesLength)); +} +/** + * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`. + * @param suffix - final OID byte for the selected hash. + * The helper accepts any byte even though only the documented NIST hash + * suffixes are meaningful downstream. + * @returns Object containing the DER-encoded OID. + * @example + * Build OID metadata for a NIST hash. + * ```ts + * oidNist(0x01); + * ``` + */ +export const oidNist = (suffix) => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]), +});