UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

585 lines (584 loc) • 18.4 kB
import { C as utf8ToBytes, S as u8, T as wrapMacConstructor, _ as isLE, b as u32, c as abytes, d as clean, f as copyBytes, g as isAligned32, h as getOutput, l as aexists, m as equalBytes, n as sha256Hex, p as createView, r as base64, t as canonicalBytes, u as aoutput32, v as swap32IfBE, w as wrapCipher, x as u64Lengths, y as swap8IfBE } from "./canonical-DuZhyO3R.mjs"; import { p as randomBytes, u as concatBytes } from "./sha2-C0YCEfVG.mjs"; //#region node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/_polyval.js /** * GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. * * Implemented in terms of GHash with conversion function for keys * GCM GHASH from * {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d}, * SIV from * {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}. * * GHASH modulo: x^128 + x^7 + x^2 + x + 1 * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 * * @module */ const BLOCK_SIZE$1 = 16; const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); const ZEROS32 = /* @__PURE__ */ u32(ZEROS16); const POLY$1 = 225; const mul2$1 = (e, t, n, r) => { const i = r & 1; return { s3: n << 31 | r >>> 1, s2: t << 31 | n >>> 1, s1: e << 31 | t >>> 1, s0: e >>> 1 ^ POLY$1 << 24 & -(i & 1) }; }; const swapLE = (e) => (e >>> 0 & 255) << 24 | (e >>> 8 & 255) << 16 | (e >>> 16 & 255) << 8 | e >>> 24 & 255 | 0; const estimateWindow = (e) => { if (e > 65536) return 8; if (e > 1024) return 4; return 2; }; /** * Incremental GHASH state for AES-GCM. * @param key - 16-byte GHASH key. * @param expectedLength - Expected message length for table sizing. * Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded * to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM * use where AAD, payload, and length block are separate padded segments. * @example * Feeds one ciphertext block into an incremental GHASH state with a fresh hash key. * * ```ts * import { GHASH } from '@noble/ciphers/_polyval.js'; * import { randomBytes } from '@noble/ciphers/utils.js'; * const key = randomBytes(16); * const mac = new GHASH(key); * mac.update(new Uint8Array(16)); * mac.digest(); * ``` */ var GHASH = class { blockLen = BLOCK_SIZE$1; outputLen = BLOCK_SIZE$1; s0 = 0; s1 = 0; s2 = 0; s3 = 0; finished = false; destroyed = false; t; W; windowSize; constructor(e, t) { abytes(e, 16, "key"); e = copyBytes(e); const n = createView(e); let r = n.getUint32(0, false); let i = n.getUint32(4, false); let a = n.getUint32(8, false); let o = n.getUint32(12, false); const s = []; for (let e = 0; e < 128; e++) { s.push({ s0: swapLE(r), s1: swapLE(i), s2: swapLE(a), s3: swapLE(o) }); ({s0: r, s1: i, s2: a, s3: o} = mul2$1(r, i, a, o)); } const c = estimateWindow(t || 1024); if (![ 1, 2, 4, 8 ].includes(c)) throw new Error("ghash: invalid window size, expected 2, 4 or 8"); this.W = c; const l = 128 / c; const u = this.windowSize = 2 ** c; const d = []; for (let e = 0; e < l; e++) for (let t = 0; t < u; t++) { let n = 0, r = 0, i = 0, a = 0; for (let o = 0; o < c; o++) { if (!(t >>> c - o - 1 & 1)) continue; const { s0: l, s1: u, s2: d, s3: f } = s[c * e + o]; n ^= l, r ^= u, i ^= d, a ^= f; } d.push({ s0: n, s1: r, s2: i, s3: a }); } this.t = d; } _updateBlock(e, t, n, r) { e ^= this.s0, t ^= this.s1, n ^= this.s2, r ^= this.s3; const { W: i, t: a, windowSize: o } = this; let s = 0, c = 0, l = 0, u = 0; const d = (1 << i) - 1; let f = 0; for (const p of [ e, t, n, r ]) for (let e = 0; e < 4; e++) { const t = p >>> 8 * e & 255; for (let e = 8 / i - 1; e >= 0; e--) { const n = t >>> i * e & d; const { s0: r, s1: p, s2: m, s3: h } = a[f * o + n]; s ^= r, c ^= p, l ^= m, u ^= h; f += 1; } } this.s0 = s; this.s1 = c; this.s2 = l; this.s3 = u; } update(e) { aexists(this); abytes(e); e = copyBytes(e); const t = u32(e); const n = Math.floor(e.length / BLOCK_SIZE$1); const r = e.length % BLOCK_SIZE$1; for (let e = 0; e < n; e++) this._updateBlock(swap8IfBE(t[e * 4 + 0]), swap8IfBE(t[e * 4 + 1]), swap8IfBE(t[e * 4 + 2]), swap8IfBE(t[e * 4 + 3])); if (r) { ZEROS16.set(e.subarray(n * BLOCK_SIZE$1)); this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3])); clean(ZEROS32); } return this; } destroy() { this.destroyed = true; const { t: e } = this; for (const t of e) t.s0 = 0, t.s1 = 0, t.s2 = 0, t.s3 = 0; } digestInto(e) { aexists(this); aoutput32(e, this); this.finished = true; const { s0: t, s1: n, s2: r, s3: i } = this; const a = u32(e); a[0] = t; a[1] = n; a[2] = r; a[3] = i; if (!isLE) swap32IfBE(a.subarray(0, BLOCK_SIZE$1 / 4)); } digest() { const e = new Uint8Array(BLOCK_SIZE$1); this.digestInto(e); this.destroy(); return e; } }; /** * GHash MAC for AES-GCM. * @param msg - Message bytes to authenticate. * @param key - 16-byte GHASH key. * @returns 16-byte authentication tag. * @example * Authenticates a short message with GHASH and a fresh hash key. * * ```ts * import { ghash } from '@noble/ciphers/_polyval.js'; * import { randomBytes } from '@noble/ciphers/utils.js'; * const key = randomBytes(16); * ghash(new Uint8Array(), key); * ``` */ const ghash = /* @__PURE__ */ wrapMacConstructor(16, (e, t) => new GHASH(e, t), (e) => [e.length]); //#endregion //#region node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/aes.js /** * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES} * a.k.a. Advanced Encryption Standard * is a variant of Rijndael block cipher, standardized by NIST in 2001. * We provide the fastest available pure JS implementation. * * `cipher = encrypt(block, key)` * * Data is split into 128-bit blocks. * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: * 1. **S-box**, table substitution * 2. **Shift rows**, cyclic shift left of all rows of data array * 3. **Mix columns**, multiplying every column by fixed polynomial * 4. **Add round key**, round_key xor i-th column of array * * Check out * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197}, * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}, * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}. * @module */ const BLOCK_SIZE = 16; const BLOCK_SIZE32 = 4; const EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE); const POLY = 283; function validateKeyLength(e) { if (![ 16, 24, 32 ].includes(e.length)) throw new Error("\"aes key\" expected Uint8Array of length 16/24/32, got length=" + e.length); } function mul2(e) { return e << 1 ^ POLY & -(e >> 7); } function mul(e, t) { let n = 0; for (; t > 0; t >>= 1) { n ^= e & -(t & 1); e = mul2(e); } return n; } const sbox = /* @__PURE__ */ (() => { const e = /* @__PURE__ */ new Uint8Array(256); for (let t = 0, n = 1; t < 256; t++, n ^= mul2(n)) e[t] = n; const t = /* @__PURE__ */ new Uint8Array(256); t[0] = 99; for (let n = 0; n < 255; n++) { let r = e[255 - n]; r |= r << 8; t[e[n]] = (r ^ r >> 4 ^ r >> 5 ^ r >> 6 ^ r >> 7 ^ 99) & 255; } clean(e); return t; })(); const rotr32_8 = (e) => e << 24 | e >>> 8; const rotl32_8 = (e) => e << 8 | e >>> 24; function genTtable(e, t) { if (e.length !== 256) throw new Error("wrong sbox length"); const n = (/* @__PURE__ */ new Uint32Array(256)).map((n, r) => t(e[r])); const r = n.map(rotl32_8); const i = r.map(rotl32_8); const a = i.map(rotl32_8); const o = /* @__PURE__ */ new Uint32Array(65536); const s = /* @__PURE__ */ new Uint32Array(65536); const c = /* @__PURE__ */ new Uint16Array(65536); for (let t = 0; t < 256; t++) for (let l = 0; l < 256; l++) { const u = t * 256 + l; o[u] = n[t] ^ r[l]; s[u] = i[t] ^ a[l]; c[u] = e[t] << 8 | e[l]; } return { sbox: e, sbox2: c, T0: n, T1: r, T2: i, T3: a, T01: o, T23: s }; } const tableEncoding = /* @__PURE__ */ genTtable(sbox, (e) => mul(e, 3) << 24 | e << 16 | e << 8 | mul(e, 2)); const xPowers = /* @__PURE__ */ (() => { const e = /* @__PURE__ */ new Uint8Array(16); for (let t = 0, n = 1; t < 16; t++, n = mul2(n)) e[t] = n; return e; })(); /** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */ function expandKeyLE(e) { abytes(e); const t = e.length; validateKeyLength(e); const { sbox2: n } = tableEncoding; const r = []; if (!isLE || !isAligned32(e)) r.push(e = copyBytes(e)); const i = swap32IfBE(u32(e)); const a = i.length; const subByte = (e) => applySbox(n, e, e, e, e); const o = new Uint32Array(t + 28); o.set(i); for (let e = a; e < o.length; e++) { let t = o[e - 1]; if (e % a === 0) t = subByte(rotr32_8(t)) ^ xPowers[e / a - 1]; else if (a > 6 && e % a === 4) t = subByte(t); o[e] = o[e - a] ^ t; } clean(...r); return o; } function apply0123(e, t, n, r, i, a) { return e[n << 8 & 65280 | r >>> 8 & 255] ^ t[i >>> 8 & 65280 | a >>> 24 & 255]; } function applySbox(e, t, n, r, i) { return e[t & 255 | n & 65280] | e[r >>> 16 & 255 | i >>> 16 & 65280] << 16; } function encrypt(e, t, n, r, i) { const { sbox2: a, T01: o, T23: s } = tableEncoding; let c = 0; t ^= e[c++], n ^= e[c++], r ^= e[c++], i ^= e[c++]; const l = e.length / 4 - 2; for (let a = 0; a < l; a++) { const a = e[c++] ^ apply0123(o, s, t, n, r, i); const l = e[c++] ^ apply0123(o, s, n, r, i, t); const u = e[c++] ^ apply0123(o, s, r, i, t, n); const d = e[c++] ^ apply0123(o, s, i, t, n, r); t = a, n = l, r = u, i = d; } return { s0: e[c++] ^ applySbox(a, t, n, r, i), s1: e[c++] ^ applySbox(a, n, r, i, t), s2: e[c++] ^ applySbox(a, r, i, t, n), s3: e[c++] ^ applySbox(a, i, t, n, r) }; } function ctr32(e, t, n, r, i) { abytes(n, BLOCK_SIZE, "nonce"); abytes(r); i = getOutput(r.length, i); const a = n; const o = u32(a); const s = createView(a); const c = u32(r); const l = u32(i); const u = t ? 0 : 12; const d = r.length; let f = s.getUint32(u, t); for (let n = 0; n + 4 <= c.length; n += 4) { const { s0: r, s1: i, s2: a, s3: d } = encrypt(e, swap8IfBE(o[0]), swap8IfBE(o[1]), swap8IfBE(o[2]), swap8IfBE(o[3])); l[n + 0] = c[n + 0] ^ swap8IfBE(r); l[n + 1] = c[n + 1] ^ swap8IfBE(i); l[n + 2] = c[n + 2] ^ swap8IfBE(a); l[n + 3] = c[n + 3] ^ swap8IfBE(d); f = f + 1 >>> 0; s.setUint32(u, f, t); } const p = BLOCK_SIZE * Math.floor(c.length / BLOCK_SIZE32); if (p < d) { const { s0: t, s1: n, s2: a, s3: s } = encrypt(e, swap8IfBE(o[0]), swap8IfBE(o[1]), swap8IfBE(o[2]), swap8IfBE(o[3])); const c = new Uint32Array([ t, n, a, s ]); swap32IfBE(c); const l = u8(c); for (let e = p, t = 0; e < d; e++, t++) i[e] = r[e] ^ l[t]; clean(c); } return i; } function computeTag(e, t, n, r, i) { const a = i ? i.length : 0; const o = e.create(n, r.length + a); if (i) o.update(i); const s = u64Lengths(8 * r.length, 8 * a, t); o.update(r); o.update(s); const c = o.digest(); clean(s); return c; } /** * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used. * Not perfect: * a) conservative key wear-out is `2**32` (4B) msgs. * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance. * c) MAC can be forged: see Poly1305 documentation. * @param key - AES key bytes. * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation). * @param AAD - Additional authenticated data. * @returns AEAD cipher instance with a fixed 16-byte tag. * @example * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce. * * ```ts * import { gcm } from '@noble/ciphers/aes.js'; * import { randomBytes } from '@noble/ciphers/utils.js'; * const key = randomBytes(16); * const nonce = randomBytes(12); * const aad = new TextEncoder().encode('session metadata'); * const cipher = gcm(key, nonce, aad); * cipher.encrypt(new Uint8Array([1, 2, 3])); * ``` */ const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aesgcm(e, t, n) { if (t.length < 8) throw new Error("aes/gcm: invalid nonce length"); const r = 16; function _computeTag(e, t, r) { const i = computeTag(ghash, false, e, r, n); for (let e = 0; e < t.length; e++) i[e] ^= t[e]; return i; } function deriveKeys() { const n = expandKeyLE(e); const r = EMPTY_BLOCK.slice(); const i = EMPTY_BLOCK.slice(); ctr32(n, false, i, i, r); if (t.length === 12) i.set(t); else { const e = EMPTY_BLOCK.slice(); createView(e).setBigUint64(8, BigInt(t.length * 8), false); const n = ghash.create(r).update(t).update(e); n.digestInto(i); n.destroy(); } return { xk: n, authKey: r, counter: i, tagMask: ctr32(n, false, i, EMPTY_BLOCK) }; } return { encrypt(e) { const { xk: t, authKey: n, counter: i, tagMask: a } = deriveKeys(); const o = new Uint8Array(e.length + r); const s = [ t, n, i, a ]; if (!isAligned32(e)) s.push(e = copyBytes(e)); ctr32(t, false, i, e, o.subarray(0, e.length)); const c = _computeTag(n, a, o.subarray(0, o.length - r)); s.push(c); o.set(c, e.length); clean(...s); return o; }, decrypt(e) { const { xk: t, authKey: n, counter: r, tagMask: i } = deriveKeys(); const a = [ t, n, i, r ]; if (!isAligned32(e)) a.push(e = copyBytes(e)); const o = e.subarray(0, -16); const s = e.subarray(-16); const c = _computeTag(n, i, o); a.push(c); if (!equalBytes(c, s)) { clean(...a); throw new Error("aes-gcm: invalid tag"); } const l = ctr32(t, false, r, o); clean(...a); return l; } }; }); //#endregion //#region extensions/reef/protocol/audit.ts function verifyChain(e, t) { if (t?.length !== void 0 && e.length !== t.length) return false; return verifyChainSegment(e, { previousHash: "", previousSeq: 0, ...t?.head === void 0 ? {} : { head: t.head } }); } function verifyChainSegment(e, t) { let n = t.previousHash; for (let r = 0; r < e.length; r++) { const i = e[r]; if (i.event.seq !== t.previousSeq + r + 1 || i.prevHash !== n || i.entryHash !== hashEntry(n, i.event)) return false; n = i.entryHash; } return t.head === void 0 || n === t.head; } function createAuditEntry(e, t, n, r, i, a = randomBytes) { if (typeof e !== "string" || e.length === 0 || !Number.isSafeInteger(n) || n < 0) throw new Error("invalid audit event"); const o = { seq: i.seq + 1, ts: n, type: e, payload: encryptSensitive(t, validateAuditKey(r), a) }; return { event: o, prevHash: i.hash, entryHash: hashEntry(i.hash, o) }; } function encryptSensitive(e, t, n) { if (Array.isArray(e)) return e.map((e) => encryptSensitive(e, t, n)); if (e !== null && typeof e === "object") { const r = {}; for (const [i, a] of Object.entries(e)) if ((i === "text" || i === "reason") && typeof a === "string") { const e = n(12); if (e.length !== 12) throw new Error("invalid audit nonce"); const o = gcm(t, e).encrypt(utf8ToBytes(a)); r[i] = { enc: base64(concatBytes(e, o)) }; } else r[i] = encryptSensitive(a, t, n); return r; } return e; } function hashEntry(e, t) { const n = e === "" ? /* @__PURE__ */ new Uint8Array() : fromHex(e); const r = canonicalBytes(t); return sha256Hex(concatBytes(n, r)); } function validateAuditKey(e) { if (!(e instanceof Uint8Array) || e.length !== 32) throw new Error("audit key must be 32 bytes"); return e; } function fromHex(e) { if (!/^[0-9a-f]{64}$/.test(e)) throw new Error("invalid audit hash"); return Uint8Array.from(e.match(/../g), (e) => Number.parseInt(e, 16)); } //#endregion //#region extensions/reef/src/audit-state-format.ts const REEF_AUDIT_NAMESPACE = "audit"; const REEF_AUDIT_HEAD_NAMESPACE = "audit-head"; const REEF_AUDIT_HEAD_KEY = "head"; const REEF_AUDIT_MAX_ENTRIES = 3e4; const REEF_AUDIT_STORE_MAX_ENTRIES = 30001; const REEF_AUDIT_MIGRATION_NAMESPACE = "audit-migration"; const REEF_AUDIT_MIGRATION_KEY = "audit-jsonl"; function reefAuditEntryKey(e) { return `entry:${e}`; } function parseReefAuditHead(e) { const t = e; if (t === void 0) return { kind: "head", hash: "", seq: 0, oldestHash: "" }; if (!t || t.kind !== "head" || typeof t.hash !== "string" || !Number.isSafeInteger(t.seq) || t.seq < 0 || t.seq === 0 !== (t.hash === "") || typeof t.oldestHash !== "string" || t.seq === 0 !== (t.oldestHash === "") || t.garbageEntryKey !== void 0 && (typeof t.garbageEntryKey !== "string" || t.garbageEntryKey.length === 0) || t.pending !== void 0 && (typeof t.pending.owner !== "string" || t.pending.owner.length === 0 || !Number.isSafeInteger(t.pending.expiresAt) || t.pending.expiresAt <= 0 || t.pending.entryKey !== void 0 && (typeof t.pending.entryKey !== "string" || t.pending.entryKey.length === 0))) throw new Error("invalid Reef audit head"); return t; } function parseAuditEntryRecord(e) { const t = e; if (!t || t.kind !== "entry") throw new Error("missing Reef audit entry"); return t.entry; } function parseAuditStateRecord(e) { parseAuditEntryRecord(e); const t = e; if (t?.nextHash !== void 0 && (typeof t.nextHash !== "string" || t.nextHash.length === 0)) throw new Error("invalid Reef audit next pointer"); return t; } function verifyReefAuditWindow(e, t, n) { if (e.length !== Math.min(t.seq, n)) throw new Error("Reef audit chain is shorter than its committed retention window"); const r = e.toReversed(); const i = r[0]; if (!i || !verifyChainSegment(r, { previousHash: i.prevHash, previousSeq: i.event.seq - 1, head: t.hash })) throw new Error("invalid Reef audit chain state"); return r; } //#endregion export { REEF_AUDIT_MIGRATION_NAMESPACE as a, parseAuditEntryRecord as c, reefAuditEntryKey as d, verifyReefAuditWindow as f, gcm as h, REEF_AUDIT_MIGRATION_KEY as i, parseAuditStateRecord as l, verifyChain as m, REEF_AUDIT_HEAD_NAMESPACE as n, REEF_AUDIT_NAMESPACE as o, createAuditEntry as p, REEF_AUDIT_MAX_ENTRIES as r, REEF_AUDIT_STORE_MAX_ENTRIES as s, REEF_AUDIT_HEAD_KEY as t, parseReefAuditHead as u };