UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

765 lines (764 loc) • 25.2 kB
import "../../redact-BDinS1q9.js"; import "../../errors-BxyFnvP3.js"; import "../../unhandled-rejections-CDJ8dOVP.js"; import "../../logger-kwZIqwuw.js"; import "../../paths-ViKUYWUK.js"; import "../../tmp-openclaw-dir-idKIOMmb.js"; import "../../theme-CdOoMzRk.js"; import "../../globals-DBUMOBZ8.js"; import "../../subsystem-DISldKSB.js"; import "../../ansi-BEJF8NKS.js"; import "../../boolean-C3GkJetE.js"; import "../../env-Dnra1IpT.js"; import "../../warning-filter-CBhOcgHd.js"; import "../../utils-CS0Ikux6.js"; import "../../links-8xRhWBQL.js"; import "../../paths-C4Oy7wjk.js"; import "../../auth-profiles-DRuJBw5y.js"; import "../../agent-scope-bjWqU22i.js"; import "../../boundary-path-Dm0QJ7-y.js"; import "../../boundary-file-read-DcZxlWD8.js"; import "../../logger-BmpSCz93.js"; import "../../exec-B5_AYfQG.js"; import "../../workspace-D4K6QX9X.js"; import "../../model-selection-BnFtDmP7.js"; import "../../io-y3Az_Onx.js"; import "../../shell-env-BOu7XeT_.js"; import "../../safe-text-yavot2qw.js"; import "../../version-CD3oP1-d.js"; import "../../env-substitution-O6uabUmO.js"; import "../../includes-Bj3eLUWH.js"; import "../../zod-schema.providers-core-COy5nBQ0.js"; import "../../legacy-web-search-BB-ZHEhz.js"; import "../../registry-C5UkPpaO.js"; import "../../config-state-Br0ucqMb.js"; import "../../min-host-version-RMBWtIAR.js"; import "../../manifest-registry-B5JNQdOM.js"; import "../../runtime-guard-PhQ6PwQa.js"; import "../../avatar-policy-B5nOfso_.js"; import "../../ip-Ce8EDTBZ.js"; import "../../zod-schema.agent-runtime-Dtg4Jy6G.js"; import "../../zod-schema.core-BuVz8Rk7.js"; import "../../config-D4zN4BRl.js"; import "../../file-lock-DEiVq2ow.js"; import "../../audit-fs-DTQIjp2r.js"; import "../../resolve-B7S4PlnO.js"; import "../../profiles-COPO-hHI.js"; import "../../tailscale-CxY-91GZ.js"; import "../../tailnet-DHiKSG7V.js"; import "../../net-JAg9zL0G.js"; import "../../auth-Buq0Niri.js"; import "../../credentials-D8pfRimu.js"; import "../../message-channel-BliByQBl.js"; import "../../store-C5UK26Ce.js"; import "../../runtime-Iz8uZ7EU.js"; import "../../plugins-B09-vgme.js"; import "../../sessions-D9ZgHCHb.js"; import "../../paths-rhN9LKM_.js"; import "../../session-write-lock-va3qZE6f.js"; import "../../method-scopes-BiEi0X2g.js"; import "../../call-CQbSO4Fr.js"; import "../../prompt-style-C4CV4Y_p.js"; import "../../ports-lsof-BLEgL_Gn.js"; import "../../restart-stale-pids-BsPvlGJd.js"; import "../../ports-FldL_Lhq.js"; import "../../logging-CznuqaMu.js"; import "../../commands-C6oAw_H-.js"; import "../../issue-format-BtLIwOtN.js"; import "../../identity-Dp-UIak4.js"; import "../../heartbeat-Bdfr_onc.js"; import { Hb as defineChannelPluginEntry } from "../../pi-embedded-CbCYZxIb.js"; import "../../internal-hooks-CIUghoK4.js"; import "../../multimodal-B8yEZcl5.js"; import "../../memory-search-B_aq08y5.js"; import "../../provider-catalog-rVN7ZbR5.js"; import "../../secret-input-DXoOLNgb.js"; import "../../bindings-CFudGB9Z.js"; import "../../resolve-route-DwFWP4JW.js"; import "../../routing-zOQ0wwtV.js"; import "../../identity-file-DVLib087.js"; import "../../outbound-runtime-m-y0nd6F.js"; import "../../provider-env-vars-CpUJqT5v.js"; import "../../provider-auth-input-Bus9W_qh.js"; import "../../provider-model-minimax-DSmX4BNO.js"; import "../../provider-models-BKjzpTsb.js"; import "../../anthropic-vertex-provider-B2x4YywE.js"; import "../../provider-catalog-BTgF8VyO.js"; import "../../provider-catalog-D0IlX18O.js"; import "../../provider-catalog-BTmUX0Mp.js"; import "../../provider-catalog-sph_Rl63.js"; import "../../provider-catalog-C7tUyBwV.js"; import "../../provider-catalog-C8dPZpHW.js"; import "../../provider-catalog-BJNff1VI.js"; import "../../provider-catalog-IAdymoqT.js"; import "../../provider-catalog-Bjc7evzh.js"; import "../../models-config.providers.discovery-CjkO08q6.js"; import "../../text-runtime-DVXt5xhi.js"; import "../../tool-catalog-BjSY4C4F.js"; import "../../docker-Bhjg8g2t.js"; import "../../sandbox-DTlKNieF.js"; import "../../common-zReYuoMM.js"; import "../../image-ops-By4YfyWa.js"; import "../../thinking-CJoSRIGR.js"; import "../../path-alias-guards-CwRM04O1.js"; import "../../sandbox-paths-Cn8i8Jxm.js"; import "../../channel-actions-fV93bLjV.js"; import "../../mime-CsUtzcn2.js"; import { s as isBlockedHostnameOrIp } from "../../ssrf-0bPJMoZR.js"; import "../../fetch-guard-CYl1q2XH.js"; import "../../provider-web-search-COZNygbd.js"; import "../../manager-Bw8JrihM.js"; import "../../config-schema-CPzP2Ds6.js"; import "../../channel-plugin-common-ClptUZHU.js"; import "../../status-helpers-Cflmo90d.js"; import "../../conversation-runtime-nmWgJSXS.js"; import "../../runtime-whatsapp-boundary-XjdkYMz_.js"; import "../../pairing-store-BGKLrjo6.js"; import "../../json-store--JDX3zNL.js"; import "../../secret-file-Bif7RlZ-.js"; import "../../channel-config-schema-CgpS17zB.js"; import "../../setup-binary-C2MYZTCc.js"; import "../../archive-pOxyr9r4.js"; import "../../fs-safe-DZyOgpPN.js"; import "../../signal-cli-install-fVOL9FvX.js"; import "../../setup-wizard-proxy-DoOpOF8S.js"; import "../../setup-BI3ohdrT.js"; import "../../dm-policy-shared-DtcQProI.js"; import "../../runtime-env-DQOYrXVl.js"; import "../../temp-path-B91lt0LF.js"; import "../../diagnostic-CDTtMQBT.js"; import "../../logging-CCTKg_fh.js"; import "../../config-runtime-BYNizC50.js"; import "../../level-overrides-DzIzQ3ZY.js"; import "../../exec-approvals-BF_Qfdq8.js"; import { D as createFixedWindowRateLimiter, I as requestBodyErrorToText, P as readJsonBodyWithLimit } from "../../webhook-ingress-D-H5frou.js"; import "../../system-events-BU_NYynX.js"; import "../../ssrf-policy-DYINyIKC.js"; import "../../hook-runtime-BUYmDbaA.js"; import "../../templating-BDXRiJUh.js"; import "../../channel-reply-pipeline-BxH4-AP2.js"; import "../../reply-history-n7nOPLta.js"; import "../../commands-registry.data-BFXJWoqi.js"; import "../../commands-registry-Bh9pJ817.js"; import "../../frontmatter-CP5371Rm.js"; import "../../env-overrides-BNSo89u5.js"; import "../../skills-M0AZJeXx.js"; import "../../skills-remote-BHxDA4Jw.js"; import "../../workspace-dirs-DqDLiRvZ.js"; import "../../pairing-token-DAszGmwD.js"; import "../../skill-commands-D73dGR_l.js"; import "../../config-CLRQPUSt.js"; import "../../routes-XT2JfvT-.js"; import "../../ssh-tunnel-LM52qY6N.js"; import "../../server-middleware-BP59C6FL.js"; import "../../provider-auth-ref-CQEp9sp3.js"; import "../../provider-auth-helpers-Do3RFvdi.js"; import "../../provider-api-key-auth-BEeRW3dq.js"; import "../../pairing-labels-D27Y4Vv6.js"; import "../../directory-runtime-D9Y42mW-.js"; import "../../read-only-account-inspect-CJPRBFj7.js"; import "../../src-BoNU6eQs.js"; import "../../web-media-PKy3RbRG.js"; import "../../media-understanding-BDOSvuM9.js"; import "../../web-media-CiSbdGPs.js"; import "../../state-paths-Dvb3Mfl3.js"; import "../../llm-task-Br6Ixjlh.js"; import "../../pi-model-discovery-DO3tFksS.js"; import "../../exec-inline-eval-CpmxWJsW.js"; import "../../target-registry-9OUOvlxj.js"; import "../../external-content-DZI9vlJn.js"; import "../../brave-onFD06fq.js"; import "../../duckduckgo-CZuAOfiQ.js"; import "../../exa-5bwgY04k.js"; import "../../security-runtime-xlw0Fxx2.js"; import "../../provider-usage-ClxTGn5c.js"; import "../../provider-models-Bjv0V4OP.js"; import "../../media-understanding-provider-DllGbg-v.js"; import "../../media-understanding-provider-BDq4rFL-.js"; import "../../provider-onboard-CSnPvkMM.js"; import "../../onboard-BU8aRvq7.js"; import "../../perplexity-web-search-provider-CI38RNUU.js"; import "../../perplexity-CMZbsreI.js"; import "../../model-definitions-CLagLj0g.js"; import "../../onboard-0P7GBI2D.js"; import "../../provider-catalog-CKHo9CRM.js"; import "../../provider-models-Dmjtw6kn.js"; import "../../stream-C-KGzzT0.js"; import "../../web-search-CO1hvu_l.js"; import "../../stagger-CFqdtCYL.js"; import "../../command-secret-targets-DLs8jC2H.js"; import "../../delivery-queue-DHURMSqX.js"; import "../../channel-summary-Ctrv7moa.js"; import "../../follow-redirects-CVAaqIk4.js"; import "../../tool-policy-match-DQWWRSN4.js"; import "../../runtime-CAdCdG-M.js"; import "../../channel-status-BfM90KqH.js"; import "../../discord-core-DLbIyXWy.js"; import "../../cli-runtime-Cx1v7N7v.js"; import "../../config-presence-DA3j8Nmi.js"; import "../../query-expansion-BOJBTXsp.js"; import "../../search-manager-DNBHwaee.js"; import "../../acp-runtime-BHZj-SLU.js"; import "../../telegram-core-DD8gCuaX.js"; import "../../audit-BI48Fi3j.js"; import "../../gateway-runtime-Dn2qAGY7.js"; import "../../connection-auth-Nl2a3tDb.js"; import "../../mcp-config-CDIWSqVk.js"; import "../../channel-setup-C5JbULY6.js"; import "../../extension-shared-B8dMu-tU.js"; import "../../nostr-V7B3bA_R.js"; import "../../runtime-api-CGm_T0dX2.js"; import "../../api-DlkRluD-.js"; import { a as resolveNostrAccount, c as getNostrRuntime, d as SimplePool, f as verifyEvent, l as setNostrRuntime, m as NostrProfileSchema, u as contentToProfile } from "../../setup-surface-D_ChCd-K.js"; import { n as nostrPlugin, r as publishNostrProfile, t as getNostrProfileState } from "../../channel-Cv0UkVMo.js"; import { z } from "zod"; //#region extensions/nostr/src/nostr-profile-import.ts /** * Nostr Profile Import * * Fetches and verifies kind:0 profile events from relays. * Used to import existing profiles before editing. */ const DEFAULT_TIMEOUT_MS = 5e3; /** * Sanitize URLs in an imported profile to prevent SSRF attacks. * Removes any URLs that don't pass SSRF validation. */ function sanitizeProfileUrls(profile) { const result = { ...profile }; for (const field of [ "picture", "banner", "website" ]) { const value = result[field]; if (value && typeof value === "string") { if (!validateUrlSafety(value).ok) delete result[field]; } } return result; } /** * Fetch the latest kind:0 profile event for a pubkey from relays. * * - Queries all relays in parallel * - Takes the event with the highest created_at * - Verifies the event signature * - Parses and returns the profile */ async function importProfileFromRelays(opts) { const { pubkey, relays, timeoutMs = DEFAULT_TIMEOUT_MS } = opts; if (!pubkey || !/^[0-9a-fA-F]{64}$/.test(pubkey)) return { ok: false, error: "Invalid pubkey format (must be 64 hex characters)", relaysQueried: [] }; if (relays.length === 0) return { ok: false, error: "No relays configured", relaysQueried: [] }; const pool = new SimplePool(); const relaysQueried = []; try { const events = []; const timeoutPromise = new Promise((resolve) => { setTimeout(resolve, timeoutMs); }); const subscriptionPromise = new Promise((resolve) => { let completed = 0; for (const relay of relays) { relaysQueried.push(relay); const sub = pool.subscribeMany([relay], [{ kinds: [0], authors: [pubkey], limit: 1 }], { onevent(event) { events.push({ event, relay }); }, oneose() { completed++; if (completed >= relays.length) resolve(); }, onclose() { completed++; if (completed >= relays.length) resolve(); } }); setTimeout(() => { sub.close(); }, timeoutMs); } }); await Promise.race([subscriptionPromise, timeoutPromise]); if (events.length === 0) return { ok: false, error: "No profile found on any relay", relaysQueried }; let bestEvent = null; for (const item of events) if (!bestEvent || item.event.created_at > bestEvent.event.created_at) bestEvent = item; if (!bestEvent) return { ok: false, error: "No valid profile event found", relaysQueried }; if (!verifyEvent(bestEvent.event)) return { ok: false, error: "Profile event has invalid signature", relaysQueried, sourceRelay: bestEvent.relay }; let content; try { content = JSON.parse(bestEvent.event.content); } catch { return { ok: false, error: "Profile event has invalid JSON content", relaysQueried, sourceRelay: bestEvent.relay }; } return { ok: true, profile: sanitizeProfileUrls(contentToProfile(content)), event: { id: bestEvent.event.id, pubkey: bestEvent.event.pubkey, created_at: bestEvent.event.created_at }, relaysQueried, sourceRelay: bestEvent.relay }; } finally { pool.close(relays); } } /** * Merge imported profile with local profile. * * Strategy: * - For each field, prefer local if set, otherwise use imported * - This preserves user customizations while filling in missing data */ function mergeProfiles(local, imported) { if (!imported) return local ?? {}; if (!local) return imported; return { name: local.name ?? imported.name, displayName: local.displayName ?? imported.displayName, about: local.about ?? imported.about, picture: local.picture ?? imported.picture, banner: local.banner ?? imported.banner, website: local.website ?? imported.website, nip05: local.nip05 ?? imported.nip05, lud16: local.lud16 ?? imported.lud16 }; } //#endregion //#region extensions/nostr/src/nostr-profile-http.ts const profileRateLimiter = createFixedWindowRateLimiter({ windowMs: 6e4, maxRequests: 5, maxTrackedKeys: 2048 }); function checkRateLimit(accountId) { return !profileRateLimiter.isRateLimited(accountId); } const publishLocks = /* @__PURE__ */ new Map(); async function withPublishLock(accountId, fn) { const prev = publishLocks.get(accountId) ?? Promise.resolve(); let resolve; const next = new Promise((r) => { resolve = r; }); publishLocks.set(accountId, next); await prev.catch(() => {}); try { return await fn(); } finally { resolve(); if (publishLocks.get(accountId) === next) publishLocks.delete(accountId); } } function validateUrlSafety(urlStr) { try { const url = new URL(urlStr); if (url.protocol !== "https:") return { ok: false, error: "URL must use https:// protocol" }; if (isBlockedHostnameOrIp(url.hostname.toLowerCase())) return { ok: false, error: "URL must not point to private/internal addresses" }; return { ok: true }; } catch { return { ok: false, error: "Invalid URL format" }; } } const nip05FormatSchema = z.string().regex(/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,}$/i, "Invalid NIP-05 format (user@domain.com)").optional(); const lud16FormatSchema = z.string().regex(/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,}$/i, "Invalid Lightning address format").optional(); const ProfileUpdateSchema = NostrProfileSchema.extend({ nip05: nip05FormatSchema, lud16: lud16FormatSchema }); function sendJson(res, status, body) { res.statusCode = status; res.setHeader("Content-Type", "application/json; charset=utf-8"); res.end(JSON.stringify(body)); } async function readJsonBody(req, maxBytes = 64 * 1024, timeoutMs = 3e4) { const result = await readJsonBodyWithLimit(req, { maxBytes, timeoutMs, emptyObjectOnEmpty: true }); if (result.ok) return result.value; if (result.code === "PAYLOAD_TOO_LARGE") throw new Error("Request body too large"); if (result.code === "REQUEST_BODY_TIMEOUT") throw new Error(requestBodyErrorToText("REQUEST_BODY_TIMEOUT")); if (result.code === "CONNECTION_CLOSED") throw new Error(requestBodyErrorToText("CONNECTION_CLOSED")); throw new Error(result.code === "INVALID_JSON" ? "Invalid JSON" : result.error); } function parseAccountIdFromPath(pathname) { return pathname.match(/^\/api\/channels\/nostr\/([^/]+)\/profile/)?.[1] ?? null; } function isLoopbackRemoteAddress(remoteAddress) { if (!remoteAddress) return false; const ipLower = remoteAddress.toLowerCase().replace(/^\[|\]$/g, ""); if (ipLower === "::1") return true; if (ipLower === "127.0.0.1" || ipLower.startsWith("127.")) return true; const v4Mapped = ipLower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/); if (v4Mapped) return isLoopbackRemoteAddress(v4Mapped[1]); return false; } function isLoopbackOriginLike(value) { try { const hostname = new URL(value).hostname.toLowerCase(); return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"; } catch { return false; } } function firstHeaderValue(value) { if (Array.isArray(value)) return value[0]; return typeof value === "string" ? value : void 0; } function normalizeIpCandidate(raw) { const unquoted = raw.trim().replace(/^"|"$/g, ""); const bracketedWithOptionalPort = unquoted.match(/^\[([^[\]]+)\](?::\d+)?$/); if (bracketedWithOptionalPort) return bracketedWithOptionalPort[1] ?? ""; const ipv4WithPort = unquoted.match(/^(\d+\.\d+\.\d+\.\d+):\d+$/); if (ipv4WithPort) return ipv4WithPort[1] ?? ""; return unquoted; } function hasNonLoopbackForwardedClient(req) { const forwardedFor = firstHeaderValue(req.headers["x-forwarded-for"]); if (forwardedFor) for (const hop of forwardedFor.split(",")) { const candidate = normalizeIpCandidate(hop); if (!candidate) continue; if (!isLoopbackRemoteAddress(candidate)) return true; } const realIp = firstHeaderValue(req.headers["x-real-ip"]); if (realIp) { const candidate = normalizeIpCandidate(realIp); if (candidate && !isLoopbackRemoteAddress(candidate)) return true; } return false; } function enforceLoopbackMutationGuards(ctx, req, res) { const remoteAddress = req.socket.remoteAddress; if (!isLoopbackRemoteAddress(remoteAddress)) { ctx.log?.warn?.(`Rejected mutation from non-loopback remoteAddress=${String(remoteAddress)}`); sendJson(res, 403, { ok: false, error: "Forbidden" }); return false; } if (hasNonLoopbackForwardedClient(req)) { ctx.log?.warn?.("Rejected mutation with non-loopback forwarded client headers"); sendJson(res, 403, { ok: false, error: "Forbidden" }); return false; } if (firstHeaderValue(req.headers["sec-fetch-site"])?.trim().toLowerCase() === "cross-site") { ctx.log?.warn?.("Rejected mutation with cross-site sec-fetch-site header"); sendJson(res, 403, { ok: false, error: "Forbidden" }); return false; } const origin = firstHeaderValue(req.headers.origin); if (typeof origin === "string" && !isLoopbackOriginLike(origin)) { ctx.log?.warn?.(`Rejected mutation with non-loopback origin=${origin}`); sendJson(res, 403, { ok: false, error: "Forbidden" }); return false; } const referer = firstHeaderValue(req.headers.referer ?? req.headers.referrer); if (typeof referer === "string" && !isLoopbackOriginLike(referer)) { ctx.log?.warn?.(`Rejected mutation with non-loopback referer=${referer}`); sendJson(res, 403, { ok: false, error: "Forbidden" }); return false; } return true; } function createNostrProfileHttpHandler(ctx) { return async (req, res) => { const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`); if (!url.pathname.startsWith("/api/channels/nostr/")) return false; const accountId = parseAccountIdFromPath(url.pathname); if (!accountId) return false; const isImport = url.pathname.endsWith("/profile/import"); if (!(url.pathname.endsWith("/profile") || isImport)) return false; try { if (req.method === "GET" && !isImport) return await handleGetProfile(accountId, ctx, res); if (req.method === "PUT" && !isImport) return await handleUpdateProfile(accountId, ctx, req, res); if (req.method === "POST" && isImport) return await handleImportProfile(accountId, ctx, req, res); sendJson(res, 405, { ok: false, error: "Method not allowed" }); return true; } catch (err) { ctx.log?.error(`Profile HTTP error: ${String(err)}`); sendJson(res, 500, { ok: false, error: "Internal server error" }); return true; } }; } async function handleGetProfile(accountId, ctx, res) { const configProfile = ctx.getConfigProfile(accountId); const publishState = await getNostrProfileState(accountId); sendJson(res, 200, { ok: true, profile: configProfile ?? null, publishState: publishState ?? null }); return true; } async function handleUpdateProfile(accountId, ctx, req, res) { if (!enforceLoopbackMutationGuards(ctx, req, res)) return true; if (!checkRateLimit(accountId)) { sendJson(res, 429, { ok: false, error: "Rate limit exceeded (5 requests/minute)" }); return true; } let body; try { body = await readJsonBody(req); } catch (err) { sendJson(res, 400, { ok: false, error: String(err) }); return true; } const parseResult = ProfileUpdateSchema.safeParse(body); if (!parseResult.success) { sendJson(res, 400, { ok: false, error: "Validation failed", details: parseResult.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`) }); return true; } const profile = parseResult.data; if (profile.picture) { const pictureCheck = validateUrlSafety(profile.picture); if (!pictureCheck.ok) { sendJson(res, 400, { ok: false, error: `picture: ${pictureCheck.error}` }); return true; } } if (profile.banner) { const bannerCheck = validateUrlSafety(profile.banner); if (!bannerCheck.ok) { sendJson(res, 400, { ok: false, error: `banner: ${bannerCheck.error}` }); return true; } } if (profile.website) { const websiteCheck = validateUrlSafety(profile.website); if (!websiteCheck.ok) { sendJson(res, 400, { ok: false, error: `website: ${websiteCheck.error}` }); return true; } } const mergedProfile = { ...ctx.getConfigProfile(accountId) ?? {}, ...profile }; try { const result = await withPublishLock(accountId, async () => { return await publishNostrProfile(accountId, mergedProfile); }); if (result.successes.length > 0) { await ctx.updateConfigProfile(accountId, mergedProfile); ctx.log?.info(`[${accountId}] Profile published to ${result.successes.length} relay(s)`); } else ctx.log?.warn(`[${accountId}] Profile publish failed on all relays`); sendJson(res, 200, { ok: true, eventId: result.eventId, createdAt: result.createdAt, successes: result.successes, failures: result.failures, persisted: result.successes.length > 0 }); } catch (err) { ctx.log?.error(`[${accountId}] Profile publish error: ${String(err)}`); sendJson(res, 500, { ok: false, error: `Publish failed: ${String(err)}` }); } return true; } async function handleImportProfile(accountId, ctx, req, res) { if (!enforceLoopbackMutationGuards(ctx, req, res)) return true; const accountInfo = ctx.getAccountInfo(accountId); if (!accountInfo) { sendJson(res, 404, { ok: false, error: `Account not found: ${accountId}` }); return true; } const { pubkey, relays } = accountInfo; if (!pubkey) { sendJson(res, 400, { ok: false, error: "Account has no public key configured" }); return true; } let autoMerge = false; try { const body = await readJsonBody(req); if (typeof body === "object" && body !== null) autoMerge = body.autoMerge === true; } catch {} ctx.log?.info(`[${accountId}] Importing profile for ${pubkey.slice(0, 8)}...`); const result = await importProfileFromRelays({ pubkey, relays, timeoutMs: 1e4 }); if (!result.ok) { sendJson(res, 200, { ok: false, error: result.error, relaysQueried: result.relaysQueried }); return true; } if (autoMerge && result.profile) { const merged = mergeProfiles(ctx.getConfigProfile(accountId), result.profile); await ctx.updateConfigProfile(accountId, merged); ctx.log?.info(`[${accountId}] Profile imported and merged`); sendJson(res, 200, { ok: true, imported: result.profile, merged, saved: true, event: result.event, sourceRelay: result.sourceRelay, relaysQueried: result.relaysQueried }); return true; } sendJson(res, 200, { ok: true, imported: result.profile, saved: false, event: result.event, sourceRelay: result.sourceRelay, relaysQueried: result.relaysQueried }); return true; } //#endregion //#region extensions/nostr/index.ts var nostr_default = defineChannelPluginEntry({ id: "nostr", name: "Nostr", description: "Nostr DM channel plugin via NIP-04", plugin: nostrPlugin, setRuntime: setNostrRuntime, registerFull(api) { const httpHandler = createNostrProfileHttpHandler({ getConfigProfile: (accountId) => { return resolveNostrAccount({ cfg: getNostrRuntime().config.loadConfig(), accountId }).profile; }, updateConfigProfile: async (accountId, profile) => { const runtime = getNostrRuntime(); const cfg = runtime.config.loadConfig(); const channels = cfg.channels ?? {}; const nostrConfig = channels.nostr ?? {}; await runtime.config.writeConfigFile({ ...cfg, channels: { ...channels, nostr: { ...nostrConfig, profile } } }); }, getAccountInfo: (accountId) => { const account = resolveNostrAccount({ cfg: getNostrRuntime().config.loadConfig(), accountId }); if (!account.configured || !account.publicKey) return null; return { pubkey: account.publicKey, relays: account.relays }; }, log: api.logger }); api.registerHttpRoute({ path: "/api/channels/nostr", auth: "gateway", match: "prefix", handler: httpHandler }); } }); //#endregion export { nostr_default as default, nostrPlugin, setNostrRuntime };