types.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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) IsLatest() bool {
  151. return t == sinceLatestMessage
  152. }
  153. func (t sinceMarker) IsID() bool {
  154. return t.id != "" && t.id != "latest"
  155. }
  156. func (t sinceMarker) Time() time.Time {
  157. return t.time
  158. }
  159. func (t sinceMarker) ID() string {
  160. return t.id
  161. }
  162. var (
  163. sinceAllMessages = sinceMarker{time.Unix(0, 0), ""}
  164. sinceNoMessages = sinceMarker{time.Unix(1, 0), ""}
  165. sinceLatestMessage = sinceMarker{time.Unix(0, 0), "latest"}
  166. )
  167. type queryFilter struct {
  168. ID string
  169. Message string
  170. Title string
  171. Tags []string
  172. Priority []int
  173. }
  174. func parseQueryFilters(r *http.Request) (*queryFilter, error) {
  175. idFilter := readParam(r, "x-id", "id")
  176. messageFilter := readParam(r, "x-message", "message", "m")
  177. titleFilter := readParam(r, "x-title", "title", "t")
  178. tagsFilter := util.SplitNoEmpty(readParam(r, "x-tags", "tags", "tag", "ta"), ",")
  179. priorityFilter := make([]int, 0)
  180. for _, p := range util.SplitNoEmpty(readParam(r, "x-priority", "priority", "prio", "p"), ",") {
  181. priority, err := util.ParsePriority(p)
  182. if err != nil {
  183. return nil, errHTTPBadRequestPriorityInvalid
  184. }
  185. priorityFilter = append(priorityFilter, priority)
  186. }
  187. return &queryFilter{
  188. ID: idFilter,
  189. Message: messageFilter,
  190. Title: titleFilter,
  191. Tags: tagsFilter,
  192. Priority: priorityFilter,
  193. }, nil
  194. }
  195. func (q *queryFilter) Pass(msg *message) bool {
  196. if msg.Event != messageEvent {
  197. return true // filters only apply to messages
  198. } else if q.ID != "" && msg.ID != q.ID {
  199. return false
  200. } else if q.Message != "" && msg.Message != q.Message {
  201. return false
  202. } else if q.Title != "" && msg.Title != q.Title {
  203. return false
  204. }
  205. messagePriority := msg.Priority
  206. if messagePriority == 0 {
  207. messagePriority = 3 // For query filters, default priority (3) is the same as "not set" (0)
  208. }
  209. if len(q.Priority) > 0 && !util.Contains(q.Priority, messagePriority) {
  210. return false
  211. }
  212. if len(q.Tags) > 0 && !util.ContainsAll(msg.Tags, q.Tags) {
  213. return false
  214. }
  215. return true
  216. }
  217. // templateMode represents the mode in which templates are used
  218. //
  219. // It can be
  220. // - empty: templating is disabled
  221. // - a boolean string (yes/1/true/no/0/false): inline-templating mode
  222. // - a filename (e.g. grafana): template mode with a file
  223. type templateMode string
  224. // Enabled returns true if templating is enabled
  225. func (t templateMode) Enabled() bool {
  226. return t != ""
  227. }
  228. // InlineMode returns true if inline-templating mode is enabled
  229. func (t templateMode) InlineMode() bool {
  230. return t.Enabled() && isBoolValue(string(t))
  231. }
  232. // FileMode returns true if file-templating mode is enabled
  233. func (t templateMode) FileMode() bool {
  234. return t.Enabled() && !isBoolValue(string(t))
  235. }
  236. // FileName returns the filename if file-templating mode is enabled, or an empty string otherwise
  237. func (t templateMode) FileName() string {
  238. if t.FileMode() {
  239. return string(t)
  240. }
  241. return ""
  242. }
  243. // templateFile represents a template file with title and message
  244. // It is used for file-based templates, e.g. grafana, influxdb, etc.
  245. //
  246. // Example YAML:
  247. //
  248. // title: "Alert: {{ .Title }}"
  249. // message: |
  250. // This is a {{ .Type }} alert.
  251. // It can be multiline.
  252. type templateFile struct {
  253. Title *string `yaml:"title"`
  254. Message *string `yaml:"message"`
  255. }
  256. type apiHealthResponse struct {
  257. Healthy bool `json:"healthy"`
  258. }
  259. type apiStatsResponse struct {
  260. Messages int64 `json:"messages"`
  261. MessagesRate float64 `json:"messages_rate"` // Average number of messages per second
  262. }
  263. type apiUserAddOrUpdateRequest struct {
  264. Username string `json:"username"`
  265. Password string `json:"password"`
  266. Hash string `json:"hash"`
  267. Tier string `json:"tier"`
  268. // Do not add 'role' here. We don't want to add admins via the API.
  269. }
  270. type apiUserResponse struct {
  271. Username string `json:"username"`
  272. Role string `json:"role"`
  273. Tier string `json:"tier,omitempty"`
  274. Grants []*apiUserGrantResponse `json:"grants,omitempty"`
  275. }
  276. type apiUserGrantResponse struct {
  277. Topic string `json:"topic"` // This may be a pattern
  278. Permission string `json:"permission"`
  279. }
  280. type apiUserDeleteRequest struct {
  281. Username string `json:"username"`
  282. }
  283. type apiAccessAllowRequest struct {
  284. Username string `json:"username"`
  285. Topic string `json:"topic"` // This may be a pattern
  286. Permission string `json:"permission"`
  287. }
  288. type apiAccessResetRequest struct {
  289. Username string `json:"username"`
  290. Topic string `json:"topic"`
  291. }
  292. type apiAccountCreateRequest struct {
  293. Username string `json:"username"`
  294. Password string `json:"password"`
  295. }
  296. type apiAccountPasswordChangeRequest struct {
  297. Password string `json:"password"`
  298. NewPassword string `json:"new_password"`
  299. }
  300. type apiAccountDeleteRequest struct {
  301. Password string `json:"password"`
  302. }
  303. type apiAccountTokenIssueRequest struct {
  304. Label *string `json:"label"`
  305. Expires *int64 `json:"expires"` // Unix timestamp
  306. }
  307. type apiAccountTokenUpdateRequest struct {
  308. Token string `json:"token"`
  309. Label *string `json:"label"`
  310. Expires *int64 `json:"expires"` // Unix timestamp
  311. }
  312. type apiAccountTokenResponse struct {
  313. Token string `json:"token"`
  314. Label string `json:"label,omitempty"`
  315. LastAccess int64 `json:"last_access,omitempty"`
  316. LastOrigin string `json:"last_origin,omitempty"`
  317. Expires int64 `json:"expires,omitempty"` // Unix timestamp
  318. Provisioned bool `json:"provisioned,omitempty"` // True if this token was provisioned by the server config
  319. }
  320. type apiAccountPhoneNumberVerifyRequest struct {
  321. Number string `json:"number"`
  322. Channel string `json:"channel"`
  323. }
  324. type apiAccountPhoneNumberAddRequest struct {
  325. Number string `json:"number"`
  326. Code string `json:"code"` // Only set when adding a phone number
  327. }
  328. type apiAccountTier struct {
  329. Code string `json:"code"`
  330. Name string `json:"name"`
  331. }
  332. type apiAccountLimits struct {
  333. Basis string `json:"basis,omitempty"` // "ip" or "tier"
  334. Messages int64 `json:"messages"`
  335. MessagesExpiryDuration int64 `json:"messages_expiry_duration"`
  336. Emails int64 `json:"emails"`
  337. Calls int64 `json:"calls"`
  338. Reservations int64 `json:"reservations"`
  339. AttachmentTotalSize int64 `json:"attachment_total_size"`
  340. AttachmentFileSize int64 `json:"attachment_file_size"`
  341. AttachmentExpiryDuration int64 `json:"attachment_expiry_duration"`
  342. AttachmentBandwidth int64 `json:"attachment_bandwidth"`
  343. }
  344. type apiAccountStats struct {
  345. Messages int64 `json:"messages"`
  346. MessagesRemaining int64 `json:"messages_remaining"`
  347. Emails int64 `json:"emails"`
  348. EmailsRemaining int64 `json:"emails_remaining"`
  349. Calls int64 `json:"calls"`
  350. CallsRemaining int64 `json:"calls_remaining"`
  351. Reservations int64 `json:"reservations"`
  352. ReservationsRemaining int64 `json:"reservations_remaining"`
  353. AttachmentTotalSize int64 `json:"attachment_total_size"`
  354. AttachmentTotalSizeRemaining int64 `json:"attachment_total_size_remaining"`
  355. }
  356. type apiAccountReservation struct {
  357. Topic string `json:"topic"`
  358. Everyone string `json:"everyone"`
  359. }
  360. type apiAccountBilling struct {
  361. Customer bool `json:"customer"`
  362. Subscription bool `json:"subscription"`
  363. Status string `json:"status,omitempty"`
  364. Interval string `json:"interval,omitempty"`
  365. PaidUntil int64 `json:"paid_until,omitempty"`
  366. CancelAt int64 `json:"cancel_at,omitempty"`
  367. }
  368. type apiAccountResponse struct {
  369. Username string `json:"username"`
  370. Role string `json:"role,omitempty"`
  371. SyncTopic string `json:"sync_topic,omitempty"`
  372. Provisioned bool `json:"provisioned,omitempty"`
  373. Language string `json:"language,omitempty"`
  374. Notification *user.NotificationPrefs `json:"notification,omitempty"`
  375. Subscriptions []*user.Subscription `json:"subscriptions,omitempty"`
  376. Reservations []*apiAccountReservation `json:"reservations,omitempty"`
  377. Tokens []*apiAccountTokenResponse `json:"tokens,omitempty"`
  378. PhoneNumbers []string `json:"phone_numbers,omitempty"`
  379. Tier *apiAccountTier `json:"tier,omitempty"`
  380. Limits *apiAccountLimits `json:"limits,omitempty"`
  381. Stats *apiAccountStats `json:"stats,omitempty"`
  382. Billing *apiAccountBilling `json:"billing,omitempty"`
  383. }
  384. type apiAccountReservationRequest struct {
  385. Topic string `json:"topic"`
  386. Everyone string `json:"everyone"`
  387. }
  388. type apiConfigResponse struct {
  389. BaseURL string `json:"base_url"`
  390. AppRoot string `json:"app_root"`
  391. EnableLogin bool `json:"enable_login"`
  392. EnableSignup bool `json:"enable_signup"`
  393. EnablePayments bool `json:"enable_payments"`
  394. EnableCalls bool `json:"enable_calls"`
  395. EnableEmails bool `json:"enable_emails"`
  396. EnableReservations bool `json:"enable_reservations"`
  397. EnableWebPush bool `json:"enable_web_push"`
  398. BillingContact string `json:"billing_contact"`
  399. WebPushPublicKey string `json:"web_push_public_key"`
  400. DisallowedTopics []string `json:"disallowed_topics"`
  401. }
  402. type apiAccountBillingPrices struct {
  403. Month int64 `json:"month"`
  404. Year int64 `json:"year"`
  405. }
  406. type apiAccountBillingTier struct {
  407. Code string `json:"code,omitempty"`
  408. Name string `json:"name,omitempty"`
  409. Prices *apiAccountBillingPrices `json:"prices,omitempty"`
  410. Limits *apiAccountLimits `json:"limits"`
  411. }
  412. type apiAccountBillingSubscriptionCreateResponse struct {
  413. RedirectURL string `json:"redirect_url"`
  414. }
  415. type apiAccountBillingSubscriptionChangeRequest struct {
  416. Tier string `json:"tier"`
  417. Interval string `json:"interval"`
  418. }
  419. type apiAccountBillingPortalRedirectResponse struct {
  420. RedirectURL string `json:"redirect_url"`
  421. }
  422. type apiAccountSyncTopicResponse struct {
  423. Event string `json:"event"`
  424. }
  425. type apiSuccessResponse struct {
  426. Success bool `json:"success"`
  427. }
  428. func newSuccessResponse() *apiSuccessResponse {
  429. return &apiSuccessResponse{
  430. Success: true,
  431. }
  432. }
  433. type apiStripeSubscriptionUpdatedEvent struct {
  434. ID string `json:"id"`
  435. Customer string `json:"customer"`
  436. Status string `json:"status"`
  437. CurrentPeriodEnd int64 `json:"current_period_end"`
  438. CancelAt int64 `json:"cancel_at"`
  439. Items *struct {
  440. Data []*struct {
  441. Price *struct {
  442. ID string `json:"id"`
  443. Recurring *struct {
  444. Interval string `json:"interval"`
  445. } `json:"recurring"`
  446. } `json:"price"`
  447. } `json:"data"`
  448. } `json:"items"`
  449. }
  450. type apiStripeSubscriptionDeletedEvent struct {
  451. ID string `json:"id"`
  452. Customer string `json:"customer"`
  453. }
  454. type apiWebPushUpdateSubscriptionRequest struct {
  455. Endpoint string `json:"endpoint"`
  456. Auth string `json:"auth"`
  457. P256dh string `json:"p256dh"`
  458. Topics []string `json:"topics"`
  459. }
  460. // List of possible Web Push events (see sw.js)
  461. const (
  462. webPushMessageEvent = "message"
  463. webPushExpiringEvent = "subscription_expiring"
  464. )
  465. type webPushPayload struct {
  466. Event string `json:"event"`
  467. SubscriptionID string `json:"subscription_id"`
  468. Message *message `json:"message"`
  469. }
  470. func newWebPushPayload(subscriptionID string, message *message) *webPushPayload {
  471. return &webPushPayload{
  472. Event: webPushMessageEvent,
  473. SubscriptionID: subscriptionID,
  474. Message: message,
  475. }
  476. }
  477. type webPushControlMessagePayload struct {
  478. Event string `json:"event"`
  479. }
  480. func newWebPushSubscriptionExpiringPayload() *webPushControlMessagePayload {
  481. return &webPushControlMessagePayload{
  482. Event: webPushExpiringEvent,
  483. }
  484. }
  485. type webPushSubscription struct {
  486. ID string
  487. Endpoint string
  488. Auth string
  489. P256dh string
  490. UserID string
  491. }
  492. func (w *webPushSubscription) Context() log.Context {
  493. return map[string]any{
  494. "web_push_subscription_id": w.ID,
  495. "web_push_subscription_user_id": w.UserID,
  496. "web_push_subscription_endpoint": w.Endpoint,
  497. }
  498. }
  499. // https://developer.mozilla.org/en-US/docs/Web/Manifest
  500. type webManifestResponse struct {
  501. Name string `json:"name"`
  502. Description string `json:"description"`
  503. ShortName string `json:"short_name"`
  504. Scope string `json:"scope"`
  505. StartURL string `json:"start_url"`
  506. Display string `json:"display"`
  507. BackgroundColor string `json:"background_color"`
  508. ThemeColor string `json:"theme_color"`
  509. Icons []*webManifestIcon `json:"icons"`
  510. }
  511. type webManifestIcon struct {
  512. SRC string `json:"src"`
  513. Sizes string `json:"sizes"`
  514. Type string `json:"type"`
  515. }