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, MR, 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 {"mr.js", func(a *Assets, u string) { a.MR = u }},
66}
67
68// sheetAssets are the files the stylesheet references as url(<dir>/<file>):
69// fonts and icons (pages hold no inline SVG; icons are CSS masks).
70var sheetAssets = []struct{ glob, typ string }{
71 {"static/fonts/*.woff2", "font/woff2"},
72 {"static/icons/*.svg", "image/svg+xml"},
73}
74
75// loadAssets hashes the embedded files. The stylesheet is the concatenation
76// of static/css/*.css in name order; its url(<dir>/<file>) references become
77// the hashed URLs of the files of sheetAssets.
78func loadAssets() (*assetSet, error) {
79 s := &assetSet{byName: map[string]asset{}}
80 put := func(dir, file string, body []byte, typ string) string {
81 sum := sha256.Sum256(body)
82 ext := path.Ext(file)
83 name := dir + "/" + strings.TrimSuffix(file, ext) + "." + hex.EncodeToString(sum[:6]) + ext
84 a := asset{body: body, typ: typ}
85 if compressible(typ) {
86 if z, err := gzipBest(body); err == nil && len(z) < len(body) {
87 a.gz = z
88 }
89 }
90 s.byName[name] = a
91 return StaticPrefix + name
92 }
93
94 var refs []string
95 for _, sa := range sheetAssets {
96 files, err := fs.Glob(staticFS, sa.glob)
97 if err != nil {
98 return nil, err
99 }
100 for _, f := range files {
101 b, err := staticFS.ReadFile(f)
102 if err != nil {
103 return nil, err
104 }
105 dir := path.Base(path.Dir(f))
106 u := put(dir, path.Base(f), b, sa.typ)
107 refs = append(refs, "url("+dir+"/"+path.Base(f)+")", "url("+u+")")
108 if f == "static/fonts/atkinson-next.woff2" {
109 s.urls.Font = u
110 }
111 }
112 }
113
114 files, err := fs.Glob(staticFS, "static/css/*.css")
115 if err != nil {
116 return nil, err
117 }
118 sort.Strings(files)
119 var css strings.Builder
120 for _, f := range files {
121 b, err := staticFS.ReadFile(f)
122 if err != nil {
123 return nil, err
124 }
125 css.WriteString("/* " + path.Base(f) + " */\n")
126 css.Write(b)
127 }
128 if s.urls.Font == "" {
129 return nil, errors.New("web: the UI font static/fonts/atkinson-next.woff2 is missing")
130 }
131 sheet := strings.NewReplacer(refs...).Replace(css.String())
132 s.urls.CSS = put("css", "ermite.css", []byte(sheet), "text/css; charset=utf-8")
133
134 rules, err := staticFS.ReadFile("static/rules.json")
135 if err != nil {
136 return nil, err
137 }
138 s.urls.Rules = put("rules", "rules.json", rules, "application/speculationrules+json")
139
140 for _, sc := range scripts {
141 b, err := staticFS.ReadFile("static/js/" + sc.file)
142 if err != nil {
143 return nil, err
144 }
145 sc.set(&s.urls, put("js", sc.file, b, "text/javascript; charset=utf-8"))
146 }
147
148 // The favicon is the brand picture of the header.
149 icon, err := staticFS.ReadFile("static/icons/brand.svg")
150 if err != nil {
151 return nil, err
152 }
153 s.urls.Icon = put("img", "icon.svg", icon, "image/svg+xml")
154
155 if err := s.loadApp(put); err != nil {
156 return nil, err
157 }
158 return s, nil
159}
160
161// appIcons are the PNG icons of the installed app (static/app), in the
162// manifest; purpose "maskable" has the picture inside the safe zone on a
163// full-bleed background, for launchers that crop to a circle or a squircle.
164var appIcons = []struct{ file, sizes, purpose string }{
165 {"icon-192.png", "192x192", "any"},
166 {"icon-512.png", "512x512", "any"},
167 {"icon-maskable-512.png", "512x512", "maskable"},
168}
169
170// webManifest is the shape of the web app manifest: the minimum a browser
171// asks for to offer "install" / "add to home screen".
172type webManifest struct {
173 Name string `json:"name"`
174 ShortName string `json:"short_name"`
175 StartURL string `json:"start_url"`
176 Scope string `json:"scope"`
177 Display string `json:"display"`
178 BackgroundColor string `json:"background_color"`
179 ThemeColor string `json:"theme_color"`
180 Icons []manifestIcon `json:"icons"`
181}
182
183type manifestIcon struct {
184 Src string `json:"src"`
185 Sizes string `json:"sizes"`
186 Type string `json:"type"`
187 Purpose string `json:"purpose"`
188}
189
190// appColor is the dark canvas: the splash screen and the bar of the installed
191// app (the pages follow the system theme; the manifest takes one colour).
192const appColor = "#050505"
193
194// loadApp adds the app icons and the manifest, which names them by their
195// hashed URLs.
196func (s *assetSet) loadApp(put func(dir, name string, b []byte, typ string) string) error {
197 m := webManifest{
198 Name: "ermite", ShortName: "ermite", StartURL: "/", Scope: "/", Display: "standalone",
199 BackgroundColor: appColor, ThemeColor: appColor,
200 }
201 for _, ic := range appIcons {
202 b, err := staticFS.ReadFile("static/app/" + ic.file)
203 if err != nil {
204 return err
205 }
206 m.Icons = append(m.Icons, manifestIcon{Src: put("app", ic.file, b, "image/png"), Sizes: ic.sizes, Type: "image/png", Purpose: ic.purpose})
207 }
208 apple, err := staticFS.ReadFile("static/app/apple-touch-icon.png")
209 if err != nil {
210 return err
211 }
212 s.urls.AppleIcon = put("app", "apple-touch-icon.png", apple, "image/png")
213 b, err := json.Marshal(m)
214 if err != nil {
215 return err
216 }
217 s.urls.Manifest = put("app", "manifest.webmanifest", b, "application/manifest+json")
218 return nil
219}
220
221// serve answers GET /-/static/<hashed name>. A name that does not match a
222// current asset is a 404, so a stale hash never serves the wrong content.
223func (s *assetSet) serve(w http.ResponseWriter, r *http.Request) {
224 a, ok := s.byName[strings.TrimPrefix(r.URL.Path, StaticPrefix)]
225 if !ok {
226 http.NotFound(w, r)
227 return
228 }
229 h := w.Header()
230 h.Set("Content-Type", a.typ)
231 h.Set("Cache-Control", "public, max-age=31536000, immutable")
232 body := a.body
233 if a.gz != nil {
234 addVary(h, "Accept-Encoding")
235 if acceptsGzip(r.Header) {
236 body = a.gz
237 h.Set("Content-Encoding", "gzip")
238 }
239 }
240 h.Set("Content-Length", itoa(len(body)))
241 if r.Method != http.MethodHead {
242 _, _ = w.Write(body)
243 }
244}
245
246// compressible tells whether a content type is worth gzip: text and
247// structured text. Fonts (woff2) and raster images are compressed already.
248func compressible(typ string) bool {
249 mt, _, _ := strings.Cut(typ, ";")
250 mt = strings.TrimSpace(strings.ToLower(mt))
251 return strings.HasPrefix(mt, "text/") || mt == "image/svg+xml" ||
252 mt == "application/javascript" || strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "/json")
253}