types.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. messageDeleteEvent = "message_delete"
  16. messageReadEvent = "message_read"
  17. pollRequestEvent = "poll_request"
  18. )
  19. const (
  20. messageIDLength = 12
  21. )
  22. // message represents a message published to a topic
  23. type message struct {
  24. ID string `json:"id"` // Random message ID
  25. SequenceID string `json:"sequence_id,omitempty"` // Message sequence ID for updating message contents (omitted if same as ID)
  26. Time int64 `json:"time"` // Unix time in seconds
  27. Expires int64 `json:"expires,omitempty"` // Unix time in seconds (not required for open/keepalive)
  28. Event string `json:"event"` // One of the above
  29. Topic string `json:"topic"`
  30. Title string `json:"title,omitempty"`
  31. Message string `json:"message"` // Allow empty message body
  32. Priority int `json:"priority,omitempty"`
  33. Tags []string `json:"tags,omitempty"`
  34. Click string `json:"click,omitempty"`
  35. Icon string `json:"icon,omitempty"`
  36. Actions []*action `json:"actions,omitempty"`
  37. Attachment *attachment `json:"attachment,omitempty"`
  38. PollID string `json:"poll_id,omitempty"`
  39. ContentType string `json:"content_type,omitempty"` // text/plain by default (if empty), or text/markdown
  40. Encoding string `json:"encoding,omitempty"` // Empty for raw UTF-8, or "base64" for encoded bytes
  41. Sender netip.Addr `json:"-"` // IP address of uploader, used for rate limiting
  42. User string `json:"-"` // UserID of the uploader, used to associated attachments
  43. }
  44. func (m *message) Context() log.Context {
  45. fields := map[string]any{
  46. "topic": m.Topic,
  47. "message_id": m.ID,
  48. "message_sequence_id": m.SequenceID,
  49. "message_time": m.Time,
  50. "message_event": m.Event,
  51. "message_body_size": len(m.Message),
  52. }
  53. if m.Sender.IsValid() {
  54. fields["message_sender"] = m.Sender.String()
  55. }
  56. if m.User != "" {
  57. fields["message_user"] = m.User
  58. }
  59. return fields
  60. }
  61. type attachment struct {
  62. Name string `json:"name"`
  63. Type string `json:"type,omitempty"`
  64. Size int64 `json:"size,omitempty"`
  65. Expires int64 `json:"expires,omitempty"`
  66. URL string `json:"url"`
  67. }
  68. type action struct {
  69. ID string `json:"id"`
  70. Action string `json:"action"` // "view", "broadcast", or "http"
  71. Label string `json:"label"` // action button label
  72. Clear bool `json:"clear"` // clear notification after successful execution
  73. URL string `json:"url,omitempty"` // used in "view" and "http" actions
  74. Method string `json:"method,omitempty"` // used in "http" action, default is POST (!)
  75. Headers map[string]string `json:"headers,omitempty"` // used in "http" action
  76. Body string `json:"body,omitempty"` // used in "http" action
  77. Intent string `json:"intent,omitempty"` // used in "broadcast" action
  78. Extras map[string]string `json:"extras,omitempty"` // used in "broadcast" action
  79. }
  80. func newAction() *action {
  81. return &action{
  82. Headers: make(map[string]string),
  83. Extras: make(map[string]string),
  84. }
  85. }
  86. // publishMessage is used as input when publishing as JSON
  87. type publishMessage struct {
  88. Topic string `json:"topic"`
  89. SequenceID string `json:"sequence_id"`
  90. Title string `json:"title"`
  91. Message string `json:"message"`
  92. Priority int `json:"priority"`
  93. Tags []string `json:"tags"`
  94. Click string `json:"click"`
  95. Icon string `json:"icon"`
  96. Actions []action `json:"actions"`
  97. Attach string `json:"attach"`
  98. Markdown bool `json:"markdown"`
  99. Filename string `json:"filename"`
  100. Email string `json:"email"`
  101. Call string `json:"call"`
  102. Cache string `json:"cache"` // use string as it defaults to true (or use &bool instead)
  103. Firebase string `json:"firebase"` // use string as it defaults to true (or use &bool instead)
  104. Delay string `json:"delay"`
  105. }
  106. // messageEncoder is a function that knows how to encode a message
  107. type messageEncoder func(msg *message) (string, error)
  108. // newMessage creates a new message with the current timestamp
  109. func newMessage(event, topic, msg string) *message {
  110. return &message{
  111. ID: util.RandomString(messageIDLength),
  112. Time: time.Now().Unix(),
  113. Event: event,
  114. Topic: topic,
  115. Message: msg,
  116. }
  117. }
  118. // newOpenMessage is a convenience method to create an open message
  119. func newOpenMessage(topic string) *message {
  120. return newMessage(openEvent, topic, "")
  121. }
  122. // newKeepaliveMessage is a convenience method to create a keepalive message
  123. func newKeepaliveMessage(topic string) *message {
  124. return newMessage(keepaliveEvent, topic, "")
  125. }
  126. // newDefaultMessage is a convenience method to create a notification message
  127. func newDefaultMessage(topic, msg string) *message {
  128. return newMessage(messageEvent, topic, msg)
  129. }
  130. // newPollRequestMessage is a convenience method to create a poll request message
  131. func newPollRequestMessage(topic, pollID string) *message {
  132. m := newMessage(pollRequestEvent, topic, newMessageBody)
  133. m.PollID = pollID
  134. return m
  135. }
  136. // newActionMessage creates a new action message (message_delete or message_read)
  137. func newActionMessage(event, topic, sequenceID string) *message {
  138. m := newMessage(event, topic, "")
  139. m.SequenceID = sequenceID
  140. return m
  141. }
  142. func validMessageID(s string) bool {
  143. return util.ValidRandomString(s, messageIDLength)
  144. }
  145. type sinceMarker struct {
  146. time time.Time
  147. id string
  148. }
  149. func newSinceTime(timestamp int64) sinceMarker {
  150. return sinceMarker{time.Unix(timestamp, 0), ""}
  151. }
  152. func newSinceID(id string) sinceMarker {
  153. return sinceMarker{time.Unix(0, 0), id}
  154. }
  155. func (t sinceMarker) IsAll() bool {
  156. return t == sinceAllMessages
  157. }
  158. func (t sinceMarker) IsNone() bool {
  159. return t == sinceNoMessages
  160. }
  161. func (t sinceMarker) IsLatest() bool {
  162. return t == sinceLatestMessage
  163. }
  164. func (t sinceMarker) IsID() bool {
  165. return t.id != "" && t.id != "latest"
  166. }
  167. func (t sinceMarker) Time() time.Time {
  168. return t.time
  169. }
  170. func (t sinceMarker) ID() string {
  171. return t.id
  172. }
  173. var (
  174. sinceAllMessages = sinceMarker{time.Unix(0, 0), ""}
  175. sinceNoMessages = sinceMarker{time.Unix(1, 0), ""}
  176. sinceLatestMessage = sinceMarker{time.Unix(0, 0), "latest"}
  177. )
  178. type queryFilter struct {
  179. ID string
  180. Message string
  181. Title string
  182. Tags []string
  183. Priority []int
  184. }
  185. func parseQueryFilters(r *http.Request) (*queryFilter, error) {
  186. idFilter := readParam(r, "x-id", "id")
  187. messageFilter := readParam(r, "x-message", "message", "m")
  188. titleFilter := readParam(r, "x-title", "title", "t")
  189. tagsFilter := util.SplitNoEmpty(readParam(r, "x-tags", "tags", "tag", "ta"), ",")
  190. priorityFilter := make([]int, 0)
  191. for _, p := range util.SplitNoEmpty(readParam(r, "x-priority", "priority", "prio", "p"), ",") {
  192. priority, err := util.ParsePriority(p)
  193. if err != nil {
  194. return nil, errHTTPBadRequestPriorityInvalid
  195. }
  196. priorityFilter = append(priorityFilter, priority)
  197. }
  198. return &queryFilter{
  199. ID: idFilter,
  200. Message: messageFilter,
  201. Title: titleFilter,
  202. Tags: tagsFilter,
  203. Priority: priorityFilter,
  204. }, nil
  205. }
  206. func (q *queryFilter) Pass(msg *message) bool {
  207. if msg.Event != messageEvent && msg.Event != messageDeleteEvent && msg.Event != messageReadEvent {
  208. return true // filters only apply to messages
  209. } else if q.ID != "" && msg.ID != q.ID {
  210. return false
  211. } else if q.Message != "" && msg.Message != q.Message {
  212. return false
  213. } else if q.Title != "" && msg.Title != q.Title {
  214. return false
  215. }
  216. messagePriority := msg.Priority
  217. if messagePriority == 0 {
  218. messagePriority = 3 // For query filters, default priority (3) is the same as "not set" (0)
  219. }
  220. if len(q.Priority) > 0 && !util.Contains(q.Priority, messagePriority) {
  221. return false
  222. }
  223. if len(q.Tags) > 0 && !util.ContainsAll(msg.Tags, q.Tags) {
  224. return false
  225. }
  226. return true
  227. }
  228. // templateMode represents the mode in which templates are used
  229. //
  230. // It can be
  231. // - empty: templating is disabled
  232. // - a boolean string (yes/1/true/no/0/false): inline-templating mode
  233. // - a filename (e.g. grafana): template mode with a file
  234. type templateMode string
  235. // Enabled returns true if templating is enabled
  236. func (t templateMode) Enabled() bool {
  237. return t != ""
  238. }
  239. // InlineMode returns true if inline-templating mode is enabled
  240. func (t templateMode) InlineMode() bool {
  241. return t.Enabled() && isBoolValue(string(t))
  242. }
  243. // FileMode returns true if file-templating mode is enabled
  244. func (t templateMode) FileMode() bool {
  245. return t.Enabled() && !isBoolValue(string(t))
  246. }
  247. // FileName returns the filename if file-templating mode is enabled, or an empty string otherwise
  248. func (t templateMode) FileName() string {
  249. if t.FileMode() {
  250. return string(t)
  251. }
  252. return ""
  253. }
  254. // templateFile represents a template file with title and message
  255. // It is used for file-based templates, e.g. grafana, influxdb, etc.
  256. //
  257. // Example YAML:
  258. //
  259. // title: "Alert: {{ .Title }}"
  260. // message: |
  261. // This is a {{ .Type }} alert.
  262. // It can be multiline.
  263. type templateFile struct {
  264. Title *string `yaml:"title"`
  265. Message *string `yaml:"message"`
  266. }
  267. type apiHealthResponse struct {
  268. Healthy bool `json:"healthy"`
  269. }
  270. type apiStatsResponse struct {
  271. Messages int64 `json:"messages"`
  272. MessagesRate float64 `json:"messages_rate"` // Average number of messages per second
  273. }
  274. type apiUserAddOrUpdateRequest struct {
  275. Username string `json:"username"`
  276. Password string `json:"password"`
  277. Hash string `json:"hash"`
  278. Tier string `json:"tier"`
  279. // Do not add 'role' here. We don't want to add admins via the API.
  280. }
  281. type apiUserResponse struct {
  282. Username string `json:"username"`
  283. Role string `json:"role"`
  284. Tier string `json:"tier,omitempty"`
  285. Grants []*apiUserGrantResponse `json:"grants,omitempty"`
  286. }
  287. type apiUserGrantResponse struct {
  288. Topic string `json:"topic"` // This may be a pattern
  289. Permission string `json:"permission"`
  290. }
  291. type apiUserDeleteRequest struct {
  292. Username string `json:"username"`
  293. }
  294. type apiAccessAllowRequest struct {
  295. Username string `json:"username"`
  296. Topic string `json:"topic"` // This may be a pattern
  297. Permission string `json:"permission"`
  298. }
  299. type apiAccessResetRequest struct {
  300. Username string `json:"username"`
  301. Topic string `json:"topic"`
  302. }
  303. type apiAccountCreateRequest struct {
  304. Username string `json:"username"`
  305. Password string `json:"password"`
  306. }
  307. type apiAccountPasswordChangeRequest struct {
  308. Password string `json:"password"`
  309. NewPassword string `json:"new_password"`
  310. }
  311. type apiAccountDeleteRequest struct {
  312. Password string `json:"password"`
  313. }
  314. type apiAccountTokenIssueRequest struct {
  315. Label *string `json:"label"`
  316. Expires *int64 `json:"expires"` // Unix timestamp
  317. }
  318. type apiAccountTokenUpdateRequest struct {
  319. Token string `json:"token"`
  320. Label *string `json:"label"`
  321. Expires *int64 `json:"expires"` // Unix timestamp
  322. }
  323. type apiAccountTokenResponse struct {
  324. Token string `json:"token"`
  325. Label string `json:"label,omitempty"`
  326. LastAccess int64 `json:"last_access,omitempty"`
  327. LastOrigin string `json:"last_origin,omitempty"`
  328. Expires int64 `json:"expires,omitempty"` // Unix timestamp
  329. Provisioned bool `json:"provisioned,omitempty"` // True if this token was provisioned by the server config
  330. }
  331. type apiAccountPhoneNumberVerifyRequest struct {
  332. Number string `json:"number"`
  333. Channel string `json:"channel"`
  334. }
  335. type apiAccountPhoneNumberAddRequest struct {
  336. Number string `json:"number"`
  337. Code string `json:"code"` // Only set when adding a phone number
  338. }
  339. type apiAccountTier struct {
  340. Code string `json:"code"`
  341. Name string `json:"name"`
  342. }
  343. type apiAccountLimits struct {
  344. Basis string `json:"basis,omitempty"` // "ip" or "tier"
  345. Messages int64 `json:"messages"`
  346. MessagesExpiryDuration int64 `json:"messages_expiry_duration"`
  347. Emails int64 `json:"emails"`
  348. Calls int64 `json:"calls"`
  349. Reservations int64 `json:"reservations"`
  350. AttachmentTotalSize int64 `json:"attachment_total_size"`
  351. AttachmentFileSize int64 `json:"attachment_file_size"`
  352. AttachmentExpiryDuration int64 `json:"attachment_expiry_duration"`
  353. AttachmentBandwidth int64 `json:"attachment_bandwidth"`
  354. }
  355. type apiAccountStats struct {
  356. Messages int64 `json:"messages"`
  357. MessagesRemaining int64 `json:"messages_remaining"`
  358. Emails int64 `json:"emails"`
  359. EmailsRemaining int64 `json:"emails_remaining"`
  360. Calls int64 `json:"calls"`
  361. CallsRemaining int64 `json:"calls_remaining"`
  362. Reservations int64 `json:"reservations"`
  363. ReservationsRemaining int64 `json:"reservations_remaining"`
  364. AttachmentTotalSize int64 `json:"attachment_total_size"`
  365. AttachmentTotalSizeRemaining int64 `json:"attachment_total_size_remaining"`
  366. }
  367. type apiAccountReservation struct {
  368. Topic string `json:"topic"`
  369. Everyone string `json:"everyone"`
  370. }
  371. type apiAccountBilling struct {
  372. Customer bool `json:"customer"`
  373. Subscription bool `json:"subscription"`
  374. Status string `json:"status,omitempty"`
  375. Interval string `json:"interval,omitempty"`
  376. PaidUntil int64 `json:"paid_until,omitempty"`
  377. CancelAt int64 `json:"cancel_at,omitempty"`
  378. }
  379. type apiAccountResponse struct {
  380. Username string `json:"username"`
  381. Role string `json:"role,omitempty"`
  382. SyncTopic string `json:"sync_topic,omitempty"`
  383. Provisioned bool `json:"provisioned,omitempty"`
  384. Language string `json:"language,omitempty"`
  385. Notification *user.NotificationPrefs `json:"notification,omitempty"`
  386. Subscriptions []*user.Subscription `json:"subscriptions,omitempty"`
  387. Reservations []*apiAccountReservation `json:"reservations,omitempty"`
  388. Tokens []*apiAccountTokenResponse `json:"tokens,omitempty"`
  389. PhoneNumbers []string `json:"phone_numbers,omitempty"`
  390. Tier *apiAccountTier `json:"tier,omitempty"`
  391. Limits *apiAccountLimits `json:"limits,omitempty"`
  392. Stats *apiAccountStats `json:"stats,omitempty"`
  393. Billing *apiAccountBilling `json:"billing,omitempty"`
  394. }
  395. type apiAccountReservationRequest struct {
  396. Topic string `json:"topic"`
  397. Everyone string `json:"everyone"`
  398. }
  399. type apiConfigResponse struct {
  400. BaseURL string `json:"base_url"`
  401. AppRoot string `json:"app_root"`
  402. EnableLogin bool `json:"enable_login"`
  403. RequireLogin bool `json:"require_login"`
  404. EnableSignup bool `json:"enable_signup"`
  405. EnablePayments bool `json:"enable_payments"`
  406. EnableCalls bool `json:"enable_calls"`
  407. EnableEmails bool `json:"enable_emails"`
  408. EnableReservations bool `json:"enable_reservations"`
  409. EnableWebPush bool `json:"enable_web_push"`
  410. BillingContact string `json:"billing_contact"`
  411. WebPushPublicKey string `json:"web_push_public_key"`
  412. DisallowedTopics []string `json:"disallowed_topics"`
  413. }
  414. type apiAccountBillingPrices struct {
  415. Month int64 `json:"month"`
  416. Year int64 `json:"year"`
  417. }
  418. type apiAccountBillingTier struct {
  419. Code string `json:"code,omitempty"`
  420. Name string `json:"name,omitempty"`
  421. Prices *apiAccountBillingPrices `json:"prices,omitempty"`
  422. Limits *apiAccountLimits `json:"limits"`
  423. }
  424. type apiAccountBillingSubscriptionCreateResponse struct {
  425. RedirectURL string `json:"redirect_url"`
  426. }
  427. type apiAccountBillingSubscriptionChangeRequest struct {
  428. Tier string `json:"tier"`
  429. Interval string `json:"interval"`
  430. }
  431. type apiAccountBillingPortalRedirectResponse struct {
  432. RedirectURL string `json:"redirect_url"`
  433. }
  434. type apiAccountSyncTopicResponse struct {
  435. Event string `json:"event"`
  436. }
  437. type apiSuccessResponse struct {
  438. Success bool `json:"success"`
  439. }
  440. func newSuccessResponse() *apiSuccessResponse {
  441. return &apiSuccessResponse{
  442. Success: true,
  443. }
  444. }
  445. type apiStripeSubscriptionUpdatedEvent struct {
  446. ID string `json:"id"`
  447. Customer string `json:"customer"`
  448. Status string `json:"status"`
  449. CurrentPeriodEnd int64 `json:"current_period_end"`
  450. CancelAt int64 `json:"cancel_at"`
  451. Items *struct {
  452. Data []*struct {
  453. Price *struct {
  454. ID string `json:"id"`
  455. Recurring *struct {
  456. Interval string `json:"interval"`
  457. } `json:"recurring"`
  458. } `json:"price"`
  459. } `json:"data"`
  460. } `json:"items"`
  461. }
  462. type apiStripeSubscriptionDeletedEvent struct {
  463. ID string `json:"id"`
  464. Customer string `json:"customer"`
  465. }
  466. type apiWebPushUpdateSubscriptionRequest struct {
  467. Endpoint string `json:"endpoint"`
  468. Auth string `json:"auth"`
  469. P256dh string `json:"p256dh"`
  470. Topics []string `json:"topics"`
  471. }
  472. // List of possible Web Push events (see sw.js)
  473. const (
  474. webPushMessageEvent = "message"
  475. webPushExpiringEvent = "subscription_expiring"
  476. )
  477. type webPushPayload struct {
  478. Event string `json:"event"`
  479. SubscriptionID string `json:"subscription_id"`
  480. Message *message `json:"message"`
  481. }
  482. func newWebPushPayload(subscriptionID string, message *message) *webPushPayload {
  483. return &webPushPayload{
  484. Event: webPushMessageEvent,
  485. SubscriptionID: subscriptionID,
  486. Message: message,
  487. }
  488. }
  489. type webPushControlMessagePayload struct {
  490. Event string `json:"event"`
  491. }
  492. func newWebPushSubscriptionExpiringPayload() *webPushControlMessagePayload {
  493. return &webPushControlMessagePayload{
  494. Event: webPushExpiringEvent,
  495. }
  496. }
  497. type webPushSubscription struct {
  498. ID string
  499. Endpoint string
  500. Auth string
  501. P256dh string
  502. UserID string
  503. }
  504. func (w *webPushSubscription) Context() log.Context {
  505. return map[string]any{
  506. "web_push_subscription_id": w.ID,
  507. "web_push_subscription_user_id": w.UserID,
  508. "web_push_subscription_endpoint": w.Endpoint,
  509. }
  510. }
  511. // https://developer.mozilla.org/en-US/docs/Web/Manifest
  512. type webManifestResponse struct {
  513. Name string `json:"name"`
  514. Description string `json:"description"`
  515. ShortName string `json:"short_name"`
  516. Scope string `json:"scope"`
  517. StartURL string `json:"start_url"`
  518. Display string `json:"display"`
  519. BackgroundColor string `json:"background_color"`
  520. ThemeColor string `json:"theme_color"`
  521. Icons []*webManifestIcon `json:"icons"`
  522. }
  523. type webManifestIcon struct {
  524. SRC string `json:"src"`
  525. Sizes string `json:"sizes"`
  526. Type string `json:"type"`
  527. }