types.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. Call string `json:"call"`
  95. Delay string `json:"delay"`
  96. }
  97. // messageEncoder is a function that knows how to encode a message
  98. type messageEncoder func(msg *message) (string, error)
  99. // newMessage creates a new message with the current timestamp
  100. func newMessage(event, topic, msg string) *message {
  101. return &message{
  102. ID: util.RandomString(messageIDLength),
  103. Time: time.Now().Unix(),
  104. Event: event,
  105. Topic: topic,
  106. Message: msg,
  107. }
  108. }
  109. // newOpenMessage is a convenience method to create an open message
  110. func newOpenMessage(topic string) *message {
  111. return newMessage(openEvent, topic, "")
  112. }
  113. // newKeepaliveMessage is a convenience method to create a keepalive message
  114. func newKeepaliveMessage(topic string) *message {
  115. return newMessage(keepaliveEvent, topic, "")
  116. }
  117. // newDefaultMessage is a convenience method to create a notification message
  118. func newDefaultMessage(topic, msg string) *message {
  119. return newMessage(messageEvent, topic, msg)
  120. }
  121. // newPollRequestMessage is a convenience method to create a poll request message
  122. func newPollRequestMessage(topic, pollID string) *message {
  123. m := newMessage(pollRequestEvent, topic, newMessageBody)
  124. m.PollID = pollID
  125. return m
  126. }
  127. func validMessageID(s string) bool {
  128. return util.ValidRandomString(s, messageIDLength)
  129. }
  130. type sinceMarker struct {
  131. time time.Time
  132. id string
  133. }
  134. func newSinceTime(timestamp int64) sinceMarker {
  135. return sinceMarker{time.Unix(timestamp, 0), ""}
  136. }
  137. func newSinceID(id string) sinceMarker {
  138. return sinceMarker{time.Unix(0, 0), id}
  139. }
  140. func (t sinceMarker) IsAll() bool {
  141. return t == sinceAllMessages
  142. }
  143. func (t sinceMarker) IsNone() bool {
  144. return t == sinceNoMessages
  145. }
  146. func (t sinceMarker) IsID() bool {
  147. return t.id != ""
  148. }
  149. func (t sinceMarker) Time() time.Time {
  150. return t.time
  151. }
  152. func (t sinceMarker) ID() string {
  153. return t.id
  154. }
  155. var (
  156. sinceAllMessages = sinceMarker{time.Unix(0, 0), ""}
  157. sinceNoMessages = sinceMarker{time.Unix(1, 0), ""}
  158. )
  159. type queryFilter struct {
  160. ID string
  161. Message string
  162. Title string
  163. Tags []string
  164. Priority []int
  165. }
  166. func parseQueryFilters(r *http.Request) (*queryFilter, error) {
  167. idFilter := readParam(r, "x-id", "id")
  168. messageFilter := readParam(r, "x-message", "message", "m")
  169. titleFilter := readParam(r, "x-title", "title", "t")
  170. tagsFilter := util.SplitNoEmpty(readParam(r, "x-tags", "tags", "tag", "ta"), ",")
  171. priorityFilter := make([]int, 0)
  172. for _, p := range util.SplitNoEmpty(readParam(r, "x-priority", "priority", "prio", "p"), ",") {
  173. priority, err := util.ParsePriority(p)
  174. if err != nil {
  175. return nil, errHTTPBadRequestPriorityInvalid
  176. }
  177. priorityFilter = append(priorityFilter, priority)
  178. }
  179. return &queryFilter{
  180. ID: idFilter,
  181. Message: messageFilter,
  182. Title: titleFilter,
  183. Tags: tagsFilter,
  184. Priority: priorityFilter,
  185. }, nil
  186. }
  187. func (q *queryFilter) Pass(msg *message) bool {
  188. if msg.Event != messageEvent {
  189. return true // filters only apply to messages
  190. } else if q.ID != "" && msg.ID != q.ID {
  191. return false
  192. } else if q.Message != "" && msg.Message != q.Message {
  193. return false
  194. } else if q.Title != "" && msg.Title != q.Title {
  195. return false
  196. }
  197. messagePriority := msg.Priority
  198. if messagePriority == 0 {
  199. messagePriority = 3 // For query filters, default priority (3) is the same as "not set" (0)
  200. }
  201. if len(q.Priority) > 0 && !util.Contains(q.Priority, messagePriority) {
  202. return false
  203. }
  204. if len(q.Tags) > 0 && !util.ContainsAll(msg.Tags, q.Tags) {
  205. return false
  206. }
  207. return true
  208. }
  209. type apiHealthResponse struct {
  210. Healthy bool `json:"healthy"`
  211. }
  212. type apiStatsResponse struct {
  213. Messages int64 `json:"messages"`
  214. MessagesRate float64 `json:"messages_rate"` // Average number of messages per second
  215. }
  216. type apiUserAddRequest struct {
  217. Username string `json:"username"`
  218. Password string `json:"password"`
  219. Tier string `json:"tier"`
  220. // Do not add 'role' here. We don't want to add admins via the API.
  221. }
  222. type apiUserResponse struct {
  223. Username string `json:"username"`
  224. Role string `json:"role"`
  225. Tier string `json:"tier,omitempty"`
  226. Grants []*apiUserGrantResponse `json:"grants,omitempty"`
  227. }
  228. type apiUserGrantResponse struct {
  229. Topic string `json:"topic"` // This may be a pattern
  230. Permission string `json:"permission"`
  231. }
  232. type apiUserDeleteRequest struct {
  233. Username string `json:"username"`
  234. }
  235. type apiAccessAllowRequest struct {
  236. Username string `json:"username"`
  237. Topic string `json:"topic"` // This may be a pattern
  238. Permission string `json:"permission"`
  239. }
  240. type apiAccessResetRequest struct {
  241. Username string `json:"username"`
  242. Topic string `json:"topic"`
  243. }
  244. type apiAccountCreateRequest struct {
  245. Username string `json:"username"`
  246. Password string `json:"password"`
  247. }
  248. type apiAccountPasswordChangeRequest struct {
  249. Password string `json:"password"`
  250. NewPassword string `json:"new_password"`
  251. }
  252. type apiAccountDeleteRequest struct {
  253. Password string `json:"password"`
  254. }
  255. type apiAccountTokenIssueRequest struct {
  256. Label *string `json:"label"`
  257. Expires *int64 `json:"expires"` // Unix timestamp
  258. }
  259. type apiAccountTokenUpdateRequest struct {
  260. Token string `json:"token"`
  261. Label *string `json:"label"`
  262. Expires *int64 `json:"expires"` // Unix timestamp
  263. }
  264. type apiAccountTokenResponse struct {
  265. Token string `json:"token"`
  266. Label string `json:"label,omitempty"`
  267. LastAccess int64 `json:"last_access,omitempty"`
  268. LastOrigin string `json:"last_origin,omitempty"`
  269. Expires int64 `json:"expires,omitempty"` // Unix timestamp
  270. }
  271. type apiAccountPhoneNumberVerifyRequest struct {
  272. Number string `json:"number"`
  273. Channel string `json:"channel"`
  274. }
  275. type apiAccountPhoneNumberAddRequest struct {
  276. Number string `json:"number"`
  277. Code string `json:"code"` // Only set when adding a phone number
  278. }
  279. type apiAccountTier struct {
  280. Code string `json:"code"`
  281. Name string `json:"name"`
  282. }
  283. type apiAccountLimits struct {
  284. Basis string `json:"basis,omitempty"` // "ip" or "tier"
  285. Messages int64 `json:"messages"`
  286. MessagesExpiryDuration int64 `json:"messages_expiry_duration"`
  287. Emails int64 `json:"emails"`
  288. Calls int64 `json:"calls"`
  289. Reservations int64 `json:"reservations"`
  290. AttachmentTotalSize int64 `json:"attachment_total_size"`
  291. AttachmentFileSize int64 `json:"attachment_file_size"`
  292. AttachmentExpiryDuration int64 `json:"attachment_expiry_duration"`
  293. AttachmentBandwidth int64 `json:"attachment_bandwidth"`
  294. }
  295. type apiAccountStats struct {
  296. Messages int64 `json:"messages"`
  297. MessagesRemaining int64 `json:"messages_remaining"`
  298. Emails int64 `json:"emails"`
  299. EmailsRemaining int64 `json:"emails_remaining"`
  300. Calls int64 `json:"calls"`
  301. CallsRemaining int64 `json:"calls_remaining"`
  302. Reservations int64 `json:"reservations"`
  303. ReservationsRemaining int64 `json:"reservations_remaining"`
  304. AttachmentTotalSize int64 `json:"attachment_total_size"`
  305. AttachmentTotalSizeRemaining int64 `json:"attachment_total_size_remaining"`
  306. }
  307. type apiAccountReservation struct {
  308. Topic string `json:"topic"`
  309. Everyone string `json:"everyone"`
  310. }
  311. type apiAccountBilling struct {
  312. Customer bool `json:"customer"`
  313. Subscription bool `json:"subscription"`
  314. Status string `json:"status,omitempty"`
  315. Interval string `json:"interval,omitempty"`
  316. PaidUntil int64 `json:"paid_until,omitempty"`
  317. CancelAt int64 `json:"cancel_at,omitempty"`
  318. }
  319. type apiAccountResponse struct {
  320. Username string `json:"username"`
  321. Role string `json:"role,omitempty"`
  322. SyncTopic string `json:"sync_topic,omitempty"`
  323. Language string `json:"language,omitempty"`
  324. Notification *user.NotificationPrefs `json:"notification,omitempty"`
  325. Subscriptions []*user.Subscription `json:"subscriptions,omitempty"`
  326. Reservations []*apiAccountReservation `json:"reservations,omitempty"`
  327. Tokens []*apiAccountTokenResponse `json:"tokens,omitempty"`
  328. PhoneNumbers []string `json:"phone_numbers,omitempty"`
  329. Tier *apiAccountTier `json:"tier,omitempty"`
  330. Limits *apiAccountLimits `json:"limits,omitempty"`
  331. Stats *apiAccountStats `json:"stats,omitempty"`
  332. Billing *apiAccountBilling `json:"billing,omitempty"`
  333. }
  334. type apiAccountReservationRequest struct {
  335. Topic string `json:"topic"`
  336. Everyone string `json:"everyone"`
  337. }
  338. type apiConfigResponse struct {
  339. BaseURL string `json:"base_url"`
  340. AppRoot string `json:"app_root"`
  341. EnableLogin bool `json:"enable_login"`
  342. EnableSignup bool `json:"enable_signup"`
  343. EnablePayments bool `json:"enable_payments"`
  344. EnableCalls bool `json:"enable_calls"`
  345. EnableEmails bool `json:"enable_emails"`
  346. EnableReservations bool `json:"enable_reservations"`
  347. BillingContact string `json:"billing_contact"`
  348. DisallowedTopics []string `json:"disallowed_topics"`
  349. }
  350. type apiAccountBillingPrices struct {
  351. Month int64 `json:"month"`
  352. Year int64 `json:"year"`
  353. }
  354. type apiAccountBillingTier struct {
  355. Code string `json:"code,omitempty"`
  356. Name string `json:"name,omitempty"`
  357. Prices *apiAccountBillingPrices `json:"prices,omitempty"`
  358. Limits *apiAccountLimits `json:"limits"`
  359. }
  360. type apiAccountBillingSubscriptionCreateResponse struct {
  361. RedirectURL string `json:"redirect_url"`
  362. }
  363. type apiAccountBillingSubscriptionChangeRequest struct {
  364. Tier string `json:"tier"`
  365. Interval string `json:"interval"`
  366. }
  367. type apiAccountBillingPortalRedirectResponse struct {
  368. RedirectURL string `json:"redirect_url"`
  369. }
  370. type apiAccountSyncTopicResponse struct {
  371. Event string `json:"event"`
  372. }
  373. type apiSuccessResponse struct {
  374. Success bool `json:"success"`
  375. }
  376. func newSuccessResponse() *apiSuccessResponse {
  377. return &apiSuccessResponse{
  378. Success: true,
  379. }
  380. }
  381. type apiStripeSubscriptionUpdatedEvent struct {
  382. ID string `json:"id"`
  383. Customer string `json:"customer"`
  384. Status string `json:"status"`
  385. CurrentPeriodEnd int64 `json:"current_period_end"`
  386. CancelAt int64 `json:"cancel_at"`
  387. Items *struct {
  388. Data []*struct {
  389. Price *struct {
  390. ID string `json:"id"`
  391. Recurring *struct {
  392. Interval string `json:"interval"`
  393. } `json:"recurring"`
  394. } `json:"price"`
  395. } `json:"data"`
  396. } `json:"items"`
  397. }
  398. type apiStripeSubscriptionDeletedEvent struct {
  399. ID string `json:"id"`
  400. Customer string `json:"customer"`
  401. }