types.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. package server
  2. import (
  3. "net/http"
  4. "net/netip"
  5. "time"
  6. "heckel.io/ntfy/v2/log"
  7. "heckel.io/ntfy/v2/user"
  8. "heckel.io/ntfy/v2/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. ContentType string `json:"content_type,omitempty"` // text/plain by default (if empty), or text/markdown
  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. Markdown bool `json:"markdown"`
  94. Filename string `json:"filename"`
  95. Email string `json:"email"`
  96. Call string `json:"call"`
  97. Cache string `json:"cache"` // use string as it defaults to true (or use &bool instead)
  98. Firebase string `json:"firebase"` // use string as it defaults to true (or use &bool instead)
  99. Delay string `json:"delay"`
  100. }
  101. // messageEncoder is a function that knows how to encode a message
  102. type messageEncoder func(msg *message) (string, error)
  103. // newMessage creates a new message with the current timestamp
  104. func newMessage(event, topic, msg string) *message {
  105. return &message{
  106. ID: util.RandomString(messageIDLength),
  107. Time: time.Now().Unix(),
  108. Event: event,
  109. Topic: topic,
  110. Message: msg,
  111. }
  112. }
  113. // newOpenMessage is a convenience method to create an open message
  114. func newOpenMessage(topic string) *message {
  115. return newMessage(openEvent, topic, "")
  116. }
  117. // newKeepaliveMessage is a convenience method to create a keepalive message
  118. func newKeepaliveMessage(topic string) *message {
  119. return newMessage(keepaliveEvent, topic, "")
  120. }
  121. // newDefaultMessage is a convenience method to create a notification message
  122. func newDefaultMessage(topic, msg string) *message {
  123. return newMessage(messageEvent, topic, msg)
  124. }
  125. // newPollRequestMessage is a convenience method to create a poll request message
  126. func newPollRequestMessage(topic, pollID string) *message {
  127. m := newMessage(pollRequestEvent, topic, newMessageBody)
  128. m.PollID = pollID
  129. return m
  130. }
  131. func validMessageID(s string) bool {
  132. return util.ValidRandomString(s, messageIDLength)
  133. }
  134. type sinceMarker struct {
  135. time time.Time
  136. id string
  137. }
  138. func newSinceTime(timestamp int64) sinceMarker {
  139. return sinceMarker{time.Unix(timestamp, 0), ""}
  140. }
  141. func newSinceID(id string) sinceMarker {
  142. return sinceMarker{time.Unix(0, 0), id}
  143. }
  144. func (t sinceMarker) IsAll() bool {
  145. return t == sinceAllMessages
  146. }
  147. func (t sinceMarker) IsNone() bool {
  148. return t == sinceNoMessages
  149. }
  150. func (t sinceMarker) IsID() bool {
  151. return t.id != ""
  152. }
  153. func (t sinceMarker) Time() time.Time {
  154. return t.time
  155. }
  156. func (t sinceMarker) ID() string {
  157. return t.id
  158. }
  159. var (
  160. sinceAllMessages = sinceMarker{time.Unix(0, 0), ""}
  161. sinceNoMessages = sinceMarker{time.Unix(1, 0), ""}
  162. )
  163. type queryFilter struct {
  164. ID string
  165. Message string
  166. Title string
  167. Tags []string
  168. Priority []int
  169. }
  170. func parseQueryFilters(r *http.Request) (*queryFilter, error) {
  171. idFilter := readParam(r, "x-id", "id")
  172. messageFilter := readParam(r, "x-message", "message", "m")
  173. titleFilter := readParam(r, "x-title", "title", "t")
  174. tagsFilter := util.SplitNoEmpty(readParam(r, "x-tags", "tags", "tag", "ta"), ",")
  175. priorityFilter := make([]int, 0)
  176. for _, p := range util.SplitNoEmpty(readParam(r, "x-priority", "priority", "prio", "p"), ",") {
  177. priority, err := util.ParsePriority(p)
  178. if err != nil {
  179. return nil, errHTTPBadRequestPriorityInvalid
  180. }
  181. priorityFilter = append(priorityFilter, priority)
  182. }
  183. return &queryFilter{
  184. ID: idFilter,
  185. Message: messageFilter,
  186. Title: titleFilter,
  187. Tags: tagsFilter,
  188. Priority: priorityFilter,
  189. }, nil
  190. }
  191. func (q *queryFilter) Pass(msg *message) bool {
  192. if msg.Event != messageEvent {
  193. return true // filters only apply to messages
  194. } else if q.ID != "" && msg.ID != q.ID {
  195. return false
  196. } else if q.Message != "" && msg.Message != q.Message {
  197. return false
  198. } else if q.Title != "" && msg.Title != q.Title {
  199. return false
  200. }
  201. messagePriority := msg.Priority
  202. if messagePriority == 0 {
  203. messagePriority = 3 // For query filters, default priority (3) is the same as "not set" (0)
  204. }
  205. if len(q.Priority) > 0 && !util.Contains(q.Priority, messagePriority) {
  206. return false
  207. }
  208. if len(q.Tags) > 0 && !util.ContainsAll(msg.Tags, q.Tags) {
  209. return false
  210. }
  211. return true
  212. }
  213. type apiHealthResponse struct {
  214. Healthy bool `json:"healthy"`
  215. }
  216. type apiStatsResponse struct {
  217. Messages int64 `json:"messages"`
  218. MessagesRate float64 `json:"messages_rate"` // Average number of messages per second
  219. }
  220. type apiUserAddRequest struct {
  221. Username string `json:"username"`
  222. Password string `json:"password"`
  223. Tier string `json:"tier"`
  224. // Do not add 'role' here. We don't want to add admins via the API.
  225. }
  226. type apiUserResponse struct {
  227. Username string `json:"username"`
  228. Role string `json:"role"`
  229. Tier string `json:"tier,omitempty"`
  230. Grants []*apiUserGrantResponse `json:"grants,omitempty"`
  231. }
  232. type apiUserGrantResponse struct {
  233. Topic string `json:"topic"` // This may be a pattern
  234. Permission string `json:"permission"`
  235. }
  236. type apiUserDeleteRequest struct {
  237. Username string `json:"username"`
  238. }
  239. type apiAccessAllowRequest struct {
  240. Username string `json:"username"`
  241. Topic string `json:"topic"` // This may be a pattern
  242. Permission string `json:"permission"`
  243. }
  244. type apiAccessResetRequest struct {
  245. Username string `json:"username"`
  246. Topic string `json:"topic"`
  247. }
  248. type apiAccountCreateRequest struct {
  249. Username string `json:"username"`
  250. Password string `json:"password"`
  251. }
  252. type apiAccountPasswordChangeRequest struct {
  253. Password string `json:"password"`
  254. NewPassword string `json:"new_password"`
  255. }
  256. type apiAccountDeleteRequest struct {
  257. Password string `json:"password"`
  258. }
  259. type apiAccountTokenIssueRequest struct {
  260. Label *string `json:"label"`
  261. Expires *int64 `json:"expires"` // Unix timestamp
  262. }
  263. type apiAccountTokenUpdateRequest struct {
  264. Token string `json:"token"`
  265. Label *string `json:"label"`
  266. Expires *int64 `json:"expires"` // Unix timestamp
  267. }
  268. type apiAccountTokenResponse struct {
  269. Token string `json:"token"`
  270. Label string `json:"label,omitempty"`
  271. LastAccess int64 `json:"last_access,omitempty"`
  272. LastOrigin string `json:"last_origin,omitempty"`
  273. Expires int64 `json:"expires,omitempty"` // Unix timestamp
  274. }
  275. type apiAccountPhoneNumberVerifyRequest struct {
  276. Number string `json:"number"`
  277. Channel string `json:"channel"`
  278. }
  279. type apiAccountPhoneNumberAddRequest struct {
  280. Number string `json:"number"`
  281. Code string `json:"code"` // Only set when adding a phone number
  282. }
  283. type apiAccountTier struct {
  284. Code string `json:"code"`
  285. Name string `json:"name"`
  286. }
  287. type apiAccountLimits struct {
  288. Basis string `json:"basis,omitempty"` // "ip" or "tier"
  289. Messages int64 `json:"messages"`
  290. MessagesExpiryDuration int64 `json:"messages_expiry_duration"`
  291. Emails int64 `json:"emails"`
  292. Calls int64 `json:"calls"`
  293. Reservations int64 `json:"reservations"`
  294. AttachmentTotalSize int64 `json:"attachment_total_size"`
  295. AttachmentFileSize int64 `json:"attachment_file_size"`
  296. AttachmentExpiryDuration int64 `json:"attachment_expiry_duration"`
  297. AttachmentBandwidth int64 `json:"attachment_bandwidth"`
  298. }
  299. type apiAccountStats struct {
  300. Messages int64 `json:"messages"`
  301. MessagesRemaining int64 `json:"messages_remaining"`
  302. Emails int64 `json:"emails"`
  303. EmailsRemaining int64 `json:"emails_remaining"`
  304. Calls int64 `json:"calls"`
  305. CallsRemaining int64 `json:"calls_remaining"`
  306. Reservations int64 `json:"reservations"`
  307. ReservationsRemaining int64 `json:"reservations_remaining"`
  308. AttachmentTotalSize int64 `json:"attachment_total_size"`
  309. AttachmentTotalSizeRemaining int64 `json:"attachment_total_size_remaining"`
  310. }
  311. type apiAccountReservation struct {
  312. Topic string `json:"topic"`
  313. Everyone string `json:"everyone"`
  314. }
  315. type apiAccountBilling struct {
  316. Customer bool `json:"customer"`
  317. Subscription bool `json:"subscription"`
  318. Status string `json:"status,omitempty"`
  319. Interval string `json:"interval,omitempty"`
  320. PaidUntil int64 `json:"paid_until,omitempty"`
  321. CancelAt int64 `json:"cancel_at,omitempty"`
  322. }
  323. type apiAccountResponse struct {
  324. Username string `json:"username"`
  325. Role string `json:"role,omitempty"`
  326. SyncTopic string `json:"sync_topic,omitempty"`
  327. Language string `json:"language,omitempty"`
  328. Notification *user.NotificationPrefs `json:"notification,omitempty"`
  329. Subscriptions []*user.Subscription `json:"subscriptions,omitempty"`
  330. Reservations []*apiAccountReservation `json:"reservations,omitempty"`
  331. Tokens []*apiAccountTokenResponse `json:"tokens,omitempty"`
  332. PhoneNumbers []string `json:"phone_numbers,omitempty"`
  333. Tier *apiAccountTier `json:"tier,omitempty"`
  334. Limits *apiAccountLimits `json:"limits,omitempty"`
  335. Stats *apiAccountStats `json:"stats,omitempty"`
  336. Billing *apiAccountBilling `json:"billing,omitempty"`
  337. }
  338. type apiAccountReservationRequest struct {
  339. Topic string `json:"topic"`
  340. Everyone string `json:"everyone"`
  341. }
  342. type apiConfigResponse struct {
  343. BaseURL string `json:"base_url"`
  344. AppRoot string `json:"app_root"`
  345. EnableLogin bool `json:"enable_login"`
  346. EnableSignup bool `json:"enable_signup"`
  347. EnablePayments bool `json:"enable_payments"`
  348. EnableCalls bool `json:"enable_calls"`
  349. EnableEmails bool `json:"enable_emails"`
  350. EnableReservations bool `json:"enable_reservations"`
  351. EnableWebPush bool `json:"enable_web_push"`
  352. BillingContact string `json:"billing_contact"`
  353. WebPushPublicKey string `json:"web_push_public_key"`
  354. DisallowedTopics []string `json:"disallowed_topics"`
  355. }
  356. type apiAccountBillingPrices struct {
  357. Month int64 `json:"month"`
  358. Year int64 `json:"year"`
  359. }
  360. type apiAccountBillingTier struct {
  361. Code string `json:"code,omitempty"`
  362. Name string `json:"name,omitempty"`
  363. Prices *apiAccountBillingPrices `json:"prices,omitempty"`
  364. Limits *apiAccountLimits `json:"limits"`
  365. }
  366. type apiAccountBillingSubscriptionCreateResponse struct {
  367. RedirectURL string `json:"redirect_url"`
  368. }
  369. type apiAccountBillingSubscriptionChangeRequest struct {
  370. Tier string `json:"tier"`
  371. Interval string `json:"interval"`
  372. }
  373. type apiAccountBillingPortalRedirectResponse struct {
  374. RedirectURL string `json:"redirect_url"`
  375. }
  376. type apiAccountSyncTopicResponse struct {
  377. Event string `json:"event"`
  378. }
  379. type apiSuccessResponse struct {
  380. Success bool `json:"success"`
  381. }
  382. func newSuccessResponse() *apiSuccessResponse {
  383. return &apiSuccessResponse{
  384. Success: true,
  385. }
  386. }
  387. type apiStripeSubscriptionUpdatedEvent struct {
  388. ID string `json:"id"`
  389. Customer string `json:"customer"`
  390. Status string `json:"status"`
  391. CurrentPeriodEnd int64 `json:"current_period_end"`
  392. CancelAt int64 `json:"cancel_at"`
  393. Items *struct {
  394. Data []*struct {
  395. Price *struct {
  396. ID string `json:"id"`
  397. Recurring *struct {
  398. Interval string `json:"interval"`
  399. } `json:"recurring"`
  400. } `json:"price"`
  401. } `json:"data"`
  402. } `json:"items"`
  403. }
  404. type apiStripeSubscriptionDeletedEvent struct {
  405. ID string `json:"id"`
  406. Customer string `json:"customer"`
  407. }
  408. type apiWebPushUpdateSubscriptionRequest struct {
  409. Endpoint string `json:"endpoint"`
  410. Auth string `json:"auth"`
  411. P256dh string `json:"p256dh"`
  412. Topics []string `json:"topics"`
  413. }
  414. // List of possible Web Push events (see sw.js)
  415. const (
  416. webPushMessageEvent = "message"
  417. webPushExpiringEvent = "subscription_expiring"
  418. )
  419. type webPushPayload struct {
  420. Event string `json:"event"`
  421. SubscriptionID string `json:"subscription_id"`
  422. Message *message `json:"message"`
  423. }
  424. func newWebPushPayload(subscriptionID string, message *message) *webPushPayload {
  425. return &webPushPayload{
  426. Event: webPushMessageEvent,
  427. SubscriptionID: subscriptionID,
  428. Message: message,
  429. }
  430. }
  431. type webPushControlMessagePayload struct {
  432. Event string `json:"event"`
  433. }
  434. func newWebPushSubscriptionExpiringPayload() *webPushControlMessagePayload {
  435. return &webPushControlMessagePayload{
  436. Event: webPushExpiringEvent,
  437. }
  438. }
  439. type webPushSubscription struct {
  440. ID string
  441. Endpoint string
  442. Auth string
  443. P256dh string
  444. UserID string
  445. }
  446. func (w *webPushSubscription) Context() log.Context {
  447. return map[string]any{
  448. "web_push_subscription_id": w.ID,
  449. "web_push_subscription_user_id": w.UserID,
  450. "web_push_subscription_endpoint": w.Endpoint,
  451. }
  452. }
  453. // https://developer.mozilla.org/en-US/docs/Web/Manifest
  454. type webManifestResponse struct {
  455. Name string `json:"name"`
  456. Description string `json:"description"`
  457. ShortName string `json:"short_name"`
  458. Scope string `json:"scope"`
  459. StartURL string `json:"start_url"`
  460. Display string `json:"display"`
  461. BackgroundColor string `json:"background_color"`
  462. ThemeColor string `json:"theme_color"`
  463. Icons []*webManifestIcon `json:"icons"`
  464. }
  465. type webManifestIcon struct {
  466. SRC string `json:"src"`
  467. Sizes string `json:"sizes"`
  468. Type string `json:"type"`
  469. }