types.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. package server
  2. import (
  3. "net/http"
  4. "net/netip"
  5. "time"
  6. "heckel.io/ntfy/log"
  7. "heckel.io/ntfy/user"
  8. "github.com/SherClockHolmes/webpush-go"
  9. "heckel.io/ntfy/util"
  10. )
  11. // List of possible events
  12. const (
  13. openEvent = "open"
  14. keepaliveEvent = "keepalive"
  15. messageEvent = "message"
  16. pollRequestEvent = "poll_request"
  17. )
  18. const (
  19. messageIDLength = 12
  20. )
  21. // message represents a message published to a topic
  22. type message struct {
  23. ID string `json:"id"` // Random message ID
  24. Time int64 `json:"time"` // Unix time in seconds
  25. Expires int64 `json:"expires,omitempty"` // Unix time in seconds (not required for open/keepalive)
  26. Event string `json:"event"` // One of the above
  27. Topic string `json:"topic"`
  28. Title string `json:"title,omitempty"`
  29. Message string `json:"message,omitempty"`
  30. Priority int `json:"priority,omitempty"`
  31. Tags []string `json:"tags,omitempty"`
  32. Click string `json:"click,omitempty"`
  33. Icon string `json:"icon,omitempty"`
  34. Actions []*action `json:"actions,omitempty"`
  35. Attachment *attachment `json:"attachment,omitempty"`
  36. PollID string `json:"poll_id,omitempty"`
  37. Encoding string `json:"encoding,omitempty"` // empty for raw UTF-8, or "base64" for encoded bytes
  38. Sender netip.Addr `json:"-"` // IP address of uploader, used for rate limiting
  39. User string `json:"-"` // UserID of the uploader, used to associated attachments
  40. }
  41. func (m *message) Context() log.Context {
  42. fields := map[string]any{
  43. "topic": m.Topic,
  44. "message_id": m.ID,
  45. "message_time": m.Time,
  46. "message_event": m.Event,
  47. "message_body_size": len(m.Message),
  48. }
  49. if m.Sender.IsValid() {
  50. fields["message_sender"] = m.Sender.String()
  51. }
  52. if m.User != "" {
  53. fields["message_user"] = m.User
  54. }
  55. return fields
  56. }
  57. type attachment struct {
  58. Name string `json:"name"`
  59. Type string `json:"type,omitempty"`
  60. Size int64 `json:"size,omitempty"`
  61. Expires int64 `json:"expires,omitempty"`
  62. URL string `json:"url"`
  63. }
  64. type action struct {
  65. ID string `json:"id"`
  66. Action string `json:"action"` // "view", "broadcast", or "http"
  67. Label string `json:"label"` // action button label
  68. Clear bool `json:"clear"` // clear notification after successful execution
  69. URL string `json:"url,omitempty"` // used in "view" and "http" actions
  70. Method string `json:"method,omitempty"` // used in "http" action, default is POST (!)
  71. Headers map[string]string `json:"headers,omitempty"` // used in "http" action
  72. Body string `json:"body,omitempty"` // used in "http" action
  73. Intent string `json:"intent,omitempty"` // used in "broadcast" action
  74. Extras map[string]string `json:"extras,omitempty"` // used in "broadcast" action
  75. }
  76. func newAction() *action {
  77. return &action{
  78. Headers: make(map[string]string),
  79. Extras: make(map[string]string),
  80. }
  81. }
  82. // publishMessage is used as input when publishing as JSON
  83. type publishMessage struct {
  84. Topic string `json:"topic"`
  85. Title string `json:"title"`
  86. Message string `json:"message"`
  87. Priority int `json:"priority"`
  88. Tags []string `json:"tags"`
  89. Click string `json:"click"`
  90. Icon string `json:"icon"`
  91. Actions []action `json:"actions"`
  92. Attach string `json:"attach"`
  93. Filename string `json:"filename"`
  94. Email string `json:"email"`
  95. Call string `json:"call"`
  96. Delay string `json:"delay"`
  97. }
  98. // messageEncoder is a function that knows how to encode a message
  99. type messageEncoder func(msg *message) (string, error)
  100. // newMessage creates a new message with the current timestamp
  101. func newMessage(event, topic, msg string) *message {
  102. return &message{
  103. ID: util.RandomString(messageIDLength),
  104. Time: time.Now().Unix(),
  105. Event: event,
  106. Topic: topic,
  107. Message: msg,
  108. }
  109. }
  110. // newOpenMessage is a convenience method to create an open message
  111. func newOpenMessage(topic string) *message {
  112. return newMessage(openEvent, topic, "")
  113. }
  114. // newKeepaliveMessage is a convenience method to create a keepalive message
  115. func newKeepaliveMessage(topic string) *message {
  116. return newMessage(keepaliveEvent, topic, "")
  117. }
  118. // newDefaultMessage is a convenience method to create a notification message
  119. func newDefaultMessage(topic, msg string) *message {
  120. return newMessage(messageEvent, topic, msg)
  121. }
  122. // newPollRequestMessage is a convenience method to create a poll request message
  123. func newPollRequestMessage(topic, pollID string) *message {
  124. m := newMessage(pollRequestEvent, topic, newMessageBody)
  125. m.PollID = pollID
  126. return m
  127. }
  128. func validMessageID(s string) bool {
  129. return util.ValidRandomString(s, messageIDLength)
  130. }
  131. type sinceMarker struct {
  132. time time.Time
  133. id string
  134. }
  135. func newSinceTime(timestamp int64) sinceMarker {
  136. return sinceMarker{time.Unix(timestamp, 0), ""}
  137. }
  138. func newSinceID(id string) sinceMarker {
  139. return sinceMarker{time.Unix(0, 0), id}
  140. }
  141. func (t sinceMarker) IsAll() bool {
  142. return t == sinceAllMessages
  143. }
  144. func (t sinceMarker) IsNone() bool {
  145. return t == sinceNoMessages
  146. }
  147. func (t sinceMarker) IsID() bool {
  148. return t.id != ""
  149. }
  150. func (t sinceMarker) Time() time.Time {
  151. return t.time
  152. }
  153. func (t sinceMarker) ID() string {
  154. return t.id
  155. }
  156. var (
  157. sinceAllMessages = sinceMarker{time.Unix(0, 0), ""}
  158. sinceNoMessages = sinceMarker{time.Unix(1, 0), ""}
  159. )
  160. type queryFilter struct {
  161. ID string
  162. Message string
  163. Title string
  164. Tags []string
  165. Priority []int
  166. }
  167. func parseQueryFilters(r *http.Request) (*queryFilter, error) {
  168. idFilter := readParam(r, "x-id", "id")
  169. messageFilter := readParam(r, "x-message", "message", "m")
  170. titleFilter := readParam(r, "x-title", "title", "t")
  171. tagsFilter := util.SplitNoEmpty(readParam(r, "x-tags", "tags", "tag", "ta"), ",")
  172. priorityFilter := make([]int, 0)
  173. for _, p := range util.SplitNoEmpty(readParam(r, "x-priority", "priority", "prio", "p"), ",") {
  174. priority, err := util.ParsePriority(p)
  175. if err != nil {
  176. return nil, errHTTPBadRequestPriorityInvalid
  177. }
  178. priorityFilter = append(priorityFilter, priority)
  179. }
  180. return &queryFilter{
  181. ID: idFilter,
  182. Message: messageFilter,
  183. Title: titleFilter,
  184. Tags: tagsFilter,
  185. Priority: priorityFilter,
  186. }, nil
  187. }
  188. func (q *queryFilter) Pass(msg *message) bool {
  189. if msg.Event != messageEvent {
  190. return true // filters only apply to messages
  191. } else if q.ID != "" && msg.ID != q.ID {
  192. return false
  193. } else if q.Message != "" && msg.Message != q.Message {
  194. return false
  195. } else if q.Title != "" && msg.Title != q.Title {
  196. return false
  197. }
  198. messagePriority := msg.Priority
  199. if messagePriority == 0 {
  200. messagePriority = 3 // For query filters, default priority (3) is the same as "not set" (0)
  201. }
  202. if len(q.Priority) > 0 && !util.Contains(q.Priority, messagePriority) {
  203. return false
  204. }
  205. if len(q.Tags) > 0 && !util.ContainsAll(msg.Tags, q.Tags) {
  206. return false
  207. }
  208. return true
  209. }
  210. type apiHealthResponse struct {
  211. Healthy bool `json:"healthy"`
  212. }
  213. type apiStatsResponse struct {
  214. Messages int64 `json:"messages"`
  215. MessagesRate float64 `json:"messages_rate"` // Average number of messages per second
  216. }
  217. type apiUserAddRequest struct {
  218. Username string `json:"username"`
  219. Password string `json:"password"`
  220. Tier string `json:"tier"`
  221. // Do not add 'role' here. We don't want to add admins via the API.
  222. }
  223. type apiUserResponse struct {
  224. Username string `json:"username"`
  225. Role string `json:"role"`
  226. Tier string `json:"tier,omitempty"`
  227. Grants []*apiUserGrantResponse `json:"grants,omitempty"`
  228. }
  229. type apiUserGrantResponse struct {
  230. Topic string `json:"topic"` // This may be a pattern
  231. Permission string `json:"permission"`
  232. }
  233. type apiUserDeleteRequest struct {
  234. Username string `json:"username"`
  235. }
  236. type apiAccessAllowRequest struct {
  237. Username string `json:"username"`
  238. Topic string `json:"topic"` // This may be a pattern
  239. Permission string `json:"permission"`
  240. }
  241. type apiAccessResetRequest struct {
  242. Username string `json:"username"`
  243. Topic string `json:"topic"`
  244. }
  245. type apiAccountCreateRequest struct {
  246. Username string `json:"username"`
  247. Password string `json:"password"`
  248. }
  249. type apiAccountPasswordChangeRequest struct {
  250. Password string `json:"password"`
  251. NewPassword string `json:"new_password"`
  252. }
  253. type apiAccountDeleteRequest struct {
  254. Password string `json:"password"`
  255. }
  256. type apiAccountTokenIssueRequest struct {
  257. Label *string `json:"label"`
  258. Expires *int64 `json:"expires"` // Unix timestamp
  259. }
  260. type apiAccountTokenUpdateRequest struct {
  261. Token string `json:"token"`
  262. Label *string `json:"label"`
  263. Expires *int64 `json:"expires"` // Unix timestamp
  264. }
  265. type apiAccountTokenResponse struct {
  266. Token string `json:"token"`
  267. Label string `json:"label,omitempty"`
  268. LastAccess int64 `json:"last_access,omitempty"`
  269. LastOrigin string `json:"last_origin,omitempty"`
  270. Expires int64 `json:"expires,omitempty"` // Unix timestamp
  271. }
  272. type apiAccountPhoneNumberVerifyRequest struct {
  273. Number string `json:"number"`
  274. Channel string `json:"channel"`
  275. }
  276. type apiAccountPhoneNumberAddRequest struct {
  277. Number string `json:"number"`
  278. Code string `json:"code"` // Only set when adding a phone number
  279. }
  280. type apiAccountTier struct {
  281. Code string `json:"code"`
  282. Name string `json:"name"`
  283. }
  284. type apiAccountLimits struct {
  285. Basis string `json:"basis,omitempty"` // "ip" or "tier"
  286. Messages int64 `json:"messages"`
  287. MessagesExpiryDuration int64 `json:"messages_expiry_duration"`
  288. Emails int64 `json:"emails"`
  289. Calls int64 `json:"calls"`
  290. Reservations int64 `json:"reservations"`
  291. AttachmentTotalSize int64 `json:"attachment_total_size"`
  292. AttachmentFileSize int64 `json:"attachment_file_size"`
  293. AttachmentExpiryDuration int64 `json:"attachment_expiry_duration"`
  294. AttachmentBandwidth int64 `json:"attachment_bandwidth"`
  295. }
  296. type apiAccountStats struct {
  297. Messages int64 `json:"messages"`
  298. MessagesRemaining int64 `json:"messages_remaining"`
  299. Emails int64 `json:"emails"`
  300. EmailsRemaining int64 `json:"emails_remaining"`
  301. Calls int64 `json:"calls"`
  302. CallsRemaining int64 `json:"calls_remaining"`
  303. Reservations int64 `json:"reservations"`
  304. ReservationsRemaining int64 `json:"reservations_remaining"`
  305. AttachmentTotalSize int64 `json:"attachment_total_size"`
  306. AttachmentTotalSizeRemaining int64 `json:"attachment_total_size_remaining"`
  307. }
  308. type apiAccountReservation struct {
  309. Topic string `json:"topic"`
  310. Everyone string `json:"everyone"`
  311. }
  312. type apiAccountBilling struct {
  313. Customer bool `json:"customer"`
  314. Subscription bool `json:"subscription"`
  315. Status string `json:"status,omitempty"`
  316. Interval string `json:"interval,omitempty"`
  317. PaidUntil int64 `json:"paid_until,omitempty"`
  318. CancelAt int64 `json:"cancel_at,omitempty"`
  319. }
  320. type apiAccountResponse struct {
  321. Username string `json:"username"`
  322. Role string `json:"role,omitempty"`
  323. SyncTopic string `json:"sync_topic,omitempty"`
  324. Language string `json:"language,omitempty"`
  325. Notification *user.NotificationPrefs `json:"notification,omitempty"`
  326. Subscriptions []*user.Subscription `json:"subscriptions,omitempty"`
  327. Reservations []*apiAccountReservation `json:"reservations,omitempty"`
  328. Tokens []*apiAccountTokenResponse `json:"tokens,omitempty"`
  329. PhoneNumbers []string `json:"phone_numbers,omitempty"`
  330. Tier *apiAccountTier `json:"tier,omitempty"`
  331. Limits *apiAccountLimits `json:"limits,omitempty"`
  332. Stats *apiAccountStats `json:"stats,omitempty"`
  333. Billing *apiAccountBilling `json:"billing,omitempty"`
  334. }
  335. type apiAccountReservationRequest struct {
  336. Topic string `json:"topic"`
  337. Everyone string `json:"everyone"`
  338. }
  339. type apiConfigResponse struct {
  340. BaseURL string `json:"base_url"`
  341. AppRoot string `json:"app_root"`
  342. EnableLogin bool `json:"enable_login"`
  343. EnableSignup bool `json:"enable_signup"`
  344. EnablePayments bool `json:"enable_payments"`
  345. EnableCalls bool `json:"enable_calls"`
  346. EnableEmails bool `json:"enable_emails"`
  347. EnableReservations bool `json:"enable_reservations"`
  348. EnableWebPush bool `json:"enable_web_push"`
  349. BillingContact string `json:"billing_contact"`
  350. WebPushPublicKey string `json:"web_push_public_key"`
  351. DisallowedTopics []string `json:"disallowed_topics"`
  352. }
  353. type apiAccountBillingPrices struct {
  354. Month int64 `json:"month"`
  355. Year int64 `json:"year"`
  356. }
  357. type apiAccountBillingTier struct {
  358. Code string `json:"code,omitempty"`
  359. Name string `json:"name,omitempty"`
  360. Prices *apiAccountBillingPrices `json:"prices,omitempty"`
  361. Limits *apiAccountLimits `json:"limits"`
  362. }
  363. type apiAccountBillingSubscriptionCreateResponse struct {
  364. RedirectURL string `json:"redirect_url"`
  365. }
  366. type apiAccountBillingSubscriptionChangeRequest struct {
  367. Tier string `json:"tier"`
  368. Interval string `json:"interval"`
  369. }
  370. type apiAccountBillingPortalRedirectResponse struct {
  371. RedirectURL string `json:"redirect_url"`
  372. }
  373. type apiAccountSyncTopicResponse struct {
  374. Event string `json:"event"`
  375. }
  376. type apiSuccessResponse struct {
  377. Success bool `json:"success"`
  378. }
  379. func newSuccessResponse() *apiSuccessResponse {
  380. return &apiSuccessResponse{
  381. Success: true,
  382. }
  383. }
  384. type apiStripeSubscriptionUpdatedEvent struct {
  385. ID string `json:"id"`
  386. Customer string `json:"customer"`
  387. Status string `json:"status"`
  388. CurrentPeriodEnd int64 `json:"current_period_end"`
  389. CancelAt int64 `json:"cancel_at"`
  390. Items *struct {
  391. Data []*struct {
  392. Price *struct {
  393. ID string `json:"id"`
  394. Recurring *struct {
  395. Interval string `json:"interval"`
  396. } `json:"recurring"`
  397. } `json:"price"`
  398. } `json:"data"`
  399. } `json:"items"`
  400. }
  401. type apiStripeSubscriptionDeletedEvent struct {
  402. ID string `json:"id"`
  403. Customer string `json:"customer"`
  404. }
  405. // List of possible Web Push events
  406. const (
  407. webPushMessageEvent = "message"
  408. webPushExpiringEvent = "subscription_expiring"
  409. )
  410. type webPushPayload struct {
  411. Event string `json:"event"`
  412. SubscriptionID string `json:"subscription_id"`
  413. Message *message `json:"message"`
  414. }
  415. func newWebPushPayload(subscriptionID string, message *message) webPushPayload {
  416. return webPushPayload{
  417. Event: webPushMessageEvent,
  418. SubscriptionID: subscriptionID,
  419. Message: message,
  420. }
  421. }
  422. type webPushControlMessagePayload struct {
  423. Event string `json:"event"`
  424. }
  425. func newWebPushSubscriptionExpiringPayload() webPushControlMessagePayload {
  426. return webPushControlMessagePayload{
  427. Event: webPushExpiringEvent,
  428. }
  429. }
  430. type webPushSubscription struct {
  431. BrowserSubscription webpush.Subscription
  432. UserID string
  433. }
  434. type webPushSubscriptionPayload struct {
  435. BrowserSubscription webpush.Subscription `json:"browser_subscription"`
  436. Topics []string `json:"topics"`
  437. }