dispatch/server/serve_files.go

392 lines
8.6 KiB
Go
Raw Normal View History

2015-05-15 23:18:52 +00:00
package server
import (
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/base64"
"encoding/json"
2017-04-14 02:33:44 +00:00
"io"
2015-05-15 23:18:52 +00:00
"io/ioutil"
2016-01-25 00:01:37 +00:00
"log"
2015-05-15 23:18:52 +00:00
"net/http"
2016-02-04 02:35:50 +00:00
"path"
2016-02-03 01:22:45 +00:00
"path/filepath"
2015-05-15 23:18:52 +00:00
"strconv"
"strings"
"time"
2017-04-14 02:33:44 +00:00
"github.com/dsnet/compress/brotli"
2015-12-11 03:35:48 +00:00
"github.com/khlieng/dispatch/assets"
"github.com/spf13/viper"
2015-05-15 23:18:52 +00:00
)
const longCacheControl = "public, max-age=31536000, immutable"
2017-04-14 02:33:44 +00:00
const disabledCacheControl = "no-cache, no-store, must-revalidate"
2016-02-03 01:22:45 +00:00
type File struct {
Path string
Asset string
2017-04-14 02:33:44 +00:00
GzipAsset []byte
2017-04-15 02:48:24 +00:00
Hash string
2016-02-03 01:22:45 +00:00
ContentType string
CacheControl string
2017-04-14 02:33:44 +00:00
Compressed bool
2016-02-03 01:22:45 +00:00
}
type h2PushAsset struct {
path string
hash string
}
func newH2PushAsset(name string) h2PushAsset {
return h2PushAsset{
path: name,
hash: strings.Split(name, ".")[1],
2016-02-03 01:22:45 +00:00
}
}
var (
files []*File
2018-11-06 10:13:32 +00:00
indexStylesheet string
indexScripts []string
inlineScript string
inlineScriptSha256 string
inlineScriptSW string
inlineScriptSWSha256 string
serviceWorker []byte
h2PushAssets []h2PushAsset
h2PushCookieValue string
2016-02-03 01:22:45 +00:00
contentTypes = map[string]string{
".js": "text/javascript",
".css": "text/css",
2016-02-03 01:22:45 +00:00
".woff2": "font/woff2",
".woff": "application/font-woff",
".ttf": "application/x-font-ttf",
}
hstsHeader string
2016-02-03 18:42:07 +00:00
cspEnabled bool
)
2015-05-15 23:18:52 +00:00
func (d *Dispatch) initFileServer() {
if viper.GetBool("dev") {
indexScripts = []string{"bundle.js"}
} else {
data, err := assets.Asset("asset-manifest.json")
if err != nil {
log.Fatal(err)
}
manifest := map[string]string{}
err = json.Unmarshal(data, &manifest)
2017-04-14 02:33:44 +00:00
if err != nil {
log.Fatal(err)
}
2018-11-06 10:13:32 +00:00
bootloader := decompressedAsset(manifest["boot.js"])
runtime := decompressedAsset(manifest["runtime.js"])
inlineScript = string(runtime)
2018-11-06 10:13:32 +00:00
inlineScriptSW = string(bootloader) + string(runtime)
2017-04-14 02:33:44 +00:00
hash := sha256.New()
hash.Write(runtime)
inlineScriptSha256 = base64.StdEncoding.EncodeToString(hash.Sum(nil))
2017-04-14 02:33:44 +00:00
2018-11-06 10:13:32 +00:00
hash.Reset()
hash.Write(bootloader)
hash.Write(runtime)
inlineScriptSWSha256 = base64.StdEncoding.EncodeToString(hash.Sum(nil))
indexStylesheet = manifest["main.css"]
indexScripts = []string{
manifest["vendors~main.js"],
manifest["main.js"],
}
h2PushAssets = []h2PushAsset{
newH2PushAsset(indexStylesheet),
newH2PushAsset(indexScripts[0]),
newH2PushAsset(indexScripts[1]),
}
for _, asset := range h2PushAssets {
h2PushCookieValue += asset.hash
}
2017-04-14 02:33:44 +00:00
2018-11-06 10:13:32 +00:00
ignoreAssets := []string{
manifest["runtime.js"],
manifest["boot.js"],
manifest["sw.js"],
2018-11-06 10:13:32 +00:00
}
outer:
for _, assetPath := range manifest {
2018-11-06 10:13:32 +00:00
for _, ignored := range ignoreAssets {
if assetPath == ignored {
continue outer
2018-11-06 10:13:32 +00:00
}
}
file := &File{
Path: assetPath,
Asset: strings.TrimLeft(assetPath, "/") + ".br",
ContentType: contentTypes[filepath.Ext(assetPath)],
CacheControl: longCacheControl,
Compressed: true,
}
files = append(files, file)
}
2017-04-14 02:33:44 +00:00
2016-02-03 01:22:45 +00:00
fonts, err := assets.AssetDir("font")
if err != nil {
log.Fatal(err)
}
for _, font := range fonts {
2017-04-14 02:33:44 +00:00
p := strings.TrimSuffix(font, ".br")
2016-02-03 01:22:45 +00:00
2017-04-14 02:33:44 +00:00
file := &File{
2016-02-04 02:35:50 +00:00
Path: path.Join("font", p),
Asset: path.Join("font", font),
ContentType: contentTypes[filepath.Ext(p)],
2017-04-14 02:33:44 +00:00
CacheControl: longCacheControl,
Compressed: strings.HasSuffix(font, ".br"),
}
files = append(files, file)
}
for _, file := range files {
2017-04-14 02:33:44 +00:00
if file.Compressed {
data, err := assets.Asset(file.Asset)
2017-04-14 02:33:44 +00:00
if err != nil {
log.Fatal(err)
}
file.GzipAsset = gzipAsset(data)
2017-04-14 02:33:44 +00:00
}
2016-02-03 01:22:45 +00:00
}
2018-11-06 10:13:32 +00:00
serviceWorker = decompressedAsset("sw.js")
hash.Reset()
IndexTemplate(hash, nil, indexStylesheet, inlineScriptSW, indexScripts)
indexHash := base64.StdEncoding.EncodeToString(hash.Sum(nil))
serviceWorker = append(serviceWorker, []byte(`
workbox.precaching.precacheAndRoute([{
revision: '`+indexHash+`',
url: '/?sw'
}]);
workbox.routing.registerNavigationRoute('/?sw');`)...)
2016-02-03 18:42:07 +00:00
if viper.GetBool("https.hsts.enabled") && viper.GetBool("https.enabled") {
hstsHeader = "max-age=" + viper.GetString("https.hsts.max_age")
if viper.GetBool("https.hsts.include_subdomains") {
hstsHeader += "; includeSubDomains"
}
if viper.GetBool("https.hsts.preload") {
hstsHeader += "; preload"
}
}
2016-02-03 18:42:07 +00:00
cspEnabled = true
}
2015-05-15 23:18:52 +00:00
}
func decompressAsset(data []byte) []byte {
br, err := brotli.NewReader(bytes.NewReader(data), nil)
if err != nil {
log.Fatal(err)
}
buf := &bytes.Buffer{}
io.Copy(buf, br)
return buf.Bytes()
}
2018-11-06 10:13:32 +00:00
func decompressedAsset(name string) []byte {
asset, err := assets.Asset(strings.TrimLeft(name, "/") + ".br")
2018-11-06 10:13:32 +00:00
if err != nil {
log.Fatal(err)
}
return decompressAsset(asset)
}
func gzipAsset(data []byte) []byte {
br, err := brotli.NewReader(bytes.NewReader(data), nil)
if err != nil {
log.Fatal(err)
}
buf := &bytes.Buffer{}
gzw, err := gzip.NewWriterLevel(buf, gzip.BestCompression)
if err != nil {
log.Fatal(err)
}
io.Copy(gzw, br)
gzw.Close()
return buf.Bytes()
}
func (d *Dispatch) serveFiles(w http.ResponseWriter, r *http.Request) {
2015-05-15 23:18:52 +00:00
if r.URL.Path == "/" {
d.serveIndex(w, r)
2015-05-15 23:18:52 +00:00
return
}
2018-11-06 10:13:32 +00:00
if r.URL.Path == "/sw.js" {
w.Header().Set("Cache-Control", disabledCacheControl)
w.Header().Set("Content-Type", "text/javascript")
w.Header().Set("Content-Length", strconv.Itoa(len(serviceWorker)))
w.Write(serviceWorker)
return
}
2015-05-15 23:18:52 +00:00
for _, file := range files {
if strings.HasSuffix(r.URL.Path, file.Path) {
d.serveFile(w, r, file)
2015-05-15 23:18:52 +00:00
return
}
}
d.serveIndex(w, r)
2016-01-25 00:01:37 +00:00
}
func (d *Dispatch) serveIndex(w http.ResponseWriter, r *http.Request) {
state := d.handleAuth(w, r, false)
2016-01-25 00:01:37 +00:00
2018-11-06 10:13:32 +00:00
_, sw := r.URL.Query()["sw"]
2016-02-03 18:42:07 +00:00
if cspEnabled {
2018-11-06 10:13:32 +00:00
var wsSrc string
2016-02-03 18:42:07 +00:00
if r.TLS != nil {
2018-11-06 10:13:32 +00:00
wsSrc = "wss://" + r.Host
2016-02-03 18:42:07 +00:00
} else {
2018-11-06 10:13:32 +00:00
wsSrc = "ws://" + r.Host
}
inlineSha := inlineScriptSha256
if sw {
inlineSha = inlineScriptSWSha256
2016-02-03 18:42:07 +00:00
}
2018-11-06 10:13:32 +00:00
w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self' 'sha256-"+inlineSha+"'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src data:; connect-src 'self' "+wsSrc)
2016-02-03 18:42:07 +00:00
}
2016-01-25 00:01:37 +00:00
w.Header().Set("Content-Type", "text/html")
2017-04-14 02:33:44 +00:00
w.Header().Set("Cache-Control", disabledCacheControl)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "deny")
w.Header().Set("X-XSS-Protection", "1; mode=block")
if hstsHeader != "" {
w.Header().Set("Strict-Transport-Security", hstsHeader)
}
2016-01-25 00:01:37 +00:00
2017-04-15 02:48:24 +00:00
if pusher, ok := w.(http.Pusher); ok {
options := &http.PushOptions{
Header: http.Header{
"Accept-Encoding": r.Header["Accept-Encoding"],
},
}
cookie, err := r.Cookie("push")
if err != nil {
for _, asset := range h2PushAssets {
pusher.Push(asset.path, options)
}
2017-04-15 02:48:24 +00:00
setPushCookie(w, r)
} else {
pushed := false
for i, asset := range h2PushAssets {
if len(cookie.Value) >= (i+1)*8 &&
asset.hash != cookie.Value[i*8:(i+1)*8] {
pusher.Push(asset.path, options)
pushed = true
}
2017-04-15 02:48:24 +00:00
}
if pushed {
setPushCookie(w, r)
}
}
}
2018-11-06 10:13:32 +00:00
var data *indexData
if !sw {
data = getIndexData(r, state)
}
inline := inlineScript
if sw {
inline = inlineScriptSW
}
2016-01-25 00:01:37 +00:00
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
2016-01-25 00:01:37 +00:00
gzw := gzip.NewWriter(w)
2018-11-06 10:13:32 +00:00
IndexTemplate(gzw, data, indexStylesheet, inline, indexScripts)
2016-01-25 00:01:37 +00:00
gzw.Close()
} else {
2018-11-06 10:13:32 +00:00
IndexTemplate(w, data, indexStylesheet, inline, indexScripts)
2016-01-25 00:01:37 +00:00
}
2015-05-15 23:18:52 +00:00
}
2017-04-15 02:48:24 +00:00
func setPushCookie(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "push",
Value: h2PushCookieValue,
2017-04-15 02:48:24 +00:00
Path: "/",
Expires: time.Now().AddDate(1, 0, 0),
HttpOnly: true,
Secure: r.TLS != nil,
})
}
func (d *Dispatch) serveFile(w http.ResponseWriter, r *http.Request, file *File) {
2016-02-03 01:22:45 +00:00
data, err := assets.Asset(file.Asset)
2015-05-15 23:18:52 +00:00
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
2016-02-03 01:22:45 +00:00
if file.CacheControl != "" {
w.Header().Set("Cache-Control", file.CacheControl)
}
w.Header().Set("Content-Type", file.ContentType)
2015-05-15 23:18:52 +00:00
if file.Compressed && strings.Contains(r.Header.Get("Accept-Encoding"), "br") {
w.Header().Set("Content-Encoding", "br")
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Write(data)
} else if file.Compressed && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Length", strconv.Itoa(len(file.GzipAsset)))
w.Write(file.GzipAsset)
2017-04-14 02:33:44 +00:00
} else if !file.Compressed {
2016-02-03 01:22:45 +00:00
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Write(data)
2015-05-15 23:18:52 +00:00
} else {
2017-04-14 02:33:44 +00:00
gzr, err := gzip.NewReader(bytes.NewReader(file.GzipAsset))
2015-05-15 23:18:52 +00:00
buf, err := ioutil.ReadAll(gzr)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(buf)))
w.Write(buf)
}
}