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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,4 @@ Backward-compatible JSON. `Secret.displayName` has a custom decoder defaulting t
- **Temp / secondary vaults.** Both halves honor `XDG_DATA_HOME`, `XDG_CONFIG_HOME`, and `TSM_AUTH_SOCK`, and the CLI passes its environment through to the daemon it spawns. The master key's Keychain account is derived from the vault path (`MacKeychain.account(forVaultPath:)`): the default `~/.local/share/tsm/vault.enc` keeps the legacy `master-key` account so existing installs are untouched; any other path gets `master-key:<sha256 of path>`. So a throwaway vault under a temp `XDG_DATA_HOME` can be `tsm init`'d without clobbering the real vault's key. Keying is by path, so moving a non-default vault file strands its key (recover via passphrase). `tsm` has no `--vault` flag; use the env vars.
- **`vault.unlock` with passphrase doesn't re-store the key.** Recovery on a new device decrypts but doesn't update the Keychain entry yet.
- **`tsm get` to a TTY is rejected.** Default output is the raw value with no framing; the command refuses to write secret values to a terminal — pipe, redirect, or use `--to-file`.
- **Touch ID dialog text comes from the kernel, not the client.** `PeerCommand.swift` reads the connecting process's argv with `KERN_PROCARGS2`. For `tsm run` it shows the command after `--`; for `tsm get` it shows the parent shell's `-c` command, after it removes Claude Code's `eval '…'` wrapper (`ShellCommand.swift`). The CLI sends no `client_id`; the audit log's `command` field holds the same text. If you change `tsm run` or `tsm get` flags, update `TsmArgv.swift` too.
5 changes: 2 additions & 3 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,8 @@ func runAdd(cmd *cobra.Command, c client.Caller) error {
}

params := map[string]any{
"name": name,
"value": value,
"client_id": clientID(),
"name": name,
"value": value,
}
if displayName != "" {
params["display_name"] = displayName
Expand Down
2 changes: 1 addition & 1 deletion cmd/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func runEdit(cmd *cobra.Command, c client.Caller, name string) error {
return fmt.Errorf("secret '%s' not found", name)
}

params := map[string]any{"name": name, "client_id": clientID()}
params := map[string]any{"name": name}

noInput, _ := cmd.Flags().GetBool("no-input")

Expand Down
2 changes: 1 addition & 1 deletion cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func runGetWith(c client.Caller, name string, opts getOptions) error {
Name string `json:"name"`
Value string `json:"value"`
}
if err := c.Call("vault.get", map[string]any{"name": name, "client_id": clientID()}, &secret); err != nil {
if err := c.Call("vault.get", map[string]any{"name": name}, &secret); err != nil {
return handleError(err)
}

Expand Down
20 changes: 20 additions & 0 deletions cmd/get_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,23 @@ func TestMockCaller_RecordsCalls(t *testing.T) {

// Ensure mockCaller satisfies client.Caller at compile time.
var _ client.Caller = (*mockCaller)(nil)

func TestGet_SendsNoClientID(t *testing.T) {
mock := &mockCaller{
onCall: func(method string, params map[string]any) (any, error) {
if method == "vault.get" {
return map[string]string{"name": "gh-pat", "value": "v"}, nil
}
return nil, nil
},
}
var stdout bytes.Buffer
if err := runGetWith(mock, "gh-pat", getOptions{Stdout: &stdout}); err != nil {
t.Fatal(err)
}
for _, c := range mock.calls {
if _, ok := c.Params["client_id"]; ok {
t.Fatalf("%s sent client_id", c.Method)
}
}
}
5 changes: 0 additions & 5 deletions cmd/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,6 @@ import (
"tsm/internal/jsonrpc"
)

// clientID returns an identifier for audit logging.
func clientID() string {
return fmt.Sprintf("cli/pid:%d", os.Getpid())
}

// withClient ensures the daemon is running, dials it, runs fn, and closes.
func withClient(fn func(c client.Caller) error) error {
sockPath, err := daemon.EnsureRunning()
Expand Down
46 changes: 26 additions & 20 deletions cmd/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,26 +63,32 @@ func runLog(tail int) error {
}

for _, line := range lines {
var entry struct {
TS string `json:"ts"`
Method string `json:"method"`
Secret *string `json:"secret"`
ClientID *string `json:"client_id"`
Result string `json:"result"`
}
if err := json.Unmarshal([]byte(line), &entry); err != nil {
fmt.Println(line)
continue
}
secret := ""
if entry.Secret != nil {
secret = " " + *entry.Secret
}
clientID := ""
if entry.ClientID != nil {
clientID = " (" + *entry.ClientID + ")"
}
fmt.Printf("%s %-14s%s %s%s\n", entry.TS, entry.Method, secret, entry.Result, clientID)
fmt.Println(formatLogLine(line))
}
return nil
}

// formatLogLine renders one access log line as text. A line that is not
// valid JSON prints unchanged. Lines written before the command field
// existed may carry client_id; it is not shown.
func formatLogLine(line string) string {
var entry struct {
TS string `json:"ts"`
Method string `json:"method"`
Secret *string `json:"secret"`
Command *string `json:"command"`
Result string `json:"result"`
}
if err := json.Unmarshal([]byte(line), &entry); err != nil {
return line
}
secret := ""
if entry.Secret != nil {
secret = " " + *entry.Secret
}
command := ""
if entry.Command != nil {
command = " " + *entry.Command
}
return fmt.Sprintf("%s %-14s%s %s%s", entry.TS, entry.Method, secret, entry.Result, command)
}
33 changes: 33 additions & 0 deletions cmd/log_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cmd

import "testing"

func TestFormatLogLine_ShowsCommand(t *testing.T) {
line := `{"ts":"2026-10-05T20:58:00Z","method":"vault.get","secret":"gh-pat","command":"gh pr list --repo tashian/tsm","result":"ok"}`
want := "2026-10-05T20:58:00Z vault.get gh-pat ok gh pr list --repo tashian/tsm"
if got := formatLogLine(line); got != want {
t.Fatalf("got %q\nwant %q", got, want)
}
}

func TestFormatLogLine_OldLineWithClientID(t *testing.T) {
line := `{"ts":"2026-01-01T00:00:00Z","method":"vault.get","secret":"k","client_id":"cli/pid:1","result":"ok"}`
want := "2026-01-01T00:00:00Z vault.get k ok"
if got := formatLogLine(line); got != want {
t.Fatalf("got %q\nwant %q", got, want)
}
}

func TestFormatLogLine_NoSecretNoCommand(t *testing.T) {
line := `{"ts":"T","method":"vault.lock","secret":null,"command":null,"result":"ok"}`
want := "T vault.lock ok"
if got := formatLogLine(line); got != want {
t.Fatalf("got %q\nwant %q", got, want)
}
}

func TestFormatLogLine_InvalidJSONUnchanged(t *testing.T) {
if got := formatLogLine("not json"); got != "not json" {
t.Fatalf("got %q", got)
}
}
2 changes: 1 addition & 1 deletion cmd/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func runRemove(cmd *cobra.Command, c client.Caller, name string) error {
}
}

if err := c.Call("vault.remove", map[string]any{"name": name, "client_id": clientID()}, nil); err != nil {
if err := c.Call("vault.remove", map[string]any{"name": name}, nil); err != nil {
return handleError(err)
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/reset.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func runReset(cmd *cobra.Command, c client.Caller) error {
}
}

if err := c.Call("vault.reset", map[string]any{"client_id": clientID()}, nil); err != nil {
if err := c.Call("vault.reset", nil, nil); err != nil {
return handleError(err)
}

Expand Down
12 changes: 1 addition & 11 deletions cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"os"
"os/exec"
"path"
"strings"

"tsm/internal/client"
Expand Down Expand Up @@ -138,10 +137,7 @@ func runWith(c client.Caller, opts runOptions) error {
Name string `json:"name"`
Value string `json:"value"`
}
params := map[string]any{
"name": name,
"client_id": runClientID(path.Base(targetPath)),
}
params := map[string]any{"name": name}
if err := c.Call("vault.get", params, &s); err != nil {
return handleError(err)
}
Expand All @@ -163,9 +159,3 @@ func execveRunner(path string, argv, addedEnv []string) error {
full := append(os.Environ(), addedEnv...)
return unix.Exec(path, argv, full)
}

// runClientID returns the client_id used in vault.get audit log entries
// for tsm run invocations.
func runClientID(targetBasename string) string {
return fmt.Sprintf("tsm-run/pid:%d/%s", os.Getpid(), targetBasename)
}
29 changes: 29 additions & 0 deletions cmd/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,32 @@ func TestRun_DedupesVaultGets(t *testing.T) {
t.Fatalf("expected 2 env vars, got %v", rec.Env)
}
}

func TestRun_SendsNoClientID(t *testing.T) {
mock := &mockCaller{
onCall: func(method string, params map[string]any) (any, error) {
switch method {
case "vault.list":
return []map[string]any{{"name": "gh-pat", "confirm": false}}, nil
case "vault.get":
return map[string]string{"name": "gh-pat", "value": "v"}, nil
}
return nil, nil
},
}
var rec recordedExec
err := runWith(mock, runOptions{
Envs: []string{"GITHUB_TOKEN=gh-pat"},
Argv: []string{"echo"},
Runner: newFakeRunner(&rec),
LookPath: func(name string) (string, error) { return "/bin/" + name, nil },
})
if err != nil {
t.Fatal(err)
}
for _, c := range mock.calls {
if _, ok := c.Params["client_id"]; ok {
t.Fatalf("%s sent client_id", c.Method)
}
}
}
2 changes: 1 addition & 1 deletion plugin/skills/credential-usage/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: Use whenever a task needs an API key, token, password, database URL

# Using credentials from the tsm vault

`tsm` is a Touch ID-gated secrets vault on this Mac. The user installed this plugin so you pull credentials from it instead of asking for them. `tsm list`, `tsm get`, and `tsm status` are allowlisted for you. `tsm run` is not, because it runs whatever command follows `--`, so the user approves each one; every other subcommand (`add`, `edit`, `remove`, `reset`, `init`, `config set`) changes the vault and is the user's to run. The first vault access in a session blocks on a system Touch ID dialog until the user responds. Do not kill or retry it.
`tsm` is a Touch ID-gated secrets vault on this Mac. The user installed this plugin so you pull credentials from it instead of asking for them. `tsm list`, `tsm get`, and `tsm status` are allowlisted for you. `tsm run` is not, because it runs whatever command follows `--`, so the user approves each one; every other subcommand (`add`, `edit`, `remove`, `reset`, `init`, `config set`) changes the vault and is the user's to run. The first vault access in a session blocks on a system Touch ID dialog until the user responds. Do not kill or retry it. The dialog shows the command that receives the secret, so keep that command short and readable: the user approves what the dialog shows.

## Workflow

Expand Down
13 changes: 5 additions & 8 deletions tsmd/Sources/tsmd/AccessLog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@ struct AccessLogEntry: Codable {
let ts: String
let method: String
let secret: String?
let clientId: String?
/// The command the daemon read from the peer process. Older lines have
/// `client_id` in its place; the decoder ignores that key.
let command: String?
let result: String

enum CodingKeys: String, CodingKey {
case ts, method, secret, result
case clientId = "client_id"
}
}

final class FileAccessLog: AccessLogProvider, @unchecked Sendable {
Expand All @@ -29,15 +26,15 @@ final class FileAccessLog: AccessLogProvider, @unchecked Sendable {
self.maxSize = maxSize
}

func log(method: String, secret: String?, clientId: String?, result: String) throws {
func log(method: String, secret: String?, command: String?, result: String) throws {
lock.lock()
defer { lock.unlock() }

let entry = AccessLogEntry(
ts: dateFormatter.string(from: Date()),
method: method,
secret: secret,
clientId: clientId,
command: command,
result: result
)
let data = try encoder.encode(entry)
Expand Down
23 changes: 23 additions & 0 deletions tsmd/Sources/tsmd/ApprovalSet.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import Foundation

/// Confirm-gated secrets the user approved in a Touch ID dialog on one
/// connection. Lives as long as the connection. Names match without case,
/// as the vault's lookup does.
final class ApprovalSet: @unchecked Sendable {
private var names: Set<String> = []
private let lock = NSLock()

init() {}

func contains(_ name: String) -> Bool {
lock.lock()
defer { lock.unlock() }
return names.contains(name.lowercased())
}

func insert(_ more: [String]) {
lock.lock()
defer { lock.unlock() }
names.formUnion(more.map { $0.lowercased() })
}
}
51 changes: 51 additions & 0 deletions tsmd/Sources/tsmd/CommandText.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import Foundation

/// Turns process arguments into one line of text that a person can read in a
/// Touch ID dialog, and that cannot hide or reorder what will run.
enum CommandText {
static let dialogLimit = 300

private static let safe = CharacterSet(charactersIn:
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_@%+=:,./-")

/// Replaces newline, carriage return, tab, and every Unicode separator
/// (Zs, Zl, Zp; Zl/Zp would break the dialog's lines) with a space.
/// Removes all other control (Cc) and format (Cf) characters; Cf
/// includes the bidirectional overrides.
static func clean(_ s: String) -> String {
var out = String.UnicodeScalarView()
for u in s.unicodeScalars {
if u == "\n" || u == "\r" || u == "\t" {
out.append(" ")
continue
}
switch u.properties.generalCategory {
case .spaceSeparator, .lineSeparator, .paragraphSeparator: out.append(" ")
case .control, .format: continue
default: out.append(u)
}
}
return String(out)
}

/// Single-quotes an argument the way a POSIX shell would need it, unless
/// it contains only characters that need no quoting.
static func quote(_ arg: String) -> String {
if arg.isEmpty { return "''" }
if arg.unicodeScalars.allSatisfy({ safe.contains($0) }) { return arg }
return "'" + arg.replacingOccurrences(of: "'", with: #"'\''"#) + "'"
}

static func join(_ argv: [String]) -> String {
argv.map { quote(clean($0)) }.joined(separator: " ")
}

/// Keeps the start (the program) and the end of a long command, and puts
/// "…" in place of the middle.
static func truncate(_ s: String, limit: Int) -> String {
guard s.count > limit, limit > 1 else { return s }
let head = limit / 2
let tail = limit - head - 1
return String(s.prefix(head)) + "…" + String(s.suffix(tail))
}
}
21 changes: 21 additions & 0 deletions tsmd/Sources/tsmd/DialogReason.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Foundation

/// Builds the Touch ID dialog reason. macOS shows it as
/// "tsmd is trying to <reason>." and adds the period itself.
enum DialogReason {
enum Action { case unlock, access }

static func make(_ action: Action, secrets: [String], command: String?) -> String {
let names = secrets.map { "'\($0)'" }.joined(separator: " and ")
var head: String
switch action {
case .unlock:
head = "unlock the vault"
if !names.isEmpty { head += " and access " + names }
case .access:
head = "access " + names
}
guard let command, !command.isEmpty else { return head }
return head + ":\n\n" + CommandText.truncate(command, limit: CommandText.dialogLimit)
}
}
Loading
Loading