diff --git a/.env.example b/.env.example index d7a4104..ef3908a 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,11 @@ # ---- Matrix Connection ---- +# GogoBee authenticates as an appservice (MAS-durable). AS_TOKEN is the +# as_token from registration.yaml — a Synapse-level credential that never +# expires and is unaffected by Matrix Authentication Service. See +# registration.yaml.example for the homeserver-side setup. HOMESERVER_URL=https://matrix.example.com BOT_USER_ID=@gogobee:example.com -BOT_PASSWORD=your_password_here +AS_TOKEN=your_appservice_as_token_here BOT_DISPLAY_NAME=GogoBee # Which rooms the bot posts scheduled content to (comma-separated room IDs) diff --git a/README.md b/README.md index f827bc7..4c6c112 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,14 @@ Everything is configured through environment variables or a `.env` file. |----------|-------------| | `HOMESERVER_URL` | Matrix homeserver URL, e.g. `https://matrix.org` | | `BOT_USER_ID` | Bot's Matrix user ID, e.g. `@gogobee:matrix.org` | -| `BOT_PASSWORD` | Bot's Matrix password | +| `AS_TOKEN` | Appservice `as_token` from `registration.yaml` (see below) | + +GogoBee authenticates as a Matrix **application service** rather than with a +password. The `as_token` is a homeserver-level credential that never expires and +is unaffected by Matrix Authentication Service (MAS) removing password login and +UIA. Device E2EE keys are created via MSC4190. See +[`registration.yaml.example`](registration.yaml.example) for the homeserver-side +setup (register the appservice, enable `msc4190_enabled`, then set `AS_TOKEN`). ### Core (optional) diff --git a/go.mod b/go.mod index b665401..cda6a2d 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/robfig/cron/v3 v3.0.1 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e golang.org/x/image v0.40.0 - maunium.net/go/mautrix v0.28.0 + maunium.net/go/mautrix v0.28.1 modernc.org/sqlite v1.50.1 ) @@ -25,7 +25,7 @@ require ( github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-sqlite3 v1.14.44 // indirect + github.com/mattn/go-sqlite3 v1.14.45 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 // indirect github.com/pkg/errors v0.9.1 // indirect @@ -35,12 +35,12 @@ require ( github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect github.com/tidwall/sjson v1.2.5 // indirect - go.mau.fi/util v0.9.9 // indirect - golang.org/x/crypto v0.51.0 // indirect - golang.org/x/exp v0.0.0-20260508232706-74f9aab9d74a // indirect - golang.org/x/net v0.54.0 // indirect - golang.org/x/sys v0.44.0 // indirect - golang.org/x/text v0.37.0 // indirect + go.mau.fi/util v0.9.10 // indirect + golang.org/x/crypto v0.53.0 // indirect + golang.org/x/exp v0.0.0-20260611194520-c48552f49976 // indirect + golang.org/x/net v0.56.0 // indirect + golang.org/x/sys v0.46.0 // indirect + golang.org/x/text v0.38.0 // indirect modernc.org/libc v1.72.3 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect diff --git a/go.sum b/go.sum index edd2c10..2171d37 100644 --- a/go.sum +++ b/go.sum @@ -38,6 +38,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8= github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= +github.com/mattn/go-sqlite3 v1.14.45 h1:6KA/spDguL3KV8rnybG7ezSaE4SeMR3KC9VbUoAQaIk= +github.com/mattn/go-sqlite3 v1.14.45/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/notnil/joker v0.0.0-20180219043703-3f2f69a75914 h1:xXPuFr3PVM4p6Vw3j0CP29oWYRVKO3cPZjR6D7BxggQ= @@ -75,6 +77,8 @@ github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.mau.fi/util v0.9.9 h1:ujDeXCo07HBor5oQLyO1tHklupmqVmPgasc53d7q/NE= go.mau.fi/util v0.9.9/go.mod h1:pqt4Vcrt+5gcH/CgrHZg11qSx+b34o6mknGzOEA6waY= +go.mau.fi/util v0.9.10 h1:wzvz5iDHyqDXB8vgisD4d3SzucLXNM3iNY+1O1RoHtg= +go.mau.fi/util v0.9.10/go.mod h1:YQOxySn+ZE3qSYqNxvyX7Yi3suA8YK17PS6QqBREW7A= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= @@ -83,8 +87,12 @@ golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI= golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= +golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= +golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= golang.org/x/exp v0.0.0-20260508232706-74f9aab9d74a h1:+3jdDGGB8NGb1Zktc737jlt3/A5f6UlwSzmvqUuufxw= golang.org/x/exp v0.0.0-20260508232706-74f9aab9d74a/go.mod h1:d2fgXJLVs4dYDHUk5lwMIfzRzSrWCfGZb0ZqeLa/Vcw= +golang.org/x/exp v0.0.0-20260611194520-c48552f49976 h1:X8Hz2ImujgbmetVuW+w2YkyZChE3cBpZi2P158rTG9M= +golang.org/x/exp v0.0.0-20260611194520-c48552f49976/go.mod h1:vnf4pv9iKZXY58sQE1L86zmNWJ4159e1RkcWiLCkeEY= golang.org/x/image v0.40.0 h1:Tw4GyDXMo+daZN1znreBRC3VayR1aLFUyUEOLUdW1a8= golang.org/x/image v0.40.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -94,6 +102,7 @@ golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -105,6 +114,8 @@ golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w= golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -114,6 +125,7 @@ golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -128,6 +140,8 @@ golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 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/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -148,6 +162,8 @@ golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= +golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= @@ -156,6 +172,7 @@ golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58 golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= +golang.org/x/tools v0.46.0 h1:7jTurBkPZu4moS/Uy4OQT1M+QBlsj3wejyZwsT8Z7rk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -163,6 +180,8 @@ 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= maunium.net/go/mautrix v0.28.0/go.mod h1:/a9A7LGaqb9B3nho4tLd28n0EPcCdwpm2dxkxkLLgh0= +maunium.net/go/mautrix v0.28.1 h1:Hic3oDMPbLbQu1fhboTRAKZcORMjzzkjxsa+SGk60b0= +maunium.net/go/mautrix v0.28.1/go.mod h1:mWXQNmOlrq4VTDU9f1HO03BSIswdUIyyY4wUKHqwzzY= modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY= modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ= diff --git a/internal/bot/client.go b/internal/bot/client.go index 17d4bab..c5b2684 100644 --- a/internal/bot/client.go +++ b/internal/bot/client.go @@ -2,203 +2,146 @@ package bot import ( "context" - "encoding/json" "fmt" "log/slog" "os" "path/filepath" - "gogobee/internal/util" - "maunium.net/go/mautrix" "maunium.net/go/mautrix/crypto/cryptohelper" "maunium.net/go/mautrix/id" ) -// DeviceInfo holds persisted device credentials. -type DeviceInfo struct { - AccessToken string `json:"access_token"` - DeviceID string `json:"device_id"` - UserID string `json:"user_id"` -} - // Config holds the bot's startup configuration. type Config struct { Homeserver string - UserID string - Password string + UserID string // Bot's full Matrix user ID, e.g. @gogobee:example.com + ASToken string // Appservice as_token from registration.yaml DataDir string DisplayName string } -// NewClient creates and configures a mautrix client with E2EE support. -// The cryptohelper handles: -// - Persistent crypto store in SQLite (device keys, sessions, cross-signing keys) -// - Automatic cross-signing bootstrap (self-signs the device on first run) -// - Automatic device trust via cross-signing (no manual verification needed) -// - Megolm session sharing and key exchange -// - Olm session management for device-to-device encryption +// NewClient creates and configures a mautrix client authenticated as an +// application service, with E2EE via the cryptohelper. // -// This solves the TS version's device verification issues because: -// 1. Crypto state persists across restarts (not in-memory like fake-indexeddb) -// 2. Cross-signing makes other devices trust this bot automatically -// 3. The bot trusts all users' devices by default (appropriate for a bot) -// 4. No manual emoji/SAS verification needed +// Why appservice instead of password login: +// +// Under Matrix Authentication Service (MAS), the legacy password login +// (m.login.password) and User-Interactive Auth (UIA) flows are being removed — +// auth moves to OAuth2/OIDC. A bot built on password login + password-UIA +// cross-signing (the old code) breaks in a MAS world: short-lived tokens with +// no refresh, and UIA-gated key uploads that simply fail. +// +// The appservice model sidesteps MAS entirely. The as_token is a Synapse-level +// trust relationship declared in registration.yaml — Synapse validates it +// directly, not via MAS — so it never expires and needs no login flow. Device +// creation uses MSC4190 (PUT /devices), which replaces the UIA-gated device +// dance for appservice users. This is the MAS-durable path. +// +// The cryptohelper still handles everything E2EE: +// - Persistent crypto store in SQLite (device keys, sessions, cross-signing) +// - Megolm session sharing / key exchange, Olm device-to-device sessions +// - The bot trusts all users' devices by default (appropriate for a bot) +// - No interactive emoji/SAS verification needed func NewClient(cfg Config) (*mautrix.Client, error) { if err := os.MkdirAll(cfg.DataDir, 0o755); err != nil { return nil, fmt.Errorf("create data dir: %w", err) } + if cfg.ASToken == "" { + return nil, fmt.Errorf("AS_TOKEN is required (appservice registration as_token)") + } + if cfg.UserID == "" { + return nil, fmt.Errorf("BOT_USER_ID is required") + } - devicePath := filepath.Join(cfg.DataDir, "device.json") + ctx := context.Background() + userID := id.UserID(cfg.UserID) - // Try to load existing device credentials - device, err := loadDevice(devicePath) + // The as_token IS the access token. No login flow, no refresh — Synapse + // trusts it for any user in the registration's namespace. + client, err := mautrix.NewClient(cfg.Homeserver, userID, cfg.ASToken) if err != nil { - slog.Info("no existing device found, will login fresh") + return nil, fmt.Errorf("create client: %w", err) } - var client *mautrix.Client + // Assert our own user ID on every request (appservice identity assertion, + // ?user_id=). Required so Synapse knows which namespaced user we're acting + // as — including on /sync and the MSC4190 device creation below. + client.SetAppServiceUserID = true - if device != nil { - // Validate existing token - valid, _ := util.IsTokenValid(cfg.Homeserver, device.AccessToken) - if valid { - slog.Info("existing device credentials valid", "device_id", device.DeviceID) - userID := id.UserID(device.UserID) - client, err = mautrix.NewClient(cfg.Homeserver, userID, device.AccessToken) - if err != nil { - return nil, fmt.Errorf("create client with existing token: %w", err) - } - client.DeviceID = id.DeviceID(device.DeviceID) - } else { - slog.Warn("existing device credentials invalid, logging in again") - device = nil - } + // Validate the token + homeserver reachability up front with a clear error. + whoami, err := client.Whoami(ctx) + if err != nil { + return nil, fmt.Errorf("appservice token validation failed (whoami): %w", err) } - - if device == nil { - // Fresh login - loginResp, err := util.LoginWithPassword(cfg.Homeserver, cfg.UserID, cfg.Password, cfg.DisplayName) - if err != nil { - return nil, fmt.Errorf("login: %w", err) - } - - userID := id.UserID(loginResp.UserID) - client, err = mautrix.NewClient(cfg.Homeserver, userID, loginResp.AccessToken) - if err != nil { - return nil, fmt.Errorf("create client: %w", err) - } - client.DeviceID = id.DeviceID(loginResp.DeviceID) - - // Save device info - device = &DeviceInfo{ - AccessToken: loginResp.AccessToken, - DeviceID: loginResp.DeviceID, - UserID: loginResp.UserID, - } - if err := saveDevice(devicePath, device); err != nil { - slog.Warn("failed to save device info", "err", err) - } - - slog.Info("logged in successfully", - "user_id", loginResp.UserID, - "device_id", loginResp.DeviceID, - ) + if whoami.UserID != userID { + return nil, fmt.Errorf("appservice identity mismatch: token resolves to %s but BOT_USER_ID is %s", whoami.UserID, userID) } + slog.Info("appservice token valid", "user_id", whoami.UserID) - // Set up E2EE via cryptohelper — stores crypto state in its own SQLite DB, - // separate from the main app database. Unlike the TS version which used an - // in-memory fake-indexeddb store that was lost on restart (causing constant - // re-verification), mautrix-go's cryptohelper persists everything in SQLite: - // device keys, olm/megolm sessions, cross-signing keys, and device trust state. - // - // We pass just the raw file path — the cryptohelper wraps it in a file: URI - // with _txlock=immediate internally (see cryptohelper.go line 82). + // Set up E2EE. The cryptohelper persists all crypto state in its own SQLite + // DB (device keys, olm/megolm sessions, cross-signing keys, device trust), + // separate from the main app database. The device ID is persisted there too, + // so restarts reuse the same device — no device.json needed. cryptoDBPath := filepath.Join(cfg.DataDir, "crypto.db") ch, err := cryptohelper.NewCryptoHelper(client, []byte("gogobee_pickle_key"), cryptoDBPath) if err != nil { return nil, fmt.Errorf("init crypto helper: %w", err) } - // LoginAs enables the cryptohelper to re-login if the token expires, - // and to bootstrap cross-signing on first run. Cross-signing means: - // - The bot's master key signs its own device key - // - Other users/devices that have verified the bot's master key - // will automatically trust this device - // - No interactive emoji/SAS verification needed + // MSC4190: create/refresh the bot's device via PUT /devices instead of the + // UIA-gated login dance. On first run the crypto store has no device ID, so + // a fresh one is generated and persisted; on restart the stored ID is + // reused (the PUT is idempotent). LoginAs carries only the display name — + // in MSC4190 mode the cryptohelper never calls /login. + ch.MSC4190 = true ch.LoginAs = &mautrix.ReqLogin{ - Type: mautrix.AuthTypePassword, - Identifier: mautrix.UserIdentifier{ - Type: mautrix.IdentifierTypeUser, - User: cfg.UserID, - }, - Password: cfg.Password, InitialDeviceDisplayName: cfg.DisplayName, } - if err := ch.Init(context.Background()); err != nil { - return nil, fmt.Errorf("crypto helper init: %w", err) + if err := ch.Init(ctx); err != nil { + return nil, fmt.Errorf("crypto helper init (MSC4190 device create): %w", err) } - - // Attach crypto helper to client client.Crypto = ch - // Bootstrap cross-signing: generate keys, sign own device, sign master key. - // This makes the bot's device show as "verified" to other users. + // Best-effort cross-signing bootstrap. This makes the bot's device show as + // "verified" to users who have verified the bot's master key. It is NOT + // required for E2EE to function — the bot already trusts all devices and + // shares keys — so any failure is logged and ignored. + // + // Under MSC3202 (appservice device assertion) Synapse may accept the key + // upload without UIA, in which case the callback below is never invoked. If + // the homeserver still demands UIA, we have no password credential to + // satisfy it (that's the whole point of going MAS-native), so it fails soft. mach := ch.Machine() - recoveryKey, _, err := mach.GenerateAndUploadCrossSigningKeys(context.Background(), func(ui *mautrix.RespUserInteractive) interface{} { - return map[string]interface{}{ - "type": mautrix.AuthTypePassword, - "identifier": map[string]interface{}{ - "type": mautrix.IdentifierTypeUser, - "user": cfg.UserID, - }, - "password": cfg.Password, - "session": ui.Session, - } + recoveryKey, _, err := mach.GenerateAndUploadCrossSigningKeys(ctx, func(ui *mautrix.RespUserInteractive) interface{} { + slog.Warn("cross-signing: homeserver requested UIA, but appservice auth has no password credential to satisfy it — skipping verified-shield bootstrap") + return map[string]interface{}{"session": ui.Session} }, "") if err != nil { - slog.Warn("cross-signing: key upload failed (may already exist)", "err", err) + slog.Warn("cross-signing: key upload skipped (may already exist or UIA required)", "err", err) } else { slog.Info("cross-signing: keys uploaded", "recovery_key", recoveryKey) } - if err := mach.SignOwnDevice(context.Background(), mach.OwnIdentity()); err != nil { + if err := mach.SignOwnDevice(ctx, mach.OwnIdentity()); err != nil { slog.Warn("cross-signing: sign own device failed", "err", err) } else { slog.Info("cross-signing: own device signed") } - if err := mach.SignOwnMasterKey(context.Background()); err != nil { + if err := mach.SignOwnMasterKey(ctx); err != nil { slog.Warn("cross-signing: sign master key failed", "err", err) } else { slog.Info("cross-signing: master key signed") } slog.Info("E2EE initialized", + "user_id", client.UserID, "device_id", client.DeviceID, "crypto_store", "sqlite-persistent", + "auth", "appservice+msc4190", ) return client, nil } - -func loadDevice(path string) (*DeviceInfo, error) { - data, err := os.ReadFile(path) - if err != nil { - return nil, err - } - var info DeviceInfo - if err := json.Unmarshal(data, &info); err != nil { - return nil, err - } - return &info, nil -} - -func saveDevice(path string, info *DeviceInfo) error { - data, err := json.MarshalIndent(info, "", " ") - if err != nil { - return err - } - return os.WriteFile(path, data, 0o600) -} diff --git a/internal/util/auth.go b/internal/util/auth.go deleted file mode 100644 index 2c48541..0000000 --- a/internal/util/auth.go +++ /dev/null @@ -1,86 +0,0 @@ -package util - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "time" -) - -// LoginResponse holds the Matrix login response fields we care about. -type LoginResponse struct { - AccessToken string `json:"access_token"` - DeviceID string `json:"device_id"` - UserID string `json:"user_id"` -} - -// LoginWithPassword performs a Matrix password login. -func LoginWithPassword(homeserver, user, password, deviceDisplayName string) (*LoginResponse, error) { - url := homeserver + "/_matrix/client/v3/login" - - body := map[string]any{ - "type": "m.login.password", - "identifier": map[string]string{ - "type": "m.id.user", - "user": user, - }, - "password": password, - "initial_device_display_name": deviceDisplayName, - } - - data, err := json.Marshal(body) - if err != nil { - return nil, fmt.Errorf("marshal login body: %w", err) - } - - client := &http.Client{Timeout: 30 * time.Second} - resp, err := client.Post(url, "application/json", bytes.NewReader(data)) - if err != nil { - return nil, fmt.Errorf("login request: %w", err) - } - defer resp.Body.Close() - - respBody, _ := io.ReadAll(resp.Body) - if resp.StatusCode != 200 { - return nil, fmt.Errorf("login failed (HTTP %d): %s", resp.StatusCode, string(respBody)) - } - - var result LoginResponse - if err := json.Unmarshal(respBody, &result); err != nil { - return nil, fmt.Errorf("parse login response: %w", err) - } - return &result, nil -} - -// IsTokenValid checks if an access token is still valid via /account/whoami. -func IsTokenValid(homeserver, accessToken string) (bool, string) { - url := homeserver + "/_matrix/client/v3/account/whoami" - - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return false, "" - } - req.Header.Set("Authorization", "Bearer "+accessToken) - - client := &http.Client{Timeout: 10 * time.Second} - resp, err := client.Do(req) - if err != nil { - return false, "" - } - defer resp.Body.Close() - - if resp.StatusCode != 200 { - return false, "" - } - - var result struct { - UserID string `json:"user_id"` - } - body, _ := io.ReadAll(resp.Body) - if err := json.Unmarshal(body, &result); err != nil { - return false, "" - } - return true, result.UserID -} diff --git a/main.go b/main.go index dcbcb40..c104410 100644 --- a/main.go +++ b/main.go @@ -59,7 +59,7 @@ func main() { cfg := bot.Config{ Homeserver: os.Getenv("HOMESERVER_URL"), UserID: os.Getenv("BOT_USER_ID"), - Password: os.Getenv("BOT_PASSWORD"), + ASToken: os.Getenv("AS_TOKEN"), DataDir: dataDir, DisplayName: envOr("BOT_DISPLAY_NAME", "GogoBee"), } diff --git a/registration.yaml.example b/registration.yaml.example new file mode 100644 index 0000000..0d6130e --- /dev/null +++ b/registration.yaml.example @@ -0,0 +1,61 @@ +# GogoBee appservice registration — MAS-durable auth. +# +# Copy to registration.yaml, fill in the tokens, and register it with your +# homeserver. This replaces the old password login: the as_token is a Synapse- +# level trust relationship, so it never expires and is unaffected by Matrix +# Authentication Service (MAS) removing password login / UIA. +# +# --------------------------------------------------------------------------- +# 1. Generate two independent secrets (do NOT reuse the same value): +# openssl rand -hex 32 # -> as_token +# openssl rand -hex 32 # -> hs_token +# +# 2. Point Synapse at this file in homeserver.yaml: +# app_service_config_files: +# - /path/to/registration.yaml +# +# 3. Restart Synapse, then set AS_TOKEN in GogoBee's .env to the as_token below. +# +# MSC4190 device management (so the bot creates its E2EE device without UIA) is +# opted into per-appservice via the `io.element.msc4190: true` flag at the +# bottom of this file — there is NO homeserver-level flag for it in current +# Synapse. Works even with Matrix Authentication Service (MAS) delegation on: +# Synapse serves PUT /devices for appservice requests regardless of MAS. +# --------------------------------------------------------------------------- + +# Unique identifier for this appservice. +id: gogobee + +# The token GogoBee sends to the homeserver (Authorization: Bearer ). +# This is the value that goes in the bot's AS_TOKEN env var. +as_token: "CHANGE_ME_as_token_from_openssl_rand_hex_32" + +# The token the homeserver would use to authenticate to the appservice's push +# endpoint. GogoBee uses /sync rather than the push (transaction) model, so it +# is not consumed by the bot — but Synapse still requires it to be set and +# distinct from as_token. +hs_token: "CHANGE_ME_hs_token_from_openssl_rand_hex_32" + +# The bot's localpart. Its full user ID is @gogobee:, which must +# match BOT_USER_ID in .env. +sender_localpart: gogobee + +# GogoBee uses /sync, not the transaction push API, so this URL is never called. +# Synapse requires the field; null disables push delivery. +url: null + +# GogoBee only ever acts as its own @gogobee user. This namespace claims that +# single user ID. Adjust the domain to match your homeserver. +# The bot only needs to ACT AS @gogobee (which already exists), not exclusively +# own the namespace — so exclusive is false to avoid any conflict with the +# existing account. +namespaces: + users: + - exclusive: false + regex: "@gogobee:example\\.com" + aliases: [] + rooms: [] + +# Required for the bot to manage its own E2EE device via MSC4190 (PUT /devices) +# instead of the UIA-gated login flow that MAS removes. +io.element.msc4190: true