Skip to content
7 changes: 7 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ linters:
disabled: true
exclusions:
generated: lax
# 一次性验证脚本,不进版本库(见 docs/verification.md);不排除的话,本地留着的脚本会让提交前的
# `golangci-lint run ./...` 失败,而 CI 上看不到它们。
paths:
- e2e/scratch
presets:
- comments
- common-false-positives
Expand All @@ -46,6 +50,9 @@ formatters:
enable:
- gofmt
- goimports
exclusions:
paths:
- e2e/scratch
settings:
goimports:
local-prefixes:
Expand Down
2 changes: 1 addition & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ command line can use the skill in [`../skills/sctl/`](../skills/sctl/SKILL.md).
| `sctl service install\|uninstall\|start\|stop\|restart\|enable\|disable\|status` | Run `sctl serve` in the background as a user service; see [Background service](#background-service-sctl-service). |
| `sctl connect` | Open a one-time enrollment window for ScriptCat or sctl Browser. |
| `sctl mcp [--name <label>]` | Serve ScriptCat and sctl Browser tools over stdio MCP. |
| `sctl status` | Show daemon status and every paired ScriptCat and sctl Browser instance with its online state. `-o json` keeps `extConnected` (true when any ScriptCat instance is online) and adds a `scriptcats` list. |
| `sctl status` | Show daemon status and every paired ScriptCat and sctl Browser instance with its online state. `-o json` keeps `extConnected` (true when any ScriptCat instance is online) and adds a `scriptcats` list. Reports `daemon is not running` (exit 0) only when nothing listens at the address. Exits 3 and says why when something listens there but does not answer as an sctl daemon (another program, or a proxy or security software intercepting local connections), or when the daemon answers but its control token is not in this data directory. |
| `sctl scriptcats [list]` / `sctl scriptcats forget <name\|id>` | List paired ScriptCat instances (name, ID, status, product, versions; a legacy ScriptCat appears as `scriptcat` with no ID while `pairing.key` exists), or forget one. Forgetting deletes its key and disconnects it; `forget scriptcat` deletes `pairing.key`. |

### ScriptCat scripts
Expand Down
3 changes: 3 additions & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ golangci-lint fmt ./... # gofmt + goimports (with this repo's prefix grouping)
golangci-lint run ./...
```

Both commands skip `e2e/scratch/`, where git-ignored one-shot verification scripts live (see
[`verification.md`](./verification.md)), so leftovers there do not fail the local run.

When bumping the version, update `GOLANGCI_LINT_VERSION` in `.github/workflows/test.yaml` to match.

Use the global `--data-dir <path>` flag or `SCTL_DATA_DIR` environment variable to override the data directory
Expand Down
1 change: 1 addition & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@ client sees, and what the endpoint does not support are in [cli.md](./cli.md#end
| Symptom | Check |
|---|---|
| MCP process exits immediately or reports that the daemon is unreachable | Start `sctl serve` first. Requester commands never auto-start it. |
| `something is listening at … but does not answer as an sctl daemon`, or `status` reports a problem while `sctl serve` sits at "sctl is starting..." | A proxy or security software is intercepting local connections (on Windows, AdGuard has been reported to do this; macOS was unaffected): exclude the sctl executable from it. Otherwise another program holds the address: stop it, or move sctl to another one with `--listen-address`. |
| Control-channel authentication fails | Confirm that `serve`, CLI commands, and the MCP process resolve to the same absolute data directory; check both `SCTL_DATA_DIR` and any explicit `--data-dir`, then restart the MCP client. |
| `status` says the extension is not connected | Enable External Access in ScriptCat. If it has never been enrolled or was revoked, run `connect` and enter a new one-time code. |
| Tools do not appear in the AI client | Use the absolute sctl executable path, validate the client's JSON/TOML syntax, and reload the client. Check stderr and `<data-dir>/logs/`. |
Expand Down
26 changes: 26 additions & 0 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ package cli

import (
"encoding/json"
"errors"
"fmt"
"net"
"os"
"strconv"

"github.com/spf13/cobra"

Expand Down Expand Up @@ -73,6 +76,9 @@ func NewRootCmd() *cobra.Command {
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
paths.SetDataDir(dataDir)
if err := validateListenAddress(listenAddress); err != nil {
return err
}
control.SetAddress(listenAddress)
// 服务管理器托管的 serve 只写文件日志,见 internal/pkg/logging。
logging.Setup(logLevel, !serveAsService)
Expand Down Expand Up @@ -156,3 +162,23 @@ func printValueJSON(v any) error {
fmt.Fprintln(os.Stdout, string(b))
return nil
}

// validateListenAddress 在入口拒绝不是 host:port 的 --listen-address:否则 serve 报的是绑定失败,
// 客户端命令则一律当成 daemon 没在运行。端口 0 让 serve 随机绑定,客户端无从得知,同样拒绝。
func validateListenAddress(address string) error {
if address == "" {
return nil
}
_, port, err := net.SplitHostPort(address)
if err == nil {
var n uint64
n, err = strconv.ParseUint(port, 10, 16)
if err == nil && n == 0 {
err = errors.New("port must be between 1 and 65535")
}
}
if err != nil {
return &ExitError{Code: exitError, Message: fmt.Sprintf("invalid --listen-address %q: want host:port such as 127.0.0.1:8643 (%v)", address, err)}
}
return nil
}
43 changes: 42 additions & 1 deletion internal/cli/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package cli

import (
"context"
"errors"
"fmt"
"net"

"github.com/cago-frame/cago"
"github.com/cago-frame/cago/configs"
Expand All @@ -10,6 +13,7 @@ import (
"github.com/spf13/cobra"
"go.uber.org/zap"

"github.com/scriptscat/sctl/internal/client/control"
"github.com/scriptscat/sctl/internal/daemon"
)

Expand All @@ -35,8 +39,26 @@ func newServeCmd() *cobra.Command {
return err
}
logger.Ctx(ctx).Info("starting sctl serve", zap.String("version", Version))
address, err := control.Address()
if err != nil {
return err
}
// 在 cago 启动组件之前绑定:组件启动失败在 cago 里是 panic,用户只会看到一屏 goroutine 栈。
ln, err := net.Listen("tcp", address)
if err != nil {
// 服务管理器托管时 stderr 没人看,原因要落进日志文件。
logger.Ctx(ctx).Error("failed to bind the listen address", zap.String("address", address), zap.Error(err))
return listenError(ctx, address, err)
}
comp, err := daemon.New(ctx, Version, ln)
if err != nil {
logger.Ctx(ctx).Error("failed to start the daemon", zap.Error(err))
// 起不来就把地址放开;关闭失败不改变要报的错。
_ = ln.Close()
return &ExitError{Code: exitError, Message: "cannot start the daemon: " + err.Error()}
}
return cago.New(ctx, cfg).
RegistryCancel(daemon.Component(Version, listenAddress)).
RegistryCancel(comp).
Start()
},
}
Expand All @@ -46,6 +68,25 @@ func newServeCmd() *cobra.Command {
return cmd
}

// listenError 说明 serve 为什么绑定不了地址。能回答健康检查的是另一个 sctl daemon——装了 sctl service 后
// 它多半就是服务起的那个,用户要的 daemon 其实已经在跑了。占着地址却不回答的,可能是别的程序,也可能是
// 回答被本机安全软件截下的 sctl daemon。
func listenError(ctx context.Context, address string, err error) error {
probeErr := control.Probe(ctx)
if probeErr == nil {
return &ExitError{Code: exitError, Message: fmt.Sprintf(
"an sctl daemon is already running at %s, so there is nothing to start; `sctl status` shows it, and `sctl service status` tells whether it is the background service",
address)}
}
if errors.Is(probeErr, control.ErrNotSctlDaemon) {
return &ExitError{Code: exitError, Message: fmt.Sprintf("cannot listen on %s: %v", address, probeErr)}
}
// 地址格式已在入口校验过,到这里多半是被占用或没有权限(比如 Windows 保留给 Hyper-V 的端口段)。
// 原始错误放最后:Windows 的系统错误文字自带句号结尾,后面再接提示读起来是断的。
return &ExitError{Code: exitError, Message: fmt.Sprintf(
"cannot listen on %s (pick another address with --listen-address, or stop the program holding it): %v", address, err)}
}

// emptyConfigSource 是一个「无任何键」的 cago 配置源:所有 Scan 保持零值并返回 nil,
// sctl 的公开配置全部来自 CLI 参数,这里只为 cago 生命周期提供空配置源。
type emptyConfigSource struct{}
Expand Down
114 changes: 114 additions & 0 deletions internal/cli/serve_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package cli

import (
"net"
"os"
"path/filepath"
"strings"
"testing"

. "github.com/smartystreets/goconvey/convey"

"github.com/scriptscat/sctl/internal/client/control"
)

func TestServeAddressInUse(t *testing.T) {
Convey("sctl serve 绑定不了监听地址", t, func() {
Convey("占着地址的是另一个 sctl daemon(比如 sctl service 起的那个)时,退出码 3,说明已在运行并指向 status / service", func() {
stubDaemon(t, control.CallResult{})
address := os.Getenv("SCTL_BRIDGE_ADDR")

code, _, errOut, err := runCLIResult(strings.NewReader(""), "serve")

So(code, ShouldEqual, exitError)
So(errOut, ShouldNotContainSubstring, "panic")
So(err.Error(), ShouldContainSubstring, "already running at "+address)
So(err.Error(), ShouldContainSubstring, "sctl status")
So(err.Error(), ShouldContainSubstring, "sctl service status")
})

Convey("占着地址的不是 sctl 时,退出码 3,给出地址与原始错误,并提示换 --listen-address", func() {
ln, err := net.Listen("tcp", "127.0.0.1:0")
So(err, ShouldBeNil)
t.Cleanup(func() { _ = ln.Close() })
// 不说 HTTP 的程序:连上就断,健康检查立刻失败而不是等到超时。
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
_ = conn.Close()
}
}()
t.Setenv("SCTL_BRIDGE_ADDR", ln.Addr().String())
t.Setenv("SCTL_DATA_DIR", t.TempDir())

code, _, errOut, err := runCLIResult(strings.NewReader(""), "serve")

So(code, ShouldEqual, exitError)
So(errOut, ShouldNotContainSubstring, "panic")
So(err.Error(), ShouldNotContainSubstring, "already running")
So(err.Error(), ShouldContainSubstring, ln.Addr().String())
So(err.Error(), ShouldContainSubstring, "--listen-address")
// 占着地址的也可能是一个回答被截下的 sctl daemon(#20 里 Windows 上的 AdGuard)。
So(err.Error(), ShouldContainSubstring, "security software")
})
})
}

// freeAddress 返回一个此刻没人占用的本机地址。
func freeAddress(t *testing.T) string {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
So(err, ShouldBeNil)
address := ln.Addr().String()
So(ln.Close(), ShouldBeNil)
return address
}

func TestServeStartupFailures(t *testing.T) {
Convey("sctl serve 绑定地址之后起不来", t, func() {
dir := t.TempDir()
t.Setenv("SCTL_DATA_DIR", dir)
address := freeAddress(t)
t.Setenv("SCTL_BRIDGE_ADDR", address)

Convey("browsers.json 损坏时退出码 3,指出是哪个文件,并放开监听地址", func() {
path := filepath.Join(dir, "browsers.json")
So(os.WriteFile(path, []byte("{broken"), 0o600), ShouldBeNil)

code, _, errOut, err := runCLIResult(strings.NewReader(""), "serve")

So(code, ShouldEqual, exitError)
So(errOut, ShouldNotContainSubstring, "panic")
So(err.Error(), ShouldContainSubstring, path)
ln, lerr := net.Listen("tcp", address)
So(lerr, ShouldBeNil)
So(ln.Close(), ShouldBeNil)
})

Convey("scriptcats.json 损坏时退出码 3,指出是哪个文件", func() {
path := filepath.Join(dir, "scriptcats.json")
So(os.WriteFile(path, []byte("x"), 0o600), ShouldBeNil)

code, _, errOut, err := runCLIResult(strings.NewReader(""), "serve")

So(code, ShouldEqual, exitError)
So(errOut, ShouldNotContainSubstring, "panic")
So(err.Error(), ShouldContainSubstring, path)
})

Convey("控制令牌写不进数据目录时退出码 3,指出令牌文件", func() {
// 令牌路径被一个目录占着:写入一定失败,root 运行也一样。
path := filepath.Join(dir, "control.token")
So(os.MkdirAll(filepath.Join(path, "x"), 0o700), ShouldBeNil)

code, _, errOut, err := runCLIResult(strings.NewReader(""), "serve")

So(code, ShouldEqual, exitError)
So(errOut, ShouldNotContainSubstring, "panic")
So(err.Error(), ShouldContainSubstring, path)
})
})
}
7 changes: 6 additions & 1 deletion internal/cli/status.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"errors"
"fmt"
"os"
"strings"
Expand All @@ -19,13 +20,17 @@ func newStatusCmd() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
client, err := control.Connect(ctx)
if err != nil {
// 只有连不上才算没在运行;连得上却读不到令牌时要把原因报出来,否则用户会去再起一个 serve。
if errors.Is(err, control.ErrDaemonUnreachable) {
if outputFormat == outputJSON {
return printValueJSON(control.StatusResult{})
}
fmt.Fprintln(os.Stdout, "daemon is not running")
return nil
}
if err != nil {
return &ExitError{Code: exitError, Message: err.Error()}
}
st, err := client.Status(ctx)
if err != nil {
return err
Expand Down
88 changes: 88 additions & 0 deletions internal/cli/status_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package cli

import (
"net"
"os"
"path/filepath"
"strings"
"testing"

. "github.com/smartystreets/goconvey/convey"

"github.com/scriptscat/sctl/internal/client/control"
)

func TestStatusDaemonRunningWithoutToken(t *testing.T) {
Convey("daemon 在运行、但本数据目录里没有它的控制令牌(多半是另一个数据目录)时", t, func() {
stubDaemon(t, control.CallResult{})
So(os.Remove(filepath.Join(os.Getenv("SCTL_DATA_DIR"), "control.token")), ShouldBeNil)

Convey("status 不说 daemon 没在运行,而是退出码 3 并指向 --data-dir", func() {
code, out, _, err := runCLIResult(strings.NewReader(""), "status")

So(code, ShouldEqual, exitError)
So(out, ShouldNotContainSubstring, "not running")
So(err.Error(), ShouldContainSubstring, "a daemon is running at")
So(err.Error(), ShouldContainSubstring, "--data-dir")
})

Convey("status -o json 同样报错,不输出一份看起来像没在运行的空状态", func() {
code, out, _ := runCLICapture("-o", "json", "status")

So(code, ShouldEqual, exitError)
So(out, ShouldBeEmpty)
})
})

Convey("daemon 确实没在运行时,status 照旧如实报告且退出码 0", t, func() {
t.Setenv("SCTL_BRIDGE_ADDR", "127.0.0.1:1")
t.Setenv("SCTL_DATA_DIR", t.TempDir())

code, out := runCLI("status")

So(code, ShouldEqual, exitOK)
So(out, ShouldContainSubstring, "daemon is not running")
})
}

func TestStatusSomethingElseListening(t *testing.T) {
Convey("地址上有程序在监听、却不像 sctl daemon 那样回答时,status 不说没在运行,退出码 3 并提示可能被拦截", t, func() {
ln, err := net.Listen("tcp", "127.0.0.1:0")
So(err, ShouldBeNil)
t.Cleanup(func() { _ = ln.Close() })
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
_ = conn.Close()
}
}()
t.Setenv("SCTL_BRIDGE_ADDR", ln.Addr().String())
t.Setenv("SCTL_DATA_DIR", t.TempDir())

code, out, _, err := runCLIResult(strings.NewReader(""), "status")

So(code, ShouldEqual, exitError)
So(out, ShouldNotContainSubstring, "not running")
So(err.Error(), ShouldContainSubstring, "something is listening at "+ln.Addr().String())
So(err.Error(), ShouldContainSubstring, "security software")
})
}

func TestListenAddressValidation(t *testing.T) {
Convey("--listen-address 不是 host:port 时,任何命令都在入口拒绝,退出码 3", t, func() {
t.Setenv("SCTL_BRIDGE_ADDR", "")
t.Setenv("SCTL_DATA_DIR", t.TempDir())
for _, address := range []string{"nonsense", "127.0.0.1", "127.0.0.1:http", "127.0.0.1:0", "127.0.0.1:70000"} {
for _, verb := range []string{"serve", "status"} {
code, out, _, err := runCLIResult(strings.NewReader(""), "--listen-address", address, verb)

So(code, ShouldEqual, exitError)
So(out, ShouldBeEmpty)
So(err.Error(), ShouldContainSubstring, "invalid --listen-address")
}
}
})
}
Loading
Loading