Compare commits

..

2 Commits

Author SHA1 Message Date
prosolis
8f38d3d9f4 Switch config format from YAML to TOML
Replaces gopkg.in/yaml.v3 with github.com/BurntSushi/toml. Updates
struct tags, default config path, Dockerfile CMD, README, and ships
config.example.toml in place of the YAML example. ${ENV_VAR}
expansion still runs on the raw file before parsing, so the behavior
is unchanged.
2026-05-24 21:05:41 -07:00
prosolis
035089c159 Fix correctness bugs found by code review
- matrix: drop cryptohelper LoginAs so device.json creds aren't
  invalidated on every restart by Init's re-login
- matrix: thread ctx through PostThreadedReply; bot dispatcher derives
  per-command ctx from app lifecycle so SIGTERM cancels in-flight work
- matrix: isTokenValid verifies /whoami user_id matches configured one
- matrix: loadDevice distinguishes missing file from corrupt parse;
  refuse to silently overwrite a corrupt device.json
- matrix: Start checks Syncer type assertion and returns error
- arr: parseLookup skips empty-title items and extracts existing id
- bot: skip Add when Result.Exists; reply "already in library"
2026-05-24 20:50:51 -07:00
12 changed files with 209 additions and 123 deletions

View File

@@ -18,4 +18,4 @@ COPY --from=build /out/bellhop /usr/local/bin/bellhop
USER bellhop
VOLUME ["/app/data"]
ENTRYPOINT ["/usr/local/bin/bellhop"]
CMD ["-config", "/app/config.yaml"]
CMD ["-config", "/app/config.toml"]

View File

@@ -19,7 +19,7 @@ Any member of an allowlisted room may issue commands. The bot auto-joins on invi
## Configuration
Copy `config.example.yaml` to `config.yaml` and edit. The loader expands `${ENV_VAR}` references at load time, so secrets can come from the environment.
Copy `config.example.toml` to `config.toml` and edit. The loader expands `${ENV_VAR}` references at load time, so secrets can come from the environment.
Required:
@@ -43,7 +43,7 @@ curl -H "X-Api-Key: YOUR_KEY" https://radarr.example.com/api/v3/qualityprofile
```bash
go build -tags goolm -o bellhop ./
./bellhop -config config.yaml
./bellhop -config config.toml
```
The `goolm` tag uses the pure-Go olm implementation so libolm isn't needed.
@@ -54,7 +54,7 @@ The `goolm` tag uses the pure-Go olm implementation so libolm isn't needed.
docker build -t bellhop .
docker run -d \
--name bellhop \
-v "$PWD/config.yaml:/app/config.yaml:ro" \
-v "$PWD/config.toml:/app/config.toml:ro" \
-v bellhop-data:/app/data \
bellhop
```
@@ -70,7 +70,7 @@ The bot bootstraps cross-signing on first run and persists Olm/Megolm sessions i
```
main.go
internal/
config/ — YAML loader with ${ENV_VAR} expansion
config/ — TOML loader with ${ENV_VAR} expansion
matrix/ — mautrix client: login, device persistence, E2EE, sync loop
arr/ — Radarr/Sonarr/Lidarr HTTP clients
bot/ — command parser + dispatch + threaded replies

43
config.example.toml Normal file
View File

@@ -0,0 +1,43 @@
# Bellhop config. Values like ${ENV_VAR} are expanded from the environment
# at load time so secrets can stay out of this file.
[matrix]
homeserver = "https://matrix.example.com"
user_id = "@bellhop:example.com"
password = "${BELLHOP_MATRIX_PASSWORD}"
# Optional. Defaults shown.
display_name = "Bellhop"
data_dir = "./data" # device.json + crypto.db live here
pickle_key = "${BELLHOP_PICKLE_KEY}" # encrypts the crypto store; pick something stable
command_prefix = "!"
# Rooms the bot will respond to commands in. Messages anywhere else are
# ignored. The bot auto-joins on invite, but joining alone does not grant
# command access — the room ID must appear here.
allowed_rooms = [
"!room-id-one:example.com",
"!room-id-two:example.com",
]
# Configure any subset. Omit a section to disable that command:
# leaving out [services.radarr] makes `!movie` reply "Radarr is not configured".
[services.radarr]
url = "https://radarr.example.com"
api_key = "${RADARR_API_KEY}"
quality_profile_id = 1
root_folder = "/movies"
[services.sonarr]
url = "https://sonarr.example.com"
api_key = "${SONARR_API_KEY}"
quality_profile_id = 1
root_folder = "/tv"
[services.lidarr]
url = "https://lidarr.example.com"
api_key = "${LIDARR_API_KEY}"
quality_profile_id = 1
metadata_profile_id = 1 # required for Lidarr only
root_folder = "/music"

View File

@@ -1,42 +0,0 @@
# Bellhop config. Values like ${ENV_VAR} are expanded from the environment
# at load time so secrets can stay out of this file.
matrix:
homeserver: https://matrix.example.com
user_id: "@bellhop:example.com"
password: ${BELLHOP_MATRIX_PASSWORD}
# Optional. Defaults shown.
display_name: Bellhop
data_dir: ./data # device.json + crypto.db live here
pickle_key: ${BELLHOP_PICKLE_KEY} # encrypts the crypto store; pick something stable
command_prefix: "!"
# Rooms the bot will respond to commands in. Messages anywhere else are
# ignored. The bot auto-joins on invite, but joining alone does not grant
# command access — the room ID must appear here.
allowed_rooms:
- "!room-id-one:example.com"
- "!room-id-two:example.com"
# Configure any subset. Omit a block to disable that command:
# leaving out `radarr` makes `!movie` reply "Radarr is not configured".
services:
radarr:
url: https://radarr.example.com
api_key: ${RADARR_API_KEY}
quality_profile_id: 1
root_folder: /movies
sonarr:
url: https://sonarr.example.com
api_key: ${SONARR_API_KEY}
quality_profile_id: 1
root_folder: /tv
lidarr:
url: https://lidarr.example.com
api_key: ${LIDARR_API_KEY}
quality_profile_id: 1
metadata_profile_id: 1 # required for Lidarr only
root_folder: /music

2
go.mod
View File

@@ -3,7 +3,7 @@ module bellhop
go 1.25.0
require (
gopkg.in/yaml.v3 v3.0.1
github.com/BurntSushi/toml v1.6.0
maunium.net/go/mautrix v0.28.0
)

4
go.sum
View File

@@ -1,5 +1,7 @@
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -41,8 +43,6 @@ golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
maunium.net/go/mautrix v0.28.0 h1:vBakLzf8MAdfED3NzAKiMeKQbc3AQ4EAS03NC+TVMXQ=

View File

@@ -19,11 +19,15 @@ import (
// Result is a single candidate returned by an *arr lookup. Title and Year
// are extracted for display; raw is the untouched JSON object used to build
// the Add payload.
// the Add payload. Exists is true when the *arr server already has this item
// in its library (lookup responses set "id" to a non-zero value in that case),
// so the bot can skip the Add and report 'already in library' instead of
// blindly re-POSTing.
type Result struct {
Title string
Year int
raw json.RawMessage
Title string
Year int
Exists bool
raw json.RawMessage
}
// Raw exposes the underlying lookup JSON; useful for tests and debugging.
@@ -105,10 +109,29 @@ func parseLookup(body []byte, titleField string) ([]Result, error) {
continue
}
var title string
_ = json.Unmarshal(meta[titleField], &title)
if raw, ok := meta[titleField]; ok && len(raw) > 0 {
_ = json.Unmarshal(raw, &title)
}
if title == "" {
// Skip items we can't display. The Add path would still POST the
// raw JSON, but the user reply would read "Added to Radarr:" with
// no title — worse than dropping the candidate.
continue
}
var year int
_ = json.Unmarshal(meta["year"], &year)
out = append(out, Result{Title: title, Year: year, raw: item})
if raw, ok := meta["year"]; ok && len(raw) > 0 {
_ = json.Unmarshal(raw, &year)
}
var existingID int
if raw, ok := meta["id"]; ok && len(raw) > 0 {
_ = json.Unmarshal(raw, &existingID)
}
out = append(out, Result{
Title: title,
Year: year,
Exists: existingID > 0,
raw: item,
})
}
return out, nil
}

View File

@@ -19,9 +19,10 @@ import (
"maunium.net/go/mautrix/id"
)
// Replier sends a threaded reply into roomID under rootEventID.
// Replier sends a threaded reply into roomID under rootEventID. The ctx
// governs cancellation/deadline so shutdown propagates through replies.
type Replier interface {
PostThreadedReply(roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error
PostThreadedReply(ctx context.Context, roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error
}
// Services holds the configured *arr clients. Any field may be nil; commands
@@ -34,6 +35,7 @@ type Services struct {
// Dispatcher routes parsed commands to services and posts replies.
type Dispatcher struct {
baseCtx context.Context
prefix string
services Services
replier Replier
@@ -41,12 +43,17 @@ type Dispatcher struct {
}
// New builds a Dispatcher. prefix is the leading character(s) on a command
// (e.g. "!"); a zero value defaults to "!".
func New(prefix string, services Services, replier Replier) *Dispatcher {
// (e.g. "!"); a zero value defaults to "!". baseCtx becomes the parent of
// every per-command context so app shutdown cancels in-flight handlers.
func New(baseCtx context.Context, prefix string, services Services, replier Replier) *Dispatcher {
if prefix == "" {
prefix = "!"
}
if baseCtx == nil {
baseCtx = context.Background()
}
return &Dispatcher{
baseCtx: baseCtx,
prefix: prefix,
services: services,
replier: replier,
@@ -64,11 +71,11 @@ func (d *Dispatcher) Handle(roomID id.RoomID, eventID id.EventID, sender id.User
slog.Info("bot: command received", "room", roomID, "sender", sender, "cmd", cmd, "query", query)
ctx, cancel := context.WithTimeout(context.Background(), d.timeout)
ctx, cancel := context.WithTimeout(d.baseCtx, d.timeout)
defer cancel()
plain, htmlBody := d.dispatch(ctx, cmd, query)
if err := d.replier.PostThreadedReply(roomID, eventID, plain, htmlBody); err != nil {
if err := d.replier.PostThreadedReply(ctx, roomID, eventID, plain, htmlBody); err != nil {
slog.Error("bot: reply failed", "room", roomID, "err", err)
}
}
@@ -130,6 +137,10 @@ func (d *Dispatcher) run(ctx context.Context, cmd, service string, client arr.Cl
}
top := results[0]
if top.Exists {
msg := fmt.Sprintf("%s already has %s in the library.", service, formatTitle(top))
return msg, html.EscapeString(msg)
}
if err := client.Add(ctx, top); err != nil {
slog.Error("bot: add failed", "service", service, "title", top.Title, "err", err)
msg := fmt.Sprintf("%s: failed to add %s: %v", service, formatTitle(top), err)

View File

@@ -44,7 +44,7 @@ type stubReplier struct {
calls int
}
func (r *stubReplier) PostThreadedReply(_ id.RoomID, _ id.EventID, plain, htmlBody string) error {
func (r *stubReplier) PostThreadedReply(_ context.Context, _ id.RoomID, _ id.EventID, plain, htmlBody string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.calls++
@@ -53,6 +53,10 @@ func (r *stubReplier) PostThreadedReply(_ id.RoomID, _ id.EventID, plain, htmlBo
return nil
}
func newDispatcher(prefix string, services Services, replier Replier) *Dispatcher {
return New(context.Background(), prefix, services, replier)
}
const (
room = id.RoomID("!room:example.org")
event = id.EventID("$evt")
@@ -87,7 +91,7 @@ func TestDispatchMovieTopHit(t *testing.T) {
{Title: "Dune", Year: 1984},
}}
rep := &stubReplier{}
d := New("!", Services{Radarr: radarr}, rep)
d := newDispatcher("!", Services{Radarr: radarr}, rep)
d.Handle(room, event, sender, "!movie dune")
@@ -105,7 +109,7 @@ func TestDispatchMovieTopHit(t *testing.T) {
func TestDispatchNoResults(t *testing.T) {
sonarr := &stubClient{}
rep := &stubReplier{}
d := New("!", Services{Sonarr: sonarr}, rep)
d := newDispatcher("!", Services{Sonarr: sonarr}, rep)
d.Handle(room, event, sender, "!tv obscure show")
@@ -119,7 +123,7 @@ func TestDispatchNoResults(t *testing.T) {
func TestDispatchUnconfigured(t *testing.T) {
rep := &stubReplier{}
d := New("!", Services{}, rep)
d := newDispatcher("!", Services{}, rep)
d.Handle(room, event, sender, "!music radiohead")
@@ -131,7 +135,7 @@ func TestDispatchUnconfigured(t *testing.T) {
func TestDispatchEmptyQuery(t *testing.T) {
radarr := &stubClient{}
rep := &stubReplier{}
d := New("!", Services{Radarr: radarr}, rep)
d := newDispatcher("!", Services{Radarr: radarr}, rep)
d.Handle(room, event, sender, "!movie")
@@ -149,7 +153,7 @@ func TestDispatchAddError(t *testing.T) {
addErr: errors.New("boom"),
}
rep := &stubReplier{}
d := New("!", Services{Radarr: radarr}, rep)
d := newDispatcher("!", Services{Radarr: radarr}, rep)
d.Handle(room, event, sender, "!movie dune")
@@ -161,7 +165,7 @@ func TestDispatchAddError(t *testing.T) {
func TestDispatchSearchError(t *testing.T) {
radarr := &stubClient{srchErr: errors.New("network down")}
rep := &stubReplier{}
d := New("!", Services{Radarr: radarr}, rep)
d := newDispatcher("!", Services{Radarr: radarr}, rep)
d.Handle(room, event, sender, "!movie dune")
@@ -172,7 +176,7 @@ func TestDispatchSearchError(t *testing.T) {
func TestDispatchHelp(t *testing.T) {
rep := &stubReplier{}
d := New("!", Services{}, rep)
d := newDispatcher("!", Services{}, rep)
d.Handle(room, event, sender, "!help")
@@ -185,7 +189,7 @@ func TestDispatchHelp(t *testing.T) {
func TestDispatchUnknown(t *testing.T) {
rep := &stubReplier{}
d := New("!", Services{}, rep)
d := newDispatcher("!", Services{}, rep)
d.Handle(room, event, sender, "!frobnicate stuff")
@@ -196,7 +200,7 @@ func TestDispatchUnknown(t *testing.T) {
func TestNonCommandIgnored(t *testing.T) {
rep := &stubReplier{}
d := New("!", Services{}, rep)
d := newDispatcher("!", Services{}, rep)
d.Handle(room, event, sender, "just chatting")
@@ -205,10 +209,25 @@ func TestNonCommandIgnored(t *testing.T) {
}
}
func TestDispatchAlreadyInLibrary(t *testing.T) {
radarr := &stubClient{results: []arr.Result{{Title: "Dune", Year: 2021, Exists: true}}}
rep := &stubReplier{}
d := newDispatcher("!", Services{Radarr: radarr}, rep)
d.Handle(room, event, sender, "!movie dune")
if len(radarr.added) != 0 {
t.Fatalf("should not re-add existing item, got %d adds", len(radarr.added))
}
if !strings.Contains(rep.plain, "already has") || !strings.Contains(rep.plain, "Dune (2021)") {
t.Fatalf("unexpected reply: %q", rep.plain)
}
}
func TestCustomPrefix(t *testing.T) {
radarr := &stubClient{results: []arr.Result{{Title: "Dune", Year: 2021}}}
rep := &stubReplier{}
d := New(".bh ", Services{Radarr: radarr}, rep)
d := newDispatcher(".bh ", Services{Radarr: radarr}, rep)
d.Handle(room, event, sender, ".bh movie dune")

View File

@@ -6,42 +6,42 @@ import (
"os"
"regexp"
"gopkg.in/yaml.v3"
"github.com/BurntSushi/toml"
)
var envBracketRe = regexp.MustCompile(`\$\{([^}]+)\}`)
type Config struct {
Matrix MatrixConfig `yaml:"matrix"`
Services ServicesConfig `yaml:"services"`
Matrix MatrixConfig `toml:"matrix"`
Services ServicesConfig `toml:"services"`
}
type MatrixConfig struct {
Homeserver string `yaml:"homeserver"`
UserID string `yaml:"user_id"`
Password string `yaml:"password"`
PickleKey string `yaml:"pickle_key"`
DisplayName string `yaml:"display_name"`
DataDir string `yaml:"data_dir"`
CommandPrefix string `yaml:"command_prefix"`
Homeserver string `toml:"homeserver"`
UserID string `toml:"user_id"`
Password string `toml:"password"`
PickleKey string `toml:"pickle_key"`
DisplayName string `toml:"display_name"`
DataDir string `toml:"data_dir"`
CommandPrefix string `toml:"command_prefix"`
// AllowedRooms is the set of room IDs the bot listens for commands in.
// Messages in any other room are ignored.
AllowedRooms []string `yaml:"allowed_rooms"`
AllowedRooms []string `toml:"allowed_rooms"`
}
type ServicesConfig struct {
Radarr *ArrConfig `yaml:"radarr"`
Sonarr *ArrConfig `yaml:"sonarr"`
Lidarr *ArrConfig `yaml:"lidarr"`
Radarr *ArrConfig `toml:"radarr"`
Sonarr *ArrConfig `toml:"sonarr"`
Lidarr *ArrConfig `toml:"lidarr"`
}
type ArrConfig struct {
URL string `yaml:"url"`
APIKey string `yaml:"api_key"`
QualityProfileID int `yaml:"quality_profile_id"`
RootFolder string `yaml:"root_folder"`
URL string `toml:"url"`
APIKey string `toml:"api_key"`
QualityProfileID int `toml:"quality_profile_id"`
RootFolder string `toml:"root_folder"`
// MetadataProfileID is required by Lidarr; ignored by Radarr/Sonarr.
MetadataProfileID int `yaml:"metadata_profile_id"`
MetadataProfileID int `toml:"metadata_profile_id"`
}
func Load(path string) (*Config, error) {
@@ -60,7 +60,7 @@ func Load(path string) (*Config, error) {
})
var cfg Config
if err := yaml.Unmarshal([]byte(expanded), &cfg); err != nil {
if _, err := toml.Decode(expanded, &cfg); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}

View File

@@ -3,6 +3,7 @@ package matrix
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
@@ -50,13 +51,16 @@ func New(cfg config.MatrixConfig) (*Client, error) {
device, err := loadDevice(devicePath)
if err != nil {
slog.Info("no existing device found, will login fresh")
// File exists but is unparseable — refuse to overwrite. A silent fresh
// login would orphan the prior device's megolm sessions and break
// decryption in every encrypted room the bot is already in.
return nil, fmt.Errorf("load device file %s: %w (refusing to overwrite — fix or delete the file)", devicePath, err)
}
var mx *mautrix.Client
if device != nil {
if isTokenValid(cfg.Homeserver, device.AccessToken) {
if isTokenValid(cfg.Homeserver, device.AccessToken, cfg.UserID) {
slog.Info("existing device credentials valid", "device_id", device.DeviceID)
mx, err = mautrix.NewClient(cfg.Homeserver, id.UserID(device.UserID), device.AccessToken)
if err != nil {
@@ -92,12 +96,11 @@ func New(cfg config.MatrixConfig) (*Client, error) {
mx.UserID = resp.UserID
mx.DeviceID = resp.DeviceID
device = &deviceInfo{
if err := saveDevice(devicePath, &deviceInfo{
AccessToken: resp.AccessToken,
DeviceID: string(resp.DeviceID),
UserID: string(resp.UserID),
}
if err := saveDevice(devicePath, device); err != nil {
}); err != nil {
slog.Warn("failed to save device info", "err", err)
}
@@ -117,16 +120,11 @@ func New(cfg config.MatrixConfig) (*Client, error) {
"room", evt.RoomID, "event_id", evt.ID, "sender", evt.Sender, "err", err)
}
ch.LoginAs = &mautrix.ReqLogin{
Type: mautrix.AuthTypePassword,
Identifier: mautrix.UserIdentifier{
Type: mautrix.IdentifierTypeUser,
User: cfg.UserID,
},
Password: cfg.Password,
InitialDeviceDisplayName: cfg.DisplayName,
}
// Intentionally NOT setting ch.LoginAs: cryptohelper.Init will Login() every
// time LoginAs is non-nil (see mautrix cryptohelper.go), which would mint a
// new access_token on every startup and silently invalidate the device.json
// we just wrote. We already have valid credentials in mx by this point —
// Init will reuse them.
if err := ch.Init(context.Background()); err != nil {
return nil, fmt.Errorf("crypto helper init: %w", err)
}
@@ -189,8 +187,11 @@ func (c *Client) SetMessageHandler(fn MessageHandler) {
}
// Start begins the Matrix sync loop in the background.
func (c *Client) Start(ctx context.Context) {
syncer := c.mx.Syncer.(*mautrix.DefaultSyncer)
func (c *Client) Start(ctx context.Context) error {
syncer, ok := c.mx.Syncer.(*mautrix.DefaultSyncer)
if !ok {
return fmt.Errorf("matrix syncer is not *mautrix.DefaultSyncer (got %T)", c.mx.Syncer)
}
syncer.OnEventType(event.EventMessage, func(ctx context.Context, evt *event.Event) {
if evt.Sender == c.userID {
@@ -243,6 +244,7 @@ func (c *Client) Start(ctx context.Context) {
}
}
}()
return nil
}
// Stop halts the sync loop and closes the crypto store.
@@ -259,10 +261,8 @@ func (c *Client) Stop() {
// PostThreadedReply sends a plain/HTML message into the thread rooted at rootEventID.
// IsFallingBack + m.in_reply_to gives non-thread-aware clients a sensible quoted reply.
func (c *Client) PostThreadedReply(roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// The caller's ctx governs cancellation and deadline.
func (c *Client) PostThreadedReply(ctx context.Context, roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error {
content := &event.MessageEventContent{
MsgType: event.MsgText,
Body: plain,
@@ -279,14 +279,24 @@ func (c *Client) PostThreadedReply(roomID id.RoomID, rootEventID id.EventID, pla
return err
}
// loadDevice returns (nil, nil) when no device file exists, the parsed device
// when it does, or (nil, err) when the file is present but unreadable/corrupt.
// Distinguishing the corrupt case lets the caller refuse to silently overwrite
// it with a brand-new device registration.
func loadDevice(path string) (*deviceInfo, error) {
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, err
}
var info deviceInfo
if err := json.Unmarshal(data, &info); err != nil {
return nil, err
return nil, fmt.Errorf("parse: %w", err)
}
if info.AccessToken == "" || info.DeviceID == "" || info.UserID == "" {
return nil, fmt.Errorf("missing required fields (access_token/device_id/user_id)")
}
return &info, nil
}
@@ -299,7 +309,11 @@ func saveDevice(path string, info *deviceInfo) error {
return os.WriteFile(path, data, 0o600)
}
func isTokenValid(homeserver, accessToken string) bool {
// isTokenValid hits /whoami and confirms both that the token is accepted AND
// that it identifies the user we expect. A bare status-code check would accept
// a token belonging to a different account if the operator swapped user_id
// without clearing data_dir.
func isTokenValid(homeserver, accessToken, expectedUserID string) bool {
req, err := http.NewRequest("GET", homeserver+"/_matrix/client/v3/account/whoami", nil)
if err != nil {
return false
@@ -312,5 +326,19 @@ func isTokenValid(homeserver, accessToken string) bool {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
if resp.StatusCode != http.StatusOK {
return false
}
var body struct {
UserID string `json:"user_id"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
return false
}
if body.UserID != expectedUserID {
slog.Warn("saved token belongs to a different user, will re-login",
"saved", body.UserID, "configured", expectedUserID)
return false
}
return true
}

14
main.go
View File

@@ -15,7 +15,7 @@ import (
)
func main() {
configPath := flag.String("config", "config.yaml", "path to config file")
configPath := flag.String("config", "config.toml", "path to config file")
flag.Parse()
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})))
@@ -43,13 +43,17 @@ func main() {
os.Exit(1)
}
dispatcher := bot.New(cfg.Matrix.CommandPrefix, services, mx)
mx.SetMessageHandler(dispatcher.Handle)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
mx.Start(ctx)
dispatcher := bot.New(ctx, cfg.Matrix.CommandPrefix, services, mx)
mx.SetMessageHandler(dispatcher.Handle)
if err := mx.Start(ctx); err != nil {
slog.Error("matrix start failed", "err", err)
mx.Stop()
os.Exit(1)
}
slog.Info("bellhop started", "allowed_rooms", len(cfg.Matrix.AllowedRooms))
sig := make(chan os.Signal, 1)