From 4e8abe1594afddc52da43907ed335cae40d60e56 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:47:13 -0500 Subject: [PATCH 1/7] fix: keep uploaded workspace fonts during file housekeeping The housekeeping sweep now treats a file listed in a workspace's fonts as in use, so uploaded fonts are no longer removed a day after upload. --- internal/files/files.go | 4 ++- internal/server/files_sweep_test.go | 38 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 internal/server/files_sweep_test.go diff --git a/internal/files/files.go b/internal/files/files.go index 5a0b091..c9335c5 100644 --- a/internal/files/files.go +++ b/internal/files/files.go @@ -504,7 +504,9 @@ func (s *Service) Sweep(ctx context.Context) { AND NOT EXISTS (SELECT 1 FROM pages WHERE cover = 'f:' || files.id OR icon = 'f:' || files.id) AND NOT EXISTS (SELECT 1 FROM doc_refs WHERE kind = 'file' AND target = files.id)) OR (purpose = 'avatar' AND NOT EXISTS (SELECT 1 FROM users WHERE avatar = 'f:' || files.id)) - OR (purpose = 'workspace' AND NOT EXISTS (SELECT 1 FROM workspaces WHERE image = 'f:' || files.id OR icon = 'f:' || files.id)))`, day) + OR (purpose = 'workspace' AND NOT EXISTS (SELECT 1 FROM workspaces WHERE image = 'f:' || files.id OR icon = 'f:' || files.id) + AND NOT EXISTS (SELECT 1 FROM workspaces, json_each(CASE WHEN json_valid(workspaces.fonts) THEN workspaces.fonts ELSE '[]' END) AS f + WHERE json_extract(f.value, '$.file') = 'f:' || files.id)))`, day) if err != nil { s.log.Warn("files: sweep rows", "err", err) return diff --git a/internal/server/files_sweep_test.go b/internal/server/files_sweep_test.go new file mode 100644 index 0000000..81fa7b1 --- /dev/null +++ b/internal/server/files_sweep_test.go @@ -0,0 +1,38 @@ +package server_test + +import ( + "context" + "testing" +) + +func TestSweepKeepsWorkspaceFonts(t *testing.T) { + e := newEnv(t, "") + ctx := context.Background() + db := e.srv.Deps.Store.W + kept := "aaaaaaaaaaaaaaaaaaaaaaaaaa" + orphan := "bbbbbbbbbbbbbbbbbbbbbbbbbb" + stmts := []string{ + `INSERT INTO workspaces (id, name, created_at, updated_at, fonts) VALUES ('wsweep', 'Fonts', 1, 1, '[{"file":"f:` + kept + `","family":"House"}]')`, + `INSERT INTO files (id, workspace_id, purpose, name, ext, mime, size, sha256, created_at) VALUES ('` + kept + `', 'wsweep', 'workspace', 'house.woff2', '.woff2', 'font/woff2', 1, 'x', 1)`, + `INSERT INTO files (id, workspace_id, purpose, name, ext, mime, size, sha256, created_at) VALUES ('` + orphan + `', 'wsweep', 'workspace', 'old.woff2', '.woff2', 'font/woff2', 1, 'x', 1)`, + } + for _, q := range stmts { + if _, err := db.ExecContext(ctx, q); err != nil { + t.Fatalf("%s: %v", q, err) + } + } + e.srv.Files.Sweep(ctx) + count := func(id string) int { + var n int + if err := e.srv.Deps.Store.R.QueryRowContext(ctx, "SELECT COUNT(*) FROM files WHERE id = ?", id).Scan(&n); err != nil { + t.Fatal(err) + } + return n + } + if count(kept) != 1 { + t.Fatal("a font listed in the workspace fonts was removed") + } + if count(orphan) != 0 { + t.Fatal("an unused workspace file was kept") + } +} From 1a993597543f0c013b8719723b5d0f627c58eb4e Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:48:45 -0500 Subject: [PATCH 2/7] fix: limit agent window commands to the credential's workspaces Window commands run for an API token or MCP grant now carry the workspaces that credential may reach, after workspace agent access is applied. The window refuses the command when the workspace it shows is not in that list, and the server refuses it when the list is empty. --- internal/claudecode/bridge.go | 8 +++- internal/claudecode/bridge_test.go | 72 ++++++++++++++++++++++++++++++ internal/claudecode/module.go | 23 +++++++++- internal/server/server.go | 11 +++++ web/src/engine/index.ts | 4 ++ web/src/engine/types.ts | 2 +- 6 files changed, 116 insertions(+), 4 deletions(-) create mode 100644 internal/claudecode/bridge_test.go diff --git a/internal/claudecode/bridge.go b/internal/claudecode/bridge.go index fa5189b..a7253e1 100644 --- a/internal/claudecode/bridge.go +++ b/internal/claudecode/bridge.go @@ -89,7 +89,7 @@ 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, userID, id string, params map[string]any, workspaces []string) (json.RawMessage, error) { if _, ok := b.Describe(userID, id); !ok { if len(b.Catalogue(userID, "")) == 0 { return nil, ErrNoWindow @@ -112,7 +112,11 @@ 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 { diff --git a/internal/claudecode/bridge_test.go b/internal/claudecode/bridge_test.go new file mode 100644 index 0000000..51bd085 --- /dev/null +++ b/internal/claudecode/bridge_test.go @@ -0,0 +1,72 @@ +package claudecode + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "sync" + "testing" + + "github.com/nodemode-ai/form.md/internal/policy" +) + +type windowHub struct { + mu sync.Mutex + bridge *Bridge + sent []map[string]any +} + +func (h *windowHub) Online(string) bool { return true } + +func (h *windowHub) Send(_, _ string, data map[string]any) { + h.mu.Lock() + h.sent = append(h.sent, data) + h.mu.Unlock() + go h.bridge.Answer(data["call_id"].(string), json.RawMessage(`{"ok":true}`), "") +} + +func newWindowService(reach func(context.Context, *policy.Principal) ([]string, error)) (*Service, *windowHub) { + hub := &windowHub{} + s := &Service{Bridge: NewBridge(hub)} + hub.bridge = s.Bridge + s.Bridge.SetCatalogue("u1", []CommandSpec{{ID: "page.new", Mutates: true}}) + if reach != nil { + s.SetReach(reach) + } + return s, hub +} + +func TestWindowCommandsCarryTheCredentialsWorkspaces(t *testing.T) { + s, hub := newWindowService(func(context.Context, *policy.Principal) ([]string, error) { return []string{"w1"}, nil }) + agent := &policy.Principal{UserID: "u1", Kind: policy.KindOAuth, Scope: "write", Workspaces: map[string]bool{"w1": true}} + if _, err := s.RunCommand(context.Background(), agent, "page.new", nil); err != nil { + t.Fatal(err) + } + if got := hub.sent[0]["workspaces"]; !reflect.DeepEqual(got, []string{"w1"}) { + t.Fatalf("workspaces sent to the window: %v", got) + } + session := &policy.Principal{UserID: "u1", Kind: policy.KindSession, Scope: "write"} + if _, err := s.RunCommand(context.Background(), session, "page.new", nil); err != nil { + t.Fatal(err) + } + if _, ok := hub.sent[1]["workspaces"]; ok { + t.Fatal("a session command was limited to a workspace list") + } +} + +func TestWindowCommandsRefusedWithoutAReachableWorkspace(t *testing.T) { + agent := &policy.Principal{UserID: "u1", Kind: policy.KindToken, Scope: "write"} + for name, reach := range map[string]func(context.Context, *policy.Principal) ([]string, error){ + "none reachable": func(context.Context, *policy.Principal) ([]string, error) { return []string{}, nil }, + "not wired": nil, + } { + s, hub := newWindowService(reach) + if _, err := s.RunCommand(context.Background(), agent, "page.new", nil); !errors.Is(err, ErrNoReach) { + t.Fatalf("%s: err = %v", name, err) + } + if len(hub.sent) != 0 { + t.Fatalf("%s: the command reached the window", name) + } + } +} diff --git a/internal/claudecode/module.go b/internal/claudecode/module.go index e016f55..15caa38 100644 --- a/internal/claudecode/module.go +++ b/internal/claudecode/module.go @@ -26,6 +26,7 @@ type Service struct { Chats *Chats addr string dataDir string + reach func(ctx context.Context, p *policy.Principal) ([]string, error) mu sync.Mutex attached map[*attachment]bool @@ -686,12 +687,32 @@ func (m module) Mount(r *httpx.Router, d *app.Deps) error { return nil } +func (s *Service) SetReach(fn func(ctx context.Context, p *policy.Principal) ([]string, error)) { + s.reach = fn +} + +var ErrNoReach = errors.New("this credential cannot reach a workspace the window can show") + func (s *Service) RunCommand(ctx context.Context, p *policy.Principal, id string, params map[string]any) (json.RawMessage, error) { spec, ok := s.Bridge.Describe(p.UserID, id) if ok && spec.Mutates && !p.CanWrite() { return nil, fmt.Errorf("%s changes the workspace and this credential is read-only", id) } - return s.Bridge.Run(ctx, p.UserID, id, params) + var scope []string + if !p.IsSession() { + if s.reach == nil { + return nil, ErrNoReach + } + ws, err := s.reach(ctx, p) + if err != nil { + return nil, err + } + if len(ws) == 0 { + return nil, ErrNoReach + } + scope = ws + } + return s.Bridge.Run(ctx, p.UserID, id, params, scope) } func (s *Service) CatalogueFor(p *policy.Principal, filter string) any { diff --git a/internal/server/server.go b/internal/server/server.go index 193bf6b..9d24824 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -186,6 +186,17 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S packer := contextpack.New(contextpack.Deps{Store: st, Gate: gate, Pages: pages, Docs: docs, Search: finder, Policy: packPolicy, Log: log, Family: fam}) runs.Handle(contextpack.UndoKind, packer.Undo) harness := claudecode.New(authSvc, hub, cfg.Addr, cfg.DataDir) + harness.SetReach(func(ctx context.Context, p *policy.Principal) ([]string, error) { + list, _, err := ws.List(ctx, p) + if err != nil { + return nil, err + } + out := make([]string, 0, len(list)) + for _, w := range list { + out = append(out, w.ID) + } + return out, nil + }) agents := mcp.New(mcp.Deps{Store: st, Auth: authSvc, Gate: gate, Pages: pages, Docs: docs, Cols: cols, Search: finder, Comments: comments, Workspace: ws, Runs: runs, Context: packer, Skill: skill, Window: harness, Version: app.Version, Log: log, Family: fam}) crew := agent.New(agent.Deps{Store: st, Auth: authSvc, Gate: gate, AI: brain, Tools: agents, Docs: docs, Cols: cols, Runs: runs, Context: packer, Log: log}) hooks.UsePages(pages) diff --git a/web/src/engine/index.ts b/web/src/engine/index.ts index 5ed69df..f2e2bfd 100644 --- a/web/src/engine/index.ts +++ b/web/src/engine/index.ts @@ -300,6 +300,10 @@ export function createEngine(deps: EngineDeps): Engine { const dispatch = (e: LiveEvent) => { 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); + 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 { From 510df73b03aa95633cfe243cf7bc31eae2eeef59 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:50:50 -0500 Subject: [PATCH 3/7] fix: restore in place on Windows while the data folder is locked Windows will not rename a folder that holds an open file, and restore keeps its lock file open inside the data folder. Restore now swaps the folder's contents in place there, as it already does for mount points. --- internal/ops/backup.go | 7 +++- internal/ops/backup_test.go | 65 +++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 internal/ops/backup_test.go diff --git a/internal/ops/backup.go b/internal/ops/backup.go index a422b53..3c76030 100644 --- a/internal/ops/backup.go +++ b/internal/ops/backup.go @@ -13,6 +13,7 @@ import ( "net/url" "os" "path/filepath" + "runtime" "strings" "time" @@ -203,17 +204,21 @@ func Backup(ctx context.Context, dataDir, keyFile, out string, flush func() bool return m, nil } +var lockPinsDir = runtime.GOOS == "windows" + func Restore(ctx context.Context, dataDir, keyFile, archive string) (string, *Manifest, error) { dataDir, err := filepath.Abs(dataDir) if err != nil { return "", nil, err } + locked := false if _, err := os.Stat(dataDir); err == nil { unlock, err := Lock(dataDir) if err != nil { return "", nil, err } defer unlock() + locked = true } parent := filepath.Dir(dataDir) if err := os.MkdirAll(parent, 0o755); err != nil { @@ -224,7 +229,7 @@ func Restore(ctx context.Context, dataDir, keyFile, archive string) (string, *Ma refPath = dataDir } uid, gid, owned := ownerOf(refPath) - inPlace := isMount(dataDir) + inPlace := isMount(dataDir) || (locked && lockPinsDir) var stage string if !inPlace { stage, err = os.MkdirTemp(parent, ".form-md-restore-*") diff --git a/internal/ops/backup_test.go b/internal/ops/backup_test.go new file mode 100644 index 0000000..0f1b38c --- /dev/null +++ b/internal/ops/backup_test.go @@ -0,0 +1,65 @@ +package ops + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/nodemode-ai/form.md/internal/store" +) + +func TestRestoreKeepsTheFolderWhenTheLockPinsIt(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + dataDir := filepath.Join(root, "data") + st, err := store.Open(ctx, dataDir, nil) + if err != nil { + t.Fatal(err) + } + if _, err := st.Bootstrap(ctx, "v0.0.0-test"); err != nil { + t.Fatal(err) + } + if err := st.Close(); err != nil { + t.Fatal(err) + } + archive := filepath.Join(root, "backup.tgz") + if _, err := Backup(ctx, dataDir, "", archive, func() bool { return false }); err != nil { + t.Fatal(err) + } + marker := filepath.Join(dataDir, "marker.txt") + if err := os.WriteFile(marker, []byte("before"), 0o600); err != nil { + t.Fatal(err) + } + before, err := os.Stat(dataDir) + if err != nil { + t.Fatal(err) + } + prev := lockPinsDir + lockPinsDir = true + t.Cleanup(func() { lockPinsDir = prev }) + old, _, err := Restore(ctx, dataDir, "", archive) + if err != nil { + t.Fatal(err) + } + after, err := os.Stat(dataDir) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(before, after) { + t.Fatal("the data folder was replaced instead of restored in place") + } + if !strings.HasPrefix(old, dataDir+string(filepath.Separator)) { + t.Fatalf("previous data kept at %q, want inside the data folder", old) + } + if _, err := os.Stat(filepath.Join(old, "marker.txt")); err != nil { + t.Fatalf("previous data not kept: %v", err) + } + if _, err := os.Stat(marker); !os.IsNotExist(err) { + t.Fatal("previous data left in the restored folder") + } + if !store.HasData(dataDir) { + t.Fatal("no restored database") + } +} From b4222ff70ab7cd0186f67a3a430234e48a5d9f0a Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:35:01 -0500 Subject: [PATCH 4/7] fix: apply credential limits to emergency access and window reach The workspace list now applies the credential's workspaces and the workspace agent setting to emergency access entries as well. The workspaces sent with a window command also leave out emergency access entries for any credential other than a normal sign-in. --- internal/server/server.go | 12 +---- internal/server/window_reach_test.go | 72 ++++++++++++++++++++++++++++ internal/workspace/workspace.go | 21 ++++++++ 3 files changed, 94 insertions(+), 11 deletions(-) create mode 100644 internal/server/window_reach_test.go diff --git a/internal/server/server.go b/internal/server/server.go index 9d24824..1f94c02 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -186,17 +186,7 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S packer := contextpack.New(contextpack.Deps{Store: st, Gate: gate, Pages: pages, Docs: docs, Search: finder, Policy: packPolicy, Log: log, Family: fam}) runs.Handle(contextpack.UndoKind, packer.Undo) harness := claudecode.New(authSvc, hub, cfg.Addr, cfg.DataDir) - harness.SetReach(func(ctx context.Context, p *policy.Principal) ([]string, error) { - list, _, err := ws.List(ctx, p) - if err != nil { - return nil, err - } - out := make([]string, 0, len(list)) - for _, w := range list { - out = append(out, w.ID) - } - return out, nil - }) + harness.SetReach(ws.Reachable) agents := mcp.New(mcp.Deps{Store: st, Auth: authSvc, Gate: gate, Pages: pages, Docs: docs, Cols: cols, Search: finder, Comments: comments, Workspace: ws, Runs: runs, Context: packer, Skill: skill, Window: harness, Version: app.Version, Log: log, Family: fam}) crew := agent.New(agent.Deps{Store: st, Auth: authSvc, Gate: gate, AI: brain, Tools: agents, Docs: docs, Cols: cols, Runs: runs, Context: packer, Log: log}) hooks.UsePages(pages) diff --git a/internal/server/window_reach_test.go b/internal/server/window_reach_test.go new file mode 100644 index 0000000..6315f8a --- /dev/null +++ b/internal/server/window_reach_test.go @@ -0,0 +1,72 @@ +package server_test + +import ( + "context" + "testing" + + "github.com/nodemode-ai/form.md/internal/policy" + "github.com/nodemode-ai/form.md/internal/store" +) + +func TestEmergencyAccessFollowsTheCredentialLimits(t *testing.T) { + e := newEnv(t, "") + owner := e.setupOwner() + home := owner.workspaceID() + ctx := context.Background() + db := e.srv.Deps.Store.W + var uid string + if err := e.srv.Deps.Store.R.QueryRowContext(ctx, "SELECT id FROM users WHERE role = 'owner'").Scan(&uid); err != nil { + t.Fatal(err) + } + later := store.NowMS() + 3600_000 + if _, err := db.ExecContext(ctx, `INSERT INTO workspaces (id, name, created_at, updated_at, agent_access) VALUES ('wopen', 'Open', 1, 1, 'open'), ('wshut', 'Shut', 1, 1, 'closed')`); err != nil { + t.Fatal(err) + } + if _, err := db.ExecContext(ctx, `INSERT INTO break_glass (id, user_id, workspace_id, reason, created_at, expires_at) VALUES ('bg1', ?, 'wopen', 'check', 1, ?), ('bg2', ?, 'wshut', 'check', 1, ?)`, uid, later, uid, later); err != nil { + t.Fatal(err) + } + listed := func(p *policy.Principal) map[string]bool { + list, _, err := e.srv.Work.List(ctx, p) + if err != nil { + t.Fatal(err) + } + out := map[string]bool{} + for _, w := range list { + out[w.ID] = true + } + return out + } + reach := func(p *policy.Principal) map[string]bool { + ids, err := e.srv.Work.Reachable(ctx, p) + if err != nil { + t.Fatal(err) + } + out := map[string]bool{} + for _, id := range ids { + out[id] = true + } + return out + } + session := &policy.Principal{UserID: uid, Role: "owner", Kind: policy.KindSession, Scope: "write"} + every := &policy.Principal{UserID: uid, Role: "owner", Kind: policy.KindToken, Scope: "write", AllWorkspaces: true} + one := &policy.Principal{UserID: uid, Role: "owner", Kind: policy.KindToken, Scope: "write", Workspaces: map[string]bool{home: true}} + + if got := listed(session); !got["wopen"] || !got["wshut"] { + t.Fatalf("session list: %v", got) + } + if got := listed(every); !got["wopen"] || got["wshut"] { + t.Fatalf("token list ignores the agent setting: %v", got) + } + if got := listed(one); got["wopen"] || got["wshut"] || !got[home] { + t.Fatalf("token list ignores the token's workspaces: %v", got) + } + if got := reach(every); got["wopen"] || got["wshut"] || !got[home] { + t.Fatalf("window reach for a token: %v", got) + } + if got := reach(one); len(got) != 1 || !got[home] { + t.Fatalf("window reach for a one-workspace token: %v", got) + } + if got := reach(session); !got["wopen"] || !got[home] { + t.Fatalf("window reach for the session: %v", got) + } +} diff --git a/internal/workspace/workspace.go b/internal/workspace/workspace.go index 3767096..ea59393 100644 --- a/internal/workspace/workspace.go +++ b/internal/workspace/workspace.go @@ -173,6 +173,9 @@ func (s *Service) List(ctx context.Context, p *policy.Principal) ([]*Workspace, if err != nil { return nil, 0, err } + if !p.Reaches(w.ID) || !policy.AgentAllowed(p, w.AgentAccess) { + continue + } w.Role, w.BreakGlass, w.ProposalWaits = "viewer", true, false out = append(out, w) } @@ -203,6 +206,24 @@ func (s *Service) List(ctx context.Context, p *policy.Principal) ([]*Workspace, return out, withheld, guest.Err() } +func (s *Service) Reachable(ctx context.Context, p *policy.Principal) ([]string, error) { + list, _, err := s.List(ctx, p) + if err != nil { + return nil, err + } + out := make([]string, 0, len(list)) + for _, w := range list { + if !p.Reaches(w.ID) || !policy.AgentAllowed(p, w.AgentAccess) { + continue + } + if w.BreakGlass && !p.IsSession() { + continue + } + out = append(out, w.ID) + } + return out, nil +} + func (s *Service) Get(ctx context.Context, p *policy.Principal, id string) (*Workspace, policy.Access, error) { a, err := s.gate.Workspace(ctx, p, id) if err != nil { From 53a3cb0c843789ebbcfa1fa2dee17d7be7866e74 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:35:01 -0500 Subject: [PATCH 5/7] fix: check the window's workspace on the server for agent commands The window now reports the workspace it shows with each command result, and the server refuses the result for an API token or MCP grant when that workspace is outside the credential's list. Account, admin, terminal and new workspace commands are kept to the signed-in person: they are left out of the catalogue and refused for other credentials. --- internal/claudecode/bridge.go | 39 ++++++++++++----- internal/claudecode/bridge_test.go | 67 ++++++++++++++++++++++++++---- internal/claudecode/module.go | 58 +++++++++++++++++++++----- web/src/engine/index.ts | 2 +- 4 files changed, 136 insertions(+), 30 deletions(-) diff --git a/internal/claudecode/bridge.go b/internal/claudecode/bridge.go index a7253e1..437036a 100644 --- a/internal/claudecode/bridge.go +++ b/internal/claudecode/bridge.go @@ -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 { @@ -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() @@ -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, workspaces []string) (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 @@ -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() @@ -120,7 +136,7 @@ func (b *Bridge) Run(ctx context.Context, userID, id string, params map[string]a 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) } @@ -133,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 diff --git a/internal/claudecode/bridge_test.go b/internal/claudecode/bridge_test.go index 51bd085..90b663c 100644 --- a/internal/claudecode/bridge_test.go +++ b/internal/claudecode/bridge_test.go @@ -12,9 +12,10 @@ import ( ) type windowHub struct { - mu sync.Mutex - bridge *Bridge - sent []map[string]any + mu sync.Mutex + bridge *Bridge + workspace string + sent []map[string]any } func (h *windowHub) Online(string) bool { return true } @@ -22,23 +23,26 @@ func (h *windowHub) Online(string) bool { return true } func (h *windowHub) Send(_, _ string, data map[string]any) { h.mu.Lock() h.sent = append(h.sent, data) + ws := h.workspace h.mu.Unlock() - go h.bridge.Answer(data["call_id"].(string), json.RawMessage(`{"ok":true}`), "") + go h.bridge.Answer(data["call_id"].(string), ws, json.RawMessage(`{"ok":true}`), "") } func newWindowService(reach func(context.Context, *policy.Principal) ([]string, error)) (*Service, *windowHub) { - hub := &windowHub{} + hub := &windowHub{workspace: "w1"} s := &Service{Bridge: NewBridge(hub)} hub.bridge = s.Bridge - s.Bridge.SetCatalogue("u1", []CommandSpec{{ID: "page.new", Mutates: true}}) + s.Bridge.SetCatalogue("u1", []CommandSpec{{ID: "page.new", Mutates: true}, {ID: "account.signOut", Mutates: true}, {ID: "dock.newTerminal", Mutates: true}, {ID: "workspace.new"}}) if reach != nil { s.SetReach(reach) } return s, hub } +func reachW1(context.Context, *policy.Principal) ([]string, error) { return []string{"w1"}, nil } + func TestWindowCommandsCarryTheCredentialsWorkspaces(t *testing.T) { - s, hub := newWindowService(func(context.Context, *policy.Principal) ([]string, error) { return []string{"w1"}, nil }) + s, hub := newWindowService(reachW1) agent := &policy.Principal{UserID: "u1", Kind: policy.KindOAuth, Scope: "write", Workspaces: map[string]bool{"w1": true}} if _, err := s.RunCommand(context.Background(), agent, "page.new", nil); err != nil { t.Fatal(err) @@ -58,8 +62,9 @@ func TestWindowCommandsCarryTheCredentialsWorkspaces(t *testing.T) { func TestWindowCommandsRefusedWithoutAReachableWorkspace(t *testing.T) { agent := &policy.Principal{UserID: "u1", Kind: policy.KindToken, Scope: "write"} for name, reach := range map[string]func(context.Context, *policy.Principal) ([]string, error){ - "none reachable": func(context.Context, *policy.Principal) ([]string, error) { return []string{}, nil }, - "not wired": nil, + "none reachable": func(context.Context, *policy.Principal) ([]string, error) { return []string{}, nil }, + "not wired": nil, + "outside credential": reachW1, } { s, hub := newWindowService(reach) if _, err := s.RunCommand(context.Background(), agent, "page.new", nil); !errors.Is(err, ErrNoReach) { @@ -70,3 +75,47 @@ func TestWindowCommandsRefusedWithoutAReachableWorkspace(t *testing.T) { } } } + +func TestWindowResultRefusedWhenTheWindowShowsAnotherWorkspace(t *testing.T) { + s, hub := newWindowService(func(context.Context, *policy.Principal) ([]string, error) { return []string{"w1", "w2"}, nil }) + agent := &policy.Principal{UserID: "u1", Kind: policy.KindToken, Scope: "write", Workspaces: map[string]bool{"w1": true, "w2": true}} + for _, shown := range []string{"w3", ""} { + hub.mu.Lock() + hub.workspace = shown + hub.mu.Unlock() + if _, err := s.RunCommand(context.Background(), agent, "page.new", nil); err == nil || err.Error() != ErrOutsideReach.Error() { + t.Fatalf("window on %q: err = %v", shown, err) + } + } + session := &policy.Principal{UserID: "u1", Kind: policy.KindSession, Scope: "write"} + if _, err := s.RunCommand(context.Background(), session, "page.new", nil); err != nil { + t.Fatalf("session command with the window on another workspace: %v", err) + } +} + +func TestAccountAndAdminCommandsStayWithTheSignedInPerson(t *testing.T) { + s, hub := newWindowService(reachW1) + agent := &policy.Principal{UserID: "u1", Kind: policy.KindToken, Scope: "write", AllWorkspaces: true} + for _, id := range []string{"account.signOut", "dock.newTerminal", "workspace.new"} { + if _, err := s.RunCommand(context.Background(), agent, id, nil); err == nil { + t.Fatalf("%s ran for an agent credential", id) + } + if _, ok := s.DescribeFor(agent, id); ok { + t.Fatalf("%s described to an agent credential", id) + } + } + if len(hub.sent) != 0 { + t.Fatal("a window-only command reached the window") + } + listed := s.CatalogueFor(agent, "").([]CommandSpec) + if len(listed) != 1 || listed[0].ID != "page.new" { + t.Fatalf("agent catalogue: %v", listed) + } + session := &policy.Principal{UserID: "u1", Kind: policy.KindSession, Scope: "write"} + if n := len(s.CatalogueFor(session, "").([]CommandSpec)); n != 4 { + t.Fatalf("session catalogue has %d commands", n) + } + if _, err := s.RunCommand(context.Background(), session, "account.signOut", nil); err != nil { + t.Fatal(err) + } +} diff --git a/internal/claudecode/module.go b/internal/claudecode/module.go index 15caa38..cea4486 100644 --- a/internal/claudecode/module.go +++ b/internal/claudecode/module.go @@ -645,11 +645,11 @@ func (m module) Mount(r *httpx.Router, d *app.Deps) error { return nil })) r.HandleFunc("GET /api/commands", a.Require(func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { - httpx.JSON(w, http.StatusOK, map[string]any{"commands": s.Bridge.Catalogue(p.UserID, r.URL.Query().Get("q"))}) + httpx.JSON(w, http.StatusOK, map[string]any{"commands": s.CatalogueFor(p, r.URL.Query().Get("q"))}) return nil })) r.HandleFunc("GET /api/commands/{id}", a.Require(func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { - c, ok := s.Bridge.Describe(p.UserID, r.PathValue("id")) + c, ok := s.DescribeFor(p, r.PathValue("id")) if !ok { return httpx.Fail(http.StatusNotFound, "not_found", "no such command in the open window") } @@ -674,14 +674,15 @@ func (m module) Mount(r *httpx.Router, d *app.Deps) error { })) r.HandleFunc("POST /api/commands/result", a.RequireSession(func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { var in struct { - CallID string `json:"call_id"` - Result json.RawMessage `json:"result"` - Error string `json:"error"` + CallID string `json:"call_id"` + WorkspaceID string `json:"workspace_id"` + Result json.RawMessage `json:"result"` + Error string `json:"error"` } if err := httpx.Decode(r, &in); err != nil { return err } - httpx.JSON(w, http.StatusOK, map[string]any{"delivered": s.Bridge.Answer(in.CallID, in.Result, in.Error)}) + httpx.JSON(w, http.StatusOK, map[string]any{"delivered": s.Bridge.Answer(in.CallID, in.WorkspaceID, in.Result, in.Error)}) return nil })) return nil @@ -693,7 +694,26 @@ func (s *Service) SetReach(fn func(ctx context.Context, p *policy.Principal) ([] var ErrNoReach = errors.New("this credential cannot reach a workspace the window can show") +var sessionOnlyPrefixes = []string{"account.", "admin.", "prefs.", "dock.", "agent."} + +var sessionOnlyCommands = map[string]bool{"workspace.new": true} + +func sessionOnly(id string) bool { + if sessionOnlyCommands[id] { + return true + } + for _, pre := range sessionOnlyPrefixes { + if strings.HasPrefix(id, pre) { + return true + } + } + return false +} + func (s *Service) RunCommand(ctx context.Context, p *policy.Principal, id string, params map[string]any) (json.RawMessage, error) { + if !p.IsSession() && sessionOnly(id) { + return nil, fmt.Errorf("%s works only for the person signed in to the window", id) + } spec, ok := s.Bridge.Describe(p.UserID, id) if ok && spec.Mutates && !p.CanWrite() { return nil, fmt.Errorf("%s changes the workspace and this credential is read-only", id) @@ -707,19 +727,37 @@ func (s *Service) RunCommand(ctx context.Context, p *policy.Principal, id string if err != nil { return nil, err } - if len(ws) == 0 { + scope = make([]string, 0, len(ws)) + for _, w := range ws { + if p.Reaches(w) { + scope = append(scope, w) + } + } + if len(scope) == 0 { return nil, ErrNoReach } - scope = ws } - return s.Bridge.Run(ctx, p.UserID, id, params, scope) + return s.Bridge.Run(ctx, p, id, params, scope) } func (s *Service) CatalogueFor(p *policy.Principal, filter string) any { - return s.Bridge.Catalogue(p.UserID, filter) + list := s.Bridge.Catalogue(p.UserID, filter) + if p.IsSession() { + return list + } + out := make([]CommandSpec, 0, len(list)) + for _, c := range list { + if !sessionOnly(c.ID) { + out = append(out, c) + } + } + return out } func (s *Service) DescribeFor(p *policy.Principal, id string) (any, bool) { + if !p.IsSession() && sessionOnly(id) { + return nil, false + } return s.Bridge.Describe(p.UserID, id) } diff --git a/web/src/engine/index.ts b/web/src/engine/index.ts index f2e2bfd..3436e7d 100644 --- a/web/src/engine/index.ts +++ b/web/src/engine/index.ts @@ -299,7 +299,7 @@ export function createEngine(deps: EngineDeps): Engine { let needsLoad = false; const dispatch = (e: LiveEvent) => { 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; From 48404a9325df1476622f87cff099492930ad2d1c Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:35:01 -0500 Subject: [PATCH 6/7] fix: start Windows script shims without cmd.exe where possible A .cmd shim that points at a script or program is now resolved to that target and run directly with node or the program itself. When it cannot be resolved, words with control characters, percent signs or double quotes, and words without spaces that hold cmd.exe operators, are refused before cmd.exe is started. --- internal/agentlookup/agentlookup.go | 83 ++++++++++++++++++++-- internal/agentlookup/windows_start_test.go | 66 +++++++++++++++++ internal/claudecode/chat.go | 2 +- internal/claudecode/claude.go | 2 +- internal/claudecode/module.go | 20 +++++- 5 files changed, 162 insertions(+), 11 deletions(-) create mode 100644 internal/agentlookup/windows_start_test.go diff --git a/internal/agentlookup/agentlookup.go b/internal/agentlookup/agentlookup.go index 4cfa143..cf362cd 100644 --- a/internal/agentlookup/agentlookup.go +++ b/internal/agentlookup/agentlookup.go @@ -659,14 +659,28 @@ 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: leave out control characters, %, double quotes and & | < > ^ ( ) ! in words without spaces") + shimTarget = regexp.MustCompile(`"(?:%~dp0%?|%dp0%)\\?([^"%]+)"\s+%\*`) + controlChars = regexp.MustCompile(`[\x00-\x1f\x7f]`) +) + +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 +688,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 +} + +func cmdSafe(word string) bool { + if controlChars.MatchString(word) || strings.ContainsAny(word, `%"`) { + return false + } + return strings.ContainsAny(word, " \t") || !strings.ContainsAny(word, "&|<>^()!") +} + +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 +757,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 +768,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..d9ac94a --- /dev/null +++ b/internal/agentlookup/windows_start_test.go @@ -0,0 +1,66 @@ +package agentlookup_test + +import ( + "errors" + "path/filepath" + "reflect" + "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"} + for _, word := range []string{"a\nb", "tab\there\x7f", "100%", "say \"hi\"", "a&b", "a|b", "x>y", "x Date: Sun, 29 Nov 2026 12:12:32 -0500 Subject: [PATCH 7/7] fix: refuse every cmd.exe special character for Windows shim fallback When a script shim cannot be resolved to the program it wraps and cmd.exe is still used, any word holding a control character or one of & | < > ^ ( ) ! % " is refused, with or without spaces, since quoting does not keep cmd.exe from reading them. The message points at stdin or a file for long text. Tests cover the resolved and fallback paths and check that the fixed launch words still pass. --- internal/agentlookup/agentlookup.go | 12 ++++--- internal/agentlookup/windows_start_test.go | 37 ++++++++++++++++++++-- internal/claudecode/windows_note_test.go | 21 ++++++++++++ 3 files changed, 62 insertions(+), 8 deletions(-) create mode 100644 internal/claudecode/windows_note_test.go diff --git a/internal/agentlookup/agentlookup.go b/internal/agentlookup/agentlookup.go index cf362cd..a2235a6 100644 --- a/internal/agentlookup/agentlookup.go +++ b/internal/agentlookup/agentlookup.go @@ -660,11 +660,13 @@ func quote(word string, fish bool) string { } var ( - ErrUnsafeArg = errors.New("this text cannot be passed to the program on Windows: leave out control characters, %, double quotes and & | < > ^ ( ) ! in words without spaces") + 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) { @@ -691,11 +693,11 @@ func StartArgv(cmd []string, env []string, platform string) ([]string, error) { 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 { - if controlChars.MatchString(word) || strings.ContainsAny(word, `%"`) { - return false - } - return strings.ContainsAny(word, " \t") || !strings.ContainsAny(word, "&|<>^()!") + return !controlChars.MatchString(word) && !strings.ContainsAny(word, cmdSpecial) } func resolveShim(shim string, env []string) []string { diff --git a/internal/agentlookup/windows_start_test.go b/internal/agentlookup/windows_start_test.go index d9ac94a..6dfe477 100644 --- a/internal/agentlookup/windows_start_test.go +++ b/internal/agentlookup/windows_start_test.go @@ -4,6 +4,7 @@ import ( "errors" "path/filepath" "reflect" + "strings" "testing" "github.com/nodemode-ai/form.md/internal/agentlookup" @@ -51,16 +52,46 @@ func TestAWindowsShimToAProgramRunsTheProgram(t *testing.T) { func TestTheCmdFallbackRefusesTextCmdWouldReadAsCommands(t *testing.T) { shim := put(t, filepath.Join(t.TempDir(), "tool.bat"), "@echo off\r\n") env := []string{"COMSPEC=cmd.exe"} - for _, word := range []string{"a\nb", "tab\there\x7f", "100%", "say \"hi\"", "a&b", "a|b", "x>y", "xy", "x