Skip to content

PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.

feat(core): add version and read-only JSON CLI queries

baiyuze60fb15b7c8b4
diff --git a/client-core/cmd/pasteferry-cli/json.go b/client-core/cmd/pasteferry-cli/json.go
new file mode 100644
index 0000000..da1b34d
--- /dev/null
+++ b/client-core/cmd/pasteferry-cli/json.go
@@ -0,0 +1,94 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "os"
+ "time"
+
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/baiyuze/pasteferry/client-core/internal/rpc"
+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"
+)
+
+// JSON mode is deliberately restricted to queries. Reject unsupported commands
+// before opening a connection so an automation cannot accidentally change data.
+func validateJSONCommand(cmd string) error {
+ switch cmd {
+ case "version", "status", "devices", "history":
+ if flag.NArg() == 1 {
+ return nil
+ }
+ case "config":
+ if flag.NArg() == 1 || (flag.NArg() == 2 && flag.Arg(1) == "get") {
+ return nil
+ }
+ }
+ return fmt.Errorf("JSON 模式仅支持 version、status、devices、history、config [get],不接受额外参数")
+}
+
+func writeJSON(data any) error {
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetEscapeHTML(false)
+ return enc.Encode(struct {
+ OK bool `json:"ok"`
+ Data any `json:"data"`
+ }{true, data})
+}
+
+// Use the existing RPC schema, with stable snake_case field names, enum names,
+// explicit defaults and empty arrays. ProtoJSON represents int64 as strings.
+func writeProtoJSON(message proto.Message) error {
+ data, err := (protojson.MarshalOptions{
+ UseProtoNames: true, EmitUnpopulated: true,
+ }).Marshal(message)
+ if err != nil {
+ return err
+ }
+ return writeJSON(json.RawMessage(data))
+}
+
+func queryJSON(ctx context.Context, client pb.DaemonServiceClient, ep rpc.Endpoint, cmd string) error {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ switch cmd {
+ case "status":
+ status, err := client.GetStatus(ctx, &pb.Empty{})
+ if err != nil {
+ return err
+ }
+ data, err := (protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: true}).Marshal(status)
+ if err != nil {
+ return err
+ }
+ return writeJSON(struct {
+ PID int `json:"pid"`
+ Port int `json:"port"`
+ Daemon json.RawMessage `json:"daemon"`
+ }{ep.PID, ep.Port, data})
+ case "devices":
+ response, err := client.ListDevices(ctx, &pb.Empty{})
+ if err != nil {
+ return err
+ }
+ return writeProtoJSON(response)
+ case "history":
+ response, err := client.ListHistory(ctx, &pb.ListHistoryRequest{Limit: 20})
+ if err != nil {
+ return err
+ }
+ return writeProtoJSON(response)
+ case "config":
+ response, err := client.GetConfig(ctx, &pb.Empty{})
+ if err != nil {
+ return err
+ }
+ return writeProtoJSON(response)
+ default:
+ return fmt.Errorf("不支持的 JSON 查询 %q", cmd)
+ }
+}
diff --git a/client-core/cmd/pasteferry-cli/main.go b/client-core/cmd/pasteferry-cli/main.go
index 51385cf..fbe4f5e 100644
--- a/client-core/cmd/pasteferry-cli/main.go
+++ b/client-core/cmd/pasteferry-cli/main.go
@@ -21,6 +21,7 @@ package main
import (
"context"
+ "encoding/json"
"errors"
"flag"
"fmt"
@@ -40,24 +41,72 @@ import (
pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"
)
+// version is set by the packaging scripts for every supported platform.
+var version = "dev"
+var jsonOutput bool
+
+func reportError(err error, code int) {
+ if jsonOutput {
+ _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"ok": false, "error": err.Error()})
+ } else {
+ fmt.Fprintln(os.Stderr, "错误:", err)
+ }
+ os.Exit(code)
+}
+
func main() {
+ flag.CommandLine = flag.NewFlagSet("pasteferry-cli", flag.ContinueOnError)
+ flag.CommandLine.SetOutput(io.Discard)
+ flag.BoolVar(&jsonOutput, "json", false, "以 JSON 输出只读查询结果")
dataDir := flag.String("data-dir", "", "数据目录(默认为系统标准位置)")
- flag.Parse()
+ if err := flag.CommandLine.Parse(os.Args[1:]); err != nil {
+ if errors.Is(err, flag.ErrHelp) {
+ if jsonOutput {
+ if err := writeJSON(map[string]string{"usage": "pasteferry-cli [-json] [-data-dir DIR] <version|status|devices|history|config [get]>"}); err != nil {
+ reportError(err, 1)
+ }
+ return
+ }
+ fmt.Println("用法: pasteferry-cli [-json] [-data-dir DIR] <version|status|devices|history|config [get]|...>")
+ return
+ }
+ reportError(err, 2)
+ }
cmd := flag.Arg(0)
if cmd == "" {
+ if jsonOutput {
+ reportError(errors.New("缺少命令:version、status、devices、history 或 config get"), 2)
+ }
fmt.Fprintln(os.Stderr,
- "用法: pasteferry-cli [-data-dir DIR] <status|watch|history|config|devices|nat|pair|join CODE [ADDRESS]|nearby [NAME]|address DEVICE ADDR|send [-relay] [-note TEXT] DEVICE PATH...|transfers [-v]|cancel ID|friends|friend code|add|remove|auto|accept [ID] [always]|decline [ID]|name NAME|avatar PATH|reset|receive-from [off|friends|everyone]|web [on|off|invite [ADDR]|remove ID]>")
+ "用法: pasteferry-cli [-json] [-data-dir DIR] <version|status|watch|history|config [get]|devices|nat|pair|join CODE [ADDRESS]|nearby [NAME]|address DEVICE ADDR|send [-relay] [-note TEXT] DEVICE PATH...|transfers [-v]|cancel ID|friends|friend code|add|remove|auto|accept [ID] [always]|decline [ID]|name NAME|avatar PATH|reset|receive-from [off|friends|everyone]|web [on|off|invite [ADDR]|remove ID]>")
os.Exit(2)
}
if err := run(cmd, *dataDir); err != nil {
- fmt.Fprintln(os.Stderr, "错误:", err)
- os.Exit(1)
+ reportError(err, 1)
}
}
func run(cmd, dataDir string) error {
+ if jsonOutput {
+ if err := validateJSONCommand(cmd); err != nil {
+ return err
+ }
+ }
+ if cmd == "version" {
+ if flag.NArg() != 1 {
+ return errors.New("用法: pasteferry-cli version")
+ }
+ if jsonOutput {
+ return writeJSON(map[string]string{"version": version})
+ }
+ fmt.Println(version)
+ return nil
+ }
+ if cmd == "config" && (flag.NArg() > 2 || (flag.NArg() == 2 && flag.Arg(1) != "get")) {
+ return errors.New("用法: pasteferry-cli config [get]")
+ }
paths, err := resolvePaths(dataDir)
if err != nil {
return err
@@ -81,6 +130,9 @@ func run(cmd, dataDir string) error {
client := pb.NewDaemonServiceClient(conn)
// token 随每次调用发送,daemon 侧用常数时间比较校验
ctx := metadata.AppendToOutgoingContext(context.Background(), "x-pasteferry-token", ep.Token)
+ if jsonOutput {
+ return queryJSON(ctx, client, ep, cmd)
+ }
switch cmd {
case "status":
diff --git a/client-core/cmd/pasteferry-cli/main_test.go b/client-core/cmd/pasteferry-cli/main_test.go
new file mode 100644
index 0000000..6c811bf
--- /dev/null
+++ b/client-core/cmd/pasteferry-cli/main_test.go
@@ -0,0 +1,295 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net"
+ "os"
+ "os/exec"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/status"
+
+ "github.com/baiyuze/pasteferry/client-core/internal/config"
+ "github.com/baiyuze/pasteferry/client-core/internal/rpc"
+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"
+)
+
+// Exercise the actual entry point in a separate process, including flag parsing,
+// exit codes, stdout/stderr and RPC authentication, on every desktop platform.
+func TestCLIProcess(t *testing.T) {
+ if os.Getenv("PASTEFERRY_CLI_TEST_PROCESS") != "1" {
+ return
+ }
+ for i, arg := range os.Args {
+ if arg == "--" {
+ os.Args = append([]string{"pasteferry-cli"}, os.Args[i+1:]...)
+ break
+ }
+ }
+ version = "2.9.0-test"
+ main()
+ os.Exit(0)
+}
+
+func invokeCLI(t *testing.T, args ...string) (string, string, int) {
+ t.Helper()
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, exe, append([]string{"-test.run=^TestCLIProcess$", "--"}, args...)...)
+ cmd.Env = append(os.Environ(), "PASTEFERRY_CLI_TEST_PROCESS=1")
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout, cmd.Stderr = &stdout, &stderr
+ code := 0
+ if err := cmd.Run(); err != nil {
+ var exit *exec.ExitError
+ if !errors.As(err, &exit) || ctx.Err() != nil {
+ t.Fatalf("CLI failed to run: %v (stdout=%q stderr=%q)", err, stdout.String(), stderr.String())
+ }
+ code = exit.ExitCode()
+ }
+ return stdout.String(), stderr.String(), code
+}
+
+func jsonCLI(t *testing.T, wantCode int, args ...string) map[string]any {
+ t.Helper()
+ out, stderr, code := invokeCLI(t, args...)
+ if code != wantCode || stderr != "" {
+ t.Fatalf("exit=%d want=%d stdout=%q stderr=%q", code, wantCode, out, stderr)
+ }
+ var result map[string]any
+ decoder := json.NewDecoder(strings.NewReader(out))
+ if err := decoder.Decode(&result); err != nil {
+ t.Fatalf("invalid JSON: %v: %q", err, out)
+ }
+ if err := decoder.Decode(new(any)); err != io.EOF {
+ t.Fatalf("extra stdout after JSON: %q (%v)", out, err)
+ }
+ if result["ok"] != (wantCode == 0) {
+ t.Fatalf("unexpected envelope: %v", result)
+ }
+ if wantCode != 0 && result["error"] == "" {
+ t.Fatalf("missing error: %v", result)
+ }
+ return result
+}
+
+type queryServer struct {
+ pb.UnimplementedDaemonServiceServer
+ devices *pb.ListDevicesResponse
+ history *pb.ListHistoryResponse
+ fail bool
+ wait bool
+ calls atomic.Int32
+}
+
+func (s *queryServer) GetStatus(ctx context.Context, _ *pb.Empty) (*pb.Status, error) {
+ if s.wait {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ if s.fail {
+ return nil, status.Error(codes.Unavailable, "test backend unavailable")
+ }
+ return &pb.Status{Version: "2.8.3", DeviceName: "我的 Mac <&> 🛳", LanEnabled: true, CacheBytesUsed: 9007199254740993}, nil
+}
+
+func (s *queryServer) ListDevices(context.Context, *pb.Empty) (*pb.ListDevicesResponse, error) {
+ return s.devices, nil
+}
+
+func (s *queryServer) ListHistory(_ context.Context, req *pb.ListHistoryRequest) (*pb.ListHistoryResponse, error) {
+ if req.GetLimit() != 20 {
+ return nil, status.Error(codes.InvalidArgument, "expected history limit 20")
+ }
+ return s.history, nil
+}
+
+func (s *queryServer) GetConfig(context.Context, *pb.Empty) (*pb.Config, error) {
+ return &pb.Config{DeviceName: "我的 Mac <&> 🛳", SyncText: true, SyncImage: true, Language: "ja", ReceiveFrom: "friends"}, nil
+}
+
+func startQueryServer(t *testing.T, s *queryServer) string {
+ t.Helper()
+ if s.devices == nil {
+ s.devices = &pb.ListDevicesResponse{}
+ }
+ if s.history == nil {
+ s.history = &pb.ListHistoryResponse{}
+ }
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ server := grpc.NewServer(grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
+ s.calls.Add(1)
+ md, _ := metadata.FromIncomingContext(ctx)
+ if strings.Join(md.Get("x-pasteferry-token"), "") != "test-private-token" {
+ return nil, status.Error(codes.Unauthenticated, "invalid token")
+ }
+ return handler(ctx, req)
+ }))
+ pb.RegisterDaemonServiceServer(server, s)
+ go server.Serve(listener)
+ t.Cleanup(server.Stop)
+ dir := t.TempDir()
+ if err := rpc.WriteEndpoint(config.PathsUnder(dir).Endpoint, rpc.Endpoint{
+ Port: listener.Addr().(*net.TCPAddr).Port, Token: "test-private-token", PID: 1234,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ return dir
+}
+
+func TestVersionWithoutDaemon(t *testing.T) {
+ dir := t.TempDir()
+ out, stderr, code := invokeCLI(t, "-data-dir", dir, "version")
+ if code != 0 || stderr != "" || out != "2.9.0-test\n" {
+ t.Fatalf("version: exit=%d stdout=%q stderr=%q", code, out, stderr)
+ }
+ for _, option := range []string{"-json", "--json"} {
+ result := jsonCLI(t, 0, option, "-data-dir", dir, "version")
+ if result["data"].(map[string]any)["version"] != "2.9.0-test" {
+ t.Fatal(result)
+ }
+ }
+}
+
+func TestReadOnlyJSON(t *testing.T) {
+ s := &queryServer{}
+ dir := startQueryServer(t, s)
+ for _, args := range [][]string{{"status"}, {"devices"}, {"history"}, {"config"}, {"config", "get"}} {
+ t.Run(strings.Join(args, "_"), func(t *testing.T) {
+ result := jsonCLI(t, 0, append([]string{"-json", "-data-dir", dir}, args...)...)
+ data := result["data"].(map[string]any)
+ switch args[0] {
+ case "status":
+ daemon := data["daemon"].(map[string]any)
+ if data["pid"] != float64(1234) || daemon["version"] != "2.8.3" || daemon["cache_bytes_used"] != "9007199254740993" || daemon["device_name"] != "我的 Mac <&> 🛳" {
+ t.Fatal(data)
+ }
+ case "devices", "history":
+ key := "peers"
+ if args[0] == "history" {
+ key = "records"
+ }
+ if list, ok := data[key].([]any); !ok || len(list) != 0 {
+ t.Fatal(data)
+ }
+ case "config":
+ if data["sync_text"] != true || data["sync_image"] != true || data["sync_file"] != false || data["language"] != "ja" {
+ t.Fatal(data)
+ }
+ }
+ if strings.Contains(string(mustJSON(t, result)), "test-private-token") {
+ t.Fatal("endpoint token leaked")
+ }
+ })
+ }
+}
+
+func mustJSON(t *testing.T, value any) []byte {
+ t.Helper()
+ data, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+}
+
+func TestPopulatedQueriesAndLegacyText(t *testing.T) {
+ s := &queryServer{
+ devices: &pb.ListDevicesResponse{Self: &pb.Device{Name: "My Mac"}, Peers: []*pb.Device{{Id: "peer", Name: "手机", Online: true, Connection: pb.ConnectionKind_CONNECTION_KIND_DIRECT}}},
+ history: &pb.ListHistoryResponse{Records: []*pb.ClipRecord{{Id: "clip", TextPreview: "中文\n<&> 🛳", Kind: pb.ClipKind_CLIP_KIND_TEXT, TotalSize: 9007199254740993}}},
+ }
+ dir := startQueryServer(t, s)
+ devices := jsonCLI(t, 0, "-json", "-data-dir", dir, "devices")["data"].(map[string]any)
+ peer := devices["peers"].([]any)[0].(map[string]any)
+ if peer["name"] != "手机" || peer["connection"] != "CONNECTION_KIND_DIRECT" || peer["online"] != true {
+ t.Fatal(peer)
+ }
+ history := jsonCLI(t, 0, "-json", "-data-dir", dir, "history")["data"].(map[string]any)
+ record := history["records"].([]any)[0].(map[string]any)
+ if record["text_preview"] != "中文\n<&> 🛳" || record["total_size"] != "9007199254740993" {
+ t.Fatal(record)
+ }
+ for _, args := range [][]string{{"status"}, {"devices"}, {"history"}, {"config"}, {"config", "get"}} {
+ out, stderr, code := invokeCLI(t, append([]string{"-data-dir", dir}, args...)...)
+ if code != 0 || stderr != "" || out == "" || json.Valid([]byte(out)) {
+ t.Fatalf("legacy %v: %d %q %q", args, code, out, stderr)
+ }
+ }
+}
+
+func TestJSONRejectsUnsupportedOperationsBeforeRPC(t *testing.T) {
+ s := &queryServer{}
+ dir := startQueryServer(t, s)
+ for _, args := range [][]string{{"name", "Changed"}, {"config", "set", "sync_text", "false"}, {"pair"}, {"join", "123"}, {"confirm", "session"}, {"unpair", "peer"}, {"apply", "clip"}, {"favorite", "clip"}, {"watch"}, {"status", "--json"}, {"unknown"}, {"config", "get", "extra"}} {
+ jsonCLI(t, 1, append([]string{"-json", "-data-dir", dir}, args...)...)
+ }
+ if s.calls.Load() != 0 {
+ t.Fatalf("unsupported commands made %d RPC calls", s.calls.Load())
+ }
+}
+
+func TestJSONErrors(t *testing.T) {
+ jsonCLI(t, 0, "-json", "-h")
+ jsonCLI(t, 2, "-json")
+ jsonCLI(t, 2, "-json", "-unknown")
+ jsonCLI(t, 2, "-json", "-data-dir")
+ jsonCLI(t, 1, "-json", "-data-dir", t.TempDir(), "status")
+ staleDir := t.TempDir()
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ port := listener.Addr().(*net.TCPAddr).Port
+ listener.Close()
+ if err := rpc.WriteEndpoint(config.PathsUnder(staleDir).Endpoint, rpc.Endpoint{Port: port, Token: "stale-token"}); err != nil {
+ t.Fatal(err)
+ }
+ jsonCLI(t, 1, "-json", "-data-dir", staleDir, "status")
+
+ s := &queryServer{fail: true}
+ dir := startQueryServer(t, s)
+ jsonCLI(t, 1, "-json", "-data-dir", dir, "status")
+ ep, err := rpc.ReadEndpoint(config.PathsUnder(dir).Endpoint)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ep.Token = "wrong-token"
+ if err := rpc.WriteEndpoint(config.PathsUnder(dir).Endpoint, ep); err != nil {
+ t.Fatal(err)
+ }
+ jsonCLI(t, 1, "-json", "-data-dir", dir, "config", "get")
+ if err := os.WriteFile(config.PathsUnder(dir).Endpoint, []byte("not JSON"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ jsonCLI(t, 1, "-json", "-data-dir", dir, "status")
+ out, stderr, code := invokeCLI(t, "-data-dir", t.TempDir(), "status")
+ if code != 1 || out != "" || !strings.Contains(stderr, "daemon 未运行") {
+ t.Fatalf("text error: %d %q %q", code, out, stderr)
+ }
+}
+
+func TestJSONRequestDeadline(t *testing.T) {
+ dir := startQueryServer(t, &queryServer{wait: true})
+ start := time.Now()
+ jsonCLI(t, 1, "-json", "-data-dir", dir, "status")
+ if elapsed := time.Since(start); elapsed < 4*time.Second || elapsed > 10*time.Second {
+ t.Fatalf("unexpected deadline: %v", elapsed)
+ }
+}
diff --git a/design/cli-json.md b/design/cli-json.md
new file mode 100644
index 0000000..9f287ca
--- /dev/null
+++ b/design/cli-json.md
@@ -0,0 +1,80 @@
+# CLI queries and JSON output
+
+PasteFerry 2.9 adds a version command and structured read-only queries to the
+existing desktop CLI. These queries use the same authenticated local RPC
+connection as the desktop app. The CLI controls an existing background service;
+it does not install or start one.
+
+## Commands
+
+Global flags must precede the command. Both `-json` and `--json` are accepted.
+
+```sh
+pasteferry-cli version
+pasteferry-cli -json version
+pasteferry-cli -json status
+pasteferry-cli -json devices
+pasteferry-cli -json history
+pasteferry-cli -json config
+pasteferry-cli -json config get
+pasteferry-cli -json -data-dir /path/to/running-instance status
+```
+
+`version` reports the CLI executable version without contacting a service.
+`status` reports the service version, which can differ from the CLI version.
+`config get` is an alias for `config`, including in text mode.
+
+## Response format
+
+Each JSON invocation writes one JSON object followed by a newline to stdout.
+Success has exit code 0:
+
+```json
+{"ok":true,"data":{"version":"2.9.0"}}
+```
+
+Failures have a nonzero exit code and an error description:
+
+```json
+{"ok":false,"error":"daemon 未运行(找不到 /path/to/daemon.json)"}
+```
+
+Errors from supported queries, invalid arguments and unsupported JSON commands
+use this envelope. Global flag parsing stops at the command, as with Go's
+standard flag parser; put `-json` before other flags to request JSON errors for
+invalid flags as well. JSON mode does not write diagnostic text to stderr.
+Error descriptions are intended for people and should not be parsed as codes.
+
+| Query | `data` contents |
+| --- | --- |
+| `version` | `version`: the CLI version string |
+| `status` | `pid`, `port`, and `daemon`: the RPC Status message |
+| `devices` | The RPC ListDevicesResponse, including `self` and `peers` |
+| `history` | The RPC ListHistoryResponse, including `records` |
+| `config [get]` | The RPC Config message |
+
+RPC messages follow [ProtoJSON](https://protobuf.dev/programming-guides/json/):
+field names use snake_case, booleans remain booleans, enums use their full names
+(for example `CONNECTION_KIND_DIRECT`), and 64-bit integers use decimal strings
+to preserve precision in JavaScript. Default scalar fields are included. Empty
+repeated fields are `[]`, and absent optional messages are `null`.
+Consumers should tolerate additional fields in future versions.
+
+For example, no paired devices produces `data.peers: []`; no history produces
+`data.records: []`. History returns up to 20 recent record summaries, matching
+the existing text command, and does not fetch file content or alter the
+clipboard. The endpoint authentication token is never included in the output.
+
+The data fields are defined in
+[`proto/pasteferry/v1/daemon.proto`](../proto/pasteferry/v1/daemon.proto).
+Each RPC request has a five-second deadline, including configuration queries.
+
+## Compatibility and scope
+
+Without `-json`, existing commands keep their human-readable output and behavior.
+JSON mode supports only the queries listed above. Commands that pair devices,
+change settings, write the clipboard or modify history are rejected before any
+RPC call. Existing text-mode operation commands remain available.
+
+The new CLI can query an existing 2.8.3 service. There are no device protocol or
+server changes in this feature.
diff --git a/scripts/build-windows.ps1 b/scripts/build-windows.ps1
index 4bf7b4b..f61c482 100644
--- a/scripts/build-windows.ps1
+++ b/scripts/build-windows.ps1
@@ -38,7 +38,7 @@ Push-Location client-core
try {
# -H=windowsgui:后台服务没有控制台窗口,开机自启时不会闪一下黑框
Invoke-Checked { go build -trimpath -ldflags "-s -w -H=windowsgui -X main.version=$Version" -o "$app\pasteferryd.exe" ./cmd/pasteferryd } 'go build pasteferryd'
- Invoke-Checked { go build -trimpath -ldflags '-s -w' -o "$app\pasteferry-cli.exe" ./cmd/pasteferry-cli } 'go build pasteferry-cli'
+ Invoke-Checked { go build -trimpath -ldflags "-s -w -X main.version=$Version" -o "$app\pasteferry-cli.exe" ./cmd/pasteferry-cli } 'go build pasteferry-cli'
} finally {
Pop-Location
Remove-Item Env:CGO_ENABLED, Env:GOOS, Env:GOARCH
diff --git a/scripts/build.sh b/scripts/build.sh
index 3bf7df7..8d0ccee 100755
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -47,7 +47,7 @@ build_universal client-core ./cmd/pasteferryd "$DIST/pasteferryd" \
"-s -w -X main.version=$VERSION"
echo "▶ 构建 CLI"
-build_universal client-core ./cmd/pasteferry-cli "$DIST/pasteferry-cli" "-s -w"
+build_universal client-core ./cmd/pasteferry-cli "$DIST/pasteferry-cli" "-s -w -X main.version=$VERSION"
echo "▶ 构建服务器"
build_universal server ./cmd/pasteferry-server "$DIST/pasteferry-server" \
diff --git a/scripts/package-linux.sh b/scripts/package-linux.sh
index c4691b8..d5ad15e 100755
--- a/scripts/package-linux.sh
+++ b/scripts/package-linux.sh
@@ -35,7 +35,7 @@ echo "▶ 后台服务与命令行(${VERSION},${ARCH})"
# 纯 Go,不依赖 glibc 版本:剪贴板经 X11 协议直接通信,不链接 libX11
(cd client-core && CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=$VERSION" \
-o "../$APP/pasteferryd" ./cmd/pasteferryd)
-(cd client-core && CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o "../$APP/pasteferry-cli" ./cmd/pasteferry-cli)
+(cd client-core && CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=$VERSION" -o "../$APP/pasteferry-cli" ./cmd/pasteferry-cli)
echo "▶ 界面"
(cd ui && flutter build linux --release --build-name "$VERSION" --dart-define=APP_VERSION="$VERSION" \