UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

680 lines (679 loc) • 27 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { o as openRootFileSync } from "./boundary-file-read-BfaFLDqt.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import "./paths-DAcAg5aV.mjs"; import { f as readDatabaseIdentityBirthtime, h as resolveDatabasePathKey } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { b as publishSqliteDatabaseAdmission, rt as OPENCLAW_STATE_SCHEMA_SQL } from "./sqlite-database-admission-DQIqro3d.mjs"; import { o as isSqliteLockError } from "./sqlite-error-diagnostics-6_hREUnq.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely, v as expressionBuilder } from "./kysely-sync-YJo2lmGV.mjs"; import { o as getAdmittedSqliteSchemaFacts, t as admitSqliteSchema } from "./sqlite-schema-facts-B1bVE8IB.mjs"; import { c as writeSqliteUserVersion, o as readSqliteUserVersion } from "./sqlite-user-version-C02a4KwH.mjs"; import { n as StartupMaintenanceRequiredError } from "./startup-maintenance-required-DEn4Krys.mjs"; import { n as openNodeSqliteDatabase, r as resolveExistingSqliteFileUri } from "./node-sqlite-CU4puofF.mjs"; import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-BHHu6P5-.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { r as assertSqliteIntegrity } from "./sqlite-integrity-CCmEgO_m.mjs"; import { c as runUpdateSqliteMigration } from "./update-doctor-migration-attribution-Dp_N9vmd.mjs"; import { t as readGeneratedSqliteCatalog } from "./sqlite-catalogs-C_npqocs.mjs"; import { t as assertSqliteSchemaContains } from "./sqlite-schema-contract-D3pR9vZs.mjs"; import { n as CLIENT_CREDENTIAL_SCHEMA_SQL, r as CLIENT_CREDENTIAL_SCHEMA_VERSION } from "./client-credential-schema-DsmkD6RV.mjs"; import { t as chunkItems } from "./chunk-items-DkvjVLcB.mjs"; import { a as salvageStoredIdentityRow, o as storedDeviceIdentityFromRow, s as storedDeviceIdentityToRow } from "./device-identity-material-BGzHHiUD.mjs"; import { a as validateSource, i as sourceRows, n as hashClientCredentialRows } from "./client-credential-migration-data-GzQwPmBH.mjs"; import { t as resolveClientCredentialStorePath } from "./client-credential-paths-CIYPaDgB.mjs"; import { a as serializeClientCredentialReceipt, i as readClientCredentialFileIdentity, n as emptyClientCredentialReceipt, r as parseClientCredentialReceipt, t as CLIENT_CREDENTIAL_LEGACY_KEYS } from "./client-credential-receipt-yx56NK9z.mjs"; import { t as preparePrivateStoreFileSync } from "./private-store-file-8MwdbJtK.mjs"; import fs from "node:fs"; import path from "node:path"; import { inspectDarwinAcl } from "@openclaw/fs-safe/permissions"; //#region src/infra/client-credential-native-bootstrap.ts /** Read-only classification for the native credential bootstrap that predates engine selection. */ function isNativeClientCredentialBootstrap(e) { admitSqliteSchema(e); const t = getAdmittedSqliteSchemaFacts(e); if (t.userVersion !== 0) return false; const n = [ ...[...t.tables].map((e) => ({ type: "table", name: e })), ...[...t.indexes].map((e) => ({ type: "index", name: e })), ...[...t.views].map((e) => ({ type: "view", name: e })), ...[...t.triggers.keys()].map((e) => ({ type: "trigger", name: e })) ].filter(({ name: e }) => !e.startsWith("sqlite_")); const r = /* @__PURE__ */ new Set([ "table:device_identities", "index:idx_device_identities_device", "table:device_auth_tokens", "index:idx_device_auth_tokens_updated", "table:macos_port_guardian_records", "index:idx_macos_port_guardian_records_port" ]); if (!n.length || n.some((e) => !r.has(`${e.type}:${e.name}`))) return false; if (t.tables.has("macos_port_guardian_records") || t.indexes.has("idx_macos_port_guardian_records_port")) { const t = readGeneratedSqliteCatalog(OPENCLAW_STATE_SCHEMA_SQL)?.tables.filter(({ name: e }) => e === "macos_port_guardian_records"); if (!t?.length) throw new Error("Native PortGuardian companion has no canonical schema catalog."); assertSqliteSchemaContains(e, "Native PortGuardian companion", { tables: t, views: [] }); } assertSqliteSchemaContains(e, "Native client credential bootstrap", CLIENT_CREDENTIAL_SCHEMA_SQL, { allowedMissingTables: [ "device_identities", "device_auth_tokens", "gateway_origin_device_tokens", "native_exec_socket_credentials", "client_credential_migration" ] }); return true; } /** Independent native sources are read-only; journal bytes and timestamps are not content identity. */ function readIndependentClientCredentialSource(e) { try { var t = _usingCtx(); const n = readClientCredentialFileIdentity(e); if (!n) throw new Error("Independent client credential source is missing; restore its matching backup."); const r = fs.openSync(e, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); try { const e = Buffer.alloc(100); if (fs.readSync(r, e, 0, e.length, 0) !== e.length || e.subarray(0, 16).toString("binary") !== "SQLite format 3\0" || e[18] !== 1 || e[19] !== 1) throw new Error("Independent client credentials require DELETE journal mode; stop the old client and restore a compatible source."); } finally { fs.closeSync(r); } const i = t.u(openNodeSqliteDatabase(e, { readOnly: true })); if (!isNativeClientCredentialBootstrap(i)) throw new Error("Independent client credential source is not a native credential-only database."); i.exec("BEGIN"); try { const e = getAdmittedSqliteSchemaFacts(i).tables.has("device_auth_tokens"); const t = sourceRows(i, true); validateSource(t); const r = hashClientCredentialRows(t, { authTablePresent: e }); return { file: n, identity: `${n.dev}:${n.ino}`, sha256: r, rows: t, authTablePresent: e }; } finally { i.exec("ROLLBACK"); } } catch (e) { t.e = e; } finally { t.d(); } } //#endregion //#region src/infra/client-credential-readiness.ts var ClientCredentialMigrationRequiredError = class extends StartupMaintenanceRequiredError { constructor(e = "Client credential migration is incomplete or stale; run openclaw doctor --fix before using this client.") { super("state-migrations", e); this.name = "ClientCredentialMigrationRequiredError"; } }; function notReady() { return new ClientCredentialMigrationRequiredError(); } function assertSupportedVersion(e) { if (e !== 1) throw new Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`); } /** The receipt is a cross-process migration-phase guard, including in-place copied → complete transitions. */ function readClientCredentialAdmission(e) { let t; try { t = e.prepare(` SELECT header.user_version, receipt.source_store, receipt.phase FROM pragma_user_version AS header LEFT JOIN client_credential_migration AS receipt ON receipt.version = 1 `).get(); } catch (t) { assertSupportedVersion(readSqliteUserVersion(e)); throw t; } if (!t || typeof t.user_version !== "number") throw notReady(); assertSupportedVersion(t.user_version); const n = e.location(); return { stored: t.source_store === null ? null : { phase: t.phase === "complete" ? "complete" : "copied", receipt: parseClientCredentialReceipt(String(t.source_store), n ? path.dirname(path.dirname(n)) : void 0) } }; } function readClientCredentialReceipt(e, t) { const n = getNodeSqliteKysely(e); const r = executeSqliteQueryTakeFirstSync(e, n.selectFrom("client_credential_migration").selectAll().where("version", "=", 1)); const i = e.location(); return r ? { phase: r.phase, receipt: parseClientCredentialReceipt(r.source_store, t ?? (i ? path.dirname(path.dirname(i)) : void 0)) } : null; } function writeClientCredentialReceipt(e, t, n, r = Date.now()) { const i = getNodeSqliteKysely(e); const a = e.location(); const o = { version: 1, source_store: serializeClientCredentialReceipt(t, a ? path.dirname(path.dirname(a)) : void 0), phase: n, updated_at_ms: r }; executeSqliteQuerySync(e, i.insertInto("client_credential_migration").values(o).onConflict((e) => e.column("version").doUpdateSet(o))); } function assertClientCredentialLegacyReady(e, t, n = false, r) { let i = false; const a = e ? getNodeSqliteKysely(e) : void 0; const o = r ?? (e ? readClientCredentialReceipt(e)?.receipt : void 0); const s = { primary: "device", node: "node-device", shareExtension: "share-device" }; for (const r of [ "primary", "node", "shareExtension" ]) for (const c of ["identity", "auth"]) { if (o?.legacyImports[`${c}:${r}`]) continue; const l = `${s[r]}${c === "auth" ? "-auth" : ""}.json`; const u = path.join(resolveStateDir(t), "identity", l); if ([ u, `${u}.doctor-importing`, `${u}.native-importing` ].some((e) => fs.existsSync(e))) { if (c === "identity" && e && a && executeSqliteQueryTakeFirstSync(e, a.selectFrom("device_identities").select("identity_key").where("identity_key", "=", r))) continue; throw new ClientCredentialMigrationRequiredError("Legacy client credentials require migration; run openclaw doctor --fix before using this client."); } if (n && o) { o.legacyImports[`${c}:${r}`] = { sha256: null }; i = true; } } if (i && o && e) writeClientCredentialReceipt(e, o, "complete"); } function assertMissingClientCredentialStoreReady(e) { assertClientCredentialLegacyReady(null, e); if (readClientCredentialFileIdentity(resolveOpenClawStateSqlitePath(e))) throw notReady(); } function prepareClientCredentialReceipt(e, t, n, r = false, i = readClientCredentialReceipt(e)) { let a = i; const o = readClientCredentialFileIdentity(resolveOpenClawStateSqlitePath(t)); if (!a && n && !o) { assertClientCredentialLegacyReady(null, t); const n = emptyClientCredentialReceipt(); for (const e of CLIENT_CREDENTIAL_LEGACY_KEYS) n.legacyImports[e] = { sha256: null }; writeClientCredentialReceipt(e, n, "complete"); a = { phase: "complete", receipt: n }; } if (!a || a.phase !== "complete") throw notReady(); if (a.receipt.source?.kind === "independent") { const t = a.receipt.sharedFile; const n = readIndependentClientCredentialSource(t.path); if (n.identity !== a.receipt.source.identity || n.file.path !== t.path || n.file.dev !== t.dev || n.file.ino !== t.ino || n.sha256 !== a.receipt.source.sha256) { if (r) throw new Error("Independent client credentials changed; open the client or run openclaw doctor --fix before read-only inspection."); const t = getNodeSqliteKysely(e); executeSqliteQuerySync(e, t.deleteFrom("device_auth_tokens")); executeSqliteQuerySync(e, t.deleteFrom("device_identities")); executeSqliteQuerySync(e, t.deleteFrom("gateway_origin_device_tokens")); for (const r of chunkItems(n.rows.identities, 500)) executeSqliteQuerySync(e, t.insertInto("device_identities").values(r)); for (const r of chunkItems(n.rows.tokens, 500)) executeSqliteQuerySync(e, t.insertInto("device_auth_tokens").values(r)); a.receipt.source = { kind: "independent", engine: "native-v0", identity: n.identity, generation: "0", sha256: n.sha256, destinationVersion: 1 }; a.receipt.sharedFile = n.file; writeClientCredentialReceipt(e, a.receipt, "complete"); } } else { const e = a.receipt.sharedFile; if (e === null ? o !== null : o === null || e.path !== o.path || e.dev !== o.dev || e.ino !== o.ino) throw notReady(); } return a; } /** Canonical receipts never open the selected Gateway database. */ function assertClientCredentialStoreReady(e, t, n) { prepareClientCredentialReceipt(e, t, n); } /** Admit once under the local owner's existing transaction and native custody. */ function admitClientCredentialStore(e, t, n) { const r = prepareClientCredentialReceipt(e, t, n.initialize, n.readOnly, n.stored); assertClientCredentialLegacyReady(e, t, !n.readOnly, r.receipt); return r.receipt; } //#endregion //#region src/infra/client-credential-operations.ts function encodeClientNativeTokenRole(e, t) { return `v2.${Buffer.from(t).toString("base64url")}.${Buffer.from(e.trim()).toString("base64url")}`; } function decodeRole(e) { const t = e.split("."); if (t.length === 3 && t[0] === "v2" && t[1] !== void 0 && t[2] !== void 0) try { const decode = (e) => { if (!/^[A-Za-z0-9_-]*$/u.test(e) || e.length % 4 === 1) throw new Error("Invalid component"); return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(e, "base64url")); }; return { gateway: decode(t[1]), role: decode(t[2]) }; } catch {} return { role: e, gateway: null }; } function clearClientNativeTokens(e, t, n) { const r = getNodeSqliteKysely(e); if (n.kind === "all") return Number(executeSqliteQuerySync(e, r.deleteFrom("device_auth_tokens").where("device_id", "=", t)).numAffectedRows); const i = executeSqliteQuerySync(e, r.selectFrom("device_auth_tokens").select("role").where("device_id", "=", t)).rows.filter(({ role: e }) => { const t = decodeRole(e); if (n.kind === "role") return t.role === n.role.trim(); if (n.kind === "gateway") return t.gateway === n.gateway; return t.gateway === null; }).map(({ role: e }) => e); if (i.length === 0) return 0; executeSqliteQuerySync(e, r.deleteFrom("device_auth_tokens").where("device_id", "=", t).where("role", "in", i)); return i.length; } /** A scoped winner is retained; the ambiguous legacy token is always consumed. */ function claimClientNativeToken(e, t, n, r) { const i = getNodeSqliteKysely(e); const a = n.trim(); const o = executeSqliteQueryTakeFirstSync(e, i.selectFrom("device_auth_tokens").selectAll().where("device_id", "=", t).where("role", "=", a)); if (!o) return false; executeSqliteQuerySync(e, i.insertInto("device_auth_tokens").values({ ...o, role: encodeClientNativeTokenRole(n, r) }).onConflict((e) => e.columns(["device_id", "role"]).doNothing())); executeSqliteQuerySync(e, i.deleteFrom("device_auth_tokens").where("device_id", "=", t).where("role", "=", a)); return true; } function performClientCredentialOperation(e, t, n) { const r = getNodeSqliteKysely(e); switch (t.kind) { case "identity.read": case "identity.create": case "identity.repair": { const n = t.kind === "identity.read" ? t.identity_key : t.identity.identity_key; const i = executeSqliteQueryTakeFirstSync(e, r.selectFrom("device_identities").selectAll().where("identity_key", "=", n)); if (t.kind === "identity.repair") { if (i) try { storedDeviceIdentityFromRow(i, n); return { kind: "identityRepair", identity: i, repaired: false, rotated: false }; } catch {} const a = i ? salvageStoredIdentityRow(i, n, t.identity.updated_at_ms) : null; const o = a ? storedDeviceIdentityToRow(n, a, t.identity.updated_at_ms) : t.identity; storedDeviceIdentityFromRow(o, n); executeSqliteQuerySync(e, r.insertInto("device_identities").values(o).onConflict((e) => e.column("identity_key").doUpdateSet(o))); return { kind: "identityRepair", identity: o, repaired: true, rotated: a === null }; } if (i) { storedDeviceIdentityFromRow(i, n); return { kind: "identity", identity: i }; } if (t.kind === "identity.create") { storedDeviceIdentityFromRow(t.identity, n); executeSqliteQuerySync(e, r.insertInto("device_identities").values(t.identity)); return { kind: "identity", identity: t.identity }; } return { kind: "identity", identity: null }; } case "native.tokens.clear": return { kind: "cleared", count: clearClientNativeTokens(e, t.device_id, t.selector) }; case "native.token.claim": return { kind: "changed", changed: claimClientNativeToken(e, t.device_id, t.role, t.gateway) }; case "token.list": { const n = t.gateway_scope === void 0 ? "device_auth_tokens" : "gateway_origin_device_tokens"; let i = r.selectFrom(n).selectAll().where("device_id", "=", t.device_id); if (t.gateway_scope !== void 0) i = i.where("gateway_scope", "=", t.gateway_scope); if (t.afterRole !== void 0) i = i.where("role", ">", t.afterRole); const a = Math.max(1, Math.min(32, Math.trunc(t.limit ?? 32))); const o = executeSqliteQuerySync(e, i.orderBy("role").limit(a + 1)).rows; const s = o.slice(0, a).map(({ device_id: e, role: t, token: n, scopes_json: r, updated_at_ms: i }) => ({ device_id: e, role: t, token: n, scopes_json: r, updated_at_ms: i })); return { kind: "tokens", tokens: s, nextRole: o.length > a ? s.at(-1)?.role ?? null : null }; } case "token.read": case "token.replace": case "token.remove": { const { key: n } = t; const i = n.gateway_scope === void 0 ? "device_auth_tokens" : "gateway_origin_device_tokens"; const a = expressionBuilder(); const o = a.and([ a("device_id", "=", n.device_id), a("role", "=", n.role), ...n.gateway_scope === void 0 ? [] : [a("gateway_scope", "=", n.gateway_scope)] ]); const s = r.selectFrom(i).selectAll().where(o); if (t.kind === "token.read") { const t = executeSqliteQueryTakeFirstSync(e, s); return { kind: "token", token: t ? { device_id: t.device_id, role: t.role, token: t.token, scopes_json: t.scopes_json, updated_at_ms: t.updated_at_ms } : null }; } const c = executeSqliteQueryTakeFirstSync(e, s); const l = t.expectedToken === void 0 ? t.kind !== "token.remove" || t.observedToken === void 0 : (c?.token ?? null) === t.expectedToken; const u = t.kind === "token.remove" && t.observedToken !== void 0 && c?.token === t.observedToken && (t.expectedToken === void 0 || typeof t.expectedToken === "string" && t.observedToken.trim() === t.expectedToken); if (!(l || u)) return { kind: "changed", changed: false }; if (t.kind === "token.remove") { if (!c) return { kind: "changed", changed: false }; executeSqliteQuerySync(e, r.deleteFrom(i).where(o)); } else { const i = { ...t.token, device_id: n.device_id, role: n.role }; if (n.gateway_scope === void 0) executeSqliteQuerySync(e, r.insertInto("device_auth_tokens").values(i).onConflict((e) => e.columns(["device_id", "role"]).doUpdateSet(i))); else executeSqliteQuerySync(e, r.insertInto("gateway_origin_device_tokens").values({ ...i, gateway_scope: n.gateway_scope }).onConflict((e) => e.columns([ "gateway_scope", "device_id", "role" ]).doUpdateSet(i))); } return { kind: "changed", changed: true }; } case "socket.read": case "socket.ensure": { const i = executeSqliteQueryTakeFirstSync(e, r.selectFrom("native_exec_socket_credentials").selectAll().where("socket_key", "=", "current")) ?? null; if (t.kind === "socket.read") return { kind: "socket", socket: i }; const a = t.requested?.path?.trim(); const o = i?.socket_path; const s = !a && o === path.join(n, "exec-approvals.sock") && o !== t.fallback.socket_path; const c = { socket_key: "current", socket_path: a || (s ? t.fallback.socket_path : o) || t.fallback.socket_path, socket_token: t.requested?.token?.trim() || i?.socket_token || t.fallback.socket_token, updated_at_ms: t.fallback.updated_at_ms }; if (i && i.socket_path === c.socket_path && i.socket_token === c.socket_token) return { kind: "socket", socket: i }; executeSqliteQuerySync(e, r.insertInto("native_exec_socket_credentials").values(c).onConflict((e) => e.column("socket_key").doUpdateSet(c))); return { kind: "socket", socket: c }; } default: throw new Error("Unsupported client credential operation."); } } //#endregion //#region src/infra/client-credential-store.ts const retainedPaths = resolveGlobalSingleton(Symbol.for("openclaw.clientCredentialCustody"), () => /* @__PURE__ */ new Set()); const admittedFiles = resolveGlobalSingleton(Symbol.for("openclaw.clientCredentialAdmittedFiles"), () => /* @__PURE__ */ new Map(), (e) => e.clear()); var ClientCredentialBusyError = class extends Error { constructor() { super("Client credential owner is busy."); this.name = "ClientCredentialBusyError"; } }; function isClientCredentialBusyError(e) { return e instanceof ClientCredentialBusyError || isSqliteLockError(e); } const schemaAdmission = { name: "client.credentials.schema-v1", schemaDependent: true, read: (e) => e === true ? true : void 0 }; function assertPrivateAcl(e) { if (process.platform === "darwin" && inspectDarwinAcl(e).kind !== "none") throw new Error("Client credentials require a private directory and file without ACL entries."); } /** One admitted handle retains SQLite exclusion across individual commits. */ function openClientCredentialCustody(e, t = {}, n) { const r = (t.createIfMissing ?? false) && !t.readOnly; const i = resolveClientCredentialStorePath(e); const a = path.dirname(i); const o = resolveDatabasePathKey(i); if (retainedPaths.has(o)) throw new ClientCredentialBusyError(); if (t.migration) admittedFiles.delete(o); if (!t.migration && !fs.existsSync(i)) assertMissingClientCredentialStoreReady(e); const s = fs.lstatSync(a, { throwIfNoEntry: false }); if (s && (!s.isDirectory() || process.getuid && s.uid !== process.getuid() || process.platform !== "win32" && (s.mode & 63) !== 0)) throw new Error("Client credential directory is unsafe."); if (!s && !r) return; if (s) assertPrivateAcl(a); let c = false; if (r) c = preparePrivateStoreFileSync(i, Boolean(s)); const l = openRootFileSync({ absolutePath: i, rootPath: a, boundaryLabel: "client credential store", rejectSymlinks: true }); if (!l.ok) { if (hasErrnoCode(l.error, "ENOENT") && !r) return; throw new Error("Client credential store cannot be safely opened.", { cause: l.error }); } retainedPaths.add(o); let u; let d = false; let physicalClose; try { const a = fs.fstatSync(l.fd, { bigint: true }); if (process.getuid && a.uid !== BigInt(process.getuid()) || process.platform !== "win32" && (a.mode & 63n) !== 0n) throw new Error("Client credential store owner is unsafe."); const s = `${a.dev}:${a.ino}:${readDatabaseIdentityBirthtime(a)}`; assertPrivateAcl(i); u = openNodeSqliteDatabase(resolveExistingSqliteFileUri(i), { timeout: t.timeoutMs ?? 5e3 }); const f = u; if (u.prepare("PRAGMA journal_mode").get()?.journal_mode !== "delete") throw new Error("Client credentials require DELETE journal mode for exclusive owner custody."); physicalClose = () => { if (!d) { d = true; try { f.close(); } finally { fs.closeSync(l.fd); retainedPaths.delete(o); } } }; const transaction = (e) => { if (d) throw new Error("Client credential custody is closed."); if (t.readOnly) return runSqliteImmediateTransactionSync(f, e); return runUpdateSqliteMigration(f, i, () => runSqliteImmediateTransactionSync(f, e), { retainExclusive: true }); }; const p = admittedFiles.get(o); let m = false; let h = false; transaction(() => { f.exec("PRAGMA locking_mode=EXCLUSIVE"); if (t.migration || p?.identity !== s || p.version !== 1) { const e = readSqliteUserVersion(f); if (e === 0 && !f.prepare("SELECT 1 FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'").get()) { if (!r) throw new Error("Client credential store is empty; run openclaw doctor --fix."); f.exec(CLIENT_CREDENTIAL_SCHEMA_SQL); m = true; writeSqliteUserVersion(f, 1); } else { if (e !== 1) throw new Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`); assertSqliteSchemaContains(f, "Client credentials", CLIENT_CREDENTIAL_SCHEMA_SQL); assertSqliteIntegrity(f, "Client credentials"); } publishSqliteDatabaseAdmission(f, schemaAdmission, true); } if (!t.migration) { const n = readClientCredentialAdmission(f); const r = admitClientCredentialStore(f, e, { initialize: m, readOnly: t.readOnly ?? false, stored: n.stored }); h = r.sharedFile !== null && r.source === null; } if (!m) n?.(f); }); if (m && n) transaction(() => n(f)); if (!t.migration) admittedFiles.set(o, { identity: s, version: 1 }); return { database: f, path: i, created: c, needsMetadataUpgrade: h, transaction, run(n, r) { if (d) throw new Error("Client credential custody is closed."); if (t.readOnly && isClientCredentialMutation(n)) throw new Error("Client credential custody is read-only."); const run = () => { const t = performClientCredentialOperation(f, n, resolveStateDir(e)); r?.(); return t; }; return transaction(run); }, close: physicalClose, [Symbol.dispose]: physicalClose }; } catch (e) { admittedFiles.delete(o); if (physicalClose) physicalClose(); else { u?.close(); fs.closeSync(l.fd); retainedPaths.delete(o); } throw e; } } function clientCredentialOperationCreatesStore(e) { return [ "identity.create", "identity.repair", "token.replace", "socket.ensure" ].includes(e.kind); } function isClientCredentialMutation(e) { return ![ "identity.read", "token.read", "token.list", "socket.read" ].includes(e.kind); } function runClientCredentialOperation(e, t, n = {}) { try { var r = _usingCtx(); if (n.readOnly && isClientCredentialMutation(t)) throw new Error("Client credential custody is read-only."); let i; return r.u(openClientCredentialCustody(e, { createIfMissing: clientCredentialOperationCreatesStore(t), readOnly: n.readOnly }, (r) => { i = performClientCredentialOperation(r, t, resolveStateDir(e)); n.beforeCommit?.(); })) ? i : missingClientCredentialResult(e, t); } catch (e) { r.e = e; } finally { r.d(); } } /** A noncreating lookup can settle without opening any database. */ function missingClientCredentialResult(e, t) { assertMissingClientCredentialStoreReady(e); switch (t.kind) { case "identity.read": return { kind: "identity", identity: null }; case "token.read": return { kind: "token", token: null }; case "token.list": return { kind: "tokens", tokens: [], nextRole: null }; case "socket.read": return { kind: "socket", socket: null }; case "native.tokens.clear": return { kind: "cleared", count: 0 }; default: return { kind: "changed", changed: false }; } } //#endregion export { ClientCredentialMigrationRequiredError as a, writeClientCredentialReceipt as c, runClientCredentialOperation as i, isNativeClientCredentialBootstrap as l, isClientCredentialMutation as n, assertClientCredentialStoreReady as o, openClientCredentialCustody as r, readClientCredentialReceipt as s, isClientCredentialBusyError as t, readIndependentClientCredentialSource as u };