server_account.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. package server
  2. import (
  3. "encoding/json"
  4. "heckel.io/ntfy/log"
  5. "heckel.io/ntfy/user"
  6. "heckel.io/ntfy/util"
  7. "net/http"
  8. "net/netip"
  9. "strings"
  10. "time"
  11. )
  12. const (
  13. syncTopicAccountSyncEvent = "sync"
  14. tokenExpiryDuration = 72 * time.Hour // Extend tokens by this much
  15. )
  16. func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  17. u := v.User()
  18. if !u.IsAdmin() { // u may be nil, but that's fine
  19. if !s.config.EnableSignup {
  20. return errHTTPBadRequestSignupNotEnabled
  21. } else if u != nil {
  22. return errHTTPUnauthorized // Cannot create account from user context
  23. }
  24. if !v.AccountCreationAllowed() {
  25. return errHTTPTooManyRequestsLimitAccountCreation
  26. }
  27. }
  28. newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit, false)
  29. if err != nil {
  30. return err
  31. }
  32. if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil {
  33. return errHTTPConflictUserExists
  34. }
  35. logvr(v, r).Tag(tagAccount).Field("user_name", newAccount.Username).Info("Creating user %s", newAccount.Username)
  36. if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser); err != nil {
  37. return err
  38. }
  39. v.AccountCreated()
  40. return s.writeJSON(w, newSuccessResponse())
  41. }
  42. func (s *Server) handleAccountGet(w http.ResponseWriter, r *http.Request, v *visitor) error {
  43. info, err := v.Info()
  44. if err != nil {
  45. return err
  46. }
  47. logvr(v, r).Tag(tagAccount).Fields(visitorExtendedInfoContext(info)).Debug("Retrieving account stats")
  48. limits, stats := info.Limits, info.Stats
  49. response := &apiAccountResponse{
  50. Limits: &apiAccountLimits{
  51. Basis: string(limits.Basis),
  52. Messages: limits.MessageLimit,
  53. MessagesExpiryDuration: int64(limits.MessageExpiryDuration.Seconds()),
  54. Emails: limits.EmailLimit,
  55. Reservations: limits.ReservationsLimit,
  56. AttachmentTotalSize: limits.AttachmentTotalSizeLimit,
  57. AttachmentFileSize: limits.AttachmentFileSizeLimit,
  58. AttachmentExpiryDuration: int64(limits.AttachmentExpiryDuration.Seconds()),
  59. AttachmentBandwidth: limits.AttachmentBandwidthLimit,
  60. },
  61. Stats: &apiAccountStats{
  62. Messages: stats.Messages,
  63. MessagesRemaining: stats.MessagesRemaining,
  64. Emails: stats.Emails,
  65. EmailsRemaining: stats.EmailsRemaining,
  66. Reservations: stats.Reservations,
  67. ReservationsRemaining: stats.ReservationsRemaining,
  68. AttachmentTotalSize: stats.AttachmentTotalSize,
  69. AttachmentTotalSizeRemaining: stats.AttachmentTotalSizeRemaining,
  70. },
  71. }
  72. u := v.User()
  73. if u != nil {
  74. response.Username = u.Name
  75. response.Role = string(u.Role)
  76. response.SyncTopic = u.SyncTopic
  77. if u.Prefs != nil {
  78. if u.Prefs.Language != nil {
  79. response.Language = *u.Prefs.Language
  80. }
  81. if u.Prefs.Notification != nil {
  82. response.Notification = u.Prefs.Notification
  83. }
  84. if u.Prefs.Subscriptions != nil {
  85. response.Subscriptions = u.Prefs.Subscriptions
  86. }
  87. }
  88. if u.Tier != nil {
  89. response.Tier = &apiAccountTier{
  90. Code: u.Tier.Code,
  91. Name: u.Tier.Name,
  92. }
  93. }
  94. if u.Billing.StripeCustomerID != "" {
  95. response.Billing = &apiAccountBilling{
  96. Customer: true,
  97. Subscription: u.Billing.StripeSubscriptionID != "",
  98. Status: string(u.Billing.StripeSubscriptionStatus),
  99. Interval: string(u.Billing.StripeSubscriptionInterval),
  100. PaidUntil: u.Billing.StripeSubscriptionPaidUntil.Unix(),
  101. CancelAt: u.Billing.StripeSubscriptionCancelAt.Unix(),
  102. }
  103. }
  104. reservations, err := s.userManager.Reservations(u.Name)
  105. if err != nil {
  106. return err
  107. }
  108. if len(reservations) > 0 {
  109. response.Reservations = make([]*apiAccountReservation, 0)
  110. for _, r := range reservations {
  111. response.Reservations = append(response.Reservations, &apiAccountReservation{
  112. Topic: r.Topic,
  113. Everyone: r.Everyone.String(),
  114. })
  115. }
  116. }
  117. tokens, err := s.userManager.Tokens(u.ID)
  118. if err != nil {
  119. return err
  120. }
  121. if len(tokens) > 0 {
  122. response.Tokens = make([]*apiAccountTokenResponse, 0)
  123. for _, t := range tokens {
  124. var lastOrigin string
  125. if t.LastOrigin != netip.IPv4Unspecified() {
  126. lastOrigin = t.LastOrigin.String()
  127. }
  128. response.Tokens = append(response.Tokens, &apiAccountTokenResponse{
  129. Token: t.Value,
  130. Label: t.Label,
  131. LastAccess: t.LastAccess.Unix(),
  132. LastOrigin: lastOrigin,
  133. Expires: t.Expires.Unix(),
  134. })
  135. }
  136. }
  137. } else {
  138. response.Username = user.Everyone
  139. response.Role = string(user.RoleAnonymous)
  140. }
  141. return s.writeJSON(w, response)
  142. }
  143. func (s *Server) handleAccountDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  144. req, err := readJSONWithLimit[apiAccountDeleteRequest](r.Body, jsonBodyBytesLimit, false)
  145. if err != nil {
  146. return err
  147. } else if req.Password == "" {
  148. return errHTTPBadRequest
  149. }
  150. u := v.User()
  151. if _, err := s.userManager.Authenticate(u.Name, req.Password); err != nil {
  152. return errHTTPBadRequestIncorrectPasswordConfirmation
  153. }
  154. if u.Billing.StripeSubscriptionID != "" {
  155. logvr(v, r).Tag(tagStripe).Info("Canceling billing subscription for user %s", u.Name)
  156. if _, err := s.stripe.CancelSubscription(u.Billing.StripeSubscriptionID); err != nil {
  157. return err
  158. }
  159. }
  160. if err := s.maybeRemoveMessagesAndExcessReservations(r, v, u, 0); err != nil {
  161. return err
  162. }
  163. logvr(v, r).Tag(tagAccount).Info("Marking user %s as deleted", u.Name)
  164. if err := s.userManager.MarkUserRemoved(u); err != nil {
  165. return err
  166. }
  167. return s.writeJSON(w, newSuccessResponse())
  168. }
  169. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  170. req, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit, false)
  171. if err != nil {
  172. return err
  173. } else if req.Password == "" || req.NewPassword == "" {
  174. return errHTTPBadRequest
  175. }
  176. u := v.User()
  177. if _, err := s.userManager.Authenticate(u.Name, req.Password); err != nil {
  178. return errHTTPBadRequestIncorrectPasswordConfirmation
  179. }
  180. logvr(v, r).Tag(tagAccount).Debug("Changing password for user %s", u.Name)
  181. if err := s.userManager.ChangePassword(u.Name, req.NewPassword); err != nil {
  182. return err
  183. }
  184. return s.writeJSON(w, newSuccessResponse())
  185. }
  186. func (s *Server) handleAccountTokenCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  187. req, err := readJSONWithLimit[apiAccountTokenIssueRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body!
  188. if err != nil {
  189. return err
  190. }
  191. var label string
  192. if req.Label != nil {
  193. label = *req.Label
  194. }
  195. expires := time.Now().Add(tokenExpiryDuration)
  196. if req.Expires != nil {
  197. expires = time.Unix(*req.Expires, 0)
  198. }
  199. u := v.User()
  200. logvr(v, r).
  201. Tag(tagAccount).
  202. Fields(log.Context{
  203. "token_label": label,
  204. "token_expires": expires,
  205. }).
  206. Debug("Creating token for user %s", u.Name)
  207. token, err := s.userManager.CreateToken(u.ID, label, expires, v.IP())
  208. if err != nil {
  209. return err
  210. }
  211. response := &apiAccountTokenResponse{
  212. Token: token.Value,
  213. Label: token.Label,
  214. LastAccess: token.LastAccess.Unix(),
  215. LastOrigin: token.LastOrigin.String(),
  216. Expires: token.Expires.Unix(),
  217. }
  218. return s.writeJSON(w, response)
  219. }
  220. func (s *Server) handleAccountTokenUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  221. u := v.User()
  222. req, err := readJSONWithLimit[apiAccountTokenUpdateRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body!
  223. if err != nil {
  224. return err
  225. } else if req.Token == "" {
  226. req.Token = u.Token
  227. if req.Token == "" {
  228. return errHTTPBadRequestNoTokenProvided
  229. }
  230. }
  231. var expires *time.Time
  232. if req.Expires != nil {
  233. expires = util.Time(time.Unix(*req.Expires, 0))
  234. } else if req.Label == nil {
  235. expires = util.Time(time.Now().Add(tokenExpiryDuration)) // If label/expires not set, extend token by 72 hours
  236. }
  237. logvr(v, r).
  238. Tag(tagAccount).
  239. Fields(log.Context{
  240. "token_label": req.Label,
  241. "token_expires": expires,
  242. }).
  243. Debug("Updating token for user %s as deleted", u.Name)
  244. token, err := s.userManager.ChangeToken(u.ID, req.Token, req.Label, expires)
  245. if err != nil {
  246. return err
  247. }
  248. response := &apiAccountTokenResponse{
  249. Token: token.Value,
  250. Label: token.Label,
  251. LastAccess: token.LastAccess.Unix(),
  252. LastOrigin: token.LastOrigin.String(),
  253. Expires: token.Expires.Unix(),
  254. }
  255. return s.writeJSON(w, response)
  256. }
  257. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  258. u := v.User()
  259. token := readParam(r, "X-Token", "Token") // DELETEs cannot have a body, and we don't want it in the path
  260. if token == "" {
  261. token = u.Token
  262. if token == "" {
  263. return errHTTPBadRequestNoTokenProvided
  264. }
  265. }
  266. if err := s.userManager.RemoveToken(u.ID, token); err != nil {
  267. return err
  268. }
  269. logvr(v, r).
  270. Tag(tagAccount).
  271. Field("token", token).
  272. Debug("Deleted token for user %s", u.Name)
  273. return s.writeJSON(w, newSuccessResponse())
  274. }
  275. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  276. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit, false)
  277. if err != nil {
  278. return err
  279. }
  280. u := v.User()
  281. if u.Prefs == nil {
  282. u.Prefs = &user.Prefs{}
  283. }
  284. prefs := u.Prefs
  285. if newPrefs.Language != nil {
  286. prefs.Language = newPrefs.Language
  287. }
  288. if newPrefs.Notification != nil {
  289. if prefs.Notification == nil {
  290. prefs.Notification = &user.NotificationPrefs{}
  291. }
  292. if newPrefs.Notification.DeleteAfter != nil {
  293. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  294. }
  295. if newPrefs.Notification.Sound != nil {
  296. prefs.Notification.Sound = newPrefs.Notification.Sound
  297. }
  298. if newPrefs.Notification.MinPriority != nil {
  299. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  300. }
  301. }
  302. logvr(v, r).Tag(tagAccount).Debug("Changing account settings for user %s", u.Name)
  303. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  304. return err
  305. }
  306. return s.writeJSON(w, newSuccessResponse())
  307. }
  308. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  309. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false)
  310. if err != nil {
  311. return err
  312. }
  313. u := v.User()
  314. prefs := u.Prefs
  315. if prefs == nil {
  316. prefs = &user.Prefs{}
  317. }
  318. for _, subscription := range prefs.Subscriptions {
  319. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  320. return errHTTPConflictSubscriptionExists
  321. }
  322. }
  323. prefs.Subscriptions = append(prefs.Subscriptions, newSubscription)
  324. logvr(v, r).Tag(tagAccount).With(newSubscription).Debug("Adding subscription for user %s", u.Name)
  325. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  326. return err
  327. }
  328. return s.writeJSON(w, newSubscription)
  329. }
  330. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  331. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false)
  332. if err != nil {
  333. return err
  334. }
  335. u := v.User()
  336. prefs := u.Prefs
  337. if prefs == nil || prefs.Subscriptions == nil {
  338. return errHTTPNotFound
  339. }
  340. var subscription *user.Subscription
  341. for _, sub := range prefs.Subscriptions {
  342. if sub.BaseURL == updatedSubscription.BaseURL && sub.Topic == updatedSubscription.Topic {
  343. sub.DisplayName = updatedSubscription.DisplayName
  344. subscription = sub
  345. break
  346. }
  347. }
  348. if subscription == nil {
  349. return errHTTPNotFound
  350. }
  351. logvr(v, r).Tag(tagAccount).With(subscription).Debug("Changing subscription for user %s", u.Name)
  352. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  353. return err
  354. }
  355. return s.writeJSON(w, subscription)
  356. }
  357. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  358. // DELETEs cannot have a body, and we don't want it in the path
  359. deleteBaseURL := readParam(r, "X-BaseURL", "BaseURL")
  360. deleteTopic := readParam(r, "X-Topic", "Topic")
  361. u := v.User()
  362. prefs := u.Prefs
  363. if prefs == nil || prefs.Subscriptions == nil {
  364. return nil
  365. }
  366. newSubscriptions := make([]*user.Subscription, 0)
  367. for _, sub := range u.Prefs.Subscriptions {
  368. if sub.BaseURL == deleteBaseURL && sub.Topic == deleteTopic {
  369. logvr(v, r).Tag(tagAccount).With(sub).Debug("Removing subscription for user %s", u.Name)
  370. } else {
  371. newSubscriptions = append(newSubscriptions, sub)
  372. }
  373. }
  374. if len(newSubscriptions) < len(prefs.Subscriptions) {
  375. prefs.Subscriptions = newSubscriptions
  376. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  377. return err
  378. }
  379. }
  380. return s.writeJSON(w, newSuccessResponse())
  381. }
  382. // handleAccountReservationAdd adds a topic reservation for the logged-in user, but only if the user has a tier
  383. // with enough remaining reservations left, or if the user is an admin. Admins can always reserve a topic, unless
  384. // it is already reserved by someone else.
  385. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  386. u := v.User()
  387. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit, false)
  388. if err != nil {
  389. return err
  390. }
  391. if !topicRegex.MatchString(req.Topic) {
  392. return errHTTPBadRequestTopicInvalid
  393. }
  394. everyone, err := user.ParsePermission(req.Everyone)
  395. if err != nil {
  396. return errHTTPBadRequestPermissionInvalid
  397. }
  398. // Check if we are allowed to reserve this topic
  399. if u.IsUser() && u.Tier == nil {
  400. return errHTTPUnauthorized
  401. } else if err := s.userManager.AllowReservation(u.Name, req.Topic); err != nil {
  402. return errHTTPConflictTopicReserved
  403. } else if u.IsUser() {
  404. hasReservation, err := s.userManager.HasReservation(u.Name, req.Topic)
  405. if err != nil {
  406. return err
  407. }
  408. if !hasReservation {
  409. reservations, err := s.userManager.ReservationsCount(u.Name)
  410. if err != nil {
  411. return err
  412. } else if reservations >= u.Tier.ReservationLimit {
  413. return errHTTPTooManyRequestsLimitReservations
  414. }
  415. }
  416. }
  417. // Actually add the reservation
  418. logvr(v, r).
  419. Tag(tagAccount).
  420. Fields(log.Context{
  421. "topic": req.Topic,
  422. "everyone": everyone.String(),
  423. }).
  424. Debug("Adding topic reservation")
  425. if err := s.userManager.AddReservation(u.Name, req.Topic, everyone); err != nil {
  426. return err
  427. }
  428. // Kill existing subscribers
  429. t, err := s.topicFromID(req.Topic)
  430. if err != nil {
  431. return err
  432. }
  433. t.CancelSubscribers(u.ID)
  434. return s.writeJSON(w, newSuccessResponse())
  435. }
  436. // handleAccountReservationDelete deletes a topic reservation if it is owned by the current user
  437. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  438. matches := apiAccountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  439. if len(matches) != 2 {
  440. return errHTTPInternalErrorInvalidPath
  441. }
  442. topic := matches[1]
  443. if !topicRegex.MatchString(topic) {
  444. return errHTTPBadRequestTopicInvalid
  445. }
  446. u := v.User()
  447. authorized, err := s.userManager.HasReservation(u.Name, topic)
  448. if err != nil {
  449. return err
  450. } else if !authorized {
  451. return errHTTPUnauthorized
  452. }
  453. deleteMessages := readBoolParam(r, false, "X-Delete-Messages", "Delete-Messages")
  454. logvr(v, r).
  455. Tag(tagAccount).
  456. Fields(log.Context{
  457. "topic": topic,
  458. "delete_messages": deleteMessages,
  459. }).
  460. Debug("Removing topic reservation")
  461. if err := s.userManager.RemoveReservations(u.Name, topic); err != nil {
  462. return err
  463. }
  464. if deleteMessages {
  465. if err := s.messageCache.ExpireMessages(topic); err != nil {
  466. return err
  467. }
  468. s.pruneMessages()
  469. }
  470. return s.writeJSON(w, newSuccessResponse())
  471. }
  472. // maybeRemoveMessagesAndExcessReservations deletes topic reservations for the given user (if too many for tier),
  473. // and marks associated messages for the topics as deleted. This also eventually deletes attachments.
  474. // The process relies on the manager to perform the actual deletions (see runManager).
  475. func (s *Server) maybeRemoveMessagesAndExcessReservations(r *http.Request, v *visitor, u *user.User, reservationsLimit int64) error {
  476. reservations, err := s.userManager.Reservations(u.Name)
  477. if err != nil {
  478. return err
  479. } else if int64(len(reservations)) <= reservationsLimit {
  480. logvr(v, r).Tag(tagAccount).Debug("No excess reservations to remove")
  481. return nil
  482. }
  483. topics := make([]string, 0)
  484. for i := int64(len(reservations)) - 1; i >= reservationsLimit; i-- {
  485. topics = append(topics, reservations[i].Topic)
  486. }
  487. logvr(v, r).Tag(tagAccount).Info("Removing excess reservations for topics %s", strings.Join(topics, ", "))
  488. if err := s.userManager.RemoveReservations(u.Name, topics...); err != nil {
  489. return err
  490. }
  491. if err := s.messageCache.ExpireMessages(topics...); err != nil {
  492. return err
  493. }
  494. go s.pruneMessages()
  495. return nil
  496. }
  497. // publishSyncEventAsync kicks of a Go routine to publish a sync message to the user's sync topic
  498. func (s *Server) publishSyncEventAsync(v *visitor) {
  499. go func() {
  500. if err := s.publishSyncEvent(v); err != nil {
  501. logv(v).Err(err).Trace("Error publishing to user's sync topic")
  502. }
  503. }()
  504. }
  505. // publishSyncEvent publishes a sync message to the user's sync topic
  506. func (s *Server) publishSyncEvent(v *visitor) error {
  507. u := v.User()
  508. if u == nil || u.SyncTopic == "" {
  509. return nil
  510. }
  511. logv(v).Field("sync_topic", u.SyncTopic).Trace("Publishing sync event to user's sync topic")
  512. syncTopic, err := s.topicFromID(u.SyncTopic)
  513. if err != nil {
  514. return err
  515. }
  516. messageBytes, err := json.Marshal(&apiAccountSyncTopicResponse{Event: syncTopicAccountSyncEvent})
  517. if err != nil {
  518. return err
  519. }
  520. m := newDefaultMessage(syncTopic.ID, string(messageBytes))
  521. if err := syncTopic.Publish(v, m); err != nil {
  522. return err
  523. }
  524. return nil
  525. }