openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
339 lines (338 loc) • 13.4 kB
JavaScript
import { p as isRecord } from "./utils-BclMknzT.mjs";
import { B as normalizeOptionalString } from "./path-guards-quCEQx1i.mjs";
import { n as readResponseWithLimit, t as cancelUnreadResponseBody } from "./http-body-Ce79vxBR.mjs";
import { t as formatErrorMessage } from "./errors-hqLS1E8Y.mjs";
import { t as sha256Hex } from "./node-crypto-CWAQhBWK.mjs";
import { _ as MANIFEST_KEY, c as isOfficialExternalPluginCatalogFeed, d as parseOfficialExternalPluginCatalogTimestamp, f as resolveHostedCatalogFeedSource, g as shouldRequireManifestInstallSourceRef, i as filterOfficialExternalPluginCatalogEntriesBySourceRefs, l as isOfficialExternalPluginCatalogRollback, n as HostedCatalogSignedFeedMonotonicityError, r as dedupeOfficialExternalPluginCatalogEntries, u as parseOfficialExternalPluginCatalogEntries } from "./official-external-plugin-catalog-source-CkTuOl59.mjs";
import { r as listOfficialExternalPluginCatalogEntries } from "./official-external-plugin-catalog-Bv-7q5p5.mjs";
//#region src/plugins/official-external-plugin-catalog-hosted.ts
const DEFAULT_HOSTED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_TIMEOUT_MS = 5e3;
const DEFAULT_HOSTED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_MAX_BYTES = 1048576;
const DEFAULT_HOSTED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_CHUNK_TIMEOUT_MS = 5e3;
const DSSE_ENVELOPE_MEDIA_TYPE = "application/vnd.dsse+json";
var HostedCatalogFeedTimestampError = class extends Error {
constructor(e, t) {
super(e);
this.sequence = t;
}
};
var HostedCatalogSnapshotWriteError = class extends Error {
constructor(e) {
super("hosted catalog snapshot write failed");
this.name = "HostedCatalogSnapshotWriteError";
this.originalError = e;
}
};
function parseHostedCatalogContentLength(e) {
const t = DEFAULT_HOSTED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_MAX_BYTES;
const n = normalizeOptionalString(e);
if (!n) return;
if (!/^\d+$/.test(n)) throw new Error("hosted catalog feed has invalid content-length");
const r = Number(n);
if (!Number.isSafeInteger(r) || r > t) throw new Error(`hosted catalog feed exceeds ${t} bytes`);
}
async function readHostedCatalogResponseText(e) {
parseHostedCatalogContentLength(e.headers.get("content-length"));
if (!e.body || typeof e.body.getReader !== "function") throw new Error("hosted catalog feed streaming response body unavailable");
const t = await readResponseWithLimit(e, DEFAULT_HOSTED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_MAX_BYTES, {
chunkTimeoutMs: DEFAULT_HOSTED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_CHUNK_TIMEOUT_MS,
onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`hosted catalog feed exceeds ${e} bytes`),
onIdleTimeout: ({ chunkTimeoutMs: e }) => /* @__PURE__ */ new Error(`hosted catalog feed read timed out after ${e}ms`)
});
return new TextDecoder("utf-8", { fatal: true }).decode(t);
}
function bundledFallbackResult(e, t) {
return {
source: "bundled-fallback",
entries: listOfficialExternalPluginCatalogEntries(),
error: formatErrorMessage(e),
...t ? { metadata: t } : {}
};
}
async function parseHostedCatalogFeedBody(e) {
const t = JSON.parse(e.body);
if (e.verification?.mode === "signed") {
const { verifyOfficialExternalPluginCatalogSignedEnvelope: n } = await import("./official-external-plugin-catalog-envelope-Dos_jfCz.mjs");
const r = e.verification.threshold ?? 1;
const i = n(t, {
trustedKeys: e.verification.keys,
threshold: r,
...e.allowLegacyBetaEnvelope ? { allowLegacyBetaEnvelope: true } : {}
});
if (!i.ok) {
const e = i.error === "invalid-payload" && "authenticatedPayload" in i ? readOfficialExternalPluginCatalogInvalidTimestampSequence(i.authenticatedPayload) : void 0;
if (e !== void 0) throw new HostedCatalogFeedTimestampError(i.message, e);
throw new Error(i.message);
}
if (e.expectedFeedId && i.feed.id !== e.expectedFeedId) throw new Error(`hosted catalog feed id "${i.feed.id}" did not match expected "${e.expectedFeedId}"`);
const a = Date.parse(i.feed.generatedAt.trim());
const o = normalizeOptionalString(i.feed.expiresAt);
let s;
if (!o) {
if (e.allowMissingExpiry !== true) throw new Error("hosted catalog signed feed requires a valid expiresAt value");
s = true;
} else {
const t = parseOfficialExternalPluginCatalogTimestamp(o);
if (t === void 0) throw new Error("hosted catalog signed feed requires a valid expiresAt value");
if (t <= a) throw new Error("hosted catalog signed feed expiresAt must be later than generatedAt");
s = t <= e.now.getTime();
}
if (s && e.allowExpired !== true) throw new Error(o ? `hosted catalog signed feed expired at ${o}` : "hosted catalog signed feed has no expiresAt");
return {
feed: enforceHostedCatalogFeedInstallAuthority(i.feed),
trust: {
mode: "signed",
signedBy: i.signedBy,
signatureCount: i.signatureCount ?? 1,
threshold: r,
verifiedAt: e.verifiedAt
},
...s ? { expired: true } : {}
};
}
if (!isOfficialExternalPluginCatalogFeed(t)) throw new Error("hosted catalog feed did not match a supported schema version");
if (e.expectedFeedId && t.id !== e.expectedFeedId) throw new Error(`hosted catalog feed id "${t.id}" did not match expected "${e.expectedFeedId}"`);
return { feed: enforceHostedCatalogFeedInstallAuthority(t) };
}
function enforceHostedCatalogFeedInstallAuthority(e) {
if (e.schemaVersion < 2) return e;
return {
...e,
entries: e.entries.map((e) => {
const t = normalizeOptionalString(e.state);
const n = normalizeOptionalString(e.publisher?.trust);
return t === "available" && n === "official" ? e : removeOfficialExternalPluginCatalogInstallAuthority(e);
})
};
}
function readOfficialExternalPluginCatalogInvalidTimestampSequence(e) {
if (!isRecord(e)) return;
if (typeof e.generatedAt === "string" && parseOfficialExternalPluginCatalogTimestamp(e.generatedAt) !== void 0) return;
const t = {
...e,
generatedAt: "1970-01-01T00:00:00.000Z"
};
return isOfficialExternalPluginCatalogFeed(t) ? t.sequence : void 0;
}
function removeOfficialExternalPluginCatalogInstallAuthority(e) {
const { install: t, [MANIFEST_KEY]: n, ...r } = e;
if (!n) return {
...r,
state: "unavailable"
};
const { install: i, ...a } = n;
return {
...r,
state: "unavailable",
[MANIFEST_KEY]: a
};
}
async function snapshotOrBundledFallbackResult(e) {
let t = e.error;
try {
const t = await e.snapshotStore.read(e.url);
if (t) {
const n = `sha256:${sha256Hex(t.body)}`;
if (n !== t.metadata.checksum) throw new Error("hosted catalog snapshot checksum mismatch");
if (e.expectedSha256 && e.expectedSha256 !== n) throw new Error("hosted catalog snapshot checksum did not match expected checksum");
const r = await parseHostedCatalogFeedBody({
body: t.body,
expectedFeedId: e.expectedFeedId,
verification: e.verification,
verifiedAt: t.trust?.verifiedAt ?? t.savedAt,
allowLegacyBetaEnvelope: true,
now: e.now,
allowExpired: true,
allowMissingExpiry: true
});
const i = dedupeOfficialExternalPluginCatalogEntries(filterOfficialExternalPluginCatalogEntriesBySourceRefs(parseOfficialExternalPluginCatalogEntries(r.feed), {
catalogConfig: e.catalogConfig,
requireManifestInstallSourceRef: e.requireManifestInstallSourceRef
}));
const a = r.expired ? i.map((e) => removeOfficialExternalPluginCatalogInstallAuthority(e)) : i;
return {
source: "hosted-snapshot",
entries: a,
feed: r.expired ? {
...r.feed,
entries: a
} : r.feed,
metadata: t.metadata,
snapshot: t,
...r.trust ? { trust: r.trust } : {},
error: r.expired ? `${formatErrorMessage(e.error)}; ${r.feed.expiresAt ? `hosted catalog signed feed expired at ${r.feed.expiresAt}` : "hosted catalog signed feed has no expiresAt"}` : formatErrorMessage(e.error)
};
}
} catch (n) {
t = `${formatErrorMessage(e.error)}; snapshot fallback failed: ${formatErrorMessage(n)}`;
}
if (e.verification?.mode === "signed") return {
source: "bundled-fallback",
entries: [],
error: formatErrorMessage(t)
};
return bundledFallbackResult(t, e.metadata);
}
async function resolveHostedCatalogSnapshotStore(e) {
const { createSqliteHostedOfficialExternalPluginCatalogSnapshotStore: t } = await import("./official-external-plugin-catalog-snapshot-store-cW6TI0hX.mjs");
return t({
...e.env ? { env: e.env } : {},
...e.stateDir ? { stateDir: e.stateDir } : {},
...e.stateDatabasePath ? { stateDatabasePath: e.stateDatabasePath } : {}
});
}
async function loadHostedOfficialExternalPluginCatalogEntries(e) {
let t;
try {
t = resolveHostedCatalogFeedSource({
feedUrl: e?.feedUrl,
feedProfile: e?.feedProfile,
catalogConfig: e?.catalogConfig
});
} catch (e) {
return bundledFallbackResult(e);
}
const { url: n } = t;
const r = await resolveHostedCatalogSnapshotStore({
env: e?.env,
stateDir: e?.stateDir,
stateDatabasePath: e?.stateDatabasePath
});
const i = normalizeOptionalString(e?.expectedSha256);
const currentTime = () => e?.now?.() ?? /* @__PURE__ */ new Date();
const a = shouldRequireManifestInstallSourceRef({
feedUrl: e?.feedUrl,
feedProfile: e?.feedProfile,
catalogConfig: e?.catalogConfig
});
if (e?.offline === true) return await snapshotOrBundledFallbackResult({
error: "hosted catalog feed offline mode",
snapshotStore: r,
url: n.href,
expectedSha256: i,
catalogConfig: e?.catalogConfig,
requireManifestInstallSourceRef: a,
expectedFeedId: t.expectedFeedId,
verification: t.verification,
now: currentTime()
});
const o = new Headers();
const s = t.verification?.mode === "signed";
if (s) o.set("accept", DSSE_ENVELOPE_MEDIA_TYPE);
const loadFallback = (o, s, c = currentTime()) => snapshotOrBundledFallbackResult({
error: o,
snapshotStore: r,
url: n.href,
metadata: s,
expectedSha256: i,
catalogConfig: e?.catalogConfig,
requireManifestInstallSourceRef: a,
expectedFeedId: t.expectedFeedId,
verification: t.verification,
now: c
});
const metadataBase = (e) => {
const t = normalizeOptionalString(e.headers.get("etag"));
const r = normalizeOptionalString(e.headers.get("last-modified"));
return {
url: n.href,
status: e.status,
...t ? { etag: t } : {},
...r ? { lastModified: r } : {}
};
};
let c;
let l;
try {
const { fetchWithSsrFGuard: u } = await import("./fetch-guard-Dt3790xW.mjs");
const d = await u({
url: n.href,
init: {
method: "GET",
headers: o
},
requireHttps: true,
maxRedirects: 2,
timeoutMs: DEFAULT_HOSTED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_TIMEOUT_MS,
policy: { hostnameAllowlist: t.hostnameAllowlist },
auditContext: "official-external-plugin-catalog-feed"
});
c = d.response;
l = d.release;
const f = metadataBase(c);
if (c.status === 304 || !c.ok) return await loadFallback(`hosted catalog feed returned HTTP ${c.status}`, f);
if (s && c.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== DSSE_ENVELOPE_MEDIA_TYPE) return await loadFallback(`signed hosted catalog feed must use ${DSSE_ENVELOPE_MEDIA_TYPE}`, f);
const p = await readHostedCatalogResponseText(c);
const m = `sha256:${sha256Hex(p)}`;
const h = {
...f,
checksum: m
};
if (i && i !== m) return await loadFallback(`hosted catalog feed checksum mismatch: expected ${i}`, h);
const g = currentTime();
const _ = g.toISOString();
const v = await parseHostedCatalogFeedBody({
body: p,
expectedFeedId: t.expectedFeedId,
verification: t.verification,
verifiedAt: _,
now: g
}).catch((e) => loadFallback(e, h, g));
if ("source" in v) return v;
if (v.trust?.mode === "signed") {
const e = await r.read(n.href);
if (e?.trust?.mode === "signed") {
const n = e.monotonic?.mode === "signed-feed" ? e.monotonic : (await parseHostedCatalogFeedBody({
body: e.body,
expectedFeedId: t.expectedFeedId,
verification: t.verification,
verifiedAt: e.trust.verifiedAt,
allowLegacyBetaEnvelope: true,
now: g,
allowExpired: true,
allowMissingExpiry: true
}).catch((e) => {
if (e instanceof HostedCatalogFeedTimestampError) return { feed: { sequence: e.sequence } };
throw e;
})).feed;
if (isOfficialExternalPluginCatalogRollback({
candidate: v.feed,
current: n
})) throw new HostedCatalogSignedFeedMonotonicityError("hosted catalog signed feed sequence is older than current snapshot");
}
}
const y = filterOfficialExternalPluginCatalogEntriesBySourceRefs(parseOfficialExternalPluginCatalogEntries(v.feed), {
catalogConfig: e?.catalogConfig,
requireManifestInstallSourceRef: a
});
await r.write({
body: p,
metadata: h,
savedAt: _,
...v.trust ? { trust: v.trust } : {},
...v.trust?.mode === "signed" ? { monotonic: {
mode: "signed-feed",
sequence: v.feed.sequence,
generatedAt: v.feed.generatedAt
} } : {}
}).catch((t) => {
if (t instanceof HostedCatalogSignedFeedMonotonicityError) throw t;
if (e?.requireSnapshotWrite) throw new HostedCatalogSnapshotWriteError(t);
});
return {
source: "hosted",
entries: dedupeOfficialExternalPluginCatalogEntries(y),
feed: v.feed,
metadata: h,
...v.trust ? { trust: v.trust } : {}
};
} catch (e) {
if (e instanceof HostedCatalogSnapshotWriteError) throw e.originalError;
return await loadFallback(e);
} finally {
await cancelUnreadResponseBody(c);
await l?.().catch(() => void 0);
}
}
//#endregion
export { loadHostedOfficialExternalPluginCatalogEntries };