webapi_session.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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. "sync"
  12. "time"
  13. "github.com/mk6i/open-oscar-server/server/webapi/types"
  14. "github.com/mk6i/open-oscar-server/wire"
  15. )
  16. var (
  17. // ErrNoWebAPISession is returned when a WebAPI session is not found.
  18. ErrNoWebAPISession = errors.New("WebAPI session not found")
  19. // ErrWebAPISessionExpired is returned when a WebAPI session has expired.
  20. ErrWebAPISessionExpired = errors.New("WebAPI session expired")
  21. // ErrWebAPISessionManagerClosed is returned when a session is requested from
  22. // a manager that has been shut down.
  23. ErrWebAPISessionManagerClosed = errors.New("WebAPI session manager is shut down")
  24. )
  25. // Web API session lifecycle timeline.
  26. //
  27. // A web client keeps its session alive by long-polling GET /aim/fetchEvents.
  28. // Every authenticated request touches the session (middleware.RequireSession
  29. // calls TouchSession at request arrival), sliding expiry to now + the TTL. A
  30. // single poll blocks for up to 60s (the fetchEvents long-poll cap) and the
  31. // client waits ~500ms (TimeToNextFetch) before re-polling, so in steady state a
  32. // healthy client touches the session at worst every ~60-65s once jitter is
  33. // included. That worst-case touch interval is the floor the TTL must clear.
  34. //
  35. // If a client hangs up without calling endSession, its last touch was at its
  36. // last poll: the session then expires webAPISessionTTL later and the reaper
  37. // sweeps it within one webAPISessionReapInterval tick. So a silent client is
  38. // removed (and its OSCAR session closed) within TTL + tick of going quiet.
  39. const (
  40. // webAPISessionTTL bounds how long a session survives without a poll. It is
  41. // sized to absorb one missed poll cycle: ~60s for the normal cycle, ~60s for
  42. // the absorbed miss, plus ~20s of jitter margin. Two consecutive misses mean
  43. // the client is genuinely gone and the session is reaped.
  44. webAPISessionTTL = 150 * time.Second
  45. // webAPISessionReapInterval is how often the cleanup goroutine sweeps for
  46. // expired sessions (~TTL/5). A dead session lingers at most
  47. // webAPISessionTTL + webAPISessionReapInterval before removal.
  48. webAPISessionReapInterval = 30 * time.Second
  49. )
  50. // WebAPISession represents an active Web AIM API session.
  51. type WebAPISession struct {
  52. AimSID string // Unique session ID for web client
  53. ScreenName DisplayScreenName // User identity
  54. OSCARSession *SessionInstance // Bridge to existing OSCAR session
  55. OSCARCookie []byte // OSCAR auth cookie for the startOSCARSession handoff
  56. BOSHost string // BOS host advertised to the web client
  57. BOSPort int // BOS port advertised to the web client
  58. UseSSL bool // Whether the handoff advertised an SSL BOS connection
  59. BaseURL string // Web API base URL advertised to the web client, used to build absolute asset URLs
  60. Events []string // Subscribed event types
  61. EventQueue *types.EventQueue // Per-session event queue
  62. DevID string // Developer ID that created this session
  63. ClientName string // Client application name
  64. ClientVersion string // Client application version
  65. CreatedAt time.Time // SessionInstance creation time
  66. LastAccessed time.Time // Last activity time
  67. ExpiresAt time.Time // SessionInstance expiration time
  68. FetchTimeout int // Long-polling timeout in milliseconds
  69. TimeToNextFetch int // Suggested delay before next fetch
  70. RemoteAddr string // Client IP address
  71. TempBuddies map[string]bool // Temporary buddies for this session only
  72. BuddyListRefresher func(ctx context.Context) (interface{}, error) // Called on feedbag changes to push buddylist event
  73. PermitDenyRefresher func(ctx context.Context) (interface{}, error) // Called on feedbag changes to push permitDeny event
  74. MyInfoRefresher func(ctx context.Context) (interface{}, error) // Called on self user-info updates (e.g. icon change) to push myInfo event
  75. BuddyAliasLoader func(ctx context.Context) (map[string]string, error)
  76. // BuddyIconURL formats the absolute buddyIcon URL for a buddy from the icon
  77. // hash carried in a presence SNAC. Returns "" when no URL can be published.
  78. BuddyIconURL func(screenName IdentScreenName, hash []byte) string
  79. aliases map[string]string // cached BuddyAliasLoader result, nil when unloaded or invalidated
  80. aliasMu sync.Mutex
  81. imLog map[string][]WebAPIStoredIM
  82. imLogMu sync.Mutex
  83. // rateAlertStatus is the rate limit status this client was last told about,
  84. // zero until it has been told anything. See ObserveRateAlert.
  85. rateAlertStatus wire.RateLimitStatus
  86. rateAlertMu sync.Mutex
  87. logger *slog.Logger // Logger for debugging
  88. listeners sync.WaitGroup
  89. ctx context.Context
  90. cancel context.CancelFunc
  91. closeMu sync.Mutex
  92. closed bool
  93. }
  94. // IsExpired checks if the session has expired.
  95. func (s *WebAPISession) IsExpired() bool {
  96. return time.Now().After(s.ExpiresAt)
  97. }
  98. // ObserveRateAlert records status as the rate limit status this web client was
  99. // last told about, and reports whether it differs from the one before it.
  100. //
  101. // The client's rate limit alert is sticky — it dismisses only on a "clear" that
  102. // follows a "limit" — so the server has to push exactly the transitions, and a
  103. // transition has to be measured per web client rather than off the OSCAR rate
  104. // state. That state belongs to the account, not to this session: a second
  105. // browser tab holds its own aimsid and its own WebAPISession over the same
  106. // state.Session, and an OSCAR client's ObserveRateChanges ticker runs against it
  107. // too. Any of them can consume a limited -> clear transition before this client
  108. // hears about it, which would leave this client's alert stuck up forever.
  109. func (s *WebAPISession) ObserveRateAlert(status wire.RateLimitStatus) bool {
  110. s.rateAlertMu.Lock()
  111. defer s.rateAlertMu.Unlock()
  112. prev := s.rateAlertStatus
  113. if prev == 0 {
  114. // A client that has been told nothing renders no alert, which is what
  115. // clear means.
  116. prev = wire.RateLimitStatusClear
  117. }
  118. if prev == status {
  119. return false
  120. }
  121. s.rateAlertStatus = status
  122. return true
  123. }
  124. // Aliases returns this session owner's private buddy aliases, keyed by normalized
  125. // screen name. Aliases live in the owner's feedbag, so the map is loaded once and
  126. // cached until a feedbag change invalidates it: a signon that brings a large buddy
  127. // list online costs one feedbag query instead of one per buddy.
  128. //
  129. // The map is owned by the session and must not be mutated by callers.
  130. //
  131. // aliasMu is deliberately held across the load rather than released while the
  132. // feedbag is queried. Another instance of the owner can rename a buddy mid-query,
  133. // and its FeedbagUpdateItem SNAC invalidates this cache; if the load ran outside
  134. // the lock, that query's pre-rename result could be stored *after* the
  135. // invalidation and serve the old alias until the next feedbag change. Holding the
  136. // lock makes the invalidation wait for the load and then win.
  137. func (s *WebAPISession) Aliases(ctx context.Context) map[string]string {
  138. s.aliasMu.Lock()
  139. defer s.aliasMu.Unlock()
  140. // The loader is wired after the session is created, so an event arriving in
  141. // that window has no way to resolve aliases.
  142. if s.BuddyAliasLoader == nil {
  143. return nil
  144. }
  145. if s.aliases == nil {
  146. aliases, err := s.BuddyAliasLoader(ctx)
  147. if err != nil {
  148. s.logger.Error("failed to load buddy aliases", "err", err.Error())
  149. return nil
  150. }
  151. s.aliases = aliases
  152. }
  153. return s.aliases
  154. }
  155. // InvalidateAliases drops the cached alias map so the next Aliases call reloads it.
  156. // Callers that change the owner's feedbag must call this: the feedbag service
  157. // relays FeedbagUpdateItem only to the owner's *other* instances, so a session
  158. // never sees a SNAC for its own writes.
  159. func (s *WebAPISession) InvalidateAliases() {
  160. s.aliasMu.Lock()
  161. defer s.aliasMu.Unlock()
  162. s.aliases = nil
  163. }
  164. // aliasFor returns this session owner's private alias for buddy, or "" when none is
  165. // set. The web client deletes the alias it holds whenever it merges a user map, so
  166. // every event naming a buddy has to repeat it.
  167. func (s *WebAPISession) aliasFor(buddy IdentScreenName) string {
  168. // Runs on the SNAC listener goroutine, which has no request context.
  169. return s.Aliases(s.ctx)[buddy.String()]
  170. }
  171. // Touch updates the last accessed time and extends expiration if needed.
  172. func (s *WebAPISession) Touch() {
  173. s.LastAccessed = time.Now()
  174. newExpiry := s.LastAccessed.Add(webAPISessionTTL)
  175. if newExpiry.After(s.ExpiresAt) {
  176. s.ExpiresAt = newExpiry
  177. }
  178. }
  179. // IsSubscribedTo checks if the session is subscribed to a specific event type.
  180. func (s *WebAPISession) IsSubscribedTo(eventType string) bool {
  181. for _, event := range s.Events {
  182. if event == eventType {
  183. return true
  184. }
  185. }
  186. return false
  187. }
  188. // StartListeningToOSCARSession starts a goroutine that listens to the OSCAR session's
  189. // message channel and converts SNAC messages into WebAPI events.
  190. func (s *WebAPISession) StartListeningToOSCARSession() {
  191. if s.OSCARSession == nil {
  192. return
  193. }
  194. s.closeMu.Lock()
  195. defer s.closeMu.Unlock()
  196. if s.closed {
  197. return
  198. }
  199. s.listeners.Add(1)
  200. go func() {
  201. defer s.listeners.Done()
  202. msgCh := s.OSCARSession.ReceiveMessage()
  203. for {
  204. select {
  205. case msg, ok := <-msgCh:
  206. if !ok {
  207. // Channel closed, OSCAR session ended
  208. return
  209. }
  210. s.handleSNACMessage(msg)
  211. case <-s.OSCARSession.Closed():
  212. // OSCAR session closed
  213. return
  214. }
  215. }
  216. }()
  217. }
  218. // Close tears down the session: it releases any parked event fetchers, closes
  219. // the OSCAR instance, and waits for the listener goroutine to unwind. Safe to
  220. // call more than once.
  221. func (s *WebAPISession) Close() {
  222. s.closeMu.Lock()
  223. if s.closed {
  224. s.closeMu.Unlock()
  225. return
  226. }
  227. s.closed = true
  228. s.closeMu.Unlock()
  229. s.EventQueue.Close()
  230. s.OSCARSession.CloseInstance()
  231. s.cancel()
  232. s.listeners.Wait()
  233. }
  234. // handleSNACMessage converts a SNAC message into WebAPI events and pushes them to the event queue.
  235. func (s *WebAPISession) handleSNACMessage(msg wire.SNACMessage) {
  236. if s.EventQueue == nil {
  237. return
  238. }
  239. // Convert SNAC message to WebAPI events based on food group and subgroup
  240. switch msg.Frame.FoodGroup {
  241. case wire.ICBM:
  242. s.handleICBMMessage(msg)
  243. case wire.Buddy:
  244. s.handleBuddyMessage(msg)
  245. case wire.Feedbag:
  246. s.handleFeedbagMessage(msg)
  247. case wire.OService:
  248. s.handleOServiceMessage(msg)
  249. }
  250. }
  251. // handleOServiceMessage handles OService SNAC messages relayed to the session's
  252. // own OSCAR instance. The only one we surface is OServiceUserInfoUpdate, which the
  253. // server relays to a user when their own user info changes (notably a buddy icon
  254. // upload or clear). The client re-renders its identity badge from myInfo events
  255. // only, so we translate this into a fresh myInfo.
  256. func (s *WebAPISession) handleOServiceMessage(msg wire.SNACMessage) {
  257. if msg.Frame.SubGroup != wire.OServiceUserInfoUpdate {
  258. return
  259. }
  260. if !s.IsSubscribedTo("myInfo") && !s.IsSubscribedTo("presence") {
  261. return
  262. }
  263. if s.MyInfoRefresher == nil {
  264. return
  265. }
  266. data, err := s.MyInfoRefresher(s.ctx)
  267. if err != nil {
  268. s.logger.Error("failed to refresh myInfo after user-info update", "err", err)
  269. return
  270. }
  271. s.EventQueue.Push(types.EventType("myInfo"), data)
  272. }
  273. // handleICBMMessage handles ICBM (instant messaging) SNAC messages.
  274. func (s *WebAPISession) handleICBMMessage(msg wire.SNACMessage) {
  275. switch msg.Frame.SubGroup {
  276. case wire.ICBMChannelMsgToClient:
  277. s.handleIncomingIM(msg)
  278. case wire.ICBMClientEvent:
  279. s.handleTypingNotification(msg)
  280. }
  281. }
  282. // handleIncomingIM handles incoming instant messages.
  283. func (s *WebAPISession) handleIncomingIM(msg wire.SNACMessage) {
  284. if !s.IsSubscribedTo("im") {
  285. return
  286. }
  287. body, ok := msg.Body.(wire.SNAC_0x04_0x07_ICBMChannelMsgToClient)
  288. if !ok {
  289. return
  290. }
  291. // Extract message text from TLV data
  292. var messageText string
  293. if msgData, hasMsg := body.Bytes(wire.ICBMTLVAOLIMData); hasMsg {
  294. if text, err := wire.UnmarshalICBMMessageText(msgData); err == nil {
  295. messageText = text
  296. }
  297. }
  298. if messageText == "" {
  299. return
  300. }
  301. // Check if it's an auto-response (channel 2)
  302. autoResponse := body.ChannelID == 0x0002
  303. // msgId must be unique per delivered event. The OSCAR cookie is not a
  304. // reliable unique id (some clients reuse it across messages), and the web
  305. // client dedupes its conversation list by msgId, silently dropping any
  306. // collisions. Mint a fresh random id instead of reusing body.Cookie.
  307. msgID := strconv.FormatUint(mrand.Uint64(), 16)
  308. // SNAC user info carries the sender's display screen name. The web client
  309. // keys conversations and users by the normalized aimId and only renders
  310. // displayId, so the two forms must not be interchanged.
  311. partnerDisplay := body.ScreenName
  312. partnerAimID := NewIdentScreenName(partnerDisplay).String()
  313. nowSec := time.Now().Unix()
  314. s.AddStoredIM(partnerAimID, partnerAimID, messageText, msgID, nowSec)
  315. // Create IM event
  316. imEvent := types.IMEvent{
  317. Source: types.UserInfo{
  318. AimID: partnerAimID,
  319. DisplayID: partnerDisplay,
  320. Friendly: s.aliasFor(NewIdentScreenName(partnerAimID)),
  321. UserType: "aim",
  322. State: "online",
  323. },
  324. Message: messageText,
  325. MsgID: msgID,
  326. Timestamp: float64(time.Now().Unix()),
  327. AutoResp: autoResponse,
  328. }
  329. s.EventQueue.Push(types.EventTypeIM, imEvent)
  330. s.logger.Debug("delivered instant message",
  331. "from", partnerDisplay,
  332. "to", s.ScreenName)
  333. if s.IsSubscribedTo("conversation") {
  334. // unread is 0 here, not 1, because the "im" event pushed above already
  335. // causes the client to increment its own persisted per-buddy unread
  336. // tally. The "Recent chats" badge is the sum of that persisted tally and
  337. // this conversation's unreadCount, so sending 1 here would double-count
  338. // the message (badge shows 2 for the first IM). Mirrors the sent-IM path,
  339. // which also passes 0.
  340. s.EventQueue.Push(types.EventTypeConversation, types.ConversationEventData("update", []map[string]interface{}{
  341. types.ConversationEntry(
  342. partnerAimID,
  343. partnerDisplay,
  344. messageText,
  345. msgID,
  346. partnerAimID,
  347. false,
  348. 0,
  349. ),
  350. }))
  351. }
  352. }
  353. // handleTypingNotification handles typing notifications.
  354. func (s *WebAPISession) handleTypingNotification(msg wire.SNACMessage) {
  355. if !s.IsSubscribedTo("typing") {
  356. return
  357. }
  358. body, ok := msg.Body.(wire.SNAC_0x04_0x14_ICBMClientEvent)
  359. if !ok {
  360. return
  361. }
  362. // Event types: 0x0000=none, 0x0001=typed (paused), 0x0002=typing
  363. var typingStatus string
  364. switch body.Event {
  365. case 0x0002:
  366. typingStatus = "typing"
  367. case 0x0001:
  368. typingStatus = "typed"
  369. default:
  370. typingStatus = "none"
  371. }
  372. typingEvent := types.TypingEvent{
  373. AimID: NewIdentScreenName(body.ScreenName).String(),
  374. TypingStatus: typingStatus,
  375. }
  376. s.EventQueue.Push(types.EventTypeTyping, typingEvent)
  377. }
  378. // handleBuddyMessage handles buddy/presence SNAC messages.
  379. func (s *WebAPISession) handleBuddyMessage(msg wire.SNACMessage) {
  380. switch msg.Frame.SubGroup {
  381. case wire.BuddyArrived:
  382. s.handleBuddyArrived(msg)
  383. case wire.BuddyDeparted:
  384. s.handleBuddyDeparted(msg)
  385. }
  386. }
  387. // handleBuddyArrived handles when a buddy comes online.
  388. func (s *WebAPISession) handleBuddyArrived(msg wire.SNACMessage) {
  389. if !s.IsSubscribedTo("presence") {
  390. return
  391. }
  392. body, ok := msg.Body.(wire.SNAC_0x03_0x0B_BuddyArrived)
  393. if !ok {
  394. return
  395. }
  396. stateStr := "online"
  397. // For BuddyArrived updates, infer presence state from the TLVUserInfo.
  398. // Away and invisible transitions are typically broadcast using BuddyArrived
  399. // with updated user flags/status bits, not BuddyDeparted.
  400. if body.IsInvisible() {
  401. stateStr = "offline"
  402. } else if body.IsAway() {
  403. stateStr = "away"
  404. } else if mask, ok := body.Uint32BE(wire.OServiceUserInfoStatus); ok {
  405. if mask&wire.OServiceUserStatusDND == wire.OServiceUserStatusDND {
  406. stateStr = "dnd"
  407. } else if mask&wire.OServiceUserStatusAway == wire.OServiceUserStatusAway {
  408. stateStr = "away"
  409. }
  410. }
  411. buddy := NewIdentScreenName(body.ScreenName)
  412. presenceEvent := types.PresenceEvent{
  413. AimID: buddy.String(),
  414. Friendly: s.aliasFor(buddy),
  415. State: stateStr,
  416. UserType: "aim",
  417. }
  418. // A BuddyArrived carries the buddy's current icon in TLV 0x1D whenever they
  419. // have one, so an icon change (or clear, which arrives as the sentinel hash)
  420. // rides along on the presence broadcast. Publish the matching URL: with an
  421. // icon it is content-addressed; without one it is the placeholder URL, which
  422. // differs from any prior icon URL and so clears a removed icon under the
  423. // client's shallow merge. An empty result (no origin known) is omitted, which
  424. // preserves whatever icon the client already holds.
  425. if s.BuddyIconURL != nil {
  426. var hash []byte
  427. if b, ok := body.Bytes(wire.OServiceUserInfoBARTInfo); ok {
  428. var id wire.BARTID
  429. if err := wire.UnmarshalBE(&id, bytes.NewBuffer(b)); err == nil {
  430. hash = id.Hash
  431. }
  432. }
  433. presenceEvent.BuddyIcon = s.BuddyIconURL(buddy, hash)
  434. }
  435. s.EventQueue.Push(types.EventTypePresence, presenceEvent)
  436. }
  437. // handleBuddyDeparted handles when a buddy goes offline.
  438. func (s *WebAPISession) handleBuddyDeparted(msg wire.SNACMessage) {
  439. if !s.IsSubscribedTo("presence") {
  440. return
  441. }
  442. body, ok := msg.Body.(wire.SNAC_0x03_0x0C_BuddyDeparted)
  443. if !ok {
  444. return
  445. }
  446. buddy := NewIdentScreenName(body.ScreenName)
  447. // BuddyIcon is deliberately omitted: an offline buddy keeps their icon, and
  448. // omitting it lets the client's merge preserve the icon it already holds.
  449. presenceEvent := types.PresenceEvent{
  450. AimID: buddy.String(),
  451. Friendly: s.aliasFor(buddy),
  452. State: "offline",
  453. UserType: "aim",
  454. }
  455. s.EventQueue.Push(types.EventTypePresence, presenceEvent)
  456. }
  457. func (s *WebAPISession) handleFeedbagMessage(msg wire.SNACMessage) {
  458. switch msg.Frame.SubGroup {
  459. case wire.FeedbagInsertItem, wire.FeedbagUpdateItem, wire.FeedbagDeleteItem:
  460. // A buddy item carries its alias, so any feedbag write can change the map.
  461. s.InvalidateAliases()
  462. if s.BuddyListRefresher != nil {
  463. groups, err := s.BuddyListRefresher(s.ctx)
  464. if err != nil {
  465. s.logger.Error("failed to refresh buddy list after feedbag change", "err", err)
  466. } else {
  467. s.EventQueue.Push(types.EventTypeBuddyList, map[string]interface{}{"groups": groups})
  468. }
  469. }
  470. if msg.Frame.SubGroup == wire.FeedbagUpdateItem && s.PermitDenyRefresher != nil {
  471. body, ok := msg.Body.(wire.SNAC_0x13_0x09_FeedbagUpdateItem)
  472. if ok {
  473. for _, item := range body.Items {
  474. if item.ClassID == wire.FeedbagClassIDPermit ||
  475. item.ClassID == wire.FeedbagClassIDDeny ||
  476. item.ClassID == wire.FeedbagClassIdPdinfo {
  477. pdd, err := s.PermitDenyRefresher(s.ctx)
  478. if err != nil {
  479. s.logger.Error("failed to refresh permit/deny after feedbag change", "err", err)
  480. } else {
  481. s.EventQueue.Push(types.EventTypePermitDeny, pdd)
  482. }
  483. break
  484. }
  485. }
  486. }
  487. }
  488. }
  489. }
  490. // WebAPISessionManager manages Web API sessions with thread-safe operations.
  491. // Construct it with NewWebAPISessionManager and drive its reaper with Run.
  492. type WebAPISessionManager struct {
  493. sessions map[string]*WebAPISession // Keyed by aimsid
  494. mu sync.RWMutex
  495. closed bool // set by Shutdown; rejects new sessions and makes drain idempotent
  496. stopCh chan struct{} // closed by Shutdown to stop the reaper
  497. reaperWG sync.WaitGroup // tracks a running reaper so Shutdown can join it
  498. }
  499. // NewWebAPISessionManager creates a new WebAPI session manager. It does not start
  500. // any goroutines; call Run to start reaping expired sessions.
  501. func NewWebAPISessionManager() *WebAPISessionManager {
  502. return &WebAPISessionManager{
  503. sessions: make(map[string]*WebAPISession),
  504. stopCh: make(chan struct{}),
  505. }
  506. }
  507. // CreateSession creates a new WebAPI session.
  508. //
  509. // The session does not begin listening to its OSCAR instance yet: the caller
  510. // must wire the session's refresher callbacks (BuddyListRefresher, BuddyIconURL,
  511. // MyInfoRefresher, ...) and then call StartListeningToOSCARSession. Wiring them
  512. // after the listener starts would race the goroutine, which reads them as it
  513. // converts SNACs into events.
  514. func (m *WebAPISessionManager) CreateSession(screenName DisplayScreenName, devID string, events []string, oscarSession *SessionInstance, baseURL string, logger *slog.Logger) (*WebAPISession, error) {
  515. m.mu.Lock()
  516. defer m.mu.Unlock()
  517. // Refuse to create sessions once shut down: the reaper is stopped, so a
  518. // session added now would never be closed or reaped.
  519. if m.closed {
  520. return nil, ErrWebAPISessionManagerClosed
  521. }
  522. // Generate unique session ID
  523. aimsid, err := generateSessionID()
  524. if err != nil {
  525. return nil, err
  526. }
  527. now := time.Now()
  528. sessCtx, sessCancel := context.WithCancel(context.Background())
  529. session := &WebAPISession{
  530. ctx: sessCtx,
  531. cancel: sessCancel,
  532. AimSID: aimsid,
  533. ScreenName: screenName,
  534. OSCARSession: oscarSession,
  535. BaseURL: baseURL,
  536. Events: events,
  537. EventQueue: types.NewEventQueue(1000), // Max 1000 events per session
  538. DevID: devID,
  539. CreatedAt: now,
  540. LastAccessed: now,
  541. ExpiresAt: now.Add(webAPISessionTTL),
  542. FetchTimeout: 60000, // 60 seconds default for better stability
  543. TimeToNextFetch: 500, // 500ms suggested delay
  544. logger: logger,
  545. }
  546. m.sessions[aimsid] = session
  547. // The caller starts the OSCAR listener (StartListeningToOSCARSession) once it
  548. // has wired the session's refresher callbacks; starting it here would race
  549. // those assignments.
  550. return session, nil
  551. }
  552. // GetSession retrieves a session by aimsid.
  553. func (m *WebAPISessionManager) GetSession(ctx context.Context, aimsid string) (*WebAPISession, error) {
  554. m.mu.RLock()
  555. defer m.mu.RUnlock()
  556. session, exists := m.sessions[aimsid]
  557. if !exists {
  558. return nil, ErrNoWebAPISession
  559. }
  560. if session.IsExpired() {
  561. return nil, ErrWebAPISessionExpired
  562. }
  563. // A rate-limit disconnect (EvaluateRateLimit -> Session.CloseSession) closes
  564. // every instance for the account while this web session is still unexpired.
  565. // The aimsid must stop resolving at that point, otherwise a client told to
  566. // disconnect could keep issuing charged requests against a dead session (the
  567. // reaper only removes it on time expiry, up to a TTL later).
  568. if session.OSCARSession != nil && session.OSCARSession.IsClosed() {
  569. return nil, ErrWebAPISessionExpired
  570. }
  571. return session, nil
  572. }
  573. // RemoveSession removes a session by aimsid.
  574. func (m *WebAPISessionManager) RemoveSession(ctx context.Context, aimsid string) error {
  575. m.mu.Lock()
  576. session, exists := m.sessions[aimsid]
  577. if !exists {
  578. m.mu.Unlock()
  579. return ErrNoWebAPISession
  580. }
  581. delete(m.sessions, aimsid)
  582. m.mu.Unlock()
  583. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  584. // broadcasts and signout, which we don't want to run under m.mu.
  585. session.Close()
  586. return nil
  587. }
  588. // TouchSession updates the last accessed time for a session.
  589. func (m *WebAPISessionManager) TouchSession(ctx context.Context, aimsid string) error {
  590. m.mu.Lock()
  591. defer m.mu.Unlock()
  592. session, exists := m.sessions[aimsid]
  593. if !exists {
  594. return ErrNoWebAPISession
  595. }
  596. session.Touch()
  597. return nil
  598. }
  599. // Run reaps expired sessions on a fixed interval until ctx is cancelled or
  600. // Shutdown is called. The caller owns the goroutine's lifecycle; typically
  601. // launch it under the server's errgroup:
  602. //
  603. // g.Go(func() error { mgr.Run(ctx); return nil })
  604. //
  605. // Run is a no-op once the manager is closed, so a reaper that loses the race
  606. // with Shutdown never starts reaping a drained manager.
  607. func (m *WebAPISessionManager) Run(ctx context.Context) {
  608. m.mu.Lock()
  609. if m.closed {
  610. m.mu.Unlock()
  611. return
  612. }
  613. // Registering under m.mu is what makes Shutdown's join sound: Shutdown flips
  614. // closed under the same lock, so a reaper either registers before Shutdown
  615. // waits or is turned away here.
  616. m.reaperWG.Add(1)
  617. m.mu.Unlock()
  618. defer m.reaperWG.Done()
  619. ticker := time.NewTicker(webAPISessionReapInterval)
  620. defer ticker.Stop()
  621. for {
  622. select {
  623. case <-ticker.C:
  624. m.reapExpired()
  625. case <-m.stopCh:
  626. return
  627. case <-ctx.Done():
  628. return
  629. }
  630. }
  631. }
  632. // reapExpired removes every dead session and tears it down. A session is dead
  633. // once it has passed its expiry, or once its underlying OSCAR session has been
  634. // closed out from under it (e.g. by a rate-limit disconnect) — the latter is
  635. // already rejected by GetSession, and reaping it here frees the entry promptly
  636. // rather than leaving it until time expiry.
  637. func (m *WebAPISessionManager) reapExpired() {
  638. m.mu.Lock()
  639. now := time.Now()
  640. var expired []*WebAPISession
  641. for aimsid, session := range m.sessions {
  642. if now.After(session.ExpiresAt) || (session.OSCARSession != nil && session.OSCARSession.IsClosed()) {
  643. delete(m.sessions, aimsid)
  644. expired = append(expired, session)
  645. }
  646. }
  647. m.mu.Unlock()
  648. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  649. // broadcasts and signout, which we don't want to run under m.mu.
  650. for _, session := range expired {
  651. session.Close()
  652. }
  653. }
  654. // Shutdown drains and closes all sessions, stops the reaper started by Run, and
  655. // blocks further CreateSession calls. It does not depend on the caller
  656. // cancelling Run's context. Safe to call more than once, though only the first
  657. // call waits for the drain. The drain is bounded by ctx: Shutdown returns
  658. // ctx.Err() rather than block forever on a listener that ignores cancellation.
  659. func (m *WebAPISessionManager) Shutdown(ctx context.Context) error {
  660. m.mu.Lock()
  661. if m.closed {
  662. m.mu.Unlock()
  663. return nil
  664. }
  665. m.closed = true
  666. close(m.stopCh)
  667. sessions := make([]*WebAPISession, 0, len(m.sessions))
  668. for _, session := range m.sessions {
  669. sessions = append(sessions, session)
  670. }
  671. // Clear all sessions
  672. m.sessions = make(map[string]*WebAPISession)
  673. m.mu.Unlock()
  674. drained := make(chan struct{})
  675. go func() {
  676. defer close(drained)
  677. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  678. // broadcasts and signout, which we don't want to run under m.mu.
  679. for _, session := range sessions {
  680. session.Close()
  681. }
  682. m.reaperWG.Wait()
  683. }()
  684. select {
  685. case <-drained:
  686. return nil
  687. case <-ctx.Done():
  688. return ctx.Err()
  689. }
  690. }
  691. // generateSessionID creates a cryptographically secure session ID.
  692. func generateSessionID() (string, error) {
  693. bytes := make([]byte, 32) // 256 bits
  694. if _, err := rand.Read(bytes); err != nil {
  695. return "", err
  696. }
  697. return hex.EncodeToString(bytes), nil
  698. }