4
0

functions.go 9.0 KB

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