types.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package server
  2. import (
  3. "heckel.io/ntfy/log"
  4. "heckel.io/ntfy/user"
  5. "net/http"
  6. "net/netip"
  7. "time"
  8. "heckel.io/ntfy/util"
  9. )
  10. // List of possible events
  11. const (
  12. openEvent = "open"
  13. keepaliveEvent = "keepalive"
  14. messageEvent = "message"
  15. pollRequestEvent = "poll_request"
  16. )
  17. const (
  18. messageIDLength = 12
  19. )
  20. // message represents a message published to a topic
  21. type message struct {
  22. ID string `json:"id"` // Random message ID
  23. Time int64 `json:"time"` // Unix time in seconds
  24. Expires int64 `json:"expires,omitempty"` // Unix time in seconds (not required for open/keepalive)
  25. Event string `json:"event"` // One of the above
  26. Topic string `json:"topic"`
  27. Title string `json:"title,omitempty"`
  28. Message string `json:"message,omitempty"`
  29. Priority int `json:"priority,omitempty"`
  30. Tags []string `json:"tags,omitempty"`
  31. Click string `json:"click,omitempty"`
  32. Icon string `json:"icon,omitempty"`
  33. Actions []*action `json:"actions,omitempty"`
  34. Attachment *attachment `json:"attachment,omitempty"`
  35. PollID string `json:"poll_id,omitempty"`
  36. Encoding string `json:"encoding,omitempty"` // empty for raw UTF-8, or "base64" for encoded bytes
  37. Sender netip.Addr `json:"-"` // IP address of uploader, used for rate limiting
  38. User string `json:"-"` // Username of the uploader, used to associated attachments
  39. }
  40. func (m *message) Context() log.Context {
  41. fields := map[string]any{
  42. "message_id": m.ID,
  43. "message_time": m.Time,
  44. "message_event": m.Event,
  45. "message_topic": m.Topic,
  46. "message_body_size": len(m.Message),
  47. }
  48. if m.Sender.IsValid() {
  49. fields["message_sender"] = m.Sender.String()
  50. }
  51. if m.User != "" {
  52. fields["message_user"] = m.User
  53. }
  54. return fields
  55. }
  56. type attachment struct {
  57. Name string `json:"name"`
  58. Type string `json:"type,omitempty"`
  59. Size int64 `json:"size,omitempty"`
  60. Expires int64 `json:"expires,omitempty"`
  61. URL string `json:"url"`
  62. }
  63. type action struct {
  64. ID string `json:"id"`
  65. Action string `json:"action"` // "view", "broadcast", or "http"
  66. Label string `json:"label"` // action button label
  67. Clear bool `json:"clear"` // clear notification after successful execution
  68. URL string `json:"url,omitempty"` // used in "view" and "http" actions
  69. Method string `json:"method,omitempty"` // used in "http" action, default is POST (!)
  70. Headers map[string]string `json:"headers,omitempty"` // used in "http" action
  71. Body string `json:"body,omitempty"` // used in "http" action
  72. Intent string `json:"intent,omitempty"` // used in "broadcast" action
  73. Extras map[string]string `json:"extras,omitempty"` // used in "broadcast" action
  74. }
  75. func newAction() *action {
  76. return &action{
  77. Headers: make(map[string]string),
  78. Extras: make(map[string]string),
  79. }
  80. }
  81. // publishMessage is used as input when publishing as JSON
  82. type publishMessage struct {
  83. Topic string `json:"topic"`
  84. Title string `json:"title"`
  85. Message string `json:"message"`
  86. Priority int `json:"priority"`
  87. Tags []string `json:"tags"`
  88. Click string `json:"click"`
  89. Icon string `json:"icon"`
  90. Actions []action `json:"actions"`
  91. Attach string `json:"attach"`
  92. Filename string `json:"filename"`
  93. Email string `json:"email"`
  94. Delay string `json:"delay"`
  95. }
  96. // messageEncoder is a function that knows how to encode a message
  97. type messageEncoder func(msg *message) (string, error)
  98. // newMessage creates a new message with the current timestamp
  99. func newMessage(event, topic, msg string) *message {
  100. return &message{
  101. ID: util.RandomString(messageIDLength),
  102. Time: time.Now().Unix(),
  103. Event: event,
  104. Topic: topic,
  105. Message: msg,
  106. }
  107. }
  108. // newOpenMessage is a convenience method to create an open message
  109. func newOpenMessage(topic string) *message {
  110. return newMessage(openEvent, topic, "")
  111. }
  112. // newKeepaliveMessage is a convenience method to create a keepalive message
  113. func newKeepaliveMessage(topic string) *message {
  114. return newMessage(keepaliveEvent, topic, "")
  115. }
  116. // newDefaultMessage is a convenience method to create a notification message
  117. func newDefaultMessage(topic, msg string) *message {
  118. return newMessage(messageEvent, topic, msg)
  119. }
  120. // newPollRequestMessage is a convenience method to create a poll request message
  121. func newPollRequestMessage(topic, pollID string) *message {
  122. m := newMessage(pollRequestEvent, topic, newMessageBody)
  123. m.PollID = pollID
  124. return m
  125. }
  126. func validMessageID(s string) bool {
  127. return util.ValidRandomString(s, messageIDLength)
  128. }
  129. type sinceMarker struct {
  130. time time.Time
  131. id string
  132. }
  133. func newSinceTime(timestamp int64) sinceMarker {
  134. return sinceMarker{time.Unix(timestamp, 0), ""}
  135. }
  136. func newSinceID(id string) sinceMarker {
  137. return sinceMarker{time.Unix(0, 0), id}
  138. }
  139. func (t sinceMarker) IsAll() bool {
  140. return t == sinceAllMessages
  141. }
  142. func (t sinceMarker) IsNone() bool {
  143. return t == sinceNoMessages
  144. }
  145. func (t sinceMarker) IsID() bool {
  146. return t.id != ""
  147. }
  148. func (t sinceMarker) Time() time.Time {
  149. return t.time
  150. }
  151. func (t sinceMarker) ID() string {
  152. return t.id
  153. }
  154. var (
  155. sinceAllMessages = sinceMarker{time.Unix(0, 0), ""}
  156. sinceNoMessages = sinceMarker{time.Unix(1, 0), ""}
  157. )
  158. type queryFilter struct {
  159. ID string
  160. Message string
  161. Title string
  162. Tags []string
  163. Priority []int
  164. }
  165. func parseQueryFilters(r *http.Request) (*queryFilter, error) {
  166. idFilter := readParam(r, "x-id", "id")
  167. messageFilter := readParam(r, "x-message", "message", "m")
  168. titleFilter := readParam(r, "x-title", "title", "t")
  169. tagsFilter := util.SplitNoEmpty(readParam(r, "x-tags", "tags", "tag", "ta"), ",")
  170. priorityFilter := make([]int, 0)
  171. for _, p := range util.SplitNoEmpty(readParam(r, "x-priority", "priority", "prio", "p"), ",") {
  172. priority, err := util.ParsePriority(p)
  173. if err != nil {
  174. return nil, errHTTPBadRequestPriorityInvalid
  175. }
  176. priorityFilter = append(priorityFilter, priority)
  177. }
  178. return &queryFilter{
  179. ID: idFilter,
  180. Message: messageFilter,
  181. Title: titleFilter,
  182. Tags: tagsFilter,
  183. Priority: priorityFilter,
  184. }, nil
  185. }
  186. func (q *queryFilter) Pass(msg *message) bool {
  187. if msg.Event != messageEvent {
  188. return true // filters only apply to messages
  189. } else if q.ID != "" && msg.ID != q.ID {
  190. return false
  191. } else if q.Message != "" && msg.Message != q.Message {
  192. return false
  193. } else if q.Title != "" && msg.Title != q.Title {
  194. return false
  195. }
  196. messagePriority := msg.Priority
  197. if messagePriority == 0 {
  198. messagePriority = 3 // For query filters, default priority (3) is the same as "not set" (0)
  199. }
  200. if len(q.Priority) > 0 && !util.Contains(q.Priority, messagePriority) {
  201. return false
  202. }
  203. if len(q.Tags) > 0 && !util.ContainsAll(msg.Tags, q.Tags) {
  204. return false
  205. }
  206. return true
  207. }
  208. type apiHealthResponse struct {
  209. Healthy bool `json:"healthy"`
  210. }
  211. type apiAccountCreateRequest struct {
  212. Username string `json:"username"`
  213. Password string `json:"password"`
  214. }
  215. type apiAccountPasswordChangeRequest struct {
  216. Password string `json:"password"`
  217. NewPassword string `json:"new_password"`
  218. }
  219. type apiAccountDeleteRequest struct {
  220. Password string `json:"password"`
  221. }
  222. type apiAccountTokenIssueRequest struct {
  223. Label *string `json:"label"`
  224. Expires *int64 `json:"expires"` // Unix timestamp
  225. }
  226. type apiAccountTokenUpdateRequest struct {
  227. Token string `json:"token"`
  228. Label *string `json:"label"`
  229. Expires *int64 `json:"expires"` // Unix timestamp
  230. }
  231. type apiAccountTokenResponse struct {
  232. Token string `json:"token"`
  233. Label string `json:"label,omitempty"`
  234. LastAccess int64 `json:"last_access,omitempty"`
  235. LastOrigin string `json:"last_origin,omitempty"`
  236. Expires int64 `json:"expires,omitempty"` // Unix timestamp
  237. }
  238. type apiAccountTier struct {
  239. Code string `json:"code"`
  240. Name string `json:"name"`
  241. }
  242. type apiAccountLimits struct {
  243. Basis string `json:"basis,omitempty"` // "ip" or "tier"
  244. Messages int64 `json:"messages"`
  245. MessagesExpiryDuration int64 `json:"messages_expiry_duration"`
  246. Emails int64 `json:"emails"`
  247. Reservations int64 `json:"reservations"`
  248. AttachmentTotalSize int64 `json:"attachment_total_size"`
  249. AttachmentFileSize int64 `json:"attachment_file_size"`
  250. AttachmentExpiryDuration int64 `json:"attachment_expiry_duration"`
  251. AttachmentBandwidth int64 `json:"attachment_bandwidth"`
  252. }
  253. type apiAccountStats struct {
  254. Messages int64 `json:"messages"`
  255. MessagesRemaining int64 `json:"messages_remaining"`
  256. Emails int64 `json:"emails"`
  257. EmailsRemaining int64 `json:"emails_remaining"`
  258. Reservations int64 `json:"reservations"`
  259. ReservationsRemaining int64 `json:"reservations_remaining"`
  260. AttachmentTotalSize int64 `json:"attachment_total_size"`
  261. AttachmentTotalSizeRemaining int64 `json:"attachment_total_size_remaining"`
  262. }
  263. type apiAccountReservation struct {
  264. Topic string `json:"topic"`
  265. Everyone string `json:"everyone"`
  266. }
  267. type apiAccountBilling struct {
  268. Customer bool `json:"customer"`
  269. Subscription bool `json:"subscription"`
  270. Status string `json:"status,omitempty"`
  271. PaidUntil int64 `json:"paid_until,omitempty"`
  272. CancelAt int64 `json:"cancel_at,omitempty"`
  273. }
  274. type apiAccountResponse struct {
  275. Username string `json:"username"`
  276. Role string `json:"role,omitempty"`
  277. SyncTopic string `json:"sync_topic,omitempty"`
  278. Language string `json:"language,omitempty"`
  279. Notification *user.NotificationPrefs `json:"notification,omitempty"`
  280. Subscriptions []*user.Subscription `json:"subscriptions,omitempty"`
  281. Reservations []*apiAccountReservation `json:"reservations,omitempty"`
  282. Tokens []*apiAccountTokenResponse `json:"tokens,omitempty"`
  283. Tier *apiAccountTier `json:"tier,omitempty"`
  284. Limits *apiAccountLimits `json:"limits,omitempty"`
  285. Stats *apiAccountStats `json:"stats,omitempty"`
  286. Billing *apiAccountBilling `json:"billing,omitempty"`
  287. }
  288. type apiAccountReservationRequest struct {
  289. Topic string `json:"topic"`
  290. Everyone string `json:"everyone"`
  291. }
  292. type apiConfigResponse struct {
  293. BaseURL string `json:"base_url"`
  294. AppRoot string `json:"app_root"`
  295. EnableLogin bool `json:"enable_login"`
  296. EnableSignup bool `json:"enable_signup"`
  297. EnablePayments bool `json:"enable_payments"`
  298. EnableReservations bool `json:"enable_reservations"`
  299. DisallowedTopics []string `json:"disallowed_topics"`
  300. }
  301. type apiAccountBillingTier struct {
  302. Code string `json:"code,omitempty"`
  303. Name string `json:"name,omitempty"`
  304. Price string `json:"price,omitempty"`
  305. Limits *apiAccountLimits `json:"limits"`
  306. }
  307. type apiAccountBillingSubscriptionCreateResponse struct {
  308. RedirectURL string `json:"redirect_url"`
  309. }
  310. type apiAccountBillingSubscriptionChangeRequest struct {
  311. Tier string `json:"tier"`
  312. }
  313. type apiAccountBillingPortalRedirectResponse struct {
  314. RedirectURL string `json:"redirect_url"`
  315. }
  316. type apiAccountSyncTopicResponse struct {
  317. Event string `json:"event"`
  318. }
  319. type apiSuccessResponse struct {
  320. Success bool `json:"success"`
  321. }
  322. func newSuccessResponse() *apiSuccessResponse {
  323. return &apiSuccessResponse{
  324. Success: true,
  325. }
  326. }
  327. type apiStripeSubscriptionUpdatedEvent struct {
  328. ID string `json:"id"`
  329. Customer string `json:"customer"`
  330. Status string `json:"status"`
  331. CurrentPeriodEnd int64 `json:"current_period_end"`
  332. CancelAt int64 `json:"cancel_at"`
  333. Items *struct {
  334. Data []*struct {
  335. Price *struct {
  336. ID string `json:"id"`
  337. } `json:"price"`
  338. } `json:"data"`
  339. } `json:"items"`
  340. }
  341. type apiStripeSubscriptionDeletedEvent struct {
  342. ID string `json:"id"`
  343. Customer string `json:"customer"`
  344. }