types.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. "topic": m.Topic,
  43. "message_id": m.ID,
  44. "message_time": m.Time,
  45. "message_event": m.Event,
  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 apiStatsResponse struct {
  212. Messages int64 `json:"messages"`
  213. MessagesRate float64 `json:"messages_rate"` // Average number of messages per second
  214. }
  215. type apiAccountCreateRequest struct {
  216. Username string `json:"username"`
  217. Password string `json:"password"`
  218. }
  219. type apiAccountPasswordChangeRequest struct {
  220. Password string `json:"password"`
  221. NewPassword string `json:"new_password"`
  222. }
  223. type apiAccountDeleteRequest struct {
  224. Password string `json:"password"`
  225. }
  226. type apiAccountTokenIssueRequest struct {
  227. Label *string `json:"label"`
  228. Expires *int64 `json:"expires"` // Unix timestamp
  229. }
  230. type apiAccountTokenUpdateRequest struct {
  231. Token string `json:"token"`
  232. Label *string `json:"label"`
  233. Expires *int64 `json:"expires"` // Unix timestamp
  234. }
  235. type apiAccountTokenResponse struct {
  236. Token string `json:"token"`
  237. Label string `json:"label,omitempty"`
  238. LastAccess int64 `json:"last_access,omitempty"`
  239. LastOrigin string `json:"last_origin,omitempty"`
  240. Expires int64 `json:"expires,omitempty"` // Unix timestamp
  241. }
  242. type apiAccountTier struct {
  243. Code string `json:"code"`
  244. Name string `json:"name"`
  245. }
  246. type apiAccountLimits struct {
  247. Basis string `json:"basis,omitempty"` // "ip" or "tier"
  248. Messages int64 `json:"messages"`
  249. MessagesExpiryDuration int64 `json:"messages_expiry_duration"`
  250. Emails int64 `json:"emails"`
  251. Reservations int64 `json:"reservations"`
  252. AttachmentTotalSize int64 `json:"attachment_total_size"`
  253. AttachmentFileSize int64 `json:"attachment_file_size"`
  254. AttachmentExpiryDuration int64 `json:"attachment_expiry_duration"`
  255. AttachmentBandwidth int64 `json:"attachment_bandwidth"`
  256. }
  257. type apiAccountStats struct {
  258. Messages int64 `json:"messages"`
  259. MessagesRemaining int64 `json:"messages_remaining"`
  260. Emails int64 `json:"emails"`
  261. EmailsRemaining int64 `json:"emails_remaining"`
  262. Reservations int64 `json:"reservations"`
  263. ReservationsRemaining int64 `json:"reservations_remaining"`
  264. AttachmentTotalSize int64 `json:"attachment_total_size"`
  265. AttachmentTotalSizeRemaining int64 `json:"attachment_total_size_remaining"`
  266. }
  267. type apiAccountReservation struct {
  268. Topic string `json:"topic"`
  269. Everyone string `json:"everyone"`
  270. }
  271. type apiAccountBilling struct {
  272. Customer bool `json:"customer"`
  273. Subscription bool `json:"subscription"`
  274. Status string `json:"status,omitempty"`
  275. Interval string `json:"interval,omitempty"`
  276. PaidUntil int64 `json:"paid_until,omitempty"`
  277. CancelAt int64 `json:"cancel_at,omitempty"`
  278. }
  279. type apiAccountResponse struct {
  280. Username string `json:"username"`
  281. Role string `json:"role,omitempty"`
  282. SyncTopic string `json:"sync_topic,omitempty"`
  283. Language string `json:"language,omitempty"`
  284. Notification *user.NotificationPrefs `json:"notification,omitempty"`
  285. Subscriptions []*user.Subscription `json:"subscriptions,omitempty"`
  286. Reservations []*apiAccountReservation `json:"reservations,omitempty"`
  287. Tokens []*apiAccountTokenResponse `json:"tokens,omitempty"`
  288. Tier *apiAccountTier `json:"tier,omitempty"`
  289. Limits *apiAccountLimits `json:"limits,omitempty"`
  290. Stats *apiAccountStats `json:"stats,omitempty"`
  291. Billing *apiAccountBilling `json:"billing,omitempty"`
  292. }
  293. type apiAccountReservationRequest struct {
  294. Topic string `json:"topic"`
  295. Everyone string `json:"everyone"`
  296. }
  297. type apiConfigResponse struct {
  298. BaseURL string `json:"base_url"`
  299. AppRoot string `json:"app_root"`
  300. EnableLogin bool `json:"enable_login"`
  301. EnableSignup bool `json:"enable_signup"`
  302. EnablePayments bool `json:"enable_payments"`
  303. EnableReservations bool `json:"enable_reservations"`
  304. BillingContact string `json:"billing_contact"`
  305. DisallowedTopics []string `json:"disallowed_topics"`
  306. }
  307. type apiAccountBillingPrices struct {
  308. Month int64 `json:"month"`
  309. Year int64 `json:"year"`
  310. }
  311. type apiAccountBillingTier struct {
  312. Code string `json:"code,omitempty"`
  313. Name string `json:"name,omitempty"`
  314. Prices *apiAccountBillingPrices `json:"prices,omitempty"`
  315. Limits *apiAccountLimits `json:"limits"`
  316. }
  317. type apiAccountBillingSubscriptionCreateResponse struct {
  318. RedirectURL string `json:"redirect_url"`
  319. }
  320. type apiAccountBillingSubscriptionChangeRequest struct {
  321. Tier string `json:"tier"`
  322. Interval string `json:"interval"`
  323. }
  324. type apiAccountBillingPortalRedirectResponse struct {
  325. RedirectURL string `json:"redirect_url"`
  326. }
  327. type apiAccountSyncTopicResponse struct {
  328. Event string `json:"event"`
  329. }
  330. type apiSuccessResponse struct {
  331. Success bool `json:"success"`
  332. }
  333. func newSuccessResponse() *apiSuccessResponse {
  334. return &apiSuccessResponse{
  335. Success: true,
  336. }
  337. }
  338. type apiStripeSubscriptionUpdatedEvent struct {
  339. ID string `json:"id"`
  340. Customer string `json:"customer"`
  341. Status string `json:"status"`
  342. CurrentPeriodEnd int64 `json:"current_period_end"`
  343. CancelAt int64 `json:"cancel_at"`
  344. Items *struct {
  345. Data []*struct {
  346. Price *struct {
  347. ID string `json:"id"`
  348. Recurring *struct {
  349. Interval string `json:"interval"`
  350. } `json:"recurring"`
  351. } `json:"price"`
  352. } `json:"data"`
  353. } `json:"items"`
  354. }
  355. type apiStripeSubscriptionDeletedEvent struct {
  356. ID string `json:"id"`
  357. Customer string `json:"customer"`
  358. }