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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,26 @@ $ tsm list

The display name is shown first; the kebab-case id (used for `tsm get`, env var derivation, and audit logs) is on the line beneath. Run `tsm add` with no flags to use the interactive TUI instead — it'll prompt for the display name and show a live "stored as: …" preview as you type.

To search, give one or more terms. `tsm list` shows the secrets where any term appears in the id, display name, description, or a tag (case-insensitive):

```bash
$ tsm list github openai --json
[
{"name":"openai-api-key","display_name":"OpenAI API key","description":"Production GPT-4 key","confirm":true,"tags":["openai","prod"]},
{"name":"github-pat","display_name":"GitHub PAT","description":"Read-only token for private repos","confirm":false,"tags":["github"]}
]
```

### JSON output

`--json` output is indented in a terminal. When stdout is a pipe or file, it is compact, and an array has one element per line, so `| head` shows whole entries. If a command fails, stdout is empty, the exit code is 1, and stderr holds the error. With `--json` the error is JSON:

```json
{"error":{"code":-32002,"name":"auth_required","message":"Authentication required"}}
```

`name` is one of `vault_locked`, `auth_required`, `secret_not_found`, `auth_unavailable`, or a JSON-RPC protocol error. Errors that do not come from the daemon have only `message`.

### Retrieving

```bash
Expand Down
95 changes: 83 additions & 12 deletions cmd/helpers.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"bytes"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -56,15 +57,41 @@ func jsonOutput() bool {
return jsonFlag
}

// printJSON writes v as indented JSON to stdout.
// printJSON writes v as JSON to stdout.
func printJSON(v any) error {
return printJSONTo(os.Stdout, v)
}

// printJSONTo writes v as JSON to w: indented for a terminal, compact
// otherwise. A compact array puts one element per line, so the output stays
// one JSON document and `| head -N` still shows whole entries.
func printJSONTo(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(v)
if f, ok := w.(*os.File); ok && isTTY(int(f.Fd())) {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(v)
}

b, err := json.Marshal(v)
if err != nil {
return err
}
var items []json.RawMessage
if len(b) > 0 && b[0] == '[' && json.Unmarshal(b, &items) == nil && len(items) > 0 {
var buf bytes.Buffer
buf.WriteString("[\n")
for i, item := range items {
if i > 0 {
buf.WriteString(",\n")
}
buf.Write(item)
}
buf.WriteString("\n]\n")
_, err = w.Write(buf.Bytes())
return err
}
_, err = w.Write(append(b, '\n'))
return err
}

// formatRPCError returns a human-friendly error message with guidance.
Expand All @@ -83,19 +110,63 @@ func formatRPCError(err *jsonrpc.RPCError) string {
}
}

// handleError formats and prints an error, returning it for cobra.
// errorName returns a stable snake_case name for a JSON-RPC error code, so
// scripts can match on a word instead of a number.
func errorName(code int) string {
switch code {
case jsonrpc.CodeVaultLocked:
return "vault_locked"
case jsonrpc.CodeAuthRequired:
return "auth_required"
case jsonrpc.CodeSecretNotFound:
return "secret_not_found"
case jsonrpc.CodeAuthUnavailable:
return "auth_unavailable"
case -32700:
return "parse_error"
case -32600:
return "invalid_request"
case -32601:
return "method_not_found"
case -32602:
return "invalid_params"
case -32603:
return "internal_error"
default:
return "error"
}
}

// handleError adds guidance to an RPC error for the text output. In --json
// mode it returns the RPC error unchanged, and Execute writes it to stderr.
func handleError(err error) error {
if rpcErr, ok := err.(*jsonrpc.RPCError); ok {
if jsonOutput() {
printJSON(map[string]any{
"error": map[string]any{
"code": rpcErr.Code,
"message": rpcErr.Message,
},
})
return errors.New("")
return rpcErr
}
return errors.New(formatRPCError(rpcErr))
}
return err
}

// writeError writes a command's final error to w (stderr in production). In
// --json mode it is {"error":{...}}, with code and name for RPC errors.
// Errors never go to stdout, so stdout holds data or nothing.
func writeError(w io.Writer, err error, asJSON bool) {
if !asJSON {
if err.Error() != "" {
fmt.Fprintln(w, "Error:", err)
}
return
}
var obj any = map[string]any{"message": err.Error()}
var rpcErr *jsonrpc.RPCError
if errors.As(err, &rpcErr) {
obj = map[string]any{
"code": rpcErr.Code,
"name": errorName(rpcErr.Code),
"message": rpcErr.Message,
}
}
printJSONTo(w, map[string]any{"error": obj})
}
106 changes: 106 additions & 0 deletions cmd/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"

Expand Down Expand Up @@ -59,3 +60,108 @@ func TestFormatError_AuthUnavailable_DoesNotAskForTouchID(t *testing.T) {
t.Errorf("CLI must not add a cause-specific hint: %q", msg)
}
}

func TestPrintJSON_CompactObjectWhenNotTTY(t *testing.T) {
var buf bytes.Buffer
if err := printJSONTo(&buf, map[string]any{"locked": true, "version": "1.0"}); err != nil {
t.Fatal(err)
}
want := `{"locked":true,"version":"1.0"}` + "\n"
if buf.String() != want {
t.Errorf("got %q, want %q", buf.String(), want)
}
}

// An array prints one element per line, so `| head -N` shows N-2 whole
// entries and the output is still one valid JSON document.
func TestPrintJSON_ArrayOneElementPerLineWhenNotTTY(t *testing.T) {
var buf bytes.Buffer
in := []map[string]any{{"name": "a"}, {"name": "b"}}
if err := printJSONTo(&buf, in); err != nil {
t.Fatal(err)
}
want := "[\n" + `{"name":"a"},` + "\n" + `{"name":"b"}` + "\n]\n"
if buf.String() != want {
t.Errorf("got %q, want %q", buf.String(), want)
}
var decoded []map[string]any
if err := json.Unmarshal(buf.Bytes(), &decoded); err != nil || len(decoded) != 2 {
t.Fatalf("not a valid 2-element array: %v %s", err, buf.String())
}
}

func TestPrintJSON_EmptyArray(t *testing.T) {
var buf bytes.Buffer
if err := printJSONTo(&buf, []string{}); err != nil {
t.Fatal(err)
}
if buf.String() != "[]\n" {
t.Errorf("got %q, want %q", buf.String(), "[]\n")
}
}

func TestWriteError_JSON_RPCErrorHasCodeAndName(t *testing.T) {
var buf bytes.Buffer
writeError(&buf, &jsonrpc.RPCError{Code: jsonrpc.CodeAuthRequired, Message: "Authentication required"}, true)

var got struct {
Error struct {
Code int `json:"code"`
Name string `json:"name"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("invalid JSON: %s", buf.String())
}
if got.Error.Code != -32002 || got.Error.Name != "auth_required" || got.Error.Message != "Authentication required" {
t.Errorf("unexpected error object: %+v", got.Error)
}
}

func TestWriteError_JSON_PlainErrorHasMessageOnly(t *testing.T) {
var buf bytes.Buffer
writeError(&buf, errors.New("daemon did not start"), true)
want := `{"error":{"message":"daemon did not start"}}` + "\n"
if buf.String() != want {
t.Errorf("got %q, want %q", buf.String(), want)
}
}

func TestWriteError_Text(t *testing.T) {
var buf bytes.Buffer
writeError(&buf, errors.New("boom"), false)
if buf.String() != "Error: boom\n" {
t.Errorf("got %q", buf.String())
}
}

func TestErrorName_KnownCodes(t *testing.T) {
cases := map[int]string{
jsonrpc.CodeVaultLocked: "vault_locked",
jsonrpc.CodeAuthRequired: "auth_required",
jsonrpc.CodeSecretNotFound: "secret_not_found",
jsonrpc.CodeAuthUnavailable: "auth_unavailable",
-32601: "method_not_found",
-1: "error",
}
for code, want := range cases {
if got := errorName(code); got != want {
t.Errorf("errorName(%d) = %q, want %q", code, got, want)
}
}
}

// In --json mode the RPC error must come back intact so Execute can write
// it to stderr as JSON; nothing may go to stdout, where data belongs.
func TestHandleError_JSONModeReturnsRPCError(t *testing.T) {
prev := jsonFlag
jsonFlag = true
t.Cleanup(func() { jsonFlag = prev })

in := &jsonrpc.RPCError{Code: jsonrpc.CodeAuthRequired, Message: "Authentication required"}
var rpcErr *jsonrpc.RPCError
if !errors.As(handleError(in), &rpcErr) || rpcErr.Code != jsonrpc.CodeAuthRequired {
t.Fatalf("expected the RPC error back, got %v", handleError(in))
}
}
59 changes: 51 additions & 8 deletions cmd/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package cmd

import (
"fmt"
"io"
"os"
"strings"

"tsm/internal/client"
Expand All @@ -19,28 +21,43 @@ type secretMetadata struct {

func newListCmd() *cobra.Command {
return &cobra.Command{
Use: "list",
Use: "list [term...]",
Short: "List secrets (names and descriptions, never values)",
Long: `List secrets: names, display names, descriptions, tags, and the confirm
flag. Never values.

With terms, list only the secrets where any term appears in the name,
display name, description, or a tag. Matching ignores case.

Examples:
tsm list
tsm list anthropic
tsm list aws amazon --json`,
RunE: func(cmd *cobra.Command, args []string) error {
return withUnlockedClient(func(c client.Caller) error {
return runList(c)
return runList(c, args, os.Stdout)
})
},
}
}

func runList(c client.Caller) error {
func runList(c client.Caller, terms []string, stdout io.Writer) error {
var secrets []secretMetadata
if err := c.Call("vault.list", nil, &secrets); err != nil {
return handleError(err)
}
secrets = filterSecrets(secrets, terms)

if jsonOutput() {
return printJSON(secrets)
return printJSONTo(stdout, secrets)
}

if len(secrets) == 0 {
fmt.Println("No secrets stored. Run 'tsm add' to add one.")
if len(terms) > 0 {
fmt.Fprintf(stdout, "No secrets match %q.\n", strings.Join(terms, " "))
} else {
fmt.Fprintln(stdout, "No secrets stored. Run 'tsm add' to add one.")
}
return nil
}

Expand All @@ -57,13 +74,39 @@ func runList(c client.Caller) error {
if s.DisplayName != "" && s.DisplayName != s.Name {
label = s.DisplayName
}
fmt.Printf(" %s%s%s\n", label, confirm, tags)
fmt.Fprintf(stdout, " %s%s%s\n", label, confirm, tags)
if s.DisplayName != "" && s.DisplayName != s.Name {
fmt.Printf(" id: %s\n", s.Name)
fmt.Fprintf(stdout, " id: %s\n", s.Name)
}
if s.Description != "" {
fmt.Printf(" %s\n", s.Description)
fmt.Fprintf(stdout, " %s\n", s.Description)
}
}
return nil
}

// filterSecrets keeps the secrets where any term appears, ignoring case, in
// the name, display name, description, or a tag. No terms keeps them all.
// The result is never nil, so JSON output is [] rather than null.
func filterSecrets(secrets []secretMetadata, terms []string) []secretMetadata {
out := []secretMetadata{}
for _, s := range secrets {
if len(terms) == 0 || matchesAny(s, terms) {
out = append(out, s)
}
}
return out
}

func matchesAny(s secretMetadata, terms []string) bool {
fields := append([]string{s.Name, s.DisplayName, s.Description}, s.Tags...)
for _, term := range terms {
t := strings.ToLower(term)
for _, f := range fields {
if strings.Contains(strings.ToLower(f), t) {
return true
}
}
}
return false
}
Loading
Loading