types.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. type templateMode string
  218. func (t templateMode) Enabled() bool {
  219. return t != ""
  220. }
  221. func (t templateMode) Name() string {
  222. if isBoolValue(string(t)) {
  223. return ""
  224. }
  225. return string(t)
  226. }
  227. type templateFile struct {
  228. Title *string `yaml:"title"`
  229. Message *string `yaml:"message"`
  230. }
  231. type apiHealthResponse struct {
  232. Healthy bool `json:"healthy"`
  233. }
  234. type apiStatsResponse struct {
  235. Messages int64 `json:"messages"`
  236. MessagesRate float64 `json:"messages_rate"` // Average number of messages per second
  237. }
  238. type apiUserAddOrUpdateRequest struct {
  239. Username string `json:"username"`
  240. Password string `json:"password"`
  241. Hash string `json:"hash"`
  242. Tier string `json:"tier"`
  243. // Do not add 'role' here. We don't want to add admins via the API.
  244. }
  245. type apiUserResponse struct {
  246. Username string `json:"username"`
  247. Role string `json:"role"`
  248. Tier string `json:"tier,omitempty"`
  249. Grants []*apiUserGrantResponse `json:"grants,omitempty"`
  250. }
  251. type apiUserGrantResponse struct {
  252. Topic string `json:"topic"` // This may be a pattern
  253. Permission string `json:"permission"`
  254. }
  255. type apiUserDeleteRequest struct {
  256. Username string `json:"username"`
  257. }
  258. type apiAccessAllowRequest struct {
  259. Username string `json:"username"`
  260. Topic string `json:"topic"` // This may be a pattern
  261. Permission string `json:"permission"`
  262. }
  263. type apiAccessResetRequest struct {
  264. Username string `json:"username"`
  265. Topic string `json:"topic"`
  266. }
  267. type apiAccountCreateRequest struct {
  268. Username string `json:"username"`
  269. Password string `json:"password"`
  270. }
  271. type apiAccountPasswordChangeRequest struct {
  272. Password string `json:"password"`
  273. NewPassword string `json:"new_password"`
  274. }
  275. type apiAccountDeleteRequest struct {
  276. Password string `json:"password"`
  277. }
  278. type apiAccountTokenIssueRequest struct {
  279. Label *string `json:"label"`
  280. Expires *int64 `json:"expires"` // Unix timestamp
  281. }
  282. type apiAccountTokenUpdateRequest struct {
  283. Token string `json:"token"`
  284. Label *string `json:"label"`
  285. Expires *int64 `json:"expires"` // Unix timestamp
  286. }
  287. type apiAccountTokenResponse struct {
  288. Token string `json:"token"`
  289. Label string `json:"label,omitempty"`
  290. LastAccess int64 `json:"last_access,omitempty"`
  291. LastOrigin string `json:"last_origin,omitempty"`
  292. Expires int64 `json:"expires,omitempty"` // Unix timestamp
  293. }
  294. type apiAccountPhoneNumberVerifyRequest struct {
  295. Number string `json:"number"`
  296. Channel string `json:"channel"`
  297. }
  298. type apiAccountPhoneNumberAddRequest struct {
  299. Number string `json:"number"`
  300. Code string `json:"code"` // Only set when adding a phone number
  301. }
  302. type apiAccountTier struct {
  303. Code string `json:"code"`
  304. Name string `json:"name"`
  305. }
  306. type apiAccountLimits struct {
  307. Basis string `json:"basis,omitempty"` // "ip" or "tier"
  308. Messages int64 `json:"messages"`
  309. MessagesExpiryDuration int64 `json:"messages_expiry_duration"`
  310. Emails int64 `json:"emails"`
  311. Calls int64 `json:"calls"`
  312. Reservations int64 `json:"reservations"`
  313. AttachmentTotalSize int64 `json:"attachment_total_size"`
  314. AttachmentFileSize int64 `json:"attachment_file_size"`
  315. AttachmentExpiryDuration int64 `json:"attachment_expiry_duration"`
  316. AttachmentBandwidth int64 `json:"attachment_bandwidth"`
  317. }
  318. type apiAccountStats struct {
  319. Messages int64 `json:"messages"`
  320. MessagesRemaining int64 `json:"messages_remaining"`
  321. Emails int64 `json:"emails"`
  322. EmailsRemaining int64 `json:"emails_remaining"`
  323. Calls int64 `json:"calls"`
  324. CallsRemaining int64 `json:"calls_remaining"`
  325. Reservations int64 `json:"reservations"`
  326. ReservationsRemaining int64 `json:"reservations_remaining"`
  327. AttachmentTotalSize int64 `json:"attachment_total_size"`
  328. AttachmentTotalSizeRemaining int64 `json:"attachment_total_size_remaining"`
  329. }
  330. type apiAccountReservation struct {
  331. Topic string `json:"topic"`
  332. Everyone string `json:"everyone"`
  333. }
  334. type apiAccountBilling struct {
  335. Customer bool `json:"customer"`
  336. Subscription bool `json:"subscription"`
  337. Status string `json:"status,omitempty"`
  338. Interval string `json:"interval,omitempty"`
  339. PaidUntil int64 `json:"paid_until,omitempty"`
  340. CancelAt int64 `json:"cancel_at,omitempty"`
  341. }
  342. type apiAccountResponse struct {
  343. Username string `json:"username"`
  344. Role string `json:"role,omitempty"`
  345. SyncTopic string `json:"sync_topic,omitempty"`
  346. Language string `json:"language,omitempty"`
  347. Notification *user.NotificationPrefs `json:"notification,omitempty"`
  348. Subscriptions []*user.Subscription `json:"subscriptions,omitempty"`
  349. Reservations []*apiAccountReservation `json:"reservations,omitempty"`
  350. Tokens []*apiAccountTokenResponse `json:"tokens,omitempty"`
  351. PhoneNumbers []string `json:"phone_numbers,omitempty"`
  352. Tier *apiAccountTier `json:"tier,omitempty"`
  353. Limits *apiAccountLimits `json:"limits,omitempty"`
  354. Stats *apiAccountStats `json:"stats,omitempty"`
  355. Billing *apiAccountBilling `json:"billing,omitempty"`
  356. }
  357. type apiAccountReservationRequest struct {
  358. Topic string `json:"topic"`
  359. Everyone string `json:"everyone"`
  360. }
  361. type apiConfigResponse struct {
  362. BaseURL string `json:"base_url"`
  363. AppRoot string `json:"app_root"`
  364. EnableLogin bool `json:"enable_login"`
  365. EnableSignup bool `json:"enable_signup"`
  366. EnablePayments bool `json:"enable_payments"`
  367. EnableCalls bool `json:"enable_calls"`
  368. EnableEmails bool `json:"enable_emails"`
  369. EnableReservations bool `json:"enable_reservations"`
  370. EnableWebPush bool `json:"enable_web_push"`
  371. BillingContact string `json:"billing_contact"`
  372. WebPushPublicKey string `json:"web_push_public_key"`
  373. DisallowedTopics []string `json:"disallowed_topics"`
  374. }
  375. type apiAccountBillingPrices struct {
  376. Month int64 `json:"month"`
  377. Year int64 `json:"year"`
  378. }
  379. type apiAccountBillingTier struct {
  380. Code string `json:"code,omitempty"`
  381. Name string `json:"name,omitempty"`
  382. Prices *apiAccountBillingPrices `json:"prices,omitempty"`
  383. Limits *apiAccountLimits `json:"limits"`
  384. }
  385. type apiAccountBillingSubscriptionCreateResponse struct {
  386. RedirectURL string `json:"redirect_url"`
  387. }
  388. type apiAccountBillingSubscriptionChangeRequest struct {
  389. Tier string `json:"tier"`
  390. Interval string `json:"interval"`
  391. }
  392. type apiAccountBillingPortalRedirectResponse struct {
  393. RedirectURL string `json:"redirect_url"`
  394. }
  395. type apiAccountSyncTopicResponse struct {
  396. Event string `json:"event"`
  397. }
  398. type apiSuccessResponse struct {
  399. Success bool `json:"success"`
  400. }
  401. func newSuccessResponse() *apiSuccessResponse {
  402. return &apiSuccessResponse{
  403. Success: true,
  404. }
  405. }
  406. type apiStripeSubscriptionUpdatedEvent struct {
  407. ID string `json:"id"`
  408. Customer string `json:"customer"`
  409. Status string `json:"status"`
  410. CurrentPeriodEnd int64 `json:"current_period_end"`
  411. CancelAt int64 `json:"cancel_at"`
  412. Items *struct {
  413. Data []*struct {
  414. Price *struct {
  415. ID string `json:"id"`
  416. Recurring *struct {
  417. Interval string `json:"interval"`
  418. } `json:"recurring"`
  419. } `json:"price"`
  420. } `json:"data"`
  421. } `json:"items"`
  422. }
  423. type apiStripeSubscriptionDeletedEvent struct {
  424. ID string `json:"id"`
  425. Customer string `json:"customer"`
  426. }
  427. type apiWebPushUpdateSubscriptionRequest struct {
  428. Endpoint string `json:"endpoint"`
  429. Auth string `json:"auth"`
  430. P256dh string `json:"p256dh"`
  431. Topics []string `json:"topics"`
  432. }
  433. // List of possible Web Push events (see sw.js)
  434. const (
  435. webPushMessageEvent = "message"
  436. webPushExpiringEvent = "subscription_expiring"
  437. )
  438. type webPushPayload struct {
  439. Event string `json:"event"`
  440. SubscriptionID string `json:"subscription_id"`
  441. Message *message `json:"message"`
  442. }
  443. func newWebPushPayload(subscriptionID string, message *message) *webPushPayload {
  444. return &webPushPayload{
  445. Event: webPushMessageEvent,
  446. SubscriptionID: subscriptionID,
  447. Message: message,
  448. }
  449. }
  450. type webPushControlMessagePayload struct {
  451. Event string `json:"event"`
  452. }
  453. func newWebPushSubscriptionExpiringPayload() *webPushControlMessagePayload {
  454. return &webPushControlMessagePayload{
  455. Event: webPushExpiringEvent,
  456. }
  457. }
  458. type webPushSubscription struct {
  459. ID string
  460. Endpoint string
  461. Auth string
  462. P256dh string
  463. UserID string
  464. }
  465. func (w *webPushSubscription) Context() log.Context {
  466. return map[string]any{
  467. "web_push_subscription_id": w.ID,
  468. "web_push_subscription_user_id": w.UserID,
  469. "web_push_subscription_endpoint": w.Endpoint,
  470. }
  471. }
  472. // https://developer.mozilla.org/en-US/docs/Web/Manifest
  473. type webManifestResponse struct {
  474. Name string `json:"name"`
  475. Description string `json:"description"`
  476. ShortName string `json:"short_name"`
  477. Scope string `json:"scope"`
  478. StartURL string `json:"start_url"`
  479. Display string `json:"display"`
  480. BackgroundColor string `json:"background_color"`
  481. ThemeColor string `json:"theme_color"`
  482. Icons []*webManifestIcon `json:"icons"`
  483. }
  484. type webManifestIcon struct {
  485. SRC string `json:"src"`
  486. Sizes string `json:"sizes"`
  487. Type string `json:"type"`
  488. }