Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions internal/agentlookup/agentlookup.go
Original file line number Diff line number Diff line change
Expand Up @@ -663,22 +663,22 @@ func quote(word string, fish bool) string {
return "'" + strings.ReplaceAll(word, "'", `'"'"'`) + "'"
}

func StartArgv(cmd []string, env []string, platform string) []string {
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...)
return windowsArgv(cmd, env)
}
return append([]string{}, cmd...)
return append([]string{}, cmd...), nil
}
sh := LoginShell(env, platform)
fish := filepath.Base(sh) == "fish"
words := make([]string, len(cmd))
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
}

type Result struct {
Expand All @@ -696,7 +696,10 @@ func Run(cmd []string, env []string, timeout time.Duration, platform string) (Re
if err := Guard(cmd[0]); err != nil {
return Result{}, err
}
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 := exec.CommandContext(ctx, argv[0], argv[1:]...)
Expand All @@ -705,7 +708,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
Expand Down
92 changes: 92 additions & 0 deletions internal/agentlookup/winstart.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package agentlookup

import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
)

var shimTarget = regexp.MustCompile(`"%dp0%\\([^"%]+)"\s+%\*`)

// windowsArgv starts a .cmd or .bat program on Windows. An npm shim is
// resolved to the node or exe it runs, so the arguments reach the program
// as written; any other batch file goes through cmd.exe with only the
// arguments cmd passes on unchanged.
func windowsArgv(cmd []string, env []string) ([]string, error) {
if target := shimArgv(cmd[0], env); target != nil {
return append(target, cmd[1:]...), nil
}
if err := cmdSafe(cmd); err != nil {
return nil, err
}
return append([]string{or(get(env, "COMSPEC"), "cmd.exe"), "/c"}, cmd...), nil
}

func shimArgv(shim string, env []string) []string {
body, err := os.ReadFile(shim)
if err != nil || len(body) > 64<<10 {
return nil
}
m := shimTarget.FindAllSubmatch(body, -1)
if len(m) == 0 {
return nil
}
rel := filepath.FromSlash(strings.ReplaceAll(string(m[len(m)-1][1]), `\`, "/"))
dir := filepath.Dir(shim)
target := filepath.Join(dir, rel)
if !isFile(target) {
return nil
}
switch strings.ToLower(filepath.Ext(target)) {
case ".exe":
return []string{target}
case ".js", ".cjs", ".mjs":
if node := filepath.Join(dir, "node.exe"); isFile(node) {
return []string{node, target}
}
for _, d := range filepath.SplitList(get(env, "PATH")) {
if node := filepath.Join(d, "node.exe"); d != "" && isFile(node) {
return []string{node, target}
}
}
}
return nil
}

func isFile(path string) bool {
st, err := os.Stat(path)
return err == nil && st.Mode().IsRegular()
}

// cmdSafe accepts only words cmd.exe /c passes to the batch file as
// written: no control characters, percent signs or double quotes, and cmd's
// special characters only inside a word that will be quoted (one holding a
// space or tab), and only while the program path itself is not quoted. A
// quoted program path keeps its quotes only when it is the one quoted word,
// so then no other word may be quoted or empty.
func cmdSafe(cmd []string) error {
quotedProgram := strings.ContainsAny(cmd[0], " \t")
if quotedProgram && strings.Contains(cmd[0], "@") {
return fmt.Errorf("argument 0 holds an @ in a path with a space, which cmd cannot run intact")
}
for i, w := range cmd {
if i > 0 && quotedProgram && (w == "" || strings.ContainsAny(w, " \t")) {
return fmt.Errorf("argument %d is empty or holds a space, which cmd cannot pass after a program path with a space", i)
}
for _, r := range w {
if r < 0x20 || r == 0x7f {
return fmt.Errorf("argument %d holds a control character, which cannot reach a batch file intact", i)
}
}
if strings.ContainsAny(w, `%"`) {
return fmt.Errorf("argument %d holds a %% sign or a double quote, which cannot reach a batch file intact", i)
}
quoted := i > 0 && !quotedProgram && strings.ContainsAny(w, " \t")
if !quoted && strings.ContainsAny(w, "&|<>^()!") {
return fmt.Errorf("argument %d holds one of & | < > ^ ( ) !, which cannot reach a batch file intact", i)
}
}
return nil
}
137 changes: 137 additions & 0 deletions internal/agentlookup/winstart_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package agentlookup

import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
)

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\r\nIF EXIST \"%dp0%\\node.exe\" (\r\n SET \"_prog=%dp0%\\node.exe\"\r\n) ELSE (\r\n SET \"_prog=node\"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\nendLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js\" %*\r\n"

func writeFile(t *testing.T, path, body string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}

func TestStartArgvRunsAnNpmShimTargetWithoutCmd(t *testing.T) {
dir := t.TempDir()
shim := filepath.Join(dir, "claude.cmd")
writeFile(t, shim, npmShim)
cli := filepath.Join(dir, "node_modules", "@anthropic-ai", "claude-code", "cli.js")
writeFile(t, cli, "")
node := filepath.Join(dir, "node.exe")
writeFile(t, node, "")
prompt := `explain the "Accept header & fix it 50% done`
got, err := StartArgv([]string{shim, prompt}, []string{"COMSPEC=cmd.exe"}, "windows")
if err != nil {
t.Fatal(err)
}
want := []string{node, cli, prompt}
if !reflect.DeepEqual(got, want) {
t.Fatalf("argv = %q, want %q", got, want)
}
}

func TestStartArgvFindsNodeOnThePathForAnNpmShim(t *testing.T) {
dir := t.TempDir()
shim := filepath.Join(dir, "npm", "claude.cmd")
writeFile(t, shim, npmShim)
cli := filepath.Join(dir, "npm", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
writeFile(t, cli, "")
node := filepath.Join(dir, "nodejs", "node.exe")
writeFile(t, node, "")
env := []string{"PATH=" + filepath.Join(dir, "empty") + string(os.PathListSeparator) + filepath.Dir(node)}
got, err := StartArgv([]string{shim, "hi"}, env, "windows")
if err != nil {
t.Fatal(err)
}
if want := []string{node, cli, "hi"}; !reflect.DeepEqual(got, want) {
t.Fatalf("argv = %q, want %q", got, want)
}
}

func TestStartArgvCmdFallbackRefusesWordsCmdWouldRead(t *testing.T) {
dir := t.TempDir()
shim := filepath.Join(dir, "claude.cmd")
writeFile(t, shim, "@echo off\r\nsomething.exe %*\r\n")
refused := []string{
`explain the "Accept header & fix it`,
"50% done",
"a&b",
"a|b",
"a>b",
"a^b",
"line one\nline two",
"tab\x7f",
`"quoted"`,
}
for _, w := range refused {
if _, err := StartArgv([]string{shim, w}, nil, "windows"); err == nil {
t.Errorf("%q was accepted", w)
}
}
accepted := []string{"hello", "fix this & that", "a (b) <c>", "--resume", "abc-123"}
for _, w := range accepted {
got, err := StartArgv([]string{shim, w}, []string{"COMSPEC=cmd.exe"}, "windows")
if err != nil {
t.Errorf("%q was refused: %v", w, err)
continue
}
if want := []string{"cmd.exe", "/c", shim, w}; !reflect.DeepEqual(got, want) {
t.Errorf("argv = %q, want %q", got, want)
}
}
}

func TestStartArgvCmdFallbackRefusesSpecialsWhenTheProgramPathIsQuoted(t *testing.T) {
dir := filepath.Join(t.TempDir(), "with space")
shim := filepath.Join(dir, "claude.cmd")
writeFile(t, shim, "@echo off\r\nsomething.exe %*\r\n")
if _, err := StartArgv([]string{shim, "fix this & that"}, nil, "windows"); err == nil {
t.Fatal("a special character was accepted after a quoted program path")
}
for _, w := range []string{"fix this and that", "tab\there", ""} {
if _, err := StartArgv([]string{shim, w}, nil, "windows"); err == nil {
t.Errorf("%q was accepted after a quoted program path", w)
}
}
got, err := StartArgv([]string{shim, "--resume", "abc-123"}, []string{"COMSPEC=cmd.exe"}, "windows")
if err != nil {
t.Fatal(err)
}
if want := []string{"cmd.exe", "/c", shim, "--resume", "abc-123"}; !reflect.DeepEqual(got, want) {
t.Fatalf("argv = %q, want %q", got, want)
}
at := filepath.Join(t.TempDir(), "with space", "a@b", "claude.cmd")
writeFile(t, at, "@echo off\r\nsomething.exe %*\r\n")
if _, err := StartArgv([]string{at, "hello"}, nil, "windows"); err == nil {
t.Fatal("an @ in a program path with a space was accepted")
}
}

func TestStartArgvRunsAnExeAsGiven(t *testing.T) {
got, err := StartArgv([]string{`C:\bin\claude.exe`, `a "b" & c`}, nil, "windows")
if err != nil {
t.Fatal(err)
}
if want := []string{`C:\bin\claude.exe`, `a "b" & c`}; !reflect.DeepEqual(got, want) {
t.Fatalf("argv = %q", got)
}
}

func TestStartArgvQuotesForTheLoginShell(t *testing.T) {
got, err := StartArgv([]string{"/bin/claude", "a b"}, []string{"SHELL=/bin/sh"}, "darwin")
if err != nil {
t.Fatal(err)
}
if len(got) != 4 || !strings.HasSuffix(got[3], "'a b'") {
t.Fatalf("argv = %q", got)
}
}
31 changes: 25 additions & 6 deletions internal/server/curl_export.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"strings"
"time"
"unicode"
"unicode/utf8"

"github.com/nodemode-dev/formnet/internal/app"
Expand Down Expand Up @@ -68,7 +69,12 @@ type curlWriter struct {
}

func (c *curlWriter) comment(format string, args ...any) {
line := fmt.Sprintf(format, args...)
line := strings.Map(func(r rune) rune {
if unicode.IsControl(r) {
return ' '
}
return r
}, fmt.Sprintf(format, args...))
if c.shell == "cmd" {
c.b.WriteString("rem " + strings.ReplaceAll(line, "%", "%%") + "\r\n")
return
Expand All @@ -85,6 +91,14 @@ func (c *curlWriter) line(s string) {
}

func (c *curlWriter) arg(v string) string {
if c.shell == "cmd" {
v = strings.Map(func(r rune) rune {
if r != '\t' && unicode.IsControl(r) {
return ' '
}
return r
}, v)
}
switch c.shell {
case "powershell":
q := shell{name: "powershell"}.quote(v)
Expand Down Expand Up @@ -154,15 +168,15 @@ func (c *curlWriter) flow(f flow.Flow, secrets bool) {
dropEncoding = true
}
args := []string{}
method := strings.ToUpper(f.Method)
method := strings.ToUpper(oneLine(f.Method))
switch {
case method == "HEAD":
args = append(args, "-I")
case method == "GET" && len(body) == 0, method == "POST" && len(body) > 0:
default:
args = append(args, "-X "+c.arg(method))
}
args = append(args, c.arg(f.URL))
args = append(args, c.arg(oneLine(f.URL)))
for _, h := range f.Request.Headers {
if curlSkip(h.Name) || (dropEncoding && strings.EqualFold(h.Name, "Content-Encoding")) {
continue
Expand All @@ -171,12 +185,12 @@ func (c *curlWriter) flow(f flow.Flow, secrets bool) {
if !secrets && flow.SecretHeader(h.Name) {
v = flow.Redacted
}
v = strings.NewReplacer("\r", " ", "\n", " ").Replace(v)
v = oneLine(v)
if v == "" {
args = append(args, "-H "+c.arg(h.Name+";"))
args = append(args, "-H "+c.arg(oneLine(h.Name)+";"))
continue
}
args = append(args, "-H "+c.arg(h.Name+": "+v))
args = append(args, "-H "+c.arg(oneLine(h.Name)+": "+v))
}
if len(body) == 0 {
c.command(args, "")
Expand Down Expand Up @@ -211,6 +225,11 @@ func (c *curlWriter) flow(f flow.Flow, secrets bool) {
}
}

// oneLine turns line breaks into spaces, so a value stays on its command's line.
func oneLine(v string) string {
return strings.NewReplacer("\r", " ", "\n", " ").Replace(v)
}

// command writes one curl command, continued over lines where the shell allows it.
func (c *curlWriter) command(args []string, prefix string) {
switch c.shell {
Expand Down
Loading
Loading