diff --git a/src/lib/messaging/applier/plan-filter.ts b/src/lib/messaging/applier/plan-filter.ts index 93953963327..6bfdec9a422 100644 --- a/src/lib/messaging/applier/plan-filter.ts +++ b/src/lib/messaging/applier/plan-filter.ts @@ -1,31 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { - MessagingChannelId, - SandboxMessagingChannelPlan, - SandboxMessagingPlan, -} from "../manifest"; - -export function enabledPlanChannels(plan: SandboxMessagingPlan): SandboxMessagingChannelPlan[] { - const disabled = disabledPlanChannelIds(plan); - return plan.channels.filter( - (channel) => channel.active && !channel.disabled && !disabled.has(channel.channelId), - ); -} - -export function enabledPlanChannelIds(plan: SandboxMessagingPlan): Set { - return new Set(enabledPlanChannels(plan).map((channel) => channel.channelId)); -} - -export function filterEnabledPlanEntries( - plan: SandboxMessagingPlan, - entries: readonly T[], -): T[] { - const enabled = enabledPlanChannelIds(plan); - return entries.filter((entry) => enabled.has(entry.channelId)); -} - -function disabledPlanChannelIds(plan: SandboxMessagingPlan): Set { - return new Set(plan.disabledChannels); -} +export { + type EnabledPlanChannel, + type EnabledPlanSelection, + enabledPlanChannelIds, + enabledPlanChannels, + filterEnabledPlanEntries, + normalizeMessagingChannelId, +} from "../post-agent-install-selection"; diff --git a/src/lib/messaging/plan-validation.test.ts b/src/lib/messaging/plan-validation.test.ts index a0993887ad6..3879b920dea 100644 --- a/src/lib/messaging/plan-validation.test.ts +++ b/src/lib/messaging/plan-validation.test.ts @@ -237,6 +237,108 @@ describe("parseSandboxMessagingPlan", () => { makePlan({ channels: [makePlan().channels[0], makePlan().channels[0]] }), ), ).toBeNull(); + expect( + parseSandboxMessagingPlan( + makePlan({ + channels: [ + makePlan().channels[0], + { ...makePlan().channels[0], channelId: " TELEGRAM " }, + ], + }), + ), + ).toBeNull(); + }); + + it("rejects a lone noncanonical channel id even when related ids are canonical", () => { + const source = makePlan(); + expect( + parseSandboxMessagingPlan( + makePlan({ + channels: [{ ...source.channels[0], channelId: " Telegram " }], + disabledChannels: ["telegram"], + credentialBindings: [ + { + channelId: "telegram", + credentialId: "telegramBotToken", + sourceInput: "botToken", + providerName: "sb-telegram-bridge", + providerEnvKey: "TELEGRAM_BOT_TOKEN", + placeholder: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + credentialAvailable: true, + }, + ], + }), + ), + ).toBeNull(); + }); + + it.each([ + ["disabledChannels", { disabledChannels: [" Telegram "] }], + ["credentialBindings", { credentialBindings: [{ channelId: "Telegram" }] }], + [ + "networkPolicy.entries", + { networkPolicy: { presets: [], entries: [{ channelId: "Telegram" }] } }, + ], + ["agentRender", { agentRender: [{ channelId: "Telegram" }] }], + ["buildSteps", { buildSteps: [{ channelId: "Telegram" }] }], + ["stateUpdates", { stateUpdates: [{ channelId: "Telegram" }] }], + ["healthChecks", { healthChecks: [{ channelId: "Telegram" }] }], + [ + "runtimeSetup.nodePreloads", + { + runtimeSetup: { + nodePreloads: [{ channelId: "Telegram" }], + envAliases: [], + secretScans: [], + }, + }, + ], + [ + "runtimeSetup.envAliases", + { + runtimeSetup: { + nodePreloads: [], + envAliases: [{ channelId: "Telegram" }], + secretScans: [], + }, + }, + ], + [ + "runtimeSetup.secretScans", + { + runtimeSetup: { + nodePreloads: [], + envAliases: [], + secretScans: [{ channelId: "Telegram" }], + }, + }, + ], + ])("rejects noncanonical channel references in %s", (_field, overrides) => { + expect(parseSandboxMessagingPlan({ ...makePlan(), ...overrides })).toBeNull(); + }); + + it.each([ + ["input", { inputs: [{ inputId: "token", channelId: "Telegram" }] }], + ["hook", { hooks: [{ channelId: "Telegram" }] }], + [ + "host forward", + { + hostForward: { + channelId: "Telegram", + port: 3978, + label: "Telegram webhook", + }, + }, + ], + ])("rejects a noncanonical nested %s channel reference", (_field, channelOverrides) => { + const channel = makePlan().channels[0]; + expect( + parseSandboxMessagingPlan( + makePlan({ + channels: [{ ...channel, ...channelOverrides }] as SandboxMessagingPlan["channels"], + }), + ), + ).toBeNull(); }); it("rejects any persisted channel when supportedChannelIds: [] is passed (deny-all)", () => { diff --git a/src/lib/messaging/plan-validation.ts b/src/lib/messaging/plan-validation.ts index 6b59cf31f87..422d0a61ae3 100644 --- a/src/lib/messaging/plan-validation.ts +++ b/src/lib/messaging/plan-validation.ts @@ -13,6 +13,7 @@ import { type MaybeCompactMessagingPlan, normalizePersistedSandboxMessagingPlanShape, } from "./persistence"; +import { normalizeMessagingChannelId } from "./post-agent-install-selection"; export interface SandboxMessagingPlanParseOptions { sandboxName?: string | null; @@ -49,8 +50,17 @@ export function parseSandboxMessagingPlan( const supported = Array.isArray(options.supportedChannelIds) ? new Set(options.supportedChannelIds) : null; - for (const [index, channel] of value.channels.entries()) { + const normalizedChannelIds = new Set(); + for (const channel of value.channels) { if (!isObjectRecord(channel) || typeof channel.channelId !== "string") return null; + const normalizedChannelId = normalizeMessagingChannelId(channel.channelId); + if ( + !normalizedChannelId || + normalizedChannelId !== channel.channelId || + normalizedChannelIds.has(normalizedChannelId) + ) { + return null; + } if (Object.hasOwn(channel, "configured") && typeof channel.configured !== "boolean") { return null; } @@ -61,23 +71,47 @@ export function parseSandboxMessagingPlan( if (Object.hasOwn(channel, "hooks") && !Array.isArray(channel.hooks)) return null; if ( Array.isArray(channel.inputs) && - channel.inputs.some((input) => !isObjectRecord(input) || typeof input.inputId !== "string") + channel.inputs.some( + (input) => + !isObjectRecord(input) || + typeof input.inputId !== "string" || + (Object.hasOwn(input, "channelId") && input.channelId !== normalizedChannelId), + ) ) { return null; } - if (Array.isArray(channel.hooks) && channel.hooks.some((hook) => !isObjectRecord(hook))) { + if ( + Array.isArray(channel.hooks) && + channel.hooks.some( + (hook) => + !isObjectRecord(hook) || + (Object.hasOwn(hook, "channelId") && hook.channelId !== normalizedChannelId), + ) + ) { return null; } - if (supported && !supported.has(channel.channelId)) return null; if ( - value.channels.findIndex( - (candidate) => isObjectRecord(candidate) && candidate.channelId === channel.channelId, - ) !== index + Object.hasOwn(channel, "hostForward") && + isObjectRecord(channel.hostForward) && + channel.hostForward.channelId !== normalizedChannelId ) { return null; } + if (supported && !supported.has(channel.channelId)) return null; + normalizedChannelIds.add(normalizedChannelId); + } + if (!value.disabledChannels.every(isCanonicalMessagingChannelId)) return null; + if ( + !hasCanonicalChannelReferences(value.credentialBindings) || + !hasCanonicalChannelReferences(value.agentRender) || + !hasCanonicalChannelReferences(value.buildSteps) || + !hasCanonicalChannelReferences(value.stateUpdates) || + !hasCanonicalChannelReferences(value.healthChecks) || + !hasCanonicalNetworkPolicyReferences(value.networkPolicy) || + !hasCanonicalRuntimeSetupReferences(value.runtimeSetup) + ) { + return null; } - if (!value.disabledChannels.every((channelId) => typeof channelId === "string")) return null; return cloneSandboxMessagingPlan( normalizePersistedSandboxMessagingPlanShape(value as MaybeCompactMessagingPlan), @@ -192,3 +226,32 @@ function isRuntimeSetup(value: unknown): boolean { value.secretScans.every(isObjectRecord) ); } + +function isCanonicalMessagingChannelId(value: unknown): value is string { + return ( + typeof value === "string" && value.length > 0 && normalizeMessagingChannelId(value) === value + ); +} + +function hasCanonicalChannelReferences(value: unknown): boolean { + return ( + value === undefined || + (Array.isArray(value) && + value.every( + (entry) => isObjectRecord(entry) && isCanonicalMessagingChannelId(entry.channelId), + )) + ); +} + +function hasCanonicalNetworkPolicyReferences(value: unknown): boolean { + if (!isObjectRecord(value) || !Object.hasOwn(value, "entries")) return true; + return hasCanonicalChannelReferences(value.entries); +} + +function hasCanonicalRuntimeSetupReferences(value: unknown): boolean { + if (value === undefined) return true; + if (!isObjectRecord(value)) return false; + return ["nodePreloads", "envAliases", "secretScans"].every((field) => + hasCanonicalChannelReferences(value[field]), + ); +} diff --git a/src/lib/messaging/post-agent-install-selection.test.ts b/src/lib/messaging/post-agent-install-selection.test.ts new file mode 100644 index 00000000000..34e8c3b23f9 --- /dev/null +++ b/src/lib/messaging/post-agent-install-selection.test.ts @@ -0,0 +1,191 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; + +import { describe, expect, it } from "vitest"; +import { filterEnabledPlanEntries } from "./applier/plan-filter"; +import type { + SandboxMessagingAgentRenderPlan, + SandboxMessagingBuildStepPlan, + SandboxMessagingChannelPlan, + SandboxMessagingPlan, +} from "./manifest"; +import { + selectActiveMessagingChannelIds, + selectEnabledMessagingAgentRender, + selectEnabledPostAgentInstallBuildFiles, +} from "./post-agent-install-selection"; + +function channel( + channelId: string, + hooks: SandboxMessagingChannelPlan["hooks"] = [], +): SandboxMessagingChannelPlan { + return { + channelId, + displayName: channelId, + authMode: "none", + active: true, + selected: true, + configured: true, + disabled: false, + inputs: [], + hooks, + }; +} + +function plan(overrides: Partial = {}): SandboxMessagingPlan { + return { + schemaVersion: 1, + sandboxName: "selection-test", + agent: "openclaw", + workflow: "onboard", + channels: [], + disabledChannels: [], + credentialBindings: [], + networkPolicy: { presets: [], entries: [] }, + agentRender: [], + buildSteps: [], + stateUpdates: [], + healthChecks: [], + ...overrides, + }; +} + +function render(channelId: string): SandboxMessagingAgentRenderPlan { + return { + channelId, + kind: "json-fragment", + agent: "openclaw", + target: "/sandbox/.openclaw/openclaw.json", + path: "channels.telegram.enabled", + value: true, + templateRefs: [], + }; +} + +function buildFile( + channelId: string, + outputId: string, + hookId?: string, +): SandboxMessagingBuildStepPlan { + return { + channelId, + kind: "build-file", + hookId, + outputId, + required: true, + value: "fixture", + }; +} + +describe("post-agent-install messaging selection", () => { + it("loads through Node's direct TypeScript ESM path used by image builds", () => { + const moduleUrl = new URL("./post-agent-install-selection.ts", import.meta.url).href; + const result = spawnSync( + process.execPath, + [ + "--experimental-strip-types", + "--input-type=module", + "--eval", + `import(${JSON.stringify(moduleUrl)})`, + ], + { encoding: "utf8" }, + ); + + expect({ status: result.status, signal: result.signal }).toEqual({ status: 0, signal: null }); + }); + + it("uses the shared enabled-channel contract and preserves canonical ordering", () => { + const selection = plan({ + channels: [channel(" Discord "), channel(" TeLeGrAm "), channel("DISCORD")], + disabledChannels: [" telegram "], + }); + + expect(selectActiveMessagingChannelIds(selection)).toEqual(["discord"]); + expect( + filterEnabledPlanEntries(selection, [ + { channelId: "DISCORD", value: "kept" }, + { channelId: "telegram", value: "disabled" }, + ]), + ).toEqual([{ channelId: "DISCORD", value: "kept" }]); + }); + + it("matches normalized channel ids across channels, render entries, and build steps", () => { + const selection = plan({ + channels: [ + channel(" Telegram ", [ + { + channelId: " Telegram ", + id: "post-install", + phase: "post-agent-install", + handler: "telegram.post-install", + }, + { + channelId: " Telegram ", + id: "render-only", + phase: "render", + handler: "telegram.render", + }, + ]), + ], + agentRender: [render("TELEGRAM"), render("discord")], + buildSteps: [ + buildFile("telegram", "post-install-file", "post-install"), + buildFile(" TELEGRAM ", "render-file", "render-only"), + buildFile("discord", "unrelated-file"), + ], + }); + + expect(selectEnabledMessagingAgentRender(selection).map(({ channelId }) => channelId)).toEqual([ + "TELEGRAM", + ]); + expect( + selectEnabledPostAgentInstallBuildFiles(selection).map(({ outputId }) => outputId), + ).toEqual(["post-install-file"]); + }); + + it("fails closed instead of selecting a hook phase from ambiguous normalized ids", () => { + const selection = plan({ + channels: [ + channel("telegram", [ + { + channelId: "telegram", + id: "shared-hook", + phase: "post-agent-install", + handler: "telegram.post-install", + }, + ]), + channel(" TELEGRAM ", [ + { + channelId: " TELEGRAM ", + id: "shared-hook", + phase: "render", + handler: "telegram.render", + }, + ]), + ], + buildSteps: [buildFile("TELEGRAM", "ambiguous-file", "shared-hook")], + }); + + expect(selectEnabledPostAgentInstallBuildFiles(selection)).toEqual([]); + }); + + it("fails closed when a build step references a missing hook", () => { + const selection = plan({ + channels: [ + channel("telegram", [ + { + channelId: "telegram", + id: "post-install", + phase: "post-agent-install", + handler: "telegram.post-install", + }, + ]), + ], + buildSteps: [buildFile("telegram", "stale-hook-file", "missing-hook")], + }); + + expect(selectEnabledPostAgentInstallBuildFiles(selection)).toEqual([]); + }); +}); diff --git a/src/lib/messaging/post-agent-install-selection.ts b/src/lib/messaging/post-agent-install-selection.ts index 63c9afb380c..8c88f212fc5 100644 --- a/src/lib/messaging/post-agent-install-selection.ts +++ b/src/lib/messaging/post-agent-install-selection.ts @@ -1,77 +1,112 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -interface SelectionHook { - readonly id: string; - readonly phase: string; +import type { + MessagingChannelId, + SandboxMessagingAgentRenderPlan, + SandboxMessagingBuildStepPlan, + SandboxMessagingChannelPlan, + SandboxMessagingHookReferencePlan, +} from "./manifest"; + +export type EnabledPlanChannel = Pick & + Partial>; + +export interface EnabledPlanSelection { + readonly channels: readonly Channel[]; + readonly disabledChannels?: readonly MessagingChannelId[]; +} + +export function normalizeMessagingChannelId(channelId: MessagingChannelId): MessagingChannelId { + return channelId.trim().toLowerCase(); +} + +export function enabledPlanChannels( + plan: EnabledPlanSelection, +): Channel[] { + const disabled = new Set( + (plan.disabledChannels ?? []).map(normalizeMessagingChannelId).filter(Boolean), + ); + return plan.channels.filter((channel) => { + const channelId = normalizeMessagingChannelId(channel.channelId); + return channelId.length > 0 && channel.active && !channel.disabled && !disabled.has(channelId); + }); } -interface SelectionChannel { - readonly channelId: string; - readonly active?: boolean; - readonly disabled?: boolean; - readonly hooks?: readonly SelectionHook[]; +export function enabledPlanChannelIds(plan: EnabledPlanSelection): Set { + return new Set( + enabledPlanChannels(plan).map((channel) => normalizeMessagingChannelId(channel.channelId)), + ); } -interface SelectionPlanBase { - readonly channels: readonly SelectionChannel[]; +export function filterEnabledPlanEntries( + plan: EnabledPlanSelection, + entries: readonly T[], +): T[] { + const enabled = enabledPlanChannelIds(plan); + return entries.filter((entry) => enabled.has(normalizeMessagingChannelId(entry.channelId))); } +type SelectionChannel = EnabledPlanChannel & { + readonly hooks?: readonly (Pick & { + readonly phase: string; + })[]; +}; + +type SelectionRender = Pick; + +type SelectionBuildStep = Pick; + /** * Canonical active-channel selection for the image applier. Each selection * consumer must resolve the same active channels and mutable outputs. */ -export function selectActiveMessagingChannelIds(plan: SelectionPlanBase): string[] { +export function selectActiveMessagingChannelIds( + plan: EnabledPlanSelection, +): MessagingChannelId[] { const seen = new Set(); const channels: string[] = []; - for (const item of plan.channels) { - const channel = String(item.channelId || "") - .trim() - .toLowerCase(); + for (const item of enabledPlanChannels(plan)) { + const channel = normalizeMessagingChannelId(item.channelId); if (!channel || seen.has(channel)) continue; - if (item.active === true && item.disabled !== true) { - seen.add(channel); - channels.push(channel); - } + seen.add(channel); + channels.push(channel); } return channels; } -export function selectEnabledMessagingAgentRender< - Render extends { - readonly agent: string; - readonly channelId: string; - }, ->( - plan: SelectionPlanBase & { +export function selectEnabledMessagingAgentRender( + plan: EnabledPlanSelection & { readonly agent: string; readonly agentRender: readonly Render[]; }, ): Render[] { const active = new Set(selectActiveMessagingChannelIds(plan)); return plan.agentRender.filter( - (render) => render.agent === plan.agent && active.has(render.channelId), + (render) => + render.agent === plan.agent && active.has(normalizeMessagingChannelId(render.channelId)), ); } export function selectEnabledPostAgentInstallBuildFiles< - Step extends { - readonly channelId: string; - readonly kind: string; - readonly hookId?: string; - }, + Channel extends SelectionChannel, + Step extends SelectionBuildStep, >( - plan: SelectionPlanBase & { + plan: EnabledPlanSelection & { readonly buildSteps: readonly Step[]; }, -): Step[] { +): Array { const active = new Set(selectActiveMessagingChannelIds(plan)); - return plan.buildSteps.filter((step) => { - if (!active.has(step.channelId) || step.kind !== "build-file") return false; + const channels = enabledPlanChannels(plan); + return plan.buildSteps.filter((step): step is Step & { readonly kind: "build-file" } => { + const channelId = normalizeMessagingChannelId(step.channelId); + if (!active.has(channelId) || step.kind !== "build-file") return false; if (!step.hookId) return true; - const hookPhase = plan.channels - .find((channel) => channel.channelId === step.channelId) - ?.hooks?.find((hook) => hook.id === step.hookId)?.phase; - return hookPhase === undefined || hookPhase === "post-agent-install"; + const matchingChannels = channels.filter( + (channel) => normalizeMessagingChannelId(channel.channelId) === channelId, + ); + if (matchingChannels.length !== 1) return false; + const matchedHook = matchingChannels[0]?.hooks?.find((hook) => hook.id === step.hookId); + return matchedHook !== undefined && matchedHook.phase === "post-agent-install"; }); } diff --git a/src/lib/onboard/managed-startup/image-runtime.ts b/src/lib/onboard/managed-startup/image-runtime.ts index 2aac60603b5..f8e5c7f4edd 100644 --- a/src/lib/onboard/managed-startup/image-runtime.ts +++ b/src/lib/onboard/managed-startup/image-runtime.ts @@ -1631,7 +1631,7 @@ export async function main(argv: readonly string[] = process.argv.slice(2)): Pro ); } -if (require.main === module) { +if (typeof require !== "undefined" && typeof module !== "undefined" && require.main === module) { main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; diff --git a/test/entrypoint-env-wrapper.test.ts b/test/entrypoint-env-wrapper.test.ts index 8bd74015681..5e58805d17f 100644 --- a/test/entrypoint-env-wrapper.test.ts +++ b/test/entrypoint-env-wrapper.test.ts @@ -6,7 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { sliceBlock } from "./helpers/corporate-ca-support"; const HELPER = path.join(import.meta.dirname, "..", "scripts", "lib", "entrypoint-env-wrapper.sh"); @@ -134,8 +134,10 @@ describe("OCI entrypoint env-wrapper normalization", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-env-wrapper-")); const fakeBin = path.join(tmpDir, "bin"); const scriptPath = path.join(tmpDir, "run.sh"); - function runScenario(setArgs: string, extraEnv: Record = {}) { + const baseEnv = { ...process.env }; + delete baseEnv.NEMOCLAW_DASHBOARD_PORT; + delete baseEnv.CHAT_UI_URL; const script = [ "#!/usr/bin/env bash", "set -euo pipefail", @@ -156,10 +158,13 @@ describe("OCI entrypoint env-wrapper normalization", () => { return spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 5000, - env: { ...process.env, PATH: `${fakeBin}:${process.env.PATH || ""}`, ...extraEnv }, + env: { ...baseEnv, PATH: `${fakeBin}:${process.env.PATH || ""}`, ...extraEnv }, }); } + vi.stubEnv("NEMOCLAW_DASHBOARD_PORT", "19999"); + vi.stubEnv("CHAT_UI_URL", "https://ambient.example.test/ui"); + try { fs.mkdirSync(fakeBin); fs.writeFileSync(path.join(fakeBin, "openclaw"), "#!/usr/bin/env bash\nexit 0\n", { @@ -205,6 +210,11 @@ describe("OCI entrypoint env-wrapper normalization", () => { expect(baked.stdout).toContain("OPENCLAW_STATE_DIR=/sandbox/.openclaw"); expect(baked.stdout).toContain("CMD=openclaw agent"); + const defaults = runScenario("set -- nemoclaw-start openclaw agent"); + expect(defaults.status).toBe(0); + expect(defaults.stdout).toContain("CHAT_UI_URL=http://127.0.0.1:18789"); + expect(defaults.stdout).toContain("PUBLIC_PORT=18789"); + const invalidHighPort = runScenario("set -- nemoclaw-start openclaw agent", { NEMOCLAW_DASHBOARD_PORT: "70000", }); @@ -212,6 +222,7 @@ describe("OCI entrypoint env-wrapper normalization", () => { expect(invalidHighPort.stderr).toContain("Invalid NEMOCLAW_DASHBOARD_PORT='70000'"); expect(invalidHighPort.stderr).toContain("must be an integer between 1024 and 65535"); } finally { + vi.unstubAllEnvs(); fs.rmSync(tmpDir, { recursive: true, force: true }); } });