UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

375 lines (374 loc) • 12.7 kB
import { C as utf8ToBytes, a as decodeUtf8, n as sha256Hex, o as fromBase64, r as base64, s as fromBase64url, t as canonicalBytes } from "./canonical-DuZhyO3R.mjs"; import { h as gcm } from "./audit-state-format-BgwDlxZw.mjs"; import { a as ahash, i as aexists, l as clean, o as anumber, p as randomBytes, r as abytes, s as aoutput, t as sha256 } from "./sha2-C0YCEfVG.mjs"; import { A as x25519, D as parseHandleEpoch, k as ed25519 } from "./state-format-BYNwYsrm.mjs"; //#region node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hmac.js /** * HMAC: RFC2104 message authentication code. * @module */ /** * Internal class for HMAC. * Accepts any byte key, although RFC 2104 §3 recommends keys at least * `HashLen` bytes long. */ var _HMAC = class { oHash; iHash; blockLen; outputLen; canXOF = false; finished = false; destroyed = false; constructor(e, t) { ahash(e); abytes(t, void 0, "key"); this.iHash = e.create(); if (typeof this.iHash.update !== "function") throw new Error("expected Hash instance"); this.blockLen = this.iHash.blockLen; this.outputLen = this.iHash.outputLen; const n = this.blockLen; const r = new Uint8Array(n); r.set(t.length > n ? e.create().update(t).digest() : t); for (let e = 0; e < r.length; e++) r[e] ^= 54; this.iHash.update(r); this.oHash = e.create(); for (let e = 0; e < r.length; e++) r[e] ^= 106; this.oHash.update(r); clean(r); } update(e) { aexists(this); this.iHash.update(e); return this; } digestInto(e) { aexists(this); aoutput(e, this); this.finished = true; const t = e.subarray(0, this.outputLen); this.iHash.digestInto(t); this.oHash.update(t); this.oHash.digestInto(t); this.destroy(); } digest() { const e = new Uint8Array(this.oHash.outputLen); this.digestInto(e); return e; } _cloneInto(e) { e ||= Object.create(Object.getPrototypeOf(this), {}); const { oHash: t, iHash: n, finished: r, destroyed: i, blockLen: a, outputLen: o, canXOF: s } = this; e = e; e.finished = r; e.destroyed = i; e.blockLen = a; e.outputLen = o; e.canXOF = s; e.oHash = t._cloneInto(e.oHash); e.iHash = n._cloneInto(e.iHash); return e; } clone() { return this._cloneInto(); } destroy() { this.destroyed = true; this.oHash.destroy(); this.iHash.destroy(); } }; const hmac = /* @__PURE__ */ (() => { const hmac_ = ((e, t, n) => new _HMAC(e, t).update(n).digest()); hmac_.create = (e, t) => new _HMAC(e, t); return hmac_; })(); //#endregion //#region node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hkdf.js /** * HKDF (RFC 5869): extract + expand in one step. * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}. * @module */ const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); /** * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM` * @param hash - hash function that would be used (e.g. sha256) * @param prk - a pseudorandom key of at least HashLen octets * (usually, the output from the extract step) * @param info - optional context and application specific information (can be a zero-length string) * @param length - length of output keying material in bytes. * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM. * @param _recycled - Internal destroyed extract hashes owned by the combined `hkdf()` call. * @returns Output keying material with the requested length. * @throws If the requested output length exceeds the HKDF limit * for the selected hash. {@link Error} * @example * Run the HKDF expand step. * ```ts * import { expand } from '@noble/hashes/hkdf.js'; * import { sha256 } from '@noble/hashes/sha2.js'; * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16); * ``` */ function expand(e, t, n, r = 32, i) { ahash(e); anumber(r, "length"); abytes(t, void 0, "prk"); const a = e.outputLen; if (t.length < a) throw new Error("\"prk\" must be at least HashLen octets"); if (r > 255 * a) throw new Error("Length must be <= 255*HashLen"); const o = Math.ceil(r / a); if (n === void 0) n = EMPTY_BUFFER; else abytes(n, void 0, "info"); if (!o) { if (i) clean(t); return /* @__PURE__ */ new Uint8Array(); } const s = i && o === 1 ? t : new Uint8Array(o * a); const { iHash: c, oHash: l } = hmac.create(e, t); const u = i ? t : new Uint8Array(a); const d = o > 1 ? i?.iHash || e.create() : void 0; for (let e = 0; e < o - 1; e++) { HKDF_COUNTER[0] = e + 1; const t = c._cloneInto(d); if (e) t.update(u); t.update(n).update(HKDF_COUNTER).digestInto(u); l._cloneInto(d).update(u).digestInto(u); s.set(u, a * e); } HKDF_COUNTER[0] = o; if (o > 1) c.update(u); c.update(n).update(HKDF_COUNTER).digestInto(u); l.update(u).digestInto(u); s.set(u, a * (o - 1)); c.destroy(); l.destroy(); d?.destroy(); if (u !== s) clean(u); clean(HKDF_COUNTER); if (r === s.length) return s; const f = s.slice(0, r); clean(s); return f; } /** * HKDF (RFC 5869): derive keys from an initial input. * Combines hkdf_extract + hkdf_expand in one step * @param hash - hash function that would be used (e.g. sha256) * @param ikm - input keying material, the initial key * @param salt - optional salt value (a non-secret random value) * @param info - optional context and application specific information bytes * @param length - length of output keying material in bytes. * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM. * @returns Output keying material derived from the input key. * @throws If the requested output length exceeds the HKDF limit * for the selected hash. {@link Error} * @example * HKDF (RFC 5869): derive keys from an initial input. * ```ts * import { hkdf } from '@noble/hashes/hkdf.js'; * import { sha256 } from '@noble/hashes/sha2.js'; * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js'; * const inputKey = randomBytes(32); * const salt = randomBytes(32); * const info = utf8ToBytes('application-key'); * const okm = hkdf(sha256, inputKey, salt, info, 32); * ``` */ const hkdf = (e, t, n, r, i) => { ahash(e); if (n === void 0) n = new Uint8Array(e.outputLen); const a = hmac.create(e, n).update(t); return expand(e, a.digest(), r, i, a); }; //#endregion //#region extensions/reef/protocol/envelope.ts var ProtocolError = class extends Error { constructor(e, t = e, n = "ProtocolError") { super(t); this.code = e; this.name = n; } }; var BadSignatureError = class extends ProtocolError { constructor(e) { super("bad_signature", e, "BadSignatureError"); } }; var NotPinnedError = class extends ProtocolError { constructor(e) { super("not_pinned", e, "NotPinnedError"); } }; var WrongRecipientError = class extends ProtocolError { constructor(e) { super("wrong_recipient", e, "WrongRecipientError"); } }; var ExpiredError = class extends ProtocolError { constructor(e) { super("expired", e, "ExpiredError"); } }; var ReplayedError = class extends ProtocolError { constructor(e) { super("replayed", e, "ReplayedError"); } }; var TooLargeError = class extends ProtocolError { constructor(e) { super("too_large", e, "TooLargeError"); } }; var MalformedError = class extends ProtocolError { constructor(e) { super("malformed", e, "MalformedError"); } }; const REEF_MAX_PLAINTEXT_BYTES = 32768; const MAX_CIPHERTEXT_BASE64 = 44752; const MAX_ENVELOPE_BYTES = 49152; const REEF_ENVELOPE_MAX_AGE_SECONDS = 2592e3; const HKDF_INFO = utf8ToBytes("reef-v1"); const ULID_PATTERN = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/; function seal(e) { const t = e.ts ?? Math.floor(Date.now() / 1e3); validateEnvelopeMetadata(e.id, e.from, e.to, t); validateMessageBody(e.body); const n = canonicalBytes(e.body); if (n.length > 32768) throw new TooLargeError(); const r = x25519.keygen((e.rng ?? randomBytes)(32)); const i = x25519.getSharedSecret(r.secretKey, decodeKey(e.recipientEncryptionPublicKey)); const a = hkdf(sha256, i, void 0, HKDF_INFO, 32); const o = (e.rng ?? randomBytes)(12); if (o.length !== 12) throw new MalformedError("rng returned invalid nonce"); const s = { v: 1, id: e.id, from: e.from, to: e.to, ts: t, epk: base64(r.publicKey), n: base64(o), ct: base64(gcm(a, o).encrypt(n)) }; return { ...s, sig: base64(ed25519.sign(canonicalBytes(s), decodeKey(e.senderSigningSecretKey))) }; } async function openClaimed(e) { const t = validateEnvelope(e.envelope); if (!e.senderSigningPublicKey) throw new NotPinnedError(); const { sig: n, ...r } = t; let i = false; try { i = ed25519.verify(fromBase64(n), canonicalBytes(r), decodeKey(e.senderSigningPublicKey)); } catch {} if (!i) throw new BadSignatureError(); if (t.v !== 1) throw new MalformedError(); validateEnvelopeMetadata(t.id, t.from, t.to, t.ts); if (t.to !== e.self) throw new WrongRecipientError(); const a = parseHandleEpoch(t.from).handle; const o = sha256Hex(canonicalBytes(t)); const s = await e.replayStore.claim(a, t.id, o); if (s === "mismatch") throw new ReplayedError("replay id binding mismatch"); if (s === "in_flight") throw new ReplayedError("in flight"); if (s === "duplicate") { const n = await e.replayStore.completed(a, t.id); if (n === void 0) return { claim: s }; return n.body === void 0 ? { claim: s, receipt: n.receipt } : { claim: s, receipt: n.receipt, body: n.body }; } try { const n = e.now ?? Math.floor(Date.now() / 1e3); const r = e.maxAgeSeconds ?? 2592e3; const i = e.maxFutureSkewSeconds ?? 300; if (t.ts > n + i || t.ts < n - r) throw new ExpiredError(); const a = x25519.getSharedSecret(decodeKey(e.recipientEncryptionSecretKey), fromBase64(t.epk)); const s = hkdf(sha256, a, void 0, HKDF_INFO, 32); const c = gcm(s, fromBase64(t.n)).decrypt(fromBase64(t.ct)); if (c.length > 32768) throw new TooLargeError(); const l = JSON.parse(decodeUtf8(c)); validateMessageBody(l); return { claim: "new", body: l, envelopeHash: o }; } catch (n) { await e.replayStore.release(a, t.id); if (n instanceof ProtocolError) throw n; throw new MalformedError(); } } function bodyHash(e) { return sha256Hex(canonicalBytes(e)); } function decodeKey(e) { const t = fromBase64url(e); if (t.length !== 32) throw new MalformedError("invalid key length"); return t; } function validateEnvelopeMetadata(e, t, n, r) { if (!ULID_PATTERN.test(e) || !Number.isSafeInteger(r) || r < 0) throw new MalformedError("invalid envelope metadata"); try { parseHandleEpoch(t); parseHandleEpoch(n); } catch { throw new MalformedError("invalid envelope peer"); } } function validateMessageBody(e) { if (!isExactObject(e, [ "text", "replyTo", "thread" ])) throw new MalformedError("invalid body"); if (typeof e.text !== "string" || e.replyTo !== void 0 && typeof e.replyTo !== "string" || e.thread !== void 0 && typeof e.thread !== "string") throw new MalformedError("invalid body"); if (e.replyTo !== void 0 && !ULID_PATTERN.test(e.replyTo) || e.thread !== void 0 && !ULID_PATTERN.test(e.thread)) throw new MalformedError("invalid body identifier"); for (const t of [ e.text, e.replyTo, e.thread ]) if (t !== void 0 && decodeUtf8(utf8ToBytes(t)) !== t) throw new MalformedError("invalid UTF-8 body"); } function validateEnvelope(e) { if (!isExactObject(e, [ "v", "id", "from", "to", "ts", "epk", "n", "ct", "sig" ])) throw new MalformedError(); if (typeof e.v !== "number" || typeof e.id !== "string" || typeof e.from !== "string" || typeof e.to !== "string" || !Number.isSafeInteger(e.ts) || typeof e.epk !== "string" || typeof e.n !== "string" || typeof e.ct !== "string" || typeof e.sig !== "string") throw new MalformedError(); if (e.id.length !== 26) throw new MalformedError("invalid envelope id length"); if (e.from.length > 80 || e.to.length > 80 || e.epk.length > 46 || e.n.length > 18 || e.sig.length > 90 || e.ct.length > MAX_CIPHERTEXT_BASE64) throw new TooLargeError(); try { if (fromBase64(e.epk).length !== 32 || fromBase64(e.n).length !== 12 || fromBase64(e.sig).length !== 64) throw new Error(); fromBase64(e.ct); } catch { throw new MalformedError(); } if (canonicalBytes(e).length > MAX_ENVELOPE_BYTES) throw new TooLargeError(); return e; } function isExactObject(e, t) { if (e === null || typeof e !== "object" || Array.isArray(e)) return false; return Object.keys(e).every((e) => t.includes(e)) && t.every((t) => t in e || ["replyTo", "thread"].includes(t)); } //#endregion export { openClaimed as a, validateMessageBody as c, bodyHash as i, REEF_MAX_PLAINTEXT_BYTES as n, seal as o, ReplayedError as r, validateEnvelopeMetadata as s, REEF_ENVELOPE_MAX_AGE_SECONDS as t };