diff --git a/internal/agentlookup/agentlookup.go b/internal/agentlookup/agentlookup.go index 4cfa143..a2235a6 100644 --- a/internal/agentlookup/agentlookup.go +++ b/internal/agentlookup/agentlookup.go @@ -659,14 +659,30 @@ func quote(word string, fish bool) string { return "'" + strings.ReplaceAll(word, "'", `'"'"'`) + "'" } -func StartArgv(cmd []string, env []string, platform string) []string { +var ( + ErrUnsafeArg = errors.New("this text cannot be passed to the program on Windows through cmd.exe: leave out control characters and & | < > ^ ( ) ! % \" or pass long text through stdin or a file if the program supports it") + shimTarget = regexp.MustCompile(`"(?:%~dp0%?|%dp0%)\\?([^"%]+)"\s+%\*`) + controlChars = regexp.MustCompile(`[\x00-\x1f\x7f]`) +) + +const cmdSpecial = `&|<>^()!%"` + +func StartArgv(cmd []string, env []string, platform string) ([]string, error) { env = environ(env) if Windows(platform) { first := strings.ToLower(cmd[0]) if strings.HasSuffix(first, ".cmd") || strings.HasSuffix(first, ".bat") { - return append([]string{or(get(env, "COMSPEC"), "cmd.exe"), "/c"}, cmd...) + if direct := resolveShim(cmd[0], env); direct != nil { + return append(direct, cmd[1:]...), nil + } + for _, w := range cmd { + if !cmdSafe(w) { + return nil, ErrUnsafeArg + } + } + return append([]string{or(get(env, "COMSPEC"), "cmd.exe"), "/c"}, cmd...), nil } - return append([]string{}, cmd...) + return append([]string{}, cmd...), nil } sh := LoginShell(env, platform) fish := filepath.Base(sh) == "fish" @@ -674,7 +690,61 @@ func StartArgv(cmd []string, env []string, platform string) []string { for i, w := range cmd { words[i] = quote(w, fish) } - return []string{sh, "-l", "-c", "exec " + strings.Join(words, " ")} + return []string{sh, "-l", "-c", "exec " + strings.Join(words, " ")}, nil +} + +// cmdSafe reports whether a word can go through cmd.exe and a script shim +// unchanged. cmd.exe reads its special characters even inside double quotes +// once a shim expands %*, so quoting is not treated as protection. +func cmdSafe(word string) bool { + return !controlChars.MatchString(word) && !strings.ContainsAny(word, cmdSpecial) +} + +func resolveShim(shim string, env []string) []string { + body, err := os.ReadFile(shim) + if err != nil { + return nil + } + found := shimTarget.FindAllStringSubmatch(string(body), -1) + if len(found) == 0 { + return nil + } + dir := winDir(shim) + target := filepath.Join(append([]string{dir}, strings.Split(strings.Trim(found[len(found)-1][1], `\`), `\`)...)...) + if st, err := os.Stat(target); err != nil || st.IsDir() { + return nil + } + switch strings.ToLower(filepath.Ext(target)) { + case ".exe": + return []string{target} + case ".js", ".cjs", ".mjs": + if node := nodeFor(dir, env); node != "" { + return []string{node, target} + } + } + return nil +} + +func winDir(path string) string { + if i := strings.LastIndexAny(path, `\/`); i >= 0 { + return path[:i] + } + return "." +} + +func nodeFor(dir string, env []string) string { + candidates := []string{filepath.Join(dir, "node.exe")} + for _, d := range strings.Split(get(env, "PATH"), ";") { + if d = strings.Trim(d, `" `); d != "" { + candidates = append(candidates, filepath.Join(d, "node.exe")) + } + } + for _, c := range candidates { + if st, err := os.Stat(c); err == nil && !st.IsDir() { + return c + } + } + return "" } type Result struct { @@ -689,7 +759,10 @@ func Run(cmd []string, env []string, timeout time.Duration, platform string) (Re if timeout <= 0 { timeout = 15 * time.Second } - argv := StartArgv(cmd, env, platform) + argv, err := StartArgv(cmd, env, platform) + if err != nil { + return Result{}, err + } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() c := nowindow.CommandContext(ctx, argv[0], argv[1:]...) @@ -697,7 +770,7 @@ func Run(cmd []string, env []string, timeout time.Duration, platform string) (Re var stdout, stderr strings.Builder c.Stdout, c.Stderr = &stdout, &stderr c.WaitDelay = 2 * time.Second - err := c.Run() + err = c.Run() res := Result{Stdout: stdout.String(), Stderr: stderr.String()} if ctx.Err() != nil { return res, ErrTimeout diff --git a/internal/agentlookup/windows_start_test.go b/internal/agentlookup/windows_start_test.go new file mode 100644 index 0000000..6dfe477 --- /dev/null +++ b/internal/agentlookup/windows_start_test.go @@ -0,0 +1,97 @@ +package agentlookup_test + +import ( + "errors" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/nodemode-ai/form.md/internal/agentlookup" +) + +const npmShim = "@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n" + + "IF EXIST \"%dp0%\\node.exe\" (\r\n SET \"_prog=%dp0%\\node.exe\"\r\n) ELSE (\r\n SET \"_prog=node\"\r\n)\r\n" + + "endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\node_modules\\tool\\cli.js\" %*\r\n" + +const exeShim = "@ECHO off\r\n\"%~dp0\\node_modules\\tool\\bin\\tool.exe\" %*\r\n" + +func TestAWindowsScriptShimRunsItsTargetWithoutCmd(t *testing.T) { + dir := t.TempDir() + shim := put(t, filepath.Join(dir, "claude.cmd"), npmShim) + cli := put(t, filepath.Join(dir, "node_modules", "tool", "cli.js"), "") + node := put(t, filepath.Join(dir, "node.exe"), "") + args := []string{shim, "-p", "line one\nline two & 100% \"done\""} + got, err := agentlookup.StartArgv(args, []string{"COMSPEC=cmd.exe"}, "windows") + if err != nil { + t.Fatal(err) + } + if want := []string{node, cli, "-p", args[2]}; !reflect.DeepEqual(got, want) { + t.Fatalf("argv = %q, want %q", got, want) + } + pathNode := put(t, filepath.Join(t.TempDir(), "node.exe"), "") + other := t.TempDir() + shim2 := put(t, filepath.Join(other, "claude.cmd"), npmShim) + cli2 := put(t, filepath.Join(other, "node_modules", "tool", "cli.js"), "") + got, err = agentlookup.StartArgv([]string{shim2}, []string{"PATH=" + filepath.Dir(pathNode)}, "windows") + if err != nil || !reflect.DeepEqual(got, []string{pathNode, cli2}) { + t.Fatalf("argv with node on the path = %q, %v", got, err) + } +} + +func TestAWindowsShimToAProgramRunsTheProgram(t *testing.T) { + dir := t.TempDir() + shim := put(t, filepath.Join(dir, "codex.cmd"), exeShim) + exe := put(t, filepath.Join(dir, "node_modules", "tool", "bin", "tool.exe"), "") + got, err := agentlookup.StartArgv([]string{shim, "a&b"}, []string{}, "windows") + if err != nil || !reflect.DeepEqual(got, []string{exe, "a&b"}) { + t.Fatalf("argv = %q, %v", got, err) + } +} + +func TestTheCmdFallbackRefusesTextCmdWouldReadAsCommands(t *testing.T) { + shim := put(t, filepath.Join(t.TempDir(), "tool.bat"), "@echo off\r\n") + env := []string{"COMSPEC=cmd.exe"} + words := []string{"a\nb", "tab\there", "del\x7f", "\x00", "\x1f", + "100%", "say \"hi\"", "a&b", "a|b", "x>y", "x { if (e.type === "command.run") { - const answer = (body: { result?: unknown; error?: string }) => request(deps.fetch, "POST", "/api/commands/result", { call_id: e.call_id, ...body }).catch(reportError); + const answer = (body: { result?: unknown; error?: string }) => request(deps.fetch, "POST", "/api/commands/result", { call_id: e.call_id, workspace_id: state.get("workspaceId") ?? "", ...body }).catch(reportError); + if (e.workspaces && !e.workspaces.includes(state.get("workspaceId") ?? "")) { + void answer({ error: "the workspace open in this window is not one this credential can reach" }); + return; + } void commands.invoke(e.id, e.params ?? {}).then( (result) => answer({ result }), (err: unknown) => answer({ error: err instanceof Error ? err.message : String(err) }), diff --git a/web/src/engine/types.ts b/web/src/engine/types.ts index 51626ec..93c3274 100644 --- a/web/src/engine/types.ts +++ b/web/src/engine/types.ts @@ -1132,7 +1132,7 @@ export type LiveEvent = | { type: "workspace"; seq: number; workspace_id: string; what: string } | { type: "user"; seq: number; what: string } | { type: "comments"; seq: number; workspace_id: string; page_id: string } - | { type: "command.run"; seq: number; call_id: string; id: string; params: Record } + | { type: "command.run"; seq: number; call_id: string; id: string; params: Record; workspaces?: string[] } | { type: "collection"; seq: number; workspace_id: string; collection_id: string; what: "rows" | "schema" | "views"; ids?: string[]; epoch: number }; export interface Member {