6 Commits

Author SHA1 Message Date
dependabot[bot]
4f30616dbd Bump modernc.org/sqlite from 1.50.1 to 1.53.0
Bumps [modernc.org/sqlite](https://gitlab.com/cznic/sqlite) from 1.50.1 to 1.53.0.
- [Changelog](https://gitlab.com/cznic/sqlite/blob/master/CHANGELOG.md)
- [Commits](https://gitlab.com/cznic/sqlite/compare/v1.50.1...v1.53.0)

---
updated-dependencies:
- dependency-name: modernc.org/sqlite
  dependency-version: 1.53.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-03 22:15:08 +00:00
prosolis
48330be3d5 Migrate Matrix auth to appservice (MAS-durable)
Replace password login + password-UIA cross-signing with appservice
as_token auth and MSC4190 device creation, so the bot survives the
Matrix Authentication Service (MAS) migration that removes m.login.password
and UIA.

- internal/bot/client.go: NewClient uses AS_TOKEN, SetAppServiceUserID,
  whoami validation, cryptohelper MSC4190 device create; drop device.json
  (crypto store persists device id); cross-signing best-effort/soft-fail.
- main.go: Config.Password -> ASToken (reads AS_TOKEN).
- internal/util/auth.go: deleted (password login dead in a MAS world).
- Bump mautrix-go v0.28.0 -> v0.28.1.
- registration.yaml.example + README/.env.example: appservice setup docs.
2026-07-03 15:12:47 -07:00
prosolis
c07d228be6 Merge email-nag into main 2026-06-28 17:40:16 -07:00
prosolis
f93fddd1d6 Add email-nag plugin: collect+verify missing Authentik emails over Matrix DM
One-shot MAS-migration helper. DMs a fixed target set of users with no
email on file in Authentik, collects an address, verifies inbox ownership
with an emailed 6-digit code (via Resend), and only writes it back to
Authentik after confirmation — so a mistyped/hostile address never becomes
a live recovery address. FSM state persists in email_nag_prompts so
restarts never re-nag anyone done or mid-flow.

- Per-user rolling-1h cap on verification emails (EMAIL_NAG_MAX_SENDS_PER_HOUR)
  to prevent send-spam abuse.
- Misconfig disables only this plugin instead of aborting bot startup.
2026-06-28 17:39:29 -07:00
prosolis
7c19788b52 Merge long-expeditions-d1 into main
Brings the J3 / long-expedition track up to main, including link-thumbnail
og:image previews + WOTD default-off.
2026-06-24 23:17:56 -07:00
prosolis
6e4928ca17 Merge pull request #11 from prosolis/forex-crypto-coingecko
Forex: convert to/from crypto via CoinGecko (keyless)
2026-05-21 22:21:52 -07:00
10 changed files with 752 additions and 263 deletions

View File

@@ -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)
@@ -128,3 +132,17 @@ MINIFLUX_MAX_PER_POLL=5 # max entries per feed per poll (default 5)
RATELIMIT_WEATHER=5
RATELIMIT_TRANSLATE=20
RATELIMIT_CONCERTS=10
# ---- Email Nag (one-shot migration helper: collect+verify missing Authentik emails over Matrix DM) ----
FEATURE_EMAIL_NAG= # set to "true" to enable
EMAIL_NAG_AUTHENTIK_URL= # e.g. https://authentik.parodia.dev
EMAIL_NAG_AUTHENTIK_TOKEN= # Authentik service-account token, scoped to user write
EMAIL_NAG_RESEND_KEY= # Resend API key (sends the verification code)
EMAIL_NAG_MAIL_FROM= # e.g. Parodia <noreply@mail.parodia.dev>
EMAIL_NAG_HOME_DOMAIN= # Matrix server name, e.g. parodia.dev (builds @user:domain)
EMAIL_NAG_TARGETS= # comma-separated Authentik usernames to nag (== Matrix localparts)
EMAIL_NAG_CODE_TTL=30m # verification code lifetime (default 30m)
EMAIL_NAG_MAX_ATTEMPTS=5 # wrong-code attempts before restart (default 5)
EMAIL_NAG_MAX_SENDS_PER_HOUR=5 # cap on verification emails per user per rolling hour (anti-spam, default 5)
EMAIL_NAG_SWEEP_DELAY=2s # delay between DMs during the startup sweep (default 2s)
EMAIL_NAG_REPROMPT_COOLDOWN= # re-nag non-responders whose last prompt is older than this (e.g. 72h); empty/0 = nag once

View File

@@ -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)

20
go.mod
View File

@@ -13,8 +13,8 @@ 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
modernc.org/sqlite v1.50.1
maunium.net/go/mautrix v0.28.1
modernc.org/sqlite v1.53.0
)
require (
@@ -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,13 +35,13 @@ 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
modernc.org/libc v1.72.3 // 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.73.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)

64
go.sum
View File

@@ -36,8 +36,8 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
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=
@@ -73,18 +73,18 @@ github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhso
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
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=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
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/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/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
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=
@@ -92,8 +92,8 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
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/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
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=
@@ -103,8 +103,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
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=
@@ -112,8 +112,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
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/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
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=
@@ -126,8 +126,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
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=
@@ -146,37 +146,37 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
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=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
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/tools v0.46.0/go.mod h1:FrD85F8l+NWL+9XWBSyVSHO6Ne4jutsfIFba7AWQ5Ys=
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=
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=
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=
modernc.org/ccgo/v4 v4.34.0/go.mod h1:AS5WYMyBakQ+fhsHhtP8mWB82KTGPkNNJDGfGQCe0/A=
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.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c=
modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws=
modernc.org/ccgo/v4 v4.34.4/go.mod h1:qdKqE8FNIYyysougB1RX9MxCzp5oJOcQXSobANJ4TuE=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/gc/v3 v3.1.3 h1:6QAplYyVO+KdPW3pGnqmJDUxtkec8ooEWvks/hhU3lc=
modernc.org/gc/v3 v3.1.3/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA=
modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
@@ -185,8 +185,8 @@ modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w=
modernc.org/sqlite v1.50.1/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=
modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=

View File

@@ -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)
}

View File

@@ -2001,6 +2001,24 @@ CREATE TABLE IF NOT EXISTS space_inviter_prompts (
);
CREATE INDEX IF NOT EXISTS idx_space_inviter_user ON space_inviter_prompts(user_id);
-- ── Email nag — collect+verify missing Authentik emails over Matrix DM ─────
-- One row per target user (MXID). Verified state survives restarts so the
-- startup sweep never re-nags someone already done or mid-flow.
CREATE TABLE IF NOT EXISTS email_nag_prompts (
user_id TEXT PRIMARY KEY, -- full MXID
username TEXT NOT NULL, -- Authentik username == Matrix localpart
dm_room_id TEXT NOT NULL,
stage TEXT NOT NULL, -- awaiting_email | awaiting_code | done
pending_email TEXT,
code TEXT,
code_expires INTEGER,
attempts INTEGER NOT NULL DEFAULT 0,
prompt_sent_at INTEGER NOT NULL,
verified_email TEXT,
verified_at INTEGER,
updated_at INTEGER NOT NULL
);
-- ── Turn-based combat — persistent per-fight session ───────────────────────
-- One row per manual elite/boss fight. Persists across bot restarts and
-- player away-from-keyboard so a fight can resume (or be auto-finished by

View File

@@ -0,0 +1,525 @@
package plugin
import (
"bytes"
"context"
"crypto/rand"
"database/sql"
"encoding/json"
"fmt"
"io"
"log/slog"
"math/big"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
"gogobee/internal/db"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/id"
)
// EmailNagPlugin DMs a fixed set of local users who have no email on file in
// Authentik, collects an address, verifies inbox ownership with an emailed
// 6-digit code, and only then writes the address to Authentik via its API.
//
// Nothing is written to Authentik until the code is confirmed, so a mistyped
// or hostile address never becomes a live recovery address. State lives in
// SQLite so restarts don't re-nag anyone already done or mid-flow. Modeled on
// SpaceInviterPlugin.
type EmailNagPlugin struct {
Base
enabled bool
cfg emailNagConfig
http *http.Client
mu sync.Mutex // serializes per-user FSM transitions
sendLog map[id.UserID][]time.Time // per-user code-send timestamps (rolling 1h window)
}
type emailNagConfig struct {
AuthentikURL string
AuthentikToken string
ResendKey string
MailFrom string
HomeDomain string
Targets []string // Authentik usernames == Matrix localparts
CodeTTL time.Duration
MaxAttempts int
SweepDelay time.Duration
RepromptCooldown time.Duration // 0 = nag once, never re-nag
MaxSendsPerHour int // cap on verification emails per user per rolling hour
}
const (
nagStageEmail = "awaiting_email"
nagStageCode = "awaiting_code"
nagStageDone = "done"
)
var emailNagRe = regexp.MustCompile(`[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}`)
func loadEmailNagConfig() emailNagConfig {
targets := []string{}
for _, t := range strings.Split(os.Getenv("EMAIL_NAG_TARGETS"), ",") {
if t = strings.TrimSpace(t); t != "" {
targets = append(targets, t)
}
}
maxAttempts := 5
if v := os.Getenv("EMAIL_NAG_MAX_ATTEMPTS"); v != "" {
var n int
if _, err := fmt.Sscanf(v, "%d", &n); err == nil && n > 0 {
maxAttempts = n
}
}
maxSends := 5
if v := os.Getenv("EMAIL_NAG_MAX_SENDS_PER_HOUR"); v != "" {
var n int
if _, err := fmt.Sscanf(v, "%d", &n); err == nil && n > 0 {
maxSends = n
}
}
return emailNagConfig{
AuthentikURL: strings.TrimRight(os.Getenv("EMAIL_NAG_AUTHENTIK_URL"), "/"),
AuthentikToken: os.Getenv("EMAIL_NAG_AUTHENTIK_TOKEN"),
ResendKey: os.Getenv("EMAIL_NAG_RESEND_KEY"),
MailFrom: os.Getenv("EMAIL_NAG_MAIL_FROM"),
HomeDomain: os.Getenv("EMAIL_NAG_HOME_DOMAIN"),
Targets: targets,
CodeTTL: envDur("EMAIL_NAG_CODE_TTL", 30*time.Minute),
MaxAttempts: maxAttempts,
SweepDelay: envDur("EMAIL_NAG_SWEEP_DELAY", 2*time.Second),
RepromptCooldown: envDur("EMAIL_NAG_REPROMPT_COOLDOWN", 0),
MaxSendsPerHour: maxSends,
}
}
func NewEmailNagPlugin(client *mautrix.Client) *EmailNagPlugin {
enabled := strings.EqualFold(os.Getenv("FEATURE_EMAIL_NAG"), "true")
if !enabled {
slog.Info("email_nag: disabled (set FEATURE_EMAIL_NAG=true to enable)")
}
return &EmailNagPlugin{
Base: NewBase(client),
enabled: enabled,
cfg: loadEmailNagConfig(),
http: &http.Client{Timeout: 30 * time.Second},
sendLog: make(map[id.UserID][]time.Time),
}
}
func (p *EmailNagPlugin) Name() string { return "email_nag" }
func (p *EmailNagPlugin) Commands() []CommandDef { return nil }
func (p *EmailNagPlugin) OnReaction(ReactionContext) error { return nil }
func (p *EmailNagPlugin) Init() error {
if !p.enabled {
return nil
}
if err := p.validateConfig(); err != nil {
// Don't take the whole bot down over a misconfigured one-shot helper —
// just disable this plugin and keep everything else running.
slog.Error("email_nag: disabled — invalid config", "err", err)
p.enabled = false
return nil
}
slog.Info("email_nag: ready",
"authentik", p.cfg.AuthentikURL,
"home_domain", p.cfg.HomeDomain,
"targets", len(p.cfg.Targets),
)
go p.runStartupSweep()
return nil
}
func (p *EmailNagPlugin) validateConfig() error {
missing := []string{}
if p.cfg.AuthentikURL == "" {
missing = append(missing, "EMAIL_NAG_AUTHENTIK_URL")
}
if p.cfg.AuthentikToken == "" {
missing = append(missing, "EMAIL_NAG_AUTHENTIK_TOKEN")
}
if p.cfg.ResendKey == "" {
missing = append(missing, "EMAIL_NAG_RESEND_KEY")
}
if p.cfg.MailFrom == "" {
missing = append(missing, "EMAIL_NAG_MAIL_FROM")
}
if p.cfg.HomeDomain == "" {
missing = append(missing, "EMAIL_NAG_HOME_DOMAIN")
}
if len(p.cfg.Targets) == 0 {
missing = append(missing, "EMAIL_NAG_TARGETS")
}
if len(missing) > 0 {
return fmt.Errorf("missing required config: %s", strings.Join(missing, ", "))
}
return nil
}
func (p *EmailNagPlugin) mxid(username string) id.UserID {
return id.UserID(fmt.Sprintf("@%s:%s", username, p.cfg.HomeDomain))
}
// ---------------------------------------------------------------------------
// Authentik API
// ---------------------------------------------------------------------------
type authentikUser struct {
PK int `json:"pk"`
Username string `json:"username"`
Email string `json:"email"`
IsActive bool `json:"is_active"`
}
// lookupUser returns the Authentik user for an exact username, or nil if absent.
func (p *EmailNagPlugin) lookupUser(ctx context.Context, username string) (*authentikUser, error) {
u := fmt.Sprintf("%s/api/v3/core/users/?username=%s", p.cfg.AuthentikURL, username)
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
req.Header.Set("Authorization", "Bearer "+p.cfg.AuthentikToken)
resp, err := p.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("authentik users status %d: %s", resp.StatusCode, string(body))
}
var page struct {
Results []authentikUser `json:"results"`
}
if err := json.Unmarshal(body, &page); err != nil {
return nil, fmt.Errorf("authentik decode: %w", err)
}
for i := range page.Results {
if page.Results[i].Username == username {
return &page.Results[i], nil
}
}
return nil, nil
}
// setEmail writes an email to an Authentik user by pk.
func (p *EmailNagPlugin) setEmail(ctx context.Context, pk int, email string) error {
payload, _ := json.Marshal(map[string]string{"email": email})
u := fmt.Sprintf("%s/api/v3/core/users/%d/", p.cfg.AuthentikURL, pk)
req, _ := http.NewRequestWithContext(ctx, http.MethodPatch, u, bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+p.cfg.AuthentikToken)
req.Header.Set("Content-Type", "application/json")
resp, err := p.http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("authentik patch status %d: %s", resp.StatusCode, string(body))
}
return nil
}
// ---------------------------------------------------------------------------
// Resend API
// ---------------------------------------------------------------------------
func (p *EmailNagPlugin) sendCode(ctx context.Context, to, code string) error {
payload, _ := json.Marshal(map[string]any{
"from": p.cfg.MailFrom,
"to": []string{to},
"subject": "Your parodia.dev verification code",
"text": fmt.Sprintf(
"Your parodia.dev email-verification code is: %s\n\n"+
"Reply to the bot with this code within %s to confirm this address.\n"+
"If you didn't request this, you can ignore this message.",
code, formatCooldown(p.cfg.CodeTTL)),
})
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.resend.com/emails", bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+p.cfg.ResendKey)
req.Header.Set("Content-Type", "application/json")
resp, err := p.http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return fmt.Errorf("resend status %d: %s", resp.StatusCode, string(body))
}
return nil
}
// allowSend enforces a per-user cap on verification emails over a rolling hour,
// so a target can't make the bot spray branded code emails at arbitrary
// addresses. Caller must hold p.mu (sendLog is not separately synchronized).
func (p *EmailNagPlugin) allowSend(mxid id.UserID, now time.Time) bool {
cutoff := now.Add(-time.Hour)
kept := p.sendLog[mxid][:0]
for _, t := range p.sendLog[mxid] {
if t.After(cutoff) {
kept = append(kept, t)
}
}
p.sendLog[mxid] = kept
if len(kept) >= p.cfg.MaxSendsPerHour {
return false
}
p.sendLog[mxid] = append(kept, now)
return true
}
func gen6() string {
n, err := rand.Int(rand.Reader, big.NewInt(1_000_000))
if err != nil {
return "000000"
}
return fmt.Sprintf("%06d", n.Int64())
}
// ---------------------------------------------------------------------------
// Startup sweep
// ---------------------------------------------------------------------------
func (p *EmailNagPlugin) runStartupSweep() {
ctx := context.Background()
sent, skipped := 0, 0
for _, username := range p.cfg.Targets {
mxid := p.mxid(username)
// Already finished in a prior run? Never re-nag.
if st, _, _, ok := p.rowStatus(mxid); ok && st == nagStageDone {
skipped++
continue
}
// Email already set in Authentik (set by us before, or out-of-band)?
u, err := p.lookupUser(ctx, username)
if err != nil {
slog.Warn("email_nag: authentik lookup failed", "user", username, "err", err)
continue
}
if u == nil {
slog.Warn("email_nag: no Authentik user", "user", username)
continue
}
if !u.IsActive {
continue
}
if strings.TrimSpace(u.Email) != "" {
p.markDone(mxid, username, "", u.Email) // record so we stop checking
skipped++
continue
}
// In-flight already (DM sent, awaiting reply)? Re-nag only if a cooldown
// is configured and the last prompt is older than it; otherwise leave alone.
if st, promptAt, dmRoom, ok := p.rowStatus(mxid); ok && (st == nagStageEmail || st == nagStageCode) {
if p.cfg.RepromptCooldown > 0 && time.Since(time.Unix(promptAt, 0)) > p.cfg.RepromptCooldown {
if err := p.renag(id.RoomID(dmRoom), mxid, st); err != nil {
slog.Warn("email_nag: renag failed", "user", username, "err", err)
} else {
sent++
time.Sleep(p.cfg.SweepDelay)
}
} else {
skipped++
}
continue
}
if err := p.startNag(ctx, username); err != nil {
slog.Warn("email_nag: start nag failed", "user", username, "err", err)
continue
}
sent++
time.Sleep(p.cfg.SweepDelay)
}
slog.Info("email_nag: startup sweep complete", "nagged", sent, "skipped", skipped)
}
func (p *EmailNagPlugin) startNag(ctx context.Context, username string) error {
mxid := p.mxid(username)
room, err := p.GetDMRoom(mxid)
if err != nil {
return fmt.Errorf("get dm room: %w", err)
}
now := time.Now().Unix()
_, err = db.Get().Exec(`
INSERT INTO email_nag_prompts (user_id, username, dm_room_id, stage, prompt_sent_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
dm_room_id=excluded.dm_room_id, stage=excluded.stage, updated_at=excluded.updated_at`,
string(mxid), username, string(room), nagStageEmail, now, now)
if err != nil {
return fmt.Errorf("record prompt: %w", err)
}
return p.SendMessage(room,
"Hi! We're migrating parodia.dev to a new login system, and your account "+
"has no email on file — it's needed for password recovery. "+
"Please reply here with your email address and I'll verify it.")
}
// ---------------------------------------------------------------------------
// Reply handling — FSM driven from DM replies
// ---------------------------------------------------------------------------
type nagRow struct {
Username string
DMRoom string
Stage string
PendingEmail sql.NullString
Code sql.NullString
CodeExpires sql.NullInt64
Attempts int
}
func (p *EmailNagPlugin) rowStatus(mxid id.UserID) (stage string, promptAt int64, dmRoom string, ok bool) {
err := db.Get().QueryRow(
`SELECT stage, prompt_sent_at, dm_room_id FROM email_nag_prompts WHERE user_id = ?`,
string(mxid)).Scan(&stage, &promptAt, &dmRoom)
return stage, promptAt, dmRoom, err == nil
}
// renag sends a stage-appropriate reminder and bumps prompt_sent_at so the
// cooldown restarts. Used by the sweep when EMAIL_NAG_REPROMPT_COOLDOWN > 0.
func (p *EmailNagPlugin) renag(room id.RoomID, mxid id.UserID, stage string) error {
msg := "Just a reminder — we still need an email on your account for the login " +
"migration. Please reply here with your email address."
if stage == nagStageCode {
msg = "Reminder: I'm still waiting for the verification code I emailed you. " +
"Reply with it, or send your email again for a fresh code."
}
now := time.Now().Unix()
if _, err := db.Get().Exec(
`UPDATE email_nag_prompts SET prompt_sent_at=?, updated_at=? WHERE user_id=?`,
now, now, string(mxid)); err != nil {
return err
}
return p.SendMessage(room, msg)
}
func (p *EmailNagPlugin) load(mxid id.UserID, room id.RoomID) (*nagRow, bool) {
var r nagRow
err := db.Get().QueryRow(`
SELECT username, dm_room_id, stage, pending_email, code, code_expires, attempts
FROM email_nag_prompts WHERE user_id = ? AND dm_room_id = ?`,
string(mxid), string(room)).Scan(
&r.Username, &r.DMRoom, &r.Stage, &r.PendingEmail, &r.Code, &r.CodeExpires, &r.Attempts)
if err != nil {
return nil, false
}
return &r, true
}
func (p *EmailNagPlugin) markDone(mxid id.UserID, username, room, email string) {
now := time.Now().Unix()
_, _ = db.Get().Exec(`
INSERT INTO email_nag_prompts (user_id, username, dm_room_id, stage, prompt_sent_at, verified_email, verified_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
stage=excluded.stage, verified_email=excluded.verified_email,
verified_at=excluded.verified_at, updated_at=excluded.updated_at`,
string(mxid), username, room, nagStageDone, now, email, now, now)
}
// OnMessage drives the per-user FSM. Only acts on messages in a tracked DM room
// sent by that room's target user.
func (p *EmailNagPlugin) OnMessage(ctx MessageContext) error {
if !p.enabled {
return nil
}
r, ok := p.load(ctx.Sender, ctx.RoomID)
if !ok || r.Stage == nagStageDone {
return nil
}
p.mu.Lock()
defer p.mu.Unlock()
// Re-read under lock in case a concurrent transition already advanced us.
r, ok = p.load(ctx.Sender, ctx.RoomID)
if !ok || r.Stage == nagStageDone {
return nil
}
bgctx := context.Background()
body := strings.TrimSpace(ctx.Body)
now := time.Now()
// An email anywhere in the message (re)starts verification for that address,
// whether we're awaiting the first email or a code-with-corrected-address.
if m := emailNagRe.FindString(body); m != "" {
email := strings.ToLower(m)
if !p.allowSend(ctx.Sender, now) {
return p.SendMessage(ctx.RoomID, fmt.Sprintf(
"That's a lot of attempts in a short window — please wait a bit before "+
"requesting another code (max %d per hour).", p.cfg.MaxSendsPerHour))
}
code := gen6()
exp := now.Add(p.cfg.CodeTTL).Unix()
if _, err := db.Get().Exec(`
UPDATE email_nag_prompts
SET stage=?, pending_email=?, code=?, code_expires=?, attempts=0, updated_at=?
WHERE user_id=?`,
nagStageCode, email, code, exp, now.Unix(), string(ctx.Sender)); err != nil {
return err
}
if err := p.sendCode(bgctx, email, code); err != nil {
slog.Error("email_nag: send code failed", "to", email, "err", err)
return p.SendMessage(ctx.RoomID,
"I couldn't send a code to that address just now — please double-check it and send it again.")
}
return p.SendMessage(ctx.RoomID, fmt.Sprintf(
"I emailed a 6-digit code to %s. Reply with the code to confirm (valid %s). "+
"Wrong address? Just send the correct one.", email, formatCooldown(p.cfg.CodeTTL)))
}
if r.Stage == nagStageEmail {
return p.SendMessage(ctx.RoomID,
"That doesn't look like an email address. Please send just your address, e.g. you@example.com")
}
// Stage awaiting_code: expect the digits.
entered := regexp.MustCompile(`\D`).ReplaceAllString(body, "")
if entered == "" {
return nil // not a code and not an email — ignore chatter
}
if !r.CodeExpires.Valid || now.Unix() > r.CodeExpires.Int64 {
_, _ = db.Get().Exec(`UPDATE email_nag_prompts SET stage=?, updated_at=? WHERE user_id=?`,
nagStageEmail, now.Unix(), string(ctx.Sender))
return p.SendMessage(ctx.RoomID, "That code expired. Send your email again and I'll issue a new one.")
}
if !r.Code.Valid || entered != r.Code.String {
attempts := r.Attempts + 1
if attempts >= p.cfg.MaxAttempts {
_, _ = db.Get().Exec(`UPDATE email_nag_prompts SET stage=?, attempts=0, updated_at=? WHERE user_id=?`,
nagStageEmail, now.Unix(), string(ctx.Sender))
return p.SendMessage(ctx.RoomID, "Too many wrong codes. Send your email again to restart.")
}
_, _ = db.Get().Exec(`UPDATE email_nag_prompts SET attempts=?, updated_at=? WHERE user_id=?`,
attempts, now.Unix(), string(ctx.Sender))
return p.SendMessage(ctx.RoomID, "That code doesn't match. Try again.")
}
// Verified — write to Authentik (re-check it's still empty to avoid clobbering).
u, err := p.lookupUser(bgctx, r.Username)
if err != nil {
slog.Error("email_nag: verify lookup failed", "user", r.Username, "err", err)
return p.SendMessage(ctx.RoomID, "Something went wrong on my end — please try the code again in a moment.")
}
if u == nil {
return p.SendMessage(ctx.RoomID, "I can't find your account anymore — please contact an admin.")
}
if strings.TrimSpace(u.Email) == "" {
if err := p.setEmail(bgctx, u.PK, r.PendingEmail.String); err != nil {
slog.Error("email_nag: set email failed", "user", r.Username, "err", err)
return p.SendMessage(ctx.RoomID, "I verified the code but couldn't save it — please try again shortly.")
}
}
p.markDone(ctx.Sender, r.Username, string(ctx.RoomID), r.PendingEmail.String)
slog.Info("email_nag: verified", "user", r.Username, "email", r.PendingEmail.String)
return p.SendMessage(ctx.RoomID, fmt.Sprintf(
"Verified ✓ %s is now on your account. Thanks — that's all we needed!", r.PendingEmail.String))
}

View File

@@ -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
}

View File

@@ -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"),
}
@@ -195,6 +195,9 @@ func main() {
spaceInviter := plugin.NewSpaceInviterPlugin(client)
registry.Register(spaceInviter)
// Email nag (DM users missing an Authentik email; verify + write it back)
registry.Register(plugin.NewEmailNagPlugin(client))
// Initialize all plugins
if err := registry.Init(); err != nil {
slog.Error("plugin init failed", "err", err)

61
registration.yaml.example Normal file
View File

@@ -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 <as_token>).
# 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:<your-domain>, 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