UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

508 lines (507 loc) • 17.2 kB
import { t as sha256 } from "./sha2-C0YCEfVG.mjs"; import { Buffer } from "node:buffer"; //#region node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/utils.js /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ /** * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. * @param a - Value to inspect. * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`. * @example * Guards a value before treating it as raw key material. * * ```ts * isBytes(new Uint8Array()); * ``` */ function isBytes(e) { return e instanceof Uint8Array || ArrayBuffer.isView(e) && e.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in e && e.BYTES_PER_ELEMENT === 1; } const atitle = (e) => e ? `"${e}" ` : ""; /** * Asserts something is boolean. * @param value - Value to validate. * @returns The validated boolean. * @throws On wrong argument types. {@link TypeError} * @example * Validates a boolean option before branching on it. * * ```ts * abool(true); * ``` */ function abool(e, t = "") { if (typeof e !== "boolean") throw new TypeError(atitle(t) + "expected boolean, got type=" + typeof e); return e; } /** * Asserts something is a non-negative safe integer. * @param n - Value to validate. * @returns The validated number. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @example * Validates a non-negative length or counter. * * ```ts * anumber(1); * ``` */ function anumber(e, t = "") { if (typeof e !== "number") throw new TypeError(atitle(t) + "expected number, got " + typeof e); if (!Number.isSafeInteger(e) || e < 0) throw new RangeError(atitle(t) + "expected integer >= 0, got " + e); return e; } /** * Asserts something is Uint8Array. * @param value - Value to validate. * @param length - Expected byte length. * @param title - Optional label used in error messages. * @returns The validated byte array. * On Node, `Buffer` is accepted too because it is a Uint8Array view. * @throws On wrong argument types. {@link TypeError} * @throws On wrong argument lengths. {@link RangeError} * @example * Validates a fixed-length nonce or key buffer. * * ```ts * abytes(new Uint8Array([1, 2]), 2); * ``` */ function abytes(e, t, n = "") { if (isBytes(e) && (t === void 0 || e.length === t)) return e; if (t !== void 0) anumber(t, "length"); const r = isBytes(e); const i = t !== void 0 ? ` of length ${t}` : ""; const a = r ? `length=${e.length}` : `type=${typeof e}`; const o = atitle(n) + "expected Uint8Array" + i + ", got " + a; if (!r) throw new TypeError(o); throw new RangeError(o); } /** * Asserts a hash- or MAC-like instance has not been destroyed or finished. * @param instance - Stateful instance to validate. * @param checkFinished - Whether to reject finished instances. * When `false`, only `destroyed` is checked. * @throws If the hash instance has already been destroyed or finalized. {@link Error} * @example * Guards against calling `update()` or `digest()` on a finished hash. * * ```ts * aexists({ destroyed: false, finished: false }); * ``` */ function aexists(e, t = true) { if (e.destroyed) throw new Error("hash was destroyed"); if (t && e.finished) throw new Error("digest() was already called"); } /** * Asserts output is a sufficiently-sized byte array. * @param out - Output buffer to validate. * @param instance - Hash-like instance providing `outputLen`. * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`, * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths. * @throws On wrong argument types. {@link TypeError} * @throws On wrong output buffer lengths. {@link RangeError} * @example * Verifies that a caller-provided output buffer is large enough. * * ```ts * aoutput(new Uint8Array(16), { outputLen: 16 }); * ``` */ function aoutput(e, t) { abytes(e, void 0, "output"); const n = t.outputLen; if (!(e.length >= n)) throw new RangeError("\"output\" expected length >= " + n); } /** * Asserts output is a sufficiently-sized, 4-byte-aligned byte array. * {@link aoutput} plus an {@link isAligned32} check, for `digestInto()` paths * that write through zero-allocation `u32` word views. * @param out - Output buffer to validate. * @param instance - Hash-like instance providing `outputLen`. * @throws On wrong argument types. {@link TypeError} * @throws On wrong output buffer lengths. {@link RangeError} * @throws On wrong output buffer alignment. {@link Error} * @example * Verifies that a caller-provided output buffer is large enough and aligned. * * ```ts * aoutput32(new Uint8Array(16), { outputLen: 16 }); * ``` */ function aoutput32(e, t) { aoutput(e, t); if (!isAligned32(e)) throw new Error("invalid output, must be aligned"); } /** * Casts a typed-array view to Uint8Array. * @param arr - Typed-array view to reinterpret. * @returns Uint8Array view over the same bytes. * @example * Views 32-bit words as raw bytes without copying. * * ```ts * u8(new Uint32Array([1])); * ``` */ function u8(e) { return new Uint8Array(e.buffer, e.byteOffset, e.byteLength); } /** * Casts a typed-array view to Uint32Array. * @param arr - Typed-array view to reinterpret. * @returns Uint32Array view over the same bytes. Callers are expected to provide a * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped. * @example * Views a byte buffer as 32-bit words for block processing. * * ```ts * u32(new Uint8Array(4)); * ``` */ function u32(e) { return new Uint32Array(e.buffer, e.byteOffset, Math.floor(e.byteLength / 4)); } /** * Zeroizes typed arrays in place. * Warning: JS provides no guarantees. * @param arrays - Arrays to wipe. * @example * Wipes a temporary key buffer after use. * * ```ts * const bytes = new Uint8Array([1]); * clean(bytes); * ``` */ function clean(...e) { for (let t = 0; t < e.length; t++) e[t].fill(0); } /** * Creates a DataView for byte-level manipulation. * @param arr - Typed-array view to wrap. * @returns DataView over the same bytes. * @example * Creates an endian-aware view for length encoding. * * ```ts * createView(new Uint8Array(4)); * ``` */ function createView(e) { return new DataView(e.buffer, e.byteOffset, e.byteLength); } /** * Whether the current platform is little-endian. * Most are; some IBM systems are not. */ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); /** * Reverses byte order of one 32-bit word. * @param word - Unsigned 32-bit word to swap. * @returns The same word with bytes reversed. * @example * Swaps a big-endian word into little-endian byte order. * * ```ts * byteSwap(0x11223344); * ``` */ function byteSwap(e) { return e << 24 & 4278190080 | e << 8 & 16711680 | e >>> 8 & 65280 | e >>> 24 & 255; } /** * Normalizes one 32-bit word to the little-endian representation expected by cipher cores. * @param n - Unsigned 32-bit word to normalize. * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged. * @example * Normalizes a host-endian word before passing it into an ARX/AES core. * * ```ts * swap8IfBE(0x11223344); * ``` */ const swap8IfBE = isLE ? (e) => e : (e) => byteSwap(e) >>> 0; /** * Byte-swaps every word of a Uint32Array in place. * @param arr - Uint32Array whose words should be swapped. * @returns The same array after in-place byte swapping. * @example * Swaps every 32-bit word in a word-view buffer. * * ```ts * byteSwap32(new Uint32Array([0x11223344])); * ``` */ function byteSwap32(e) { for (let t = 0; t < e.length; t++) e[t] = byteSwap(e[t]); return e; } /** * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores. * @param u - Word view to normalize in place. * @returns Little-endian normalized word view. * @example * Normalizes a word-view buffer before block processing. * * ```ts * swap32IfBE(new Uint32Array([0x11223344])); * ``` */ const swap32IfBE = isLE ? (e) => e : byteSwap32; const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")(); const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (e, t) => t.toString(16).padStart(2, "0")); /** * Convert byte array to hex string. Uses built-in function, when available. * @param bytes - Bytes to encode. * @returns Lowercase hexadecimal string. * @throws On wrong argument types. {@link TypeError} * @example * Formats ciphertext bytes for logs or test vectors. * * ```ts * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' * ``` */ function bytesToHex(e) { abytes(e); if (hasHexBuiltin) return e.toHex(); let t = ""; for (let n = 0; n < e.length; n++) t += hexes[e[n]]; return t; } /** * Converts string to bytes using UTF8 encoding. * @param str - String to encode. * @returns UTF-8 bytes in a detached fresh Uint8Array copy. * @throws On wrong argument types. {@link TypeError} * @example * Encodes application text before encryption or MACing. * * ```ts * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99]) * ``` */ function utf8ToBytes(e) { if (typeof e !== "string") throw new TypeError("string expected"); return new Uint8Array(new TextEncoder().encode(e)); } /** * Compares two byte arrays in kinda constant time once lengths already match. * @param a - First byte array. * @param b - Second byte array. * @returns `true` when the arrays contain the same bytes. Different lengths still return early. * @example * Compares an expected authentication tag with the received one. * * ```ts * equalBytes(new Uint8Array([1]), new Uint8Array([1])); * ``` */ function equalBytes(e, t) { e = abytes(e); t = abytes(t); if (e.length !== t.length) return false; let n = 0; for (let r = 0; r < e.length; r++) n |= e[r] ^ t[r]; return n === 0; } /** * Wraps a keyed MAC constructor into a one-shot helper with `.create()`. * @param keyLen - Valid probe-key length used to read static metadata once. * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes * can pass any representative size as long as those values stay fixed. * @param macCons - Keyed MAC constructor or factory. * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message. * @returns Callable MAC helper with `.create()`. */ function wrapMacConstructor(e, t, n) { const r = t; const i = n || (() => []); const macC = (e, t) => r(t, ...i(e)).update(e).digest(); const a = r(new Uint8Array(e), ...i(/* @__PURE__ */ new Uint8Array(0))); macC.outputLen = a.outputLen; macC.blockLen = a.blockLen; macC.create = (e, ...t) => r(e, ...t); return macC; } /** * Wraps a cipher: validates args, ensures encrypt() can only be called once. * Used internally by the exported cipher constructors. * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt` * arity (`fn.length === 2`), so wrapped output-capable methods must use a normal * second parameter, not a default/rest parameter. AAD support is explicit in * `params.withAAD`; optional AAD starts after the nonce slot when one is present. * @__NO_SIDE_EFFECTS__ * @param params - Static cipher metadata. See {@link CipherParams}. * @param constructor - Cipher constructor. * @returns Wrapped constructor with validation. */ const wrapCipher = (e, t) => { function wrappedCipher(n, ...r) { abytes(n, void 0, "key"); if (e.nonceLength !== void 0) { const t = r[0]; abytes(t, e.varSizeNonce ? void 0 : e.nonceLength, "nonce"); } const i = e.tagLength; const a = e.nonceLength !== void 0 ? 1 : 0; if (!e.withAAD) { for (let e = a; e < r.length; e++) if (isBytes(r[e])) throw new Error("AAD not supported"); } if (e.withAAD && r[a] !== void 0) abytes(r[a], void 0, "AAD"); const o = t(n, ...r); const checkOutput = (e, t) => { if (t !== void 0) { if (e !== 2) throw new Error("cipher output not supported"); abytes(t, void 0, "output"); } }; let s = false; return { encrypt(e, t) { if (s) throw new Error("cannot encrypt() twice with same key + nonce"); s = true; abytes(e, void 0, "data"); checkOutput(o.encrypt.length, t); return o.encrypt(e, t); }, decrypt(e, t) { abytes(e, void 0, "data"); if (i && e.length < i) throw new Error("\"ciphertext\" expected length >= tagLength=" + i); checkOutput(o.decrypt.length, t); return o.decrypt(e, t); } }; } Object.assign(wrappedCipher, e); return wrappedCipher; }; /** * By default, returns u8a of length. * When out is available, it checks it for validity and uses it. * @param expectedLength - Required output length. * @param out - Optional destination buffer. * @param onlyAligned - Whether `out` must be 4-byte aligned. * @returns Output buffer ready for writing. * @throws On wrong argument types. {@link TypeError} * @throws If the provided output buffer has the wrong size. {@link RangeError} * @throws If the provided output buffer has the wrong alignment. {@link Error} * @example * Reuses a caller-provided output buffer when lengths match. * * ```ts * getOutput(16, new Uint8Array(16)); * ``` */ function getOutput(e, t, n = true) { if (t === void 0) return new Uint8Array(e); abytes(t, e, "output"); if (n && !isAligned32(t)) throw new Error("invalid output, must be aligned"); return t; } /** * Encodes data and AAD lengths into a 16-byte buffer. * @param dataLength - Data length. Units are caller-defined: GCM passes bit * lengths, ChaCha20-Poly1305 passes byte lengths — the helper writes the raw values. * @param aadLength - AAD length, same unit convention as `dataLength`. * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305 * conventions even though the helper parameter order is `(dataLength, aadLength)`. * @param isLE - Whether to encode lengths as little-endian. * @returns 16-byte length block. * @throws On wrong argument types passed to the endian validator. {@link TypeError} * @throws On wrong argument ranges or values. {@link RangeError} * @example * Builds the length block appended by GCM and Poly1305. * * ```ts * u64Lengths(16, 8, true); * ``` */ function u64Lengths(e, t, n) { anumber(e); anumber(t); abool(n); const r = /* @__PURE__ */ new Uint8Array(16); const i = createView(r); i.setBigUint64(0, BigInt(t), n); i.setBigUint64(8, BigInt(e), n); return r; } /** * Checks whether a byte array is aligned to a 4-byte offset. * @param bytes - Byte array to inspect. * @returns `true` when the view is 4-byte aligned. * @example * Checks whether a buffer can be safely viewed as Uint32Array. * * ```ts * isAligned32(new Uint8Array(4)); * ``` */ function isAligned32(e) { return e.byteOffset % 4 === 0; } /** * Copies bytes into a new Uint8Array. * @param bytes - Bytes to copy. * @returns Copied byte array. * @throws On wrong argument types. {@link TypeError} * @example * Copies input into an aligned Uint8Array before block processing. * * ```ts * copyBytes(new Uint8Array([1, 2])); * ``` */ function copyBytes(e) { return Uint8Array.from(abytes(e)); } //#endregion //#region extensions/reef/protocol/encoding.ts const decoder = new TextDecoder("utf-8", { fatal: true }); function decodeUtf8(e) { return decoder.decode(e); } function base64url(e) { return Buffer.from(e).toString("base64url"); } function fromBase64url(e) { if (!/^[A-Za-z0-9_-]*$/.test(e) || e.length % 4 === 1) throw new Error("invalid base64url"); const t = Buffer.from(e, "base64url"); if (t.toString("base64url") !== e) throw new Error("invalid base64url padding"); return Uint8Array.from(t); } function base64(e) { return Buffer.from(e).toString("base64"); } function fromBase64(e) { if (e.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)) throw new Error("invalid base64"); const t = Buffer.from(e, "base64"); if (t.toString("base64") !== e) throw new Error("non-canonical base64"); return Uint8Array.from(t); } //#endregion //#region extensions/reef/protocol/canonical.ts function canonicalJson(e) { if (e === null || typeof e === "boolean" || typeof e === "string") return JSON.stringify(e); if (typeof e === "number") { if (!Number.isFinite(e)) throw new TypeError("canonical JSON requires finite numbers"); return JSON.stringify(e); } if (Array.isArray(e)) return `[${e.map(canonicalJson).join(",")}]`; if (typeof e === "object") { const t = e; return `{${Object.keys(t).filter((e) => t[e] !== void 0).toSorted().map((e) => `${JSON.stringify(e)}:${canonicalJson(t[e])}`).join(",")}}`; } throw new TypeError("unsupported canonical JSON value"); } function canonicalBytes(e) { return utf8ToBytes(canonicalJson(e)); } function sha256Hex(e) { return bytesToHex(sha256(e)); } //#endregion export { utf8ToBytes as C, u8 as S, wrapMacConstructor as T, isLE as _, decodeUtf8 as a, u32 as b, abytes as c, clean as d, copyBytes as f, isAligned32 as g, getOutput as h, base64url as i, aexists as l, equalBytes as m, sha256Hex as n, fromBase64 as o, createView as p, base64 as r, fromBase64url as s, canonicalBytes as t, aoutput32 as u, swap32IfBE as v, wrapCipher as w, u64Lengths as x, swap8IfBE as y };