UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

408 lines (407 loc) • 19.1 kB
import { t as expandHomePrefix } from "./home-dir-EKmgmdPG.mjs"; import { o as writeRuntimeJson } from "./runtime-B-SLYP-m.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as openNodeSqliteDatabase } from "./node-sqlite-CU4puofF.mjs"; import { c as sha256File } from "./directory-durability-DlnWwNmv.mjs"; import { n as formatDiskSpaceBytes, r as tryReadDiskSpace } from "./disk-space-B5Tl0OOd.mjs"; import { t as SQLITE_SIDECAR_SUFFIXES } from "./sqlite-files-rWisKj_V.mjs"; import { r as assertSqliteIntegrity } from "./sqlite-integrity-CCmEgO_m.mjs"; import { n as readEngineAnchor } from "./open-jth9KEHn.mjs"; import { n as readOpenClawAgentDatabaseRegistryRows } from "./openclaw-agent-db-registry.read-DpiFiW8m.mjs"; import { a as normalizeArchiveRoot, c as resolvePortableArchivePathKey, i as normalizeArchivePath, n as findPortableArchiveEntryPathCollision, r as isArchivePathWithin, s as recordArchiveSymbolicLink, t as buildBackupArchivePath } from "./backup-archive-path-policy-Cr8KWL_A.mjs"; import { n as assertOpenClawAgentDatabaseOwner } from "./openclaw-agent-db-maintenance-BjsfVelp.mjs"; import { t as loadSqliteVecExtension } from "./sqlite-vec-2t4h9sP9.mjs"; import { r as extract } from "./esm-C2faEQS9.mjs"; import { c as resolveBackupArchivePath, t as BACKUP_MAX_DECOMPRESSION_RATIO } from "./backup-shared-BmR-itzA.mjs"; import { a as parseBackupManifest, c as verifyBackupManifestEntries, i as listBackupArchiveEntries, l as verifyBackupSqliteCoverage, n as isRegularArchiveFile, r as isRootBackupManifestEntry, s as resolvePostgresRestoreEntries } from "./backup-verify-manifest-CVAAAU_5.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import os from "node:os"; //#region src/commands/backup-recovery-config.ts function resolveBackupRecoveryConfig(e, t, n) { const r = e.paths?.configPath ?? e.assets.find((e) => e.kind === "config")?.sourcePath; if (!r) return {}; const i = buildBackupArchivePath(e.archiveRoot, r); let a = e.paths?.configSourcePath ?? r; if (!e.paths?.configSourcePath) { const t = n.find(({ entryPath: e }) => e === i); if (t) { const n = e.platform === "win32" ? path.win32 : path.posix; a = n.resolve(n.dirname(r), t.linkpath); } } const o = buildBackupArchivePath(e.archiveRoot, a); return { recoveryConfigContextPath: i, recoveryConfigPath: t.some((e) => e.normalized === o && isRegularArchiveFile(e.type)) ? o : void 0 }; } //#endregion //#region src/commands/backup-verify.ts const MAX_DATABASE_SNAPSHOT_EXTRACT_BYTES = 68719476736; const DATABASE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES = 268435456; function formatResult(e) { return [ terminalText`Backup archive OK: ${e.archivePath}`, terminalText`Archive root: ${e.archiveRoot}`, terminalText`Created at: ${e.createdAt}`, terminalText`Runtime version: ${e.runtimeVersion}`, terminalText`Assets verified: ${e.assetCount}`, terminalText`Archive entries scanned: ${e.entryCount}`, terminalText`Symbolic links checked: ${e.symlinkCount}`, e.sqliteInventoryVerified ? "SQLite database inventory verified." : "SQLite database coverage unknown: this legacy archive has no database inventory.", ...(e.warnings ?? []).map((e) => terminalText`${e}`) ].join("\n"); } function resolveExtractionBytes(e, t = false) { const n = t ? "SQLite snapshot" : "Archive"; let r = 0; for (const i of e) { if (!t && !isRegularArchiveFile(i.type)) continue; if (!Number.isSafeInteger(i.size) || (i.size ?? -1) < 0) throw new Error(t ? `SQLite snapshot has an invalid archive size: ${i.normalized}` : `Archive regular file has an invalid size: ${i.normalized}`); if (t && i.size === 0) throw new Error(`SQLite snapshot is empty: ${i.normalized}`); r += i.size ?? 0; if (!Number.isSafeInteger(r)) throw new Error(`${n} extraction size exceeds the supported integer range.`); } return r; } function assertCanonicalStateAssetRoot(e) { const t = e.assets.filter((e) => e.kind === "state"); const n = t[0]; if (!n) return; if (t.length !== 1) throw new Error(`Backup manifest must contain at most one state asset; found ${t.length}.`); if (normalizeArchivePath(n.archivePath, "Backup manifest state asset path") !== buildBackupArchivePath(normalizeArchiveRoot(e.archiveRoot), n.sourcePath)) throw new Error("Backup manifest state asset archivePath does not match its sourcePath."); } function listSqliteSnapshotEntries(e, t, n) { const r = new Map(t.map((e) => [resolvePortableArchivePathKey(e.archivePath), e])); const i = []; const a = new Map(e.map((e) => [e.normalized, e])); for (const t of e) { const e = resolvePortableArchivePathKey(t.normalized); for (const n of SQLITE_SIDECAR_SUFFIXES) if (e.endsWith(n) && r.has(e.slice(0, -n.length))) throw new Error(`Backup contains a SQLite snapshot sidecar: ${t.normalized}`); const o = r.get(e); if (!o) continue; if (t.normalized !== o.archivePath) throw new Error(`Backup contains a SQLite path with incorrect letter casing: ${t.normalized}`); if (!isRegularArchiveFile(t.type)) throw new Error(`SQLite snapshot must be a regular archive file: ${t.normalized}`); const s = `${t.normalized}.postgres`; const c = n.has(t.normalized) ? a.get(`${s}/database.sqlite`) : t; if (!c || !isRegularArchiveFile(c.type)) throw new Error(`PostgreSQL snapshot is missing its portable database: ${s}`); i.push({ ...c, ...o }); } return i; } function readArchivedAgentDatabaseOwners(e, t, n) { const r = readOpenClawAgentDatabaseRegistryRows(e, n); const i = t.platform === "win32" ? path.win32 : path.posix; return r.map((e) => ({ archivePath: buildBackupArchivePath(t.archiveRoot, i.isAbsolute(e.path) ? e.path : i.join(n, e.path)), role: "agent", agentId: e.agent_id })); } function assertSnapshotExtractionBudget(e) { const t = e.postgres ? "PostgreSQL artifacts" : "SQLite snapshots"; const n = resolveExtractionBytes(e.entries, !e.postgres); if (n > MAX_DATABASE_SNAPSHOT_EXTRACT_BYTES) throw new Error(`${t} require ${formatDiskSpaceBytes(n)} of extraction space; the verification limit is ${formatDiskSpaceBytes(MAX_DATABASE_SNAPSHOT_EXTRACT_BYTES)}.`); const r = n - (e.extractedBytes ?? 0); const i = tryReadDiskSpace(e.tempRoot); if (i && r + DATABASE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES > i.availableBytes) throw new Error(`${t} require ${formatDiskSpaceBytes(r)} of extraction space, but only ${formatDiskSpaceBytes(i.availableBytes)} is available near ${e.tempRoot}; verification reserves ${formatDiskSpaceBytes(DATABASE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES)} for the host.`); } function assertExpectedSqliteRole(e, t, n) { if (e.prepare("SELECT type FROM sqlite_schema WHERE name = 'schema_meta'").get()?.type !== "table") throw new Error(`SQLite snapshot ${t} is missing the expected schema_meta table.`); const r = e.prepare("SELECT role FROM schema_meta WHERE meta_key = 'primary'").get(); const i = typeof r?.role === "string" ? r.role : "missing"; if (i !== n) throw new Error(`SQLite snapshot ${t} has role ${i}; expected ${n}.`); } async function assertSqliteSnapshotFileShape(e, t, n) { const r = Buffer.alloc(100); const i = await fs.open(e, "r"); try { const { bytesRead: e } = await i.read(r, 0, r.byteLength, 0); if (e !== r.byteLength || r.subarray(0, 16).toString("utf8") !== "SQLite format 3\0") throw new Error(`SQLite snapshot ${t} has an invalid database header.`); } finally { await i.close(); } const a = r.readUInt16BE(16); const o = a === 1 ? 65536 : a; if (!(o >= 512 && o <= 65536 && (o & o - 1) === 0) || n % o !== 0) throw new Error(`SQLite snapshot ${t} has an invalid page layout.`); const s = r.readUInt32BE(24); const c = r.readUInt32BE(28); const l = r.readUInt32BE(92); if (c !== 0 && s === l && c !== n / o) throw new Error(`SQLite snapshot ${t} has an invalid page layout.`); } async function extractDatabaseArtifacts(e, t, n) { const r = new Map(n.map((e) => [e.raw, e])); await extract({ file: e, gzip: true, maxDecompressionRatio: BACKUP_MAX_DECOMPRESSION_RATIO, cwd: t, strict: true, preserveOwner: false, filter: (e, t) => { const n = r.get(e); if (!n) return false; if (t.size !== n.size) throw new Error(`Database artifact size changed during verification: ${e}`); return true; } }); for (const e of n) { const n = await fs.lstat(path.join(t, ...e.normalized.split("/"))); if (!n.isFile() || n.size !== e.size) throw new Error(`Extracted database artifact does not match archive: ${e.normalized}`); } } async function verifyPostgresSnapshots(e, t, n) { if (!n.length) return; const r = new Set(n.flatMap(({ directoryPath: e, anchorPath: t }) => [t, ...[ "manifest.json", "anchor.sqlite", "database.sqlite", ".pending" ].map((t) => `${e}/${t}`)])); const i = t.filter((e) => r.has(e.normalized)); const a = os.tmpdir(); assertSnapshotExtractionBudget({ entries: i, tempRoot: a, postgres: true }); const o = await fs.mkdtemp(path.join(a, "openclaw-backup-verify-postgres-")); try { await extractDatabaseArtifacts(e, o, i); const { readBackupEngineImage: t, verifyMatchedPostgresBackup: r } = await import("./database-backup-ZFHLPLfI.mjs"); for (const { directoryPath: e, anchorPath: i, manifestSha256: a } of n) { const n = path.join(o, e, "manifest.json"); if (a && (await sha256File(n)).digest !== a) throw new Error(`PostgreSQL capsule does not match its capture inventory: ${e}`); const s = t(path.join(o, i), i); if (s.engine !== "postgres") throw new Error(`PostgreSQL backup has an invalid outer anchor: ${i}`); await r(path.join(o, e), "user-backup", s); } } finally { await fs.rm(o, { recursive: true, force: true }); } } async function verifySqliteSnapshots(e) { const t = []; const n = e.manifest.paths?.stateDir ?? e.manifest.assets.find((e) => e.kind === "state")?.sourcePath; if (!n) return t; const r = buildBackupArchivePath(e.manifest.archiveRoot, n); const i = resolvePortableArchivePathKey(r); for (const t of e.entries) if (isArchivePathWithin(resolvePortableArchivePathKey(t.normalized), i) && !isArchivePathWithin(t.normalized, r)) throw new Error(`Backup contains a case-mangled state asset path: ${t.normalized}`); const a = [{ archivePath: path.posix.join(r, "state/openclaw.sqlite"), role: "global" }, ...(e.manifest.sqliteSnapshots ?? []).filter((e) => e.role === "agent").map(({ sourcePath: t, role: n, agentId: r }) => ({ role: n, agentId: r, archivePath: buildBackupArchivePath(e.manifest.archiveRoot, t) }))]; const o = listSqliteSnapshotEntries(e.entries, a, e.postgresAnchors); if (o.length === 0) return t; assertCanonicalStateAssetRoot(e.manifest); const s = os.tmpdir(); assertSnapshotExtractionBudget({ entries: o, tempRoot: s }); const c = await fs.mkdtemp(path.join(s, "openclaw-backup-verify-sqlite-")); try { const r = [o]; const i = []; for (const o of r) { const l = resolveExtractionBytes(i, true); i.push(...o); if (l > 0) assertSnapshotExtractionBudget({ entries: i, tempRoot: s, extractedBytes: l }); await extractDatabaseArtifacts(e.archivePath, c, o); for (const s of o) { const o = path.join(c, ...s.normalized.split("/")); let l; try { await assertSqliteSnapshotFileShape(o, s.normalized, s.size); l = openNodeSqliteDatabase(o, { allowExtension: true, readOnly: true }); if (readEngineAnchor(l)) throw new Error("PostgreSQL anchor has no owned matched capsule. Re-run backup with this version on the source installation."); l.exec("PRAGMA query_only = ON; PRAGMA trusted_schema = OFF;"); await loadSqliteVecExtension({ db: l }); assertSqliteIntegrity(l, s.normalized); if (s.role === "agent") assertOpenClawAgentDatabaseOwner(l, { agentId: s.agentId, pathname: s.normalized }); else assertExpectedSqliteRole(l, s.normalized, s.role); t.push({ ...s }); if (s.role === "global") { const t = readArchivedAgentDatabaseOwners(l, e.manifest, n); const o = new Map(a.map((e) => [resolvePortableArchivePathKey(e.archivePath), e])); for (const e of t) { const t = resolvePortableArchivePathKey(e.archivePath); const n = o.get(t); if (n && (n.role !== "agent" || e.role !== "agent" || n.agentId !== e.agentId || n.archivePath !== e.archivePath)) throw new Error(`SQLite snapshot has conflicting registered owners: ${e.archivePath}`); o.set(t, e); } const s = listSqliteSnapshotEntries(e.entries, t, e.postgresAnchors).filter((e) => !i.some((t) => t.raw === e.raw)); if (s.length > 0) r.push(s); } } catch (e) { const t = e instanceof Error ? e.message : String(e); throw new Error(`Backup SQLite snapshot failed verification: ${s.normalized}. ${t}`, { cause: e }); } finally { l?.close(); } } } } finally { await fs.rm(c, { recursive: true, force: true }); } return t; } async function verifyResolvedBackupArchive(e, t) { let n; try { n = await fs.stat(e); } catch (e) { if (hasErrnoCode(e, "ENOENT")) throw new Error("Archive does not exist. Check the path and run `openclaw backup verify <archive>` again.", { cause: e }); throw new Error(`Archive could not be inspected. ${formatErrorMessage(e)} Check the path and file permissions, then try again.`, { cause: e }); } if (!n.isFile()) throw new Error("Archive must be a regular file. Choose a backup archive created by `openclaw backup create` and try again."); const r = await listBackupArchiveEntries(e).catch((e) => { throw new Error(`Archive could not be read or parsed. ${formatErrorMessage(e)} Check the file permissions and archive integrity, then try again.`); }); if (r.invalidReason) throw new Error(`Archive is not a valid OpenClaw backup. ${r.invalidReason.replace(/[.!?]*$/u, ".")} Choose another archive or create a new one with \`openclaw backup create\`.`); if (r.pathError) throw r.pathError; const i = r.entries; const a = i.filter((e) => e.type === "SymbolicLink").map((e) => ({ entryPath: e.raw, linkpath: e.linkpath })); const o = /* @__PURE__ */ new Map(); let s; for (const e of i) { if (o.has(e.normalized)) s ??= e.normalized; o.set(e.normalized, e); } const c = new Set(o.keys()); const l = i.filter((e) => isRootBackupManifestEntry(e.normalized)); if (l.length !== 1) throw new Error(`Expected exactly one backup manifest entry, found ${l.length}.`); if (s) throw new Error(`Archive contains duplicate entry path: ${s}`); const u = findPortableArchiveEntryPathCollision(i); if (u) throw new Error(`Archive contains a portable path collision: ${u.first} and ${u.second}`); if (!r.manifestContent) throw new Error("Backup archive manifest entry could not be resolved."); const d = await r.manifestContent; if (d instanceof Error) throw d; const f = parseBackupManifest(d); verifyBackupManifestEntries(f, c); const p = normalizeArchiveRoot(f.archiveRoot); const m = /* @__PURE__ */ new Map(); for (const e of i) if (e.type === "Link") { const t = normalizeArchivePath(e.linkpath ?? "", `Archive hardlink target for ${e.raw}`); const n = isArchivePathWithin(t, p) ? t : path.posix.join(p, t); let r = o.get(n)?.raw; if (!r && !isArchivePathWithin(t, p)) { const n = /* @__PURE__ */ new Set(); for (let r = path.posix.dirname(e.normalized); isArchivePathWithin(r, p); r = path.posix.dirname(r)) { const e = o.get(path.posix.join(r, t)); if (e && isRegularArchiveFile(e.type)) n.add(e.raw); if (r === p) break; } if (n.size > 1) throw new Error(`Archive hardlink target is ambiguous: ${e.raw} -> ${t}`); r = n.values().next().value; } if (!r) throw new Error(`Archive hardlink target is missing from archive entries: ${e.raw} -> ${n}`); m.set(e.raw, r); } const h = []; const g = []; const _ = new Set(a.map(({ entryPath: e }) => resolvePortableArchivePathKey(normalizeArchivePath(e, "Archive symbolic link path")))); for (const e of i) for (let t = path.posix.dirname(e.normalized); t !== "."; t = path.posix.dirname(t)) if (_.has(resolvePortableArchivePathKey(t))) throw new Error(`Archive entry is beneath a symbolic link: ${e.raw}`); const v = f.assets.find((e) => e.kind === "state") ?? (f.paths?.stateDir ? { sourcePath: f.paths.stateDir, archivePath: buildBackupArchivePath(f.archiveRoot, f.paths.stateDir) } : void 0); for (const e of a) { const { external: t, ...n } = recordArchiveSymbolicLink({ ...e, archiveRoot: f.archiveRoot, platform: f.platform, state: v, hasExternalLinkReport: f.externalSymbolicLinks !== void 0, assets: f.assets }); h.push(n); if (t) g.push(n); } const y = new Map((f.externalSymbolicLinks ?? []).map(({ entryPath: e, linkpath: t }) => [e, t])); if (f.externalSymbolicLinks !== void 0 && (y.size !== g.length || g.some(({ entryPath: e, linkpath: t }) => y.get(e) !== t))) throw new Error("Backup manifest external symbolic links do not match archive entries."); const { captures: b, warnings: x } = resolvePostgresRestoreEntries(i, f); await verifyPostgresSnapshots(e, i, b); const S = await verifySqliteSnapshots({ archivePath: e, entries: i, manifest: f, postgresAnchors: new Set(b.map(({ anchorPath: e }) => e)) }); verifyBackupSqliteCoverage(f, t, S); return { result: { ok: true, archivePath: e, archiveRoot: f.archiveRoot, createdAt: f.createdAt, runtimeVersion: f.runtimeVersion, assetCount: f.assets.length, entryCount: i.length, symlinkCount: a.length, sqliteInventoryVerified: f.sqliteSnapshots !== void 0, ...x.length ? { warnings: x } : {}, ...g.length ? { externalSymbolicLinks: g } : {} }, ...resolveBackupRecoveryConfig(f, i, h), manifest: f, hardlinkTargets: m, symbolicLinks: h, regularFileExtractionBytes: resolveExtractionBytes(i), databaseRestoreCandidates: b }; } /** Verify an archive and prepare the exact hardlink targets needed by extraction. */ async function prepareBackupArchive(e, t = []) { let n = resolveBackupArchivePath(e, "<archive>"); if (process.platform !== "win32") { const t = expandHomePrefix(e); if (t.split("/").includes("..")) n = path.isAbsolute(t) ? t : process.cwd() + "/" + t; } return await verifyResolvedBackupArchive(n, t).catch((e) => { const t = e instanceof Error ? e.message : formatErrorMessage(e); throw new Error(`Backup archive verification failed: ${n}. ${t}`); }); } /** Verify a backup archive without exposing extraction metadata in CLI output. */ async function verifyBackupArchive(e, t = []) { return (await prepareBackupArchive(e, t)).result; } /** Verify a backup archive, including snapshot shape and canonical SQLite integrity checks. */ async function backupVerifyCommand(e, t) { const n = await verifyBackupArchive(t.archive); if (t.json) writeRuntimeJson(e, n); else e.log(formatResult(n)); return n; } //#endregion export { prepareBackupArchive as n, verifyBackupArchive as r, backupVerifyCommand as t };