functions.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package template // import "miniflux.app/v2/internal/template"
  4. import (
  5. "errors"
  6. "fmt"
  7. "html/template"
  8. "math"
  9. "net/mail"
  10. "net/url"
  11. "slices"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "miniflux.app/v2/internal/config"
  16. "miniflux.app/v2/internal/crypto"
  17. "miniflux.app/v2/internal/locale"
  18. "miniflux.app/v2/internal/mediaproxy"
  19. "miniflux.app/v2/internal/model"
  20. "miniflux.app/v2/internal/reader/sanitizer"
  21. "miniflux.app/v2/internal/timezone"
  22. "miniflux.app/v2/internal/ui/static"
  23. "miniflux.app/v2/internal/urllib"
  24. )
  25. type funcMap struct {
  26. basePath string
  27. }
  28. // Map returns a map of template functions that are compiled during template parsing.
  29. func (f *funcMap) Map() template.FuncMap {
  30. return template.FuncMap{
  31. "contains": strings.Contains,
  32. "csp": csp,
  33. "startsWith": strings.HasPrefix,
  34. "formatFileSize": formatFileSize,
  35. "dict": dict,
  36. "truncate": truncate,
  37. "isEmail": isEmail,
  38. "baseURL": config.Opts.BaseURL,
  39. "apiEnabled": config.Opts.HasAPI,
  40. "rootURL": config.Opts.RootURL,
  41. "disableLocalAuth": config.Opts.DisableLocalAuth,
  42. "oidcProviderName": config.Opts.OAuth2OIDCProviderName,
  43. "hasOAuth2Provider": func(provider string) bool {
  44. return config.Opts.OAuth2Provider() == provider
  45. },
  46. "hasAuthProxy": func() bool {
  47. return config.Opts.AuthProxyHeader() != ""
  48. },
  49. "routePath": func(format string, args ...any) string {
  50. if len(args) > 0 {
  51. return f.basePath + fmt.Sprintf(format, args...)
  52. }
  53. return f.basePath + format
  54. },
  55. "untrustedURL": untrustedURL,
  56. "safeCSS": func(str string) template.CSS {
  57. return template.CSS(str)
  58. },
  59. "safeJS": func(str string) template.JS {
  60. return template.JS(str)
  61. },
  62. "safeHTML": func(str string) template.HTML {
  63. return template.HTML(str)
  64. },
  65. "proxyFilter": mediaproxy.RewriteDocumentWithRelativeProxyURL,
  66. "proxyURL": func(link string) string {
  67. mediaProxyMode := config.Opts.MediaProxyMode()
  68. if mediaProxyMode == "all" || (mediaProxyMode != "none" && !urllib.IsHTTPS(link)) {
  69. return mediaproxy.ProxifyRelativeURL(link)
  70. }
  71. return link
  72. },
  73. "mustBeProxyfied": func(mediaType string) bool {
  74. return slices.Contains(config.Opts.MediaProxyResourceTypes(), mediaType)
  75. },
  76. "domain": urllib.Domain,
  77. "replace": func(str, old, new string) string {
  78. return strings.Replace(str, old, new, 1)
  79. },
  80. "isodate": func(ts time.Time) string {
  81. return ts.Format("2006-01-02 15:04:05")
  82. },
  83. "theme_color": model.ThemeColor,
  84. "iconPath": f.iconPath,
  85. "icon": f.iconFunc(),
  86. "nonce": func() string {
  87. return crypto.GenerateRandomStringHex(16)
  88. },
  89. "deRef": func(i *int) int { return *i },
  90. "duration": duration,
  91. "urlEncode": url.PathEscape,
  92. "subtract": func(a, b int) int {
  93. return a - b
  94. },
  95. "queryString": func(params map[string]any) string {
  96. if len(params) == 0 {
  97. return ""
  98. }
  99. values := url.Values{}
  100. for key, value := range params {
  101. switch v := value.(type) {
  102. case string:
  103. if v != "" {
  104. values.Set(key, v)
  105. }
  106. case int:
  107. if v != 0 {
  108. values.Set(key, strconv.Itoa(v))
  109. }
  110. case int64:
  111. if v != 0 {
  112. values.Set(key, strconv.FormatInt(v, 10))
  113. }
  114. case bool:
  115. if v {
  116. values.Set(key, "1")
  117. }
  118. default:
  119. if value != nil {
  120. str := fmt.Sprint(value)
  121. if str != "" {
  122. values.Set(key, str)
  123. }
  124. }
  125. }
  126. }
  127. encoded := values.Encode()
  128. if encoded == "" {
  129. return ""
  130. }
  131. return "?" + encoded
  132. },
  133. // These functions are overridden at runtime after parsing.
  134. "elapsed": func(timezone string, t time.Time) string {
  135. return ""
  136. },
  137. "t": func(key any, args ...any) string {
  138. return ""
  139. },
  140. "plural": func(key string, n int, args ...any) string {
  141. return ""
  142. },
  143. }
  144. }
  145. func (f *funcMap) iconPath(filename string) string {
  146. if bundle, ok := static.BinaryBundles[filename]; ok {
  147. return fmt.Sprintf("%s/icon/%s/%s", f.basePath, bundle.Checksum, filename)
  148. }
  149. return fmt.Sprintf("%s/icon/_/%s", f.basePath, filename)
  150. }
  151. func (f *funcMap) iconFunc() func(string) template.HTML {
  152. // Concatenation is used instead of fmt.Sprintf,
  153. // as it's much faster, and this function is called
  154. // a bunch of times per feed item on the main page.
  155. prefix := `<svg class="icon" aria-hidden="true"><use href="` + f.iconPath("sprite.svg") + `#icon-`
  156. const suffix = `"/></svg>`
  157. return func(iconName string) template.HTML {
  158. return template.HTML(prefix + iconName + suffix)
  159. }
  160. }
  161. func csp(user *model.User, nonce string) string {
  162. policies := map[string]string{
  163. "default-src": "'none'",
  164. "frame-src": "*",
  165. "img-src": "* data:",
  166. "manifest-src": "'self'",
  167. "media-src": "*",
  168. "require-trusted-types-for": "'script'",
  169. "script-src": "'nonce-" + nonce + "' 'strict-dynamic'",
  170. "style-src": "'nonce-" + nonce + "'",
  171. "trusted-types": "html url",
  172. "connect-src": "'self'",
  173. }
  174. if user != nil {
  175. if user.ExternalFontHosts != "" {
  176. policies["font-src"] = user.ExternalFontHosts
  177. if user.Stylesheet != "" {
  178. policies["style-src"] += " " + user.ExternalFontHosts
  179. }
  180. }
  181. }
  182. var policy strings.Builder
  183. policy.Grow(350)
  184. for key, value := range policies {
  185. policy.WriteString(key)
  186. policy.WriteString(" ")
  187. policy.WriteString(value)
  188. policy.WriteString("; ")
  189. }
  190. return `<meta http-equiv="Content-Security-Policy" content="` + policy.String() + `">`
  191. }
  192. func dict(values ...any) (map[string]any, error) {
  193. if len(values)%2 != 0 {
  194. return nil, errors.New("dict expects an even number of arguments")
  195. }
  196. dict := make(map[string]any, len(values)/2)
  197. for i := 0; i < len(values); i += 2 {
  198. key, ok := values[i].(string)
  199. if !ok {
  200. return nil, errors.New("dict keys must be strings")
  201. }
  202. dict[key] = values[i+1]
  203. }
  204. return dict, nil
  205. }
  206. func truncate(str string, max int) string {
  207. if max <= 0 {
  208. panic("truncate: max must be greater than zero")
  209. }
  210. // Template callers pass feed titles from remote content. Scanning and
  211. // allocating the entire untrusted input just to truncate it could create a
  212. // denial-of-service risk, so stop as soon as we reach the requested limit.
  213. runeCount := 0
  214. for i := range str {
  215. if runeCount == max {
  216. return str[:i] + "…"
  217. }
  218. runeCount++
  219. }
  220. return str
  221. }
  222. func isEmail(str string) bool {
  223. _, err := mail.ParseAddress(str)
  224. return err == nil
  225. }
  226. // untrustedURL validates a feed-supplied URL against the sanitizer's scheme
  227. // allowlist before exposing it to html/template. Returns "#" for unsafe URLs
  228. // (e.g. javascript:, data:) so anchors render as inert links.
  229. //
  230. // Go's built-in html/template URL filter only allows http(s), mailto, and
  231. // relative URLs — too narrow for feeds which legitimately use schemes like
  232. // magnet:, feed:, webcal:, and tel:.
  233. func untrustedURL(rawURL string) template.URL {
  234. if !sanitizer.HasValidURIScheme(rawURL) {
  235. return template.URL("#")
  236. }
  237. return template.URL(rawURL)
  238. }
  239. // Returns the duration in human readable format (hours and minutes).
  240. func duration(t time.Time) string {
  241. return durationImpl(t, time.Now())
  242. }
  243. // Accepts now argument for easy testing
  244. func durationImpl(t time.Time, now time.Time) string {
  245. if t.IsZero() {
  246. return ""
  247. }
  248. if diff := t.Sub(now); diff >= 0 {
  249. // Round to nearest second to get e.g. "14m56s" rather than "14m56.245483933s"
  250. return diff.Round(time.Second).String()
  251. }
  252. return ""
  253. }
  254. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  255. if t.IsZero() {
  256. return printer.Print("time_elapsed.not_yet")
  257. }
  258. now := timezone.Now(tz)
  259. t = timezone.Convert(tz, t)
  260. if now.Before(t) {
  261. return printer.Print("time_elapsed.not_yet")
  262. }
  263. diff := now.Sub(t)
  264. // Duration in seconds
  265. s := diff.Seconds()
  266. // Duration in days
  267. d := int(s / 86400)
  268. switch {
  269. case s < 60:
  270. return printer.Print("time_elapsed.now")
  271. case s < 3600:
  272. minutes := int(diff.Minutes())
  273. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  274. case s < 86400:
  275. hours := int(diff.Hours())
  276. return printer.Plural("time_elapsed.hours", hours, hours)
  277. case d == 1:
  278. return printer.Print("time_elapsed.yesterday")
  279. case d < 21:
  280. return printer.Plural("time_elapsed.days", d, d)
  281. case d < 31:
  282. weeks := int(math.Round(float64(d) / 7))
  283. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  284. case d < 365:
  285. months := int(math.Round(float64(d) / 30))
  286. return printer.Plural("time_elapsed.months", months, months)
  287. default:
  288. years := int(math.Round(float64(d) / 365))
  289. return printer.Plural("time_elapsed.years", years, years)
  290. }
  291. }
  292. func formatFileSize(b int64) string {
  293. const unit = 1024
  294. if b < unit {
  295. return fmt.Sprintf("%d B", b)
  296. }
  297. base := math.Log(float64(b)) / math.Log(unit)
  298. number := math.Pow(unit, base-math.Floor(base))
  299. return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
  300. }