diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..15db900 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 vincentb99 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/client.go b/client.go new file mode 100644 index 0000000..f1c00f8 --- /dev/null +++ b/client.go @@ -0,0 +1,237 @@ +package signalbot + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// Client talks to a signal-cli-rest-api service. It is safe for concurrent use. +type Client struct { + base *url.URL + number string + http *http.Client + log *slog.Logger + + minBackoff, maxBackoff time.Duration + + mu sync.Mutex + acct *Account // resolved account, cached after the first success +} + +// Option configures a Client. +type Option func(*Client) + +// WithNumber selects the linked account to use, by phone number (E.164) or +// ACI. Without it, the service must have exactly one linked account. +func WithNumber(number string) Option { return func(c *Client) { c.number = number } } + +// WithHTTPClient sets the HTTP client used for REST calls and the websocket +// handshake. The default is a client without timeout: use contexts. +func WithHTTPClient(h *http.Client) Option { return func(c *Client) { c.http = h } } + +// WithLogger sets the logger used for reconnections and handler panics. +// The default is slog.Default(). +func WithLogger(l *slog.Logger) Option { return func(c *Client) { c.log = l } } + +// Account is a Signal account linked in the service. Number may be empty +// for accounts without a phone number; ACI may be empty on old service +// versions. +type Account struct { + Number string + ACI string +} + +// id returns the identifier used in API paths and payloads. +func (a Account) id() string { + if a.Number != "" { + return a.Number + } + return a.ACI +} + +// New returns a client for the service at baseURL (e.g. +// "http://signal-api:8080"). It does not contact the service. +func New(baseURL string, opts ...Option) (*Client, error) { + u, err := url.Parse(baseURL) + if err != nil { + return nil, fmt.Errorf("signalbot: invalid base URL: %w", err) + } + if (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return nil, fmt.Errorf("signalbot: invalid base URL %q: want http(s)://host[:port][/path]", baseURL) + } + u.Path = strings.TrimSuffix(u.Path, "/") + c := &Client{ + base: u, + http: http.DefaultClient, + log: slog.Default(), + minBackoff: time.Second, + maxBackoff: 30 * time.Second, + } + for _, o := range opts { + o(c) + } + return c, nil +} + +// endpoint joins path (which may carry a "?query") to the base URL. +func (c *Client) endpoint(path string) string { + p, q, _ := strings.Cut(path, "?") + u := *c.base + u.Path += p + u.RawPath = "" + u.RawQuery = q + return u.String() +} + +// do performs a JSON request. in may be nil; out may be nil to ignore the body. +func (c *Client) do(ctx context.Context, method, path string, in, out any) error { + var body io.Reader + if in != nil { + b, err := json.Marshal(in) + if err != nil { + return fmt.Errorf("signalbot: encode request: %w", err) + } + body = bytes.NewReader(b) + } + req, err := http.NewRequestWithContext(ctx, method, c.endpoint(path), body) + if err != nil { + return fmt.Errorf("signalbot: build request: %w", err) + } + if in != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := c.http.Do(req) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return unavailable(err) + } + defer resp.Body.Close() + data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if err != nil { + return unavailable(err) + } + if resp.StatusCode >= 300 { + return apiError(resp.StatusCode, data) + } + if out == nil || len(bytes.TrimSpace(data)) == 0 { + return nil + } + if err := json.Unmarshal(data, out); err != nil { + return fmt.Errorf("signalbot: decode %s response: %w", path, err) + } + return nil +} + +func apiError(status int, body []byte) *APIError { + var e struct { + Error string `json:"error"` + } + msg := strings.TrimSpace(string(body)) + if json.Unmarshal(body, &e) == nil && e.Error != "" { + msg = e.Error + } + if msg == "" { + msg = http.StatusText(status) + } + return &APIError{StatusCode: status, Message: msg} +} + +// Accounts lists the accounts linked in the service. +func (c *Client) Accounts(ctx context.Context) ([]Account, error) { + var raw []json.RawMessage + if err := c.do(ctx, http.MethodGet, "/v1/accounts", nil, &raw); err != nil { + return nil, err + } + accts := make([]Account, 0, len(raw)) + for _, r := range raw { + var number string + if json.Unmarshal(r, &number) == nil { + accts = append(accts, Account{Number: number}) + continue + } + var obj struct { + Number string `json:"number"` + ACI *string `json:"aci"` + } + if err := json.Unmarshal(r, &obj); err != nil { + return nil, fmt.Errorf("signalbot: decode account %s: %w", r, err) + } + a := Account{Number: obj.Number} + if obj.ACI != nil { + a.ACI = *obj.ACI + } + accts = append(accts, a) + } + return accts, nil +} + +// account resolves the account to use and caches it after the first success. +func (c *Client) account(ctx context.Context) (Account, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.acct != nil { + return *c.acct, nil + } + accts, err := c.Accounts(ctx) + if err != nil { + return Account{}, err + } + var found *Account + switch { + case c.number != "": + for i := range accts { + if accts[i].Number == c.number || accts[i].ACI == c.number { + found = &accts[i] + break + } + } + if found == nil { + return Account{}, fmt.Errorf("%w: %s", ErrNotLinked, c.number) + } + case len(accts) == 0: + return Account{}, ErrNotLinked + case len(accts) > 1: + return Account{}, ErrMultipleAccounts + default: + found = &accts[0] + } + c.acct = found + return *found, nil +} + +// LinkURI asks the service for a device-link URI ("sgnl://linkdevice?…") to +// be shown as a QR code and scanned from the phone holding the bot account. +func (c *Client) LinkURI(ctx context.Context, deviceName string) (string, error) { + var resp struct { + URI string `json:"device_link_uri"` + } + path := "/v1/qrcodelink/raw?device_name=" + url.QueryEscape(deviceName) + if err := c.do(ctx, http.MethodGet, path, nil, &resp); err != nil { + return "", err + } + if resp.URI == "" { + return "", errors.New("signalbot: empty device link URI") + } + return resp.URI, nil +} + +// Ping checks that the service is reachable and the account is linked. +func (c *Client) Ping(ctx context.Context) error { + if err := c.do(ctx, http.MethodGet, "/v1/health", nil, nil); err != nil { + return err + } + _, err := c.account(ctx) + return err +} diff --git a/client_test.go b/client_test.go new file mode 100644 index 0000000..490727e --- /dev/null +++ b/client_test.go @@ -0,0 +1,177 @@ +package signalbot + +import ( + "context" + "errors" + "net/http" + "reflect" + "testing" +) + +func TestNewDoesNoNetwork(t *testing.T) { + if _, err := New("http://127.0.0.1:1"); err != nil { + t.Fatalf("New returned %v, want nil", err) + } +} + +func TestNewRejectsBadURL(t *testing.T) { + for _, u := range []string{"ftp://x", "::", ""} { + if _, err := New(u); err == nil { + t.Errorf("New(%q) returned nil error", u) + } + } +} + +func TestAccountsObjectAndLegacyFormats(t *testing.T) { + cases := []struct { + body string + want []Account + }{ + {`[{"number":"+331","aci":"a-1"},{"number":"","aci":"a-2"}]`, []Account{{"+331", "a-1"}, {"", "a-2"}}}, + {`[{"number":"+331","aci":null}]`, []Account{{"+331", ""}}}, + {`["+331"]`, []Account{{"+331", ""}}}, + } + for _, tc := range cases { + f := newFakeAPI(t) + f.accounts(tc.body) + got, err := mustNew(t, f.URL).Accounts(context.Background()) + if err != nil { + t.Fatalf("%s: %v", tc.body, err) + } + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("%s: got %v, want %v", tc.body, got, tc.want) + } + } +} + +func TestAccountAutoDetect(t *testing.T) { + cases := []struct { + body string + want Account + wantErr error + }{ + {`[{"number":"+331","aci":"a-1"}]`, Account{"+331", "a-1"}, nil}, + {`[]`, Account{}, ErrNotLinked}, + {`[{"number":"+331"},{"number":"+332"}]`, Account{}, ErrMultipleAccounts}, + } + for _, tc := range cases { + f := newFakeAPI(t) + f.accounts(tc.body) + got, err := mustNew(t, f.URL).account(context.Background()) + if !errors.Is(err, tc.wantErr) { + t.Errorf("%s: err = %v, want %v", tc.body, err, tc.wantErr) + } + if got != tc.want { + t.Errorf("%s: got %v, want %v", tc.body, got, tc.want) + } + } +} + +func TestAccountWithNumber(t *testing.T) { + f := newFakeAPI(t) + f.accounts(`[{"number":"+331","aci":"a-1"},{"number":"+332","aci":"a-2"}]`) + + got, err := mustNew(t, f.URL, WithNumber("+332")).account(context.Background()) + if err != nil || got != (Account{"+332", "a-2"}) { + t.Fatalf("got %v, %v; want {+332 a-2}, nil", got, err) + } + + _, err = mustNew(t, f.URL, WithNumber("+339")).account(context.Background()) + if !errors.Is(err, ErrNotLinked) { + t.Fatalf("unknown number: err = %v, want ErrNotLinked", err) + } +} + +func TestAccountCachedAfterSuccess(t *testing.T) { + f := newFakeAPI(t) + f.health() + f.accounts(`[{"number":"+331"}]`) + c := mustNew(t, f.URL) + for i := 0; i < 2; i++ { + if err := c.Ping(context.Background()); err != nil { + t.Fatalf("Ping %d: %v", i, err) + } + } + if n := f.hitCount("GET /v1/accounts"); n != 1 { + t.Fatalf("/v1/accounts hit %d times, want 1", n) + } +} + +func TestPing(t *testing.T) { + f := newFakeAPI(t) + f.health() + f.accounts(`[{"number":"+331"}]`) + if err := mustNew(t, f.URL).Ping(context.Background()); err != nil { + t.Fatalf("Ping: %v", err) + } + + closed := newFakeAPI(t) + url := closed.URL + closed.Close() + err := mustNew(t, url).Ping(context.Background()) + if !errors.Is(err, ErrUnavailable) { + t.Fatalf("Ping on closed server: err = %v, want ErrUnavailable", err) + } +} + +func TestAPIErrorMapping(t *testing.T) { + cases := []struct { + status int + body string + wantIs error + wantNotIs []error + wantMsg string + }{ + {503, `{"error":"down"}`, ErrUnavailable, []error{ErrRateLimited}, "down"}, + {429, `{"error":"slow down","challenge_tokens":["x"]}`, ErrRateLimited, []error{ErrUnavailable}, "slow down"}, + {400, `{"error":"bad"}`, nil, []error{ErrUnavailable, ErrRateLimited}, "bad"}, + {400, "plain text oops\n", nil, []error{ErrUnavailable, ErrRateLimited}, "plain text oops"}, + } + for _, tc := range cases { + f := newFakeAPI(t) + f.mux.HandleFunc("GET /v1/accounts", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.body)) + }) + _, err := mustNew(t, f.URL).Accounts(context.Background()) + var apiErr *APIError + if !errors.As(err, &apiErr) { + t.Fatalf("%d: err %v is not *APIError", tc.status, err) + } + if apiErr.StatusCode != tc.status || apiErr.Message != tc.wantMsg { + t.Errorf("%d: got %+v, want status %d message %q", tc.status, apiErr, tc.status, tc.wantMsg) + } + if tc.wantIs != nil && !errors.Is(err, tc.wantIs) { + t.Errorf("%d: errors.Is(%v) = false", tc.status, tc.wantIs) + } + for _, not := range tc.wantNotIs { + if errors.Is(err, not) { + t.Errorf("%d: errors.Is(%v) = true, want false", tc.status, not) + } + } + } +} + +func TestLinkURI(t *testing.T) { + f := newFakeAPI(t) + f.mux.HandleFunc("GET /v1/qrcodelink/raw", func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.Query().Get("device_name"); got != "imdbotg" { + writeJSON(w, 400, map[string]string{"error": "device_name=" + got}) + return + } + writeJSON(w, 200, map[string]string{"device_link_uri": "sgnl://linkdevice?uuid=x"}) + }) + uri, err := mustNew(t, f.URL).LinkURI(context.Background(), "imdbotg") + if err != nil || uri != "sgnl://linkdevice?uuid=x" { + t.Fatalf("got %q, %v", uri, err) + } +} + +func TestEndpointJoin(t *testing.T) { + for _, base := range []string{"http://h/signal/", "http://h/signal"} { + got := mustNew(t, base).endpoint("/v1/accounts") + if got != "http://h/signal/v1/accounts" { + t.Errorf("base %q: got %q", base, got) + } + } +} diff --git a/doc.go b/doc.go new file mode 100644 index 0000000..2ca5c02 --- /dev/null +++ b/doc.go @@ -0,0 +1,25 @@ +// Package signalbot sends and receives Signal text messages through a +// signal-cli-rest-api service (https://github.com/bbernhard/signal-cli-rest-api). +// +// signalbot is an unofficial client, not affiliated with Signal. The Signal +// protocol itself is handled by signal-cli inside the service container; +// this package is pure Go and only speaks HTTP and websocket to it. +// +// Basic usage: +// +// client, err := signalbot.New("http://signal-api:8080") +// if err != nil { ... } +// +// // Send to a group ("group."), a phone number or an ACI UUID. +// err = client.Send(ctx, groupID, "Hello from signalbot") +// +// // Receive incoming text messages until ctx is cancelled. +// err = client.Listen(ctx, func(ctx context.Context, m signalbot.Message) { +// _ = m.Reply(ctx, "got it: "+m.Text) +// }) +// +// The service must run with MODE=json-rpc (or json-rpc-native) and +// JSON_RPC_RECEIVE_MODE=manual, and Listen should run permanently, even if +// the application only publishes: receiving also processes the retry +// receipts that keep group members able to decrypt the bot's messages. +package signalbot diff --git a/errors.go b/errors.go new file mode 100644 index 0000000..3435aa6 --- /dev/null +++ b/errors.go @@ -0,0 +1,54 @@ +package signalbot + +import ( + "errors" + "fmt" + "net/http" +) + +var ( + // ErrNotLinked means the service has no linked account (or not the one + // requested with WithNumber). Run `signalbot link`. + ErrNotLinked = errors.New("signalbot: no linked account") + + // ErrMultipleAccounts means the service has several linked accounts and + // no WithNumber option was given to choose one. + ErrMultipleAccounts = errors.New("signalbot: several linked accounts, use WithNumber") + + // ErrUnavailable means the service could not be reached or answered with + // a server error (5xx). + ErrUnavailable = errors.New("signalbot: service unavailable") + + // ErrRateLimited means Signal rate-limited the account (HTTP 429). + ErrRateLimited = errors.New("signalbot: rate limited") + + // ErrEmptyText means Send was called with an empty or blank text. + ErrEmptyText = errors.New("signalbot: empty text") +) + +// APIError is an error response from signal-cli-rest-api. +// +// errors.Is reports ErrUnavailable for 5xx responses and ErrRateLimited +// for 429 responses. +type APIError struct { + StatusCode int + Message string +} + +func (e *APIError) Error() string { + return fmt.Sprintf("signalbot: API error %d: %s", e.StatusCode, e.Message) +} + +func (e *APIError) Is(target error) bool { + switch target { + case ErrUnavailable: + return e.StatusCode >= 500 + case ErrRateLimited: + return e.StatusCode == http.StatusTooManyRequests + } + return false +} + +func unavailable(err error) error { + return fmt.Errorf("%w: %w", ErrUnavailable, err) +} diff --git a/fake_test.go b/fake_test.go new file mode 100644 index 0000000..d7b129d --- /dev/null +++ b/fake_test.go @@ -0,0 +1,66 @@ +package signalbot + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "testing" +) + +// fakeAPI is a minimal stand-in for signal-cli-rest-api. Routes are +// registered on mux; hits counts requests per "METHOD path". +type fakeAPI struct { + *httptest.Server + mux *http.ServeMux + mu sync.Mutex + hits map[string]int +} + +func newFakeAPI(t *testing.T) *fakeAPI { + t.Helper() + f := &fakeAPI{mux: http.NewServeMux(), hits: map[string]int{}} + f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + f.hits[r.Method+" "+r.URL.Path]++ + f.mu.Unlock() + f.mux.ServeHTTP(w, r) + })) + t.Cleanup(f.Close) + return f +} + +func (f *fakeAPI) hitCount(key string) int { + f.mu.Lock() + defer f.mu.Unlock() + return f.hits[key] +} + +// accounts serves GET /v1/accounts with the given raw JSON body. +func (f *fakeAPI) accounts(body string) { + f.mux.HandleFunc("GET /v1/accounts", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + }) +} + +func (f *fakeAPI) health() { + f.mux.HandleFunc("GET /v1/health", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNoContent) + }) +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func mustNew(t *testing.T, url string, opts ...Option) *Client { + t.Helper() + c, err := New(url, opts...) + if err != nil { + t.Fatalf("New: %v", err) + } + return c +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5aac5be --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.siteop.biz/vincentb99/signalbot + +go 1.23