[#46] Remove external font deps, add SRI checks (#47)

This commit is contained in:
Knut Ahlers 2021-09-26 14:49:18 +02:00 committed by GitHub
parent ef910705f8
commit 9ad6d468fd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 274 additions and 59 deletions

View file

@ -1 +1 @@
src src/node_modules

2
.gitignore vendored
View file

@ -1,7 +1,9 @@
frontend/app.js
frontend/app.js.LICENSE.txt frontend/app.js.LICENSE.txt
frontend/css frontend/css
frontend/js frontend/js
frontend/locale/*.untranslated.json frontend/locale/*.untranslated.json
frontend/webfonts frontend/webfonts
frontend/*.woff2
node_modules node_modules
ots ots

View file

@ -1,13 +1,14 @@
--- ---
image: "reporunner/golang-alpine" image: "reporunner/archlinux"
checkout_dir: /go/src/github.com/Luzifer/ots checkout_dir: /go/src/github.com/Luzifer/ots
commands: commands:
# Dependencies for downloading libraries # Dependencies for downloading libraries
- apk add --update curl git make tar unzip - pacman -Syy --noconfirm awk curl git go make nodejs-lts-fermium npm tar unzip which zip
- make publish - make publish
environment: environment:
DRAFT: "false"
CGO_ENABLED: 0 CGO_ENABLED: 0
DRAFT: "false"
GOPATH: /go

View file

@ -1,20 +1,28 @@
FROM golang:alpine as builder FROM luzifer/archlinux as builder
ENV CGO_ENABLED=0 \
GOPATH=/go
COPY . /go/src/github.com/Luzifer/ots COPY . /go/src/github.com/Luzifer/ots
WORKDIR /go/src/github.com/Luzifer/ots WORKDIR /go/src/github.com/Luzifer/ots
RUN set -ex \ RUN set -ex \
&& apk add --update \ && pacman --noconfirm -Syy \
curl \ curl \
git \ git \
go \
make \ make \
nodejs-lts-fermium \
npm \
tar \ tar \
unzip \ unzip \
&& make -C src -f ../Makefile generate-inner \
&& make download_libs \ && make download_libs \
&& go install \ && go install \
-ldflags "-X main.version=$(git describe --tags --always || echo dev)" \ -ldflags "-X main.version=$(git describe --tags --always || echo dev)" \
-mod=readonly -mod=readonly
FROM alpine:latest FROM alpine:latest
LABEL maintainer "Knut Ahlers <knut@ahlers.me>" LABEL maintainer "Knut Ahlers <knut@ahlers.me>"

View file

@ -1,16 +1,28 @@
FROM golang:alpine as builder FROM luzifer/archlinux as builder
ENV CGO_ENABLED=0 ENV CGO_ENABLED=0 \
GOPATH=/go
COPY . /go/src/github.com/Luzifer/ots COPY . /go/src/github.com/Luzifer/ots
WORKDIR /go/src/github.com/Luzifer/ots WORKDIR /go/src/github.com/Luzifer/ots
RUN set -ex \ RUN set -ex \
&& apk add --update git \ && pacman --noconfirm -Syy \
curl \
git \
go \
make \
nodejs-lts-fermium \
npm \
tar \
unzip \
&& make -C src -f ../Makefile generate-inner \
&& make download_libs \
&& go install \ && go install \
-ldflags "-X main.version=$(git describe --tags --always || echo dev)" \ -ldflags "-X main.version=$(git describe --tags --always || echo dev)" \
-mod=readonly -mod=readonly
FROM scratch FROM scratch
LABEL maintainer "Knut Ahlers <knut@ahlers.me>" LABEL maintainer "Knut Ahlers <knut@ahlers.me>"

View file

@ -4,10 +4,15 @@ VER_FONTAWESOME=5.14.0
default: generate download_libs default: generate download_libs
generate: generate:
docker run --rm -ti -v $(CURDIR):$(CURDIR) -w $(CURDIR)/src node:14-alpine \ docker run --rm -i -v $(CURDIR):$(CURDIR) -w $(CURDIR) node:14-alpine \
sh -exc "npx npm@lts ci && npx npm@lts run build && chown -R $(shell id -u) ../frontend node_modules" sh -exc "apk add make && make -C src -f ../Makefile generate-inner && chown -R $(shell id -u) frontend src/node_modules"
generate-inner:
npx npm@lts ci
npx npm@lts run build
publish: download_libs publish: download_libs
$(MAKE) -C src -f ../Makefile generate-inner
curl -sSLo golang.sh https://raw.githubusercontent.com/Luzifer/github-publish/master/golang.sh curl -sSLo golang.sh https://raw.githubusercontent.com/Luzifer/github-publish/master/golang.sh
bash golang.sh bash golang.sh

File diff suppressed because one or more lines are too long

View file

@ -6,7 +6,22 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/all.min.css"/> {{ range (list "webfonts/fa-solid-900.woff2" "webfonts/fa-brands-400.woff2" "lato-v20-latin-ext_latin-regular.woff2" "lato-v20-latin-ext_latin-700.woff2") }}
<link
as="font"
crossorigin="anonymous"
href="{{ . }}"
integrity="{{ assetSRI . }}"
rel="preload"
>
{{ end }}
<link
crossorigin="anonymous"
href="css/all.min.css"
integrity="{{ assetSRI `css/all.min.css` }}"
rel="stylesheet"
>
<title>OTS - One Time Secrets</title> <title>OTS - One Time Secrets</title>
@ -24,13 +39,21 @@
// Very early load of theme definition to avoid flickering // Very early load of theme definition to avoid flickering
document.addEventListener('DOMContentLoaded', () => window.refreshTheme()) document.addEventListener('DOMContentLoaded', () => window.refreshTheme())
// Template variable from Golang process
{{- range $key, $value := .Vars }}
const {{ $key }} = "{{ $value }}"
{{- end }}
</script> </script>
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
<script src="vars.js"></script> <script
<script src="app.js"></script> crossorigin="anonymous"
integrity="{{ assetSRI `app.js` }}"
src="app.js"
></script>
</body> </body>
</html> </html>

1
go.mod
View file

@ -7,6 +7,7 @@ require (
github.com/Luzifer/rconfig/v2 v2.2.1 github.com/Luzifer/rconfig/v2 v2.2.1
github.com/gofrs/uuid/v3 v3.1.2 github.com/gofrs/uuid/v3 v3.1.2
github.com/gorilla/mux v1.7.3 github.com/gorilla/mux v1.7.3
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.4.2 github.com/sirupsen/logrus v1.4.2
github.com/xuyu/goredis v0.0.0-20160929021245-89fbe9474b37 github.com/xuyu/goredis v0.0.0-20160929021245-89fbe9474b37
) )

2
go.sum
View file

@ -13,6 +13,8 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv
github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/leekchan/gtf v0.0.0-20190214083521-5fba33c5b00b/go.mod h1:thNruaSwydMhkQ8dXzapABF9Sc1Tz08ZBcDdgott9RA= github.com/leekchan/gtf v0.0.0-20190214083521-5fba33c5b00b/go.mod h1:thNruaSwydMhkQ8dXzapABF9Sc1Tz08ZBcDdgott9RA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=

66
main.go
View file

@ -8,8 +8,10 @@ import (
"os" "os"
"path" "path"
"strings" "strings"
"text/template"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
http_helpers "github.com/Luzifer/go_helpers/v2/http" http_helpers "github.com/Luzifer/go_helpers/v2/http"
@ -56,66 +58,58 @@ func main() {
api := newAPI(store) api := newAPI(store)
r := mux.NewRouter() r := mux.NewRouter()
r.Use(http_helpers.GzipHandler)
api.Register(r.PathPrefix("/api").Subrouter()) api.Register(r.PathPrefix("/api").Subrouter())
r.HandleFunc("/vars.js", handleVars)
r.PathPrefix("/").HandlerFunc(http_helpers.GzipFunc(assetDelivery)) r.HandleFunc("/", handleIndex)
r.PathPrefix("/").HandlerFunc(assetDelivery)
log.Fatalf("HTTP server quit: %s", http.ListenAndServe(cfg.Listen, http_helpers.NewHTTPLogHandler(r))) log.Fatalf("HTTP server quit: %s", http.ListenAndServe(cfg.Listen, http_helpers.NewHTTPLogHandler(r)))
} }
func assetDelivery(res http.ResponseWriter, r *http.Request) { func assetDelivery(w http.ResponseWriter, r *http.Request) {
assetName := r.URL.Path assetName := r.URL.Path
if assetName == "/" {
assetName = "/index.html"
}
dot := strings.LastIndex(assetName, ".") dot := strings.LastIndex(assetName, ".")
if dot < 0 { if dot < 0 {
// There are no assets with no dot in it // There are no assets with no dot in it
http.Error(res, "404 not found", http.StatusNotFound) http.Error(w, "404 not found", http.StatusNotFound)
return return
} }
ext := assetName[dot:] ext := assetName[dot:]
assetData, err := assets.ReadFile(path.Join("frontend", assetName)) assetData, err := assets.ReadFile(path.Join("frontend", assetName))
if err != nil { if err != nil {
http.Error(res, "404 not found", http.StatusNotFound) http.Error(w, "404 not found", http.StatusNotFound)
return return
} }
res.Header().Set("Content-Type", mime.TypeByExtension(ext)) w.Header().Set("Content-Type", mime.TypeByExtension(ext))
res.Write(assetData) w.Write(assetData)
} }
func handleVars(w http.ResponseWriter, r *http.Request) { func handleIndex(w http.ResponseWriter, r *http.Request) {
cookie, _ := r.Cookie("lang") indexTpl, err := assets.ReadFile("frontend/index.html")
if err != nil {
cookieLang := "" http.Error(w, "404 not found", http.StatusNotFound)
if cookie != nil { return
cookieLang = cookie.Value
}
acceptLang := r.Header.Get("Accept-Language")
defaultLang := "en" // known valid language
vars := map[string]string{
"version": version,
} }
switch { tpl, err := template.New("index.html").Funcs(tplFuncs).Parse(string(indexTpl))
case cookieLang != "": if err != nil {
vars["locale"] = normalizeLang(cookieLang) http.Error(w, errors.Wrap(err, "parsing template").Error(), http.StatusInternalServerError)
case acceptLang != "": return
vars["locale"] = normalizeLang(strings.Split(acceptLang, ",")[0])
default:
vars["locale"] = defaultLang
} }
w.Header().Set("Content-Type", "application/javascript") if err = tpl.Execute(w, struct {
for k, v := range vars { Vars map[string]string
fmt.Fprintf(w, "var %s = %q\n", k, v) }{
Vars: map[string]string{
"version": version,
},
}); err != nil {
http.Error(w, errors.Wrap(err, "parsing template").Error(), http.StatusInternalServerError)
return
} }
} }
func normalizeLang(lang string) string {
return strings.ToLower(strings.Split(lang, "-")[0])
}

21
src/lato.scss Normal file
View file

@ -0,0 +1,21 @@
/* lato-regular - latin-ext_latin */
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 400;
src: url('latofont/lato-v20-latin-ext_latin-regular.woff2') format('woff2'); /* Chrome 26+, Opera 23+, Firefox 39+ */
}
/* lato-italic - latin-ext_latin */
@font-face {
font-family: 'Lato';
font-style: italic;
font-weight: 400;
src: url('latofont/lato-v20-latin-ext_latin-italic.woff2') format('woff2'); /* Chrome 26+, Opera 23+, Firefox 39+ */
}
/* lato-700 - latin-ext_latin */
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 700;
src: url('latofont/lato-v20-latin-ext_latin-700.woff2') format('woff2'); /* Chrome 26+, Opera 23+, Firefox 39+ */
}

94
src/latofont/OFL.txt Executable file
View file

@ -0,0 +1,94 @@
Copyright (c) 2010-2015, Łukasz Dziedzic (dziedzic@typoland.com),
with Reserved Font Name Lato.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -13,8 +13,12 @@ import messages from './langs/langs.js'
Vue.use(BootstrapVue) Vue.use(BootstrapVue)
Vue.use(VueI18n) Vue.use(VueI18n)
const cookieSet = Object.fromEntries(document.cookie.split('; ')
.map(el => el.split('=')
.map(el => decodeURIComponent(el))))
const i18n = new VueI18n({ const i18n = new VueI18n({
locale, locale: cookieSet.lang?.split(/[_-]/)[0] || navigator?.language?.split(/[_-]/)[0] || 'en',
fallbackLocale: 'en', fallbackLocale: 'en',
messages, messages,
}) })

View file

@ -1,7 +1,14 @@
// Force local fonts
$web-font-path: '';
@import "lato";
:root { :root {
&[mode="dark"] { &[mode="dark"] {
@import "node_modules/bootswatch/dist/darkly/bootstrap"; @import "node_modules/bootswatch/dist/darkly/_variables";
@import "node_modules/bootstrap/scss/bootstrap";
@import "node_modules/bootswatch/dist/darkly/_bootswatch";
.custom-control-input:checked ~ .custom-control-label::before { .custom-control-input:checked ~ .custom-control-label::before {
border-color: #333; border-color: #333;
@ -31,7 +38,9 @@
} }
&[mode="light"] { &[mode="light"] {
@import "node_modules/bootswatch/dist/flatly/bootstrap"; @import "node_modules/bootswatch/dist/flatly/_variables";
@import "node_modules/bootstrap/scss/bootstrap";
@import "node_modules/bootswatch/dist/flatly/_bootswatch";
.footer { .footer {
color: #2f2f2f; color: #2f2f2f;

View file

@ -48,6 +48,14 @@ module.exports = {
loader: 'vue-loader', loader: 'vue-loader',
}, },
{
test: /\.woff2/,
type: 'asset/resource',
generator: {
filename: '[name][ext]',
},
},
], ],
}, },
} }

View file

@ -4,14 +4,23 @@ import (
"crypto/sha512" "crypto/sha512"
"encoding/base64" "encoding/base64"
"path" "path"
"sync"
"text/template" "text/template"
) )
var tplFuncs = template.FuncMap{ var (
"SRIHash": assetSRIHash, sriCacheStore = newSRICache()
} tplFuncs = template.FuncMap{
"list": func(args ...string) []string { return args },
"assetSRI": assetSRIHash,
}
)
func assetSRIHash(assetName string) string { func assetSRIHash(assetName string) string {
if sri, ok := sriCacheStore.Get(assetName); ok {
return sri
}
data, err := assets.ReadFile(path.Join("frontend", assetName)) data, err := assets.ReadFile(path.Join("frontend", assetName))
if err != nil { if err != nil {
panic(err) panic(err)
@ -21,5 +30,29 @@ func assetSRIHash(assetName string) string {
h.Write(data) h.Write(data)
sum := h.Sum(nil) sum := h.Sum(nil)
return "sha384-" + base64.StdEncoding.EncodeToString(sum) sri := "sha384-" + base64.StdEncoding.EncodeToString(sum)
sriCacheStore.Set(assetName, sri)
return sri
}
type sriCache struct {
c map[string]string
l sync.RWMutex
}
func newSRICache() *sriCache { return &sriCache{c: map[string]string{}} }
func (s *sriCache) Get(assetName string) (string, bool) {
s.l.RLock()
defer s.l.RUnlock()
h, ok := s.c[assetName]
return h, ok
}
func (s *sriCache) Set(assetName, hash string) {
s.l.Lock()
defer s.l.Unlock()
s.c[assetName] = hash
} }