session.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. package handlers
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "log/slog"
  7. "net/http"
  8. "slices"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/google/uuid"
  13. "github.com/mk6i/open-oscar-server/server/webapi/middleware"
  14. "github.com/mk6i/open-oscar-server/server/webapi/types"
  15. "github.com/mk6i/open-oscar-server/state"
  16. "github.com/mk6i/open-oscar-server/wire"
  17. )
  18. // SessionHandler handles Web AIM API session management endpoints.
  19. type SessionHandler struct {
  20. SessionManager *state.WebAPISessionManager
  21. OSCARAuthService AuthService
  22. FeedbagService FeedbagService
  23. ICBMService ICBMService
  24. BuddyListManager *BuddyListManager
  25. IconSource BuddyIconSource
  26. Logger *slog.Logger
  27. OServiceService OServiceService
  28. // the same SNAC-to-rate-class mapping RateLimitMiddleware enforces against, so
  29. // the class a session alerts on cannot drift from the one it is charged
  30. SNACRateLimits wire.SNACRateLimits
  31. FnSessCfg func(sess *state.Session)
  32. FnSessInit func(instance *state.SessionInstance) func() error
  33. FnInstanceClose func(instance *state.SessionInstance) func()
  34. }
  35. // AuthService defines methods needed for authentication.
  36. type AuthService interface {
  37. BUCPChallenge(ctx context.Context, bodyIn wire.SNAC_0x17_0x06_BUCPChallengeRequest, newUUID func() uuid.UUID) (wire.SNACMessage, error)
  38. BUCPLogin(ctx context.Context, bodyIn wire.SNAC_0x17_0x02_BUCPLoginRequest, advertisedHost string) (wire.SNACMessage, error)
  39. CrackCookie(authCookie []byte) (state.ServerCookie, error)
  40. RegisterBOSSession(ctx context.Context, authCookie state.ServerCookie, conf func(sess *state.Session)) (*state.SessionInstance, error)
  41. FLAPLogin(ctx context.Context, inFrame wire.FLAPSignonFrame, advertisedHost string) (wire.TLVRestBlock, error)
  42. Signout(ctx context.Context, session *state.Session)
  43. SignoutChat(ctx context.Context, sess *state.Session)
  44. }
  45. // SessionManager defines methods for OSCAR session management.
  46. type SessionManager interface {
  47. AddSession(ctx context.Context, screenName state.DisplayScreenName, doMultiSess bool, cfg ...func(sess *state.Session)) (*state.SessionInstance, error)
  48. RemoveSession(session *state.Session)
  49. RelayToScreenName(ctx context.Context, screenName state.IdentScreenName, msg wire.SNACMessage)
  50. }
  51. // BuddyListRegistry defines methods for buddy list management.
  52. type BuddyListRegistry interface {
  53. RegisterBuddyList(ctx context.Context, screenName state.IdentScreenName) error
  54. UnregisterBuddyList(ctx context.Context, screenName state.IdentScreenName) error
  55. }
  56. type ChatSessionManager interface {
  57. RemoveUserFromAllChats(user state.IdentScreenName)
  58. }
  59. // MyInfo is the user's own identity blob, which the Web AIM client renders in
  60. // its identity badge. It is both the startSession payload's myInfo and the
  61. // myInfo event's data.
  62. type MyInfo struct {
  63. AimID string `json:"aimId" xml:"aimId"`
  64. DisplayID string `json:"displayId" xml:"displayId"`
  65. Friendly string `json:"friendly" xml:"friendly"`
  66. State string `json:"state" xml:"state"`
  67. UserType string `json:"userType" xml:"userType"` // "aim", "icq"
  68. Bot bool `json:"bot" xml:"bot"`
  69. Service string `json:"service" xml:"service"` // "AIM", "ICQ" (compared case-sensitively)
  70. // Capabilities is always sent, empty included, because the client iterates it
  71. // unconditionally.
  72. Capabilities []string `json:"capabilities" xml:"capabilities>capability"`
  73. // BuddyIcon is omitted when empty so the client's merge preserves the icon it
  74. // already holds.
  75. BuddyIcon string `json:"buddyIcon,omitempty" xml:"buddyIcon,omitempty"`
  76. AwayMsg string `json:"awayMsg,omitempty" xml:"awayMsg,omitempty"`
  77. StatusMsg string `json:"statusMsg,omitempty" xml:"statusMsg,omitempty"`
  78. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"`
  79. MemberSince int64 `json:"memberSince,omitempty" xml:"memberSince,omitempty"`
  80. Self *MyInfoSelf `json:"self,omitempty" xml:"self,omitempty"`
  81. }
  82. // MyInfoSelf carries the session-scoped half of myInfo: the instance the client
  83. // is talking to and the limits it must respect.
  84. type MyInfoSelf struct {
  85. InstNum int `json:"instNum" xml:"instNum"`
  86. LoginTime int64 `json:"loginTime" xml:"loginTime"`
  87. SessionTimeout int `json:"sessionTimeout" xml:"sessionTimeout"`
  88. Events []string `json:"events" xml:"events>event"`
  89. AssertCaps []string `json:"assertCaps" xml:"assertCaps>capability"`
  90. RightsInfo RightsInfo `json:"rightsInfo" xml:"rightsInfo"`
  91. }
  92. // RightsInfo reports the account limits the client enforces client-side.
  93. type RightsInfo struct {
  94. MaxDenies int `json:"maxDenies" xml:"maxDenies"`
  95. MaxPermits int `json:"maxPermits" xml:"maxPermits"`
  96. MaxWatchers int `json:"maxWatchers" xml:"maxWatchers"`
  97. MaxBuddies int `json:"maxBuddies" xml:"maxBuddies"`
  98. MaxTempBuddies int `json:"maxTempBuddies" xml:"maxTempBuddies"`
  99. MaxIMSize int `json:"maxIMSize" xml:"maxIMSize"`
  100. MinInterIcbmInterval int `json:"minInterIcbmInterval" xml:"minInterIcbmInterval"`
  101. MaxSourceEvil int `json:"maxSourceEvil" xml:"maxSourceEvil"`
  102. MaxDstEvil int `json:"maxDstEvil" xml:"maxDstEvil"`
  103. MaxSigLen int `json:"maxSigLen" xml:"maxSigLen"`
  104. }
  105. // WellKnownUrls advertises the API roots to clients that discover them rather
  106. // than deriving them.
  107. type WellKnownUrls struct {
  108. WebApiBase string `json:"webApiBase" xml:"webApiBase"`
  109. FetchBaseURL string `json:"fetchBaseURL" xml:"fetchBaseURL"`
  110. LifestreamApiBase string `json:"lifestreamApiBase" xml:"lifestreamApiBase"`
  111. }
  112. // StartSessionEvents seeds the client with the first value of each event it
  113. // subscribed to, so it renders a populated UI before its first fetchEvents.
  114. // Each field is absent unless the client asked for that event.
  115. type StartSessionEvents struct {
  116. MyInfo *MyInfo `json:"myInfo,omitempty" xml:"myInfo,omitempty"`
  117. BuddyList *BuddyListData `json:"buddylist,omitempty" xml:"buddylist,omitempty"`
  118. Preference *PreferenceData `json:"preference,omitempty" xml:"preference,omitempty"`
  119. PermitDeny interface{} `json:"permitDeny,omitempty" xml:"permitDeny,omitempty"`
  120. }
  121. // BuddyListData is the buddylist event payload and the buddy list half of the
  122. // startSession seed.
  123. type BuddyListData struct {
  124. Groups []WebAPIBuddyGroup `json:"groups" xml:"groups>group"`
  125. }
  126. // StartSessionData is the startSession payload.
  127. type StartSessionData struct {
  128. AimSID string `json:"aimsid" xml:"aimsid"`
  129. Ts int64 `json:"ts" xml:"ts"`
  130. FetchTimeout int `json:"fetchTimeout" xml:"fetchTimeout"`
  131. TimeToNextFetch int `json:"timeToNextFetch" xml:"timeToNextFetch"`
  132. // FetchBaseURL sits directly in data, not in wellKnownUrls: it is where the
  133. // client reads its poll URL from.
  134. FetchBaseURL string `json:"fetchBaseURL" xml:"fetchBaseURL"`
  135. MyInfo *MyInfo `json:"myInfo,omitempty" xml:"myInfo,omitempty"`
  136. Events *StartSessionEvents `json:"events,omitempty" xml:"events,omitempty"`
  137. WellKnownUrls *WellKnownUrls `json:"wellKnownUrls,omitempty" xml:"wellKnownUrls,omitempty"`
  138. }
  139. // StartSession handles GET /aim/startSession requests.
  140. func (h *SessionHandler) StartSession(w http.ResponseWriter, r *http.Request) {
  141. ctx := r.Context()
  142. // Get API key info from context (set by auth middleware)
  143. apiKey, ok := ctx.Value(middleware.ContextKeyAPIKey).(*state.WebAPIKey)
  144. if !ok {
  145. h.sendError(w, r, http.StatusInternalServerError, "internal server error")
  146. return
  147. }
  148. // Parse parameters
  149. params := r.URL.Query()
  150. // Get authentication token if provided
  151. authToken := params.Get("a")
  152. // Get client info
  153. clientName := params.Get("clientName")
  154. if clientName == "" {
  155. clientName = "WebAIM"
  156. }
  157. clientVersion := params.Get("clientVersion")
  158. if clientVersion == "" {
  159. clientVersion = "1.0"
  160. }
  161. // Get events to subscribe to
  162. eventsParam := params.Get("events")
  163. var events []string
  164. if eventsParam != "" {
  165. events = strings.Split(eventsParam, ",")
  166. h.Logger.DebugContext(ctx, "parsing events from request",
  167. "eventsParam", eventsParam,
  168. "parsedEvents", events,
  169. )
  170. } else {
  171. // Default events if none specified
  172. events = []string{"buddylist", "presence", "im", "sentIM"}
  173. h.Logger.DebugContext(ctx, "using default events",
  174. "events", events,
  175. )
  176. }
  177. // Get timeout settings
  178. timeout := 60000 // Default 60 seconds for better stability with Gromit
  179. if t := params.Get("timeout"); t != "" {
  180. if val, err := strconv.Atoi(t); err == nil && val > 0 {
  181. timeout = val * 1000 // Convert to milliseconds
  182. }
  183. }
  184. // A Web API session must be bridged to an authenticated OSCAR session;
  185. // anonymous guests are not supported.
  186. if authToken == "" {
  187. h.sendError(w, r, http.StatusUnauthorized, "authentication token required")
  188. return
  189. }
  190. rawCookie, err := base64.URLEncoding.DecodeString(strings.TrimSpace(authToken))
  191. if err != nil {
  192. h.Logger.Warn("invalid authentication token (base64)", "error", err)
  193. h.sendError(w, r, http.StatusUnauthorized, "invalid or expired token")
  194. return
  195. }
  196. cookie, err := h.OSCARAuthService.CrackCookie(rawCookie)
  197. if err != nil {
  198. h.Logger.Warn("invalid authentication token", "error", err)
  199. h.sendError(w, r, http.StatusUnauthorized, "invalid or expired token")
  200. return
  201. }
  202. screenName := cookie.ScreenName
  203. tokenPreview := authToken
  204. if len(tokenPreview) > 8 {
  205. tokenPreview = tokenPreview[:8] + "..."
  206. }
  207. h.Logger.Info("authenticated session requested",
  208. "token", tokenPreview,
  209. "screenName", screenName)
  210. var instance *state.SessionInstance
  211. // Create OSCAR session
  212. instance, err = h.OSCARAuthService.RegisterBOSSession(ctx, cookie, h.FnSessCfg)
  213. if err != nil {
  214. h.Logger.ErrorContext(ctx, "failed to create OSCAR session", "err", err.Error())
  215. h.sendError(w, r, http.StatusServiceUnavailable, "unable to establish session")
  216. return
  217. }
  218. if err = instance.Session().RunOnce(h.FnSessInit(instance)); err != nil {
  219. h.Logger.ErrorContext(context.Background(), "failed to init session", "err", err.Error())
  220. // RunOnce has already closed the whole session; this is belt-and-braces,
  221. // since CloseInstance is idempotent and nothing else owns the instance yet.
  222. instance.CloseInstance()
  223. h.sendError(w, r, http.StatusInternalServerError, "internal server error")
  224. return
  225. }
  226. instance.OnClose(h.FnInstanceClose(instance))
  227. if err := h.FeedbagService.Use(ctx, instance); err != nil {
  228. h.Logger.ErrorContext(ctx, "failed to use feedbag", "err", err.Error())
  229. }
  230. // A web client signals that it wants typing events through its event
  231. // subscription, not through a stored feedbag buddy pref. Reflect that
  232. // on the OSCAR session so ICBMService attaches the WantEvents TLV to
  233. // outgoing IMs, prompting recipients to send typing notifications
  234. // back. This must run after FeedbagService.Use, which otherwise
  235. // overwrites the flag from stored prefs the web user may not have set.
  236. instance.Session().SetTypingEventsEnabled(slices.Contains(events, "typing"))
  237. instance.SetSignonComplete()
  238. if err := h.OServiceService.ClientOnline(ctx, wire.BOS, wire.SNAC_0x01_0x02_OServiceClientOnline{}, instance); err != nil {
  239. h.Logger.ErrorContext(ctx, "failed to set client online", "err", err.Error())
  240. instance.CloseInstance()
  241. h.sendError(w, r, http.StatusInternalServerError, "internal server error")
  242. return
  243. }
  244. // The rate class sending an IM spends. Only its updates surface to the client's
  245. // conversation-window alert, which renders any rateLimit event as the IM
  246. // banner. A miss yields zero, which disables the alert rather than indexing a
  247. // rate class that isn't there.
  248. imRateClassID, ok := h.SNACRateLimits.RateClassLookup(wire.ICBM, wire.ICBMChannelMsgToHost)
  249. if !ok {
  250. h.Logger.ErrorContext(ctx, "no rate class maps to sending an IM, rate limit events are disabled")
  251. }
  252. // Subscribe the same way an OSCAR client does at handshake, so the per-account
  253. // monitor broadcasts this class's transitions to this session.
  254. if imRateClassID != 0 {
  255. h.OServiceService.RateParamsSubAdd(ctx, instance, wire.SNAC_0x01_0x08_OServiceRateParamsSubAdd{
  256. ClassIDs: []uint16{uint16(imRateClassID)},
  257. })
  258. }
  259. // Create WebAPI session
  260. // Record the origin the client reached us on. Asset URLs published to the
  261. // client (buddy icons) must be absolute, since the client page is served from
  262. // a different origin than this API, and they are built in places that have no
  263. // request in hand. Pinning the origin here also keeps those URLs on the same
  264. // host as the wellKnownUrls advertised below. It is passed into CreateSession
  265. // so it is set before the session is published and its listener goroutine can
  266. // read it.
  267. baseURL := baseURLFromRequest(r)
  268. session, err := h.SessionManager.CreateSession(screenName, apiKey.DevID, events, instance, baseURL, h.Logger)
  269. if err != nil {
  270. h.Logger.ErrorContext(ctx, "failed to create session", "err", err.Error())
  271. // CreateSession refuses once the manager is shut down, so this is the
  272. // path a startSession racing shutdown takes. The WebAPISession that
  273. // would have owned the instance was never created.
  274. instance.CloseInstance()
  275. h.sendError(w, r, http.StatusInternalServerError, "failed to create session")
  276. return
  277. }
  278. h.Logger.DebugContext(ctx, "session created with event subscriptions",
  279. "aimsid", session.AimSID,
  280. "events", events,
  281. )
  282. // Wire buddy list refresher so feedbag SNACs from the OSCAR bridge trigger a buddylist event.
  283. // The refresher yields the whole buddylist event payload, not just the groups,
  284. // so the session that pushes it does not have to know the payload's shape.
  285. session.BuddyListRefresher = func(ctx context.Context) (interface{}, error) {
  286. groups, err := h.BuddyListManager.GetBuddyListForUser(ctx, session)
  287. if err != nil {
  288. return nil, err
  289. }
  290. return &BuddyListData{Groups: groups}, nil
  291. }
  292. // Wire the alias loader so OSCAR-driven im/presence events can repeat the
  293. // buddy's friendly name. The client discards the alias it holds each time it
  294. // merges a user map, so an event that omits it renames the buddy. The session
  295. // caches what this returns until a feedbag change invalidates it.
  296. session.BuddyAliasLoader = func(ctx context.Context) (map[string]string, error) {
  297. return LookupBuddyAliases(ctx, h.FeedbagService, session.OSCARSession)
  298. }
  299. // Wire the buddy-icon URL formatter so presence broadcasts (BuddyArrived) can
  300. // publish a buddy's current icon from the hash carried in the SNAC, no lookup.
  301. session.BuddyIconURL = func(sn state.IdentScreenName, hash []byte) string {
  302. return h.IconSource.URLForHash(session.BaseURL, sn, hash)
  303. }
  304. // Wire the myInfo refresher so a self user-info update (icon upload/clear)
  305. // re-renders the identity badge. currentWebState reflects the user's live
  306. // presence; PublishedURL reflects the feedbag icon, already updated by the time
  307. // the OServiceUserInfoUpdate is relayed.
  308. session.MyInfoRefresher = func(ctx context.Context) (interface{}, error) {
  309. icon := h.IconSource.PublishedURL(ctx, session.BaseURL, screenName.IdentScreenName())
  310. return buildMyInfo(screenName, currentWebState(session.OSCARSession), icon), nil
  311. }
  312. // Wire permit/deny refresher so FeedbagUpdateItem SNACs trigger a permitDeny event.
  313. session.PermitDenyRefresher = func(ctx context.Context) (interface{}, error) {
  314. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  315. fb, err := h.FeedbagService.Query(ctx, session.OSCARSession, frame)
  316. if err != nil {
  317. return nil, err
  318. }
  319. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  320. if !ok {
  321. return nil, fmt.Errorf("unexpected feedbag reply type")
  322. }
  323. return permitDenyData(reply.Items), nil
  324. }
  325. // Only IM-class rate limit updates should surface to the client alert.
  326. session.IMRateClassID = imRateClassID
  327. seedRateLimitAlert(session, imRateClassID)
  328. // Now that every refresher callback is wired, start the OSCAR listener. Doing
  329. // this inside CreateSession would race these assignments, since the goroutine
  330. // reads the callbacks as it converts SNACs into events.
  331. session.StartListeningToOSCARSession()
  332. // Store client info
  333. session.ClientName = clientName
  334. session.ClientVersion = clientVersion
  335. session.FetchTimeout = timeout
  336. session.RemoteAddr = r.RemoteAddr
  337. // The identity badge renders the user's own icon from myInfo, which is the
  338. // only event it binds its self-presence render to. PublishedURL always yields
  339. // a URL (the blank placeholder when the user has no icon) so that clearing the
  340. // icon propagates to the badge.
  341. myIconURL := h.IconSource.PublishedURL(ctx, baseURL, screenName.IdentScreenName())
  342. now := time.Now().Unix()
  343. // Prepare response
  344. data := &StartSessionData{
  345. AimSID: session.AimSID,
  346. Ts: now,
  347. FetchTimeout: session.FetchTimeout,
  348. TimeToNextFetch: session.TimeToNextFetch,
  349. // Gromit expects fetchBaseURL directly in data, not in wellKnownUrls
  350. FetchBaseURL: fmt.Sprintf("%s/aim/fetchEvents?aimsid=%s&seqNum=0", baseURL, session.AimSID),
  351. // Add wellKnownUrls for other clients that might use it.
  352. WellKnownUrls: &WellKnownUrls{
  353. WebApiBase: baseURL + "/",
  354. FetchBaseURL: baseURL + "/aim/fetchEvents",
  355. LifestreamApiBase: baseURL + "/",
  356. },
  357. Events: &StartSessionEvents{},
  358. }
  359. myInfoPayload := buildMyInfo(screenName, "online", myIconURL)
  360. myInfoPayload.OnlineTime = time.Now().Unix()
  361. myInfoPayload.MemberSince = time.Now().Unix() - 86400*30 // 30 days ago
  362. myInfoPayload.Self = &MyInfoSelf{
  363. InstNum: 1,
  364. LoginTime: time.Now().Unix(),
  365. SessionTimeout: 30,
  366. Events: events,
  367. AssertCaps: []string{},
  368. RightsInfo: RightsInfo{
  369. MaxDenies: 500,
  370. MaxPermits: 500,
  371. MaxWatchers: 3000,
  372. MaxBuddies: 500,
  373. MaxTempBuddies: 160,
  374. MaxIMSize: 3987,
  375. MinInterIcbmInterval: 1000,
  376. MaxSourceEvil: 900,
  377. MaxDstEvil: 999,
  378. MaxSigLen: 4096,
  379. },
  380. }
  381. data.MyInfo = myInfoPayload
  382. data.Events.MyInfo = myInfoPayload
  383. // Seeds that only queue an event are keyed off the subscription rather than
  384. // iterated with it, so the server fixes their order and each is queued once.
  385. // myInfo and presence render the identity badge from the same payload and the
  386. // client subscribes to both, which a per-subscription loop would queue twice.
  387. if slices.Contains(events, "myInfo") || slices.Contains(events, "presence") {
  388. myInfoData := buildMyInfo(screenName, "online", myIconURL)
  389. myInfoData.OnlineTime = time.Now().Unix()
  390. myInfoData.MemberSince = time.Now().Unix() - 86400*30 // 30 days ago
  391. session.EventQueue.Push(types.EventTypeMyInfo, myInfoData)
  392. }
  393. if slices.Contains(events, "conversation") {
  394. session.EventQueue.Push(types.EventTypeConversation,
  395. types.ConversationEventData("list", nil))
  396. }
  397. // The remaining seeds also populate the response payload, so they stay keyed off
  398. // the subscription list they are rendered into.
  399. for _, event := range events {
  400. switch types.EventType(event) {
  401. case types.EventTypeBuddyList:
  402. buddyGroups := []WebAPIBuddyGroup{}
  403. if h.BuddyListManager != nil {
  404. var err error
  405. buddyGroups, err = h.BuddyListManager.GetBuddyListForUser(ctx, session)
  406. if err != nil {
  407. h.Logger.ErrorContext(ctx, "failed to get buddy list", "err", err.Error())
  408. buddyGroups = []WebAPIBuddyGroup{}
  409. }
  410. }
  411. if buddyGroups == nil {
  412. buddyGroups = []WebAPIBuddyGroup{}
  413. }
  414. blPayload := &BuddyListData{Groups: buddyGroups}
  415. data.Events.BuddyList = blPayload
  416. session.EventQueue.Push(types.EventTypeBuddyList, blPayload)
  417. case types.EventTypePreference:
  418. // Seed the client with effective preference values: the user's stored
  419. // prefs where set, and the server-side spec defaults otherwise. The
  420. // client reads its buddy-list display prefs (e.g. showGroups) only from
  421. // this event and has no default of its own for them, so an omitted pref
  422. // would silently fall back to the client's hidden default and, for
  423. // showGroups, hide group headers.
  424. prefPayload := &PreferenceData{}
  425. if item, err := buddyPrefsItem(ctx, h.FeedbagService, session.OSCARSession); err != nil {
  426. h.Logger.ErrorContext(ctx, "failed to get preferences", "err", err.Error())
  427. } else {
  428. prefPayload = effectiveBuddyPrefs(item.TLVList)
  429. }
  430. data.Events.Preference = prefPayload
  431. session.EventQueue.Push(types.EventTypePreference, prefPayload)
  432. case types.EventTypePermitDeny:
  433. // The client keeps its privacy state solely in the model this event
  434. // populates. Both the block/unblock menu action and the "blocked"
  435. // presence state read that model and no-op silently while it is
  436. // empty, so the session has to start with one.
  437. var pdPayload interface{} = PermitDenyData{PDMode: "permitAll"}
  438. if pdd, err := session.PermitDenyRefresher(ctx); err != nil {
  439. h.Logger.ErrorContext(ctx, "failed to get permit/deny settings", "err", err.Error())
  440. } else {
  441. pdPayload = pdd
  442. }
  443. data.Events.PermitDeny = pdPayload
  444. session.EventQueue.Push(types.EventTypePermitDeny, pdPayload)
  445. }
  446. }
  447. // Drain messages stored while the user was signed off. The service relays them
  448. // as ordinary ICBMChannelMsgToClient SNACs stamped with a send time, which the
  449. // listener started above turns into offlineIM events. Retrieval deletes them
  450. // from the store and the Web API has no ack, so this is the one delivery attempt.
  451. // Skip it for a client that did not subscribe, which leaves the messages stored
  452. // for a session that wants them rather than spending them on one that does not.
  453. //
  454. // This trails every event queued above because the listener pushes from its own
  455. // goroutine, so anything drained here can overtake a later push. An offlineIM
  456. // names its sender by bare aimId and leaves the client to resolve the display
  457. // name against the buddy list it holds, and the conversation list is rebuilt from
  458. // scratch on the first "list" the client sees. Both of those events are queued in
  459. // the loop above, so the drain has to come after it.
  460. if slices.Contains(events, "offlineIM") {
  461. frame := wire.SNACFrame{
  462. FoodGroup: wire.ICBM,
  463. SubGroup: wire.ICBMOfflineRetrieve,
  464. RequestID: wire.ReqIDFromServer,
  465. }
  466. if _, err := h.ICBMService.OfflineRetrieve(ctx, instance, frame); err != nil {
  467. h.Logger.ErrorContext(ctx, "failed to retrieve offline messages", "err", err.Error())
  468. }
  469. }
  470. resp := BaseResponse{}
  471. resp.Response.StatusCode = 200
  472. resp.Response.StatusText = "OK"
  473. resp.Response.Data = data
  474. // Send response in requested format (JSON, JSONP, XML, or AMF)
  475. SendResponse(w, r, resp, h.Logger)
  476. h.Logger.DebugContext(ctx, "session started",
  477. "aimsid", session.AimSID,
  478. "screen_name", screenName,
  479. "dev_id", apiKey.DevID,
  480. "events", events,
  481. "format", r.URL.Query().Get("f"),
  482. )
  483. }
  484. // EndSession handles GET /aim/endSession requests.
  485. func (h *SessionHandler) EndSession(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  486. ctx := r.Context()
  487. // RemoveSession evicts the session from the manager and tears it down
  488. // (closes the event queue and the OSCAR instance). Without this the aimsid
  489. // stays resolvable until the reaper sweeps it, and RequireSession would keep
  490. // handing handlers a session whose OSCAR instance is already closed.
  491. if err := h.SessionManager.RemoveSession(ctx, session.AimSID); err != nil {
  492. h.Logger.ErrorContext(ctx, "failed to remove session", "err", err.Error())
  493. }
  494. // Send response
  495. resp := BaseResponse{}
  496. resp.Response.StatusCode = 200
  497. resp.Response.StatusText = "OK"
  498. // Send response in requested format (JSON, JSONP, or AMF)
  499. SendResponse(w, r, resp, h.Logger)
  500. h.Logger.DebugContext(ctx, "session ended",
  501. "aimsid", session.AimSID,
  502. "screen_name", session.ScreenName,
  503. )
  504. }
  505. // sendError sends a Web AIM API error envelope, honoring JSONP when requested.
  506. func (h *SessionHandler) sendError(w http.ResponseWriter, r *http.Request, statusCode int, message string) {
  507. resp := BaseResponse{}
  508. resp.Response.StatusCode = statusCode
  509. resp.Response.StatusText = message
  510. SendResponse(w, r, resp, h.Logger)
  511. }
  512. // buildMyInfo assembles the shared base of a myInfo payload — the user's own
  513. // identity blob that the AIM client renders in its identity badge.
  514. //
  515. // It carries only fields that are safe to repeat on every myInfo: the client's
  516. // user-object merge deletes friendly and capabilities before merging, so both
  517. // must be present on each push or the badge loses them. Time-sensitive fields
  518. // (onlineTime, memberSince) are intentionally excluded — a mid-session refresh
  519. // omits them so the client keeps the signon time it already has; the startSession
  520. // builders add them explicitly. buddyIcon is included only when non-empty; an
  521. // empty value would be dropped by the client merge anyway, and the placeholder
  522. // URL (not "") is what clears an icon.
  523. func buildMyInfo(screenName state.DisplayScreenName, webState, buddyIcon string) *MyInfo {
  524. // The web client compares userType/service case-sensitively; a UIN account must
  525. // report ICQ so it renders as an ICQ contact rather than AIM.
  526. userType, service := "aim", "AIM"
  527. if screenName.IsUIN() {
  528. userType, service = "icq", "ICQ"
  529. }
  530. return &MyInfo{
  531. AimID: screenName.IdentScreenName().String(),
  532. DisplayID: screenName.String(),
  533. Friendly: screenName.String(),
  534. State: webState,
  535. UserType: userType,
  536. // Never nil: the client iterates capabilities unconditionally.
  537. Capabilities: []string{},
  538. Bot: false,
  539. Service: service,
  540. BuddyIcon: buddyIcon,
  541. }
  542. }
  543. func requestScheme(r *http.Request) string {
  544. if r.TLS != nil {
  545. return "https"
  546. }
  547. if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  548. return proto
  549. }
  550. return "http"
  551. }
  552. // baseURLFromRequest returns the absolute base URL the client reached this
  553. // server on, used to build asset URLs that the client loads directly.
  554. func baseURLFromRequest(r *http.Request) string {
  555. return fmt.Sprintf("%s://%s", requestScheme(r), r.Host)
  556. }