UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

447 lines (446 loc) • 15.2 kB
import { r as resolvePathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs"; import { l as trackAsyncWork } from "./async-work-scope-BXagjUap.mjs"; import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-qiyJvDDT.mjs"; import { a as resolveRuntimeWorkerUrl } from "./runtime-worker-url-DRDkoS4J.mjs"; import { s as stageSqliteTransactionState } from "./sqlite-post-commit-BrUVQObC.mjs"; import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs"; import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { n as createSqliteWorkerWriteAdmission } from "./sqlite-worker-store-D51tD0Vp.mjs"; import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs"; import { t as AuthProfileAuthorizationError } from "./authorization-contract-CQ0hvliU.mjs"; import { G as getScopedAuthProfileEnv, H as assertPersonalAuthProfileRuntime, J as isEnvOnlyAuthProfileRuntime, K as getScopedSharedAuthStore, R as authProfilesLog, Y as resolveRuntimeAuthProfileAgentDir, d as isUserModelAuthProfileId, o as capturePersonalCredentialAuthority } from "./user-model-account-authority-CRj924IP.mjs"; import { s as readAuthProfileAuthorizationLifetime } from "./authorization-lifetime-qBbc4Xfj.mjs"; import { n as enqueueKeyedTask } from "./keyed-async-queue-DewLnYvW.mjs"; import { o as noteAuthProfileFileWrite } from "./file-state-DHEsgd_R.mjs"; import { s as runOpenClawAgentWriteTransaction } from "./openclaw-agent-db-CwXW4hGa.mjs"; import { U as fenceAuthProfileAuthorizationWrite, W as retainAuthProfileAuthorizationObservation, b as resolveAuthProfileDatabasePath, z as resolveLegacyAuthProfileSourceCandidates } from "./sqlite-B2CoJ4Om.mjs"; import { d as resolveSharedAuthStorePath, u as resolveSharedAuthStoreOwnershipAsync } from "./path-resolve-CpNl_n1M.mjs"; import { a as assertAuthProfileMigrationStateAtDatabasePath, d as prepareAuthProfileMigrationCandidates } from "./legacy-source-diagnostic-cbBtIQVj.mjs"; import { U as mergeLocalAuthProfileStoreWithInheritedStore } from "./runtime-snapshots-1lyYKb7Y.mjs"; import { n as captureOpenClawAgentDatabaseExecution } from "./openclaw-agent-execution-C4FyHhb0.mjs"; import { n as openOpenClawAgentSqliteWorkerStore } from "./openclaw-agent-worker-store-Do41NaPe.mjs"; import "./store-Bh2lUvOT.mjs"; import { a as readSharedAuthProfileRows, n as prepareAgentAuthProfileRowsRead, t as loadPersistedAuthProfileStoreFromRows } from "./sqlite-read-CREbuXqx.mjs"; import { r as enrollPersonalAuthProfileAuthorizationAsync } from "./user-model-account-operations-DmkXXwRf.mjs"; import { t as enrollAuthProfileAuthorizationInDatabase } from "./authorization-enrollment-DaNGO6M2.mjs"; import { createHash } from "node:crypto"; //#region src/agents/auth-profiles/authorization-enrollment-runtime.ts /** Uses the existing agent executor/shared actor, including native transaction/commit guards. */ async function enrollOwnedAuthProfileAuthorization(e) { const { databasePath: t, assertCurrent: n } = e; let r; let i; let a; try { if (e.agentId === void 0) { const o = createSqliteWorkerWriteAdmission((e) => { n(); if (e.stage === "commit") r ??= fenceAuthProfileAuthorizationWrite(t); }, [t]); i = await runOpenClawStateWorkerOperation(e.context, (t) => t.execute({ type: "authProfiles.enrollAuthorization", input: e.input }), { assertCurrent: n, createAdmission(e) { const t = o(e); a = e.settled.then((e) => { r?.(e.kind !== "unknown"); }); return t; } }); } else if (e.context.maintenanceScope?.ownsSchemaMaintenance) { i = runOpenClawAgentWriteTransaction(({ db: i }) => { n(); const a = enrollAuthProfileAuthorizationInDatabase(i, "agent", e.input); stageSqliteTransactionState(i, { stage() {}, prepareCommit() { n(); r ??= fenceAuthProfileAuthorizationWrite(t); }, commit: () => r?.(true, a.raw), rollback: () => r?.(true), invalidate() { r ??= fenceAuthProfileAuthorizationWrite(t); r(false); } }); return a; }, { agentId: e.agentId, path: t, env: e.env }, { operationLabel: "auth-profiles.doctor-enroll-authorization", repairAdmission: { assertCurrent: n, integrityTables: ["auth_profile_store"] } }); noteAuthProfileFileWrite(t); } else { const a = { agentId: e.agentId, path: t, env: e.env }; const o = captureOpenClawAgentDatabaseExecution(a); try { await o.prepare({ assertCurrent: n, createAdmission(e) { return () => ({ nativeLocations: e.nativeLocations, admission: createSqliteWorkerOperationAdmission((t, r) => { n(); e.authorize(t); if (!r()) throw new Error("Auth profile enrollment lost admission"); }, e.attachment) }); } }); n(); const s = await openOpenClawAgentSqliteWorkerStore(a, { execution: o }, { moduleUrl: resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.authProfileInlineUsage), input: {}, assertAdmission(e) { n(); if (e.stage === "commit") r ??= fenceAuthProfileAuthorizationWrite(t); return e; } }); try { i = await s.execute({ type: "authProfiles.enrollAuthorization", input: e.input }, n); noteAuthProfileFileWrite(t); r?.(true, i.raw); } finally { await s.close(); } } finally { await o.release(); } } } finally { await a; r?.(i !== void 0, i?.raw); } } //#endregion //#region src/agents/auth-profiles/personal-authorization.ts /** Capture the private account owner's lifetime without exposing or copying bearer material. */ async function capturePersonalAuthProfileAuthorization(e) { const sanitize = (e) => e instanceof AuthProfileAuthorizationError ? e : new AuthProfileAuthorizationError("unavailable"); let t = false; let n = false; const assertSource = () => { if (t || n) throw new AuthProfileAuthorizationError("retired"); try { e.assertCurrent(); assertPersonalAuthProfileRuntime(); } catch { n = true; throw new AuthProfileAuthorizationError("retired"); } }; try { assertPersonalAuthProfileRuntime(); assertSource(); const r = captureOpenClawStateWorkerContext(); const assertOwner = () => { assertSource(); try { r.admission.assertCurrent(); r.maintenanceScope?.assertAdmission(); } catch { n = true; throw new AuthProfileAuthorizationError("retired"); } }; const i = await capturePersonalCredentialAuthority(r, e.profileId); const readCanonical = async () => { assertOwner(); const t = await executeExistingOpenClawStateRead({ path: r.admission.databasePath, env: r.environment }, { type: "userModelAccounts.authorization", authProfileId: e.profileId }, { context: r, current: true, preferIndependentWarmRead: true }); assertOwner(); return t?.authorization; }; let a = await readCanonical(); if (a && !a.authorizationId) { a = await enrollPersonalAuthProfileAuthorizationAsync({ profileId: e.profileId, assertCurrent: assertOwner }, { context: r }); assertOwner(); } if (!a?.authorizationId) throw new AuthProfileAuthorizationError("retired"); const { authorizationId: o, ownerProfileId: s } = a; i.observeAuthorizationId(o); let c = "ready"; const assertFacts = () => { assertOwner(); i.assertAuthorizationCurrent(o); }; assertFacts(); return { authorizationId: createHash("sha256").update(JSON.stringify([ "personal-auth-profile-v1", e.profileId, s, o ])).digest("hex"), assertCurrent() { assertFacts(); if (c !== "ready") throw new AuthProfileAuthorizationError("unavailable"); }, async revalidate() { assertFacts(); if (c === "pending") throw new AuthProfileAuthorizationError("unavailable"); c = "pending"; try { const e = await readCanonical(); if (e?.authorizationId !== o || e.ownerProfileId !== s) { n = true; throw new AuthProfileAuthorizationError("retired"); } assertFacts(); c = "ready"; } catch (e) { c = "unavailable"; throw sanitize(e); } }, dispose() { t = true; } }; } catch (e) { throw sanitize(e); } } //#endregion //#region src/agents/auth-profiles/authorization.ts const authorizationCaptureTails = /* @__PURE__ */ new Map(); /** * Capture a persisted credential lifetime through its canonical owner, without bearer material. * Personal accounts keep their own owner; env-only and bounded shared-store scopes never * substitute an ambient admin credential. */ async function captureAuthProfileAuthorization(e) { if (isUserModelAuthProfileId(e.profileId)) return capturePersonalAuthProfileAuthorization(e); let cleanup; const sanitize = (e) => e instanceof AuthProfileAuthorizationError ? e : new AuthProfileAuthorizationError("unavailable"); try { const { profileId: t, assertCurrent: n, cfg: r } = e; const i = resolveRuntimeAuthProfileAgentDir(e.agentDir); const a = { ...getScopedAuthProfileEnv() ?? process.env }; let o = false; let s = false; const assertSource = () => { if (o || s) throw new AuthProfileAuthorizationError("retired"); try { n(); } catch { s = true; throw new AuthProfileAuthorizationError("retired"); } }; assertSource(); if (isEnvOnlyAuthProfileRuntime() || getScopedSharedAuthStore()) throw new AuthProfileAuthorizationError("unavailable"); const c = captureOpenClawStateWorkerContext({ env: a }); const assertRoot = () => { assertSource(); try { c.admission.assertCurrent(); c.maintenanceScope?.assertAdmission(); } catch { s = true; throw new AuthProfileAuthorizationError("retired"); } }; const l = await resolveSharedAuthStoreOwnershipAsync(c); assertRoot(); const u = resolvePathViaExistingAncestorSync(resolveSharedAuthStorePath(a)); const d = i ? resolvePathViaExistingAncestorSync(resolveAuthProfileDatabasePath(i)) : u; const f = [.../* @__PURE__ */ new Set([d, u])]; const p = f.map((e) => ({ databasePath: e, agentDir: e === u ? void 0 : i, observation: retainAuthProfileAuthorizationObservation(e, t) })); const closeReaders = async () => { await Promise.all(p.map(async (e) => { const t = e.reader; e.reader = void 0; await t?.dispose(); })); }; const release = () => { o = true; for (const e of p) e.observation.dispose(); }; cleanup = async () => { release(); await closeReaders(); }; const assertOwners = () => { assertRoot(); if (resolvePathViaExistingAncestorSync(resolveSharedAuthStorePath(a)) !== u) { s = true; throw new AuthProfileAuthorizationError("retired"); } try { for (const e of p) e.reader?.assertCurrent(); } catch { s = true; throw new AuthProfileAuthorizationError("retired"); } }; const readCanonical = async () => { assertOwners(); const e = p.map((e) => e.observation.prepareRead()); const n = await Promise.all(p.map(async (e) => { if (e.databasePath === u && l.location === "state-db") return readSharedAuthProfileRows(c, void 0, "canonical"); e.reader ??= await prepareAgentAuthProfileRowsRead({ databasePath: e.databasePath, agentId: e.agentId, env: a, source: "canonical" }); e.agentId = e.reader.agentId; return e.reader.read(); })); assertOwners(); const i = []; for (const [o, s] of n.entries()) { const n = p[o]; const c = loadPersistedAuthProfileStoreFromRows(s, n.databasePath) ?? { version: 1, profiles: {} }; await prepareAuthProfileMigrationCandidates({ databasePath: n.databasePath, candidates: resolveLegacyAuthProfileSourceCandidates({ agentDir: n.agentDir, env: a }), hasCredentials: Object.keys(c.profiles).length > 0, assertCurrent: assertOwners }); assertAuthProfileMigrationStateAtDatabasePath(n.databasePath, c.profiles[t]?.provider, r); e[o](s.store.status === "readable" ? s.store.raw : void 0); i.push(c); } const o = i[0]; const m = i[f.indexOf(u)]; const h = mergeLocalAuthProfileStoreWithInheritedStore(o, d === u ? void 0 : m); const g = h.profiles[t]; if (!Object.hasOwn(h.profiles, t) || !g) { s = true; throw new AuthProfileAuthorizationError("retired"); } const _ = g === o.profiles[t] && h.runtimeLocalProfileIds?.includes(t) ? d : u; return { rows: n, selectedPath: _, lineagePaths: _ === d && g.type !== "oauth" ? [d] : f }; }; return await enqueueKeyedTask({ tails: authorizationCaptureTails, keys: f, task: async () => { const assertFacts = () => { assertOwners(); for (const e of p) { if (!e.incarnation) continue; const t = e.observation.readFact(); if (!t || t.incarnation !== e.incarnation) { s = true; throw new AuthProfileAuthorizationError("retired"); } if (e.databasePath === r) { if (t.status === "retired" || t.status === "absent" || t.expires !== void 0 && t.expires <= Date.now()) { s = true; throw new AuthProfileAuthorizationError("retired"); } if (t.status === "pending") throw new AuthProfileAuthorizationError("unavailable"); } } }; let e = await readCanonical(); const n = e.rows.flatMap(({ store: n }, r) => e.lineagePaths.includes(p[r].databasePath) && !readAuthProfileAuthorizationLifetime(n.status === "readable" ? n.raw : void 0, t) ? [{ target: p[r], store: n }] : []); if (n.length) { await closeReaders(); for (const { target: e, store: r } of n) { await enrollOwnedAuthProfileAuthorization({ databasePath: e.databasePath, agentId: e.agentId, env: a, context: c, input: { profileId: t, expected: r }, assertCurrent: assertRoot }); assertRoot(); } e = await readCanonical(); } const r = e.selectedPath; const i = p.filter((t) => e.lineagePaths.includes(t.databasePath)); for (const e of i) { e.incarnation = e.observation.readFact()?.incarnation; if (!e.incarnation) throw new AuthProfileAuthorizationError("unavailable"); } assertFacts(); return { authorizationId: createHash("sha256").update(JSON.stringify([ "mcp-auth-profile-v1", t, r, ...i.map((e) => [e.databasePath, e.incarnation]) ])).digest("hex"), assertCurrent: assertFacts, async revalidate() { assertFacts(); }, dispose() { if (o) return; release(); trackAsyncWork(closeReaders).catch(() => { authProfilesLog.warn("Auth-profile reader cleanup failed"); }); } }; } }); } catch (e) { try { await cleanup?.(); } catch (e) { throw sanitize(e); } throw sanitize(e); } } //#endregion export { captureAuthProfileAuthorization as t };