Skip to content
85 changes: 79 additions & 6 deletions internal/agentlookup/agentlookup.go
Original file line number Diff line number Diff line change
Expand Up @@ -659,22 +659,92 @@ 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"
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
}

// 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 {
Expand All @@ -689,15 +759,18 @@ 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:]...)
c.Env = env
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
97 changes: 97 additions & 0 deletions internal/agentlookup/windows_start_test.go
Original file line number Diff line number Diff line change
@@ -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<y", "a^b", "(a)", "a!b",
"a & b", "two words (quoted)", "spaced | pipe", "\"a b\"", "50 %", "hi there!"}
for _, word := range words {
if _, err := agentlookup.StartArgv([]string{shim, word}, env, "windows"); !errors.Is(err, agentlookup.ErrUnsafeArg) {
t.Fatalf("%q: err = %v", word, err)
}
}
got, err := agentlookup.StartArgv([]string{shim, "--flag", "plain words, with: punctuation.", "C:\\data\\file.md", ""}, env, "windows")
if err != nil {
t.Fatal(err)
}
if want := []string{"cmd.exe", "/c", shim, "--flag", "plain words, with: punctuation.", "C:\\data\\file.md", ""}; !reflect.DeepEqual(got, want) {
t.Fatalf("argv = %q, want %q", got, want)
}
}

func TestTheCmdFallbackChecksTheProgramPathToo(t *testing.T) {
shim := put(t, filepath.Join(t.TempDir(), "tool(1).cmd"), "@echo off\r\n")
if _, err := agentlookup.StartArgv([]string{shim}, []string{}, "windows"); !errors.Is(err, agentlookup.ErrUnsafeArg) {
t.Fatalf("err = %v", err)
}
}

func TestTheRefusalPointsAtStdinOrAFile(t *testing.T) {
msg := agentlookup.ErrUnsafeArg.Error()
for _, want := range []string{"stdin", "file"} {
if !strings.Contains(msg, want) {
t.Fatalf("message %q does not mention %q", msg, want)
}
}
}

func TestAResolvedShimNeedsNoCharacterCheck(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"), "")
text := "a & b (c) | d ^ e ! 100% \"f\"\n"
got, err := agentlookup.StartArgv([]string{shim, text}, []string{"COMSPEC=cmd.exe"}, "windows")
if err != nil || !reflect.DeepEqual(got, []string{exe, text}) {
t.Fatalf("argv = %q, %v", got, err)
}
}
45 changes: 34 additions & 11 deletions internal/claudecode/bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"time"

"github.com/nodemode-ai/form.md/internal/ids"
"github.com/nodemode-ai/form.md/internal/policy"
)

type CommandSpec struct {
Expand Down Expand Up @@ -45,17 +46,25 @@ type reply struct {
Err string
}

type waiter struct {
ch chan reply
p *policy.Principal
scope map[string]bool
}

type Bridge struct {
hub Sender
mu sync.Mutex
catalog map[string][]CommandSpec
waiting map[string]chan reply
waiting map[string]*waiter
}

func NewBridge(hub Sender) *Bridge {
return &Bridge{hub: hub, catalog: map[string][]CommandSpec{}, waiting: map[string]chan reply{}}
return &Bridge{hub: hub, catalog: map[string][]CommandSpec{}, waiting: map[string]*waiter{}}
}

var ErrOutsideReach = errors.New("the workspace open in this window is not one this credential can reach")

func (b *Bridge) SetCatalogue(userID string, specs []CommandSpec) {
sort.Slice(specs, func(i, j int) bool { return specs[i].ID < specs[j].ID })
b.mu.Lock()
Expand Down Expand Up @@ -89,7 +98,8 @@ func (b *Bridge) Describe(userID, id string) (CommandSpec, bool) {

var ErrNoWindow = errors.New("no form.md window is open for this account: open form.md in a browser or the desktop app and try again")

func (b *Bridge) Run(ctx context.Context, userID, id string, params map[string]any) (json.RawMessage, error) {
func (b *Bridge) Run(ctx context.Context, p *policy.Principal, id string, params map[string]any, workspaces []string) (json.RawMessage, error) {
userID := p.UserID
if _, ok := b.Describe(userID, id); !ok {
if len(b.Catalogue(userID, "")) == 0 {
return nil, ErrNoWindow
Expand All @@ -100,9 +110,15 @@ func (b *Bridge) Run(ctx context.Context, userID, id string, params map[string]a
return nil, ErrNoWindow
}
call := ids.New()
ch := make(chan reply, 1)
wt := &waiter{ch: make(chan reply, 1), p: p}
if workspaces != nil {
wt.scope = make(map[string]bool, len(workspaces))
for _, w := range workspaces {
wt.scope[w] = true
}
}
b.mu.Lock()
b.waiting[call] = ch
b.waiting[call] = wt
b.mu.Unlock()
defer func() {
b.mu.Lock()
Expand All @@ -112,11 +128,15 @@ func (b *Bridge) Run(ctx context.Context, userID, id string, params map[string]a
if params == nil {
params = map[string]any{}
}
b.hub.Send(userID, "command.run", map[string]any{"call_id": call, "id": id, "params": params})
data := map[string]any{"call_id": call, "id": id, "params": params}
if workspaces != nil {
data["workspaces"] = workspaces
}
b.hub.Send(userID, "command.run", data)
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
select {
case r := <-ch:
case r := <-wt.ch:
if r.Err != "" {
return nil, errors.New(r.Err)
}
Expand All @@ -129,15 +149,18 @@ func (b *Bridge) Run(ctx context.Context, userID, id string, params map[string]a
}
}

func (b *Bridge) Answer(call string, result json.RawMessage, errText string) bool {
func (b *Bridge) Answer(call, workspaceID string, result json.RawMessage, errText string) bool {
b.mu.Lock()
ch := b.waiting[call]
wt := b.waiting[call]
b.mu.Unlock()
if ch == nil {
if wt == nil {
return false
}
if wt.scope != nil && (!wt.scope[workspaceID] || !wt.p.Reaches(workspaceID)) {
result, errText = nil, ErrOutsideReach.Error()
}
select {
case ch <- reply{Result: result, Err: errText}:
case wt.ch <- reply{Result: result, Err: errText}:
default:
}
return true
Expand Down
Loading
Loading