4
0

webapi_session.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. package state
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "errors"
  8. "log/slog"
  9. mrand "math/rand/v2"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/mk6i/open-oscar-server/server/webapi/types"
  16. "github.com/mk6i/open-oscar-server/wire"
  17. )
  18. var (
  19. // ErrNoWebAPISession is returned when a WebAPI session is not found.
  20. ErrNoWebAPISession = errors.New("WebAPI session not found")
  21. // ErrWebAPISessionExpired is returned when a WebAPI session has expired.
  22. ErrWebAPISessionExpired = errors.New("WebAPI session expired")
  23. // ErrWebAPISessionManagerClosed is returned when a session is requested from
  24. // a manager that has been shut down.
  25. ErrWebAPISessionManagerClosed = errors.New("WebAPI session manager is shut down")
  26. )
  27. // Web API session lifecycle timeline.
  28. //
  29. // A web client keeps its session alive by long-polling GET /aim/fetchEvents.
  30. // Every authenticated request touches the session (middleware.RequireSession
  31. // calls TouchSession at request arrival), sliding expiry to now + the TTL. A
  32. // single poll blocks for up to 60s (the fetchEvents long-poll cap) and the
  33. // client waits ~500ms (TimeToNextFetch) before re-polling, so in steady state a
  34. // healthy client touches the session at worst every ~60-65s once jitter is
  35. // included. That worst-case touch interval is the floor the TTL must clear.
  36. //
  37. // If a client hangs up without calling endSession, its last touch was at its
  38. // last poll: the session then expires webAPISessionTTL later and the reaper
  39. // sweeps it within one webAPISessionReapInterval tick. So a silent client is
  40. // removed (and its OSCAR session closed) within TTL + tick of going quiet.
  41. const (
  42. // webAPISessionTTL bounds how long a session survives without a poll. It is
  43. // sized to absorb one missed poll cycle: ~60s for the normal cycle, ~60s for
  44. // the absorbed miss, plus ~20s of jitter margin. Two consecutive misses mean
  45. // the client is genuinely gone and the session is reaped.
  46. webAPISessionTTL = 150 * time.Second
  47. // webAPISessionReapInterval is how often the cleanup goroutine sweeps for
  48. // expired sessions (~TTL/5). A dead session lingers at most
  49. // webAPISessionTTL + webAPISessionReapInterval before removal.
  50. webAPISessionReapInterval = 30 * time.Second
  51. )
  52. // WebAPISession represents an active Web AIM API session.
  53. type WebAPISession struct {
  54. AimSID string // Unique session ID for web client
  55. ScreenName DisplayScreenName // User identity
  56. OSCARSession *SessionInstance // Bridge to existing OSCAR session
  57. OSCARCookie []byte // OSCAR auth cookie for the startOSCARSession handoff
  58. BOSHost string // BOS host advertised to the web client
  59. BOSPort int // BOS port advertised to the web client
  60. UseSSL bool // Whether the handoff advertised an SSL BOS connection
  61. BaseURL string // Web API base URL advertised to the web client, used to build absolute asset URLs
  62. Events []string // Subscribed event types
  63. EventQueue *types.EventQueue // Per-session event queue
  64. DevID string // Developer ID that created this session
  65. ClientName string // Client application name
  66. ClientVersion string // Client application version
  67. CreatedAt time.Time // SessionInstance creation time
  68. LastAccessed time.Time // Last activity time
  69. ExpiresAt time.Time // SessionInstance expiration time
  70. FetchTimeout int // Long-polling timeout in milliseconds
  71. TimeToNextFetch int // Suggested delay before next fetch
  72. RemoteAddr string // Client IP address
  73. TempBuddies map[string]bool // Temporary buddies for this session only
  74. BuddyListRefresher func(ctx context.Context) (interface{}, error) // Called on feedbag changes to push buddylist event
  75. PermitDenyRefresher func(ctx context.Context) (interface{}, error) // Called on feedbag changes to push permitDeny event
  76. MyInfoRefresher func(ctx context.Context) (interface{}, error) // Called on self user-info updates (e.g. icon change) to push myInfo event
  77. BuddyAliasLoader func(ctx context.Context) (map[string]string, error)
  78. // BuddyIconURL formats the absolute buddyIcon URL for a buddy from the icon
  79. // hash carried in a presence SNAC. Returns "" when no URL can be published.
  80. BuddyIconURL func(screenName IdentScreenName, hash []byte) string
  81. aliases map[string]string // cached BuddyAliasLoader result, nil when unloaded or invalidated
  82. aliasMu sync.Mutex
  83. imLog map[string][]WebAPIStoredIM
  84. imLogMu sync.Mutex
  85. logger *slog.Logger // Logger for debugging
  86. listeners sync.WaitGroup
  87. // chatRooms maps a joined room id (the ChatRoom cookie the web client uses as
  88. // its im/sendIM target) to that room's dedicated chat SessionInstance. Each
  89. // join registers a separate OSCAR chat session here, analogous to TOC's
  90. // ChatRegistry. chatRoomsClosed is set once Close has drained the map, so a
  91. // join racing teardown cannot re-add (and thereby leak) an instance Close will
  92. // never see. Both guarded by chatRoomsMu.
  93. chatRooms map[string]*SessionInstance
  94. chatRoomsClosed bool
  95. chatRoomsMu sync.Mutex
  96. ctx context.Context
  97. cancel context.CancelFunc
  98. closeMu sync.Mutex
  99. closed bool
  100. }
  101. // IsExpired checks if the session has expired.
  102. func (s *WebAPISession) IsExpired() bool {
  103. return time.Now().After(s.ExpiresAt)
  104. }
  105. // Aliases returns this session owner's private buddy aliases, keyed by normalized
  106. // screen name. Aliases live in the owner's feedbag, so the map is loaded once and
  107. // cached until a feedbag change invalidates it: a signon that brings a large buddy
  108. // list online costs one feedbag query instead of one per buddy.
  109. //
  110. // The map is owned by the session and must not be mutated by callers.
  111. //
  112. // aliasMu is deliberately held across the load rather than released while the
  113. // feedbag is queried. Another instance of the owner can rename a buddy mid-query,
  114. // and its FeedbagUpdateItem SNAC invalidates this cache; if the load ran outside
  115. // the lock, that query's pre-rename result could be stored *after* the
  116. // invalidation and serve the old alias until the next feedbag change. Holding the
  117. // lock makes the invalidation wait for the load and then win.
  118. func (s *WebAPISession) Aliases(ctx context.Context) map[string]string {
  119. s.aliasMu.Lock()
  120. defer s.aliasMu.Unlock()
  121. // The loader is wired after the session is created, so an event arriving in
  122. // that window has no way to resolve aliases.
  123. if s.BuddyAliasLoader == nil {
  124. return nil
  125. }
  126. if s.aliases == nil {
  127. aliases, err := s.BuddyAliasLoader(ctx)
  128. if err != nil {
  129. s.logger.Error("failed to load buddy aliases", "err", err.Error())
  130. return nil
  131. }
  132. s.aliases = aliases
  133. }
  134. return s.aliases
  135. }
  136. // InvalidateAliases drops the cached alias map so the next Aliases call reloads it.
  137. // Callers that change the owner's feedbag must call this: the feedbag service
  138. // relays FeedbagUpdateItem only to the owner's *other* instances, so a session
  139. // never sees a SNAC for its own writes.
  140. func (s *WebAPISession) InvalidateAliases() {
  141. s.aliasMu.Lock()
  142. defer s.aliasMu.Unlock()
  143. s.aliases = nil
  144. }
  145. // aliasFor returns this session owner's private alias for buddy, or "" when none is
  146. // set. The web client deletes the alias it holds whenever it merges a user map, so
  147. // every event naming a buddy has to repeat it.
  148. func (s *WebAPISession) aliasFor(buddy IdentScreenName) string {
  149. // Runs on the SNAC listener goroutine, which has no request context.
  150. return s.Aliases(s.ctx)[buddy.String()]
  151. }
  152. // Touch updates the last accessed time and extends expiration if needed.
  153. func (s *WebAPISession) Touch() {
  154. s.LastAccessed = time.Now()
  155. newExpiry := s.LastAccessed.Add(webAPISessionTTL)
  156. if newExpiry.After(s.ExpiresAt) {
  157. s.ExpiresAt = newExpiry
  158. }
  159. }
  160. // IsSubscribedTo checks if the session is subscribed to a specific event type.
  161. func (s *WebAPISession) IsSubscribedTo(eventType string) bool {
  162. for _, event := range s.Events {
  163. if event == eventType {
  164. return true
  165. }
  166. }
  167. return false
  168. }
  169. // StartListeningToOSCARSession starts a goroutine that listens to the OSCAR session's
  170. // message channel and converts SNAC messages into WebAPI events.
  171. func (s *WebAPISession) StartListeningToOSCARSession() {
  172. if s.OSCARSession == nil {
  173. return
  174. }
  175. s.closeMu.Lock()
  176. defer s.closeMu.Unlock()
  177. if s.closed {
  178. return
  179. }
  180. s.listeners.Add(1)
  181. go func() {
  182. defer s.listeners.Done()
  183. msgCh := s.OSCARSession.ReceiveMessage()
  184. for {
  185. select {
  186. case msg, ok := <-msgCh:
  187. if !ok {
  188. // Channel closed, OSCAR session ended
  189. return
  190. }
  191. s.handleSNACMessage(msg)
  192. case <-s.OSCARSession.Closed():
  193. // OSCAR session closed
  194. return
  195. }
  196. }
  197. }()
  198. }
  199. // Close tears down the session: it releases any parked event fetchers, closes
  200. // the OSCAR instance, and waits for the listener goroutine to unwind. Safe to
  201. // call more than once.
  202. func (s *WebAPISession) Close() {
  203. s.closeMu.Lock()
  204. if s.closed {
  205. s.closeMu.Unlock()
  206. return
  207. }
  208. s.closed = true
  209. s.closeMu.Unlock()
  210. s.EventQueue.Close()
  211. s.OSCARSession.CloseInstance()
  212. // Close every joined chat instance so each room announces the user's
  213. // departure and SignoutChat runs. Their listeners also observe s.ctx below,
  214. // but closing the instances is what tears down the room membership.
  215. // chatRoomsClosed is set under the same lock so a concurrent AddChatRoom that
  216. // arrives after this drain is turned away instead of re-adding an instance
  217. // this drain would never close.
  218. s.chatRoomsMu.Lock()
  219. for _, inst := range s.chatRooms {
  220. inst.CloseInstance()
  221. }
  222. s.chatRooms = nil
  223. s.chatRoomsClosed = true
  224. s.chatRoomsMu.Unlock()
  225. s.cancel()
  226. s.listeners.Wait()
  227. }
  228. // AddChatRoom registers a joined room's chat SessionInstance under its room id
  229. // (the ChatRoom cookie). Returns false if the session is already closing, in
  230. // which case the caller must close inst itself.
  231. func (s *WebAPISession) AddChatRoom(roomID string, inst *SessionInstance) bool {
  232. // The closed-check and the insert must be atomic with Close's drain, so both
  233. // run under chatRoomsMu. A nil map alone can't distinguish "closing" from
  234. // "never used yet", which is why Close sets chatRoomsClosed.
  235. s.chatRoomsMu.Lock()
  236. defer s.chatRoomsMu.Unlock()
  237. if s.chatRoomsClosed {
  238. return false
  239. }
  240. if s.chatRooms == nil {
  241. s.chatRooms = make(map[string]*SessionInstance)
  242. }
  243. s.chatRooms[roomID] = inst
  244. return true
  245. }
  246. // ChatRoom returns the chat SessionInstance for a joined room id, or false if
  247. // the session is not in that room. The web client addresses a room exactly like
  248. // a buddy, so this is how the im/sendIM path tells a room target from a buddy.
  249. func (s *WebAPISession) ChatRoom(roomID string) (*SessionInstance, bool) {
  250. s.chatRoomsMu.Lock()
  251. defer s.chatRoomsMu.Unlock()
  252. inst, ok := s.chatRooms[roomID]
  253. return inst, ok
  254. }
  255. // RemoveChatRoom unregisters a joined room and returns its chat SessionInstance
  256. // so the caller can close it. Returns false if the room was not joined.
  257. func (s *WebAPISession) RemoveChatRoom(roomID string) (*SessionInstance, bool) {
  258. s.chatRoomsMu.Lock()
  259. defer s.chatRoomsMu.Unlock()
  260. inst, ok := s.chatRooms[roomID]
  261. if ok {
  262. delete(s.chatRooms, roomID)
  263. }
  264. return inst, ok
  265. }
  266. // StartListeningToChatSession converts SNACs relayed to a joined room's chat
  267. // SessionInstance into web events on this session's queue. roomID is the room's
  268. // ChatRoom cookie, which the web client uses to key the conversation. The
  269. // goroutine exits when the chat instance closes (room left) or the web session is
  270. // torn down. closeMu is held across Add so a concurrent Close either observes the
  271. // listener or is observed by it — mirrors StartListeningToOSCARSession.
  272. func (s *WebAPISession) StartListeningToChatSession(roomID string, inst *SessionInstance) {
  273. s.closeMu.Lock()
  274. defer s.closeMu.Unlock()
  275. if s.closed {
  276. return
  277. }
  278. s.listeners.Add(1)
  279. go func() {
  280. defer s.listeners.Done()
  281. msgCh := inst.ReceiveMessage()
  282. for {
  283. select {
  284. case <-s.ctx.Done():
  285. return
  286. case <-inst.Closed():
  287. return
  288. case msg, ok := <-msgCh:
  289. if !ok {
  290. return
  291. }
  292. s.handleChatSNAC(roomID, msg)
  293. }
  294. }
  295. }()
  296. }
  297. // handleChatSNAC converts a SNAC relayed to a room's chat instance into a web
  298. // event. For MVP only chat messages are surfaced; participant join/leave tracking
  299. // is deferred with imserv/getMembers.
  300. func (s *WebAPISession) handleChatSNAC(roomID string, msg wire.SNACMessage) {
  301. if s.EventQueue == nil {
  302. return
  303. }
  304. if body, ok := msg.Body.(wire.SNAC_0x0E_0x06_ChatChannelMsgToClient); ok {
  305. s.handleRoomMessage(roomID, body)
  306. }
  307. }
  308. // handleRoomMessage pushes a relayed room line as an `im` event. The client keys
  309. // the conversation by the room id but reads the speaker and text from
  310. // specialData.imFromImserv, so both are populated here. See RoomIMEvent.
  311. func (s *WebAPISession) handleRoomMessage(roomID string, body wire.SNAC_0x0E_0x06_ChatChannelMsgToClient) {
  312. if !s.IsSubscribedTo("im") {
  313. return
  314. }
  315. senderInfo, ok := body.Bytes(wire.ChatTLVSenderInformation)
  316. if !ok {
  317. return
  318. }
  319. var userInfo wire.TLVUserInfo
  320. if err := wire.UnmarshalBE(&userInfo, bytes.NewReader(senderInfo)); err != nil {
  321. s.logger.Error("failed to unmarshal chat sender info", "err", err)
  322. return
  323. }
  324. msgInfo, ok := body.Bytes(wire.ChatTLVMessageInfo)
  325. if !ok {
  326. return
  327. }
  328. text, err := wire.UnmarshalChatMessageText(msgInfo)
  329. if err != nil {
  330. s.logger.Error("failed to unmarshal chat message text", "err", err)
  331. return
  332. }
  333. // The sender screen name is carried as its display form; the client keys the
  334. // speaker by the normalized aimId and renders the display form separately.
  335. speakerAimID := NewIdentScreenName(userInfo.ScreenName).String()
  336. s.PushRoomLine(roomID, speakerAimID, text)
  337. }
  338. // PushRoomLine queues a group-chat room line as an `im` event. roomID keys the
  339. // conversation; speakerAimID attributes the line to the participant who spoke.
  340. // Both the relay listener (incoming lines) and the send path (the sender's own
  341. // reflected line) funnel through here so every room line has the same shape the
  342. // client expects — see types.RoomIMEvent.
  343. func (s *WebAPISession) PushRoomLine(roomID, speakerAimID, text string) {
  344. if s.EventQueue == nil || !s.IsSubscribedTo("im") {
  345. return
  346. }
  347. s.EventQueue.Push(types.EventTypeIM, types.RoomIMEvent{
  348. Source: types.UserInfo{
  349. AimID: roomID,
  350. UserType: "aim",
  351. State: "online",
  352. },
  353. Imserv: roomID,
  354. SpecialIM: "imservMsg",
  355. SpecialData: types.RoomSpecialData{
  356. ImFromImserv: types.RoomImFrom{
  357. OrigSender: speakerAimID,
  358. Sender: speakerAimID,
  359. Text: text,
  360. },
  361. },
  362. Message: text,
  363. MsgID: strconv.FormatUint(mrand.Uint64(), 16),
  364. Timestamp: float64(time.Now().Unix()),
  365. })
  366. }
  367. // handleSNACMessage converts a SNAC message into WebAPI events and pushes them to the event queue.
  368. func (s *WebAPISession) handleSNACMessage(msg wire.SNACMessage) {
  369. if s.EventQueue == nil {
  370. return
  371. }
  372. // Convert SNAC message to WebAPI events based on food group and subgroup
  373. switch msg.Frame.FoodGroup {
  374. case wire.ICBM:
  375. s.handleICBMMessage(msg)
  376. case wire.Buddy:
  377. s.handleBuddyMessage(msg)
  378. case wire.Feedbag:
  379. s.handleFeedbagMessage(msg)
  380. case wire.OService:
  381. s.handleOServiceMessage(msg)
  382. }
  383. }
  384. // handleOServiceMessage handles OService SNAC messages relayed to the session's
  385. // own OSCAR instance. The only one we surface is OServiceUserInfoUpdate, which the
  386. // server relays to a user when their own user info changes (notably a buddy icon
  387. // upload or clear). The client re-renders its identity badge from myInfo events
  388. // only, so we translate this into a fresh myInfo.
  389. func (s *WebAPISession) handleOServiceMessage(msg wire.SNACMessage) {
  390. if msg.Frame.SubGroup != wire.OServiceUserInfoUpdate {
  391. return
  392. }
  393. if !s.IsSubscribedTo("myInfo") && !s.IsSubscribedTo("presence") {
  394. return
  395. }
  396. if s.MyInfoRefresher == nil {
  397. return
  398. }
  399. data, err := s.MyInfoRefresher(s.ctx)
  400. if err != nil {
  401. s.logger.Error("failed to refresh myInfo after user-info update", "err", err)
  402. return
  403. }
  404. s.EventQueue.Push(types.EventType("myInfo"), data)
  405. }
  406. // handleICBMMessage handles ICBM (instant messaging) SNAC messages.
  407. func (s *WebAPISession) handleICBMMessage(msg wire.SNACMessage) {
  408. switch msg.Frame.SubGroup {
  409. case wire.ICBMChannelMsgToClient:
  410. // A chat-room invitation arrives as a channel-2 rendezvous, not a plain
  411. // IM. Route it to the invite handler; everything else is a 1:1 message.
  412. if body, ok := msg.Body.(wire.SNAC_0x04_0x07_ICBMChannelMsgToClient); ok &&
  413. body.ChannelID == wire.ICBMChannelRendezvous {
  414. s.handleChatInvite(body)
  415. return
  416. }
  417. s.handleIncomingIM(msg)
  418. case wire.ICBMClientEvent:
  419. s.handleTypingNotification(msg)
  420. }
  421. }
  422. // handleChatInvite converts an incoming chat-room invitation (a channel-2
  423. // CapChat rendezvous) into an `im` event carrying specialData.invitation, which
  424. // is how the web client recognizes and can accept an invite (via imserv/join
  425. // with the room id). Non-chat rendezvous (file transfer, etc.) are ignored.
  426. func (s *WebAPISession) handleChatInvite(body wire.SNAC_0x04_0x07_ICBMChannelMsgToClient) {
  427. if !s.IsSubscribedTo("im") {
  428. return
  429. }
  430. rdinfo, ok := body.Bytes(wire.ICBMTLVData)
  431. if !ok {
  432. return
  433. }
  434. var frag wire.ICBMCh2Fragment
  435. if err := wire.UnmarshalBE(&frag, bytes.NewReader(rdinfo)); err != nil {
  436. return
  437. }
  438. if frag.Type != wire.ICBMRdvMessagePropose || uuid.UUID(frag.Capability) != wire.CapChat {
  439. return
  440. }
  441. svcData, ok := frag.Bytes(wire.ICBMRdvTLVTagsSvcData)
  442. if !ok {
  443. return
  444. }
  445. var roomInfo wire.ICBMRoomInfo
  446. if err := wire.UnmarshalBE(&roomInfo, bytes.NewReader(svcData)); err != nil {
  447. return
  448. }
  449. prompt, _ := frag.String(wire.ICBMRdvTLVTagsInvitation)
  450. inviterAimID := NewIdentScreenName(body.ScreenName).String()
  451. s.EventQueue.Push(types.EventTypeIM, types.RoomInviteEvent{
  452. Source: types.UserInfo{
  453. AimID: inviterAimID,
  454. UserType: "aim",
  455. State: "online",
  456. },
  457. Imserv: roomInfo.Cookie,
  458. Message: prompt,
  459. MsgID: strconv.FormatUint(mrand.Uint64(), 16),
  460. Timestamp: float64(time.Now().Unix()),
  461. SpecialData: types.RoomInviteSpecial{
  462. Invitation: types.RoomInvitation{
  463. From: body.ScreenName,
  464. GroupName: roomNameFromCookie(roomInfo.Cookie),
  465. },
  466. },
  467. })
  468. }
  469. // roomNameFromCookie returns the human room name embedded in a chat room cookie
  470. // of the form "<exchange>-<instance>-<name>". The name may itself contain "-",
  471. // so only the first two segments are split off. Falls back to the whole cookie.
  472. func roomNameFromCookie(cookie string) string {
  473. parts := strings.SplitN(cookie, "-", 3)
  474. if len(parts) < 3 {
  475. return cookie
  476. }
  477. return parts[2]
  478. }
  479. // handleIncomingIM handles incoming instant messages.
  480. func (s *WebAPISession) handleIncomingIM(msg wire.SNACMessage) {
  481. if !s.IsSubscribedTo("im") {
  482. return
  483. }
  484. body, ok := msg.Body.(wire.SNAC_0x04_0x07_ICBMChannelMsgToClient)
  485. if !ok {
  486. return
  487. }
  488. // Extract message text from TLV data
  489. var messageText string
  490. if msgData, hasMsg := body.Bytes(wire.ICBMTLVAOLIMData); hasMsg {
  491. if text, err := wire.UnmarshalICBMMessageText(msgData); err == nil {
  492. messageText = text
  493. }
  494. }
  495. if messageText == "" {
  496. return
  497. }
  498. // Check if it's an auto-response (channel 2)
  499. autoResponse := body.ChannelID == 0x0002
  500. // msgId must be unique per delivered event. The OSCAR cookie is not a
  501. // reliable unique id (some clients reuse it across messages), and the web
  502. // client dedupes its conversation list by msgId, silently dropping any
  503. // collisions. Mint a fresh random id instead of reusing body.Cookie.
  504. msgID := strconv.FormatUint(mrand.Uint64(), 16)
  505. // SNAC user info carries the sender's display screen name. The web client
  506. // keys conversations and users by the normalized aimId and only renders
  507. // displayId, so the two forms must not be interchanged.
  508. partnerDisplay := body.ScreenName
  509. partnerAimID := NewIdentScreenName(partnerDisplay).String()
  510. nowSec := time.Now().Unix()
  511. s.AddStoredIM(partnerAimID, partnerAimID, messageText, msgID, nowSec)
  512. // Create IM event
  513. imEvent := types.IMEvent{
  514. Source: types.UserInfo{
  515. AimID: partnerAimID,
  516. DisplayID: partnerDisplay,
  517. Friendly: s.aliasFor(NewIdentScreenName(partnerAimID)),
  518. UserType: "aim",
  519. State: "online",
  520. },
  521. Message: messageText,
  522. MsgID: msgID,
  523. Timestamp: float64(time.Now().Unix()),
  524. AutoResp: autoResponse,
  525. }
  526. s.EventQueue.Push(types.EventTypeIM, imEvent)
  527. s.logger.Debug("delivered instant message",
  528. "from", partnerDisplay,
  529. "to", s.ScreenName)
  530. if s.IsSubscribedTo("conversation") {
  531. // unread is 0 here, not 1, because the "im" event pushed above already
  532. // causes the client to increment its own persisted per-buddy unread
  533. // tally. The "Recent chats" badge is the sum of that persisted tally and
  534. // this conversation's unreadCount, so sending 1 here would double-count
  535. // the message (badge shows 2 for the first IM). Mirrors the sent-IM path,
  536. // which also passes 0.
  537. s.EventQueue.Push(types.EventTypeConversation, types.ConversationEventData("update", []map[string]interface{}{
  538. types.ConversationEntry(
  539. partnerAimID,
  540. partnerDisplay,
  541. messageText,
  542. msgID,
  543. partnerAimID,
  544. false,
  545. 0,
  546. ),
  547. }))
  548. }
  549. }
  550. // handleTypingNotification handles typing notifications.
  551. func (s *WebAPISession) handleTypingNotification(msg wire.SNACMessage) {
  552. if !s.IsSubscribedTo("typing") {
  553. return
  554. }
  555. body, ok := msg.Body.(wire.SNAC_0x04_0x14_ICBMClientEvent)
  556. if !ok {
  557. return
  558. }
  559. // Event types: 0x0000=none, 0x0001=typed (paused), 0x0002=typing
  560. var typingStatus string
  561. switch body.Event {
  562. case 0x0002:
  563. typingStatus = "typing"
  564. case 0x0001:
  565. typingStatus = "typed"
  566. default:
  567. typingStatus = "none"
  568. }
  569. typingEvent := types.TypingEvent{
  570. AimID: NewIdentScreenName(body.ScreenName).String(),
  571. TypingStatus: typingStatus,
  572. }
  573. s.EventQueue.Push(types.EventTypeTyping, typingEvent)
  574. }
  575. // handleBuddyMessage handles buddy/presence SNAC messages.
  576. func (s *WebAPISession) handleBuddyMessage(msg wire.SNACMessage) {
  577. switch msg.Frame.SubGroup {
  578. case wire.BuddyArrived:
  579. s.handleBuddyArrived(msg)
  580. case wire.BuddyDeparted:
  581. s.handleBuddyDeparted(msg)
  582. }
  583. }
  584. // handleBuddyArrived handles when a buddy comes online.
  585. func (s *WebAPISession) handleBuddyArrived(msg wire.SNACMessage) {
  586. if !s.IsSubscribedTo("presence") {
  587. return
  588. }
  589. body, ok := msg.Body.(wire.SNAC_0x03_0x0B_BuddyArrived)
  590. if !ok {
  591. return
  592. }
  593. stateStr := "online"
  594. // For BuddyArrived updates, infer presence state from the TLVUserInfo.
  595. // Away and invisible transitions are typically broadcast using BuddyArrived
  596. // with updated user flags/status bits, not BuddyDeparted.
  597. if body.IsInvisible() {
  598. stateStr = "offline"
  599. } else if body.IsAway() {
  600. stateStr = "away"
  601. } else if mask, ok := body.Uint32BE(wire.OServiceUserInfoStatus); ok {
  602. if mask&wire.OServiceUserStatusDND == wire.OServiceUserStatusDND {
  603. stateStr = "dnd"
  604. } else if mask&wire.OServiceUserStatusAway == wire.OServiceUserStatusAway {
  605. stateStr = "away"
  606. }
  607. }
  608. buddy := NewIdentScreenName(body.ScreenName)
  609. presenceEvent := types.PresenceEvent{
  610. AimID: buddy.String(),
  611. Friendly: s.aliasFor(buddy),
  612. State: stateStr,
  613. UserType: "aim",
  614. }
  615. // A BuddyArrived carries the buddy's current icon in TLV 0x1D whenever they
  616. // have one, so an icon change (or clear, which arrives as the sentinel hash)
  617. // rides along on the presence broadcast. Publish the matching URL: with an
  618. // icon it is content-addressed; without one it is the placeholder URL, which
  619. // differs from any prior icon URL and so clears a removed icon under the
  620. // client's shallow merge. An empty result (no origin known) is omitted, which
  621. // preserves whatever icon the client already holds.
  622. if s.BuddyIconURL != nil {
  623. var hash []byte
  624. if b, ok := body.Bytes(wire.OServiceUserInfoBARTInfo); ok {
  625. var id wire.BARTID
  626. if err := wire.UnmarshalBE(&id, bytes.NewBuffer(b)); err == nil {
  627. hash = id.Hash
  628. }
  629. }
  630. presenceEvent.BuddyIcon = s.BuddyIconURL(buddy, hash)
  631. }
  632. s.EventQueue.Push(types.EventTypePresence, presenceEvent)
  633. }
  634. // handleBuddyDeparted handles when a buddy goes offline.
  635. func (s *WebAPISession) handleBuddyDeparted(msg wire.SNACMessage) {
  636. if !s.IsSubscribedTo("presence") {
  637. return
  638. }
  639. body, ok := msg.Body.(wire.SNAC_0x03_0x0C_BuddyDeparted)
  640. if !ok {
  641. return
  642. }
  643. buddy := NewIdentScreenName(body.ScreenName)
  644. // BuddyIcon is deliberately omitted: an offline buddy keeps their icon, and
  645. // omitting it lets the client's merge preserve the icon it already holds.
  646. presenceEvent := types.PresenceEvent{
  647. AimID: buddy.String(),
  648. Friendly: s.aliasFor(buddy),
  649. State: "offline",
  650. UserType: "aim",
  651. }
  652. s.EventQueue.Push(types.EventTypePresence, presenceEvent)
  653. }
  654. func (s *WebAPISession) handleFeedbagMessage(msg wire.SNACMessage) {
  655. switch msg.Frame.SubGroup {
  656. case wire.FeedbagInsertItem, wire.FeedbagUpdateItem, wire.FeedbagDeleteItem:
  657. // A buddy item carries its alias, so any feedbag write can change the map.
  658. s.InvalidateAliases()
  659. if s.BuddyListRefresher != nil {
  660. groups, err := s.BuddyListRefresher(s.ctx)
  661. if err != nil {
  662. s.logger.Error("failed to refresh buddy list after feedbag change", "err", err)
  663. } else {
  664. s.EventQueue.Push(types.EventTypeBuddyList, map[string]interface{}{"groups": groups})
  665. }
  666. }
  667. if msg.Frame.SubGroup == wire.FeedbagUpdateItem && s.PermitDenyRefresher != nil {
  668. body, ok := msg.Body.(wire.SNAC_0x13_0x09_FeedbagUpdateItem)
  669. if ok {
  670. for _, item := range body.Items {
  671. if item.ClassID == wire.FeedbagClassIDPermit ||
  672. item.ClassID == wire.FeedbagClassIDDeny ||
  673. item.ClassID == wire.FeedbagClassIdPdinfo {
  674. pdd, err := s.PermitDenyRefresher(s.ctx)
  675. if err != nil {
  676. s.logger.Error("failed to refresh permit/deny after feedbag change", "err", err)
  677. } else {
  678. s.EventQueue.Push(types.EventTypePermitDeny, pdd)
  679. }
  680. break
  681. }
  682. }
  683. }
  684. }
  685. }
  686. }
  687. // WebAPISessionManager manages Web API sessions with thread-safe operations.
  688. // Construct it with NewWebAPISessionManager and drive its reaper with Run.
  689. type WebAPISessionManager struct {
  690. sessions map[string]*WebAPISession // Keyed by aimsid
  691. mu sync.RWMutex
  692. closed bool // set by Shutdown; rejects new sessions and makes drain idempotent
  693. stopCh chan struct{} // closed by Shutdown to stop the reaper
  694. reaperWG sync.WaitGroup // tracks a running reaper so Shutdown can join it
  695. }
  696. // NewWebAPISessionManager creates a new WebAPI session manager. It does not start
  697. // any goroutines; call Run to start reaping expired sessions.
  698. func NewWebAPISessionManager() *WebAPISessionManager {
  699. return &WebAPISessionManager{
  700. sessions: make(map[string]*WebAPISession),
  701. stopCh: make(chan struct{}),
  702. }
  703. }
  704. // CreateSession creates a new WebAPI session.
  705. //
  706. // The session does not begin listening to its OSCAR instance yet: the caller
  707. // must wire the session's refresher callbacks (BuddyListRefresher, BuddyIconURL,
  708. // MyInfoRefresher, ...) and then call StartListeningToOSCARSession. Wiring them
  709. // after the listener starts would race the goroutine, which reads them as it
  710. // converts SNACs into events.
  711. func (m *WebAPISessionManager) CreateSession(screenName DisplayScreenName, devID string, events []string, oscarSession *SessionInstance, baseURL string, logger *slog.Logger) (*WebAPISession, error) {
  712. m.mu.Lock()
  713. defer m.mu.Unlock()
  714. // Refuse to create sessions once shut down: the reaper is stopped, so a
  715. // session added now would never be closed or reaped.
  716. if m.closed {
  717. return nil, ErrWebAPISessionManagerClosed
  718. }
  719. // Generate unique session ID
  720. aimsid, err := generateSessionID()
  721. if err != nil {
  722. return nil, err
  723. }
  724. now := time.Now()
  725. sessCtx, sessCancel := context.WithCancel(context.Background())
  726. session := &WebAPISession{
  727. ctx: sessCtx,
  728. cancel: sessCancel,
  729. AimSID: aimsid,
  730. ScreenName: screenName,
  731. OSCARSession: oscarSession,
  732. BaseURL: baseURL,
  733. Events: events,
  734. EventQueue: types.NewEventQueue(1000), // Max 1000 events per session
  735. DevID: devID,
  736. CreatedAt: now,
  737. LastAccessed: now,
  738. ExpiresAt: now.Add(webAPISessionTTL),
  739. FetchTimeout: 60000, // 60 seconds default for better stability
  740. TimeToNextFetch: 500, // 500ms suggested delay
  741. logger: logger,
  742. }
  743. m.sessions[aimsid] = session
  744. // The caller starts the OSCAR listener (StartListeningToOSCARSession) once it
  745. // has wired the session's refresher callbacks; starting it here would race
  746. // those assignments.
  747. return session, nil
  748. }
  749. // GetSession retrieves a session by aimsid.
  750. func (m *WebAPISessionManager) GetSession(ctx context.Context, aimsid string) (*WebAPISession, error) {
  751. m.mu.RLock()
  752. defer m.mu.RUnlock()
  753. session, exists := m.sessions[aimsid]
  754. if !exists {
  755. return nil, ErrNoWebAPISession
  756. }
  757. if session.IsExpired() {
  758. return nil, ErrWebAPISessionExpired
  759. }
  760. return session, nil
  761. }
  762. // RemoveSession removes a session by aimsid.
  763. func (m *WebAPISessionManager) RemoveSession(ctx context.Context, aimsid string) error {
  764. m.mu.Lock()
  765. session, exists := m.sessions[aimsid]
  766. if !exists {
  767. m.mu.Unlock()
  768. return ErrNoWebAPISession
  769. }
  770. delete(m.sessions, aimsid)
  771. m.mu.Unlock()
  772. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  773. // broadcasts and signout, which we don't want to run under m.mu.
  774. session.Close()
  775. return nil
  776. }
  777. // TouchSession updates the last accessed time for a session.
  778. func (m *WebAPISessionManager) TouchSession(ctx context.Context, aimsid string) error {
  779. m.mu.Lock()
  780. defer m.mu.Unlock()
  781. session, exists := m.sessions[aimsid]
  782. if !exists {
  783. return ErrNoWebAPISession
  784. }
  785. session.Touch()
  786. return nil
  787. }
  788. // Run reaps expired sessions on a fixed interval until ctx is cancelled or
  789. // Shutdown is called. The caller owns the goroutine's lifecycle; typically
  790. // launch it under the server's errgroup:
  791. //
  792. // g.Go(func() error { mgr.Run(ctx); return nil })
  793. //
  794. // Run is a no-op once the manager is closed, so a reaper that loses the race
  795. // with Shutdown never starts reaping a drained manager.
  796. func (m *WebAPISessionManager) Run(ctx context.Context) {
  797. m.mu.Lock()
  798. if m.closed {
  799. m.mu.Unlock()
  800. return
  801. }
  802. // Registering under m.mu is what makes Shutdown's join sound: Shutdown flips
  803. // closed under the same lock, so a reaper either registers before Shutdown
  804. // waits or is turned away here.
  805. m.reaperWG.Add(1)
  806. m.mu.Unlock()
  807. defer m.reaperWG.Done()
  808. ticker := time.NewTicker(webAPISessionReapInterval)
  809. defer ticker.Stop()
  810. for {
  811. select {
  812. case <-ticker.C:
  813. m.reapExpired()
  814. case <-m.stopCh:
  815. return
  816. case <-ctx.Done():
  817. return
  818. }
  819. }
  820. }
  821. // reapExpired removes every expired session and tears it down.
  822. func (m *WebAPISessionManager) reapExpired() {
  823. m.mu.Lock()
  824. now := time.Now()
  825. var expired []*WebAPISession
  826. for aimsid, session := range m.sessions {
  827. if now.After(session.ExpiresAt) {
  828. delete(m.sessions, aimsid)
  829. expired = append(expired, session)
  830. }
  831. }
  832. m.mu.Unlock()
  833. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  834. // broadcasts and signout, which we don't want to run under m.mu.
  835. for _, session := range expired {
  836. session.Close()
  837. }
  838. }
  839. // Shutdown drains and closes all sessions, stops the reaper started by Run, and
  840. // blocks further CreateSession calls. It does not depend on the caller
  841. // cancelling Run's context. Safe to call more than once, though only the first
  842. // call waits for the drain. The drain is bounded by ctx: Shutdown returns
  843. // ctx.Err() rather than block forever on a listener that ignores cancellation.
  844. func (m *WebAPISessionManager) Shutdown(ctx context.Context) error {
  845. m.mu.Lock()
  846. if m.closed {
  847. m.mu.Unlock()
  848. return nil
  849. }
  850. m.closed = true
  851. close(m.stopCh)
  852. sessions := make([]*WebAPISession, 0, len(m.sessions))
  853. for _, session := range m.sessions {
  854. sessions = append(sessions, session)
  855. }
  856. // Clear all sessions
  857. m.sessions = make(map[string]*WebAPISession)
  858. m.mu.Unlock()
  859. drained := make(chan struct{})
  860. go func() {
  861. defer close(drained)
  862. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  863. // broadcasts and signout, which we don't want to run under m.mu.
  864. for _, session := range sessions {
  865. session.Close()
  866. }
  867. m.reaperWG.Wait()
  868. }()
  869. select {
  870. case <-drained:
  871. return nil
  872. case <-ctx.Done():
  873. return ctx.Err()
  874. }
  875. }
  876. // generateSessionID creates a cryptographically secure session ID.
  877. func generateSessionID() (string, error) {
  878. bytes := make([]byte, 32) // 256 bits
  879. if _, err := rand.Read(bytes); err != nil {
  880. return "", err
  881. }
  882. return hex.EncodeToString(bytes), nil
  883. }