openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
402 lines (401 loc) • 18.2 kB
JavaScript
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { m as toStringifiedError } from "./error-coercion-hDrHOSGy.mjs";
import { a as normalizeWindowsPathForComparison } from "./path-guards-TIjxtj6H.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { Jn as string, Lt as boolean, Nt as array, Pn as number, Yt as discriminatedUnion, or as union, qn as strictObject, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { t as SQLITE_SIDECAR_SUFFIXES } from "./sqlite-files-rWisKj_V.mjs";
import { a as UpdateRunDriverSchema } from "./update-run-schema-tIwTkB6s.mjs";
import { a as normalizeArchiveRoot, c as resolvePortableArchivePathKey, i as normalizeArchivePath, r as isArchivePathWithin, t as buildBackupArchivePath } from "./backup-archive-path-policy-Cr8KWL_A.mjs";
import { m as list, v as Header } from "./esm-C2faEQS9.mjs";
import { t as BACKUP_MAX_DECOMPRESSION_RATIO } from "./backup-shared-BmR-itzA.mjs";
import path from "node:path";
import { isUtf8 } from "node:buffer";
//#region src/commands/backup-verify-manifest.ts
const recoveryPath = string().min(1).refine((e) => !e.includes("\0") && path.resolve(e) === e);
const recoveryDigest = string().regex(/^[a-f0-9]{64}$/u);
const recoveryEntry = discriminatedUnion("kind", [
strictObject({
kind: literal("file"),
sourcePath: recoveryPath,
archivePath: string().regex(/^payload\/\d+$/u),
size: number().int().nonnegative(),
sha256: recoveryDigest,
sqlite: boolean(),
mode: number().int().nonnegative()
}),
strictObject({
kind: literal("directory"),
sourcePath: recoveryPath,
mode: number().int().nonnegative()
}),
strictObject({
kind: literal("symlink"),
sourcePath: recoveryPath,
target: string().refine((e) => !e.includes("\0")),
contentPath: recoveryPath.optional()
}),
strictObject({
kind: literal("missing"),
sourcePath: recoveryPath,
sqlite: boolean(),
directory: boolean()
})
]);
const updateRecoveryManifestSchema = strictObject({
schemaVersion: union([literal(1), literal(2)]),
kind: literal("update-recovery"),
generation: discriminatedUnion("kind", [
strictObject({ kind: literal("baseline") }),
strictObject({
kind: literal("candidate"),
baselineSha256: recoveryDigest
}),
strictObject({
kind: literal("prepared"),
baselineSha256: recoveryDigest,
candidateSha256: recoveryDigest
})
]).optional(),
databases: array(discriminatedUnion("role", [strictObject({
path: recoveryPath,
role: literal("global")
}), strictObject({
path: recoveryPath,
role: literal("agent"),
agentId: string().min(1)
})])).optional(),
runId: string().regex(/^[a-zA-Z0-9_-]{1,128}$/u),
installRoot: recoveryPath,
stateDir: recoveryPath,
configPath: recoveryPath,
configPaths: array(recoveryPath).min(1).max(512),
creator: UpdateRunDriverSchema,
drivers: array(UpdateRunDriverSchema).max(32),
createdAt: string().datetime(),
roots: array(recoveryPath).min(1),
excludedRoots: array(recoveryPath),
protectedPaths: array(recoveryPath),
entries: array(recoveryEntry).max(1e6),
warnings: array(strictObject({
kind: literal("undeclared-migration-resources"),
pluginId: string().min(1),
message: string().min(1)
})).optional()
});
/** Update recovery binds every payload; ordinary archive manifests retain their existing contract. */
function parseUpdateRecoveryBackupManifest(e) {
const t = updateRecoveryManifestSchema.parse(JSON.parse(e));
if (t.schemaVersion === 1 && (t.generation || t.databases) || t.schemaVersion === 2 && (!t.generation || !t.databases)) throw new Error("Update recovery generation metadata does not match its format version.");
const n = /* @__PURE__ */ new Set();
let r;
for (const e of t.databases ?? []) {
if (n.has(e.path) || e.role === "global" && r !== void 0 || e.role === "agent" && normalizeAgentId(e.agentId) !== e.agentId) throw new Error(`Invalid update recovery database identity: ${e.path}`);
n.add(e.path);
if (e.role === "global") r = e.path;
}
const i = /* @__PURE__ */ new Map();
const a = /* @__PURE__ */ new Set();
const o = new Set(t.excludedRoots);
if (o.size !== t.excludedRoots.length || [
...t.roots,
...t.protectedPaths,
...t.configPaths
].some((e) => o.has(e))) throw new Error("Update recovery exclusions conflict with retained resource inventory.");
for (const e of t.entries) {
if (o.has(e.sourcePath)) throw new Error(`Excluded update recovery source has a retained entry: ${e.sourcePath}`);
if (e.kind === "missing" && e.sqlite && e.directory) throw new Error("Missing SQLite inventory cannot describe a directory.");
if (i.has(e.sourcePath) || !t.roots.some((t) => {
const n = path.relative(t, e.sourcePath);
return n === "" || !path.isAbsolute(n) && n !== ".." && !n.startsWith(`..${path.sep}`);
})) throw new Error(`Invalid update recovery source: ${e.sourcePath}`);
i.set(e.sourcePath, e);
if (e.kind === "file") {
if (a.has(e.archivePath)) throw new Error(`Duplicate update recovery payload: ${e.archivePath}`);
a.add(e.archivePath);
}
}
for (const e of t.databases ?? []) {
const t = i.get(e.path);
if (!t || !((t.kind === "file" || t.kind === "missing" && !t.directory) && t.sqlite)) throw new Error(`Update recovery database is missing its SQLite inventory: ${e.path}`);
}
if (t.roots.some((e) => !i.has(e))) throw new Error("Update recovery manifest is missing a root entry.");
if (!t.configPaths.includes(t.configPath) || new Set(t.configPaths).size !== t.configPaths.length) throw new Error("Update recovery manifest is missing its configuration inventory.");
for (const e of t.configPaths) {
const n = i.get(e);
const r = n?.kind === "symlink" && n.contentPath ? i.get(n.contentPath) : void 0;
if (!n || n.kind === "directory" || n.kind === "file" && n.sqlite || n.kind === "missing" && (n.directory || n.sqlite) || n.kind === "symlink" && (!n.contentPath || !t.configPaths.includes(n.contentPath) || !r || !((r.kind === "file" || r.kind === "missing" && !r.directory) && !r.sqlite))) throw new Error("Update recovery manifest is missing its configuration inventory.");
}
return t;
}
function backupManifestSizeError(e) {
const t = 1048576;
return e > t ? /* @__PURE__ */ new Error(`Backup manifest exceeds ${t} byte limit.`) : void 0;
}
/** Encode the bounded root manifest as the archive's final tar member. */
function encodeBackupManifest(e) {
const t = Buffer.from(JSON.stringify(e, null, 2) + "\n");
const n = backupManifestSizeError(t.length);
if (n) throw n;
const r = Buffer.alloc(512);
new Header({
path: e.archiveRoot + "/manifest.json",
type: "File",
mode: 420,
size: t.length
}).encode(r);
return Buffer.concat([
r,
t,
Buffer.alloc((512 - t.length % 512) % 512 + 1024)
]);
}
function parseBackupManifestSourcePath(e, t) {
if (typeof e !== "string" || e.includes("\0")) throw new Error(`Backup manifest ${t} has an invalid sourcePath.`);
const n = /^(?:[A-Za-z]:[\\/]|\\\\(?![?.]\\))/u.test(e);
const r = n ? path.win32.normalize(e) : path.posix.normalize(e);
if (!n && !e.startsWith("/") || r !== e) throw new Error(`Backup manifest ${t} sourcePath must be absolute and normalized.`);
return e;
}
function parseBackupManifestAgentRoots(e) {
if (e === void 0) return;
if (!Array.isArray(e)) throw new Error("Backup manifest agentRoots must be an array.");
const t = [];
const n = /* @__PURE__ */ new Set();
const r = /* @__PURE__ */ new Set();
for (const i of e) {
if (!isRecord(i) || Object.keys(i).length !== 2 || !Object.hasOwn(i, "agentId") || !Object.hasOwn(i, "sourcePath")) throw new Error("Backup manifest agent root must contain only agentId and sourcePath.");
const { agentId: e, sourcePath: a } = i;
if (typeof e !== "string" || !e || normalizeAgentId(e) !== e) throw new Error("Backup manifest agent root has an invalid or noncanonical agentId.");
const o = parseBackupManifestSourcePath(a, "agent root");
const s = /^(?:[A-Za-z]:[\\/]|\\\\(?![?.]\\))/u.test(o) ? normalizeWindowsPathForComparison(o) : o;
if (n.has(e) || r.has(s)) throw new Error("Backup manifest contains duplicate agent root ownership.");
n.add(e);
r.add(s);
t.push({
agentId: e,
sourcePath: o
});
}
return t;
}
function parseBackupManifestSqliteSnapshots(e) {
if (e === void 0) return;
if (!Array.isArray(e)) throw new Error("Backup manifest sqliteSnapshots must be an array.");
let t = false;
const n = /* @__PURE__ */ new Set();
return e.map((e) => {
if (!isRecord(e) || e.role !== "global" && e.role !== "agent" || Object.keys(e).some((t) => t !== "sourcePath" && t !== "role" && !(e.role === "agent" && t === "agentId"))) throw new Error("Backup manifest contains an invalid SQLite snapshot owner.");
const r = parseBackupManifestSourcePath(e.sourcePath, "SQLite snapshot");
let i;
if (e.role === "global") i = { role: "global" };
else {
const t = e.agentId;
if (typeof t !== "string" || !t || normalizeAgentId(t) !== t) throw new Error("Backup manifest SQLite snapshot has an invalid agentId.");
i = {
role: "agent",
agentId: t
};
}
const a = r.replaceAll("\\", "/").normalize("NFC").toLowerCase();
if (i.role === "global" && t || n.has(a)) throw new Error("Backup manifest contains duplicate SQLite snapshot ownership.");
t ||= i.role === "global";
n.add(a);
return {
sourcePath: r,
...i
};
});
}
function parseBackupManifestPostgresSnapshots(e) {
if (e === void 0) return;
if (!Array.isArray(e)) throw new Error("Backup manifest postgresSnapshots must be an array.");
const t = /* @__PURE__ */ new Set();
return e.map((e) => {
if (!isRecord(e) || Object.keys(e).length !== 2 || typeof e.archivePath !== "string") throw new Error("Backup manifest contains an invalid PostgreSQL snapshot.");
const n = recoveryDigest.safeParse(e.manifestSha256);
if (!n.success) throw new Error("Backup manifest contains an invalid PostgreSQL snapshot hash.");
const r = normalizeArchivePath(e.archivePath, "PostgreSQL capsule path");
if (r !== e.archivePath || !r.endsWith(".postgres")) throw new Error("Backup manifest PostgreSQL capsule path must be normalized and end in .postgres.");
const i = r.normalize("NFC").toLowerCase();
if (t.has(i)) throw new Error("Backup manifest contains duplicate PostgreSQL snapshot paths.");
t.add(i);
return {
archivePath: r,
manifestSha256: n.data
};
});
}
function readRequiredManifestString(e, t, n = "Backup manifest") {
const r = readNonBlankString(e[t]);
if (r === void 0) throw new Error(`${n} is missing ${t}.`);
return r;
}
function parseBackupManifest(e) {
let t;
try {
t = JSON.parse(e);
} catch (e) {
throw new Error("Backup manifest is not valid JSON.", { cause: e });
}
if (!isRecord(t)) throw new Error("Backup manifest must be an object.");
if (t.schemaVersion !== 1) throw new Error(`Unsupported backup manifest schemaVersion: ${String(t.schemaVersion)}`);
const n = readRequiredManifestString(t, "archiveRoot");
const r = readRequiredManifestString(t, "createdAt");
if (!Array.isArray(t.assets)) throw new Error("Backup manifest is missing assets.");
const i = t.assets.map((e) => {
if (!isRecord(e)) throw new Error("Backup manifest contains a non-object asset.");
return {
kind: readRequiredManifestString(e, "kind", "Backup manifest asset"),
sourcePath: readRequiredManifestString(e, "sourcePath", "Backup manifest asset"),
archivePath: readRequiredManifestString(e, "archivePath", "Backup manifest asset")
};
});
const a = [];
if (t.externalSymbolicLinks !== void 0) {
if (!Array.isArray(t.externalSymbolicLinks)) throw new Error("Backup manifest externalSymbolicLinks must be an array.");
for (const e of t.externalSymbolicLinks) {
if (!isRecord(e) || typeof e.entryPath !== "string" || typeof e.linkpath !== "string") throw new Error("Backup manifest contains an invalid external symbolic link.");
a.push({
entryPath: e.entryPath,
linkpath: e.linkpath
});
}
}
return {
schemaVersion: 1,
archiveRoot: n,
createdAt: r,
runtimeVersion: readNonBlankString(t.runtimeVersion) ?? "unknown",
platform: typeof t.platform === "string" ? t.platform : "unknown",
nodeVersion: typeof t.nodeVersion === "string" ? t.nodeVersion : "unknown",
paths: isRecord(t.paths) ? {
...t.paths.stateDir === void 0 ? {} : { stateDir: parseBackupManifestSourcePath(t.paths.stateDir, "state directory") },
...t.paths.configPath === void 0 ? {} : { configPath: parseBackupManifestSourcePath(t.paths.configPath, "configuration") },
...t.paths.configSourcePath === void 0 ? {} : { configSourcePath: parseBackupManifestSourcePath(t.paths.configSourcePath, "configuration source") },
...t.paths.sharedDatabaseSourcePath === void 0 ? {} : { sharedDatabaseSourcePath: parseBackupManifestSourcePath(t.paths.sharedDatabaseSourcePath, "shared database source") },
agentRoots: parseBackupManifestAgentRoots(t.paths.agentRoots)
} : void 0,
assets: i,
sqliteSnapshots: parseBackupManifestSqliteSnapshots(t.sqliteSnapshots),
postgresSnapshots: parseBackupManifestPostgresSnapshots(t.postgresSnapshots),
...t.externalSymbolicLinks === void 0 ? {} : { externalSymbolicLinks: a }
};
}
function isRootBackupManifestEntry(e) {
const t = e.split("/");
return t.length === 2 && t[0] !== "" && t[1] === "manifest.json";
}
function verifyBackupManifestEntries(e, t) {
const n = normalizeArchiveRoot(e.archiveRoot);
const r = path.posix.join(n, "manifest.json");
const i = [...t];
if (!t.has(r)) throw new Error(`Archive is missing manifest entry: ${r}`);
for (const e of i) if (!isArchivePathWithin(e, n)) throw new Error(`Archive entry is outside the declared archive root: ${e}`);
const a = path.posix.join(n, "payload");
for (const n of e.assets) {
const e = normalizeArchivePath(n.archivePath, "Backup manifest asset path");
if (!isArchivePathWithin(e, a)) throw new Error(`Manifest asset path is outside payload root: ${n.archivePath}`);
if (!t.has(e) && !i.some((t) => isArchivePathWithin(t, e))) throw new Error(`Archive is missing payload for manifest asset: ${e}`);
}
}
/** The capture-time inventory, never today's filesystem, defines required database coverage. */
function verifyBackupSqliteCoverage(e, t, n) {
for (const r of [...e.sqliteSnapshots ?? [], ...t]) {
const t = buildBackupArchivePath(e.archiveRoot, r.sourcePath);
if (!n.some((e) => e.archivePath === t && e.role === r.role && (r.role === "global" || e.role === "agent" && e.agentId === r.agentId))) throw new Error(`Backup lacks verified SQLite database coverage for ${r.sourcePath}.`);
}
}
async function listBackupArchiveEntries(e) {
const t = [];
let n;
let r;
let i;
await list({
file: e,
gzip: true,
maxDecompressionRatio: BACKUP_MAX_DECOMPRESSION_RATIO,
onwarn: (e, t) => {
if (e === "TAR_BAD_ARCHIVE" || e === "TAR_ENTRY_INVALID") n ??= formatErrorMessage(t);
},
onReadEntry: (e) => {
if (r) return;
let n;
try {
n = normalizeArchivePath(e.path, "Archive entry");
} catch (e) {
r ??= toStringifiedError(e);
return;
}
t.push({
raw: e.path,
normalized: n,
...e.linkpath ? { linkpath: e.linkpath } : {},
...Number.isSafeInteger(e.size) && e.size >= 0 ? { size: e.size } : {},
...e.type ? { type: e.type } : {}
});
if (!i && isRootBackupManifestEntry(n)) i = readBackupManifestEntry(e);
}
});
return {
entries: t,
invalidReason: n,
pathError: r,
manifestContent: i
};
}
/** Collect during listing; defer content errors until the complete entry inventory is checked. */
async function readBackupManifestEntry(e) {
const t = backupManifestSizeError(e.size);
if (t) return t;
try {
const t = await e.concat();
return isUtf8(t) ? t.toString("utf8") : /* @__PURE__ */ new Error("Backup manifest must be valid UTF-8.");
} catch (e) {
return toStringifiedError(e);
}
}
function isRegularArchiveFile(e) {
return e === "File" || e === "OldFile" || e === "ContiguousFile";
}
function resolvePostgresRestoreEntries(e, t) {
const n = t.postgresSnapshots?.map(({ archivePath: e, manifestSha256: t }) => ({
directoryPath: e,
anchorPath: e.slice(0, -9),
manifestSha256: t
})) ?? (t.sqliteSnapshots ?? []).flatMap(({ sourcePath: n }) => {
const r = buildBackupArchivePath(t.archiveRoot, n);
const i = `${r}.postgres`;
return e.some((e) => isArchivePathWithin(e.normalized, i)) ? [{
anchorPath: r,
directoryPath: i
}] : [];
});
const r = new Map(e.map((e) => [e.normalized, e]));
const i = new Set(e.map((e) => resolvePortableArchivePathKey(e.normalized)));
const a = path.posix.join(normalizeArchiveRoot(t.archiveRoot), "payload");
for (const { directoryPath: e, anchorPath: t } of n) {
if (!isArchivePathWithin(e, a)) throw new Error(`PostgreSQL capsule path is outside payload root: ${e}`);
for (const n of [
t,
`${e}/anchor.sqlite`,
`${e}/database.sqlite`
]) for (const e of SQLITE_SIDECAR_SUFFIXES) if (i.has(resolvePortableArchivePathKey(`${n}${e}`))) throw new Error(`PostgreSQL export has unexpected SQLite sidecar: ${n}${e}`);
for (const n of [t, ...[
"manifest.json",
"anchor.sqlite",
"database.sqlite"
].map((t) => path.posix.join(e, t))]) {
const e = r.get(n);
if (!e || !isRegularArchiveFile(e.type)) throw new Error(`PostgreSQL backup is missing a regular matched artifact: ${n}`);
}
}
const o = new Set(n.map(({ directoryPath: e }) => e));
return {
captures: n,
warnings: t.postgresSnapshots === void 0 && e.some((e) => e.normalized.endsWith(".postgres/manifest.json") && !o.has(path.posix.dirname(e.normalized))) ? ["This legacy archive has no PostgreSQL capsule ownership inventory. Unlisted exports are preserved as files, not imported. Re-run backup with this version on the source installation to recover plugin PostgreSQL stores automatically."] : []
};
}
//#endregion
export { parseBackupManifest as a, verifyBackupManifestEntries as c, listBackupArchiveEntries as i, verifyBackupSqliteCoverage as l, isRegularArchiveFile as n, parseUpdateRecoveryBackupManifest as o, isRootBackupManifestEntry as r, resolvePostgresRestoreEntries as s, encodeBackupManifest as t };