Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🐚 fix: Fail Closed When Plugin Hook Shell Cannot Start (#17227)

lia-by-librechat[bot]fd2496db8639
diff --git a/Dockerfile b/Dockerfile
index cd7aca075a..7a9e6e80bb 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -4,7 +4,7 @@
FROM node:24.16.0-alpine AS node
RUN apk upgrade --no-cache
-RUN apk add --no-cache jemalloc
+RUN apk add --no-cache bash jemalloc
RUN apk add --no-cache python3 py3-pip uv
# Set environment variable to use jemalloc
diff --git a/Dockerfile.multi b/Dockerfile.multi
index 3c99f25cef..712640eace 100644
--- a/Dockerfile.multi
+++ b/Dockerfile.multi
@@ -14,7 +14,7 @@ FROM node:24.16.0-alpine AS base-min
ARG NPM_CI_TIMEOUT_SECONDS=1500
ARG NPM_CI_ATTEMPTS=2
RUN apk upgrade --no-cache
-RUN apk add --no-cache jemalloc
+RUN apk add --no-cache bash jemalloc
# Set environment variable to use jemalloc
ENV LD_PRELOAD=/usr/lib/libjemalloc.so.2
# Disable dependency installation analytics before any npm lifecycle scripts run.
diff --git a/packages/api/src/agents/hooks/executor.spec.ts b/packages/api/src/agents/hooks/executor.spec.ts
index 04ba8a12fa..cb51fb6f07 100644
--- a/packages/api/src/agents/hooks/executor.spec.ts
+++ b/packages/api/src/agents/hooks/executor.spec.ts
@@ -8,6 +8,7 @@ import {
commandExecutorCapabilities,
createCommandExecutor,
getShellHandlerIssue,
+ getCommandShellIssue,
} from './executor';
let pluginRoot: string;
@@ -423,11 +424,81 @@ describe('createCommandExecutor', () => {
).resolves.toEqual({ decision: 'deny', reason: 'unrecognized native' });
});
- test('ignores non-blocking failures', async () => {
- const output = await execute({ type: 'command', command: 'echo oops >&2; exit 1' });
+ test.each([1, 127])('ignores a started command exiting with code %i', async (code) => {
+ const output = await execute({ type: 'command', command: `echo oops >&2; exit ${code}` });
expect(output).toEqual({});
});
+ test.each<HookEvent>(['PreToolUse', 'UserPromptSubmit', 'SubagentStart', 'Stop', 'StopFinalize'])(
+ 'fails closed on %s when the shell is missing',
+ async (event) => {
+ const output = await execute(
+ { type: 'command', command: 'exit 2' },
+ { sourceEvent: event, targetEvent: event },
+ { PATH: pluginData },
+ );
+ expect(output).toEqual({
+ decision: event === 'Stop' || event === 'StopFinalize' ? 'block' : 'deny',
+ reason: 'Plugin hook command could not start',
+ });
+ },
+ );
+
+ test.each<HookEvent>([
+ 'RunStart',
+ 'PostToolUse',
+ 'PostToolUseFailure',
+ 'PostToolBatch',
+ 'PreemptBoundary',
+ 'PermissionDenied',
+ 'SubagentStop',
+ 'StopFailure',
+ 'PreCompact',
+ 'PostCompact',
+ ])('keeps %s nonblocking when the shell is missing', async (event) => {
+ const output = await execute(
+ { type: 'command', command: 'exit 2' },
+ { sourceEvent: event, targetEvent: event },
+ { PATH: pluginData },
+ );
+ expect(output).toEqual({});
+ });
+
+ test('fails closed when the shell is not executable', async () => {
+ await fs.promises.writeFile(path.join(pluginData, 'bash'), '#!/bin/sh\nexit 0\n', {
+ mode: 0o600,
+ });
+ await expect(
+ execute({ type: 'command', command: 'exit 2' }, {}, { PATH: pluginData }),
+ ).resolves.toEqual({ decision: 'deny', reason: 'Plugin hook command could not start' });
+ });
+
+ test('fails closed when the command working directory is missing', async () => {
+ await fs.promises.rmdir(pluginRoot);
+ await expect(execute({ type: 'command', command: 'exit 2' })).resolves.toEqual({
+ decision: 'deny',
+ reason: 'Plugin hook command could not start',
+ });
+ });
+
+ test('keeps an already-aborted command nonblocking when the shell is missing', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const executor = createCommandExecutor({
+ pluginRoot,
+ pluginData,
+ env: { PATH: pluginData },
+ });
+ await expect(
+ executor.execute(request({ type: 'command', command: 'exit 2' }), controller.signal),
+ ).resolves.toEqual({});
+ });
+
+ test('reports a missing shell without disabling command capabilities', () => {
+ expect(getCommandShellIssue({ PATH: pluginData })).toContain('could not start');
+ expect(getCommandShellIssue({ PATH: process.env.PATH })).toBeUndefined();
+ });
+
test('runs from the plugin root with PLUGIN_ROOT, PLUGIN_DATA, and only allowlisted vars', async () => {
const output = await execute(
{
diff --git a/packages/api/src/agents/hooks/executor.ts b/packages/api/src/agents/hooks/executor.ts
index ea2e6d7099..0c24cde8e1 100644
--- a/packages/api/src/agents/hooks/executor.ts
+++ b/packages/api/src/agents/hooks/executor.ts
@@ -1,6 +1,6 @@
-import { spawn } from 'node:child_process';
import { Tools } from 'librechat-data-provider';
import { logger } from '@librechat/data-schemas';
+import { spawn, spawnSync } from 'node:child_process';
import { BashExecutionToolDefinition, ReadFileToolDefinition } from '@librechat/agents';
import type { HookEvent, HookOutput, ToolDecision, StopDecision } from '@librechat/agents';
import type { PluginHookExecutor, PluginHookExecutionRequest } from './runtime';
@@ -269,6 +269,25 @@ export const commandExecutorCapabilities: PluginHookCapabilities = {
sessionLifecycle: true,
};
+/** Startup probe only; unavailable shells must not disable registered guards. */
+export function getCommandShellIssue(env: NodeJS.ProcessEnv = process.env): string | undefined {
+ const executable = process.platform === 'win32' ? 'powershell.exe' : 'bash';
+ const argv =
+ process.platform === 'win32'
+ ? ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', 'exit 0']
+ : ['--version'];
+ const result = spawnSync(executable, argv, {
+ env,
+ stdio: 'ignore',
+ timeout: 5_000,
+ windowsHide: true,
+ });
+ if (result.error !== undefined || result.status !== 0) {
+ return `The plugin hook shell "${executable}" could not start; install it and make it available on PATH. Blocking hooks will fail closed`;
+ }
+ return undefined;
+}
+
export interface CommandExecutorOptions {
/** Filesystem-resolved plugin root; becomes the command's cwd and `PLUGIN_ROOT`. */
pluginRoot: string;
@@ -611,8 +630,9 @@ function parseCompletion(
* process, mirroring Claude Code's contract: the event payload arrives as
* JSON on stdin, exit 0 with JSON stdout returns a (sanitized) hook output,
* exit 2 blocks with stderr as the reason, and any other exit is logged and
- * ignored. Commands run from the plugin root with a minimal allowlisted
- * environment plus `PLUGIN_ROOT`/`PLUGIN_DATA`.
+ * ignored. Failure to start denies decision-bearing events; observation-only
+ * events and cancellation remain nonblocking. Commands run from the plugin
+ * root with a minimal allowlisted environment plus `PLUGIN_ROOT`/`PLUGIN_DATA`.
*
* SECURITY: deployment plugins are operator-installed code, the same trust
* level as `toolApproval.hooks` modules. Execution is additionally gated on
@@ -660,7 +680,10 @@ export function createCommandExecutor(options: CommandExecutorOptions): PluginHo
`[pluginHooks] ${request.pluginId} ${request.sourceEvent}: command failed to run`,
error,
);
- return {};
+ const decision = EVENT_TRAITS[request.targetEvent].exitTwo;
+ return decision === 'prevent'
+ ? {}
+ : { decision, reason: 'Plugin hook command could not start' };
}
},
};
diff --git a/packages/api/src/plugins/runtime.spec.ts b/packages/api/src/plugins/runtime.spec.ts
index 42163c435b..fdfaca4430 100644
--- a/packages/api/src/plugins/runtime.spec.ts
+++ b/packages/api/src/plugins/runtime.spec.ts
@@ -1,6 +1,7 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
+import { logger } from '@librechat/data-schemas';
import { HookRegistry, executeHooks } from '@librechat/agents';
import {
getDeploymentPluginHookCapabilities,
@@ -98,6 +99,26 @@ afterEach(async () => {
});
describe('getDeploymentPluginHookCapabilities', () => {
+ it('logs a startup error for a missing shell but keeps guards executable', () => {
+ const error = jest.spyOn(logger, 'error');
+ const capabilities = getDeploymentPluginHookCapabilities({
+ DEPLOYMENT_PLUGIN_HOOKS: 'true',
+ PATH: dataDir,
+ });
+ expect(capabilities?.handlerTypes.has('command')).toBe(true);
+ expect(error).toHaveBeenCalledWith(
+ expect.stringMatching(/DEPLOYMENT_PLUGIN_HOOKS is enabled:.*could not start/),
+ );
+ });
+
+ it('does not report a missing shell when hooks are disabled', () => {
+ const error = jest.spyOn(logger, 'error');
+ expect(
+ getDeploymentPluginHookCapabilities({ DEPLOYMENT_PLUGIN_HOOKS: 'false', PATH: dataDir }),
+ ).toBeUndefined();
+ expect(error).not.toHaveBeenCalled();
+ });
+
it('returns undefined unless DEPLOYMENT_PLUGIN_HOOKS is enabled', () => {
expect(getDeploymentPluginHookCapabilities({})).toBeUndefined();
expect(
@@ -162,6 +183,29 @@ describe('registerDeploymentPluginHooks', () => {
expect(unmatched.decision).toBeUndefined();
});
+ it('denies through the hook registry when the command shell cannot spawn', async () => {
+ await writePlugin('guard');
+ await initialize();
+ const registry = new HookRegistry();
+ registerDeploymentPluginHooks({ registry, context: { sessionId: 'missing-shell' } });
+ jest.replaceProperty(process.env, 'PATH', dataDir);
+
+ const result = await executeHooks({
+ registry,
+ matchQuery: 'write_file',
+ input: {
+ hook_event_name: 'PreToolUse',
+ runId: 'run-1',
+ toolName: 'write_file',
+ toolInput: { path: '/etc/passwd' },
+ toolUseId: 'tool-1',
+ },
+ });
+ expect(result).toEqual(
+ expect.objectContaining({ decision: 'deny', reason: 'Plugin hook command could not start' }),
+ );
+ });
+
it('fires Claude-alias matchers against runtime tool names with plugin-namespace payloads', async () => {
await writePlugin('alias');
await initialize();
diff --git a/packages/api/src/plugins/runtime.ts b/packages/api/src/plugins/runtime.ts
index 2b1b926f41..5128cc24a6 100644
--- a/packages/api/src/plugins/runtime.ts
+++ b/packages/api/src/plugins/runtime.ts
@@ -13,6 +13,7 @@ import type { LoadedPlugin } from './types';
import {
commandExecutorCapabilities,
createCommandExecutor,
+ getCommandShellIssue,
registerPluginHooks,
} from '~/agents/hooks';
import { getDeploymentPluginRegistry } from './deployment';
@@ -101,7 +102,14 @@ function withOnceDedup(
export function getDeploymentPluginHookCapabilities(
env: NodeJS.ProcessEnv = process.env,
): PluginHookCapabilities | undefined {
- return isEnabled(env[DEPLOYMENT_PLUGIN_HOOKS_ENV]) ? commandExecutorCapabilities : undefined;
+ if (!isEnabled(env[DEPLOYMENT_PLUGIN_HOOKS_ENV])) {
+ return undefined;
+ }
+ const shellIssue = getCommandShellIssue(env);
+ if (shellIssue !== undefined) {
+ logger.error(`[pluginHooks] ${DEPLOYMENT_PLUGIN_HOOKS_ENV} is enabled: ${shellIssue}`);
+ }
+ return commandExecutorCapabilities;
}
function getExecutableHookPlugins(): LoadedPlugin[] {