types.go 16 KB

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