openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
298 lines (297 loc) • 10.2 kB
JavaScript
import { x as registerOpenClawStateDatabaseLifecycleListener } from "./openclaw-state-db-cache-CkwtTqzF.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, n as executeOpenClawStateWorker } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { t as AuthProfileAuthorizationError } from "./authorization-contract-CQ0hvliU.mjs";
import { r as withOpenClawStateLeaseWorkerAdmission } from "./openclaw-state-lease-worker-owner-ByOat7YE.mjs";
import { n as runWithOpenClawStateLeaseWorker } from "./openclaw-state-lease-worker-operation-BbYaDixv.mjs";
import { r as recordMcpStartupAuthorizationRequired } from "./mcp-startup-backoff-cb5C4N0P.mjs";
import { n as isMcpOAuthAuthorizationReceipt } from "./mcp-oauth-authorization-facts-BN0BPuN8.mjs";
import { n as mcpOAuthSignInHint } from "./mcp-oauth-identity-B4O1ccto.mjs";
//#region src/agents/mcp-oauth-store.authorization.ts
const databases = /* @__PURE__ */ new Map();
let observingLifecycle = false;
function retainMcpOAuthAuthorizationState(e, t) {
if (!observingLifecycle) {
observingLifecycle = true;
registerOpenClawStateDatabaseLifecycleListener((e) => {
if (e.kind !== "opened" && e.identity) databases.delete(e.identity.key);
});
}
e.assertCurrent();
const n = e.identity.key;
let r = databases.get(n);
if (!r) {
r = /* @__PURE__ */ new Map();
databases.set(n, r);
}
let i = r.get(t);
if (!i) {
i = {
revision: {},
fact: { authorizationId: null },
pending: 0,
uncertain: false,
references: 0
};
r.set(t, i);
}
const a = i;
a.references++;
let o = false;
const assertCurrent = () => {
try {
e.assertCurrent();
} catch {
throw new AuthProfileAuthorizationError("retired");
}
if (o || databases.get(n)?.get(t) !== a) throw new AuthProfileAuthorizationError("retired");
};
const assertSettled = () => {
assertCurrent();
if (a.uncertain || a.pending) throw new AuthProfileAuthorizationError("unavailable");
};
return {
assertSettled,
captureRevision() {
const e = a.revision;
return () => {
try {
assertSettled();
return a.revision === e;
} catch {
return false;
}
};
},
assertAuthorization(e) {
assertSettled();
if (a.fact.authorizationId !== e || a.fact.expiresAt !== void 0 && a.fact.expiresAt <= Date.now()) throw new AuthProfileAuthorizationError("retired");
},
prepareRead() {
assertSettled();
const e = a.revision;
return (t) => {
assertSettled();
if (a.revision !== e) throw new AuthProfileAuthorizationError("unavailable");
if (a.fact.authorizationId !== t.authorizationId || a.fact.expiresAt !== t.expiresAt) {
a.revision = {};
a.fact = t;
}
};
},
/** Called synchronously before the native lease owner can grant COMMIT. */
fence() {
assertCurrent();
a.revision = {};
a.pending++;
let e = false;
return (t, n) => {
if (e) return;
e = true;
if (!t) a.uncertain = true;
else if (n) a.fact = n;
a.revision = {};
a.pending--;
};
},
release() {
if (o) return;
o = true;
a.references--;
if (!a.references && !a.pending && !a.uncertain && databases.get(n)?.get(t) === a) {
r.delete(t);
if (!r.size) databases.delete(n);
}
}
};
}
function mcpOAuthAuthorizationRequiredError(e, t, n = false) {
const r = /* @__PURE__ */ new Error(`MCP server "${e.serverName}" requires ${n ? "additional " : ""}OAuth authorization. ${mcpOAuthSignInHint(e)}`);
recordMcpStartupAuthorizationRequired(r, () => {
const n = retainMcpOAuthAuthorizationState(t, e.storeKey);
return {
isCurrent: n.captureRevision(),
dispose: n.release
};
});
return r;
}
//#endregion
//#region src/agents/mcp-oauth-status.ts
function projectMcpOAuthCredentialsStatus(e) {
if (e.pendingAuthorizationChallenge?.requiresAuthorization === true) return { state: "requires-authorization" };
if (e.tokens) return {
state: "authorized",
...e.tokenExpiresAt === void 0 ? {} : { expiresAt: e.tokenExpiresAt }
};
if (e.clientInformation || e.codeVerifier || e.discoveryState || e.lastAuthorizationUrl || e.redirectUrl || e.pendingAuthorizationChallenge) return { state: "pending-authorization" };
return { state: "unauthenticated" };
}
//#endregion
//#region src/agents/mcp-oauth-store.ts
function readExisting(e, t) {
return executeExistingOpenClawStateRead({
path: e.admission.databasePath,
env: e.environment
}, t, { context: e });
}
/** Read canonical state, opening the writable lifecycle when runtime owns it. */
async function readMcpOAuthStore(e, t = captureOpenClawStateWorkerContext()) {
return executeOpenClawStateWorker(t, {
type: "mcpOAuth.read",
input: e
});
}
/** Read status state without creating or repairing the shared database. */
async function readMcpOAuthStoreReadOnly(e, t = captureOpenClawStateWorkerContext()) {
return (await readExisting(t, {
type: "mcpOAuth.readOnly",
input: e
}))?.value ?? {};
}
async function readMcpOAuthStoreStatuses(e, t = captureOpenClawStateWorkerContext()) {
if (e.length === 0) return [];
return (await readExisting(t, {
type: "mcpOAuth.statuses",
input: e
}))?.value ?? e.map(() => projectMcpOAuthCredentialsStatus({}));
}
/** List canonical store keys matching one server/principal prefix without creating state. */
async function listMcpOAuthStoreKeysByPrefix(e, t = captureOpenClawStateWorkerContext()) {
return (await readExisting(t, {
type: "mcpOAuth.keys",
input: e
}))?.value ?? [];
}
async function countMcpOAuthStorePrincipals(e) {
return (await readExisting(captureOpenClawStateWorkerContext(), {
type: "mcpOAuth.countPrincipals",
input: e
}))?.value ?? 0;
}
/** Resolve one unexpired callback state without creating state or scanning credential JSON. */
async function readMcpOAuthPendingAuthorization(e, t = captureOpenClawStateWorkerContext()) {
return (await readExisting(t, {
type: "mcpOAuth.pending",
input: e
}))?.value;
}
/** Apply a bounded mutation under its original live store lease. */
function mutateMcpOAuthStore({ storeKey: e, lease: t, context: n }, r, i) {
const a = structuredClone(r);
return runMcpOAuthCredentialWrite({
storeKey: e,
lease: t,
context: n
}, (n, r) => n.execute({
type: "mcpOAuth.mutate",
input: {
storeKey: e,
identity: r,
mutation: a
}
}, { signal: t.signal }), i);
}
/** Claim one exact unexpired callback state while its store lease is still owned. */
function consumeOAuthState({ storeKey: e, lease: t, context: n }, r, i) {
return runWithOpenClawStateLeaseWorker(t, n, (n, i) => n.execute({
type: "mcpOAuth.consumePending",
input: {
storeKey: e,
identity: i,
state: r
}
}, { signal: t.signal }), i);
}
/** Replace one store's callback state after OAuth persisted its session. */
function writeMcpOAuthPendingAuthorization({ storeKey: e, lease: t, context: n }, r, i) {
return runWithOpenClawStateLeaseWorker(t, n, (n, i) => n.execute({
type: "mcpOAuth.writePending",
input: {
storeKey: e,
identity: i,
state: r
}
}, { signal: t.signal }), i);
}
/** Delete callback correlation for one settled or cleared OAuth store. */
function deleteMcpOAuthPendingAuthorization({ storeKey: e, lease: t, context: n }, r) {
return runWithOpenClawStateLeaseWorker(t, n, (n, r) => n.execute({
type: "mcpOAuth.deletePending",
input: {
storeKey: e,
identity: r
}
}, { signal: t.signal }), r);
}
/** Clear one OAuth session while retaining explicit logout provenance. */
function clearMcpOAuthStore({ storeKey: e, lease: t, context: n }) {
return runMcpOAuthCredentialWrite({
storeKey: e,
lease: t,
context: n
}, (n, r) => n.execute({
type: "mcpOAuth.clear",
input: {
storeKey: e,
identity: r
}
}, { signal: t.signal }));
}
/** The lease owns admission; the credential owner fences and publishes its authorization fact. */
async function runMcpOAuthCredentialWrite({ storeKey: e, lease: t, context: n }, r, i) {
let a;
let o;
let s;
const c = i?.beforeCommit;
try {
return await withOpenClawStateLeaseWorkerAdmission(t, n.admission.databasePath, (t) => runOpenClawStateWorkerOperation(n, (e) => r(e, t.identity), {
assertCurrent: t.assertCurrent,
createAdmission(n) {
const r = t.createAdmission(n);
s = n.settled.then((t) => {
if (!o) return;
let n = false;
try {
const i = r.admission.committed?.facts;
if (i !== void 0 && (!isMcpOAuthAuthorizationReceipt(i) || i.storeKey !== e)) throw new Error("MCP OAuth mutation returned an invalid commit receipt");
n = t.kind !== "unknown";
o(n, i?.authorization);
} finally {
o(n);
}
});
s.catch(() => void 0);
return r;
}
}), {
...i,
assertCurrent: i?.assertCurrent ?? (() => {}),
beforeCommit() {
c?.();
a = retainMcpOAuthAuthorizationState(n.admission, e);
o = a.fence();
}
});
} finally {
try {
await s;
} finally {
a?.release();
}
}
}
/** Remove orphan callback rows for a removed server's requester prefix. */
function deleteMcpOAuthPendingAuthorizationsByPrefix(e, t = captureOpenClawStateWorkerContext()) {
return runOpenClawStateWorkerOperation(t, (t) => t.execute({
type: "mcpOAuth.clearPendingPrefix",
input: e
}), {
assertCurrent: t.admission.assertCurrent,
createAdmission: createSqliteWorkerWriteAdmission(t.admission.assertCurrent, [t.admission.databasePath])
});
}
//#endregion
export { deleteMcpOAuthPendingAuthorizationsByPrefix as a, readMcpOAuthPendingAuthorization as c, readMcpOAuthStoreStatuses as d, writeMcpOAuthPendingAuthorization as f, retainMcpOAuthAuthorizationState as h, deleteMcpOAuthPendingAuthorization as i, readMcpOAuthStore as l, mcpOAuthAuthorizationRequiredError as m, consumeOAuthState as n, listMcpOAuthStoreKeysByPrefix as o, projectMcpOAuthCredentialsStatus as p, countMcpOAuthStorePrincipals as r, mutateMcpOAuthStore as s, clearMcpOAuthStore as t, readMcpOAuthStoreReadOnly as u };