openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
735 lines (734 loc) • 27.1 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as sha256Base64Url } from "./crypto-digest-B2m8wIBj.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { t as GATEWAY_OWNER_PROFILE_ID } from "./user-profile-constants-Bj3FwpfE.mjs";
import { p as normalizeOperatorScopeList, t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import "./io-4QsrsWTJ.mjs";
import { o as roleScopesAllow, t as intersectOperatorScopes } from "./operator-scope-compat-CpFHu-FC.mjs";
import { n as authorizeOperatorScopesForMethod, t as CLI_DEFAULT_OPERATOR_SCOPES } from "./method-scopes-Dpyb0Ck-.mjs";
import { n as getBearerToken, r as getHeader } from "./http-header-value-BTQlMYRm.mjs";
import { c as prepareUserProfileCatalog, t as captureResidentUserProfileAccess } from "./user-profile-list-D7DDbqt5.mjs";
import { c as projectUserProfileDisplay } from "./user-profiles-internal-BlqpbmyM.mjs";
import { h as resolveOperatorRolePolicyForAssignment, y as prepareSessionCreatorProfile } from "./operator-role-policy-DhcqVpmG.mjs";
import { c as AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET, i as AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN } from "./auth-rate-limit-DGfPTrXr.mjs";
import { a as getRemoteControlUiIngressContext, c as prepareGatewayIngressAttribution, n as PROXY_ATTRIBUTION_REQUIRED_REASON, r as assertRemoteControlUiIngressCurrent } from "./ingress-attribution-DAAQgd6y.mjs";
import { o as resolveBrowserOriginPolicy } from "./origin-check-C_9X1y_u.mjs";
import { t as withSerializedCredentialFallbackAttempt } from "./rate-limit-attempt-serialization-B_N04LLR.mjs";
import { n as authorizeControlUiReadHttpGatewayConnect, r as authorizeHttpGatewayConnect } from "./auth-dV1bLOjr.mjs";
import { o as prepareUserProfileRoleAuthority } from "./user-channel-identity-operations-6wbdZymd.mjs";
import { n as createProfileSessionEntryFilter } from "./session-sharing-read-BqjuH16A.mjs";
import { t as shouldUseGatewayOwnerProfile } from "./gateway-owner-profile--usQDxAz.mjs";
import { a as resolveGatewayOperatorAccessAuthority, i as hasGatewayOperatorAccessPolicies, n as GatewayOperatorAccessDeniedError, r as hasCurrentGatewayOperatorAccess } from "./operator-access-policy-BWvd6twL.mjs";
import { r as listControlUiPluginTabAuthGrants } from "./control-ui-plugin-tabs-C_6CJE64.mjs";
import { i as listDevicePairing } from "./device-pairing-D--Fzrek.mjs";
import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs";
import { t as captureGatewayAuthPolicy } from "./auth-policy-CR6nKvhI.mjs";
import { t as resolveSharedGatewaySessionGeneration } from "./ws-shared-generation-BWsSp-Zl.mjs";
import { t as sendJson } from "./http-json-ddGJz5CA.mjs";
import { f as sendMissingScopeForbidden, h as sendUnauthorized, l as sendGatewayAuthFailure } from "./http-common-FfhIIwOW.mjs";
import { c as sendGatewayHttpAuthFailure, i as captureHttpRequestAuthority, r as bindHttpResponseAuthority, s as bindHttpOperatorAccessAuthority, t as GatewayHttpRequestAuthorityError } from "./http-request-authority-CYXIvBHo.mjs";
import { n as verifyPairingToken } from "./pairing-token-alWAf5pN.mjs";
import { i as verifyDeviceToken } from "./device-pairing-tokens-Bivg3I0v.mjs";
import { a as setControlUiPluginAuthCookie, r as resolveControlUiPluginAuthCookieGrants } from "./control-ui-plugin-auth-cookie-XXccwM59.mjs";
import { t as resolveHostAccountName } from "./host-account-name-BgMaslGp.mjs";
import { i as ensureCanonicalUserProfileForTailscaleIdentity, n as ensureCanonicalGatewayOwnerProfile, r as ensureCanonicalUserProfileForEmail } from "./user-profile-writes-Coep_BY9.mjs";
import { t as createAuthenticatedGitHubIdentitySync } from "./github-user-identity-Da6Ux46-.mjs";
import { isDeepStrictEqual } from "node:util";
//#region src/gateway/http-auth-user-profile.ts
const profileLog = createSubsystemLogger("gateway/user-profiles");
function failedHttpProfileAuthentication(e) {
return {
ok: false,
authResult: {
ok: false,
reason: e instanceof GatewayOperatorAccessDeniedError ? "operator_access_denied" : "user_profile_unavailable"
}
};
}
async function checkAuthenticatedHttpUserProfile(e) {
try {
return {
ok: true,
profile: await resolveAuthenticatedHttpUserProfile(e)
};
} catch (e) {
return failedHttpProfileAuthentication(e);
}
}
/** A signed cookie retains one exact profile reference; current policy still governs its admission. */
function checkHttpCookieUserProfile(e, t) {
if (!t && (e.gateway?.roles || hasGatewayOperatorAccessPolicies(e))) return failedHttpProfileAuthentication();
if (!t) return {
ok: true,
profile: {}
};
try {
return {
ok: true,
profile: resolveHttpProfile(t, e)
};
} catch (e) {
return failedHttpProfileAuthentication(e);
}
}
/** Response disclosure retains the existing profile owner through its last synchronous check. */
async function prepareHttpUserProfileCatalog(e) {
if (e.writableEnded || e.destroyed) return false;
let t;
try {
t = await prepareUserProfileCatalog();
} catch {
return false;
}
const release = () => {
e.off("finish", release);
e.off("close", release);
t.release();
};
if (e.writableEnded || e.destroyed) {
release();
return false;
}
e.once("finish", release);
e.once("close", release);
return true;
}
function usesSharedSecretGatewayMethod(e) {
return e === "token" || e === "password";
}
async function resolveAuthenticatedHttpUserProfile(e) {
const t = getRemoteControlUiIngressContext(e.req);
if (t) {
assertRemoteControlUiIngressCurrent(t);
const e = t.resolvePrincipal();
return {
authenticatedUserProfile: e.authenticatedUserProfile,
preparedSessionProfile: e.preparedSessionProfile,
operatorRolePolicy: e.operatorRolePolicy,
operatorRoleActor: e.operatorRoleActor,
operatorAccessAuthority: e.operatorAccessAuthority
};
}
const readAdmissionPolicy = (t) => ({
auth: {
...t.gateway?.auth,
identityScopes: void 0
},
roles: t.gateway?.roles,
trustedProxies: t.gateway?.trustedProxies,
allowRealIpFallback: t.gateway?.allowRealIpFallback,
browserOrigin: resolveBrowserOriginPolicy({
req: e.req,
cfg: t
})
});
const n = structuredClone(readAdmissionPolicy(e.cfg));
const assertCurrent = () => {
if (e.req.aborted || e.req.socket?.destroyed || e.res?.destroyed || e.res?.writableEnded || !isDeepStrictEqual(n, readAdmissionPolicy(e.getRuntimeConfig?.() ?? readRuntimeConfig()))) throw new Error("HTTP profile acquisition authority expired");
};
assertCurrent();
const r = { assertCurrent };
const i = normalizeOptionalString(e.authResult.user);
const a = Boolean(e.cfg.gateway?.roles);
const o = hasGatewayOperatorAccessPolicies(e.cfg);
if (!i) {
if (shouldUseGatewayOwnerProfile({
role: "operator",
authenticatedUserId: i,
authMethod: e.authResult.method,
rolesConfigured: a
})) try {
const e = await resolveHostAccountName();
assertCurrent();
const t = await ensureCanonicalGatewayOwnerProfile(e, r);
return await prepareHttpProfile(t.id, t.updatedAt, assertCurrent);
} catch (e) {
assertCurrent();
profileLog.warn(`owner profile resolution failed: ${formatForLog(e)}`);
return {};
}
throw new Error("operator role policies require a verified durable user profile");
}
try {
const t = createAuthenticatedGitHubIdentitySync({
authResult: e.authResult,
authConfig: e.cfg.gateway?.auth,
config: e.cfg,
requestHeaders: e.req.headers,
assertCurrent
});
const n = t ? await t() : e.authResult.tailscaleIdentity ? await ensureCanonicalUserProfileForTailscaleIdentity(e.authResult.tailscaleIdentity, r) : await ensureCanonicalUserProfileForEmail(i, r);
return await prepareHttpProfile("profileId" in n ? n.profileId : n.id, n.updatedAt, assertCurrent, usesSharedSecretGatewayMethod(e.authResult.method) ? void 0 : e.cfg);
} catch (e) {
assertCurrent();
if (a || o) throw e;
return {};
}
}
async function prepareHttpProfile(e, t, n, r) {
n();
if (r && hasGatewayOperatorAccessPolicies(r)) {
(await prepareUserProfileCatalog()).release();
n();
}
const i = await prepareUserProfileRoleAuthority(e);
n();
if (!i?.isCurrent()) throw new Error("HTTP profile authority changed during acquisition");
const a = i.display;
const o = r ? resolveOperatorRolePolicyForAssignment(a.id, i.role, r, i.githubLogin ?? null) : void 0;
const s = r ? resolveGatewayOperatorAccessAuthority(e, r) : void 0;
n();
if (!i.isCurrent()) throw new Error("HTTP profile authority changed during acquisition");
return {
...projectHttpProfile(a, t, o, s),
...r ? { hasCurrentProfileAuthority: i.isCurrent } : {},
...r ? { preparedSessionProfile: {
profileId: i.profileId,
aliases: new Set(i.aliases),
role: i.role,
githubLogin: i.githubLogin
} } : {}
};
}
/** Cookie and media disclosure retain their existing synchronous final policy check. */
function resolveHttpProfile(e, t) {
const n = captureResidentUserProfileAccess(e).assertCurrent();
const r = projectUserProfileDisplay(n);
const i = t ? resolveOperatorRolePolicyForAssignment(n.id, n.role ?? null, t, n.githubLogin ?? null) : void 0;
const a = t ? resolveGatewayOperatorAccessAuthority(e, t) : void 0;
return projectHttpProfile(r, n.updated_at, i, a);
}
function projectHttpProfile(e, t, n, r) {
return {
authenticatedUserProfile: {
profileId: e.id,
displayName: e.displayName,
avatarRevision: e.avatarRevision,
hasAvatar: e.hasAvatar,
updatedAt: t
},
...n ? { operatorRolePolicy: n } : {},
...r !== void 0 ? { operatorAccessAuthority: r } : {}
};
}
function applyHttpOperatorRoleScopeCeiling(e, t) {
const n = t?.operatorRolePolicy?.scopes;
return n ? intersectOperatorScopes(e, n) : e;
}
//#endregion
//#region src/gateway/http-auth-plugin-cookie.ts
function resolveControlUiPluginAuthCookieGeneration(e, t) {
return e ? sha256Base64Url(`${e}\0${captureGatewayAuthPolicy(t, null).generation}`) : void 0;
}
function readControlUiPluginCookieRequest(e, t) {
const n = getRemoteControlUiIngressContext(e);
assertRemoteControlUiIngressCurrent(n);
if (getBearerToken(e) || e.method !== "GET" && e.method !== "HEAD") return null;
const r = readRuntimeConfig();
const i = resolveControlUiPluginAuthCookieGrants(e, {
requestPath: t.requestPath,
generation: resolveControlUiPluginAuthCookieGeneration(t.authGeneration, r)
});
if (i.length === 0) return null;
const a = i[0]?.profileId;
if (i.some((e) => e.profileId !== a)) return null;
return {
cfg: r,
grants: i,
profileId: a
};
}
async function prepareControlUiPluginCookieRequest(e, t) {
const n = readControlUiPluginCookieRequest(e, t);
if (!getRemoteControlUiIngressContext(e) && n?.profileId && !await prepareHttpUserProfileCatalog(t.res)) return null;
return authorizeControlUiPluginCookieRequest(e, t);
}
function authorizeControlUiPluginCookieRequest(e, t) {
const n = readControlUiPluginCookieRequest(e, t);
if (!n) return null;
const { cfg: r, grants: i, profileId: a } = n;
const o = getRemoteControlUiIngressContext(e)?.resolvePrincipal();
const s = o ? {
ok: true,
profile: {
authenticatedUserProfile: o.authenticatedUserProfile,
operatorRolePolicy: o.operatorRolePolicy,
operatorRoleActor: o.operatorRoleActor,
operatorAccessAuthority: o.operatorAccessAuthority
}
} : checkHttpCookieUserProfile(r, a);
if (!s.ok) {
if (s.authResult.reason === "operator_access_denied" && t.res) sendGatewayHttpAuthFailure(t.res, s.authResult);
return null;
}
const c = s.profile;
for (const e of i) e.scopes = normalizeOperatorScopeList(applyHttpOperatorRoleScopeCeiling(e.scopes, c)) ?? [];
if (t.res && !bindHttpOperatorAccessAuthority(t.res, c.operatorAccessAuthority)) return null;
return {
requestAuth: {
trustDeclaredOperatorScopes: false,
controlUiPluginGrants: i,
...c
},
operatorScopes: []
};
}
function bindControlUiPluginCookieRequestAuthority(e, t) {
const n = bindHttpResponseAuthority(e.requestAuth, t.res, t.hasCurrentClientAuthority);
const revalidate = async () => {
n.assertCurrent();
const r = authorizeControlUiPluginCookieRequest(t.req, {
requestPath: t.requestPath,
authGeneration: resolveSharedGatewaySessionGeneration(t.getResolvedAuth?.() ?? t.auth, t.trustedProxies ?? readRuntimeConfig().gateway?.trustedProxies)
});
const i = r?.requestAuth.controlUiPluginGrants ?? [];
n.assertCurrent();
if (!isDeepStrictEqual(r?.requestAuth.operatorRolePolicy, e.requestAuth.operatorRolePolicy) || !e.requestAuth.controlUiPluginGrants.every((e) => i.some((t) => t.pluginId === e.pluginId && t.path === e.path && t.match === e.match && t.profileId === e.profileId && roleScopesAllow({
role: "operator",
requestedScopes: e.scopes,
allowedScopes: t.scopes
})))) {
sendUnauthorized(t.res);
throw new GatewayHttpRequestAuthorityError("Unauthorized");
}
};
return {
...e,
requestAuth: {
...n,
revalidate
}
};
}
//#endregion
//#region src/gateway/http-auth-utils.ts
const CONTROL_UI_OPERATOR_READ_SCOPE = "operator.read";
const CONTROL_UI_OPERATOR_ROLE = "operator";
function resolveHttpBrowserOriginPolicy(e, t = readRuntimeConfig()) {
return resolveBrowserOriginPolicy({
req: e,
cfg: t
});
}
function resolveControlUiReadAuthToken(e, t) {
const n = getBearerToken(e);
if (n || !t || !e.url) return n;
try {
return normalizeOptionalString(new URL(e.url, "http://localhost").searchParams.get("token"));
} catch {
return;
}
}
async function verifyHttpOperatorDeviceToken(e, t, n = []) {
const r = await listDevicePairing();
for (const i of r.paired) {
const r = i.tokens?.[CONTROL_UI_OPERATOR_ROLE];
if (!r || r.revokedAtMs || !verifyPairingToken(e, r.token)) continue;
return (await verifyDeviceToken({
deviceId: i.deviceId,
token: e,
role: CONTROL_UI_OPERATOR_ROLE,
scopes: [
CONTROL_UI_OPERATOR_READ_SCOPE,
...r.scopes,
...n
],
requiredSharedGatewaySessionGeneration: t
})).ok ? [...r.scopes] : null;
}
return null;
}
function resolveControlUiReadOperatorScopes(e, t, n, r) {
if (t === "remote-ingress") return getRemoteControlUiIngressContext(e)?.resolvePrincipal().scopes ?? [];
if (t === "device-token") return applyHttpOperatorRoleScopeCeiling(n ?? [], r);
if (t === "trusted-proxy" || t === "tailscale") return resolveTrustedHttpOperatorScopes(e, {
trustDeclaredOperatorScopes: true,
...r
});
return t === "bootstrap-token" ? [] : [...CLI_DEFAULT_OPERATOR_SCOPES];
}
async function checkHttpOperatorCredentials(e, t) {
const { auth: n, token: r } = e;
const i = getRemoteControlUiIngressContext(e.req);
if (i) {
assertRemoteControlUiIngressCurrent(i);
return {
authResult: r ? {
ok: false,
reason: "unauthorized"
} : {
ok: true,
method: "remote-ingress"
},
authGeneration: resolveSharedGatewaySessionGeneration(n, e.trustedProxies)
};
}
const a = prepareGatewayIngressAttribution({
req: e.req,
trustedProxies: e.trustedProxies,
allowRealIpFallback: e.allowRealIpFallback
});
if (a.kind === "unattributable-proxy") return { authResult: {
ok: false,
reason: a.reason
} };
const o = a.rateLimit.subject.key;
const s = Boolean(r) && n.mode !== "trusted-proxy" && n.mode !== "none";
const run = async () => {
const i = await t({
auth: n,
connectAuth: r ? {
token: r,
password: r
} : null,
req: e.req,
browserOriginPolicy: resolveHttpBrowserOriginPolicy(e.req, e.cfg),
trustedProxies: e.trustedProxies,
allowRealIpFallback: e.allowRealIpFallback,
rateLimiter: e.rateLimiter,
clientIp: o,
rateLimitScope: AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET,
deferRateLimitFailure: s
});
const a = resolveSharedGatewaySessionGeneration(n, e.trustedProxies);
let c = i;
let l;
if (!i.ok && i.reason !== "proxy_attribution_required" && s && r) {
const recordSharedSecretFailure = async () => {
if (i.reason === "token_mismatch" || i.reason === "password_mismatch") await e.rateLimiter?.recordFailureAndDelay(o, AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET);
};
const t = e.rateLimiter?.check(o, AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN);
if (t && !t.allowed) {
await recordSharedSecretFailure();
c = {
ok: false,
reason: "rate_limited",
rateLimited: true,
retryAfterMs: t.retryAfterMs
};
} else {
const t = await verifyHttpOperatorDeviceToken(r, a, e.requiredDeviceScopes);
if (t) {
l = t;
e.rateLimiter?.reset(o, AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN);
c = {
ok: true,
method: "device-token"
};
} else {
await recordSharedSecretFailure();
await e.rateLimiter?.recordFailureAndDelay(o, AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN);
}
}
}
return {
authResult: c,
authGeneration: a,
...l ? { deviceOperatorScopes: l } : {}
};
};
if (!s || !e.rateLimiter) return await run();
return await withSerializedCredentialFallbackAttempt({
limiter: e.rateLimiter,
ip: o,
run
});
}
/** Authorize a read-only same-origin Control UI request, including paired devices. */
async function authorizeControlUiReadRequestOrReply(e) {
const t = e.getResolvedAuth?.() ?? e.auth;
const n = e.cfg ?? readRuntimeConfig();
const r = captureHttpRequestAuthority({
...e,
auth: t ?? {
mode: "none",
allowTailscale: false
}
});
if (!t) {
if (getRemoteControlUiIngressContext(e.req)) {
sendUnauthorized(e.res);
return null;
}
e.onPluginFrameGrants?.([]);
return bindHttpResponseAuthority({
authMethod: "none",
operatorScopes: [...CLI_DEFAULT_OPERATOR_SCOPES]
}, e.res, r);
}
const i = resolveControlUiReadAuthToken(e.req, e.allowQueryToken);
const { authResult: a, authGeneration: o, deviceOperatorScopes: s } = await checkHttpOperatorCredentials({
...e,
cfg: n,
auth: t,
token: i,
rateLimiter: i ? e.rateLimiter : void 0
}, authorizeControlUiReadHttpGatewayConnect);
if (!a.ok) {
if (e.replyOnFailure !== false) sendGatewayAuthFailure(e.res, a);
return null;
}
const c = await checkAuthenticatedHttpUserProfile({
authResult: a,
cfg: n,
getRuntimeConfig: e.getRuntimeConfig,
req: e.req,
res: e.res
});
if (!c.ok) {
if (e.replyOnFailure !== false) sendGatewayHttpAuthFailure(e.res, c.authResult);
return null;
}
const l = c.profile;
if (!bindHttpOperatorAccessAuthority(e.res, l.operatorAccessAuthority, e.replyOnFailure)) return null;
if (!r()) {
if (e.replyOnFailure !== false) sendUnauthorized(e.res);
return null;
}
const u = a.method ?? "none";
const d = resolveControlUiReadOperatorScopes(e.req, u, s, l);
const f = authorizeOperatorScopesForMethod(e.requiredOperatorMethod ?? "assistant.media.get", d);
if (!f.allowed) {
if (e.replyOnFailure !== false) sendMissingScopeForbidden(e.res, f.missingScope);
return null;
}
const p = bindHttpResponseAuthority({
authMethod: u,
operatorScopes: d,
...l
}, e.res, r);
if (u === "device-token" && i) {
const verifyCurrentDeviceToken = () => verifyHttpOperatorDeviceToken(i, o, s);
if (!await verifyCurrentDeviceToken() || !p.hasCurrentClientAuthority()) {
if (e.replyOnFailure !== false) {
p.assertCurrent();
sendUnauthorized(e.res);
}
return null;
}
const t = p.assertCurrent;
p.revalidate = async () => {
t();
const n = await verifyCurrentDeviceToken();
t();
if (!n) {
sendUnauthorized(e.res);
throw new GatewayHttpRequestAuthorityError("Unauthorized");
}
};
}
e.onPluginFrameGrants?.(setControlUiPluginAuthCookieForRequest(e.req, e.res, o, n, d, l.authenticatedUserProfile?.profileId));
return p;
}
/**
* Session byte routes serve one session's bytes after the route resolves its
* entry, so they apply the same per-profile visibility rule as session reads:
* the creating profile sees its own sessions and other profiles see shared ones
* within their role's session cap. Admin scope and locally approved ingress
* owner grants keep the unfiltered view. A request without an authenticated
* profile has no visibility to evaluate and stays refused.
*/
async function authorizeControlUiSessionOwnerReadRequestOrReply(e) {
const t = await authorizeControlUiReadRequestOrReply({
...e,
requiredOperatorMethod: "sessions.list"
});
if (!t) return null;
if (t.operatorScopes.includes("operator.admin") || getRemoteControlUiIngressContext(e.req) && t.authenticatedUserProfile?.profileId === "gateway-owner") return {
...t,
canReadSession: () => true
};
const n = t.preparedSessionProfile;
if (!n?.profileId) {
sendJson(e.res, 403, {
ok: false,
error: {
message: "owner access required",
type: "forbidden"
}
});
return null;
}
const r = createProfileSessionEntryFilter({
profileId: n.profileId,
sessionCap: t.operatorRolePolicy?.sessions.others
}, prepareSessionCreatorProfile(n.profileId, n.aliases));
return {
...t,
canReadSession: r
};
}
async function authorizeGatewayHttpRequestOrReply(e, t = false) {
const n = await checkGatewayHttpRequestAuth(e, t);
if (!n.ok) {
sendGatewayHttpAuthFailure(e.res, n.authResult);
return null;
}
if (!bindHttpOperatorAccessAuthority(e.res, n.requestAuth.operatorAccessAuthority)) return null;
return bindHttpResponseAuthority(n.requestAuth, e.res, n.requestAuth.hasCurrentClientAuthority);
}
function setControlUiPluginAuthCookieForRequest(e, t, n, r, i, a) {
const o = listControlUiPluginTabAuthGrants(i);
if (o.length > 0) return setControlUiPluginAuthCookie(t, o, {
generation: resolveControlUiPluginAuthCookieGeneration(n, r),
basePath: r.gateway?.controlUi?.basePath,
request: e,
...a ? { profileId: a } : {}
});
return [];
}
async function authorizePluginGatewayHttpRequestOrReply(e) {
const t = resolveSharedGatewaySessionGeneration(e.auth, e.trustedProxies);
const n = captureHttpRequestAuthority(e);
const r = await prepareControlUiPluginCookieRequest(e.req, {
requestPath: e.requestPath,
authGeneration: t,
res: e.res
});
if (r) {
if (!n()) {
sendUnauthorized(e.res);
return null;
}
return bindControlUiPluginCookieRequestAuthority(r, {
...e,
hasCurrentClientAuthority: n
});
}
if (e.res.writableEnded || e.res.destroyed) return null;
const i = await authorizeGatewayHttpRequestOrReply(e, true);
if (i?.authMethod === "device-token") {
const t = getBearerToken(e.req);
const n = [...i.deviceOperatorScopes ?? []];
const r = i.revalidate;
i.revalidate = async () => {
await r();
const { authResult: i } = await checkHttpOperatorCredentials({
...e,
auth: e.getResolvedAuth?.() ?? e.auth,
token: t,
requiredDeviceScopes: n,
rateLimiter: void 0
}, authorizeHttpGatewayConnect);
await r();
if (!i.ok || i.method !== "device-token") {
sendUnauthorized(e.res);
throw new GatewayHttpRequestAuthorityError("Unauthorized");
}
};
}
return i ? {
requestAuth: i,
operatorScopes: e.resolveOperatorScopes(e.req, i)
} : null;
}
async function checkGatewayHttpRequestAuth(e, t = false) {
const n = e.cfg ?? readRuntimeConfig();
const r = captureHttpRequestAuthority(e);
const i = getBearerToken(e.req);
const { authResult: a, deviceOperatorScopes: o } = t || getRemoteControlUiIngressContext(e.req) ? await checkHttpOperatorCredentials({
...e,
cfg: n,
token: i
}, authorizeHttpGatewayConnect) : { authResult: await authorizeHttpGatewayConnect({
auth: e.auth,
connectAuth: i ? {
token: i,
password: i
} : null,
req: e.req,
trustedProxies: e.trustedProxies,
allowRealIpFallback: e.allowRealIpFallback,
rateLimiter: e.rateLimiter,
browserOriginPolicy: resolveHttpBrowserOriginPolicy(e.req, n)
}) };
if (!a.ok) return {
ok: false,
authResult: a
};
if (!r()) return {
ok: false,
authResult: {
ok: false,
reason: "unauthorized"
}
};
const s = await checkAuthenticatedHttpUserProfile({
authResult: a,
cfg: n,
getRuntimeConfig: e.getRuntimeConfig,
req: e.req,
res: e.res
});
if (!s.ok) return s;
const c = s.profile;
if (!r()) return {
ok: false,
authResult: {
ok: false,
reason: "unauthorized"
}
};
return {
ok: true,
requestAuth: {
hasCurrentClientAuthority: () => r() && hasCurrentGatewayOperatorAccess(c.operatorAccessAuthority),
authMethod: a.method,
...a.user ? { user: a.user } : {},
trustDeclaredOperatorScopes: a.method !== "device-token" && !usesSharedSecretGatewayMethod(a.method),
...o ? { deviceOperatorScopes: applyHttpOperatorRoleScopeCeiling(o, c) } : {},
...usesSharedSecretGatewayMethod(a.method) ? { operatorRoleActor: { kind: "system" } } : {},
...c
}
};
}
async function authorizeScopedGatewayHttpRequestOrReply(e) {
const t = e.cfg ?? readRuntimeConfig();
const n = await authorizeGatewayHttpRequestOrReply({
...e,
cfg: t,
trustedProxies: e.trustedProxies ?? t.gateway?.trustedProxies,
allowRealIpFallback: e.allowRealIpFallback ?? t.gateway?.allowRealIpFallback
});
if (!n) return null;
const r = resolveSharedSecretHttpOperatorScopes(e.req, n);
const i = authorizeOperatorScopesForMethod(e.operatorMethod, r);
if (!i.allowed) {
sendMissingScopeForbidden(e.res, i.missingScope);
return null;
}
return {
cfg: t,
requestAuth: n,
operatorScopes: r
};
}
function resolveTrustedHttpOperatorScopes(e, t) {
const n = getRemoteControlUiIngressContext(e);
if (n) {
const t = n.resolvePrincipal().scopes;
const r = getHeader(e, "x-openclaw-scopes");
return r === void 0 ? t : intersectOperatorScopes(t, r.split(",").map((e) => e.trim()).filter(Boolean));
}
if (!t.trustDeclaredOperatorScopes) return [];
const r = getHeader(e, "x-openclaw-scopes");
const i = r === void 0 ? [...CLI_DEFAULT_OPERATOR_SCOPES] : r.split(",").map((e) => e.trim()).filter((e) => e.length > 0);
return applyHttpOperatorRoleScopeCeiling(i, t);
}
function resolveSharedSecretHttpOperatorScopes(e, t) {
if (usesSharedSecretGatewayMethod(t.authMethod)) return [...CLI_DEFAULT_OPERATOR_SCOPES];
return resolveTrustedHttpOperatorScopes(e, t);
}
function resolveOpenAiCompatibleHttpSenderIsOwner(e, t) {
return resolveSharedSecretHttpOperatorScopes(e, t).includes(ADMIN_SCOPE);
}
function authorizeOpenAiCompatibleHttpModelOverride(e, t) {
if (!normalizeOptionalString(getHeader(e, "x-openclaw-model")) || resolveOpenAiCompatibleHttpSenderIsOwner(e, t)) return { allowed: true };
return {
allowed: false,
missingScope: ADMIN_SCOPE
};
}
//#endregion
export { resolveHttpProfile as _, authorizePluginGatewayHttpRequestOrReply as a, resolveHttpBrowserOriginPolicy as c, resolveTrustedHttpOperatorScopes as d, setControlUiPluginAuthCookieForRequest as f, prepareHttpUserProfileCatalog as g, applyHttpOperatorRoleScopeCeiling as h, authorizeOpenAiCompatibleHttpModelOverride as i, resolveOpenAiCompatibleHttpSenderIsOwner as l, prepareControlUiPluginCookieRequest as m, authorizeControlUiSessionOwnerReadRequestOrReply as n, authorizeScopedGatewayHttpRequestOrReply as o, authorizeControlUiPluginCookieRequest as p, authorizeGatewayHttpRequestOrReply as r, checkGatewayHttpRequestAuth as s, authorizeControlUiReadRequestOrReply as t, resolveSharedSecretHttpOperatorScopes as u };