custompuppet.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "crypto/hmac"
  19. "crypto/sha512"
  20. "encoding/hex"
  21. "errors"
  22. "fmt"
  23. "time"
  24. "maunium.net/go/mautrix"
  25. "maunium.net/go/mautrix/appservice"
  26. "maunium.net/go/mautrix/event"
  27. "maunium.net/go/mautrix/id"
  28. )
  29. var (
  30. ErrNoCustomMXID = errors.New("no custom mxid set")
  31. ErrMismatchingMXID = errors.New("whoami result does not match custom mxid")
  32. )
  33. func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid id.UserID) error {
  34. prevCustomMXID := puppet.CustomMXID
  35. if puppet.customIntent != nil {
  36. puppet.stopSyncing()
  37. }
  38. puppet.CustomMXID = mxid
  39. puppet.AccessToken = accessToken
  40. err := puppet.StartCustomMXID(false)
  41. if err != nil {
  42. return err
  43. }
  44. if len(prevCustomMXID) > 0 {
  45. delete(puppet.bridge.puppetsByCustomMXID, prevCustomMXID)
  46. }
  47. if len(puppet.CustomMXID) > 0 {
  48. puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  49. }
  50. puppet.EnablePresence = puppet.bridge.Config.Bridge.DefaultBridgePresence
  51. puppet.EnableReceipts = puppet.bridge.Config.Bridge.DefaultBridgeReceipts
  52. puppet.bridge.AS.StateStore.MarkRegistered(puppet.CustomMXID)
  53. puppet.Update()
  54. // TODO leave rooms with default puppet
  55. return nil
  56. }
  57. func (puppet *Puppet) loginWithSharedSecret(mxid id.UserID) (string, error) {
  58. _, homeserver, _ := mxid.Parse()
  59. puppet.log.Debugfln("Logging into %s with shared secret", mxid)
  60. loginSecret := puppet.bridge.Config.Bridge.LoginSharedSecretMap[homeserver]
  61. client, err := puppet.bridge.newDoublePuppetClient(mxid, "")
  62. if err != nil {
  63. return "", fmt.Errorf("failed to create mautrix client to log in: %v", err)
  64. }
  65. req := mautrix.ReqLogin{
  66. Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: string(mxid)},
  67. DeviceID: "WhatsApp Bridge",
  68. InitialDeviceDisplayName: "WhatsApp Bridge",
  69. }
  70. if loginSecret == "appservice" {
  71. client.AccessToken = puppet.bridge.AS.Registration.AppToken
  72. req.Type = mautrix.AuthTypeAppservice
  73. } else {
  74. mac := hmac.New(sha512.New, []byte(loginSecret))
  75. mac.Write([]byte(mxid))
  76. req.Password = hex.EncodeToString(mac.Sum(nil))
  77. req.Type = mautrix.AuthTypePassword
  78. }
  79. resp, err := client.Login(&req)
  80. if err != nil {
  81. return "", err
  82. }
  83. return resp.AccessToken, nil
  84. }
  85. func (br *WABridge) newDoublePuppetClient(mxid id.UserID, accessToken string) (*mautrix.Client, error) {
  86. _, homeserver, err := mxid.Parse()
  87. if err != nil {
  88. return nil, err
  89. }
  90. homeserverURL, found := br.Config.Bridge.DoublePuppetServerMap[homeserver]
  91. if !found {
  92. if homeserver == br.AS.HomeserverDomain {
  93. homeserverURL = ""
  94. } else if br.Config.Bridge.DoublePuppetAllowDiscovery {
  95. resp, err := mautrix.DiscoverClientAPI(homeserver)
  96. if err != nil {
  97. return nil, fmt.Errorf("failed to find homeserver URL for %s: %v", homeserver, err)
  98. }
  99. homeserverURL = resp.Homeserver.BaseURL
  100. br.Log.Debugfln("Discovered URL %s for %s to enable double puppeting for %s", homeserverURL, homeserver, mxid)
  101. } else {
  102. return nil, fmt.Errorf("double puppeting from %s is not allowed", homeserver)
  103. }
  104. }
  105. return br.AS.NewExternalMautrixClient(mxid, accessToken, homeserverURL)
  106. }
  107. func (puppet *Puppet) newCustomIntent() (*appservice.IntentAPI, error) {
  108. if len(puppet.CustomMXID) == 0 {
  109. return nil, ErrNoCustomMXID
  110. }
  111. client, err := puppet.bridge.newDoublePuppetClient(puppet.CustomMXID, puppet.AccessToken)
  112. if err != nil {
  113. return nil, err
  114. }
  115. client.Syncer = puppet
  116. client.Store = puppet
  117. ia := puppet.bridge.AS.NewIntentAPI("custom")
  118. ia.Client = client
  119. ia.Localpart, _, _ = puppet.CustomMXID.Parse()
  120. ia.UserID = puppet.CustomMXID
  121. ia.IsCustomPuppet = true
  122. return ia, nil
  123. }
  124. func (puppet *Puppet) clearCustomMXID() {
  125. puppet.CustomMXID = ""
  126. puppet.AccessToken = ""
  127. puppet.customIntent = nil
  128. puppet.customUser = nil
  129. }
  130. func (puppet *Puppet) StartCustomMXID(reloginOnFail bool) error {
  131. if len(puppet.CustomMXID) == 0 {
  132. puppet.clearCustomMXID()
  133. return nil
  134. }
  135. intent, err := puppet.newCustomIntent()
  136. if err != nil {
  137. puppet.clearCustomMXID()
  138. return err
  139. }
  140. resp, err := intent.Whoami()
  141. if err != nil {
  142. if !reloginOnFail || (errors.Is(err, mautrix.MUnknownToken) && !puppet.tryRelogin(err, "initializing double puppeting")) {
  143. puppet.clearCustomMXID()
  144. return err
  145. }
  146. intent.AccessToken = puppet.AccessToken
  147. } else if resp.UserID != puppet.CustomMXID {
  148. puppet.clearCustomMXID()
  149. return ErrMismatchingMXID
  150. }
  151. puppet.customIntent = intent
  152. puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
  153. puppet.startSyncing()
  154. return nil
  155. }
  156. func (puppet *Puppet) startSyncing() {
  157. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  158. return
  159. }
  160. go func() {
  161. puppet.log.Debugln("Starting syncing...")
  162. puppet.customIntent.SyncPresence = "offline"
  163. err := puppet.customIntent.Sync()
  164. if err != nil {
  165. puppet.log.Errorln("Fatal error syncing:", err)
  166. }
  167. }()
  168. }
  169. func (puppet *Puppet) stopSyncing() {
  170. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  171. return
  172. }
  173. puppet.customIntent.StopSync()
  174. }
  175. func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, _ string) error {
  176. if !puppet.customUser.IsLoggedIn() {
  177. puppet.log.Debugln("Skipping sync processing: custom user not connected to whatsapp")
  178. return nil
  179. }
  180. for roomID, events := range resp.Rooms.Join {
  181. for _, evt := range events.Ephemeral.Events {
  182. evt.RoomID = roomID
  183. err := evt.Content.ParseRaw(evt.Type)
  184. if err != nil {
  185. continue
  186. }
  187. switch evt.Type {
  188. case event.EphemeralEventReceipt:
  189. if puppet.EnableReceipts {
  190. go puppet.bridge.MatrixHandler.HandleReceipt(evt)
  191. }
  192. case event.EphemeralEventTyping:
  193. go puppet.bridge.MatrixHandler.HandleTyping(evt)
  194. }
  195. }
  196. }
  197. if puppet.EnablePresence {
  198. for _, evt := range resp.Presence.Events {
  199. if evt.Sender != puppet.CustomMXID {
  200. continue
  201. }
  202. err := evt.Content.ParseRaw(evt.Type)
  203. if err != nil {
  204. continue
  205. }
  206. go puppet.bridge.HandlePresence(evt)
  207. }
  208. }
  209. return nil
  210. }
  211. func (puppet *Puppet) tryRelogin(cause error, action string) bool {
  212. if !puppet.bridge.Config.CanAutoDoublePuppet(puppet.CustomMXID) {
  213. return false
  214. }
  215. puppet.log.Debugfln("Trying to relogin after '%v' while %s", cause, action)
  216. accessToken, err := puppet.loginWithSharedSecret(puppet.CustomMXID)
  217. if err != nil {
  218. puppet.log.Errorfln("Failed to relogin after '%v' while %s: %v", cause, action, err)
  219. return false
  220. }
  221. puppet.log.Infofln("Successfully relogined after '%v' while %s", cause, action)
  222. puppet.AccessToken = accessToken
  223. return true
  224. }
  225. func (puppet *Puppet) OnFailedSync(_ *mautrix.RespSync, err error) (time.Duration, error) {
  226. puppet.log.Warnln("Sync error:", err)
  227. if errors.Is(err, mautrix.MUnknownToken) {
  228. if !puppet.tryRelogin(err, "syncing") {
  229. return 0, err
  230. }
  231. puppet.customIntent.AccessToken = puppet.AccessToken
  232. return 0, nil
  233. }
  234. return 10 * time.Second, nil
  235. }
  236. func (puppet *Puppet) GetFilterJSON(_ id.UserID) *mautrix.Filter {
  237. everything := []event.Type{{Type: "*"}}
  238. return &mautrix.Filter{
  239. Presence: mautrix.FilterPart{
  240. Senders: []id.UserID{puppet.CustomMXID},
  241. Types: []event.Type{event.EphemeralEventPresence},
  242. },
  243. AccountData: mautrix.FilterPart{NotTypes: everything},
  244. Room: mautrix.RoomFilter{
  245. Ephemeral: mautrix.FilterPart{Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}},
  246. IncludeLeave: false,
  247. AccountData: mautrix.FilterPart{NotTypes: everything},
  248. State: mautrix.FilterPart{NotTypes: everything},
  249. Timeline: mautrix.FilterPart{NotTypes: everything},
  250. },
  251. }
  252. }
  253. func (puppet *Puppet) SaveFilterID(_ id.UserID, _ string) {}
  254. func (puppet *Puppet) SaveNextBatch(_ id.UserID, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
  255. func (puppet *Puppet) SaveRoom(_ *mautrix.Room) {}
  256. func (puppet *Puppet) LoadFilterID(_ id.UserID) string { return "" }
  257. func (puppet *Puppet) LoadNextBatch(_ id.UserID) string { return puppet.NextBatch }
  258. func (puppet *Puppet) LoadRoom(_ id.RoomID) *mautrix.Room { return nil }