fix: per-caller context on account lookup, stop on non-websocket receive, sanitize CLI output

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Vincent BourdonandClaude Opus 5.5 committed 2026-11-20 15:51:38 +01:00
1 parent 45f88378a6
commit 136e431917
8 files changed
+89 -7

No files matched your search

+3 -1
View File
@@ -64,7 +64,9 @@ Options: `WithNumber` (choose an account when several are linked),
Errors can be checked with `errors.Is`: `ErrNotLinked`,
`ErrMultipleAccounts`, `ErrUnavailable` (unreachable or 5xx),
`ErrRateLimited` (429), `ErrEmptyText`. Other API errors are `*APIError`
`ErrRateLimited` (429), `ErrEmptyText`, `ErrNotJSONRPC` (the service is not in
`MODE=json-rpc`/`json-rpc-native`; `Listen` stops instead of silently
consuming messages). Other API errors are `*APIError`
(`StatusCode`, `Message`). `Send` never retries.
See [`examples/`](examples/) for a complete app and a docker-compose file.
+8 -3
View File
@@ -178,11 +178,14 @@ func (c *Client) Accounts(ctx context.Context) ([]Account, error) {
}
// account resolves the account to use and caches it after the first success.
// The lock is not held during the lookup, so each caller's ctx applies; a
// concurrent duplicate lookup is harmless.
func (c *Client) account(ctx context.Context) (Account, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.acct != nil {
return *c.acct, nil
cached := c.acct
c.mu.Unlock()
if cached != nil {
return *cached, nil
}
accts, err := c.Accounts(ctx)
if err != nil {
@@ -207,7 +210,9 @@ func (c *Client) account(ctx context.Context) (Account, error) {
default:
found = &accts[0]
}
c.mu.Lock()
c.acct = found
c.mu.Unlock()
return *found, nil
}
+29
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"reflect"
"testing"
"time"
)
func TestNewDoesNoNetwork(t *testing.T) {
@@ -175,3 +176,31 @@ func TestEndpointJoin(t *testing.T) {
}
}
}
func TestAccountLookupRespectsCallerContext(t *testing.T) {
f := newFakeAPI(t)
release := make(chan struct{})
t.Cleanup(func() { close(release) })
f.mux.HandleFunc("GET /v1/accounts", func(w http.ResponseWriter, r *http.Request) {
select {
case <-release:
case <-r.Context().Done():
}
})
c := mustNew(t, f.URL)
go func() { _, _ = c.account(context.Background()) }() // e.g. Listen, stuck on a hung service
time.Sleep(50 * time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
done := make(chan error, 1)
go func() { done <- c.Send(ctx, "+332", "hi") }()
select {
case err := <-done:
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Send err = %v, want DeadlineExceeded", err)
}
case <-time.After(2 * time.Second):
t.Fatal("Send ignored its context while another account lookup was in flight")
}
}
+13 -1
View File
@@ -23,6 +23,7 @@ import (
"strings"
"text/tabwriter"
"time"
"unicode"
"git.siteop.biz/vincentb99/signalbot"
"github.com/mdp/qrterminal/v3"
@@ -213,10 +214,21 @@ func listen(ctx context.Context, c *signalbot.Client, stdout io.Writer) error {
if where == "" {
where = "direct"
}
fmt.Fprintf(stdout, "[%s] %s (%s): %s\n", m.Timestamp.Format("2006-01-02 15:04:05"), m.From, where, m.Text)
fmt.Fprintf(stdout, "[%s] %s (%s): %s\n", m.Timestamp.Format("2006-01-02 15:04:05"), sanitize(m.From), where, sanitize(m.Text))
})
if errors.Is(err, context.Canceled) {
return nil
}
return err
}
// sanitize replaces control characters (except newline and tab) so that
// message text from strangers cannot inject terminal escape sequences.
func sanitize(s string) string {
return strings.Map(func(r rune) rune {
if r == '\n' || r == '\t' || !unicode.IsControl(r) {
return r
}
return '?'
}, s)
}
+10
View File
@@ -166,3 +166,13 @@ func TestRunListen(t *testing.T) {
t.Fatalf("code %d, stderr %q", code, errOut.String())
}
}
func TestSanitizeStripsControlChars(t *testing.T) {
got := sanitize("hi\x1b]0;pwned\x07 there\x1b[2J\nline2\tx")
if strings.ContainsAny(got, "\x1b\x07") {
t.Fatalf("control chars left: %q", got)
}
if !strings.Contains(got, "\nline2\tx") || !strings.HasPrefix(got, "hi") {
t.Fatalf("legit text altered: %q", got)
}
}
+4
View File
@@ -22,6 +22,10 @@ var (
// ErrRateLimited means Signal rate-limited the account (HTTP 429).
ErrRateLimited = errors.New("signalbot: rate limited")
// ErrNotJSONRPC means the service's receive endpoint is not a websocket:
// the service must run with MODE=json-rpc or MODE=json-rpc-native.
ErrNotJSONRPC = errors.New("signalbot: receive endpoint is not a websocket, run the service with MODE=json-rpc or json-rpc-native")
// ErrEmptyText means Send was called with an empty or blank text.
ErrEmptyText = errors.New("signalbot: empty text")
)
+7 -2
View File
@@ -20,7 +20,7 @@ type Handler func(ctx context.Context, m Message)
// Connection losses and an unavailable service are retried with an
// exponential backoff (1s to 30s), logged at Warn level. Listen returns
// early only for errors that retrying cannot fix: ErrNotLinked,
// ErrMultipleAccounts, or a 4xx answer (*APIError) to the websocket
// ErrMultipleAccounts, ErrNotJSONRPC, or a 4xx answer (*APIError) to the websocket
// handshake. A panic in h is recovered and logged at Error level.
//
// Only one Listen per account should run at a time.
@@ -51,7 +51,7 @@ func (c *Client) Listen(ctx context.Context, h Handler) error {
// permanent reports whether retrying cannot fix err.
func permanent(err error) bool {
if errors.Is(err, ErrNotLinked) || errors.Is(err, ErrMultipleAccounts) {
if errors.Is(err, ErrNotLinked) || errors.Is(err, ErrMultipleAccounts) || errors.Is(err, ErrNotJSONRPC) {
return true
}
var apiErr *APIError
@@ -69,6 +69,11 @@ func (c *Client) listenOnce(ctx context.Context, h Handler) (connected bool, err
}
conn, resp, err := websocket.Dial(ctx, c.wsURL(acct), &websocket.DialOptions{HTTPClient: c.http})
if err != nil {
if resp != nil && resp.StatusCode >= 200 && resp.StatusCode < 300 {
// A plain HTTP answer: the service runs in normal/native mode,
// where each GET consumes messages. Retrying would lose them.
return false, ErrNotJSONRPC
}
if resp != nil && resp.StatusCode >= 300 {
return false, &APIError{StatusCode: resp.StatusCode, Message: err.Error()}
}
+15
View File
@@ -276,3 +276,18 @@ func TestListenWebsocketURL(t *testing.T) {
}
}
}
func TestListenServiceNotInJSONRPCMode(t *testing.T) {
f := newFakeAPI(t)
f.accounts(`[{"number":"+331"}]`)
f.mux.HandleFunc("GET /v1/receive/{acct}", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, []any{}) // MODE=normal: plain GET, no websocket upgrade
})
err := fastClient(t, f.URL).Listen(context.Background(), func(context.Context, Message) {})
if !errors.Is(err, ErrNotJSONRPC) {
t.Fatalf("err = %v, want ErrNotJSONRPC", err)
}
if n := f.hitCount("GET /v1/receive/+331"); n != 1 {
t.Fatalf("handshakes = %d, want 1 (no retry)", n)
}
}