UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

220 lines (219 loc) • 9.28 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as containsAsciiControlCharacter } from "./string-normalization-DLmfYZXI.mjs"; import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs"; import { n as deriveCanonicalEd25519PrivateKeyRaw } from "./ed25519-signature-CUaH7IDK.mjs"; import { t as getOrCreateWeakOwnerMap } from "./weak-owner-map-BGsaUABm.mjs"; import { n as resolveDeviceIdentityStore } from "./device-identity-store-options-Bz70uEBm.mjs"; import { i as loadOrCreateProcessDeviceIdentityAsync, n as loadDeviceIdentityIfPresentAsync } from "./device-identity-async-B1EfjFkw.mjs"; import { t as CONTROL_UI_PUBLIC_SESSION_SHARE_TOKEN_MAX_LENGTH } from "./public-share-B-H7sO_M.mjs"; import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from "node:crypto"; //#region src/gateway/control-ui-public-session-token.ts const PUBLIC_SESSION_TOKEN_PREFIX = "v1."; const PUBLIC_SESSION_TOKEN_CIPHER = "aes-256-gcm"; const PUBLIC_SESSION_TOKEN_NONCE_BYTES = 12; const PUBLIC_SESSION_TOKEN_AAD = Buffer.from("openclaw.public-session-share-locator.aad.v1", "utf8"); const PUBLIC_SESSION_WIDGET_TOKEN_AAD = Buffer.from("openclaw.public-session-widget-locator.aad.v1", "utf8"); const PUBLIC_SESSION_TOKEN_KEY_SALT = Buffer.from("openclaw.public-session-share-locator.salt.v1", "utf8"); const PUBLIC_SESSION_TOKEN_KEY_INFO = Buffer.from("openclaw.public-session-share-locator.key.v1", "utf8"); const PUBLIC_SESSION_TOKEN_MAX_PLAINTEXT_BYTES = 5e3; const PUBLIC_SESSION_LOCATOR_KEYS = [ "agentId", "sessionId", "sessionKey", "shareId" ].toSorted(); const PUBLIC_SESSION_CLAIM_KEYS = [...PUBLIC_SESSION_LOCATOR_KEYS, "v"].toSorted(); const PUBLIC_SESSION_WIDGET_CLAIM_KEYS = [...PUBLIC_SESSION_CLAIM_KEYS, "doc"].toSorted(); function hasExactKeys(e, t) { return Object.keys(e).toSorted().join("\0") === t.join("\0"); } function isValidLocator(e) { if (!isRecord(e)) return false; return typeof e.agentId === "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/u.test(e.agentId) && typeof e.sessionKey === "string" && e.sessionKey.length > 0 && e.sessionKey.length <= 4096 && !containsAsciiControlCharacter(e.sessionKey) && typeof e.sessionId === "string" && e.sessionId.length > 0 && e.sessionId.length <= 512 && !/[/\\\s\p{Cc}]/u.test(e.sessionId) && typeof e.shareId === "string" && /^[a-f0-9]{48}$/u.test(e.shareId); } function parseClaims(e, t = PUBLIC_SESSION_CLAIM_KEYS) { if (!isRecord(e)) return null; if (e.v !== 1 || !hasExactKeys(e, t) || !isValidLocator(e)) return null; return { agentId: e.agentId, sessionKey: e.sessionKey, sessionId: e.sessionId, shareId: e.shareId }; } function isValidWidgetDocumentId(e) { return typeof e === "string" && e.length <= 128 && /^[A-Za-z0-9._-]+$/u.test(e) && e !== "." && e !== ".."; } function derivePublicSessionTokenKey(e) { const t = deriveCanonicalEd25519PrivateKeyRaw(e.privateKeyPem); try { return Buffer.from(hkdfSync("sha256", t, PUBLIC_SESSION_TOKEN_KEY_SALT, PUBLIC_SESSION_TOKEN_KEY_INFO, 32)); } finally { t.fill(0); } } function encodePublicSessionLocator(e, t) { if (!isValidLocator(e) || !hasExactKeys(e, PUBLIC_SESSION_LOCATOR_KEYS)) throw new Error("invalid public session locator"); const n = t === void 0 ? { v: 1, ...e } : { v: 1, ...e, doc: t }; const r = Buffer.from(JSON.stringify(n), "utf8"); if (r.byteLength > PUBLIC_SESSION_TOKEN_MAX_PLAINTEXT_BYTES) throw new Error("public session locator exceeds the maximum length"); return r; } /** Validate the exact encoded claims before a publication grant becomes durable. */ function encodePublicSessionShareLocator(e) { return encodePublicSessionLocator(e); } /** Creates a domain-separated opaque-locator codec from one durable Gateway identity. */ function createPublicSessionShareTokenCodec(e) { const t = derivePublicSessionTokenKey(e); function seal(e, n, r) { const i = randomBytes(PUBLIC_SESSION_TOKEN_NONCE_BYTES); const a = createCipheriv(PUBLIC_SESSION_TOKEN_CIPHER, t, i); a.setAAD(n); const o = Buffer.concat([a.update(e), a.final()]); const s = `${PUBLIC_SESSION_TOKEN_PREFIX}${Buffer.concat([ i, a.getAuthTag(), o ]).toString("base64url")}`; if (s.length > 7e3) throw new Error("public session token exceeds the maximum length"); registerSecretValueForRedaction(r.shareId); registerSecretValueForRedaction(s); return s; } function open(e, n) { if (e.length > 7e3 || !e.startsWith(PUBLIC_SESSION_TOKEN_PREFIX)) return null; const r = e.slice(3); if (!r || !/^[A-Za-z0-9_-]+$/u.test(r)) return null; const i = Buffer.from(r, "base64url"); if (i.toString("base64url") !== r || i.byteLength <= 28) return null; const a = i.subarray(0, PUBLIC_SESSION_TOKEN_NONCE_BYTES); const o = i.subarray(PUBLIC_SESSION_TOKEN_NONCE_BYTES, 28); const s = i.subarray(28); if (s.byteLength > PUBLIC_SESSION_TOKEN_MAX_PLAINTEXT_BYTES) return null; try { const e = createDecipheriv(PUBLIC_SESSION_TOKEN_CIPHER, t, a); e.setAAD(n); e.setAuthTag(o); const r = Buffer.concat([e.update(s), e.final()]); if (r.byteLength > PUBLIC_SESSION_TOKEN_MAX_PLAINTEXT_BYTES) return null; return JSON.parse(r.toString("utf8")); } catch { return null; } } return { mint: (e) => seal(encodePublicSessionShareLocator(e), PUBLIC_SESSION_TOKEN_AAD, e), resolve(e) { const t = parseClaims(open(e, PUBLIC_SESSION_TOKEN_AAD)); if (t) { registerSecretValueForRedaction(e); registerSecretValueForRedaction(t.shareId); } return t; }, mintWidget(e, t) { if (!isValidWidgetDocumentId(t)) throw new Error("invalid public session widget document"); return seal(encodePublicSessionLocator(e, t), PUBLIC_SESSION_WIDGET_TOKEN_AAD, e); }, resolveWidget(e) { const t = open(e, PUBLIC_SESSION_WIDGET_TOKEN_AAD); const n = parseClaims(t, PUBLIC_SESSION_WIDGET_CLAIM_KEYS); if (!n || !isRecord(t) || !isValidWidgetDocumentId(t.doc)) return null; registerSecretValueForRedaction(e); registerSecretValueForRedaction(n.shareId); return { locator: n, docId: t.doc }; } }; } const codecsByDatabasePath = /* @__PURE__ */ new Map(); const missingIdentityDatabasePaths = /* @__PURE__ */ new Map(); const previewTokens = /* @__PURE__ */ new WeakMap(); const widgetTokens = /* @__PURE__ */ new WeakMap(); function cacheCodec(e, t) { const n = codecsByDatabasePath.get(e); if (n) return n; const r = createPublicSessionShareTokenCodec(t); pruneMapToMaxSize(codecsByDatabasePath, 31); codecsByDatabasePath.set(e, r); missingIdentityDatabasePaths.delete(e); return r; } function resolveProcessCodec(e) { const { databasePath: t } = resolveDeviceIdentityStore(); const n = codecsByDatabasePath.get(t); if (n) return n; if (!e.create && missingIdentityDatabasePaths.has(t)) return null; return (e.create ? loadOrCreateProcessDeviceIdentityAsync({ path: t }) : loadDeviceIdentityIfPresentAsync({ path: t })).then((e) => { if (!e) { const e = codecsByDatabasePath.get(t); if (e) return e; pruneMapToMaxSize(missingIdentityDatabasePaths, 31); missingIdentityDatabasePaths.set(t, true); return null; } return cacheCodec(t, e); }); } function requirePublicSessionShareTokenCodec(e) { if (!e) throw new Error("public session token identity is unavailable"); return e; } /** Warm codecs remain synchronous so a prepared session row needs no new read phase. */ function loadPublicSessionShareTokenCodec() { const e = resolveProcessCodec({ create: true }); return e instanceof Promise ? e.then(requirePublicSessionShareTokenCodec) : requirePublicSessionShareTokenCodec(e); } /** Resolves an opaque locator without letting anonymous traffic create durable identity state. */ async function resolvePublicSessionShareToken(e) { return (await resolveProcessCodec({ create: false }))?.resolve(e) ?? null; } /** Public readers may reuse the installation identity but must never create it. */ async function mintExistingPublicSessionShareToken(e) { const t = await resolveProcessCodec({ create: false }); if (!t) return; const n = getOrCreateWeakOwnerMap(previewTokens, t); const r = JSON.stringify(e); let i = n.get(r); if (!i) { i = t.mint(e); pruneMapToMaxSize(n, 127); n.set(r, i); } return i; } /** Widget frames carry only a document-scoped credential, never the publication bearer. */ async function mintPublicSessionWidgetToken(e, t) { if (!isValidWidgetDocumentId(t)) return; const n = await resolveProcessCodec({ create: false }); if (!n) return; let r = widgetTokens.get(n); if (!r) { r = /* @__PURE__ */ new Map(); widgetTokens.set(n, r); } const i = JSON.stringify([Object.entries(e).toSorted(([e], [t]) => e.localeCompare(t)), t]); let a = r.get(i); if (!a) { a = n.mintWidget(e, t); pruneMapToMaxSize(r, 127); r.set(i, a); } return a; } async function resolvePublicSessionWidgetToken(e) { return (await resolveProcessCodec({ create: false }))?.resolveWidget(e) ?? null; } //#endregion export { resolvePublicSessionShareToken as a, mintPublicSessionWidgetToken as i, loadPublicSessionShareTokenCodec as n, resolvePublicSessionWidgetToken as o, mintExistingPublicSessionShareToken as r, encodePublicSessionShareLocator as t };