types.go 18 KB

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