1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6 "crypto/sha256"
7 "embed"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "io/fs"
12 "net/http"
13 "path"
14 "sort"
15 "strings"
16)
17
18//go:embed static
19var staticFS embed.FS
20
21// StaticPrefix is where the embedded assets are served.
22const StaticPrefix = "/-/static/"
23
24// Assets are the URLs of the assets a page loads. Their names carry a hash of
25// the content, so they can be cached for ever.
26type Assets struct {
27 CSS, HTMX, Live, SSE, App, Files, Passkey, Log, Icon string
28 // Manifest is the web app manifest (install on a phone's home screen),
29 // AppleIcon the home screen icon iOS reads from a link instead.
30 Manifest, AppleIcon string
31 // Font is the UI font, preloaded by every page.
32 Font string
33 // Rules is the speculation rules file named by the Speculation-Rules header.
34 Rules string
35}
36
37// asset is one embedded file under its content-hashed name.
38type asset struct {
39 body []byte
40 typ string
41 // gz is the gzip form of body, compressed once at load; nil when the type
42 // is already compressed or gzip does not make the body smaller.
43 gz []byte
44}
45
46// assetSet is the embedded files by hashed URL path (under StaticPrefix).
47type assetSet struct {
48 byName map[string]asset
49 urls Assets
50}
51
52// scripts are the JavaScript files of the page, in embedded static/js: the
53// file to serve, as it is named in Assets.
54var scripts = []struct {
55 file string
56 set func(*Assets, string)
57}{
58 {"htmx.min.js", func(a *Assets, u string) { a.HTMX = u }},
59 {"hx-live.min.js", func(a *Assets, u string) { a.Live = u }},
60 {"hx-sse.min.js", func(a *Assets, u string) { a.SSE = u }},
61 {"ermite.js", func(a *Assets, u string) { a.App = u }},
62 {"files.js", func(a *Assets, u string) { a.Files = u }},
63 {"passkey.js", func(a *Assets, u string) { a.Passkey = u }},
64 {"log.js", func(a *Assets, u string) { a.Log = u }},
65}
66
67// sheetAssets are the files the stylesheet references as url(<dir>/<file>):
68// fonts and icons (pages hold no inline SVG; icons are CSS masks).
69var sheetAssets = []struct{ glob, typ string }{
70 {"static/fonts/*.woff2", "font/woff2"},
71 {"static/icons/*.svg", "image/svg+xml"},
72}
73
74// loadAssets hashes the embedded files. The stylesheet is the concatenation
75// of static/css/*.css in name order; its url(<dir>/<file>) references become
76// the hashed URLs of the files of sheetAssets.
77func loadAssets() (*assetSet, error) {
78 s := &assetSet{byName: map[string]asset{}}
79 put := func(dir, file string, body []byte, typ string) string {
80 sum := sha256.Sum256(body)
81 ext := path.Ext(file)
82 name := dir + "/" + strings.TrimSuffix(file, ext) + "." + hex.EncodeToString(sum[:6]) + ext
83 a := asset{body: body, typ: typ}
84 if compressible(typ) {
85 if z, err := gzipBest(body); err == nil && len(z) < len(body) {
86 a.gz = z
87 }
88 }
89 s.byName[name] = a
90 return StaticPrefix + name
91 }
92
93 var refs []string
94 for _, sa := range sheetAssets {
95 files, err := fs.Glob(staticFS, sa.glob)
96 if err != nil {
97 return nil, err
98 }
99 for _, f := range files {
100 b, err := staticFS.ReadFile(f)
101 if err != nil {
102 return nil, err
103 }
104 dir := path.Base(path.Dir(f))
105 u := put(dir, path.Base(f), b, sa.typ)
106 refs = append(refs, "url("+dir+"/"+path.Base(f)+")", "url("+u+")")
107 if f == "static/fonts/atkinson-next.woff2" {
108 s.urls.Font = u
109 }
110 }
111 }
112
113 files, err := fs.Glob(staticFS, "static/css/*.css")
114 if err != nil {
115 return nil, err
116 }
117 sort.Strings(files)
118 var css strings.Builder
119 for _, f := range files {
120 b, err := staticFS.ReadFile(f)
121 if err != nil {
122 return nil, err
123 }
124 css.WriteString("/* " + path.Base(f) + " */\n")
125 css.Write(b)
126 }
127 if s.urls.Font == "" {
128 return nil, errors.New("web: the UI font static/fonts/atkinson-next.woff2 is missing")
129 }
130 sheet := strings.NewReplacer(refs...).Replace(css.String())
131 s.urls.CSS = put("css", "ermite.css", []byte(sheet), "text/css; charset=utf-8")
132
133 rules, err := staticFS.ReadFile("static/rules.json")
134 if err != nil {
135 return nil, err
136 }
137 s.urls.Rules = put("rules", "rules.json", rules, "application/speculationrules+json")
138
139 for _, sc := range scripts {
140 b, err := staticFS.ReadFile("static/js/" + sc.file)
141 if err != nil {
142 return nil, err
143 }
144 sc.set(&s.urls, put("js", sc.file, b, "text/javascript; charset=utf-8"))
145 }
146
147 // The favicon is the brand picture of the header.
148 icon, err := staticFS.ReadFile("static/icons/brand.svg")
149 if err != nil {
150 return nil, err
151 }
152 s.urls.Icon = put("img", "icon.svg", icon, "image/svg+xml")
153
154 if err := s.loadApp(put); err != nil {
155 return nil, err
156 }
157 return s, nil
158}
159
160// appIcons are the PNG icons of the installed app (static/app), in the
161// manifest; purpose "maskable" has the picture inside the safe zone on a
162// full-bleed background, for launchers that crop to a circle or a squircle.
163var appIcons = []struct{ file, sizes, purpose string }{
164 {"icon-192.png", "192x192", "any"},
165 {"icon-512.png", "512x512", "any"},
166 {"icon-maskable-512.png", "512x512", "maskable"},
167}
168
169// webManifest is the shape of the web app manifest: the minimum a browser
170// asks for to offer "install" / "add to home screen".
171type webManifest struct {
172 Name string `json:"name"`
173 ShortName string `json:"short_name"`
174 StartURL string `json:"start_url"`
175 Scope string `json:"scope"`
176 Display string `json:"display"`
177 BackgroundColor string `json:"background_color"`
178 ThemeColor string `json:"theme_color"`
179 Icons []manifestIcon `json:"icons"`
180}
181
182type manifestIcon struct {
183 Src string `json:"src"`
184 Sizes string `json:"sizes"`
185 Type string `json:"type"`
186 Purpose string `json:"purpose"`
187}
188
189// appColor is the dark canvas: the splash screen and the bar of the installed
190// app (the pages follow the system theme; the manifest takes one colour).
191const appColor = "#050505"
192
193// loadApp adds the app icons and the manifest, which names them by their
194// hashed URLs.
195func (s *assetSet) loadApp(put func(dir, name string, b []byte, typ string) string) error {
196 m := webManifest{
197 Name: "ermite", ShortName: "ermite", StartURL: "/", Scope: "/", Display: "standalone",
198 BackgroundColor: appColor, ThemeColor: appColor,
199 }
200 for _, ic := range appIcons {
201 b, err := staticFS.ReadFile("static/app/" + ic.file)
202 if err != nil {
203 return err
204 }
205 m.Icons = append(m.Icons, manifestIcon{Src: put("app", ic.file, b, "image/png"), Sizes: ic.sizes, Type: "image/png", Purpose: ic.purpose})
206 }
207 apple, err := staticFS.ReadFile("static/app/apple-touch-icon.png")
208 if err != nil {
209 return err
210 }
211 s.urls.AppleIcon = put("app", "apple-touch-icon.png", apple, "image/png")
212 b, err := json.Marshal(m)
213 if err != nil {
214 return err
215 }
216 s.urls.Manifest = put("app", "manifest.webmanifest", b, "application/manifest+json")
217 return nil
218}
219
220// serve answers GET /-/static/<hashed name>. A name that does not match a
221// current asset is a 404, so a stale hash never serves the wrong content.
222func (s *assetSet) serve(w http.ResponseWriter, r *http.Request) {
223 a, ok := s.byName[strings.TrimPrefix(r.URL.Path, StaticPrefix)]
224 if !ok {
225 http.NotFound(w, r)
226 return
227 }
228 h := w.Header()
229 h.Set("Content-Type", a.typ)
230 h.Set("Cache-Control", "public, max-age=31536000, immutable")
231 body := a.body
232 if a.gz != nil {
233 addVary(h, "Accept-Encoding")
234 if acceptsGzip(r.Header) {
235 body = a.gz
236 h.Set("Content-Encoding", "gzip")
237 }
238 }
239 h.Set("Content-Length", itoa(len(body)))
240 if r.Method != http.MethodHead {
241 _, _ = w.Write(body)
242 }
243}
244
245// compressible tells whether a content type is worth gzip: text and
246// structured text. Fonts (woff2) and raster images are compressed already.
247func compressible(typ string) bool {
248 mt, _, _ := strings.Cut(typ, ";")
249 mt = strings.TrimSpace(strings.ToLower(mt))
250 return strings.HasPrefix(mt, "text/") || mt == "image/svg+xml" ||
251 mt == "application/javascript" || strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "/json")
252}