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