1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6 "crypto/sha256"
7 "embed"
8 "encoding/hex"
9 "errors"
10 "io/fs"
11 "net/http"
12 "path"
13 "sort"
14 "strings"
15)
16
17//go:embed static
18var staticFS embed.FS
19
20// StaticPrefix is where the embedded assets are served.
21const StaticPrefix = "/-/static/"
22
23// Assets are the URLs of the assets a page loads. Their names carry a hash of
24// the content, so they can be cached for ever.
25type Assets struct {
26 CSS, HTMX, Live, SSE, App, Icon string
27 // Font is the UI font, preloaded by every page.
28 Font string
29 // Rules is the speculation rules file named by the Speculation-Rules header.
30 Rules string
31}
32
33// asset is one embedded file under its content-hashed name.
34type asset struct {
35 body []byte
36 typ string
37}
38
39// assetSet is the embedded files by hashed URL path (under StaticPrefix).
40type assetSet struct {
41 byName map[string]asset
42 urls Assets
43}
44
45// scripts are the JavaScript files of the page, in embedded static/js: the
46// file to serve, as it is named in Assets.
47var scripts = []struct {
48 file string
49 set func(*Assets, string)
50}{
51 {"htmx.min.js", func(a *Assets, u string) { a.HTMX = u }},
52 {"hx-live.min.js", func(a *Assets, u string) { a.Live = u }},
53 {"hx-sse.min.js", func(a *Assets, u string) { a.SSE = u }},
54 {"ermite.js", func(a *Assets, u string) { a.App = u }},
55}
56
57// sheetAssets are the files the stylesheet references as url(<dir>/<file>):
58// fonts and icons (pages hold no inline SVG; icons are CSS masks).
59var sheetAssets = []struct{ glob, typ string }{
60 {"static/fonts/*.woff2", "font/woff2"},
61 {"static/icons/*.svg", "image/svg+xml"},
62}
63
64// loadAssets hashes the embedded files. The stylesheet is the concatenation
65// of static/css/*.css in name order; its url(<dir>/<file>) references become
66// the hashed URLs of the files of sheetAssets.
67func loadAssets() (*assetSet, error) {
68 s := &assetSet{byName: map[string]asset{}}
69 put := func(dir, file string, body []byte, typ string) string {
70 sum := sha256.Sum256(body)
71 ext := path.Ext(file)
72 name := dir + "/" + strings.TrimSuffix(file, ext) + "." + hex.EncodeToString(sum[:6]) + ext
73 s.byName[name] = asset{body: body, typ: typ}
74 return StaticPrefix + name
75 }
76
77 var refs []string
78 for _, sa := range sheetAssets {
79 files, err := fs.Glob(staticFS, sa.glob)
80 if err != nil {
81 return nil, err
82 }
83 for _, f := range files {
84 b, err := staticFS.ReadFile(f)
85 if err != nil {
86 return nil, err
87 }
88 dir := path.Base(path.Dir(f))
89 u := put(dir, path.Base(f), b, sa.typ)
90 refs = append(refs, "url("+dir+"/"+path.Base(f)+")", "url("+u+")")
91 if f == "static/fonts/atkinson-next.woff2" {
92 s.urls.Font = u
93 }
94 }
95 }
96
97 files, err := fs.Glob(staticFS, "static/css/*.css")
98 if err != nil {
99 return nil, err
100 }
101 sort.Strings(files)
102 var css strings.Builder
103 for _, f := range files {
104 b, err := staticFS.ReadFile(f)
105 if err != nil {
106 return nil, err
107 }
108 css.WriteString("/* " + path.Base(f) + " */\n")
109 css.Write(b)
110 }
111 if s.urls.Font == "" {
112 return nil, errors.New("web: the UI font static/fonts/atkinson-next.woff2 is missing")
113 }
114 sheet := strings.NewReplacer(refs...).Replace(css.String())
115 s.urls.CSS = put("css", "ermite.css", []byte(sheet), "text/css; charset=utf-8")
116
117 rules, err := staticFS.ReadFile("static/rules.json")
118 if err != nil {
119 return nil, err
120 }
121 s.urls.Rules = put("rules", "rules.json", rules, "application/speculationrules+json")
122
123 for _, sc := range scripts {
124 b, err := staticFS.ReadFile("static/js/" + sc.file)
125 if err != nil {
126 return nil, err
127 }
128 sc.set(&s.urls, put("js", sc.file, b, "text/javascript; charset=utf-8"))
129 }
130
131 // The favicon is the brand picture of the header.
132 icon, err := staticFS.ReadFile("static/icons/brand.svg")
133 if err != nil {
134 return nil, err
135 }
136 s.urls.Icon = put("img", "icon.svg", icon, "image/svg+xml")
137 return s, nil
138}
139
140// serve answers GET /-/static/<hashed name>. A name that does not match a
141// current asset is a 404, so a stale hash never serves the wrong content.
142func (s *assetSet) serve(w http.ResponseWriter, r *http.Request) {
143 a, ok := s.byName[strings.TrimPrefix(r.URL.Path, StaticPrefix)]
144 if !ok {
145 http.NotFound(w, r)
146 return
147 }
148 h := w.Header()
149 h.Set("Content-Type", a.typ)
150 h.Set("Cache-Control", "public, max-age=31536000, immutable")
151 h.Set("Content-Length", itoa(len(a.body)))
152 if r.Method != http.MethodHead {
153 _, _ = w.Write(a.body)
154 }
155}