From 76ec61f56201c1eadd7140f8c27794ab4916fe71 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Sun, 8 Nov 2026 14:01:03 -0300 Subject: [PATCH 1/4] chore(telemetry): remove cli telemetry --- internal/cmd/root.go | 57 +----- internal/cmd/telemetry.go | 168 ----------------- internal/cmd/telemetry_test.go | 163 ---------------- internal/telemetry/sender.go | 78 -------- internal/telemetry/sender_test.go | 124 ------------ internal/telemetry/telemetry.go | 259 ------------------------- internal/telemetry/telemetry_test.go | 271 --------------------------- 7 files changed, 1 insertion(+), 1119 deletions(-) delete mode 100644 internal/cmd/telemetry.go delete mode 100644 internal/cmd/telemetry_test.go delete mode 100644 internal/telemetry/sender.go delete mode 100644 internal/telemetry/sender_test.go delete mode 100644 internal/telemetry/telemetry.go delete mode 100644 internal/telemetry/telemetry_test.go diff --git a/internal/cmd/root.go b/internal/cmd/root.go index 9fd37de..6bc8b10 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -3,14 +3,11 @@ package cmd import ( "fmt" "os" - "sync" - "time" "github.com/spf13/cobra" "golang.org/x/term" "github.com/ararahq/cli/internal/output" - "github.com/ararahq/cli/internal/telemetry" "github.com/ararahq/cli/internal/tui" "github.com/ararahq/cli/internal/version" ) @@ -30,12 +27,6 @@ var ( globalNoColor bool ) -// commandStartTimes holds the wall-clock at which the current command's -// PersistentPreRun fired, so PersistentPostRunE can compute durationMs -// for telemetry. Keyed by *cobra.Command pointer in case sibling commands -// somehow run concurrently inside a single process (REPL). -var commandStartTimes sync.Map - var rootCmd = &cobra.Command{ Use: "arara", Short: "AraraHQ CLI \u2014 WhatsApp API Platform", @@ -45,13 +36,8 @@ var rootCmd = &cobra.Command{ SilenceErrors: true, PersistentPreRun: func(command *cobra.Command, arguments []string) { applyGlobalFlags() - commandStartTimes.Store(command, time.Now()) maybePrintOAuthNudge(command) }, - PersistentPostRunE: func(command *cobra.Command, arguments []string) error { - recordCommandTelemetry(command, 0) - return nil - }, RunE: func(command *cobra.Command, arguments []string) error { if term.IsTerminal(int(os.Stdin.Fd())) { return tui.RunREPL() @@ -63,33 +49,6 @@ var rootCmd = &cobra.Command{ }, } -// recordCommandTelemetry enqueues an Event for the just-completed command -// and flushes synchronously (with a short timeout) so the process can exit -// without leaking events. exitCode=0 from PostRun; the wrapper layer in -// Execute() rewrites it on error before flush. -func recordCommandTelemetry(command *cobra.Command, exitCode int) { - recorder := resolveTelemetryRecorder() - if !recorder.Enabled() { - return - } - - startedAtRaw, ok := commandStartTimes.LoadAndDelete(command) - if !ok { - return - } - startedAt, ok := startedAtRaw.(time.Time) - if !ok { - return - } - - recorder.Record(telemetry.Event{ - Command: command.Name(), - ExitCode: exitCode, - DurationMs: int(time.Since(startedAt).Milliseconds()), - CLIVersion: version.Version, - }) -} - const helpTemplate = `{{with .Long}}{{. | trimTrailingWhitespaces}}{{end}} {{if .HasAvailableSubCommands}}Commands:{{range .Commands}}{{if .IsAvailableCommand}} @@ -120,21 +79,7 @@ func init() { func Execute() error { registerDiscoveredPlugins(rootCmd) registerDiscoveredCommands(rootCmd) - executeError := rootCmd.Execute() - flushTelemetryQuietly() - return executeError -} - -// flushTelemetryQuietly drains the recorder on process exit. Errors are -// swallowed (printed only in verbose mode) — telemetry never blocks exit. -func flushTelemetryQuietly() { - recorder := resolveTelemetryRecorder() - if !recorder.Enabled() { - return - } - if flushErr := recorder.Flush(); flushErr != nil && IsVerbose() { - fmt.Fprintf(os.Stderr, "[telemetry] flush: %v\n", flushErr) - } + return rootCmd.Execute() } func applyGlobalFlags() { diff --git a/internal/cmd/telemetry.go b/internal/cmd/telemetry.go deleted file mode 100644 index 18927b5..0000000 --- a/internal/cmd/telemetry.go +++ /dev/null @@ -1,168 +0,0 @@ -package cmd - -import ( - "fmt" - "io" - "os" - "sync" - - "github.com/spf13/cobra" - - "github.com/ararahq/cli/internal/api" - "github.com/ararahq/cli/internal/output" - "github.com/ararahq/cli/internal/telemetry" -) - -// telemetryRecorderOnce builds (and lazily caches) the process-wide Recorder -// used by all command wrappers via PersistentPreRun/PostRun. We resolve -// state from disk once, then every Cobra hook reads from the same instance. -var ( - telemetryRecorderOnce sync.Once - telemetryRecorderInst *telemetry.Recorder -) - -var telemetryCmd = &cobra.Command{ - Use: "telemetry", - Short: "Manage anonymous CLI usage telemetry (off by default)", - Long: "Telemetry sends a small set of anonymized metrics — command name, exit\n" + - "code, latency, CLI version, platform, and a locally-generated UUID — to\n" + - "AraraHQ so we can prioritize improvements based on real usage. We never\n" + - "capture phone numbers, message bodies, recipient names, template content,\n" + - "or API keys. Off by default; opt in with `arara telemetry on`.", -} - -var telemetryOnCmd = &cobra.Command{ - Use: "on", - Short: "Enable anonymous telemetry", - RunE: runTelemetryOn, -} - -var telemetryOffCmd = &cobra.Command{ - Use: "off", - Short: "Disable telemetry and stop sending events", - RunE: runTelemetryOff, -} - -var telemetryStatusCmd = &cobra.Command{ - Use: "status", - Short: "Show whether telemetry is enabled and the local anonymous id", - RunE: runTelemetryStatus, -} - -func init() { - telemetryCmd.AddCommand(telemetryOnCmd) - telemetryCmd.AddCommand(telemetryOffCmd) - telemetryCmd.AddCommand(telemetryStatusCmd) - rootCmd.AddCommand(telemetryCmd) -} - -func runTelemetryOn(_ *cobra.Command, _ []string) error { - home, err := userHomeDir() - if err != nil { - return err - } - state, loadErr := telemetry.LoadState(home) - if loadErr != nil { - return loadErr - } - state.Enabled = true - state, ensureErr := telemetry.EnsureAnonymousID(home, state) - if ensureErr != nil { - return ensureErr - } - if saveErr := telemetry.SaveState(home, state); saveErr != nil { - return saveErr - } - - output.PrintSuccess("Telemetry enabled.") - output.PrintInfo(fmt.Sprintf("Anonymous ID: %s", state.AnonymousID)) - output.PrintInfo("We collect: command name, exit code, latency, CLI version, platform.") - output.PrintInfo("We never collect: phone numbers, message bodies, contacts, template content, API keys.") - return nil -} - -func runTelemetryOff(_ *cobra.Command, _ []string) error { - home, err := userHomeDir() - if err != nil { - return err - } - state, loadErr := telemetry.LoadState(home) - if loadErr != nil { - return loadErr - } - state.Enabled = false - if saveErr := telemetry.SaveState(home, state); saveErr != nil { - return saveErr - } - - output.PrintSuccess("Telemetry disabled. No further events will be sent.") - return nil -} - -func runTelemetryStatus(_ *cobra.Command, _ []string) error { - home, err := userHomeDir() - if err != nil { - return err - } - state, loadErr := telemetry.LoadState(home) - if loadErr != nil { - return loadErr - } - - return printTelemetryStatus(os.Stdout, state) -} - -func printTelemetryStatus(writer io.Writer, state telemetry.State) error { - if state.Enabled { - fmt.Fprintln(writer, output.SuccessStyle.Render("enabled")) - } else { - fmt.Fprintln(writer, output.DimStyle.Render("disabled")) - } - if state.AnonymousID != "" { - fmt.Fprintf(writer, "anonymous id: %s\n", state.AnonymousID) - } - return nil -} - -// resolveTelemetryRecorder returns the singleton Recorder used by Cobra -// hooks. Built lazily so commands like `arara --help` don't pay the cost -// of disk I/O. -func resolveTelemetryRecorder() *telemetry.Recorder { - telemetryRecorderOnce.Do(func() { - home, err := userHomeDir() - if err != nil { - return - } - state, loadErr := telemetry.LoadState(home) - if loadErr != nil || !state.Enabled || state.AnonymousID == "" { - return - } - baseURL := defaultTelemetryBaseURL() - if baseURL == "" { - return - } - telemetryRecorderInst = telemetry.NewRecorder(state, telemetry.NewHTTPSender(baseURL)) - }) - return telemetryRecorderInst -} - -// defaultTelemetryBaseURL pulls the API URL from the active config so -// telemetry follows the same environment (staging/prod) the user is on. -func defaultTelemetryBaseURL() string { - client, err := newClientForCmd() - if err != nil || client == nil { - return "" - } - return client.BaseURL() -} - -func userHomeDir() (string, error) { - dir, err := os.UserHomeDir() - if err != nil { - return "", fmt.Errorf("resolve home dir: %w", err) - } - return dir, nil -} - -// silence unused-import warning when api isn't directly referenced. -var _ = api.NewClient diff --git a/internal/cmd/telemetry_test.go b/internal/cmd/telemetry_test.go deleted file mode 100644 index 2db3970..0000000 --- a/internal/cmd/telemetry_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package cmd - -import ( - "bytes" - "os" - "path/filepath" - "strings" - "sync" - "testing" - - "github.com/ararahq/cli/internal/telemetry" -) - -func TestRunTelemetryOn_PersistsEnabledStateAndID(t *testing.T) { - home := t.TempDir() - t.Setenv("HOME", home) - - if err := runTelemetryOn(nil, nil); err != nil { - t.Fatalf("runTelemetryOn: %v", err) - } - - state, err := telemetry.LoadState(home) - if err != nil { - t.Fatalf("LoadState: %v", err) - } - if !state.Enabled { - t.Error("state should be enabled after on") - } - if state.AnonymousID == "" { - t.Error("anonymous id should be generated") - } -} - -func TestRunTelemetryOff_PersistsDisabledState(t *testing.T) { - home := t.TempDir() - t.Setenv("HOME", home) - - // First enable - if err := runTelemetryOn(nil, nil); err != nil { - t.Fatal(err) - } - - if err := runTelemetryOff(nil, nil); err != nil { - t.Fatalf("runTelemetryOff: %v", err) - } - - state, _ := telemetry.LoadState(home) - if state.Enabled { - t.Error("state should be disabled after off") - } - if state.AnonymousID == "" { - t.Error("anonymous id should be preserved across off (no need to re-roll)") - } -} - -func TestRunTelemetryStatus_PrintsState(t *testing.T) { - home := t.TempDir() - t.Setenv("HOME", home) - - if err := telemetry.SaveState(home, telemetry.State{Enabled: true, AnonymousID: "abc-123"}); err != nil { - t.Fatal(err) - } - - if err := runTelemetryStatus(nil, nil); err != nil { - t.Errorf("runTelemetryStatus: %v", err) - } -} - -func TestPrintTelemetryStatus_EnabledRenders(t *testing.T) { - buffer := &bytes.Buffer{} - state := telemetry.State{Enabled: true, AnonymousID: "anon-xyz"} - - if err := printTelemetryStatus(buffer, state); err != nil { - t.Fatal(err) - } - - rendered := buffer.String() - if !strings.Contains(rendered, "enabled") { - t.Errorf("output should contain 'enabled', got: %q", rendered) - } - if !strings.Contains(rendered, "anon-xyz") { - t.Errorf("output should contain anonymous id, got: %q", rendered) - } -} - -func TestPrintTelemetryStatus_DisabledRenders(t *testing.T) { - buffer := &bytes.Buffer{} - if err := printTelemetryStatus(buffer, telemetry.State{Enabled: false}); err != nil { - t.Fatal(err) - } - if !strings.Contains(buffer.String(), "disabled") { - t.Errorf("output should contain 'disabled', got: %q", buffer.String()) - } -} - -func TestRunTelemetryOn_OverwritesExistingId(t *testing.T) { - home := t.TempDir() - t.Setenv("HOME", home) - - // Pre-populate with a known id and disabled state - preexisting := telemetry.State{Enabled: false, AnonymousID: "preexisting-id"} - if err := telemetry.SaveState(home, preexisting); err != nil { - t.Fatal(err) - } - - if err := runTelemetryOn(nil, nil); err != nil { - t.Fatalf("runTelemetryOn: %v", err) - } - - state, _ := telemetry.LoadState(home) - if !state.Enabled { - t.Error("should be enabled after on") - } - if state.AnonymousID != "preexisting-id" { - t.Errorf("existing id should be preserved across on, got %q", state.AnonymousID) - } -} - -func TestUserHomeDir_ReturnsValue(t *testing.T) { - home, err := userHomeDir() - if err != nil { - t.Fatalf("userHomeDir: %v", err) - } - if home == "" { - t.Error("home should not be empty") - } -} - -func TestResolveTelemetryRecorder_NilWhenStateMissing(t *testing.T) { - // Reset the singleton — sync.Once means tests can race. Use a new - // HOME so LoadState returns zero value. - resetTelemetryRecorderSingleton(t) - t.Setenv("HOME", t.TempDir()) - - got := resolveTelemetryRecorder() - if got.Enabled() { - t.Error("recorder should not be enabled when state file missing") - } -} - -// resetTelemetryRecorderSingleton clears the cached recorder so tests can -// drive resolveTelemetryRecorder with a fresh state. Restores on cleanup. -// -// We can't copy a sync.Once value (vet rule), so we just zero out the -// recorder pointer and replace the Once with a freshly-zero one. The -// cleanup path does the same — anything that previously ran one-shot -// initialization is allowed to run again in the next test that needs it. -func resetTelemetryRecorderSingleton(t *testing.T) { - t.Helper() - originalInst := telemetryRecorderInst - t.Cleanup(func() { - telemetryRecorderInst = originalInst - telemetryRecorderOnce = sync.Once{} - }) - telemetryRecorderInst = nil - telemetryRecorderOnce = sync.Once{} -} - -// silence unused-import warning if filepath/os not referenced elsewhere -var ( - _ = os.UserHomeDir - _ = filepath.Join -) diff --git a/internal/telemetry/sender.go b/internal/telemetry/sender.go deleted file mode 100644 index afe6050..0000000 --- a/internal/telemetry/sender.go +++ /dev/null @@ -1,78 +0,0 @@ -package telemetry - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - "time" -) - -const ( - httpSendTimeout = 5 * time.Second - contentTypeHeader = "Content-Type" - contentTypeJSON = "application/json" - userAgentHeader = "User-Agent" - defaultUserAgent = "arara-cli-telemetry" -) - -type httpSendBody struct { - Events []Event `json:"events"` -} - -// HTTPSender ships batches over HTTP to the AraraHQ telemetry endpoint. -// Stateless and safe to keep around for the lifetime of the process. -type HTTPSender struct { - BaseURL string - Path string - HTTPClient *http.Client - UserAgent string -} - -// NewHTTPSender builds a sender wired to the given base URL. The path -// defaults to DefaultIngestPath; callers can override for tests or to -// point at a staging endpoint. -func NewHTTPSender(baseURL string) *HTTPSender { - return &HTTPSender{ - BaseURL: strings.TrimRight(baseURL, "/"), - Path: DefaultIngestPath, - HTTPClient: &http.Client{Timeout: httpSendTimeout}, - UserAgent: defaultUserAgent, - } -} - -// Send POSTs one batch. Returns nil on 2xx, error on anything else. The -// caller (Recorder.Flush) decides what to do with the error — usually -// log in verbose mode and move on. -func (sender *HTTPSender) Send(events []Event) error { - if len(events) == 0 { - return nil - } - - encoded, marshalErr := json.Marshal(httpSendBody{Events: events}) - if marshalErr != nil { - return fmt.Errorf("encode telemetry batch: %w", marshalErr) - } - - url := sender.BaseURL + sender.Path - request, requestErr := http.NewRequest(http.MethodPost, url, bytes.NewReader(encoded)) - if requestErr != nil { - return fmt.Errorf("build telemetry request: %w", requestErr) - } - request.Header.Set(contentTypeHeader, contentTypeJSON) - request.Header.Set(userAgentHeader, sender.UserAgent) - - response, doErr := sender.HTTPClient.Do(request) - if doErr != nil { - return fmt.Errorf("send telemetry: %w", doErr) - } - defer response.Body.Close() - _, _ = io.Copy(io.Discard, response.Body) - - if response.StatusCode >= 300 { - return fmt.Errorf("telemetry endpoint returned HTTP %d", response.StatusCode) - } - return nil -} diff --git a/internal/telemetry/sender_test.go b/internal/telemetry/sender_test.go deleted file mode 100644 index d3fc24c..0000000 --- a/internal/telemetry/sender_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package telemetry - -import ( - "encoding/json" - "io" - "net/http" - "net/http/httptest" - "strings" - "sync" - "testing" - "time" -) - -func TestHTTPSender_Send_GoldenPath(t *testing.T) { - var ( - mu sync.Mutex - receivedPath string - receivedMethod string - receivedCT string - receivedBody []byte - ) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, _ := io.ReadAll(r.Body) - mu.Lock() - receivedPath = r.URL.Path - receivedMethod = r.Method - receivedCT = r.Header.Get("Content-Type") - receivedBody = body - mu.Unlock() - w.WriteHeader(http.StatusNoContent) - })) - t.Cleanup(server.Close) - - sender := NewHTTPSender(server.URL) - events := []Event{ - { - Timestamp: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC), - Command: "send", - ExitCode: 0, - DurationMs: 150, - CLIVersion: "0.2.0", - Platform: "darwin/arm64", - AnonymousID: "anon-1", - }, - } - - if err := sender.Send(events); err != nil { - t.Fatalf("Send: %v", err) - } - - mu.Lock() - defer mu.Unlock() - - if receivedPath != DefaultIngestPath { - t.Errorf("path: want %q, got %q", DefaultIngestPath, receivedPath) - } - if receivedMethod != http.MethodPost { - t.Errorf("method: want POST, got %s", receivedMethod) - } - if receivedCT != contentTypeJSON { - t.Errorf("content-type: want %q, got %q", contentTypeJSON, receivedCT) - } - - var decoded httpSendBody - if err := json.Unmarshal(receivedBody, &decoded); err != nil { - t.Fatalf("server received malformed JSON: %v", err) - } - if len(decoded.Events) != 1 || decoded.Events[0].Command != "send" { - t.Errorf("server received wrong events: %+v", decoded.Events) - } -} - -func TestHTTPSender_Send_EmptyIsNoop(t *testing.T) { - called := false - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - called = true - w.WriteHeader(http.StatusNoContent) - })) - t.Cleanup(server.Close) - - sender := NewHTTPSender(server.URL) - if err := sender.Send(nil); err != nil { - t.Errorf("empty Send should be nil error, got: %v", err) - } - if called { - t.Error("empty Send should not hit the network") - } -} - -func TestHTTPSender_Send_5xxIsError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusInternalServerError) - })) - t.Cleanup(server.Close) - - sender := NewHTTPSender(server.URL) - err := sender.Send([]Event{{Command: "send"}}) - if err == nil { - t.Fatal("expected error from 500") - } - if !strings.Contains(err.Error(), "500") { - t.Errorf("error should mention status, got: %v", err) - } -} - -func TestHTTPSender_Send_429IsError(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusTooManyRequests) - })) - t.Cleanup(server.Close) - - sender := NewHTTPSender(server.URL) - if err := sender.Send([]Event{{Command: "x"}}); err == nil { - t.Fatal("expected error from 429") - } -} - -func TestHTTPSender_TrimsTrailingSlashFromBaseURL(t *testing.T) { - sender := NewHTTPSender("https://api.example.com/api/") - if sender.BaseURL != "https://api.example.com/api" { - t.Errorf("trailing slash not trimmed, got %q", sender.BaseURL) - } -} diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.go deleted file mode 100644 index a1dcdd8..0000000 --- a/internal/telemetry/telemetry.go +++ /dev/null @@ -1,259 +0,0 @@ -// Package telemetry collects opt-in usage metrics from the CLI and ships -// them in batches to the AraraHQ backend. The design rules are short: -// -// - **Off by default.** No event is recorded until the user runs -// `arara telemetry on`. Their consent is persisted on disk. -// - **No PII.** We never capture phone numbers, message bodies, recipient -// names, template content, or API keys. The schema is intentionally -// small (command name, exit code, latency, version, platform). -// - **Anonymous.** A UUID v4 generated once and stored locally identifies -// the install, not the user. Not joinable to any AraraHQ account. -// - **Fire and forget.** Telemetry never blocks the user — failures to -// enqueue or flush are silent except in verbose mode. -package telemetry - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "path/filepath" - "runtime" - "sync" - "time" - - "github.com/google/uuid" -) - -const ( - // MaxBatchSize must match the backend cap (CliTelemetryService.MAX_BATCH_SIZE). - MaxBatchSize = 50 - - // DefaultIngestPath is the API path the events go to. Joined to the - // active client's BaseURL. - DefaultIngestPath = "/v1/cli/telemetry/events" - - dirName = ".arara" - configFileName = "telemetry.json" - idFileName = "telemetry-id" - dirPerms = 0o700 - filePerms = 0o600 -) - -// Event is the on-the-wire record. Field names match the backend -// CliTelemetryEventDto exactly so the JSON encoding round-trips unchanged. -type Event struct { - Timestamp time.Time `json:"timestamp"` - Command string `json:"command"` - ExitCode int `json:"exitCode"` - DurationMs int `json:"durationMs"` - CLIVersion string `json:"cliVersion"` - Platform string `json:"platform"` - AnonymousID string `json:"anonymousId"` -} - -// State is the persisted opt-in flag + anonymous id pointer. Stored as -// telemetry.json next to the rest of the CLI config. -type State struct { - Enabled bool `json:"enabled"` - AnonymousID string `json:"anonymousId"` -} - -// Recorder accumulates events in memory and flushes them in batches to the -// configured Sender. Safe for concurrent use — each Cobra command may end -// up triggering a Record concurrently with a background flush. -type Recorder struct { - mu sync.Mutex - events []Event - sender Sender - state State - disabled bool -} - -// Sender is what actually ships a batch over the network. Implemented by -// HTTPSender in production and replaced by a fake in tests so we don't -// need an httptest server for every test that touches Record. -type Sender interface { - Send(events []Event) error -} - -// NewRecorder builds a Recorder honoring the persisted opt-in state. When -// the user has not opted in, every Record call is a no-op and Flush sends -// nothing. -func NewRecorder(state State, sender Sender) *Recorder { - return &Recorder{ - sender: sender, - state: state, - disabled: !state.Enabled, - } -} - -// Record enqueues a single event. Drops it silently when telemetry is off, -// or when the queue is full. We never apply backpressure to the calling -// command — the user shouldn't pay latency for telemetry. -func (recorder *Recorder) Record(event Event) { - if recorder == nil || recorder.disabled { - return - } - if event.AnonymousID == "" { - event.AnonymousID = recorder.state.AnonymousID - } - if event.CLIVersion == "" { - event.CLIVersion = "dev" - } - if event.Platform == "" { - event.Platform = fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH) - } - if event.Timestamp.IsZero() { - event.Timestamp = time.Now().UTC() - } - - recorder.mu.Lock() - defer recorder.mu.Unlock() - if len(recorder.events) >= MaxBatchSize*2 { - // Bound the queue so a long-running command (REPL, mcp) doesn't - // leak memory. Drop the oldest to keep the most recent context. - recorder.events = recorder.events[len(recorder.events)-MaxBatchSize:] - } - recorder.events = append(recorder.events, event) -} - -// Flush sends every queued event, splitting into batches of MaxBatchSize. -// Errors from Sender are returned but the queue is drained either way — -// retrying the same batch indefinitely creates worse problems than dropping. -func (recorder *Recorder) Flush() error { - if recorder == nil || recorder.disabled { - return nil - } - - recorder.mu.Lock() - pending := recorder.events - recorder.events = nil - recorder.mu.Unlock() - - if len(pending) == 0 { - return nil - } - - var firstErr error - for start := 0; start < len(pending); start += MaxBatchSize { - end := start + MaxBatchSize - if end > len(pending) { - end = len(pending) - } - batch := pending[start:end] - if sendErr := recorder.sender.Send(batch); sendErr != nil && firstErr == nil { - firstErr = sendErr - } - } - return firstErr -} - -// PendingCount returns the in-memory queue size — useful for tests and -// for verbose-mode logging at command exit. -func (recorder *Recorder) PendingCount() int { - if recorder == nil { - return 0 - } - recorder.mu.Lock() - defer recorder.mu.Unlock() - return len(recorder.events) -} - -// Enabled reports whether the user opted in. Cobra wrappers use this to -// gate per-command timing instrumentation when telemetry is off. -func (recorder *Recorder) Enabled() bool { - return recorder != nil && !recorder.disabled -} - -// LoadState reads telemetry.json. Missing file = telemetry off (zero State). -func LoadState(homeDir string) (State, error) { - path := stateFilePath(homeDir) - bytes, readErr := os.ReadFile(path) - if readErr != nil { - if errors.Is(readErr, os.ErrNotExist) { - return State{}, nil - } - return State{}, fmt.Errorf("read telemetry state: %w", readErr) - } - - var state State - if unmarshalErr := json.Unmarshal(bytes, &state); unmarshalErr != nil { - return State{}, fmt.Errorf("parse telemetry state: %w", unmarshalErr) - } - return state, nil -} - -// SaveState persists opt-in + anonymous id atomically. -func SaveState(homeDir string, state State) error { - dir := stateDirPath(homeDir) - if mkErr := os.MkdirAll(dir, dirPerms); mkErr != nil { - return fmt.Errorf("create telemetry dir: %w", mkErr) - } - - encoded, marshalErr := json.MarshalIndent(state, "", " ") - if marshalErr != nil { - return fmt.Errorf("encode telemetry state: %w", marshalErr) - } - - if writeErr := writeStateAtomic(dir, stateFilePath(homeDir), encoded); writeErr != nil { - return writeErr - } - - // Mirror the anonymous id into a standalone file too — some operators - // want a single short file they can grep without parsing JSON. - idPath := filepath.Join(dir, idFileName) - _ = os.WriteFile(idPath, []byte(state.AnonymousID+"\n"), filePerms) - return nil -} - -// writeStateAtomic writes `encoded` to a sibling temp file in `dir`, chmods -// to filePerms, and renames it on top of `finalPath`. Failures clean up the -// temp file so the directory doesn't accumulate `.telemetry.*.tmp` debris. -func writeStateAtomic(dir, finalPath string, encoded []byte) error { - tempFile, tempErr := os.CreateTemp(dir, ".telemetry.*.tmp") - if tempErr != nil { - return fmt.Errorf("create temp: %w", tempErr) - } - tempPath := tempFile.Name() - - if _, writeErr := tempFile.Write(encoded); writeErr != nil { - _ = tempFile.Close() - _ = os.Remove(tempPath) - return fmt.Errorf("write temp: %w", writeErr) - } - if closeErr := tempFile.Close(); closeErr != nil { - _ = os.Remove(tempPath) - return fmt.Errorf("close temp: %w", closeErr) - } - if chmodErr := os.Chmod(tempPath, filePerms); chmodErr != nil { - _ = os.Remove(tempPath) - return fmt.Errorf("chmod temp: %w", chmodErr) - } - if renameErr := os.Rename(tempPath, finalPath); renameErr != nil { - _ = os.Remove(tempPath) - return fmt.Errorf("rename: %w", renameErr) - } - return nil -} - -// EnsureAnonymousID returns the existing id from state or generates a new -// UUID v4 and persists it. Deterministic per install — never re-rolled. -func EnsureAnonymousID(homeDir string, state State) (State, error) { - if state.AnonymousID != "" { - return state, nil - } - state.AnonymousID = uuid.NewString() - if saveErr := SaveState(homeDir, state); saveErr != nil { - return state, saveErr - } - return state, nil -} - -func stateDirPath(homeDir string) string { - return filepath.Join(homeDir, dirName) -} - -func stateFilePath(homeDir string) string { - return filepath.Join(stateDirPath(homeDir), configFileName) -} diff --git a/internal/telemetry/telemetry_test.go b/internal/telemetry/telemetry_test.go deleted file mode 100644 index 9a4e206..0000000 --- a/internal/telemetry/telemetry_test.go +++ /dev/null @@ -1,271 +0,0 @@ -package telemetry - -import ( - "errors" - "os" - "path/filepath" - "sync" - "testing" - "time" -) - -// fakeSender records every batch it received in order. Used for tests -// that need to assert what got shipped. -type fakeSender struct { - mu sync.Mutex - batches [][]Event - failNext bool -} - -func (sender *fakeSender) Send(events []Event) error { - sender.mu.Lock() - defer sender.mu.Unlock() - if sender.failNext { - sender.failNext = false - return errors.New("simulated send failure") - } - cloned := make([]Event, len(events)) - copy(cloned, events) - sender.batches = append(sender.batches, cloned) - return nil -} - -func (sender *fakeSender) totalEvents() int { - sender.mu.Lock() - defer sender.mu.Unlock() - count := 0 - for _, batch := range sender.batches { - count += len(batch) - } - return count -} - -func TestRecorder_DisabledIsNoop(t *testing.T) { - sender := &fakeSender{} - recorder := NewRecorder(State{Enabled: false}, sender) - - for i := 0; i < 10; i++ { - recorder.Record(Event{Command: "send"}) - } - if recorder.PendingCount() != 0 { - t.Errorf("disabled recorder should not enqueue, got %d", recorder.PendingCount()) - } - if err := recorder.Flush(); err != nil { - t.Errorf("flush of disabled recorder should be nil error, got: %v", err) - } - if sender.totalEvents() != 0 { - t.Errorf("disabled recorder should never call Send, got %d events", sender.totalEvents()) - } -} - -func TestRecorder_EnabledRecordsAndFlushes(t *testing.T) { - sender := &fakeSender{} - recorder := NewRecorder(State{Enabled: true, AnonymousID: "test-id"}, sender) - - recorder.Record(Event{Command: "send", ExitCode: 0}) - recorder.Record(Event{Command: "logs", ExitCode: 0}) - - if recorder.PendingCount() != 2 { - t.Errorf("want 2 pending, got %d", recorder.PendingCount()) - } - - if err := recorder.Flush(); err != nil { - t.Fatalf("flush: %v", err) - } - if sender.totalEvents() != 2 { - t.Errorf("want 2 sent, got %d", sender.totalEvents()) - } - if recorder.PendingCount() != 0 { - t.Errorf("flush should drain queue, got %d pending", recorder.PendingCount()) - } -} - -func TestRecorder_FillsDefaultFields(t *testing.T) { - sender := &fakeSender{} - recorder := NewRecorder(State{Enabled: true, AnonymousID: "anon-xyz"}, sender) - - recorder.Record(Event{Command: "send"}) - if err := recorder.Flush(); err != nil { - t.Fatal(err) - } - - if len(sender.batches) != 1 || len(sender.batches[0]) != 1 { - t.Fatalf("expected 1 batch of 1, got %d batches", len(sender.batches)) - } - event := sender.batches[0][0] - if event.AnonymousID != "anon-xyz" { - t.Errorf("anonymous ID not filled from state: %q", event.AnonymousID) - } - if event.Timestamp.IsZero() { - t.Errorf("timestamp not filled") - } - if event.Platform == "" { - t.Errorf("platform not filled") - } - if event.CLIVersion == "" { - t.Errorf("cli version not filled") - } -} - -func TestRecorder_BatchesOverMaxSize(t *testing.T) { - sender := &fakeSender{} - recorder := NewRecorder(State{Enabled: true, AnonymousID: "x"}, sender) - - const total = MaxBatchSize + 5 - for i := 0; i < total; i++ { - recorder.Record(Event{Command: "send"}) - } - - if err := recorder.Flush(); err != nil { - t.Fatalf("flush: %v", err) - } - - if len(sender.batches) != 2 { - t.Errorf("expected 2 batches (50+5), got %d", len(sender.batches)) - } - if sender.totalEvents() != total { - t.Errorf("expected %d total events, got %d", total, sender.totalEvents()) - } -} - -func TestRecorder_BoundsQueueOnSpammyRecord(t *testing.T) { - sender := &fakeSender{} - recorder := NewRecorder(State{Enabled: true, AnonymousID: "x"}, sender) - - for i := 0; i < MaxBatchSize*4; i++ { - recorder.Record(Event{Command: "send"}) - } - - pending := recorder.PendingCount() - if pending > MaxBatchSize*2 { - t.Errorf("queue should be bounded to %d, got %d", MaxBatchSize*2, pending) - } -} - -func TestRecorder_FlushDrainsEvenOnSenderError(t *testing.T) { - sender := &fakeSender{failNext: true} - recorder := NewRecorder(State{Enabled: true, AnonymousID: "x"}, sender) - - recorder.Record(Event{Command: "send"}) - if err := recorder.Flush(); err == nil { - t.Fatal("expected error from failing sender") - } - if recorder.PendingCount() != 0 { - t.Errorf("queue should drain even on error, got %d pending", recorder.PendingCount()) - } -} - -func TestLoadState_MissingFileMeansDisabled(t *testing.T) { - state, err := LoadState(t.TempDir()) - if err != nil { - t.Fatalf("LoadState: %v", err) - } - if state.Enabled || state.AnonymousID != "" { - t.Errorf("missing file should yield zero State, got %+v", state) - } -} - -func TestSaveAndLoadState_RoundTrip(t *testing.T) { - home := t.TempDir() - original := State{Enabled: true, AnonymousID: "uuid-abc"} - - if err := SaveState(home, original); err != nil { - t.Fatalf("SaveState: %v", err) - } - - reloaded, err := LoadState(home) - if err != nil { - t.Fatalf("LoadState: %v", err) - } - if reloaded != original { - t.Errorf("round-trip mismatch: want %+v, got %+v", original, reloaded) - } - - // idFile mirror should also be written - idPath := filepath.Join(home, dirName, idFileName) - body, _ := os.ReadFile(idPath) - if string(body) != "uuid-abc\n" { - t.Errorf("id mirror file content unexpected: %q", string(body)) - } -} - -func TestSaveState_EnforcesPerms(t *testing.T) { - home := t.TempDir() - if err := SaveState(home, State{Enabled: true, AnonymousID: "x"}); err != nil { - t.Fatal(err) - } - info, err := os.Stat(stateFilePath(home)) - if err != nil { - t.Fatal(err) - } - if info.Mode().Perm() != filePerms { - t.Errorf("perms: want %o, got %o", filePerms, info.Mode().Perm()) - } -} - -func TestEnsureAnonymousID_GeneratesAndPersists(t *testing.T) { - home := t.TempDir() - state := State{Enabled: true} - - updated, err := EnsureAnonymousID(home, state) - if err != nil { - t.Fatalf("EnsureAnonymousID: %v", err) - } - if updated.AnonymousID == "" { - t.Error("anonymous id should be generated") - } - - // Round-trip from disk should return the same id - reloaded, _ := LoadState(home) - if reloaded.AnonymousID != updated.AnonymousID { - t.Errorf("persisted id mismatch: want %q, got %q", updated.AnonymousID, reloaded.AnonymousID) - } -} - -func TestEnsureAnonymousID_PreservesExisting(t *testing.T) { - home := t.TempDir() - state := State{Enabled: true, AnonymousID: "preexisting-xyz"} - - updated, err := EnsureAnonymousID(home, state) - if err != nil { - t.Fatalf("EnsureAnonymousID: %v", err) - } - if updated.AnonymousID != "preexisting-xyz" { - t.Errorf("existing id should be preserved, got %q", updated.AnonymousID) - } -} - -func TestRecorder_NilIsSafe(t *testing.T) { - var recorder *Recorder - recorder.Record(Event{}) - if err := recorder.Flush(); err != nil { - t.Errorf("nil recorder Flush should be nil error, got: %v", err) - } - if recorder.PendingCount() != 0 { - t.Errorf("nil recorder PendingCount should be 0, got %d", recorder.PendingCount()) - } - if recorder.Enabled() { - t.Error("nil recorder should not be Enabled") - } -} - -func TestEvent_FieldsRoundTripJSON(t *testing.T) { - event := Event{ - Timestamp: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC), - Command: "send", - ExitCode: 0, - DurationMs: 287, - CLIVersion: "0.2.0", - Platform: "darwin/arm64", - AnonymousID: "uuid-abc", - } - sender := &fakeSender{} - recorder := NewRecorder(State{Enabled: true, AnonymousID: "x"}, sender) - recorder.Record(event) - if err := recorder.Flush(); err != nil { - t.Fatal(err) - } - if len(sender.batches) != 1 || sender.batches[0][0].Command != "send" { - t.Errorf("round-trip mismatch: %+v", sender.batches) - } -} From 6ae566a566505903a3c92b92153f42cd6bba3082 Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Sun, 8 Nov 2026 14:08:58 -0300 Subject: [PATCH 2/4] chore(listen): remove the listen command and event stream client --- README.md | 8 +- SECURITY.md | 15 - internal/api/stream.go | 204 ----------- internal/api/stream_test.go | 243 ------------- internal/api/webhook_listener.go | 151 -------- internal/api/webhook_listener_test.go | 181 ---------- internal/cmd/listen.go | 431 ---------------------- internal/cmd/listen_test.go | 501 -------------------------- internal/cmd/logs.go | 52 +-- internal/cmd/logs_test.go | 28 -- internal/cmd/manpages_test.go | 1 - internal/tui/logs_viewer.go | 239 ------------ internal/tui/repl.go | 22 -- internal/tui/repl_completion.go | 2 - internal/tui/repl_dispatch.go | 3 - internal/tui/repl_dispatch_test.go | 2 - internal/tui/webhook_viewer.go | 465 ------------------------ 17 files changed, 6 insertions(+), 2542 deletions(-) delete mode 100644 internal/api/stream.go delete mode 100644 internal/api/stream_test.go delete mode 100644 internal/api/webhook_listener.go delete mode 100644 internal/api/webhook_listener_test.go delete mode 100644 internal/cmd/listen.go delete mode 100644 internal/cmd/listen_test.go delete mode 100644 internal/tui/logs_viewer.go delete mode 100644 internal/tui/webhook_viewer.go diff --git a/README.md b/README.md index 4ed3886..8ce661a 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,6 @@ arara doctor | `arara numbers` | Manage phone numbers | | `arara keys` | Manage API keys (list, create, revoke) | | `arara logs` | View message history and logs | -| `arara listen` | Real-time message listener (webhooks) | | `arara status` | Live dashboard with auto-refresh (aliases: `dash`, `dashboard`) | | `arara config` | Configure CLI settings (list, set, get) | | `arara upgrade` | Update CLI to latest version | @@ -99,7 +98,6 @@ The CLI includes a rich Terminal UI built with [Bubble Tea](https://github.com/c - Interactive message sending wizard (run `arara send` with no flags) - Live dashboard with auto-refresh every 30s (`arara status`) -- Real-time message listener with live updates (`arara listen`) - Formatted output with colors and tables ### Secure Credential Storage @@ -115,11 +113,7 @@ arara logs # Pretty JSON arara logs -o json -# NDJSON (one event per line) — pipe to jq, datadog, etc -arara listen -o stream-json | jq -r '.event' -arara logs --follow | tee log.ndjson - -# Watch a single message via NDJSON (one line per state change) +# Watch a single message via NDJSON (one line per state change) — pipe to jq, datadog, etc arara send --to +5511999999999 --template hello_world --watch -o stream-json ``` diff --git a/SECURITY.md b/SECURITY.md index 4f11dbf..8c7b614 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -85,21 +85,6 @@ flow). Both are treated as bearer secrets. - Bearer tokens go in the `Authorization` header, never in the URL or query string. -### Webhook Capture Secrets (`arara listen --capture`) - -When you start a CLI capture listener, the backend issues a one-shot -signing secret (`wh_cli_…`). This secret: - -- Is shown **once** in the create-response and printed to the terminal. -- Lives in the CLI process memory only — **not** written to disk, the - keyring, or anywhere else. -- Dies when the process exits. There is no recovery. - -If your terminal scrollback is captured (shared session, screen -recording), treat the secret as compromised and re-run the capture -command to rotate it. Capture sessions are also bounded by TTL (default -60 min) on the backend. - ## Known Risks These are documented so they're not surprises: diff --git a/internal/api/stream.go b/internal/api/stream.go deleted file mode 100644 index e5f6e56..0000000 --- a/internal/api/stream.go +++ /dev/null @@ -1,204 +0,0 @@ -package api - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "net/http" - "strings" - "time" -) - -const ( - streamEventsPath = "/v1/stream" - sseEventPrefix = "event:" - sseDataPrefix = "data:" - sseContentType = "text/event-stream" - acceptHeader = "Accept" - sseInitialBackoff = 1 * time.Second - sseMaxBackoff = 30 * time.Second - sseBackoffMultiplier = 2 - sseEventChannelBuffer = 64 -) - -// SSEEvent represents a single Server-Sent Event received from the stream. -// -// When the backend wraps an event in an envelope (RFC 0003), Data carries -// only the inner payload JSON (the part the customer's webhook handler -// would normally receive) and Signature carries the pre-computed -// `sha256=` HMAC. Old-format events leave Signature empty and Data -// holds the raw `data:` line as-is. -type SSEEvent struct { - Event string - Data string - Signature string -} - -// streamEnvelope is the shape backends emit when they want the CLI to -// re-sign forwarded webhooks (RFC 0003). All three keys must be present -// for the envelope to be detected — otherwise we treat `data:` as a raw -// payload string for backwards compatibility. -type streamEnvelope struct { - Event string `json:"event"` - Data json.RawMessage `json:"data"` - Signature string `json:"signature"` -} - -// StreamEvents connects to the SSE endpoint and returns a channel of events. -// The channel is closed when the context is cancelled or the connection is -// permanently lost. Temporary disconnections are retried with exponential backoff. -func (client *Client) StreamEvents(ctx context.Context) (<-chan SSEEvent, error) { - eventChannel := make(chan SSEEvent, sseEventChannelBuffer) - - go client.consumeStream(ctx, eventChannel) - - return eventChannel, nil -} - -func (client *Client) consumeStream(ctx context.Context, eventChannel chan<- SSEEvent) { - defer close(eventChannel) - - backoff := sseInitialBackoff - - for { - if ctx.Err() != nil { - return - } - - connectionError := client.readSSEStream(ctx, eventChannel) - if ctx.Err() != nil { - return - } - - if connectionError != nil { - select { - case <-ctx.Done(): - return - case <-time.After(backoff): - backoff = nextBackoff(backoff) - } - continue - } - - backoff = sseInitialBackoff - } -} - -func (client *Client) readSSEStream(ctx context.Context, eventChannel chan<- SSEEvent) error { - requestURL := client.baseURL + streamEventsPath - - httpRequest, requestError := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil) - if requestError != nil { - return fmt.Errorf("failed to create SSE request: %w", requestError) - } - - httpRequest.Header.Set(authorizationHeader, bearerPrefix+client.apiKey) - httpRequest.Header.Set(acceptHeader, sseContentType) - httpRequest.Header.Set(userAgentHeader, buildUserAgent()) - - sseClient := &http.Client{} - httpResponse, responseError := sseClient.Do(httpRequest) - if responseError != nil { - return fmt.Errorf("SSE connection failed: %w", responseError) - } - defer httpResponse.Body.Close() - - if httpResponse.StatusCode != http.StatusOK { - return fmt.Errorf("SSE endpoint returned status %d", httpResponse.StatusCode) - } - - scanner := bufio.NewScanner(httpResponse.Body) - var currentEvent SSEEvent - - for scanner.Scan() { - if ctx.Err() != nil { - return nil - } - - line := scanner.Text() - - if isEmptyLine(line) { - dispatchEvent(ctx, eventChannel, ¤tEvent) - continue - } - - parseSSELine(line, ¤tEvent) - } - - if scanError := scanner.Err(); scanError != nil { - return fmt.Errorf("SSE stream read error: %w", scanError) - } - - return nil -} - -func parseSSELine(line string, currentEvent *SSEEvent) { - if strings.HasPrefix(line, sseEventPrefix) { - currentEvent.Event = strings.TrimSpace(strings.TrimPrefix(line, sseEventPrefix)) - return - } - - if strings.HasPrefix(line, sseDataPrefix) { - currentEvent.Data = strings.TrimSpace(strings.TrimPrefix(line, sseDataPrefix)) - return - } -} - -func dispatchEvent(ctx context.Context, eventChannel chan<- SSEEvent, currentEvent *SSEEvent) { - if currentEvent.Data == "" && currentEvent.Event == "" { - return - } - - unwrapEnvelopeInto(currentEvent) - - select { - case eventChannel <- *currentEvent: - case <-ctx.Done(): - } - - currentEvent.Event = "" - currentEvent.Data = "" - currentEvent.Signature = "" -} - -// unwrapEnvelopeInto checks whether currentEvent.Data carries an RFC 0003 -// envelope and, if so, replaces Data with the inner payload and lifts the -// signature into the dedicated field. Non-envelope data is left untouched -// so legacy backends keep working. -func unwrapEnvelopeInto(currentEvent *SSEEvent) { - trimmed := strings.TrimSpace(currentEvent.Data) - if !looksLikeJSONObject(trimmed) { - return - } - - var envelope streamEnvelope - if unmarshalErr := json.Unmarshal([]byte(trimmed), &envelope); unmarshalErr != nil { - return - } - if envelope.Signature == "" || len(envelope.Data) == 0 { - return - } - - if envelope.Event != "" && currentEvent.Event == "" { - currentEvent.Event = envelope.Event - } - currentEvent.Data = string(envelope.Data) - currentEvent.Signature = envelope.Signature -} - -func looksLikeJSONObject(s string) bool { - return len(s) >= 2 && s[0] == '{' && s[len(s)-1] == '}' -} - -func isEmptyLine(line string) bool { - return strings.TrimSpace(line) == "" -} - -func nextBackoff(current time.Duration) time.Duration { - next := current * sseBackoffMultiplier - if next > sseMaxBackoff { - return sseMaxBackoff - } - return next -} diff --git a/internal/api/stream_test.go b/internal/api/stream_test.go deleted file mode 100644 index 590f5db..0000000 --- a/internal/api/stream_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package api - -import ( - "context" - "fmt" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" -) - -func TestParseSSELine(t *testing.T) { - var current SSEEvent - - parseSSELine("event: message.delivered", ¤t) - if current.Event != "message.delivered" { - t.Errorf("event: want message.delivered, got %q", current.Event) - } - - parseSSELine("data: {\"id\":\"abc\"}", ¤t) - if current.Data != `{"id":"abc"}` { - t.Errorf("data parse failed, got %q", current.Data) - } - - parseSSELine("comment line", ¤t) - if current.Event != "message.delivered" || current.Data != `{"id":"abc"}` { - t.Error("non-prefix line should not mutate event/data") - } -} - -func TestIsEmptyLine(t *testing.T) { - if !isEmptyLine("") || !isEmptyLine(" ") { - t.Error("blank should be empty line") - } - if isEmptyLine("data: x") { - t.Error("data line should not be empty") - } -} - -func TestNextBackoff(t *testing.T) { - got := nextBackoff(time.Second) - if got != 2*time.Second { - t.Errorf("nextBackoff(1s): want 2s, got %v", got) - } - - if got := nextBackoff(sseMaxBackoff); got != sseMaxBackoff { - t.Errorf("nextBackoff at cap: want %v, got %v", sseMaxBackoff, got) - } -} - -func TestStreamEvents_DeliversThenCloses(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - w.WriteHeader(http.StatusOK) - flusher, _ := w.(http.Flusher) - fmt.Fprint(w, "event: message.delivered\ndata: {\"id\":\"a\"}\n\n") - fmt.Fprint(w, "event: message.read\ndata: {\"id\":\"b\"}\n\n") - if flusher != nil { - flusher.Flush() - } - })) - t.Cleanup(server.Close) - - client := NewClient(server.URL, "ara_test_xxxxxxxxxxxx") - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - events, err := client.StreamEvents(ctx) - if err != nil { - t.Fatalf("StreamEvents: %v", err) - } - - timeout := time.After(2 * time.Second) - collected := []SSEEvent{} - for len(collected) < 2 { - select { - case ev := <-events: - collected = append(collected, ev) - case <-timeout: - t.Fatalf("timeout, only collected %d events", len(collected)) - } - } - - if collected[0].Event != "message.delivered" || collected[0].Data != `{"id":"a"}` { - t.Errorf("first event mismatch: %+v", collected[0]) - } - if collected[1].Event != "message.read" || collected[1].Data != `{"id":"b"}` { - t.Errorf("second event mismatch: %+v", collected[1]) - } -} - -func TestStreamEvents_NonOKStatusErrors(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusUnauthorized) - })) - t.Cleanup(server.Close) - - client := NewClient(server.URL, "ara_test_xxxxxxxxxxxx") - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - - events, err := client.StreamEvents(ctx) - if err != nil { - t.Fatalf("StreamEvents setup error: %v", err) - } - - select { - case _, open := <-events: - if open { - t.Error("did not expect events on auth failure path before context expiry") - } - case <-ctx.Done(): - } -} - -func TestDispatchEvent_SkipsEmpty(t *testing.T) { - ctx := context.Background() - channel := make(chan SSEEvent, 1) - current := &SSEEvent{} - - dispatchEvent(ctx, channel, current) - - if len(channel) != 0 { - t.Error("empty event should not be dispatched") - } -} - -func TestDispatchEvent_RespectsCanceledContext(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - channel := make(chan SSEEvent) - current := &SSEEvent{Event: "x", Data: "y"} - - done := make(chan struct{}) - go func() { - dispatchEvent(ctx, channel, current) - close(done) - }() - - select { - case <-done: - case <-time.After(time.Second): - t.Fatal("dispatchEvent stuck on canceled context") - } -} - -func TestUnwrapEnvelopeInto_DetectsAndExtracts(t *testing.T) { - current := &SSEEvent{ - Event: "", - Data: `{"event":"message.delivered","data":{"id":"msg_1","status":"delivered"},"signature":"sha256=abc123"}`, - } - - unwrapEnvelopeInto(current) - - if current.Event != "message.delivered" { - t.Errorf("event from envelope not lifted, got %q", current.Event) - } - if current.Signature != "sha256=abc123" { - t.Errorf("signature not extracted, got %q", current.Signature) - } - if current.Data != `{"id":"msg_1","status":"delivered"}` { - t.Errorf("data should be inner payload, got %q", current.Data) - } -} - -func TestUnwrapEnvelopeInto_PreservesExplicitOuterEvent(t *testing.T) { - // SSE `event:` line is authoritative when both layers carry it. - current := &SSEEvent{ - Event: "outer.event", - Data: `{"event":"inner.event","data":{"x":1},"signature":"sha256=zzz"}`, - } - unwrapEnvelopeInto(current) - if current.Event != "outer.event" { - t.Errorf("outer event should win, got %q", current.Event) - } - if current.Signature != "sha256=zzz" { - t.Errorf("signature should still be lifted, got %q", current.Signature) - } -} - -func TestUnwrapEnvelopeInto_LegacyDataIsUntouched(t *testing.T) { - current := &SSEEvent{ - Event: "ping", - Data: `{"id":"abc","status":"ok"}`, // no envelope keys - } - unwrapEnvelopeInto(current) - - if current.Signature != "" { - t.Errorf("legacy data should not produce signature, got %q", current.Signature) - } - if current.Data != `{"id":"abc","status":"ok"}` { - t.Errorf("legacy data mutated: %q", current.Data) - } -} - -func TestUnwrapEnvelopeInto_IncompleteEnvelopeIsIgnored(t *testing.T) { - cases := []string{ - `{"event":"x","data":{"a":1}}`, // no signature - `{"event":"x","signature":"sha256=y"}`, // no data - `{"data":{"a":1},"signature":"sha256=y"}`, // no event — but should still pass since outer Event might exist - } - for _, raw := range cases { - current := &SSEEvent{Event: "outer", Data: raw} - unwrapEnvelopeInto(current) - if raw[1:] != "" && current.Signature != "" && current.Data != raw { - // only the third case has signature+data, those are valid - if !strings.Contains(raw, `"signature"`) || !strings.Contains(raw, `"data"`) { - t.Errorf("incomplete envelope %q should not produce signature, got Sig=%q Data=%q", raw, current.Signature, current.Data) - } - } - } -} - -func TestUnwrapEnvelopeInto_NonJSONIsUntouched(t *testing.T) { - current := &SSEEvent{Event: "ping", Data: "plain text"} - unwrapEnvelopeInto(current) - if current.Data != "plain text" { - t.Errorf("plain text should pass through, got %q", current.Data) - } - if current.Signature != "" { - t.Errorf("plain text should not produce signature, got %q", current.Signature) - } -} - -func TestLooksLikeJSONObject(t *testing.T) { - if !looksLikeJSONObject(`{"x":1}`) { - t.Error("simple object should be recognized") - } - if looksLikeJSONObject(`[1,2]`) { - t.Error("array should not be recognized as object") - } - if looksLikeJSONObject("plain") { - t.Error("string should not be recognized") - } - if looksLikeJSONObject("") { - t.Error("empty should not panic / not be recognized") - } - if looksLikeJSONObject("{") { - t.Error("single brace should not be recognized") - } -} diff --git a/internal/api/webhook_listener.go b/internal/api/webhook_listener.go deleted file mode 100644 index 6e1ad59..0000000 --- a/internal/api/webhook_listener.go +++ /dev/null @@ -1,151 +0,0 @@ -package api - -import ( - "errors" - "fmt" - "net/http" - "strings" -) - -const ( - webhookListenersPath = "/v1/cli/webhook-listeners" - webhookListenerHeartbeatSuffix = "/heartbeat" -) - -// ErrCaptureNotSupported is returned when the backend doesn't yet expose -// the capture-listener endpoints. The CLI uses it to fall back to passive -// SSE mode without breaking the user flow. -var ErrCaptureNotSupported = errors.New("backend does not support webhook capture listeners (RFC 0003)") - -// CaptureConflictError is returned when another CLI session is already -// holding the org's capture slot. The CLI displays the conflict details -// (owner, expiresAt) so the user can decide whether to wait or kill the -// other session. -type CaptureConflictError struct { - ListenerID string - Owner string - StartedAt string - ExpiresAt string - Message string -} - -func (err *CaptureConflictError) Error() string { - return fmt.Sprintf("capture conflict: another CLI session %s (owner=%q, expires=%s) is active", err.ListenerID, err.Owner, err.ExpiresAt) -} - -// CreateWebhookListenerRequest is the body of POST /v1/cli/webhook-listeners. -// Both fields are optional — the backend supplies sensible defaults when -// they're empty. -type CreateWebhookListenerRequest struct { - Owner string `json:"owner,omitempty"` - TTLSeconds int `json:"ttlSeconds,omitempty"` -} - -// CreateWebhookListenerResponse is the 201 body. Secret is shown ONCE and -// must not be persisted to disk by the CLI — it dies with the process. -type CreateWebhookListenerResponse struct { - ID string `json:"id"` - Secret string `json:"secret"` - OrganizationID string `json:"organizationId"` - ExpiresAt string `json:"expiresAt"` - HeartbeatIntervalSeconds int `json:"heartbeatIntervalSeconds"` -} - -// CreateWebhookListener registers an ephemeral capture session. Returns -// ErrCaptureNotSupported on 404 (graceful fallback) and CaptureConflictError -// on 409 (another session holds the slot). -func (client *Client) CreateWebhookListener(req CreateWebhookListenerRequest) (*CreateWebhookListenerResponse, error) { - var response CreateWebhookListenerResponse - if postErr := client.Post(webhookListenersPath, req, &response); postErr != nil { - return nil, classifyCaptureError(postErr) - } - return &response, nil -} - -// HeartbeatWebhookListener extends the listener's TTL. Returns nil on 204 -// success. On 410 (already expired), returns a sentinel so the CLI can -// surface "listener expired, re-run with --capture to grab a fresh slot". -func (client *Client) HeartbeatWebhookListener(listenerID string) error { - path := webhookListenersPath + "/" + listenerID + webhookListenerHeartbeatSuffix - if postErr := client.Post(path, struct{}{}, nil); postErr != nil { - return classifyCaptureError(postErr) - } - return nil -} - -// ReleaseWebhookListener tells the backend the CLI is done. Idempotent on -// the backend side. Best-effort from the CLI's perspective: failure here -// just means the listener will expire naturally on its TTL. -func (client *Client) ReleaseWebhookListener(listenerID string) error { - path := webhookListenersPath + "/" + listenerID - if delErr := client.Delete(path); delErr != nil { - return classifyCaptureError(delErr) - } - return nil -} - -// classifyCaptureError unwraps an APIError and returns one of the -// well-known sentinel errors when applicable. Anything else passes through. -func classifyCaptureError(err error) error { - var apiError *APIError - if !errors.As(err, &apiError) { - return err - } - - if apiError.StatusCode == http.StatusNotFound && apiError.Code == "" { - // Spring's default "no controller mapped" page — feature isn't - // deployed. Domain 404s with a structured code are passed through. - return ErrCaptureNotSupported - } - - // EqualFold porque o backend emite CAPTURE_LISTENER_ACTIVE em maiusculo - // (GlobalExceptionHandler.kt) e a comparacao exata em minusculo nunca casava: o usuario via - // um conflito generico em vez de quem esta com o listener e ate quando. - if apiError.StatusCode == http.StatusConflict && - strings.EqualFold(apiError.Code, "CAPTURE_LISTENER_ACTIVE") { - return &CaptureConflictError{ - ListenerID: stringFromDetails(apiError, "listenerId"), - Owner: stringFromDetails(apiError, "owner"), - StartedAt: stringFromDetails(apiError, "startedAt"), - ExpiresAt: stringFromDetails(apiError, "expiresAt"), - Message: apiError.Message, - } - } - - return err -} - -// stringFromDetails reads the apiError's RawBody for the named key under -// `error.details`. Defensive — APIError today doesn't expose a typed -// details map, so we fall back to a small JSON walk only when needed. -func stringFromDetails(apiError *APIError, key string) string { - body := apiError.RawBody - if body == "" { - return "" - } - // The body shape is `{"error":{"code":..., "details":{:,...}}}`. - // We don't bring in a real JSON tree here just for an error helper. - // A naive substring match is robust enough — the keys are known short - // identifiers (listenerId, owner, expiresAt) that don't appear in the - // other fields. - needle := `"` + key + `":"` - start := indexOf(body, needle) - if start < 0 { - return "" - } - start += len(needle) - end := indexOf(body[start:], `"`) - if end < 0 { - return "" - } - return body[start : start+end] -} - -func indexOf(haystack, needle string) int { - for index := 0; index+len(needle) <= len(haystack); index++ { - if haystack[index:index+len(needle)] == needle { - return index - } - } - return -1 -} diff --git a/internal/api/webhook_listener_test.go b/internal/api/webhook_listener_test.go deleted file mode 100644 index a3b906b..0000000 --- a/internal/api/webhook_listener_test.go +++ /dev/null @@ -1,181 +0,0 @@ -package api - -import ( - "errors" - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestCreateWebhookListener_GoldenPath(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost || r.URL.Path != webhookListenersPath { - w.WriteHeader(http.StatusNotFound) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - _, _ = w.Write([]byte(`{ - "id":"lst_8f3e2d", - "secret":"wh_cli_4f8a2b9e3c1d", - "organizationId":"org_acme", - "expiresAt":"2026-05-11T19:30:00Z", - "heartbeatIntervalSeconds":30 - }`)) - })) - t.Cleanup(server.Close) - - client := newTestClient(server.URL) - resp, err := client.CreateWebhookListener(CreateWebhookListenerRequest{Owner: "darwin/arm64@host"}) - if err != nil { - t.Fatalf("CreateWebhookListener: %v", err) - } - if resp.ID != "lst_8f3e2d" || resp.Secret != "wh_cli_4f8a2b9e3c1d" { - t.Errorf("response mismatch: %+v", resp) - } - if resp.HeartbeatIntervalSeconds != 30 { - t.Errorf("heartbeat interval: %d", resp.HeartbeatIntervalSeconds) - } -} - -func TestCreateWebhookListener_404FallsBackGracefully(t *testing.T) { - // Bare 404 (no JSON body) means the controller isn't deployed yet — - // CLI should get ErrCaptureNotSupported and fall back to passive mode. - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusNotFound) - _, _ = w.Write([]byte(`404 Not Found`)) - })) - t.Cleanup(server.Close) - - client := newTestClient(server.URL) - _, err := client.CreateWebhookListener(CreateWebhookListenerRequest{}) - if !errors.Is(err, ErrCaptureNotSupported) { - t.Errorf("expected ErrCaptureNotSupported, got: %v", err) - } -} - -func TestCreateWebhookListener_409ReturnsTypedConflict(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusConflict) - _, _ = w.Write([]byte(`{ - "error":{ - "code":"CAPTURE_LISTENER_ACTIVE", - "message":"another CLI session is already capturing for this org", - "details":{ - "listenerId":"lst_existing", - "owner":"darwin/arm64@other-host", - "startedAt":"2026-05-11T18:30:00Z", - "expiresAt":"2026-05-11T19:30:00Z" - } - } - }`)) - })) - t.Cleanup(server.Close) - - client := newTestClient(server.URL) - _, err := client.CreateWebhookListener(CreateWebhookListenerRequest{}) - - var conflict *CaptureConflictError - if !errors.As(err, &conflict) { - t.Fatalf("expected *CaptureConflictError, got: %T (%v)", err, err) - } - if conflict.ListenerID != "lst_existing" { - t.Errorf("listenerId: %q", conflict.ListenerID) - } - if conflict.Owner != "darwin/arm64@other-host" { - t.Errorf("owner: %q", conflict.Owner) - } - if conflict.ExpiresAt != "2026-05-11T19:30:00Z" { - t.Errorf("expiresAt: %q", conflict.ExpiresAt) - } - if !strings.Contains(conflict.Error(), "lst_existing") { - t.Errorf("Error() should reference listener id, got: %v", conflict) - } -} - -func TestCreateWebhookListener_404WithStructuredCodeIsDomainError(t *testing.T) { - // 404 WITH error.code is a real domain error (e.g. org not found), - // not "feature missing". Must NOT collapse to ErrCaptureNotSupported. - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusNotFound) - _, _ = w.Write([]byte(`{"error":{"code":"organization_not_found","message":"unknown org"}}`)) - })) - t.Cleanup(server.Close) - - client := newTestClient(server.URL) - _, err := client.CreateWebhookListener(CreateWebhookListenerRequest{}) - if errors.Is(err, ErrCaptureNotSupported) { - t.Errorf("structured 404 should NOT collapse to ErrCaptureNotSupported, got: %v", err) - } -} - -func TestHeartbeatWebhookListener_204IsSuccess(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !strings.HasSuffix(r.URL.Path, "/heartbeat") { - w.WriteHeader(http.StatusNotFound) - return - } - w.WriteHeader(http.StatusNoContent) - })) - t.Cleanup(server.Close) - - client := newTestClient(server.URL) - if err := client.HeartbeatWebhookListener("lst_x"); err != nil { - t.Errorf("heartbeat: %v", err) - } -} - -func TestReleaseWebhookListener_204IsSuccess(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodDelete { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - w.WriteHeader(http.StatusNoContent) - })) - t.Cleanup(server.Close) - - client := newTestClient(server.URL) - if err := client.ReleaseWebhookListener("lst_x"); err != nil { - t.Errorf("release: %v", err) - } -} - -func TestStringFromDetails_HandlesMissingAndPresent(t *testing.T) { - apiErr := &APIError{ - RawBody: `{"error":{"code":"x","details":{"foo":"bar","baz":"qux"}}}`, - } - if got := stringFromDetails(apiErr, "foo"); got != "bar" { - t.Errorf("foo: want bar, got %q", got) - } - if got := stringFromDetails(apiErr, "baz"); got != "qux" { - t.Errorf("baz: want qux, got %q", got) - } - if got := stringFromDetails(apiErr, "missing"); got != "" { - t.Errorf("missing: want empty, got %q", got) - } -} - -func TestStringFromDetails_EmptyBodyReturnsEmpty(t *testing.T) { - apiErr := &APIError{} - if got := stringFromDetails(apiErr, "foo"); got != "" { - t.Errorf("empty body should return empty, got %q", got) - } -} - -func TestIndexOf(t *testing.T) { - if indexOf("hello world", "world") != 6 { - t.Errorf("simple match") - } - if indexOf("hello", "world") != -1 { - t.Errorf("no match should return -1") - } - if indexOf("", "x") != -1 { - t.Errorf("empty haystack") - } - if indexOf("xx", "") != 0 { - t.Errorf("empty needle should return 0") - } -} diff --git a/internal/cmd/listen.go b/internal/cmd/listen.go deleted file mode 100644 index e840c67..0000000 --- a/internal/cmd/listen.go +++ /dev/null @@ -1,431 +0,0 @@ -package cmd - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "os" - "os/signal" - "runtime" - "strings" - "syscall" - "time" - - tea "github.com/charmbracelet/bubbletea" - "github.com/spf13/cobra" - - "github.com/ararahq/cli/internal/api" - "github.com/ararahq/cli/internal/output" - "github.com/ararahq/cli/internal/tui" -) - -const ( - forwardTimeout = 10 * time.Second - forwardEventHeader = "X-Arara-Webhook-Event" - forwardSourceHeader = "X-Arara-Forwarded-By" - forwardSignatureHeader = "X-Arara-Signature" - forwardSourceName = "arara-cli" - contentTypeHeaderKey = "Content-Type" - contentTypeJSONValue = "application/json" -) - -var ( - listenForwardToFlag string - listenEventsFlag string - listenCaptureFlag bool -) - -const ( - captureHeartbeatFloorSeconds = 10 - captureHeartbeatDefault = 30 * time.Second - captureMaxHeartbeatFailures = 3 - captureOwnerHostnameFallback = "unknown-host" -) - -var listenCmd = &cobra.Command{ - Use: "listen", - Short: "Listen to live webhook events via SSE", - Long: "Connect to the AraraHQ SSE stream and display webhook events in real time.\n" + - "Optionally forward each event to a local URL for testing integrations.\n" + - "Use -o stream-json to emit one NDJSON record per event for piping to tools like jq.", - RunE: runListen, -} - -func init() { - listenCmd.Flags().StringVar(&listenForwardToFlag, "forward-to", "", "URL to forward each webhook event to via POST") - listenCmd.Flags().StringVar(&listenEventsFlag, "events", "", "comma-separated event types to filter (e.g., message.delivered,message.read)") - listenCmd.Flags().BoolVar(&listenCaptureFlag, "capture", false, "register an ephemeral capture listener (RFC 0003) so production webhooks are intercepted and signed for the local handler — falls back to passive SSE if backend doesn't support it") - - rootCmd.AddCommand(listenCmd) -} - -func runListen(command *cobra.Command, arguments []string) error { - if validationErr := validateForwardURL(listenForwardToFlag); validationErr != nil { - output.PrintError(validationErr.Error()) - return validationErr - } - - client, clientError := newClientForCmd() - if clientError != nil { - output.PrintError(fmt.Sprintf("Failed to create API client: %s", clientError.Error())) - return clientError - } - - client.SetVerbose(IsVerbose()) - return dispatchListenMode(client, parseEventFilters(listenEventsFlag), listenForwardToFlag) -} - -// dispatchListenMode picks which listener implementation runs based on the -// flag combination: capture takes precedence; explicit stream-json / a -// forward URL forces non-TUI mode; everything else opens the bubbletea -// webhook viewer. -func dispatchListenMode(client *api.Client, eventFilters []string, forwardURL string) error { - if listenCaptureFlag { - captureCtx, captureCancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) - defer captureCancel() - return runListenCapture(captureCtx, client, eventFilters, forwardURL) - } - - if GetOutputFormat() == output.FormatStreamJSON || forwardURL != "" { - return runListenStream(client, eventFilters, forwardURL) - } - - return runListenViewer(client, eventFilters, forwardURL) -} - -func runListenViewer(client *api.Client, eventFilters []string, forwardURL string) error { - viewerModel := tui.NewWebhookViewer(tui.WebhookViewerConfig{ - Client: client, - ForwardToURL: forwardURL, - EventFilters: eventFilters, - }) - - program := tea.NewProgram(viewerModel, tea.WithAltScreen()) - if _, runError := program.Run(); runError != nil { - output.PrintError(fmt.Sprintf("Webhook viewer failed: %s", runError.Error())) - return runError - } - return nil -} - -// runListenCapture orchestrates the --capture lifecycle: register listener, -// print signing secret, start heartbeat goroutine, run the SSE consumer, -// release on exit. Falls back to passive runListenStream when the backend -// doesn't expose the capture endpoints (RFC 0003 not deployed). -func runListenCapture(ctx context.Context, client *api.Client, eventFilters []string, forwardURL string) error { - created, captureErr := registerCaptureListener(client) - if captureErr != nil { - return handleCaptureSetupError(ctx, client, eventFilters, forwardURL, captureErr) - } - - printCaptureBanner(created, forwardURL) - - heartbeatCtx, stopHeartbeat := context.WithCancel(ctx) - defer stopHeartbeat() - go runCaptureHeartbeat(heartbeatCtx, client, created) - - defer releaseCaptureListener(client, created.ID) - - return runListenStreamWithCtx(ctx, client, eventFilters, forwardURL) -} - -func registerCaptureListener(client *api.Client) (*api.CreateWebhookListenerResponse, error) { - return client.CreateWebhookListener(api.CreateWebhookListenerRequest{ - Owner: captureOwnerIdentity(), - }) -} - -// handleCaptureSetupError centralizes the three failure modes of the -// listener-registration step: feature missing (fall back to passive SSE), -// already-active-on-other-CLI (show conflict, exit), or anything else -// (surface and exit). -func handleCaptureSetupError(ctx context.Context, client *api.Client, eventFilters []string, forwardURL string, captureErr error) error { - if errors.Is(captureErr, api.ErrCaptureNotSupported) { - output.PrintWarning("Capture mode not yet supported by this AraraHQ environment.") - output.PrintWarning("Falling back to passive SSE mode — production webhooks will continue receiving callbacks too.") - return runListenStreamWithCtx(ctx, client, eventFilters, forwardURL) - } - var conflict *api.CaptureConflictError - if errors.As(captureErr, &conflict) { - printCaptureConflict(conflict) - return captureErr - } - output.PrintError(fmt.Sprintf("Failed to start capture listener: %s", captureErr.Error())) - return captureErr -} - -func releaseCaptureListener(client *api.Client, listenerID string) { - if releaseErr := client.ReleaseWebhookListener(listenerID); releaseErr != nil { - if IsVerbose() { - fmt.Fprintf(os.Stderr, "[capture] release failed: %v\n", releaseErr) - } - return - } - output.PrintSuccess("Listener released. Webhooks resume normal delivery to the configured URL.") -} - -// runListenStreamWithCtx is the ctx-aware twin of runListenStream. We need -// it because runListenCapture builds its own signal context and wraps the -// stream + heartbeat under the same lifetime. -func runListenStreamWithCtx(ctx context.Context, client *api.Client, eventFilters []string, forwardURL string) error { - events, streamError := client.StreamEvents(ctx) - if streamError != nil { - return fmt.Errorf("failed to start SSE stream: %w", streamError) - } - - forwarder := newForwarder(forwardURL) - - for { - select { - case <-ctx.Done(): - return nil - case event, channelOpen := <-events: - if !channelOpen { - return nil - } - if !eventMatchesFilter(event.Event, eventFilters) { - continue - } - if writeError := writeStreamEvent(os.Stdout, event); writeError != nil { - return writeError - } - if forwarder != nil { - forwarder.send(event) - } - } - } -} - -func runCaptureHeartbeat(ctx context.Context, client *api.Client, listener *api.CreateWebhookListenerResponse) { - interval := captureHeartbeatDefault - if listener.HeartbeatIntervalSeconds >= captureHeartbeatFloorSeconds { - interval = time.Duration(listener.HeartbeatIntervalSeconds) * time.Second - } - - ticker := time.NewTicker(interval) - defer ticker.Stop() - - consecutiveFailures := 0 - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - if hbErr := client.HeartbeatWebhookListener(listener.ID); hbErr != nil { - consecutiveFailures++ - if IsVerbose() { - fmt.Fprintf(os.Stderr, "[capture] heartbeat failed (%d/%d): %v\n", consecutiveFailures, captureMaxHeartbeatFailures, hbErr) - } - if consecutiveFailures >= captureMaxHeartbeatFailures { - output.PrintWarning("Capture listener heartbeat failed 3× — listener may have expired. Re-run with --capture to grab a fresh slot.") - return - } - continue - } - consecutiveFailures = 0 - } - } -} - -func printCaptureBanner(listener *api.CreateWebhookListenerResponse, forwardURL string) { - output.PrintSuccess(fmt.Sprintf("Capture listener active (id: %s, expires: %s)", listener.ID, listener.ExpiresAt)) - output.PrintInfo(fmt.Sprintf("Signing secret: %s", listener.Secret)) - output.PrintInfo("Use this secret in your local handler to verify X-Arara-Signature.") - if forwardURL != "" { - output.PrintInfo(fmt.Sprintf("Forwarding all events to %s", forwardURL)) - } else { - output.PrintWarning("No --forward-to set — events will print to stdout but won't be POSTed anywhere.") - } -} - -func printCaptureConflict(conflict *api.CaptureConflictError) { - output.PrintError("Another CLI session is already capturing for this org:") - fmt.Fprintf(os.Stderr, " listener: %s\n", conflict.ListenerID) - if conflict.Owner != "" { - fmt.Fprintf(os.Stderr, " owner: %s\n", conflict.Owner) - } - if conflict.StartedAt != "" { - fmt.Fprintf(os.Stderr, " started: %s\n", conflict.StartedAt) - } - if conflict.ExpiresAt != "" { - fmt.Fprintf(os.Stderr, " expires: %s\n", conflict.ExpiresAt) - } - output.PrintInfo("Stop that session before starting a new one, or wait until it expires.") -} - -// validateForwardURL rejects --forward-to values that aren't http/https URLs -// pointing at a host. Empty is allowed (means "don't forward"). Anything -// else fails fast before we open the SSE connection so the user gets a -// clear, immediate error instead of a stream of failed POSTs to garbage. -func validateForwardURL(raw string) error { - trimmed := strings.TrimSpace(raw) - if trimmed == "" { - return nil - } - - parsed, parseErr := url.Parse(trimmed) - if parseErr != nil { - return fmt.Errorf("--forward-to %q is not a valid URL: %w", raw, parseErr) - } - if parsed.Scheme != "http" && parsed.Scheme != "https" { - return fmt.Errorf("--forward-to %q must use http or https scheme (got %q)", raw, parsed.Scheme) - } - if parsed.Host == "" { - return fmt.Errorf("--forward-to %q is missing a host", raw) - } - return nil -} - -// captureOwnerIdentity builds the `owner` string sent to the backend so a -// human looking at conflict errors can tell which workstation holds the -// active capture slot. Format: `/@`. -func captureOwnerIdentity() string { - hostname, hostErr := os.Hostname() - if hostErr != nil || hostname == "" { - hostname = captureOwnerHostnameFallback - } - return fmt.Sprintf("%s/%s@%s", runtime.GOOS, runtime.GOARCH, hostname) -} - -func runListenStream(client *api.Client, eventFilters []string, forwardURL string) error { - ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) - defer cancel() - - events, streamError := client.StreamEvents(ctx) - if streamError != nil { - return fmt.Errorf("failed to start SSE stream: %w", streamError) - } - - forwarder := newForwarder(forwardURL) - - for { - select { - case <-ctx.Done(): - return nil - case event, channelOpen := <-events: - if !channelOpen { - return nil - } - if !eventMatchesFilter(event.Event, eventFilters) { - continue - } - if writeError := writeStreamEvent(os.Stdout, event); writeError != nil { - return writeError - } - if forwarder != nil { - forwarder.send(event) - } - } - } -} - -// streamForwarder POSTs each SSE event to a local URL while the listen loop -// is running. Failures are reported on stderr but never abort the loop — -// dropping a forward POST should not silence the live stream. -type streamForwarder struct { - url string - httpClient *http.Client - stderr io.Writer -} - -func newForwarder(forwardURL string) *streamForwarder { - if forwardURL == "" { - return nil - } - return &streamForwarder{ - url: forwardURL, - httpClient: &http.Client{Timeout: forwardTimeout}, - stderr: os.Stderr, - } -} - -func (forwarder *streamForwarder) send(event api.SSEEvent) { - if forwarder == nil { - return - } - - requestBody := bytes.NewBufferString(event.Data) - httpRequest, requestError := http.NewRequest(http.MethodPost, forwarder.url, requestBody) - if requestError != nil { - fmt.Fprintf(forwarder.stderr, "forward to %s failed: %v\n", forwarder.url, requestError) - return - } - - httpRequest.Header.Set(contentTypeHeaderKey, contentTypeJSONValue) - httpRequest.Header.Set(forwardEventHeader, event.Event) - httpRequest.Header.Set(forwardSourceHeader, forwardSourceName) - if event.Signature != "" { - // Backend pre-computed the HMAC against the capture session secret - // (RFC 0003). Propagating verbatim lets the local handler use the - // same verification logic it'll use against the production secret. - httpRequest.Header.Set(forwardSignatureHeader, event.Signature) - } - - startTime := time.Now() - httpResponse, responseError := forwarder.httpClient.Do(httpRequest) - if responseError != nil { - fmt.Fprintf(forwarder.stderr, "forward to %s failed: %v\n", forwarder.url, responseError) - return - } - defer httpResponse.Body.Close() - _, _ = io.Copy(io.Discard, httpResponse.Body) - - fmt.Fprintf(forwarder.stderr, "forwarded %s → %s [%d in %s]\n", event.Event, forwarder.url, httpResponse.StatusCode, time.Since(startTime).Round(time.Millisecond)) -} - -func writeStreamEvent(writer interface { - Write([]byte) (int, error) -}, event api.SSEEvent, -) error { - record := map[string]any{ - "event": event.Event, - "data": decodeEventData(event.Data), - } - return output.WriteJSONLine(writer, record) -} - -func decodeEventData(raw string) any { - if raw == "" { - return nil - } - var parsed any - if unmarshalError := json.Unmarshal([]byte(raw), &parsed); unmarshalError == nil { - return parsed - } - return raw -} - -func eventMatchesFilter(eventName string, filters []string) bool { - if len(filters) == 0 { - return true - } - for _, filter := range filters { - if strings.EqualFold(filter, eventName) { - return true - } - } - return false -} - -func parseEventFilters(rawFilters string) []string { - if rawFilters == "" { - return nil - } - - parts := strings.Split(rawFilters, ",") - filters := make([]string, 0, len(parts)) - - for _, part := range parts { - trimmed := strings.TrimSpace(part) - if trimmed != "" { - filters = append(filters, trimmed) - } - } - - return filters -} diff --git a/internal/cmd/listen_test.go b/internal/cmd/listen_test.go deleted file mode 100644 index f0ef94f..0000000 --- a/internal/cmd/listen_test.go +++ /dev/null @@ -1,501 +0,0 @@ -package cmd - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "io" - "net/http" - "net/http/httptest" - "reflect" - "runtime" - "strings" - "sync" - "testing" - "time" - - "github.com/ararahq/cli/internal/api" -) - -func TestDecodeEventData(t *testing.T) { - if got := decodeEventData(""); got != nil { - t.Errorf("empty data should decode to nil, got %v", got) - } - - got := decodeEventData(`{"id":"abc"}`) - asMap, isMap := got.(map[string]any) - if !isMap { - t.Fatalf("JSON object should decode to map, got %T", got) - } - if asMap["id"] != "abc" { - t.Errorf("expected id=abc, got %v", asMap["id"]) - } - - if got := decodeEventData("plain string"); got != "plain string" { - t.Errorf("non-JSON should pass through, got %v", got) - } -} - -func TestEventMatchesFilter(t *testing.T) { - if !eventMatchesFilter("any", nil) { - t.Error("nil filters should match everything") - } - if !eventMatchesFilter("any", []string{}) { - t.Error("empty filters should match everything") - } - if !eventMatchesFilter("Message.Delivered", []string{"message.delivered"}) { - t.Error("filter match should be case-insensitive") - } - if eventMatchesFilter("message.read", []string{"message.delivered"}) { - t.Error("filter mismatch should reject") - } -} - -func TestWriteStreamEvent_EmitsNDJSON(t *testing.T) { - buffer := &bytes.Buffer{} - event := api.SSEEvent{Event: "message.delivered", Data: `{"id":"abc"}`} - - if err := writeStreamEvent(buffer, event); err != nil { - t.Fatalf("writeStreamEvent: %v", err) - } - - rawLine := strings.TrimSpace(buffer.String()) - if strings.Contains(rawLine, "\n") { - t.Errorf("NDJSON line must not contain embedded newlines: %q", rawLine) - } - - var decoded map[string]any - if err := json.Unmarshal([]byte(rawLine), &decoded); err != nil { - t.Fatalf("output not valid JSON: %v", err) - } - if decoded["event"] != "message.delivered" { - t.Errorf("event mismatch: %v", decoded["event"]) - } - dataMap, isMap := decoded["data"].(map[string]any) - if !isMap { - t.Fatalf("data should be parsed object, got %T", decoded["data"]) - } - if dataMap["id"] != "abc" { - t.Errorf("data.id mismatch: %v", dataMap["id"]) - } -} - -func TestWriteStreamEvent_NonJSONDataPassesThrough(t *testing.T) { - buffer := &bytes.Buffer{} - event := api.SSEEvent{Event: "ping", Data: "pong"} - - if err := writeStreamEvent(buffer, event); err != nil { - t.Fatal(err) - } - - var decoded map[string]any - if err := json.Unmarshal(buffer.Bytes(), &decoded); err != nil { - t.Fatal(err) - } - if decoded["data"] != "pong" { - t.Errorf("expected data='pong', got %v", decoded["data"]) - } -} - -func TestNewForwarder_NilOnEmptyURL(t *testing.T) { - if got := newForwarder(""); got != nil { - t.Errorf("expected nil forwarder for empty URL, got %v", got) - } -} - -func TestNewForwarder_BuildsClientWithTimeout(t *testing.T) { - forwarder := newForwarder("http://localhost:3000/webhook") - if forwarder == nil { - t.Fatal("expected non-nil forwarder") - } - if forwarder.url != "http://localhost:3000/webhook" { - t.Errorf("url: %q", forwarder.url) - } - if forwarder.httpClient == nil { - t.Error("httpClient should be set") - } - if forwarder.httpClient.Timeout != forwardTimeout { - t.Errorf("timeout: %v", forwarder.httpClient.Timeout) - } -} - -func TestStreamForwarder_Send_PostsBodyAndHeaders(t *testing.T) { - var ( - mu sync.Mutex - receivedBody []byte - receivedHeaders http.Header - receivedMethod string - callCount int - ) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, _ := io.ReadAll(r.Body) - mu.Lock() - receivedBody = body - receivedHeaders = r.Header.Clone() - receivedMethod = r.Method - callCount++ - mu.Unlock() - w.WriteHeader(http.StatusAccepted) - })) - t.Cleanup(server.Close) - - stderr := &bytes.Buffer{} - forwarder := newForwarder(server.URL) - forwarder.stderr = stderr - - event := api.SSEEvent{ - Event: "message.delivered", - Data: `{"id":"msg_1","status":"delivered"}`, - } - forwarder.send(event) - - mu.Lock() - defer mu.Unlock() - - if callCount != 1 { - t.Errorf("expected 1 POST, got %d", callCount) - } - if receivedMethod != http.MethodPost { - t.Errorf("method: want POST, got %s", receivedMethod) - } - if string(receivedBody) != event.Data { - t.Errorf("body: want %q, got %q", event.Data, string(receivedBody)) - } - if receivedHeaders.Get(forwardEventHeader) != "message.delivered" { - t.Errorf("event header missing or wrong: %q", receivedHeaders.Get(forwardEventHeader)) - } - if receivedHeaders.Get(forwardSourceHeader) != forwardSourceName { - t.Errorf("source header missing or wrong: %q", receivedHeaders.Get(forwardSourceHeader)) - } - if receivedHeaders.Get(contentTypeHeaderKey) != contentTypeJSONValue { - t.Errorf("content-type header missing: %q", receivedHeaders.Get(contentTypeHeaderKey)) - } - if !strings.Contains(stderr.String(), "forwarded message.delivered") { - t.Errorf("stderr should log forward, got: %q", stderr.String()) - } -} - -func TestStreamForwarder_Send_PropagatesSignatureWhenPresent(t *testing.T) { - var ( - mu sync.Mutex - signatureSeen string - ) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - signatureSeen = r.Header.Get(forwardSignatureHeader) - mu.Unlock() - w.WriteHeader(http.StatusOK) - })) - t.Cleanup(server.Close) - - forwarder := newForwarder(server.URL) - forwarder.stderr = &bytes.Buffer{} - - forwarder.send(api.SSEEvent{ - Event: "message.delivered", - Data: `{"id":"msg_1"}`, - Signature: "sha256=cafebabe", - }) - - mu.Lock() - defer mu.Unlock() - if signatureSeen != "sha256=cafebabe" { - t.Errorf("signature header: want %q, got %q", "sha256=cafebabe", signatureSeen) - } -} - -func TestStreamForwarder_Send_OmitsSignatureWhenAbsent(t *testing.T) { - var ( - mu sync.Mutex - sigEmpty bool - ) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - sigEmpty = r.Header.Get(forwardSignatureHeader) == "" - mu.Unlock() - w.WriteHeader(http.StatusOK) - })) - t.Cleanup(server.Close) - - forwarder := newForwarder(server.URL) - forwarder.stderr = &bytes.Buffer{} - - forwarder.send(api.SSEEvent{Event: "message.delivered", Data: `{"id":"x"}`}) - - mu.Lock() - defer mu.Unlock() - if !sigEmpty { - t.Error("signature header should be absent when SSEEvent has no Signature") - } -} - -func TestStreamForwarder_Send_LogsErrorOnUnreachable(t *testing.T) { - stderr := &bytes.Buffer{} - // Port 1 is privileged on most systems and not listening — instant failure. - forwarder := newForwarder("http://127.0.0.1:1/webhook") - forwarder.stderr = stderr - - forwarder.send(api.SSEEvent{Event: "ping", Data: "{}"}) - - if !strings.Contains(stderr.String(), "forward to") { - t.Errorf("expected error log, got: %q", stderr.String()) - } -} - -func TestStreamForwarder_Send_NilForwarderIsNoop(t *testing.T) { - var forwarder *streamForwarder - // Should not panic. - forwarder.send(api.SSEEvent{Event: "x"}) -} - -func TestRunListen_RejectsInvalidForwardURL(t *testing.T) { - originalForward := listenForwardToFlag - t.Cleanup(func() { listenForwardToFlag = originalForward }) - listenForwardToFlag = "ftp://bad-scheme" - - err := runListen(nil, nil) - if err == nil { - t.Fatal("expected validation error") - } -} - -// dispatchListenMode is awkward to test end-to-end because the non-capture, -// non-stream branch enters bubbletea (Program.Run blocks on a real TTY). -// We exercise it indirectly via runListenViewer in TestRunListenViewer_* -// tests and via runListenCapture in TestRunListenCapture_*. The dispatcher -// itself is a 3-way switch with no logic, so additional direct tests would -// duplicate without adding signal. - -// startFakeSSEServer returns an httptest.Server that serves one SSE event and -// keeps the connection open until ctx is canceled. Designed for tests that -// need runListenStream to drain a single event and observe the side effect. -func startFakeSSEServer(t *testing.T, event string, dataJSON string) *httptest.Server { - t.Helper() - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - w.WriteHeader(http.StatusOK) - flusher, ok := w.(http.Flusher) - if !ok { - return - } - _, _ = w.Write([]byte("event: " + event + "\n")) - _, _ = w.Write([]byte("data: " + dataJSON + "\n\n")) - flusher.Flush() - - // Block until the client disconnects. - <-r.Context().Done() - })) -} - -func TestRunListenStreamWithCtx_EmitsEventToStdout(t *testing.T) { - server := startFakeSSEServer(t, "message.delivered", `{"id":"msg_1"}`) - t.Cleanup(server.Close) - - client := api.NewClient(server.URL, "ara_test_xxx") - - ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) - defer cancel() - - done := make(chan error, 1) - go func() { - done <- runListenStreamWithCtx(ctx, client, nil, "") - }() - - select { - case <-done: - // loop exited cleanly when ctx expired - case <-time.After(2 * time.Second): - t.Fatal("runListenStreamWithCtx did not exit after ctx timeout") - } -} - -func TestRunCaptureHeartbeat_StopsOnContextCancel(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusNoContent) - })) - t.Cleanup(server.Close) - - client := api.NewClient(server.URL, "ara_test_xxx") - listener := &api.CreateWebhookListenerResponse{ - ID: "lst_x", - HeartbeatIntervalSeconds: captureHeartbeatFloorSeconds, - } - - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan struct{}) - go func() { - runCaptureHeartbeat(ctx, client, listener) - close(done) - }() - - // Cancel almost immediately; heartbeat should exit promptly. - cancel() - select { - case <-done: - case <-time.After(2 * time.Second): - t.Fatal("heartbeat goroutine did not exit after ctx cancel") - } -} - -func TestReleaseCaptureListener_VerboseLogsOnFailure(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusInternalServerError) - })) - t.Cleanup(server.Close) - - client := api.NewClient(server.URL, "ara_test_xxx") - // Just exercise both branches — success and failure. - releaseCaptureListener(client, "lst_x") // 500 → verbose log path - - successServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusNoContent) - })) - t.Cleanup(successServer.Close) - successClient := api.NewClient(successServer.URL, "ara_test_xxx") - releaseCaptureListener(successClient, "lst_x") -} - -func TestValidateForwardURL(t *testing.T) { - cases := []struct { - input string - wantErr bool - }{ - {"", false}, - {"http://localhost:3000/webhook", false}, - {"https://hooks.example.com/x", false}, - {" http://example.com ", false}, - {"localhost:3000", true}, - {"ftp://example.com", true}, - {"http://", true}, - {"::not a url::", true}, - } - for _, tc := range cases { - t.Run(tc.input, func(t *testing.T) { - err := validateForwardURL(tc.input) - if tc.wantErr && err == nil { - t.Errorf("validateForwardURL(%q): want error, got nil", tc.input) - } - if !tc.wantErr && err != nil { - t.Errorf("validateForwardURL(%q): want nil, got %v", tc.input, err) - } - }) - } -} - -func TestCaptureOwnerIdentity_HasGOOSGOARCHAndHostname(t *testing.T) { - got := captureOwnerIdentity() - for _, expected := range []string{runtime.GOOS, runtime.GOARCH, "@"} { - if !strings.Contains(got, expected) { - t.Errorf("owner identity should contain %q, got %q", expected, got) - } - } -} - -func TestRunListenCapture_FallbackWhenBackend404(t *testing.T) { - // Backend doesn't have the capture endpoints yet → CLI must NOT fail. - // It logs a warning and falls back to passive SSE. We don't actually - // need the SSE to deliver anything for this assertion — we only care - // that runListenCapture doesn't propagate the 404 as an error. - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch { - case r.URL.Path == "/v1/cli/webhook-listeners": - // Spring's bare 404 — feature missing - w.WriteHeader(http.StatusNotFound) - _, _ = w.Write([]byte(`404 Not Found`)) - case strings.HasPrefix(r.URL.Path, "/v1/stream"): - // Hold the SSE open briefly; ctx will cancel us. - w.Header().Set("Content-Type", "text/event-stream") - w.WriteHeader(http.StatusOK) - default: - w.WriteHeader(http.StatusNotFound) - } - })) - t.Cleanup(server.Close) - - client := api.NewClient(server.URL, "ara_test_xxx") - - ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) - defer cancel() - - err := runListenCapture(ctx, client, nil, "") - // We expect nil — fallback path. The SSE consumer returns when ctx - // expires. - if err != nil { - t.Errorf("expected nil on 404 fallback, got: %v", err) - } -} - -func TestRunListenCapture_PropagatesConflict(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/v1/cli/webhook-listeners" && r.Method == http.MethodPost { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusConflict) - _, _ = w.Write([]byte(`{"error":{"code":"CAPTURE_LISTENER_ACTIVE","message":"taken","details":{"listenerId":"lst_other","owner":"laptop@there","expiresAt":"2026-12-01T00:00:00Z"}}}`)) - return - } - w.WriteHeader(http.StatusNotFound) - })) - t.Cleanup(server.Close) - - client := api.NewClient(server.URL, "ara_test_xxx") - ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) - defer cancel() - - err := runListenCapture(ctx, client, nil, "http://localhost:3000") - var conflict *api.CaptureConflictError - if !errors.As(err, &conflict) { - t.Fatalf("expected CaptureConflictError, got: %v", err) - } - if conflict.ListenerID != "lst_other" { - t.Errorf("conflict ID: %q", conflict.ListenerID) - } -} - -func TestPrintCaptureBanner_NoForwardWarning(t *testing.T) { - // Smoke — outputs go to stderr, just ensure we don't panic. - listener := &api.CreateWebhookListenerResponse{ - ID: "lst_x", - Secret: "wh_cli_xxx", - ExpiresAt: "2026-12-01T00:00:00Z", - } - printCaptureBanner(listener, "") - printCaptureBanner(listener, "http://localhost:3000") -} - -func TestPrintCaptureConflict_RendersAllFields(t *testing.T) { - conflict := &api.CaptureConflictError{ - ListenerID: "lst_x", - Owner: "darwin/arm64@host", - StartedAt: "2026-05-11T18:00:00Z", - ExpiresAt: "2026-05-11T19:00:00Z", - } - printCaptureConflict(conflict) - - conflict.Owner = "" - conflict.StartedAt = "" - conflict.ExpiresAt = "" - printCaptureConflict(conflict) -} - -func TestParseEventFilters(t *testing.T) { - cases := []struct { - input string - want []string - }{ - {"", nil}, - {" ", []string{}}, - {"message.delivered", []string{"message.delivered"}}, - {"message.delivered,message.read", []string{"message.delivered", "message.read"}}, - {" a , b , , c ", []string{"a", "b", "c"}}, - } - for _, tc := range cases { - t.Run(tc.input, func(t *testing.T) { - got := parseEventFilters(tc.input) - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("parseEventFilters(%q): want %#v, got %#v", tc.input, tc.want, got) - } - }) - } -} diff --git a/internal/cmd/logs.go b/internal/cmd/logs.go index b6ff841..7bba592 100644 --- a/internal/cmd/logs.go +++ b/internal/cmd/logs.go @@ -5,12 +5,10 @@ import ( "io" "os" - tea "github.com/charmbracelet/bubbletea" "github.com/spf13/cobra" "github.com/ararahq/cli/internal/api" "github.com/ararahq/cli/internal/output" - "github.com/ararahq/cli/internal/tui" ) const ( @@ -24,24 +22,18 @@ const ( ) var ( - logsTailFlag bool - logsFollowFlag bool - logsLimitFlag int - logsModeFlag string + logsLimitFlag int + logsModeFlag string ) var logsCmd = &cobra.Command{ Use: "logs", - Short: "View recent messages or tail live events", - Long: "Fetch and display recent messages from the AraraHQ console.\n" + - "Use --tail for a scrollable TUI of live events.\n" + - "Use --follow to emit live events as NDJSON to stdout (pipe-friendly).", - RunE: runLogs, + Short: "View recent messages", + Long: "Fetch and display recent messages from the AraraHQ console.", + RunE: runLogs, } func init() { - logsCmd.Flags().BoolVar(&logsTailFlag, "tail", false, "stream live events via SSE in a TUI viewer") - logsCmd.Flags().BoolVarP(&logsFollowFlag, "follow", "f", false, "stream live events as NDJSON to stdout (script-friendly)") logsCmd.Flags().IntVar(&logsLimitFlag, "limit", defaultLogsLimit, "number of recent messages to display") logsCmd.Flags().StringVar(&logsModeFlag, "mode", "", "filter by mode (e.g., sandbox, production)") @@ -49,10 +41,6 @@ func init() { } func runLogs(command *cobra.Command, arguments []string) error { - if logsTailFlag && logsFollowFlag { - return fmt.Errorf("--tail and --follow are mutually exclusive — pick one") - } - client, clientError := newClientForCmd() if clientError != nil { output.PrintError(fmt.Sprintf("Failed to create API client: %s", clientError.Error())) @@ -61,39 +49,9 @@ func runLogs(command *cobra.Command, arguments []string) error { client.SetVerbose(IsVerbose()) - if logsFollowFlag { - return runLogsFollow(client) - } - - if logsTailFlag { - return runLogsTail(client) - } - return runLogsFetch(client) } -func runLogsFollow(client *api.Client) error { - return runListenStream(client, nil, "") -} - -func runLogsTail(client *api.Client) error { - viewerConfig := tui.LogsViewerConfig{ - Client: client, - } - - viewerModel := tui.NewLogsViewer(viewerConfig) - - program := tea.NewProgram(viewerModel, tea.WithAltScreen()) - - _, runError := program.Run() - if runError != nil { - output.PrintError(fmt.Sprintf("Logs viewer failed: %s", runError.Error())) - return runError - } - - return nil -} - func runLogsFetch(client *api.Client) error { mode := resolveLogsMode(client) return runLogsFetchImpl(client, GetOutputFormat(), os.Stdout, mode, logsLimitFlag) diff --git a/internal/cmd/logs_test.go b/internal/cmd/logs_test.go index 22f3ba2..67214d7 100644 --- a/internal/cmd/logs_test.go +++ b/internal/cmd/logs_test.go @@ -187,35 +187,7 @@ func TestRunLogsFetchImpl_ServerErrorReturnsError(t *testing.T) { } } -func TestRunLogs_RejectsTailAndFollowTogether(t *testing.T) { - originalTail := logsTailFlag - originalFollow := logsFollowFlag - t.Cleanup(func() { - logsTailFlag = originalTail - logsFollowFlag = originalFollow - }) - logsTailFlag = true - logsFollowFlag = true - - err := runLogs(nil, nil) - if err == nil { - t.Fatal("expected mutual exclusion error") - } - if !strings.Contains(err.Error(), "mutually exclusive") { - t.Errorf("error should mention conflict, got: %v", err) - } -} - func TestRunLogs_FetchPathUsesInjectedClient(t *testing.T) { - originalTail := logsTailFlag - originalFollow := logsFollowFlag - t.Cleanup(func() { - logsTailFlag = originalTail - logsFollowFlag = originalFollow - }) - logsTailFlag = false - logsFollowFlag = false - body := `{"data":[{"id":"m","receiver":"+1","status":"sent","createdAt":"2026-01-01"}],"pagination":{}}` _, client := fakeAPIServerJSON(t, http.StatusOK, body) withFakeAPIClient(t, client) diff --git a/internal/cmd/manpages_test.go b/internal/cmd/manpages_test.go index c46e3ce..c4606c8 100644 --- a/internal/cmd/manpages_test.go +++ b/internal/cmd/manpages_test.go @@ -27,7 +27,6 @@ func TestRunGenerateManpages_WritesAllCommands(t *testing.T) { "arara.1", "arara-doctor.1", "arara-send.1", - "arara-listen.1", "arara-logs.1", "arara-completion.1", } diff --git a/internal/tui/logs_viewer.go b/internal/tui/logs_viewer.go deleted file mode 100644 index 703c604..0000000 --- a/internal/tui/logs_viewer.go +++ /dev/null @@ -1,239 +0,0 @@ -package tui - -import ( - "context" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/charmbracelet/bubbles/viewport" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" - - "github.com/ararahq/cli/internal/api" -) - -const ( - logsViewerHeight = 30 - logsViewerWidth = 120 - logsStatusBarHeight = 2 - logsTimestampFormat = "2006-01-02 15:04:05" - logsStatusLabelTailing = "Tailing live events" - logsStatusIcon = "\u26A1" - logsDisconnectedIcon = "\u2717" - logsDisconnectedLabel = "Disconnected" - logsQuitHint = "q: quit" -) - -var ( - logsTimestampStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#888888")) - logsEventStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FFFFFF")) - logsReceiverStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#CCCCCC")) - logsStatusStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#00C853")) - logsConnStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#00C853")) - logsDisconnStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FF1744")) - logsCounterStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#888888")) - logsHintStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#555555")) -) - -// logsEventReceived carries an SSE event for the logs viewer. -type logsEventReceived struct { - event api.SSEEvent -} - -// logsStreamDisconnected signals a stream disconnection. -type logsStreamDisconnected struct{} - -// LogsViewerConfig holds configuration for the live logs viewer. -type LogsViewerConfig struct { - Client *api.Client -} - -// LogsViewerModel is the Bubbletea model for streaming logs. -type LogsViewerModel struct { - config LogsViewerConfig - viewport viewport.Model - lines []string - eventCount int - connected bool - ready bool -} - -// NewLogsViewer creates a new LogsViewerModel. -func NewLogsViewer(config LogsViewerConfig) LogsViewerModel { - viewportModel := viewport.New(logsViewerWidth, logsViewerHeight) - viewportModel.SetContent("") - - return LogsViewerModel{ - config: config, - viewport: viewportModel, - lines: make([]string, 0), - } -} - -// Init starts the SSE stream for logs. -func (model LogsViewerModel) Init() tea.Cmd { - return model.subscribeToLogStream() -} - -// Update handles messages for the logs viewer. -func (model LogsViewerModel) Update(message tea.Msg) (tea.Model, tea.Cmd) { - switch typedMessage := message.(type) { - case tea.KeyMsg: - return model.handleKeyPress(typedMessage) - - case tea.WindowSizeMsg: - return model.handleWindowResize(typedMessage) - - case logsEventReceived: - return model.handleEvent(typedMessage) - - case logsStreamDisconnected: - return model.handleDisconnection() - } - - updatedViewport, viewportCmd := model.viewport.Update(message) - model.viewport = updatedViewport - return model, viewportCmd -} - -// View renders the logs viewer TUI. -func (model LogsViewerModel) View() string { - var builder strings.Builder - - builder.WriteString(model.renderStatusBar()) - builder.WriteString("\n") - builder.WriteString(model.viewport.View()) - builder.WriteString("\n") - builder.WriteString(logsHintStyle.Render(" " + logsQuitHint)) - - return builder.String() -} - -func (model LogsViewerModel) handleKeyPress(keyMessage tea.KeyMsg) (tea.Model, tea.Cmd) { - switch keyMessage.String() { - case "q", "ctrl+c": - return model, tea.Quit - } - - updatedViewport, viewportCmd := model.viewport.Update(keyMessage) - model.viewport = updatedViewport - return model, viewportCmd -} - -func (model *LogsViewerModel) handleWindowResize(sizeMessage tea.WindowSizeMsg) (tea.Model, tea.Cmd) { - model.viewport.Width = sizeMessage.Width - model.viewport.Height = sizeMessage.Height - logsStatusBarHeight - model.ready = true - model.viewport.SetContent(strings.Join(model.lines, "\n")) - return model, nil -} - -func (model *LogsViewerModel) handleEvent(received logsEventReceived) (tea.Model, tea.Cmd) { - model.connected = true - model.eventCount++ - - logLine := formatLogLine(received.event) - model.lines = append(model.lines, logLine) - model.viewport.SetContent(strings.Join(model.lines, "\n")) - model.viewport.GotoBottom() - - return model, model.waitForLogEvent() -} - -func (model *LogsViewerModel) handleDisconnection() (tea.Model, tea.Cmd) { - model.connected = false - return model, model.subscribeToLogStream() -} - -func (model LogsViewerModel) subscribeToLogStream() tea.Cmd { - return func() tea.Msg { - streamContext := context.Background() - - eventChannel, streamError := model.config.Client.StreamEvents(streamContext) - if streamError != nil { - return logsStreamDisconnected{} - } - - event, channelOpen := <-eventChannel - if !channelOpen { - return logsStreamDisconnected{} - } - - return logsEventReceived{event: event} - } -} - -func (model LogsViewerModel) waitForLogEvent() tea.Cmd { - return func() tea.Msg { - streamContext := context.Background() - - eventChannel, streamError := model.config.Client.StreamEvents(streamContext) - if streamError != nil { - return logsStreamDisconnected{} - } - - event, channelOpen := <-eventChannel - if !channelOpen { - return logsStreamDisconnected{} - } - - return logsEventReceived{event: event} - } -} - -func (model LogsViewerModel) renderStatusBar() string { - if model.connected { - statusText := logsConnStyle.Render(fmt.Sprintf("%s %s", logsStatusIcon, logsStatusLabelTailing)) - counterText := logsCounterStyle.Render(fmt.Sprintf("Events: %d", model.eventCount)) - return fmt.Sprintf("%s %s", statusText, counterText) - } - - return logsDisconnStyle.Render(fmt.Sprintf("%s %s", logsDisconnectedIcon, logsDisconnectedLabel)) -} - -func formatLogLine(event api.SSEEvent) string { - timestamp := time.Now().Format(logsTimestampFormat) - receiver := extractReceiverFromData(event.Data) - status := extractStatusFromData(event.Data) - - return fmt.Sprintf( - "%s %s %s %s", - logsTimestampStyle.Render(timestamp), - logsEventStyle.Render(padLogEventType(event.Event)), - logsReceiverStyle.Render(receiver), - logsStatusStyle.Render(status), - ) -} - -func extractReceiverFromData(data string) string { - var payload map[string]any - if jsonError := json.Unmarshal([]byte(data), &payload); jsonError != nil { - return "" - } - - receiver := extractStringField(payload, "receiver") - if receiver == "" { - receiver = extractStringField(payload, "to") - } - - return maskPhoneNumber(receiver) -} - -func extractStatusFromData(data string) string { - var payload map[string]any - if jsonError := json.Unmarshal([]byte(data), &payload); jsonError != nil { - return "" - } - - return extractStringField(payload, "status") -} - -func padLogEventType(eventType string) string { - const logEventTypePadWidth = 22 - if len(eventType) >= logEventTypePadWidth { - return eventType - } - return eventType + strings.Repeat(" ", logEventTypePadWidth-len(eventType)) -} diff --git a/internal/tui/repl.go b/internal/tui/repl.go index 598f8f8..06e2cf3 100644 --- a/internal/tui/repl.go +++ b/internal/tui/repl.go @@ -762,9 +762,6 @@ func (repl REPLModel) dispatchAction(action Action) (tea.Model, tea.Cmd) { case ActionShowConfig: repl.appendOutput(repl.renderConfig()) return repl, nil - case ActionShowListenHint: - repl.appendOutput(renderListenHint()) - return repl, nil case ActionRunSend: return repl.runAsync("send", repl.executeSendCommand(action.Args)) case ActionRunTemplates: @@ -936,9 +933,6 @@ func renderHelpText() string { lines = append(lines, cmd("numbers", "Registered phone numbers")) lines = append(lines, cmd("whoami", "Current profile and mode")) lines = append(lines, "") - lines = append(lines, sectionSep("Realtime")) - lines = append(lines, cmd("listen", "Stream webhook events (SSE)")) - lines = append(lines, "") lines = append(lines, sectionSep("Tools")) lines = append(lines, cmd("config", "Show configuration")) lines = append(lines, cmd("docs", "Open docs in browser")) @@ -1746,22 +1740,6 @@ func (repl REPLModel) executeBalanceCommand() tea.Cmd { } } -// ── /listen hint ───────────────────────────────────────────────── - -func renderListenHint() string { - card := sCard.Width(55) - - content := sBold.Render("Webhook Listener") + "\n\n" + - sMuted.Render(" The listener runs in full-screen mode.") + "\n" + - sMuted.Render(" Exit the REPL and run:") + "\n\n" + - sValue.Render(" arara listen") + "\n\n" + - sMuted.Render(" Options:") + "\n" + - sDim.Render(" --forward-to http://localhost:3000/webhook") + "\n" + - sDim.Render(" --events message.sent,message.delivered") - - return "\n" + card.Render(content) + "\n" -} - // ── Not logged in ──────────────────────────────────────────────── func renderNotLoggedIn() string { diff --git a/internal/tui/repl_completion.go b/internal/tui/repl_completion.go index 8f54fdd..f32f697 100644 --- a/internal/tui/repl_completion.go +++ b/internal/tui/repl_completion.go @@ -31,7 +31,6 @@ var completionSuggestions = []string{ "whoami", "config", "docs", - "listen", "clear", "quit", "exit", @@ -51,7 +50,6 @@ var completionSuggestions = []string{ "/whoami", "/config", "/docs", - "/listen", "/clear", "/quit", } diff --git a/internal/tui/repl_dispatch.go b/internal/tui/repl_dispatch.go index ac1cb67..d327442 100644 --- a/internal/tui/repl_dispatch.go +++ b/internal/tui/repl_dispatch.go @@ -16,7 +16,6 @@ const ( ActionShowWhoami ActionShowConfig ActionOpenDocs - ActionShowListenHint ActionRunSend ActionRunTemplates ActionRunStatus @@ -77,8 +76,6 @@ func ParseInput(rawInput string) Action { return Action{Kind: ActionOpenDocs} case "/config", "config": return Action{Kind: ActionShowConfig} - case "/listen", "listen": - return Action{Kind: ActionShowListenHint} case "/send", "send": return Action{Kind: ActionRunSend, Args: commandArgs, RequiresAPIClient: true} diff --git a/internal/tui/repl_dispatch_test.go b/internal/tui/repl_dispatch_test.go index 4c03488..a1dc67a 100644 --- a/internal/tui/repl_dispatch_test.go +++ b/internal/tui/repl_dispatch_test.go @@ -42,8 +42,6 @@ func TestParseInput_BuiltinCommandsNoArgs(t *testing.T) { "docs": ActionOpenDocs, "/config": ActionShowConfig, "config": ActionShowConfig, - "/listen": ActionShowListenHint, - "listen": ActionShowListenHint, } for input, wantKind := range cases { t.Run(input, func(t *testing.T) { diff --git a/internal/tui/webhook_viewer.go b/internal/tui/webhook_viewer.go deleted file mode 100644 index d3ccca2..0000000 --- a/internal/tui/webhook_viewer.go +++ /dev/null @@ -1,465 +0,0 @@ -package tui - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - "time" - - "github.com/charmbracelet/bubbles/viewport" - tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" - - "github.com/ararahq/cli/internal/api" -) - -const ( - webhookViewerWidth = 120 - webhookViewerHeight = 30 - statusBarHeight = 2 - forwardingTimeoutSeconds = 10 - httpStatusOKThreshold = 300 - httpStatusClientError = 400 - httpStatusServerError = 500 - phoneMaskVisibleDigits = 5 - phoneMaskPrefix = "..." - latencyUnitMilliseconds = "ms" - statusConnected = "connected" - statusDisconnected = "disconnected" - jsonIndentSpaces = " " - statusLabelConnected = "Connected to SSE stream" - statusLabelDisconnected = "Disconnected" - statusIconConnected = "\u26A1" - statusIconDisconnected = "\u2717" - eventCounterLabel = "Events received: " - quitHint = "q: quit" - jsonToggleHint = "j: toggle JSON" - whatsappReceiverPrefix = "whatsapp:" -) - -// Styles for the webhook viewer. -var ( - timestampStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#888888")) - eventTypeStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FFFFFF")) - phoneStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#CCCCCC")) - statusOKStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#00C853")) - statusErrStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF1744")) - latencyStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#888888")) - connectedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#00C853")) - disconnStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FF1744")) - counterStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#888888")) - hintStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#555555")) - jsonStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#888888")) -) - -// webhookEventReceived is a Bubbletea message carrying a new SSE event. -type webhookEventReceived struct { - event api.SSEEvent -} - -// webhookStreamDisconnected signals the SSE stream closed unexpectedly. -type webhookStreamDisconnected struct{} - -// forwardResult carries the HTTP response from forwarding a webhook event. -type forwardResult struct { - statusCode int - latency time.Duration - eventIndex int -} - -// webhookLogEntry represents a single rendered log line with optional raw JSON. -type webhookLogEntry struct { - renderedLine string - rawJSON string - forwardCode int - forwardTime time.Duration -} - -// WebhookViewerConfig holds initialization parameters for the viewer. -type WebhookViewerConfig struct { - Client *api.Client - ForwardToURL string - EventFilters []string -} - -// WebhookViewerModel is the Bubbletea model for the live webhook viewer. -type WebhookViewerModel struct { - config WebhookViewerConfig - viewport viewport.Model - entries []webhookLogEntry - eventCount int - connected bool - showJSON bool - cancelStream context.CancelFunc - ready bool -} - -// NewWebhookViewer creates a new WebhookViewerModel. -func NewWebhookViewer(config WebhookViewerConfig) WebhookViewerModel { - viewportModel := viewport.New(webhookViewerWidth, webhookViewerHeight) - viewportModel.SetContent("") - - return WebhookViewerModel{ - config: config, - viewport: viewportModel, - entries: make([]webhookLogEntry, 0), - connected: false, - showJSON: false, - ready: false, - } -} - -// Init starts the SSE stream subscription. -func (model WebhookViewerModel) Init() tea.Cmd { - return model.subscribeToStream() -} - -// Update handles incoming messages and key presses. -func (model WebhookViewerModel) Update(message tea.Msg) (tea.Model, tea.Cmd) { - switch typedMessage := message.(type) { - case tea.KeyMsg: - return model.handleKeyPress(typedMessage) - - case tea.WindowSizeMsg: - return model.handleWindowResize(typedMessage) - - case webhookEventReceived: - return model.handleEventReceived(typedMessage) - - case webhookStreamDisconnected: - return model.handleDisconnection() - - case forwardResult: - return model.handleForwardResult(typedMessage) - } - - updatedViewport, viewportCmd := model.viewport.Update(message) - model.viewport = updatedViewport - return model, viewportCmd -} - -// View renders the complete TUI. -func (model WebhookViewerModel) View() string { - var builder strings.Builder - - builder.WriteString(model.renderStatusBar()) - builder.WriteString("\n") - builder.WriteString(model.viewport.View()) - builder.WriteString("\n") - builder.WriteString(model.renderFooter()) - - return builder.String() -} - -func (model WebhookViewerModel) handleKeyPress(keyMessage tea.KeyMsg) (tea.Model, tea.Cmd) { - switch keyMessage.String() { - case "q", "ctrl+c": - if model.cancelStream != nil { - model.cancelStream() - } - return model, tea.Quit - - case "j": - model.showJSON = !model.showJSON - model.refreshViewportContent() - return model, nil - } - - updatedViewport, viewportCmd := model.viewport.Update(keyMessage) - model.viewport = updatedViewport - return model, viewportCmd -} - -func (model *WebhookViewerModel) handleWindowResize(sizeMessage tea.WindowSizeMsg) (tea.Model, tea.Cmd) { - model.viewport.Width = sizeMessage.Width - model.viewport.Height = sizeMessage.Height - statusBarHeight - model.ready = true - model.refreshViewportContent() - return model, nil -} - -func (model *WebhookViewerModel) handleEventReceived(received webhookEventReceived) (tea.Model, tea.Cmd) { - model.connected = true - - if !model.shouldIncludeEvent(received.event.Event) { - return model, model.waitForNextEvent() - } - - model.eventCount++ - - entry := buildLogEntry(received.event) - model.entries = append(model.entries, entry) - model.refreshViewportContent() - model.viewport.GotoBottom() - - var commands []tea.Cmd - commands = append(commands, model.waitForNextEvent()) - - if model.config.ForwardToURL != "" { - commands = append(commands, model.forwardEvent(received.event, len(model.entries)-1)) - } - - return model, tea.Batch(commands...) -} - -func (model *WebhookViewerModel) handleDisconnection() (tea.Model, tea.Cmd) { - model.connected = false - return model, model.subscribeToStream() -} - -func (model *WebhookViewerModel) handleForwardResult(result forwardResult) (tea.Model, tea.Cmd) { - if result.eventIndex >= len(model.entries) { - return model, nil - } - - model.entries[result.eventIndex].forwardCode = result.statusCode - model.entries[result.eventIndex].forwardTime = result.latency - model.refreshViewportContent() - return model, nil -} - -func (model WebhookViewerModel) shouldIncludeEvent(eventType string) bool { - if len(model.config.EventFilters) == 0 { - return true - } - - for _, filter := range model.config.EventFilters { - if filter == eventType { - return true - } - } - - return false -} - -func (model WebhookViewerModel) subscribeToStream() tea.Cmd { - return func() tea.Msg { - // Background context here is intentional: the stream lifetime is - // owned by the bubbletea program, which is torn down via the - // process exiting. Using context.WithCancel without storing the - // cancelFunc on the model would leak it (gosec G118), so we pick - // the simpler model: the underlying SSE goroutine ends when the - // channel reader stops or the HTTP connection drops. - streamContext := context.Background() - - eventChannel, streamError := model.config.Client.StreamEvents(streamContext) - if streamError != nil { - return webhookStreamDisconnected{} - } - - event, channelOpen := <-eventChannel - if !channelOpen { - return webhookStreamDisconnected{} - } - - return webhookEventReceived{event: event} - } -} - -func (model WebhookViewerModel) waitForNextEvent() tea.Cmd { - return func() tea.Msg { - streamContext := context.Background() - - eventChannel, streamError := model.config.Client.StreamEvents(streamContext) - if streamError != nil { - return webhookStreamDisconnected{} - } - - event, channelOpen := <-eventChannel - if !channelOpen { - return webhookStreamDisconnected{} - } - - return webhookEventReceived{event: event} - } -} - -func (model WebhookViewerModel) forwardEvent(event api.SSEEvent, eventIndex int) tea.Cmd { - forwardURL := model.config.ForwardToURL - - return func() tea.Msg { - startTime := time.Now() - - httpClient := &http.Client{ - Timeout: forwardingTimeoutSeconds * time.Second, - } - - requestBody := bytes.NewBufferString(event.Data) - httpRequest, requestError := http.NewRequest(http.MethodPost, forwardURL, requestBody) - if requestError != nil { - return forwardResult{ - statusCode: 0, - latency: time.Since(startTime), - eventIndex: eventIndex, - } - } - - httpRequest.Header.Set("Content-Type", "application/json") - - httpResponse, responseError := httpClient.Do(httpRequest) - if responseError != nil { - return forwardResult{ - statusCode: 0, - latency: time.Since(startTime), - eventIndex: eventIndex, - } - } - defer httpResponse.Body.Close() - _, _ = io.Copy(io.Discard, httpResponse.Body) - - return forwardResult{ - statusCode: httpResponse.StatusCode, - latency: time.Since(startTime), - eventIndex: eventIndex, - } - } -} - -func (model *WebhookViewerModel) refreshViewportContent() { - var lines []string - - for entryIndex, entry := range model.entries { - line := entry.renderedLine - - if entry.forwardCode > 0 { - line += " " + renderForwardStatus(entry.forwardCode, entry.forwardTime) - } - - lines = append(lines, line) - - isLastEntry := entryIndex == len(model.entries)-1 - if model.showJSON && isLastEntry && entry.rawJSON != "" { - lines = append(lines, jsonStyle.Render(entry.rawJSON)) - } - } - - model.viewport.SetContent(strings.Join(lines, "\n")) -} - -func (model WebhookViewerModel) renderStatusBar() string { - var statusText string - - if model.connected { - statusText = connectedStyle.Render(fmt.Sprintf("%s %s", statusIconConnected, statusLabelConnected)) - } else { - statusText = disconnStyle.Render(fmt.Sprintf("%s %s", statusIconDisconnected, statusLabelDisconnected)) - } - - counterText := counterStyle.Render(fmt.Sprintf("%s%d", eventCounterLabel, model.eventCount)) - - return fmt.Sprintf("%s %s", statusText, counterText) -} - -func (model WebhookViewerModel) renderFooter() string { - return hintStyle.Render(fmt.Sprintf(" %s %s", quitHint, jsonToggleHint)) -} - -func buildLogEntry(event api.SSEEvent) webhookLogEntry { - timestamp := time.Now().Format("2006-01-02 15:04:05") - phone := extractPhoneFromEventData(event.Data) - - renderedLine := fmt.Sprintf( - "%s %s %s", - timestampStyle.Render(timestamp), - eventTypeStyle.Render(padEventType(event.Event)), - phoneStyle.Render(phone), - ) - - prettyJSON := formatJSONData(event.Data) - - return webhookLogEntry{ - renderedLine: renderedLine, - rawJSON: prettyJSON, - } -} - -func renderForwardStatus(statusCode int, latency time.Duration) string { - latencyMilliseconds := latency.Milliseconds() - latencyText := latencyStyle.Render(fmt.Sprintf("%d%s", latencyMilliseconds, latencyUnitMilliseconds)) - - if statusCode >= httpStatusServerError { - return statusErrStyle.Render(fmt.Sprintf("[%d ERR]", statusCode)) + " " + latencyText - } - - if statusCode >= httpStatusClientError { - return statusErrStyle.Render(fmt.Sprintf("[%d ERR]", statusCode)) + " " + latencyText - } - - if statusCode > 0 && statusCode < httpStatusOKThreshold { - return statusOKStyle.Render(fmt.Sprintf("[%d OK]", statusCode)) + " " + latencyText - } - - return statusErrStyle.Render("[ERR]") + " " + latencyText -} - -func extractPhoneFromEventData(data string) string { - var payload map[string]any - if jsonError := json.Unmarshal([]byte(data), &payload); jsonError != nil { - return "" - } - - receiver := extractStringField(payload, "receiver") - if receiver == "" { - receiver = extractStringField(payload, "to") - } - if receiver == "" { - receiver = extractStringField(payload, "phone") - } - - return maskPhoneNumber(receiver) -} - -func extractStringField(payload map[string]any, fieldName string) string { - value, exists := payload[fieldName] - if !exists { - return "" - } - - stringValue, isString := value.(string) - if !isString { - return "" - } - - return stringValue -} - -func maskPhoneNumber(phone string) string { - if phone == "" { - return "" - } - - cleaned := strings.TrimPrefix(phone, whatsappReceiverPrefix) - - if len(cleaned) <= phoneMaskVisibleDigits { - return cleaned - } - - visiblePart := cleaned[len(cleaned)-phoneMaskVisibleDigits:] - return phoneMaskPrefix + visiblePart -} - -func padEventType(eventType string) string { - const eventTypePadWidth = 22 - if len(eventType) >= eventTypePadWidth { - return eventType - } - return eventType + strings.Repeat(" ", eventTypePadWidth-len(eventType)) -} - -func formatJSONData(data string) string { - var parsed any - if jsonError := json.Unmarshal([]byte(data), &parsed); jsonError != nil { - return data - } - - formatted, formatError := json.MarshalIndent(parsed, " ", jsonIndentSpaces) - if formatError != nil { - return data - } - - return " " + string(formatted) -} From 51c1c899e918316f6d96d7ccbb126d65f49f521f Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Sun, 8 Nov 2026 14:08:58 -0300 Subject: [PATCH 3/4] docs(changelog): note removal of listen and telemetry --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6410033..370cf0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,16 @@ All notable changes to the Arara CLI are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project adheres to [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Removed + +- `arara listen` and telemetry. The `listen` command, the SSE event + stream client (`GET /v1/stream`), the capture listener client + (`/v1/cli/webhook-listeners`), `arara logs --tail`/`--follow`, the + REPL `/listen` hint, and `arara telemetry on|off|status` (with its + `POST /v1/cli/telemetry/events` sender) are gone. + ## [0.2.0] - 2026-05-12 ### Added From ed0a01305cf1d0fd7cee1b100d55e12c6cfcb3da Mon Sep 17 00:00:00 2001 From: Micael Marques Date: Mon, 9 Nov 2026 15:51:37 -0300 Subject: [PATCH 4/4] chore(go): bump toolchain to 1.26.10 to clear stdlib vulnerabilities --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 7c4c7aa..78abd2d 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/ararahq/cli -go 1.26.5 +go 1.26.10 require ( github.com/charmbracelet/bubbles v1.0.0