Skip to content

Commit 8fb87b5

Browse files
terisukeclaude
andcommitted
fix(hook): address CRITICAL env var size + 3 HIGH review findings
- CRITICAL: Truncate OPENCODE_TOOL_INPUT at 128KB to prevent E2BIG spawn failure that silently bypasses security hooks - HIGH: Import HookConfig from hook/schema.ts in config.ts (SSOT) - HIGH: Check PostToolUse hook block result instead of discarding - HIGH: Require non-empty command string (z.string().min(1)) Closes #75 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 819b053 commit 8fb87b5

7 files changed

Lines changed: 61 additions & 21 deletions

File tree

‎packages/opencode/src/config/config.ts‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import { Duration, Effect, Layer, Option, ServiceMap } from "effect"
4141
import { Flock } from "@/util/flock"
4242
import { isPathPluginSpec, parsePluginSpecifier, resolvePathPluginTarget } from "@/plugin/shared"
4343
import { Npm } from "@/npm"
44+
import { HookConfig } from "../hook/schema"
4445

4546
export namespace Config {
4647
const ModelId = z.string().meta({ $ref: "https://models.dev/model-schema.json#/$defs/Model" })
@@ -999,17 +1000,7 @@ export namespace Config {
9991000
layout: Layout.optional().describe("@deprecated Always uses stretch layout."),
10001001
permission: Permission.optional(),
10011002
tools: z.record(z.string(), z.boolean()).optional(),
1002-
hooks: z
1003-
.object({
1004-
PreToolUse: z.array(z.object({ command: z.string(), matcher: z.string().optional(), timeout: z.number().int().positive().optional() })),
1005-
PostToolUse: z.array(z.object({ command: z.string(), matcher: z.string().optional(), timeout: z.number().int().positive().optional() })),
1006-
SessionStart: z.array(z.object({ command: z.string(), matcher: z.string().optional(), timeout: z.number().int().positive().optional() })),
1007-
Notification: z.array(z.object({ command: z.string(), matcher: z.string().optional(), timeout: z.number().int().positive().optional() })),
1008-
})
1009-
.strict()
1010-
.partial()
1011-
.optional()
1012-
.describe("Shell script hooks for lifecycle events"),
1003+
hooks: HookConfig,
10131004
enterprise: z
10141005
.object({
10151006
url: z.string().optional().describe("Enterprise URL"),

‎packages/opencode/src/hook/execute.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ import type { HookEntry } from "./schema"
55
const log = Log.create({ service: "hook" })
66
const DEFAULT_TIMEOUT = 10_000
77

8+
const MAX_HOOK_INPUT_ENV = 128 * 1024 // 128KB
9+
export function safeToolInput(args: unknown): string {
10+
const raw = JSON.stringify(args)
11+
if (raw.length <= MAX_HOOK_INPUT_ENV) return raw
12+
return raw.slice(0, MAX_HOOK_INPUT_ENV) + "\n[truncated]"
13+
}
14+
815
export interface HookEnv {
916
OPENCODE_HOOK_EVENT: string
1017
OPENCODE_TOOL_NAME?: string

‎packages/opencode/src/hook/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,4 @@ export {
66
HookEntry as HookEntrySchema,
77
HookConfig as HookConfigSchema,
88
} from "./schema"
9-
export { runHooks, runHook, matchesTool, type HookResult, type HookEnv } from "./execute"
9+
export { runHooks, runHook, matchesTool, safeToolInput, type HookResult, type HookEnv } from "./execute"

‎packages/opencode/src/hook/schema.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export const HOOK_EVENTS = ["PreToolUse", "PostToolUse", "SessionStart", "Notifi
44
export type HookEvent = (typeof HOOK_EVENTS)[number]
55

66
export const HookEntry = z.object({
7-
command: z.string().describe("Shell command or path to script"),
7+
command: z.string().min(1).describe("Shell command or path to script"),
88
matcher: z.string().optional().describe("Tool name glob pattern (PreToolUse/PostToolUse only)"),
99
timeout: z.number().int().positive().optional().describe("Timeout in ms (default: 10000)"),
1010
})

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import { Shell } from "@/shell/shell"
4848
import { AppFileSystem } from "@/filesystem"
4949
import { Truncate } from "@/tool/truncate"
5050
import { decodeDataUrl } from "@/util/data-url"
51-
import { runHooks, type HookEnv } from "../hook"
51+
import { runHooks, safeToolInput, type HookEnv } from "../hook"
5252
import { Config } from "../config/config"
5353
import { Process } from "@/util/process"
5454
import { Cause, Effect, Exit, Layer, Option, Scope, ServiceMap } from "effect"
@@ -467,7 +467,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the
467467
const hookEnv: HookEnv = {
468468
OPENCODE_HOOK_EVENT: "PreToolUse",
469469
OPENCODE_TOOL_NAME: item.id,
470-
OPENCODE_TOOL_INPUT: JSON.stringify(args),
470+
OPENCODE_TOOL_INPUT: safeToolInput(args),
471471
OPENCODE_PROJECT_DIR: Instance.directory,
472472
OPENCODE_SESSION_ID: ctx.sessionID,
473473
}
@@ -504,13 +504,21 @@ NOTE: At any point in time through this workflow you should feel free to ask the
504504
)
505505

506506
// PostToolUse hooks
507-
yield* Effect.promise(() =>
507+
const postHookResult = yield* Effect.promise(() =>
508508
runHooks(hookCfg.hooks?.PostToolUse, item.id, {
509509
...hookEnv,
510510
OPENCODE_HOOK_EVENT: "PostToolUse",
511-
}),
511+
}).catch((): { action: "pass" } => ({ action: "pass" })),
512512
)
513513

514+
if (postHookResult.action === "block") {
515+
return {
516+
title: "Blocked by post-execution hook",
517+
output: postHookResult.message ?? "Tool output suppressed by hook",
518+
metadata: {} as any,
519+
}
520+
}
521+
514522
return output
515523
}),
516524
)
@@ -535,7 +543,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the
535543
const mcpHookEnv: HookEnv = {
536544
OPENCODE_HOOK_EVENT: "PreToolUse",
537545
OPENCODE_TOOL_NAME: key,
538-
OPENCODE_TOOL_INPUT: JSON.stringify(args),
546+
OPENCODE_TOOL_INPUT: safeToolInput(args),
539547
OPENCODE_PROJECT_DIR: Instance.directory,
540548
OPENCODE_SESSION_ID: ctx.sessionID,
541549
}
@@ -569,13 +577,19 @@ NOTE: At any point in time through this workflow you should feel free to ask the
569577
)
570578

571579
// PostToolUse hooks
572-
yield* Effect.promise(() =>
580+
const mcpPostResult = yield* Effect.promise(() =>
573581
runHooks(mcpHookCfg.hooks?.PostToolUse, key, {
574582
...mcpHookEnv,
575583
OPENCODE_HOOK_EVENT: "PostToolUse",
576-
}),
584+
}).catch((): { action: "pass" } => ({ action: "pass" })),
577585
)
578586

587+
if (mcpPostResult.action === "block") {
588+
return {
589+
content: [{ type: "text" as const, text: mcpPostResult.message ?? "Tool output suppressed by hook" }],
590+
}
591+
}
592+
579593
const textParts: string[] = []
580594
const attachments: Omit<MessageV2.FilePart, "id" | "sessionID" | "messageID">[] = []
581595
for (const contentItem of result.content) {

‎packages/opencode/test/hook/execute.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, test } from "bun:test"
2-
import { runHook, runHooks, matchesTool, type HookEnv } from "../../src/hook"
2+
import { runHook, runHooks, matchesTool, safeToolInput, type HookEnv } from "../../src/hook"
33
import type { HookEntry } from "../../src/hook"
44

55
function makeEnv(overrides?: Partial<HookEnv>): HookEnv {
@@ -149,4 +149,27 @@ describe("hook.execute", () => {
149149
expect(result.message).toBe("global")
150150
})
151151
})
152+
153+
describe("safeToolInput", () => {
154+
test("returns JSON for small input", () => {
155+
const result = safeToolInput({ key: "value" })
156+
expect(result).toBe('{"key":"value"}')
157+
})
158+
159+
test("truncates input exceeding 128KB", () => {
160+
const largeArgs = { data: "x".repeat(256 * 1024) }
161+
const result = safeToolInput(largeArgs)
162+
expect(result.length).toBeLessThanOrEqual(128 * 1024 + 12) // 128KB + "\n[truncated]"
163+
expect(result).toEndWith("\n[truncated]")
164+
})
165+
166+
test("does not truncate input exactly at 128KB", () => {
167+
// Create input that serializes to exactly 128KB
168+
const targetLen = 128 * 1024
169+
const overhead = '{"d":""}'.length
170+
const filler = "a".repeat(targetLen - overhead)
171+
const result = safeToolInput({ d: filler })
172+
expect(result).not.toContain("[truncated]")
173+
})
174+
})
152175
})

‎packages/opencode/test/hook/schema.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ describe("hook.schema", () => {
4848
const result = HookEntrySchema.safeParse({ command: "echo", timeout: 1.5 })
4949
expect(result.success).toBe(false)
5050
})
51+
52+
test("rejects empty command string", () => {
53+
const result = HookEntrySchema.safeParse({ command: "" })
54+
expect(result.success).toBe(false)
55+
})
5156
})
5257

5358
describe("HookConfig", () => {

0 commit comments

Comments
 (0)