Files
2026-11-20 15:36:55 +01:00

266 lines
22 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# signalbot Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** A pure-Go library + CLI that sends and receives Signal text messages through a `bbernhard/signal-cli-rest-api` container.
**Architecture:** `signalbot.Client` wraps the REST API (HTTP for accounts, link, groups, send; websocket `/v1/receive/{account}` for incoming messages). The protocol is handled by signal-cli inside the container (`MODE=json-rpc-native`, `JSON_RPC_RECEIVE_MODE=manual`). A `cmd/signalbot` CLI (link, groups, send, listen) is built on the same client.
**Tech Stack:** Go (go directive 1.23), stdlib (`net/http`, `encoding/json`, `log/slog`, `flag`, `text/tabwriter`), `github.com/coder/websocket` v1.8.15 (lib), `github.com/mdp/qrterminal/v3` v3.2.1 (CLI only).
**Spec:** `docs/superpowers/specs/2026-11-20-signalbot-design.md`
## Global Constraints
- Module path: `git.siteop.biz/vincentb99/signalbot`; package `signalbot`; CLI at `cmd/signalbot`.
- `go.mod` declares `go 1.23`; no CGO; `go vet ./...` must pass (its `stdversion` check catches stdlib APIs newer than 1.23 — the local toolchain is 1.27).
- Library dependencies: stdlib + `github.com/coder/websocket` only. `qrterminal` is imported only by `cmd/signalbot`.
- Licence MIT (`LICENSE`, copyright holder "vincentb99", year 2026).
- Text only: send with `"text_mode": "normal"`; never interpret markdown.
- Code, identifiers, comments, CLI output and README in English (public Go library convention — planner's call).
- No automatic retry on `Send`. `Listen` reconnects automatically.
- Every network method takes `ctx context.Context` first. `Client` is safe for concurrent use.
- Recipients/groups are passed through as given: `group.<base64>`, E.164 number, or ACI UUID.
## Upstream facts (verified in signal-cli-rest-api source, 2026-11-20)
- `GET /v1/accounts` → `[{"number":"+33…","aci":"uuid"|null}]`; older versions return `["+33…"]`. Accept both. `number` may be `""` (then identify the account by `aci`).
- `GET /v1/qrcodelink/raw?device_name=X` → `{"device_link_uri":"sgnl://linkdevice?…"}`; 400 if `device_name` missing.
- `GET /v1/groups/{account}` → `[{"id":"group.…","internal_id":"…","name":"…","admins":["+33…"|"uuid"],"permissions":{"send_messages":"only-admins"|"every-member",…},…}]`.
- `POST /v2/send` body `{"number":acct,"recipients":[to],"message":text,"text_mode":"normal"}` → 201 on success; 400 `{"error":"…"}`; 429 `{"error":"…","challenge_tokens":[…],"account":"…"}`.
- `GET /v1/health` → 204 when up.
- `{account}` path segment accepts a number or an ACI.
- Websocket `/v1/receive/{account}` (json-rpc mode) pushes one text frame per signal-cli `receive` notification:
`{"envelope":{"source":"+33…","sourceNumber":"+33…","sourceUuid":"…","sourceName":"…","sourceDevice":1,"timestamp":1763640000000,"dataMessage":{"timestamp":…,"message":"hello","groupInfo":{"groupId":"<base64>","type":"DELIVER"}}},"account":"+33…"}`.
Receipts/typing/sync come as envelopes with `receiptMessage`/`typingMessage`/`syncMessage` and no `dataMessage`.
- Group id conversion: REST `id` = `"group." + base64.StdEncoding(internal_id)`, and `groupInfo.groupId` in envelopes is the internal id. So reply id = `"group." + base64.StdEncoding.EncodeToString([]byte(groupInfo.groupId))`.
- Latest stable image tag: `bbernhard/signal-cli-rest-api:0.101`.
## Review Focus
1. **Slow handler** (handler takes longer than the server's ws ping interval): the connection must stay alive — reads (and pong replies) continue in a reader goroutine while handlers run sequentially. → test in Task 5.
2. **Echo loop**: a message whose sender is the bot's own account (number or ACI) must not reach the handler, so `Reply` can never answer itself. → test in Task 4.
3. **Base URL variants**: trailing slash and path prefix (`http://proxy/signal/`) must build correct HTTP URLs, and `http→ws` / `https→wss` for the websocket. → test in Task 1 and Task 5.
4. **Handler panic**: must not crash the host app; recovered, logged at Error via the client logger, next message still delivered. → test in Task 5.
5. **Unicode and newlines** in text (emoji, accents, `\n`) must round-trip byte-exact through `Send` and through received messages. → tests in Task 2 and Task 4.
---
### Task 1: Module scaffold, client core, errors, accounts, link URI
**Files:**
- Create: `go.mod`, `LICENSE`, `doc.go`, `client.go`, `errors.go`
- Test: `client_test.go`, `fake_test.go` (shared fake server helpers for all lib tests)
**Interfaces:**
- Produces:
- `func New(baseURL string, opts ...Option) (*Client, error)` — no network; error only if `baseURL` doesn't parse or isn't http/https.
- `type Option func(*Client)`; `WithNumber(number string) Option`; `WithHTTPClient(*http.Client) Option`; `WithLogger(*slog.Logger) Option` (default `slog.Default()`).
- `type Account struct { Number, ACI string }`
- `func (c *Client) Accounts(ctx) ([]Account, error)`
- `func (c *Client) LinkURI(ctx, deviceName string) (string, error)`
- `func (c *Client) Ping(ctx) error` — health OK **and** account resolved.
- unexported: `func (c *Client) account(ctx) (Account, error)` (resolves once, caches under mutex; failures not cached); `func (Account) id() string` (Number if non-empty else ACI); `func (c *Client) do(ctx, method, path string, in, out any) error` (JSON in/out, maps errors); `func (c *Client) endpoint(path string) string`.
- Errors: `ErrNotLinked`, `ErrMultipleAccounts`, `ErrUnavailable`, `ErrRateLimited`, `ErrEmptyText`; `type APIError struct { StatusCode int; Message string }` with `Error()` and `Is(target error) bool` (true for `ErrUnavailable` when `StatusCode >= 500`, `ErrRateLimited` when 429). Transport failures wrap `ErrUnavailable` and the cause (`fmt.Errorf("signalbot: %w: %w", ErrUnavailable, err)`).
- [ ] **Step 1: Init module and licence** — `go mod init git.siteop.biz/vincentb99/signalbot`, set `go 1.23`, MIT `LICENSE`, `doc.go` with a package comment summarising usage (New → Send / Listen) and that the service must run `JSON_RPC_RECEIVE_MODE=manual` with `Listen` running permanently.
- [ ] **Step 2: Write failing tests** in `client_test.go` (fake server via `httptest.NewServer` + helpers in `fake_test.go`):
- `TestNewDoesNoNetwork`: `New("http://127.0.0.1:1")` returns nil error.
- `TestNewRejectsBadURL`: `New("ftp://x")` and `New("::")` error.
- `TestAccountsObjectAndLegacyFormats`: `[{"number":"+331","aci":"a-1"},{"number":"","aci":"a-2"}]` → `[{+331 a-1} {"" a-2}]`; `["+331"]` → `[{+331 ""}]`.
- `TestAccountAutoDetect`: one account → used; zero → `errors.Is(err, ErrNotLinked)`; two → `ErrMultipleAccounts`.
- `TestAccountWithNumber`: `WithNumber("+332")` with accounts `+331,+332` → `{+332 …}` (ACI filled from list); with number absent from list → `ErrNotLinked`.
- `TestAccountCachedAfterSuccess`: two `Ping` calls → `/v1/accounts` hit once.
- `TestPing`: health 204 + one account → nil; health conn refused (closed server) → `errors.Is(err, ErrUnavailable)`.
- `TestAPIErrorMapping`: handler returning 503 `{"error":"down"}` → `errors.Is(err, ErrUnavailable)` and `errors.As` gives `StatusCode 503, Message "down"`; 429 → `ErrRateLimited`; 400 → neither, `Message` set; non-JSON body → `Message` = trimmed body.
- `TestLinkURI`: asserts query `device_name=imdbotg`, returns `sgnl://linkdevice?uuid=x`.
- `TestEndpointJoin` (Review Focus 3): base `http://h/signal/` and `http://h/signal` + `/v1/accounts` → `http://h/signal/v1/accounts`.
- [ ] **Step 3: Run** `go test ./...` → FAIL (undefined symbols).
- [ ] **Step 4: Implement** `client.go` and `errors.go` per Interfaces. Accounts decoding: unmarshal into `[]json.RawMessage`, each element string or object.
- [ ] **Step 5: Run** `go test ./... && go vet ./...` → PASS.
- [ ] **Step 6: Commit** `feat: client core, accounts, link URI, errors`.
### Task 2: Send
**Files:**
- Create: `send.go`
- Test: `send_test.go`
**Interfaces:**
- Consumes: `account`, `do`, errors (Task 1).
- Produces: `func (c *Client) Send(ctx context.Context, to, text string) error`.
- [ ] **Step 1: Write failing tests:**
- `TestSendPayload`: fake `/v2/send` captures body; `Send(ctx, "group.QUJD", "hi")` with account `+331` → body exactly `{"number":"+331","recipients":["group.QUJD"],"message":"hi","text_mode":"normal"}` (compare decoded maps), method POST, `Content-Type: application/json`.
- `TestSendUsesACIWhenNoNumber`: account `{"" a-2}` → `"number":"a-2"`.
- `TestSendEmptyText`: `Send(ctx, "+332", "")` → `errors.Is(err, ErrEmptyText)`, no HTTP call. Whitespace-only `" \n"` also `ErrEmptyText`.
- `TestSendUnicodeRoundTrip` (Review Focus 5): text `"Nouveauté 🎬\nligne 2"` arrives byte-exact.
- `TestSendErrors`: 400 `{"error":"Invalid group id"}` → `*APIError{400,"Invalid group id"}`; 429 → `ErrRateLimited`.
- [ ] **Step 2: Run** `go test -run TestSend ./...` → FAIL.
- [ ] **Step 3: Implement** `Send` in `send.go` (201 and 200 both success; response body ignored).
- [ ] **Step 4: Run** `go test ./... && go vet ./...` → PASS.
- [ ] **Step 5: Commit** `feat: send text messages`.
### Task 3: Groups
**Files:**
- Create: `groups.go`
- Test: `groups_test.go`
**Interfaces:**
- Consumes: `account`, `do` (Task 1).
- Produces: `type Group struct { ID, Name string; IsAdmin, AdminsOnly bool }`; `func (c *Client) Groups(ctx context.Context) ([]Group, error)`.
- [ ] **Step 1: Write failing tests:**
- `TestGroupsMapping`: fake `GET /v1/groups/+331` with two groups → `ID` from `id`, `Name` from `name`, `AdminsOnly` true iff `permissions.send_messages == "only-admins"`.
- `TestGroupsIsAdminByNumberOrACI`: account `{+331 a-1}`; group A admins `["+331"]` → true; group B admins `["a-1"]` → true; group C admins `["+339"]` → false.
- `TestGroupsEmpty`: `[]` → empty slice, nil error.
- [ ] **Step 2: Run** `go test -run TestGroups ./...` → FAIL.
- [ ] **Step 3: Implement** `Groups` (path segment `url.PathEscape(acct.id())`).
- [ ] **Step 4: Run** `go test ./... && go vet ./...` → PASS.
- [ ] **Step 5: Commit** `feat: list groups`.
### Task 4: Incoming message parsing and Reply
**Files:**
- Create: `message.go`
- Test: `message_test.go`
**Interfaces:**
- Consumes: `Send` (Task 2), `Account` (Task 1).
- Produces:
- `type Message struct { From string; GroupID string; Text string; Timestamp time.Time; client *Client }` — `From` = `sourceNumber` if non-empty else `sourceUuid`; `GroupID` = converted id (see Upstream facts) or `""`; `Timestamp` = `time.UnixMilli(envelope.timestamp)`.
- `func (m Message) Reply(ctx context.Context, text string) error` — `Send` to `GroupID` if set, else `From`.
- unexported `func parseEnvelope(data []byte, self Account) (Message, bool)` — returns a Message with `client` nil (Listen sets it; tests build `Message{client: c, …}` directly). False for: invalid JSON, no `dataMessage`, empty `message`, sender equal to `self.Number` or `self.ACI` (non-empty values only).
- [ ] **Step 1: Write failing tests** (fixtures as raw JSON strings in the test file, shaped exactly like Upstream facts):
- `TestParseDirectMessage`: no `groupInfo` → `From "+33600000001"`, `GroupID ""`, `Text "hello"`, `Timestamp == time.UnixMilli(1763640000000)`.
- `TestParseGroupMessage`: `groupInfo.groupId "Z3JvdXAtaW50ZXJuYWw="` → `GroupID == "group."+base64.StdEncoding.EncodeToString([]byte("Z3JvdXAtaW50ZXJuYWw="))`.
- `TestParseFromUUIDWhenNoNumber`: `sourceNumber ""`, `sourceUuid "u-1"` → `From "u-1"`.
- `TestParseIgnored`: receipt envelope, typing envelope, syncMessage envelope, dataMessage with `message ""`/absent (e.g. reaction only), invalid JSON → all `ok == false`.
- `TestParseIgnoresSelf` (Review Focus 2): sender `sourceNumber == self.Number` → false; `sourceUuid == self.ACI` with empty number → false.
- `TestParseUnicode` (Review Focus 5): `"message":"é 🎬\nx"` → exact.
- `TestReplyTargets`: fake `/v2/send`; group message reply → recipient `GroupID`; direct reply → recipient `From`.
- [ ] **Step 2: Run** `go test -run 'TestParse|TestReply' ./...` → FAIL.
- [ ] **Step 3: Implement** `message.go`.
- [ ] **Step 4: Run** `go test ./... && go vet ./...` → PASS.
- [ ] **Step 5: Commit** `feat: parse incoming messages and reply`.
### Task 5: Listen (websocket, reconnect, sequential handlers)
**Files:**
- Create: `listen.go`
- Modify: `go.mod` (add `github.com/coder/websocket v1.8.15`)
- Test: `listen_test.go`
**Interfaces:**
- Consumes: `account`, `endpoint`, `parseEnvelope`, logger (Tasks 1, 4).
- Produces:
- `type Handler func(ctx context.Context, m Message)`
- `func (c *Client) Listen(ctx context.Context, h Handler) error` — blocks; returns `ctx.Err()` when ctx is done; returns a non-nil error immediately for `ErrNotLinked`/`ErrMultipleAccounts` and for a websocket handshake answered with HTTP 4xx (as `*APIError`); retries on `ErrUnavailable`, 5xx handshake, dial errors and connection drops.
- unexported fields `minBackoff` (default 1s) and `maxBackoff` (default 30s), set small in tests. Backoff doubles per consecutive failure, capped, reset after a successful handshake. Each retry logged at Warn with the error.
Design decided here: one reader goroutine per connection reads frames (`conn.Read`) into a buffered channel (cap 64); the Listen loop consumes it and calls `h` sequentially. Reading continuously keeps pongs flowing while a handler is slow. Each handler call is wrapped in `recover()`; a panic is logged at Error and the loop continues. Unlimited read size is not needed: `conn.SetReadLimit(1 << 20)`.
- [ ] **Step 1: Write failing tests** (fake ws server: `httptest.NewServer` + `websocket.Accept` on `/v1/receive/{acct}`, plus `/v1/accounts`):
- `TestListenDeliversInOrder`: server sends 3 text envelopes + 1 receipt → handler sees 3 messages in order, receipt skipped.
- `TestListenReconnects`: server closes after first message; second connection sends another → both delivered; at least 2 handshakes observed.
- `TestListenStopsOnCancel`: cancel ctx → `Listen` returns `context.Canceled` within 1s.
- `TestListenNotLinked`: accounts `[]` → returns `ErrNotLinked` without dialing.
- `TestListenHandshake4xx`: receive endpoint returns 400 → returns `*APIError` with 400, no retry.
- `TestListenRetriesWhenUnavailable`: first 2 handshakes 503, then OK → message delivered.
- `TestListenSlowHandler` (Review Focus 1): handler blocks until signalled; server calls `conn.Ping(ctx)` with 1s timeout while handler is blocked → ping succeeds; then unblock.
- `TestListenHandlerPanic` (Review Focus 4): first handler call panics, second message still delivered; logger (`slog.New` over a buffer) contains `panic`.
- `TestListenWebsocketURL` (Review Focus 3): base `http://h/signal/` → dial URL path `/signal/v1/receive/%2B331`; `https://` base → `wss://` scheme (unit-test the URL builder `func (c *Client) wsURL(acct Account) string`).
- [ ] **Step 2: Run** `go test -run TestListen ./...` → FAIL.
- [ ] **Step 3: Implement** `listen.go` (`go get github.com/coder/websocket@v1.8.15`).
- [ ] **Step 4: Run** `go test -race ./... && go vet ./...` → PASS.
- [ ] **Step 5: Commit** `feat: listen for incoming messages with reconnect`.
### Task 6: CLI
**Files:**
- Create: `cmd/signalbot/main.go`
- Modify: `go.mod` (add `github.com/mdp/qrterminal/v3 v3.2.1`)
- Test: `cmd/signalbot/main_test.go`
**Interfaces:**
- Consumes: `New`, `WithNumber`, `Accounts`, `LinkURI`, `Groups`, `Send`, `Listen`.
- Produces: `func run(ctx context.Context, args []string, stdout, stderr io.Writer) int` (main calls it with `signal.NotifyContext(..., os.Interrupt)` and `os.Exit`).
Subcommands (each its own `flag.FlagSet`; common `-url`, default `$SIGNALBOT_URL` else `http://localhost:8080`; `-number` on groups/send/listen):
- `link [-device-name signalbot] [-timeout 5m]`: snapshot `Accounts`, fetch `LinkURI`, print QR (`qrterminal.GenerateHalfBlock(uri, qrterminal.L, stdout)`), the raw URI, and the instruction line `On the bot's phone: Signal > Settings > Linked devices > +, then scan.`; poll `Accounts` every 2s until an account not in the snapshot appears → print `Linked: <number or aci>`, exit 0; timeout → exit 1.
- `groups`: tabwriter columns `NAME ID BOT ADMIN ADMINS ONLY` (yes/no); after the table, a `warning:` line per group where the bot is not admin or the group is not admins-only.
- `send -to <id|number|uuid> <text...>`: joins remaining args with spaces; exit 0 on success.
- `listen`: prints one line per message `[2006-01-02 15:04:05] <from> (<group id or "direct">): <text>` until interrupt; exit 0 on ctx cancel.
- Unknown/missing subcommand → usage on stderr, exit 2. Errors → `error: <err>` on stderr, exit 1.
- [ ] **Step 1: Write failing tests** against an `httptest` fake (package `main` cannot use the lib's `_test.go` helpers — write a small fake in `main_test.go`):
- `TestRunUsage`: no args → 2, stderr contains `usage`.
- `TestRunSend`: `send -url X -to group.QUJD hello world` → fake receives message `"hello world"`, exit 0.
- `TestRunGroups`: two groups (one admin+admins-only, one not admin) → stdout contains both names and exactly one `warning:` line naming the second group.
- `TestRunLink`: accounts `[]` first, then `[{"number":"+331"}]` on 2nd poll (poll interval overridable via an unexported package var) → stdout contains `sgnl://` and `Linked: +331`, exit 0.
- `TestRunListen`: ws fake sends one direct message then ctx is cancelled → stdout line contains `+33600000001 (direct): hello`, exit 0.
- [ ] **Step 2: Run** `go test ./cmd/...` → FAIL.
- [ ] **Step 3: Implement** `cmd/signalbot/main.go`.
- [ ] **Step 4: Run** `go test ./... && go vet ./... && CGO_ENABLED=0 go build ./...` → PASS.
- [ ] **Step 5: Commit** `feat: signalbot CLI (link, groups, send, listen)`.
### Task 7: README, compose example, integration test
**Files:**
- Create: `README.md`, `examples/docker-compose.yml`, `examples/main.go` (minimal app: Listen + echo reply + Send on start, config from `SIGNAL_API_URL`, `SIGNAL_GROUP_ID`), `integration_test.go`
**Interfaces:**
- Consumes: public API from Tasks 1–6.
- [ ] **Step 1: `examples/docker-compose.yml`** — service `signal-api`: image `bbernhard/signal-cli-rest-api:0.101`, env `MODE=json-rpc-native`, `JSON_RPC_RECEIVE_MODE=manual`, volume `signal-data:/home/.local/share/signal-cli`, `restart: unless-stopped`, port `127.0.0.1:8080:8080` commented with "only while linking"; service `app` with `SIGNAL_API_URL=http://signal-api:8080` and `SIGNAL_GROUP_ID`.
- [ ] **Step 2: `README.md`** sections: what it is (unofficial client, not affiliated with Signal); how it works (diagram from spec); install (`go get`, `go install …/cmd/signalbot@latest`); quick start code (Send + Listen); setup procedure (the 5 steps from the spec, including creating the group and enabling "only admins can send"); **important** notes: keep `Listen` running even if you only publish (sender-key retries), `JSON_RPC_RECEIVE_MODE=manual` (otherwise messages are lost while the app is down), never expose the API publicly (no auth), losing the volume means re-linking, `MODE=json-rpc` fallback if native mode is unstable, browser alternative `http://localhost:8080/v1/qrcodelink?device_name=x`; licences (signalbot MIT; the container ships GPL/AGPL components, used unmodified).
- [ ] **Step 3: `integration_test.go`** — skipped unless `SIGNALBOT_IT_URL` and `SIGNALBOT_IT_GROUP` are set: `TestIntegrationPingGroupsSend` (Ping ok; `Groups` contains `SIGNALBOT_IT_GROUP`; `Send` a timestamped text succeeds).
- [ ] **Step 4: Run** `go test ./... && go vet ./... && go build ./examples/` → PASS (integration test SKIP).
- [ ] **Step 5: Commit** `docs: README, compose example, integration test`.
### Task 8: Live verification with the real number (with the user), then release
Needs the user at their phone. No code is assumed correct for the items below until observed.
- [ ] **Step 1:** `docker compose -f examples/docker-compose.yml up -d signal-api` (port exposed), `go run ./cmd/signalbot link -device-name signalbot-dev` → user scans → `Linked:` printed (verifies link wait in `json-rpc-native`).
- [ ] **Step 2:** User creates a test group, admins-only, bot admin. `signalbot groups` shows it with `yes yes`, no warning.
- [ ] **Step 3:** Run the integration test with `SIGNALBOT_IT_URL=http://localhost:8080 SIGNALBOT_IT_GROUP=<id>` → PASS.
- [ ] **Step 4:** `signalbot listen`; user sends a direct message and a group message → both printed with correct `from`/group; a reaction and read receipts print nothing. Save one real envelope of each kind (anonymised) as fixtures in `message_test.go` if they differ from the plan's shapes, and fix `parseEnvelope` accordingly.
- [ ] **Step 5:** Stop `listen`, user sends 2 messages, restart `listen` → both delivered (verifies `manual` mode).
- [ ] **Step 6:** Send a 3 000-character text → observe how it arrives on the phone; document the result in README.
- [ ] **Step 7:** Trigger errors: send to `group.AAAA` (unknown) and to an invalid number → record status codes/messages; if a distinct sentinel is clearly warranted, add it with a test; update README error section.
- [ ] **Step 8:** Check Signal's support docs for how long a linked device / the primary account survive inactivity; document the result (and "keep the bot's phone opening Signal regularly" if applicable) in README.
- [ ] **Step 9:** Commit fixes `fix: align with observed signal-cli-rest-api behaviour`.
- [ ] **Step 10:** **Ask the user for confirmation**, then `git push -u origin main`, `git tag v0.1.0 && git push origin v0.1.0`; from a temp dir, `go mod init x && go get git.siteop.biz/vincentb99/signalbot@v0.1.0` succeeds (repo must be public).