openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
199 lines (198 loc) • 9.32 kB
JavaScript
import { o as asDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { n as containsAsciiControlCharacter } from "./string-normalization-DLmfYZXI.mjs";
import { f as isOperatorScope } from "./operator-scopes-CULmYfyY.mjs";
import { t as safeEqualSecret } from "./secret-equal-BogABOFr.mjs";
import { t as intersectOperatorScopes } from "./operator-scope-compat-CpFHu-FC.mjs";
import { r as isLocalDirectRequest, s as isLoopbackHost, y as resolveHostName } from "./net-BgRayX-P.mjs";
import { a as getRemoteControlUiIngressContext, r as assertRemoteControlUiIngressCurrent } from "./ingress-attribution-DAAQgd6y.mjs";
import { n as resolvePluginRoutePathContext } from "./path-context-7uf9WsoW.mjs";
import { d as CONTROL_UI_PLUGIN_AUTH_GRANT_TTL_MS, f as CONTROL_UI_PLUGIN_AUTH_PROBE_MESSAGE, l as controlUiPluginAssetPrefix, m as CONTROL_UI_PLUGIN_AUTH_PROBE_QUERY, p as CONTROL_UI_PLUGIN_AUTH_PROBE_ORIGIN_QUERY } from "./control-ui-plugin-tabs-C_6CJE64.mjs";
import "./control-ui-contract-DTmt_Jww.mjs";
import { createHash, createHmac, randomBytes } from "node:crypto";
import { TLSSocket } from "node:tls";
//#region src/gateway/control-ui-plugin-auth-cookie.ts
const CONTROL_UI_PLUGIN_AUTH_COOKIE_PREFIX = `__openclaw_plugin_tab_auth_${randomBytes(8).toString("hex")}`;
const CONTROL_UI_PLUGIN_AUTH_COOKIE_SCOPE = "plugin-tab";
const controlUiPluginAuthCookieSecret = randomBytes(32);
const ingressCookieGenerations = /* @__PURE__ */ new WeakMap();
function requestCookieGeneration(e, t) {
const n = t && getRemoteControlUiIngressContext(t);
if (!n) return e;
let r = ingressCookieGenerations.get(n.resolvePrincipal);
if (!r) {
r = randomBytes(32).toString("base64url");
ingressCookieGenerations.set(n.resolvePrincipal, r);
}
return createHash("sha256").update(`${e}\0${r}`).digest("base64url");
}
/** Forward only this host process's core-issued read-cookie namespace; verification stays at its owner. */
function filterRemoteControlUiPluginReadCookies(e) {
const t = `${CONTROL_UI_PLUGIN_AUTH_COOKIE_PREFIX}_`;
const n = e.split(";").map((e) => e.trimStart()).filter((e) => {
const n = e.indexOf("=");
if (n < 0) return false;
const r = e.slice(0, n);
const i = e.slice(n + 1);
return r.startsWith(t) && /^[a-f0-9]{64}$/.test(r.slice(t.length)) && /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(i);
});
return n.length ? n.join("; ") : void 0;
}
function signPayload(e) {
return createHmac("sha256", controlUiPluginAuthCookieSecret).update(e).digest("base64url");
}
function readCookieHeaderValues(e, t) {
const n = Array.isArray(e) ? e.join(";") : e;
const r = [];
for (const e of n?.split(";") ?? []) {
const n = e.indexOf("=");
if (n <= 0) continue;
const i = e.slice(0, n).trim();
const a = e.slice(n + 1).trim();
if (i.startsWith(`${t}_`)) r.push(a);
}
return r;
}
function cookieNameForPlugin(e) {
const t = createHash("sha256").update(e).digest("hex");
return `${CONTROL_UI_PLUGIN_AUTH_COOKIE_PREFIX}_${t}`;
}
function normalizeCookiePath(e) {
if (!e.startsWith("/") || e.startsWith("//") || e.includes(";") || containsAsciiControlCharacter(e)) return;
return URL.parse(e, "http://localhost")?.pathname === e ? e : void 0;
}
function createControlUiPluginAuthCookie(e, t) {
const n = normalizeCookiePath(e.path);
if (!n || !e.pluginId || !t.generation) return;
const r = asDateTimestampMs(t.nowMs ?? Date.now());
if (r === void 0) return;
const i = asDateTimestampMs(r + CONTROL_UI_PLUGIN_AUTH_GRANT_TTL_MS);
if (i === void 0) return;
const a = {
scope: CONTROL_UI_PLUGIN_AUTH_COOKIE_SCOPE,
pluginId: e.pluginId,
scopes: e.scopes.filter(isOperatorScope),
path: n,
match: e.match,
generation: requestCookieGeneration(t.generation, t.request),
exp: i,
...t.profileId ? { profileId: t.profileId } : {}
};
const o = Buffer.from(JSON.stringify(a), "utf8").toString("base64url");
const s = signPayload(o);
const c = e.match === "prefix" && n === controlUiPluginAssetPrefix(e.pluginId, t.basePath);
const l = t.request;
const u = l && !(l.socket instanceof TLSSocket) && isLocalDirectRequest(l) && isLoopbackHost(resolveHostName(l.headers.host));
const d = !c || !u;
const f = cookieNameForPlugin(e.pluginId);
const p = `v1.${o}.${s}`;
const m = Math.ceil(CONTROL_UI_PLUGIN_AUTH_GRANT_TTL_MS / 1e3);
return {
serialized: `${f}=${p}; Path=${n}; HttpOnly;${d ? " Secure;" : ""} SameSite=${c ? "Strict" : "None"}; Max-Age=${m}`,
metadata: {
name: f,
value: p,
path: n,
maxAgeSeconds: m,
kind: c ? "native-assets" : "iframe-read"
}
};
}
const issuedReadCookies = /* @__PURE__ */ new WeakMap();
/** Only cookies signed and marked by the core read-grant owner can cross remote ingress. */
function readGatewayPluginReadCookies(e) {
return issuedReadCookies.get(e) ?? [];
}
function setControlUiPluginAuthCookie(e, t, n) {
assertRemoteControlUiIngressCurrent(n.request ? getRemoteControlUiIngressContext(n.request) : void 0);
const r = [];
const i = [];
const a = t.flatMap((e) => {
const t = createControlUiPluginAuthCookie(e, n);
if (!t) return [];
r.push(e);
i.push(Object.freeze(t.metadata));
return [t.serialized];
});
if (a.length === 0) return r;
const o = typeof e.getHeader === "function" ? e.getHeader("Set-Cookie") : void 0;
const s = Array.isArray(o) ? [...o, ...a] : typeof o === "string" ? [o, ...a] : a;
e.setHeader("Set-Cookie", s);
issuedReadCookies.set(e, Object.freeze([...readGatewayPluginReadCookies(e), ...i]));
return r;
}
function grantPathMatchesRequest(e, t, n) {
if (t === "exact") return n === e;
return n === e || n.startsWith(e) && (e.endsWith("/") || n.at(e.length) === "/");
}
function resolveControlUiPluginAuthCookieGrants(e, t) {
const n = getRemoteControlUiIngressContext(e);
assertRemoteControlUiIngressCurrent(n);
const r = n?.resolvePrincipal();
const i = asDateTimestampMs(Date.now());
if (i === void 0) return [];
const a = normalizeCookiePath(t.requestPath);
if (!a || !t.generation) return [];
const o = resolvePluginRoutePathContext(a);
if (o.malformedEncoding || o.decodePassLimitReached) return [];
const s = [];
for (const n of readCookieHeaderValues(e.headers.cookie, CONTROL_UI_PLUGIN_AUTH_COOKIE_PREFIX)) {
const a = n.split(".");
if (a.length !== 3 || a[0] !== "v1") continue;
const [, c, l] = a;
if (!c || !l || !safeEqualSecret(l, signPayload(c))) continue;
try {
const n = JSON.parse(Buffer.from(c, "base64url").toString("utf8"));
if (n?.scope !== CONTROL_UI_PLUGIN_AUTH_COOKIE_SCOPE || n.exp <= i || n.generation !== requestCookieGeneration(t.generation, e) || typeof n.pluginId !== "string" || n.pluginId.length === 0 || n.profileId !== void 0 && (typeof n.profileId !== "string" || n.profileId.length === 0) || r && n.profileId !== r.authenticatedUserProfile.profileId || !Array.isArray(n.scopes) || typeof n.path !== "string" || normalizeCookiePath(n.path) !== n.path || n.match !== "exact" && n.match !== "prefix") continue;
const a = resolvePluginRoutePathContext(n.path);
if (a.malformedEncoding || a.decodePassLimitReached || !grantPathMatchesRequest(a.canonicalPath, n.match, o.canonicalPath)) continue;
const l = n.scopes.filter(isOperatorScope);
const u = {
pluginId: n.pluginId,
path: n.path,
match: n.match,
scopes: r ? intersectOperatorScopes(l, r.scopes).filter(isOperatorScope) : l,
...n.profileId ? { profileId: n.profileId } : {}
};
s.push(u);
} catch {
continue;
}
}
return s.toSorted((e, t) => t.path.length - e.path.length);
}
/**
* Confirms that the browser actually sent a grant from inside the opaque
* sandbox. Secure contexts can still block third-party cookies, so bootstrap
* acknowledgement alone is not enough to mount the plugin frame.
*/
function respondControlUiPluginAuthCookieProbe(e, t) {
const n = getRemoteControlUiIngressContext(e);
assertRemoteControlUiIngressCurrent(n);
const r = new URL(e.url ?? "/", "http://localhost");
const i = r.searchParams.get(CONTROL_UI_PLUGIN_AUTH_PROBE_QUERY);
if (i === null) return false;
const a = r.searchParams.get(CONTROL_UI_PLUGIN_AUTH_PROBE_ORIGIN_QUERY);
const o = a ? URL.parse(a) : null;
const s = o?.origin === a && (o?.protocol === "https:" || o?.protocol === "http:");
if (!/^[a-zA-Z0-9_-]{16,128}$/.test(i) || !s) {
t.statusCode = 400;
t.setHeader("Cache-Control", "no-store");
t.setHeader("Content-Type", "text/plain; charset=utf-8");
t.end("Invalid plugin frame auth check");
return true;
}
t.statusCode = 200;
t.setHeader("Cache-Control", "no-store");
t.setHeader("Content-Type", "text/html; charset=utf-8");
t.setHeader("Content-Security-Policy", `default-src 'none'; script-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors ${n ? [n.publicOrigin, ...n.frameAncestors].join(" ") : "'self'"}`);
t.setHeader("Referrer-Policy", "no-referrer");
t.setHeader("X-Content-Type-Options", "nosniff");
const c = JSON.stringify({
type: CONTROL_UI_PLUGIN_AUTH_PROBE_MESSAGE,
nonce: i
});
t.end(`<!doctype html><script>parent.postMessage(${c}, ${JSON.stringify(a)})<\/script>`);
return true;
}
//#endregion
export { setControlUiPluginAuthCookie as a, respondControlUiPluginAuthCookieProbe as i, readGatewayPluginReadCookies as n, resolveControlUiPluginAuthCookieGrants as r, filterRemoteControlUiPluginReadCookies as t };