Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7afb6a022a | ||
|
|
fb2cb7bcfa | ||
|
|
28db4f707f | ||
|
|
0f9b40df9f | ||
|
|
d6bf6f94d8 | ||
|
|
7d5feb21a1 | ||
|
|
840e4e96e3 | ||
|
|
f4d7e3b1ab | ||
|
|
8774ef62ce | ||
|
|
e4f88485f2 | ||
|
|
03a1ce56d8 |
No files matched your search
@@ -0,0 +1,17 @@
|
|||||||
|
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
|
||||||
|
|
||||||
|
This software and its documentation are proprietary
|
||||||
|
(SPDX: LicenseRef-Proprietary). No license to use, copy, modify, merge,
|
||||||
|
publish, distribute, sublicense or sell copies of this software, in whole
|
||||||
|
or in part, is granted without the prior written permission of the
|
||||||
|
copyright holder.
|
||||||
|
|
||||||
|
Third-party components bundled in this repository keep their own licenses; see NOTICE.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# yetano-webui-template is a library (package layout): nothing to build or
|
||||||
|
# publish, only to check. A release is a git tag -- see README.md,
|
||||||
|
# "Versioning note".
|
||||||
|
|
||||||
|
.PHONY: all
|
||||||
|
all: ci
|
||||||
|
|
||||||
|
.PHONY: test
|
||||||
|
test:
|
||||||
|
go test ./... -race
|
||||||
|
|
||||||
|
.PHONY: fmt
|
||||||
|
fmt:
|
||||||
|
@out="$$(gofmt -l .)"; \
|
||||||
|
if [ -n "$$out" ]; then \
|
||||||
|
echo "not gofmt'ed:"; echo "$$out"; exit 1; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
.PHONY: fmt-fix
|
||||||
|
fmt-fix:
|
||||||
|
gofmt -w .
|
||||||
|
|
||||||
|
.PHONY: vet
|
||||||
|
vet:
|
||||||
|
go vet ./...
|
||||||
|
|
||||||
|
# govulncheck at a pinned version via "go run" -- no global install. Not
|
||||||
|
# part of test on purpose: it needs network access to vuln.go.dev, and
|
||||||
|
# since that database changes daily, a check would start failing without
|
||||||
|
# any code change (see ../TODO.md "govulncheck in allen Go-Modulen").
|
||||||
|
GOVULNCHECK ?= go run golang.org/x/vuln/cmd/govulncheck@v1.9.0
|
||||||
|
|
||||||
|
.PHONY: vulncheck
|
||||||
|
vulncheck:
|
||||||
|
$(GOVULNCHECK) ./...
|
||||||
|
|
||||||
|
.PHONY: tidy
|
||||||
|
tidy:
|
||||||
|
go mod tidy
|
||||||
|
|
||||||
|
.PHONY: ci
|
||||||
|
ci: fmt vet test vulncheck
|
||||||
|
|
||||||
|
.PHONY: help
|
||||||
|
help:
|
||||||
|
@echo "Targets:"
|
||||||
|
@echo " ci fmt + vet + test + vulncheck (the default)"
|
||||||
|
@echo " fmt fail if a file is not gofmt'ed (fmt-fix rewrites them)"
|
||||||
|
@echo " vet go vet"
|
||||||
|
@echo " test go test -race"
|
||||||
|
@echo " vulncheck govulncheck $(subst go run ,,$(GOVULNCHECK))"
|
||||||
|
@echo " tidy go mod tidy"
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
yetano-webui-template
|
||||||
|
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
|
||||||
|
yetano-webui-template itself is proprietary, see LICENSE.
|
||||||
|
|
||||||
|
This repository bundles the following third-party files, which keep
|
||||||
|
their own licenses:
|
||||||
|
|
||||||
|
- Bootstrap v5.3.3 (https://getbootstrap.com/): static/bootstrap.min.css,
|
||||||
|
static/bootstrap.bundle.min.js -- MIT, Copyright 2011-2024 The
|
||||||
|
Bootstrap Authors (https://github.com/twbs/bootstrap/blob/main/LICENSE).
|
||||||
@@ -96,10 +96,16 @@ German when `Lang` starts with `de`) with one POST form whose buttons
|
|||||||
submit `theme` or `palette`. `AppearanceHandler` stores the choice in
|
submit `theme` or `palette`. `AppearanceHandler` stores the choice in
|
||||||
the cookies `yw_theme`/`yw_palette` (path `BasePath/`, a year,
|
the cookies `yw_theme`/`yw_palette` (path `BasePath/`, a year,
|
||||||
`HttpOnly`, `SameSite=Lax`) and redirects to `back`, but only to a path
|
`HttpOnly`, `SameSite=Lax`) and redirects to `back`, but only to a path
|
||||||
inside the UI. Any other method gets 405. `ApplyAppearance` ignores unknown cookie
|
inside the UI. Any other method gets 405. `ApplyAppearance` ignores
|
||||||
values, so whatever the consumer set before stays the default. A
|
unknown cookie values, so whatever the consumer set before stays the
|
||||||
consumer with its own switch (e.g. `yareco`'s) can keep it and just set
|
default. It works with and without `http.StripPrefix` in front of the
|
||||||
`Theme`/`Palette`.
|
UI: a path that differs from the request's `RequestURI` is taken as
|
||||||
|
already relative and kept as it is (v0.3.1; up to v0.3.0 the page
|
||||||
|
`/feeds` behind StripPrefix with base path `/feeds` was wrongly cut to
|
||||||
|
`/`). A consumer whose middleware wants a CSRF token on every POST
|
||||||
|
puts the hidden field into `AppearanceFormHTML`, which is rendered
|
||||||
|
inside the menu's form. A consumer with its own switch can keep it and
|
||||||
|
just set `Theme`/`Palette` (none does today).
|
||||||
|
|
||||||
**Adding a palette:** a `:root[data-palette="..."]` block in
|
**Adding a palette:** a `:root[data-palette="..."]` block in
|
||||||
`static/style.css`, a constant and an entry in `Palettes` in
|
`static/style.css`, a constant and an entry in `Palettes` in
|
||||||
@@ -120,19 +126,105 @@ mux.Handle("/webui-static/", layout.StaticHandler("/webui-static/"))
|
|||||||
See `yetano/yasta` for a full worked example (the pilot migration of this
|
See `yetano/yasta` for a full worked example (the pilot migration of this
|
||||||
module).
|
module).
|
||||||
|
|
||||||
|
## Flash messages (v0.3.0)
|
||||||
|
|
||||||
|
A message after a form POST travels in the query parameters `flash` and
|
||||||
|
`flashKind` (owner decision 2026-10-31): no server state, and it works
|
||||||
|
behind a base path and through the Verse relay. The text lands in the
|
||||||
|
browser history, so it never carries a secret.
|
||||||
|
|
||||||
|
```go
|
||||||
|
layout.RedirectFlash(w, r, basePath+"/services", layout.FlashOK, "service a started") // 303
|
||||||
|
...
|
||||||
|
hdr.ApplyFlash(r) // fills Flash/FlashKind; an unknown kind shows as an error
|
||||||
|
```
|
||||||
|
|
||||||
|
`FlashKind` is `FlashOK` (green), `FlashInfo` (blue) or `FlashError`
|
||||||
|
(red). `ApplyAppearance` drops the flash parameters from
|
||||||
|
`AppearanceBack` (`WithoutFlash`), so switching the theme does not show
|
||||||
|
the message again.
|
||||||
|
|
||||||
|
## HTTP hardening: package `httpsec` (v0.3.0)
|
||||||
|
|
||||||
|
`teruna.dev/yetano/yetano-webui-template/httpsec`, net/http only. Owner
|
||||||
|
decisions of 2026-10-31 are built in.
|
||||||
|
|
||||||
|
- `Headers(h, HeaderOptions{...})` -- outermost wrapper. Default set:
|
||||||
|
`Content-Security-Policy` `DefaultCSP` (`default-src 'self'; img-src
|
||||||
|
'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors
|
||||||
|
'none'; form-action 'self'`), `nosniff`, `X-Frame-Options: DENY`,
|
||||||
|
`Referrer-Policy: same-origin`, `Cross-Origin-Opener-Policy:
|
||||||
|
same-origin`, `Cache-Control: no-store` except below
|
||||||
|
`CacheablePrefixes`, HSTS only with `TLS: true`. `CSP` overrides the
|
||||||
|
policy for a UI that needs more.
|
||||||
|
- Host gate against DNS rebinding: `Gate(h, allowed, "<config key>")`
|
||||||
|
answers 421. `HostAllowed` accepts IP addresses, `localhost`,
|
||||||
|
`*.localhost` and the configured hosts (add a public URL's host with
|
||||||
|
`HostOf`); an **empty Host is rejected**. `GateActive(loginOn,
|
||||||
|
allowed)` is the family rule for when to install it: **always without
|
||||||
|
a login, with a login only once hosts are configured**.
|
||||||
|
- `SafeNext(next, basePath, "/login", "/logout")` -- the target after a
|
||||||
|
login or a "back" link: a local path inside the UI, else
|
||||||
|
`basePath + "/"`.
|
||||||
|
- `CookiePath(basePath)` (`basePath + "/"`, `/` at the root) and
|
||||||
|
`SecureCookies(r, publicURL)` (TLS or an https public URL).
|
||||||
|
|
||||||
|
Cross-origin protection stays `http.NewCrossOriginProtection()` from
|
||||||
|
the standard library, wrapped inside `Headers`.
|
||||||
|
|
||||||
|
Order: `Headers(Gate(cop.Handler(app)))` -- the headers also reach a 421
|
||||||
|
or 403.
|
||||||
|
|
||||||
|
- `BearerTokens(h, tokens)` (v0.4.0) -- for a UI without user
|
||||||
|
management of its own: only requests with `Authorization: Bearer <one
|
||||||
|
of tokens>` pass (constant-time compare), others get 401. A reverse
|
||||||
|
proxy in front sets the header (Traefik `headers.customRequestHeaders`),
|
||||||
|
or yasta for a UI shown over the bus. No tokens: everything passes --
|
||||||
|
bind such a UI to loopback only.
|
||||||
|
|
||||||
|
## Web UI over the YAPL bus: package `busweb` (v0.4.0)
|
||||||
|
|
||||||
|
`teruna.dev/yetano/yetano-webui-template/busweb` (meta-repo
|
||||||
|
`docs/verse/protocols.md` §18, D-200; types in `yetano.dev/yetano/verse/web`).
|
||||||
|
A YAPL participant provides `<name>.web@1`; yasta mounts its UI at
|
||||||
|
`/apps/<service>/` of yasta's web UI and sends each HTTP request as one
|
||||||
|
call. The same `http.Handler` serves both ways:
|
||||||
|
|
||||||
|
```go
|
||||||
|
app := myUI() // links/redirects use busweb.Prefix(r)
|
||||||
|
// over the bus: in the capability handler
|
||||||
|
resp := busweb.Serve(ctx, httpsec.BearerTokens(app, tokens), req) // req web.Request
|
||||||
|
// on a TCP port (optional), e.g. behind Traefik
|
||||||
|
h := busweb.WithPrefix(app, basePath)
|
||||||
|
h = httpsec.BearerTokens(h, tokens)
|
||||||
|
h = httpsec.Headers(httpsec.Gate(http.NewCrossOriginProtection().Handler(h), hosts, "web.allowed_hosts"), httpsec.HeaderOptions{})
|
||||||
|
```
|
||||||
|
|
||||||
|
- `Prefix(r)` -- where the UI is mounted; set `PageHeader.BasePath` to it
|
||||||
|
per request (it differs between the bus, the TCP port and yasta's web
|
||||||
|
relay).
|
||||||
|
- `User(r)` -- the yasta web user for a request over the bus (yasta's
|
||||||
|
claim; require yasta's token if other participants may call the
|
||||||
|
capability), `FromBus(r)`.
|
||||||
|
- `Serve` hands the handler the path below the prefix with `RequestURI`
|
||||||
|
as the browser sent it (so `ApplyAppearance` works), keeps only the
|
||||||
|
allowed response headers and cuts bodies over 512 KiB.
|
||||||
|
|
||||||
## Migration status
|
## Migration status
|
||||||
|
|
||||||
Seven projects use it (`yet serve` on `v0.1.7`, the others on `v0.1.6`).
|
Eight projects use it, all on `v0.3.0` (2026-10-31): the built-in theme
|
||||||
|
menu, `httpsec` and the flash helpers.
|
||||||
|
|
||||||
| Project | Meta-repo | Status |
|
| Project | Meta-repo | Status |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `yasta` | yetano | migrated (pilot) |
|
| `yasta` | yetano | migrated (pilot) |
|
||||||
| `yasl` | yetano | migrated |
|
| `yasl` | yetano | migrated |
|
||||||
| `yaiam` | yetano | migrated |
|
| `yaiam` | yetano | migrated (`yaiam-web` and the `yaiam-authd` login pages) |
|
||||||
| `yakwui` | yak | migrated |
|
| `yakwui` | yak | migrated |
|
||||||
| `yamase-web` | yamase | migrated |
|
| `yamase-web` | yamase | migrated |
|
||||||
| `yamocir` | yetano | migrated |
|
| `yamocir` | yetano | migrated |
|
||||||
| `yet` (`yet serve`) | yetano | built on it (a server-rendered shell whose content area a small JS app fills) |
|
| `yet` (`yet serve`) | yetano | built on it (a server-rendered shell whose content area a small JS app fills) |
|
||||||
|
| `yareco` | yetano | built on it (reference consumer for themes) |
|
||||||
|
|
||||||
`yaais` was evaluated too and deliberately NOT migrated: it's a
|
`yaais` was evaluated too and deliberately NOT migrated: it's a
|
||||||
client-rendered SPA (static `index.html` + vanilla JS), not a
|
client-rendered SPA (static `index.html` + vanilla JS), not a
|
||||||
@@ -141,6 +233,12 @@ deliverable (Go templates) doesn't apply. It adopted the same dark
|
|||||||
palette independently in its own stylesheet instead, plus its own
|
palette independently in its own stylesheet instead, plus its own
|
||||||
light/dark toggle — see its `internal/yaais/static/style.css`.
|
light/dark toggle — see its `internal/yaais/static/style.css`.
|
||||||
|
|
||||||
|
## Checks
|
||||||
|
|
||||||
|
`make ci` (the default target) runs `fmt`, `vet`, `test` (with `-race`)
|
||||||
|
and `vulncheck` (govulncheck at a pinned version, needs network access).
|
||||||
|
Run it before tagging.
|
||||||
|
|
||||||
## Versioning note
|
## Versioning note
|
||||||
|
|
||||||
Use `v0.1.5` or later. `v0.1.3` and `v0.1.4` were force-moved to
|
Use `v0.1.5` or later. `v0.1.3` and `v0.1.4` were force-moved to
|
||||||
@@ -150,7 +248,7 @@ concurrent-edit conflict during the initial rollout) and can produce a
|
|||||||
force-move an existing tag again for any future change — always cut a
|
force-move an existing tag again for any future change — always cut a
|
||||||
new one, even for a one-line fix.
|
new one, even for a one-line fix.
|
||||||
|
|
||||||
## PageHeader fields (current as of v0.2.0)
|
## PageHeader fields (current as of v0.2.5)
|
||||||
|
|
||||||
`Title`, `AppName` (lowercase product name for `<title>`/footer — not
|
`Title`, `AppName` (lowercase product name for `<title>`/footer — not
|
||||||
`Name`, which collides with a domain type's own `Name` field once
|
`Name`, which collides with a domain type's own `Name` field once
|
||||||
@@ -158,8 +256,8 @@ embedded in the same struct, as yakwui's viewmodel types do), `Lang`
|
|||||||
(`<html lang>`, defaults to `"en"`), `Theme` (`<html data-theme>`, see
|
(`<html lang>`, defaults to `"en"`), `Theme` (`<html data-theme>`, see
|
||||||
Theming), `Brand`, `BrandInitial`, `Subtitle`,
|
Theming), `Brand`, `BrandInitial`, `Subtitle`,
|
||||||
`BasePath`, `NavItems`/`ActiveNav`, `Flash`/`FlashKind`, `Username`,
|
`BasePath`, `NavItems`/`ActiveNav`, `Flash`/`FlashKind`, `Username`,
|
||||||
`Palette`, `AppearancePath`/`AppearanceBack` (since v0.2.0, see
|
`Palette`, `AppearancePath`/`AppearanceBack` (since v0.2.0) and
|
||||||
Theming), `LogoutPath` (since v0.1.10 a `<form method="post">` with a submit
|
`AppearanceFormHTML` (since v0.2.4, see Theming), `LogoutPath` (since v0.1.10 a `<form method="post">` with a submit
|
||||||
button styled like the former link, never a GET link: a logout reachable
|
button styled like the former link, never a GET link: a logout reachable
|
||||||
by GET can be triggered from any foreign page via an `<img>`/link and by
|
by GET can be triggered from any foreign page via an `<img>`/link and by
|
||||||
link prefetchers; the consumer registers the route as `POST` only and
|
link prefetchers; the consumer registers the route as `POST` only and
|
||||||
@@ -171,4 +269,11 @@ brand link, e.g. a mobile sidebar-toggle button),
|
|||||||
`ExtraHeadHTML`/`ExtraBodyHTML`, and `BodyAttrs`/`SidebarAttrs` —
|
`ExtraHeadHTML`/`ExtraBodyHTML`, and `BodyAttrs`/`SidebarAttrs` —
|
||||||
`template.HTMLAttr`, not `template.HTML` — raw extra attributes on
|
`template.HTMLAttr`, not `template.HTML` — raw extra attributes on
|
||||||
`<body>` and the sidebar `<nav>` for a consumer's own client-side
|
`<body>` and the sidebar `<nav>` for a consumer's own client-side
|
||||||
framework state (e.g. yakwui's Alpine.js collapsible sidebar).
|
framework state (e.g. yakwui's Alpine.js collapsible sidebar). A page
|
||||||
|
without a sidebar (a login page) sets `BodyAttrs` to
|
||||||
|
`` ` class="no-sidebar"` ``: since v0.2.5 `static/style.css` then hides
|
||||||
|
the sidebar column and gives `<main>` the full width.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Proprietary (`LicenseRef-Proprietary`), see [LICENSE](LICENSE). Third-party components bundled in this repository keep their own licenses; see [NOTICE](NOTICE).
|
||||||
+26
-19
@@ -4,6 +4,8 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"teruna.dev/yetano/yetano-webui-template/httpsec"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Values for PageHeader.Palette; each has its own block in
|
// Values for PageHeader.Palette; each has its own block in
|
||||||
@@ -67,18 +69,35 @@ func (h *PageHeader) ApplyAppearance(r *http.Request) {
|
|||||||
if c, err := r.Cookie(PaletteCookie); err == nil && known(Palettes, c.Value) {
|
if c, err := r.Cookie(PaletteCookie); err == nil && known(Palettes, c.Value) {
|
||||||
h.Palette = c.Value
|
h.Palette = c.Value
|
||||||
}
|
}
|
||||||
// Only a whole leading BasePath segment is cut: behind
|
|
||||||
// http.StripPrefix the path is already relative, and "/r" must not
|
|
||||||
// eat the start of "/release-notes".
|
|
||||||
path := r.URL.Path
|
path := r.URL.Path
|
||||||
if h.BasePath != "" && (path == h.BasePath || strings.HasPrefix(path, h.BasePath+"/")) {
|
if h.BasePath != "" && !strippedPath(r) &&
|
||||||
|
(path == h.BasePath || strings.HasPrefix(path, h.BasePath+"/")) {
|
||||||
path = strings.TrimPrefix(path, h.BasePath)
|
path = strings.TrimPrefix(path, h.BasePath)
|
||||||
}
|
}
|
||||||
if path == "" {
|
if path == "" {
|
||||||
path = "/"
|
path = "/"
|
||||||
}
|
}
|
||||||
back := url.URL{Path: path, RawQuery: r.URL.RawQuery}
|
back := url.URL{Path: path, RawQuery: r.URL.RawQuery}
|
||||||
h.AppearanceBack = back.String()
|
h.AppearanceBack = WithoutFlash(back.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// strippedPath reports whether r.URL.Path is already relative to the
|
||||||
|
// UI's base path, i.e. a handler such as http.StripPrefix cut it down
|
||||||
|
// from what the client asked for. Those keep RequestURI as sent, so a
|
||||||
|
// path that no longer matches RequestURI's was stripped -- and must not
|
||||||
|
// be stripped again: for base path "/feeds" the relative page "/feeds"
|
||||||
|
// is a page of its own, not the start page. Without a RequestURI (a
|
||||||
|
// request built in code) only a whole leading BasePath segment is cut,
|
||||||
|
// so "/r" never eats the start of "/release-notes".
|
||||||
|
func strippedPath(r *http.Request) bool {
|
||||||
|
if r.RequestURI == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
u, err := url.ParseRequestURI(r.RequestURI)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return u.Path != r.URL.Path
|
||||||
}
|
}
|
||||||
|
|
||||||
// AppearanceHandler stores a theme and/or palette choice from a POST
|
// AppearanceHandler stores a theme and/or palette choice from a POST
|
||||||
@@ -103,7 +122,7 @@ func AppearanceHandler(basePath string) http.Handler {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
set := func(name, value string) {
|
set := func(name, value string) {
|
||||||
http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: basePath + "/",
|
http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: httpsec.CookiePath(basePath),
|
||||||
MaxAge: 365 * 24 * 3600, HttpOnly: true, SameSite: http.SameSiteLaxMode})
|
MaxAge: 365 * 24 * 3600, HttpOnly: true, SameSite: http.SameSiteLaxMode})
|
||||||
}
|
}
|
||||||
if theme != "" {
|
if theme != "" {
|
||||||
@@ -112,22 +131,10 @@ func AppearanceHandler(basePath string) http.Handler {
|
|||||||
if palette != "" {
|
if palette != "" {
|
||||||
set(PaletteCookie, palette)
|
set(PaletteCookie, palette)
|
||||||
}
|
}
|
||||||
http.Redirect(w, r, basePath+localPath(r.FormValue("back")), http.StatusSeeOther)
|
http.Redirect(w, r, basePath+httpsec.SafeNext(r.FormValue("back"), ""), http.StatusSeeOther)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// localPath returns back if it is a path (with query) inside this UI,
|
|
||||||
// otherwise "/".
|
|
||||||
func localPath(back string) string {
|
|
||||||
u, err := url.Parse(back)
|
|
||||||
if err != nil || u.Scheme != "" || u.Host != "" || u.User != nil ||
|
|
||||||
!strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") ||
|
|
||||||
strings.ContainsAny(back, "\\\r\n") {
|
|
||||||
return "/"
|
|
||||||
}
|
|
||||||
return back
|
|
||||||
}
|
|
||||||
|
|
||||||
// AppearanceItem is one button of the rendered appearance menu.
|
// AppearanceItem is one button of the rendered appearance menu.
|
||||||
type AppearanceItem struct {
|
type AppearanceItem struct {
|
||||||
ID, Label, Symbol string
|
ID, Label, Symbol string
|
||||||
|
|||||||
+28
-3
@@ -143,7 +143,7 @@ func TestApplyAppearance(t *testing.T) {
|
|||||||
t.Errorf("AppearanceBack = %q, want %q", h.AppearanceBack, "/tasks?f=1")
|
t.Errorf("AppearanceBack = %q, want %q", h.AppearanceBack, "/tasks?f=1")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Behind http.StripPrefix the path is already relative to BasePath.
|
// Without StripPrefix only a whole leading BasePath segment is cut.
|
||||||
for path, want := range map[string]string{"/release-notes": "/release-notes", "/r": "/", "/r/x": "/x"} {
|
for path, want := range map[string]string{"/release-notes": "/release-notes", "/r": "/", "/r/x": "/x"} {
|
||||||
h := PageHeader{BasePath: "/r"}
|
h := PageHeader{BasePath: "/r"}
|
||||||
h.ApplyAppearance(httptest.NewRequest(http.MethodGet, path, nil))
|
h.ApplyAppearance(httptest.NewRequest(http.MethodGet, path, nil))
|
||||||
@@ -153,6 +153,30 @@ func TestApplyAppearance(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Behind http.StripPrefix the path is already relative to BasePath and
|
||||||
|
// must stay as it is, even when it looks like the base path itself.
|
||||||
|
func TestApplyAppearanceBehindStripPrefix(t *testing.T) {
|
||||||
|
cases := []struct{ base, request, want string }{
|
||||||
|
{"/feeds", "/feeds/feeds", "/feeds"},
|
||||||
|
{"/feeds", "/feeds/feeds/x?a=1", "/feeds/x?a=1"},
|
||||||
|
{"/feeds", "/feeds/", "/"},
|
||||||
|
{"/feeds", "/feeds/items", "/items"},
|
||||||
|
{"/r", "/r/release-notes", "/release-notes"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
var got string
|
||||||
|
h := http.StripPrefix(c.base, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hdr := PageHeader{BasePath: c.base}
|
||||||
|
hdr.ApplyAppearance(r)
|
||||||
|
got = hdr.AppearanceBack
|
||||||
|
}))
|
||||||
|
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, c.request, nil))
|
||||||
|
if got != c.want {
|
||||||
|
t.Errorf("base %s, request %s: AppearanceBack = %q, want %q", c.base, c.request, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAppearanceHandler(t *testing.T) {
|
func TestAppearanceHandler(t *testing.T) {
|
||||||
h := AppearanceHandler("/ui")
|
h := AppearanceHandler("/ui")
|
||||||
post := func(form url.Values) *httptest.ResponseRecorder {
|
post := func(form url.Values) *httptest.ResponseRecorder {
|
||||||
@@ -209,14 +233,15 @@ func TestAppearanceMenu(t *testing.T) {
|
|||||||
|
|
||||||
buf.Reset()
|
buf.Reset()
|
||||||
data := PageHeader{Title: "Dashboard", Lang: "de", BasePath: "/ui", AppearancePath: "/appearance",
|
data := PageHeader{Title: "Dashboard", Lang: "de", BasePath: "/ui", AppearancePath: "/appearance",
|
||||||
AppearanceBack: "/tasks", Theme: ThemeLight, Palette: PaletteGraphite}
|
AppearanceBack: "/tasks", Theme: ThemeLight, Palette: PaletteGraphite,
|
||||||
|
AppearanceFormHTML: `<input type="hidden" name="csrf_token" value="t0k">`}
|
||||||
if err := r.Page(&buf, "dashboard", data); err != nil {
|
if err := r.Page(&buf, "dashboard", data); err != nil {
|
||||||
t.Fatalf("Page: %v", err)
|
t.Fatalf("Page: %v", err)
|
||||||
}
|
}
|
||||||
out := buf.String()
|
out := buf.String()
|
||||||
for _, want := range []string{
|
for _, want := range []string{
|
||||||
`<form method="post" action="/ui/appearance"`,
|
`<form method="post" action="/ui/appearance"`,
|
||||||
`name="back" value="/tasks"`,
|
`name="back" value="/tasks"><input type="hidden" name="csrf_token" value="t0k">`,
|
||||||
`name="theme" value="light" aria-pressed="true"><span aria-hidden="true">☀</span> Hell</button>`,
|
`name="theme" value="light" aria-pressed="true"><span aria-hidden="true">☀</span> Hell</button>`,
|
||||||
`name="theme" value="dark" aria-pressed="false">`,
|
`name="theme" value="dark" aria-pressed="false">`,
|
||||||
`name="palette" value="graphite" aria-pressed="true">Graphit</button>`,
|
`name="palette" value="graphite" aria-pressed="true">Graphit</button>`,
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
// Package busweb serves a web UI over the YAPL bus (meta-repository
|
||||||
|
// docs/verse/protocols.md §18, D-200): yasta mounts a participant's UI in
|
||||||
|
// its own web UI and sends each HTTP request as one call of the
|
||||||
|
// participant's "<name>.web@N" capability. Serve runs such a request
|
||||||
|
// against the UI's ordinary http.Handler, so the same handler can also
|
||||||
|
// listen on a TCP port (behind a reverse proxy, see httpsec.BearerTokens).
|
||||||
|
//
|
||||||
|
// The handler learns where it is mounted from Prefix(r) -- it writes its
|
||||||
|
// links and redirects with it, as with a layout.PageHeader BasePath --
|
||||||
|
// and, over the bus, the web user yasta reports from User(r).
|
||||||
|
package busweb
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/verse/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ctxKey int
|
||||||
|
|
||||||
|
const (
|
||||||
|
keyPrefix ctxKey = iota
|
||||||
|
keyUser
|
||||||
|
keyBus
|
||||||
|
)
|
||||||
|
|
||||||
|
// Prefix is where the UI serving r is mounted ("" at the root), set by
|
||||||
|
// Serve or WithPrefix.
|
||||||
|
func Prefix(r *http.Request) string {
|
||||||
|
p, _ := r.Context().Value(keyPrefix).(string)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// User is the logged-in user of yasta's web UI for a request that came
|
||||||
|
// over the bus ("" otherwise, or when yasta's login is off). It is yasta's
|
||||||
|
// claim: trust it as far as yasta's "calls" gate for the capability (or
|
||||||
|
// require yasta's bearer token).
|
||||||
|
func User(r *http.Request) string {
|
||||||
|
u, _ := r.Context().Value(keyUser).(string)
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromBus reports whether r came over the bus (Serve).
|
||||||
|
func FromBus(r *http.Request) bool {
|
||||||
|
b, _ := r.Context().Value(keyBus).(bool)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithPrefix serves next below prefix ("" or "/..." without trailing
|
||||||
|
// slash) on a TCP listener: it strips the prefix and records it for
|
||||||
|
// Prefix. Requests outside it get 404.
|
||||||
|
func WithPrefix(next http.Handler, prefix string) http.Handler {
|
||||||
|
prefix = strings.TrimSuffix(prefix, "/")
|
||||||
|
set := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), keyPrefix, prefix)))
|
||||||
|
})
|
||||||
|
if prefix == "" {
|
||||||
|
return set
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.Handle(prefix+"/", http.StripPrefix(prefix, set))
|
||||||
|
mux.Handle(prefix, http.RedirectHandler(prefix+"/", http.StatusMovedPermanently))
|
||||||
|
return mux
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve runs req against h and returns its response. An invalid request
|
||||||
|
// gets 400. The handler sees the path below the prefix (as after
|
||||||
|
// http.StripPrefix), RequestURI as the browser sent it, Host "yapl" and
|
||||||
|
// RemoteAddr "yapl"; headers outside web.ResponseHeaders are dropped and
|
||||||
|
// a body over web.MaxResponseBody is cut (Truncated).
|
||||||
|
func Serve(ctx context.Context, h http.Handler, req web.Request) web.Response {
|
||||||
|
if err := req.Validate(); err != nil {
|
||||||
|
return text(http.StatusBadRequest, err.Error())
|
||||||
|
}
|
||||||
|
u, err := url.ParseRequestURI(req.URL)
|
||||||
|
if err != nil {
|
||||||
|
return text(http.StatusBadRequest, "bad url")
|
||||||
|
}
|
||||||
|
ctx = context.WithValue(ctx, keyPrefix, req.Prefix)
|
||||||
|
ctx = context.WithValue(ctx, keyUser, req.User)
|
||||||
|
ctx = context.WithValue(ctx, keyBus, true)
|
||||||
|
r, err := http.NewRequestWithContext(ctx, req.Method, req.URL, bytes.NewReader(req.Body))
|
||||||
|
if err != nil {
|
||||||
|
return text(http.StatusBadRequest, "bad request")
|
||||||
|
}
|
||||||
|
r.URL = u
|
||||||
|
r.RequestURI = req.Prefix + req.URL
|
||||||
|
r.Host = "yapl"
|
||||||
|
r.RemoteAddr = "yapl"
|
||||||
|
r.ContentLength = int64(len(req.Body))
|
||||||
|
for k, vs := range req.Header {
|
||||||
|
for _, v := range vs {
|
||||||
|
r.Header.Add(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rec := &recorder{header: http.Header{}}
|
||||||
|
h.ServeHTTP(rec, r)
|
||||||
|
if rec.status == 0 {
|
||||||
|
rec.status = http.StatusOK
|
||||||
|
}
|
||||||
|
resp := web.Response{Status: rec.status, Header: web.FilterHeader(rec.header, web.ResponseHeaders),
|
||||||
|
Truncated: rec.truncated}
|
||||||
|
if req.Method != http.MethodHead {
|
||||||
|
resp.Body = rec.body.Bytes()
|
||||||
|
}
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
func text(status int, msg string) web.Response {
|
||||||
|
return web.Response{Status: status, Header: map[string][]string{"Content-Type": {"text/plain; charset=utf-8"}},
|
||||||
|
Body: []byte(msg + "\n")}
|
||||||
|
}
|
||||||
|
|
||||||
|
// recorder is an http.ResponseWriter that keeps at most
|
||||||
|
// web.MaxResponseBody bytes.
|
||||||
|
type recorder struct {
|
||||||
|
header http.Header
|
||||||
|
status int
|
||||||
|
body bytes.Buffer
|
||||||
|
truncated bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recorder) Header() http.Header { return r.header }
|
||||||
|
|
||||||
|
func (r *recorder) WriteHeader(code int) {
|
||||||
|
if r.status == 0 {
|
||||||
|
r.status = code
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recorder) Write(b []byte) (int, error) {
|
||||||
|
r.WriteHeader(http.StatusOK)
|
||||||
|
room := web.MaxResponseBody - r.body.Len()
|
||||||
|
if len(b) > room {
|
||||||
|
r.body.Write(b[:max(room, 0)])
|
||||||
|
r.truncated = true
|
||||||
|
return len(b), nil
|
||||||
|
}
|
||||||
|
return r.body.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush is a no-op: the response leaves as one message.
|
||||||
|
func (r *recorder) Flush() {}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package busweb
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
layout "teruna.dev/yetano/yetano-webui-template"
|
||||||
|
"yetano.dev/yetano/verse/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
func echo() http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/plain")
|
||||||
|
w.Header().Set("Server", "secret")
|
||||||
|
w.Header().Set("Set-Cookie", "a=b")
|
||||||
|
io.WriteString(w, "prefix="+Prefix(r)+" user="+User(r)+" path="+r.URL.Path+" q="+r.URL.Query().Get("q")+" ua="+r.UserAgent())
|
||||||
|
})
|
||||||
|
mux.HandleFunc("POST /form", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Redirect(w, r, Prefix(r)+"/hello?q="+r.FormValue("v"), http.StatusSeeOther)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /big", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Write(make([]byte, web.MaxResponseBody+10))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /appearance-back", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := layout.PageHeader{BasePath: Prefix(r)}
|
||||||
|
h.ApplyAppearance(r)
|
||||||
|
io.WriteString(w, h.AppearanceBack)
|
||||||
|
})
|
||||||
|
return mux
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServe(t *testing.T) {
|
||||||
|
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/hello?q=1", Prefix: "/apps/x",
|
||||||
|
User: "alice", Header: map[string][]string{"User-Agent": {"t"}}})
|
||||||
|
if resp.Status != 200 || string(resp.Body) != "prefix=/apps/x user=alice path=/hello q=1 ua=t" {
|
||||||
|
t.Fatalf("%d %q", resp.Status, resp.Body)
|
||||||
|
}
|
||||||
|
if resp.Header["Server"] != nil || resp.Header["Set-Cookie"][0] != "a=b" {
|
||||||
|
t.Fatalf("headers %v", resp.Header)
|
||||||
|
}
|
||||||
|
if err := resp.Validate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServePostRedirect(t *testing.T) {
|
||||||
|
resp := Serve(context.Background(), echo(), web.Request{Method: "POST", URL: "/form", Prefix: "/p",
|
||||||
|
Header: map[string][]string{"Content-Type": {"application/x-www-form-urlencoded"}}, Body: []byte("v=7")})
|
||||||
|
if resp.Status != http.StatusSeeOther || resp.Header["Location"][0] != "/p/hello?q=7" {
|
||||||
|
t.Fatalf("%d %v", resp.Status, resp.Header)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServeTruncatesAndRejects(t *testing.T) {
|
||||||
|
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/big"})
|
||||||
|
if !resp.Truncated || len(resp.Body) != web.MaxResponseBody {
|
||||||
|
t.Fatalf("truncated %v len %d", resp.Truncated, len(resp.Body))
|
||||||
|
}
|
||||||
|
if resp := Serve(context.Background(), echo(), web.Request{Method: "PUT", URL: "/hello"}); resp.Status != 400 {
|
||||||
|
t.Fatalf("PUT: %d", resp.Status)
|
||||||
|
}
|
||||||
|
if resp := Serve(context.Background(), echo(), web.Request{Method: "HEAD", URL: "/hello"}); resp.Status != 405 && len(resp.Body) != 0 {
|
||||||
|
t.Fatalf("HEAD body: %q", resp.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The layout's appearance menu returns to the page below the prefix, not
|
||||||
|
// to the prefix stripped twice.
|
||||||
|
func TestServeAppearanceBack(t *testing.T) {
|
||||||
|
resp := Serve(context.Background(), echo(), web.Request{Method: "GET", URL: "/appearance-back?x=1", Prefix: "/appearance-back"})
|
||||||
|
if string(resp.Body) != "/appearance-back?x=1" {
|
||||||
|
t.Fatalf("%q", resp.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWithPrefix(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(WithPrefix(echo(), "/ui/"))
|
||||||
|
defer srv.Close()
|
||||||
|
res, err := http.Get(srv.URL + "/ui/hello?q=2")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, _ := io.ReadAll(res.Body)
|
||||||
|
res.Body.Close()
|
||||||
|
if !strings.HasPrefix(string(b), "prefix=/ui user= path=/hello q=2") {
|
||||||
|
t.Fatalf("%q", b)
|
||||||
|
}
|
||||||
|
if res, _ := http.Get(srv.URL + "/hello"); res.StatusCode != 404 {
|
||||||
|
t.Fatalf("outside prefix: %d", res.StatusCode)
|
||||||
|
}
|
||||||
|
root := httptest.NewServer(WithPrefix(echo(), ""))
|
||||||
|
defer root.Close()
|
||||||
|
res, _ = http.Get(root.URL + "/hello")
|
||||||
|
b, _ = io.ReadAll(res.Body)
|
||||||
|
res.Body.Close()
|
||||||
|
if !strings.HasPrefix(string(b), "prefix= user= path=/hello") {
|
||||||
|
t.Fatalf("root: %q", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package layout
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Values for PageHeader.FlashKind.
|
||||||
|
const (
|
||||||
|
FlashOK = "ok"
|
||||||
|
FlashError = "error"
|
||||||
|
FlashInfo = "info"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Query parameters a flash message travels in across a redirect: no
|
||||||
|
// server state, and it works behind a base path or a relay. The text
|
||||||
|
// ends up in the browser history, so it never carries a secret.
|
||||||
|
const (
|
||||||
|
FlashParam = "flash"
|
||||||
|
FlashKindParam = "flashKind"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FlashURL adds a flash message of kind (FlashOK, FlashError, FlashInfo)
|
||||||
|
// to target's query, replacing one that is already there.
|
||||||
|
func FlashURL(target, kind, msg string) string {
|
||||||
|
u, err := url.Parse(target)
|
||||||
|
if err != nil {
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
q := u.Query()
|
||||||
|
q.Set(FlashParam, msg)
|
||||||
|
q.Set(FlashKindParam, kind)
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
return u.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RedirectFlash answers a form POST with 303 See Other to target (a
|
||||||
|
// path the handler has already made local, e.g. with httpsec.SafeNext),
|
||||||
|
// carrying a flash message.
|
||||||
|
func RedirectFlash(w http.ResponseWriter, r *http.Request, target, kind, msg string) {
|
||||||
|
http.Redirect(w, r, FlashURL(target, kind, msg), http.StatusSeeOther)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyFlash fills h.Flash and h.FlashKind from r's query. An unknown
|
||||||
|
// kind is shown as an error, the way the base template renders it.
|
||||||
|
func (h *PageHeader) ApplyFlash(r *http.Request) {
|
||||||
|
q := r.URL.Query()
|
||||||
|
h.Flash = q.Get(FlashParam)
|
||||||
|
if h.Flash == "" {
|
||||||
|
h.FlashKind = ""
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch kind := q.Get(FlashKindParam); kind {
|
||||||
|
case FlashOK, FlashInfo:
|
||||||
|
h.FlashKind = kind
|
||||||
|
default:
|
||||||
|
h.FlashKind = FlashError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithoutFlash removes the flash parameters from a (relative) URL, so a
|
||||||
|
// link back to the current page -- e.g. AppearanceBack -- does not show
|
||||||
|
// the message again.
|
||||||
|
func WithoutFlash(target string) string {
|
||||||
|
u, err := url.Parse(target)
|
||||||
|
if err != nil || u.RawQuery == "" {
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
q := u.Query()
|
||||||
|
if !q.Has(FlashParam) && !q.Has(FlashKindParam) {
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
q.Del(FlashParam)
|
||||||
|
q.Del(FlashKindParam)
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
return u.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package layout
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFlashRoundTrip(t *testing.T) {
|
||||||
|
u := FlashURL("/services?x=1", FlashOK, "service a started")
|
||||||
|
var h PageHeader
|
||||||
|
h.ApplyFlash(httptest.NewRequest("GET", u, nil))
|
||||||
|
if h.Flash != "service a started" || h.FlashKind != FlashOK {
|
||||||
|
t.Fatalf("ApplyFlash(%q) = %q/%q", u, h.Flash, h.FlashKind)
|
||||||
|
}
|
||||||
|
if got := WithoutFlash(u); got != "/services?x=1" {
|
||||||
|
t.Errorf("WithoutFlash = %q", got)
|
||||||
|
}
|
||||||
|
if WithoutFlash("/a?b=c") != "/a?b=c" || WithoutFlash("/a") != "/a" {
|
||||||
|
t.Error("WithoutFlash changed a URL without flash")
|
||||||
|
}
|
||||||
|
|
||||||
|
h.ApplyFlash(httptest.NewRequest("GET", "/?flash=x&flashKind=bogus", nil))
|
||||||
|
if h.FlashKind != FlashError {
|
||||||
|
t.Errorf("unknown kind = %q", h.FlashKind)
|
||||||
|
}
|
||||||
|
h.ApplyFlash(httptest.NewRequest("GET", "/", nil))
|
||||||
|
if h.Flash != "" || h.FlashKind != "" {
|
||||||
|
t.Errorf("no flash = %q/%q", h.Flash, h.FlashKind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRedirectFlash(t *testing.T) {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
RedirectFlash(rec, httptest.NewRequest("POST", "/x", nil), "/ui/repos", FlashInfo, "nothing to do")
|
||||||
|
if rec.Code != 303 || rec.Header().Get("Location") != "/ui/repos?flash=nothing+to+do&flashKind=info" {
|
||||||
|
t.Fatalf("%d %q", rec.Code, rec.Header().Get("Location"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestApplyAppearanceDropsFlash(t *testing.T) {
|
||||||
|
h := PageHeader{BasePath: "/ui"}
|
||||||
|
h.ApplyAppearance(httptest.NewRequest("GET", "/ui/repos?flash=done&flashKind=ok&page=2", nil))
|
||||||
|
if h.AppearanceBack != "/repos?page=2" {
|
||||||
|
t.Fatalf("AppearanceBack = %q", h.AppearanceBack)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,10 @@
|
|||||||
module teruna.dev/yetano/yetano-webui-template
|
module teruna.dev/yetano/yetano-webui-template
|
||||||
|
|
||||||
go 1.26.3
|
go 1.26.3
|
||||||
|
|
||||||
|
require yetano.dev/yetano/verse v0.10.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
|
||||||
|
github.com/x448/float16 v0.8.4 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
|
||||||
|
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
|
||||||
|
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||||
|
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||||
|
yetano.dev/yetano/verse v0.10.0 h1:NP7drY+nGW7R59CtDp30k0m+lvYj18GzyQ89oZ7LBVE=
|
||||||
|
yetano.dev/yetano/verse v0.10.0/go.mod h1:TzVydtH9ljDTzhD98uufRW8V2OZECktqIcPxiaWH6p4=
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
// Package httpsec holds the HTTP hardening every Yetano/Yak/Yamase web
|
||||||
|
// UI shares: security headers, the Host gate against DNS rebinding,
|
||||||
|
// open-redirect-safe "next" targets and the cookie scope for a UI served
|
||||||
|
// under a base path. It only builds on net/http; cross-origin protection
|
||||||
|
// stays the standard library's http.CrossOriginProtection.
|
||||||
|
package httpsec
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/subtle"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultCSP allows the UI's own scripts, styles and images (plus data:
|
||||||
|
// images, e.g. the template's favicon) and nothing else: no plugins, no
|
||||||
|
// <base> rewriting, no framing, forms only to the UI itself.
|
||||||
|
const DefaultCSP = "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"
|
||||||
|
|
||||||
|
// HeaderOptions configures Headers. The zero value is the default set.
|
||||||
|
type HeaderOptions struct {
|
||||||
|
// CSP replaces DefaultCSP, e.g. for a UI that still needs inline
|
||||||
|
// scripts or a WebSocket to another origin.
|
||||||
|
CSP string
|
||||||
|
// TLS adds Strict-Transport-Security. Set it only when the UI itself
|
||||||
|
// serves HTTPS (or is only ever reached through an HTTPS proxy):
|
||||||
|
// browsers remember it for a year.
|
||||||
|
TLS bool
|
||||||
|
// CacheablePrefixes are path prefixes (as the handler sees them) whose
|
||||||
|
// responses may be cached, e.g. "/static/", "/webui-static/";
|
||||||
|
// everything else gets Cache-Control: no-store, so pages with
|
||||||
|
// session data never land in a shared or back-button cache.
|
||||||
|
CacheablePrefixes []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Headers sets the security headers on every response of next. Put it
|
||||||
|
// outermost, so even a 421 from the Host gate or a 403 from cross-origin
|
||||||
|
// protection carries them.
|
||||||
|
func Headers(next http.Handler, opts HeaderOptions) http.Handler {
|
||||||
|
csp := opts.CSP
|
||||||
|
if csp == "" {
|
||||||
|
csp = DefaultCSP
|
||||||
|
}
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := w.Header()
|
||||||
|
h.Set("Content-Security-Policy", csp)
|
||||||
|
h.Set("X-Content-Type-Options", "nosniff")
|
||||||
|
h.Set("X-Frame-Options", "DENY")
|
||||||
|
h.Set("Referrer-Policy", "same-origin")
|
||||||
|
h.Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||||
|
if opts.TLS {
|
||||||
|
h.Set("Strict-Transport-Security", "max-age=31536000")
|
||||||
|
}
|
||||||
|
cacheable := false
|
||||||
|
for _, p := range opts.CacheablePrefixes {
|
||||||
|
if strings.HasPrefix(r.URL.Path, p) {
|
||||||
|
cacheable = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !cacheable {
|
||||||
|
h.Set("Cache-Control", "no-store")
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GateActive is the family's rule for when the Host gate runs: always
|
||||||
|
// when the UI has no login (anyone who can make a browser send requests
|
||||||
|
// to it could otherwise drive it through a rebound DNS name), and also
|
||||||
|
// with a login once hosts are configured explicitly. A UI behind a
|
||||||
|
// domain with a login keeps working without extra configuration.
|
||||||
|
func GateActive(loginOn bool, allowed []string) bool {
|
||||||
|
return !loginOn || len(allowed) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostAllowed reports whether a request's Host header names this UI: an
|
||||||
|
// IP address, localhost or a *.localhost name, or one of allowed
|
||||||
|
// (compared case-insensitively, a trailing dot ignored). A port is
|
||||||
|
// ignored. An empty Host is rejected -- every browser sends one, so only
|
||||||
|
// a hand-made request lacks it.
|
||||||
|
func HostAllowed(host string, allowed []string) bool {
|
||||||
|
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||||
|
host = h
|
||||||
|
}
|
||||||
|
host = strings.TrimSuffix(strings.ToLower(strings.Trim(host, "[]")), ".")
|
||||||
|
if host == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if net.ParseIP(host) != nil || host == "localhost" || strings.HasSuffix(host, ".localhost") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, a := range allowed {
|
||||||
|
if strings.TrimSuffix(strings.ToLower(a), ".") == host {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostOf returns the host of a public URL (e.g. a configured external
|
||||||
|
// address), for adding it to the allowed list; "" if there is none.
|
||||||
|
func HostOf(publicURL string) string {
|
||||||
|
u, err := url.Parse(publicURL)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return u.Hostname()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gate answers 421 Misdirected Request for a Host HostAllowed rejects,
|
||||||
|
// naming setting (the configuration key that lists allowed hosts, e.g.
|
||||||
|
// "settings.webUI.allowedHosts") so the operator knows what to change.
|
||||||
|
func Gate(next http.Handler, allowed []string, setting string) http.Handler {
|
||||||
|
msg := "unknown host"
|
||||||
|
if setting != "" {
|
||||||
|
msg += " (see " + setting + ")"
|
||||||
|
}
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !HostAllowed(r.Host, allowed) {
|
||||||
|
http.Error(w, msg, http.StatusMisdirectedRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SafeNext returns next if it is a local target inside the UI at
|
||||||
|
// basePath ("" for a UI at the root) -- a path, optionally with query,
|
||||||
|
// that cannot leave the host: no scheme, host or user, no "//" or "/\"
|
||||||
|
// start, no backslash or control character -- and none of the
|
||||||
|
// basePath-relative paths in exclude (e.g. "/login", "/logout", so a
|
||||||
|
// login never returns to itself). Otherwise it returns basePath + "/".
|
||||||
|
func SafeNext(next, basePath string, exclude ...string) string {
|
||||||
|
fallback := basePath + "/"
|
||||||
|
if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
for _, c := range next {
|
||||||
|
if c < 0x20 || c == 0x7f || c == '\\' {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
u, err := url.Parse(next)
|
||||||
|
if err != nil || u.Scheme != "" || u.Host != "" || u.User != nil || u.Opaque != "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
rel := u.Path
|
||||||
|
if basePath != "" {
|
||||||
|
if rel != basePath && !strings.HasPrefix(rel, basePath+"/") {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
rel = strings.TrimPrefix(rel, basePath)
|
||||||
|
}
|
||||||
|
for _, x := range exclude {
|
||||||
|
if rel == x {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
|
||||||
|
// CookiePath is the Path for cookies of a UI at basePath: basePath + "/"
|
||||||
|
// ("/" at the root), so two UIs on one host keep separate sessions and
|
||||||
|
// "/app" never matches "/application". (A "__Host-" cookie needs Path
|
||||||
|
// "/" and therefore a UI at the root.)
|
||||||
|
func CookiePath(basePath string) string {
|
||||||
|
return strings.TrimSuffix(basePath, "/") + "/"
|
||||||
|
}
|
||||||
|
|
||||||
|
// SecureCookies reports whether cookies for r should carry Secure: when
|
||||||
|
// the request came over TLS, or the UI's public URL is https (it then
|
||||||
|
// sits behind a TLS-terminating proxy).
|
||||||
|
func SecureCookies(r *http.Request, publicURL string) bool {
|
||||||
|
return r.TLS != nil || strings.HasPrefix(strings.ToLower(publicURL), "https://")
|
||||||
|
}
|
||||||
|
|
||||||
|
// BearerTokens lets a request through only when it carries
|
||||||
|
// "Authorization: Bearer <token>" with one of tokens (compared in
|
||||||
|
// constant time); others get 401. It is the access control of a UI
|
||||||
|
// without user management of its own: a reverse proxy in front of it
|
||||||
|
// (or yasta, for a UI shown over the YAPL bus) sets the header. Empty
|
||||||
|
// tokens are ignored; with none left every request passes.
|
||||||
|
func BearerTokens(next http.Handler, tokens []string) http.Handler {
|
||||||
|
var keep [][]byte
|
||||||
|
for _, t := range tokens {
|
||||||
|
if t = strings.TrimSpace(t); t != "" {
|
||||||
|
keep = append(keep, []byte(t))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(keep) == 0 {
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if tokenAllowed(r.Header.Get("Authorization"), keep) {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("WWW-Authenticate", `Bearer realm="web UI"`)
|
||||||
|
http.Error(w, "missing or wrong bearer token", http.StatusUnauthorized)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func tokenAllowed(header string, tokens [][]byte) bool {
|
||||||
|
scheme, got, ok := strings.Cut(header, " ")
|
||||||
|
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
g := []byte(strings.TrimSpace(got))
|
||||||
|
match := 0
|
||||||
|
for _, t := range tokens {
|
||||||
|
match |= subtle.ConstantTimeCompare(g, t)
|
||||||
|
}
|
||||||
|
return match == 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
package httpsec
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ok = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
|
||||||
|
|
||||||
|
func TestHeaders(t *testing.T) {
|
||||||
|
h := Headers(ok, HeaderOptions{CacheablePrefixes: []string{"/static/"}})
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest("GET", "/page", nil))
|
||||||
|
for k, want := range map[string]string{
|
||||||
|
"Content-Security-Policy": DefaultCSP,
|
||||||
|
"X-Content-Type-Options": "nosniff",
|
||||||
|
"X-Frame-Options": "DENY",
|
||||||
|
"Referrer-Policy": "same-origin",
|
||||||
|
"Cross-Origin-Opener-Policy": "same-origin",
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
"Strict-Transport-Security": "",
|
||||||
|
} {
|
||||||
|
if got := rec.Header().Get(k); got != want {
|
||||||
|
t.Errorf("%s = %q, want %q", k, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest("GET", "/static/app.css", nil))
|
||||||
|
if got := rec.Header().Get("Cache-Control"); got != "" {
|
||||||
|
t.Errorf("static Cache-Control = %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
Headers(ok, HeaderOptions{CSP: "default-src 'none'", TLS: true}).ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
|
||||||
|
if rec.Header().Get("Content-Security-Policy") != "default-src 'none'" || rec.Header().Get("Strict-Transport-Security") == "" {
|
||||||
|
t.Errorf("options ignored: %v", rec.Header())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGateActive(t *testing.T) {
|
||||||
|
if !GateActive(false, nil) || GateActive(true, nil) || !GateActive(true, []string{"a.example"}) {
|
||||||
|
t.Fatal("GateActive rule")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHostAllowed(t *testing.T) {
|
||||||
|
allowed := []string{"Ops.Example.", "b.example"}
|
||||||
|
for host, want := range map[string]bool{
|
||||||
|
"": false,
|
||||||
|
":8080": false,
|
||||||
|
"127.0.0.1:8080": true,
|
||||||
|
"[::1]:8080": true,
|
||||||
|
"::1": true,
|
||||||
|
"localhost": true,
|
||||||
|
"LOCALHOST:1": true,
|
||||||
|
"app.localhost": true,
|
||||||
|
"ops.example": true,
|
||||||
|
"ops.example.:443": true,
|
||||||
|
"b.example": true,
|
||||||
|
"evil.example": false,
|
||||||
|
"localhost.evil.com": false,
|
||||||
|
} {
|
||||||
|
if got := HostAllowed(host, allowed); got != want {
|
||||||
|
t.Errorf("HostAllowed(%q) = %v, want %v", host, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGate(t *testing.T) {
|
||||||
|
g := Gate(ok, nil, "web.allowed_hosts")
|
||||||
|
for host, code := range map[string]int{"localhost": 200, "evil.example": 421, "": 421} {
|
||||||
|
r := httptest.NewRequest("GET", "/", nil)
|
||||||
|
r.Host = host
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
g.ServeHTTP(rec, r)
|
||||||
|
if rec.Code != code {
|
||||||
|
t.Errorf("Host %q: %d, want %d", host, rec.Code, code)
|
||||||
|
}
|
||||||
|
if code == 421 && rec.Body.String() != "unknown host (see web.allowed_hosts)\n" {
|
||||||
|
t.Errorf("body %q", rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHostOf(t *testing.T) {
|
||||||
|
if HostOf("https://ops.example:8443/ui") != "ops.example" || HostOf("") != "" {
|
||||||
|
t.Fatal("HostOf")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSafeNext(t *testing.T) {
|
||||||
|
for _, tc := range []struct{ next, base, want string }{
|
||||||
|
{"/services?x=1", "", "/services?x=1"},
|
||||||
|
{"", "", "/"},
|
||||||
|
{"services", "", "/"},
|
||||||
|
{"//evil.example", "", "/"},
|
||||||
|
{"/\\evil.example", "", "/"},
|
||||||
|
{"/a\\b", "", "/"},
|
||||||
|
{"/a\nb", "", "/"},
|
||||||
|
{"/a\x7f", "", "/"},
|
||||||
|
{"https://evil.example/", "", "/"},
|
||||||
|
{"/login", "", "/"},
|
||||||
|
{"/logout", "", "/"},
|
||||||
|
{"/login/help", "", "/login/help"},
|
||||||
|
{"/ui/repos", "/ui", "/ui/repos"},
|
||||||
|
{"/ui", "/ui", "/ui"},
|
||||||
|
{"/other", "/ui", "/ui/"},
|
||||||
|
{"/uix", "/ui", "/ui/"},
|
||||||
|
{"/ui/login", "/ui", "/ui/"},
|
||||||
|
} {
|
||||||
|
if got := SafeNext(tc.next, tc.base, "/login", "/logout"); got != tc.want {
|
||||||
|
t.Errorf("SafeNext(%q, %q) = %q, want %q", tc.next, tc.base, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCookiePath(t *testing.T) {
|
||||||
|
if CookiePath("") != "/" || CookiePath("/ui") != "/ui/" || CookiePath("/ui/") != "/ui/" {
|
||||||
|
t.Fatal("CookiePath")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSecureCookies(t *testing.T) {
|
||||||
|
r := httptest.NewRequest("GET", "/", nil)
|
||||||
|
if SecureCookies(r, "") || !SecureCookies(r, "HTTPS://ops.example") {
|
||||||
|
t.Fatal("public URL")
|
||||||
|
}
|
||||||
|
r.TLS = &tls.ConnectionState{}
|
||||||
|
if !SecureCookies(r, "") {
|
||||||
|
t.Fatal("TLS")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBearerTokens(t *testing.T) {
|
||||||
|
ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })
|
||||||
|
h := BearerTokens(ok, []string{" one ", "", "two"})
|
||||||
|
for auth, want := range map[string]int{
|
||||||
|
"": 401, "Bearer one": 204, "bearer two": 204, "Bearer three": 401, "Basic one": 401, "Bearer": 401, "Bearer onex": 401,
|
||||||
|
} {
|
||||||
|
r := httptest.NewRequest("GET", "/", nil)
|
||||||
|
if auth != "" {
|
||||||
|
r.Header.Set("Authorization", auth)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(w, r)
|
||||||
|
if w.Code != want {
|
||||||
|
t.Errorf("%q: %d, want %d", auth, w.Code, want)
|
||||||
|
}
|
||||||
|
if want == 401 && w.Header().Get("WWW-Authenticate") == "" {
|
||||||
|
t.Errorf("%q: no WWW-Authenticate", auth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
BearerTokens(ok, []string{" ", ""}).ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
|
||||||
|
if w.Code != 204 {
|
||||||
|
t.Errorf("no tokens: %d", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -75,6 +75,10 @@ type PageHeader struct {
|
|||||||
// the menu returns to (ApplyAppearance sets it).
|
// the menu returns to (ApplyAppearance sets it).
|
||||||
AppearancePath string
|
AppearancePath string
|
||||||
AppearanceBack string
|
AppearanceBack string
|
||||||
|
// AppearanceFormHTML is extra markup inside the menu's POST form,
|
||||||
|
// e.g. a hidden CSRF token field for a consumer whose middleware
|
||||||
|
// demands one on every POST.
|
||||||
|
AppearanceFormHTML template.HTML
|
||||||
Brand string // navbar brand text, e.g. "YASTA"
|
Brand string // navbar brand text, e.g. "YASTA"
|
||||||
BrandInitial string // single-letter favicon glyph, e.g. "y"
|
BrandInitial string // single-letter favicon glyph, e.g. "y"
|
||||||
Subtitle string
|
Subtitle string
|
||||||
@@ -82,7 +86,7 @@ type PageHeader struct {
|
|||||||
NavItems []NavItem
|
NavItems []NavItem
|
||||||
ActiveNav string
|
ActiveNav string
|
||||||
Flash string
|
Flash string
|
||||||
FlashKind string // "ok" or "error"; meaningless if Flash == ""
|
FlashKind string // FlashOK, FlashError or FlashInfo (flash.go); meaningless if Flash == ""
|
||||||
Username string
|
Username string
|
||||||
LogoutPath string // BasePath-relative, e.g. "/logout"; rendered as a POST form (never a GET link); "" hides it
|
LogoutPath string // BasePath-relative, e.g. "/logout"; rendered as a POST form (never a GET link); "" hides it
|
||||||
NavbarBeforeBrand template.HTML // extra markup rendered before the brand link, e.g. a mobile sidebar toggle
|
NavbarBeforeBrand template.HTML // extra markup rendered before the brand link, e.g. a mobile sidebar toggle
|
||||||
|
|||||||
@@ -508,6 +508,19 @@ a.navbar-subtitle:hover {
|
|||||||
border-left: 2px solid var(--yw-accent);
|
border-left: 2px solid var(--yw-accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A page without a sidebar (a login page): BodyAttrs ` class="no-sidebar"`.
|
||||||
|
The layout always renders the sidebar column; this hides it and gives
|
||||||
|
<main> the full width. !important: Bootstrap's d-md-block, column and
|
||||||
|
ms-sm-auto classes on those elements are !important or more specific. */
|
||||||
|
body.no-sidebar .sidebar {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.no-sidebar main {
|
||||||
|
width: 100% !important;
|
||||||
|
margin-left: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
/* --- Alerts (flash banners) ---------------------------------------- */
|
/* --- Alerts (flash banners) ---------------------------------------- */
|
||||||
.alert-success { background: var(--yw-success-bg); border-color: var(--yw-success-border); color: var(--yw-success-text); }
|
.alert-success { background: var(--yw-success-bg); border-color: var(--yw-success-border); color: var(--yw-success-text); }
|
||||||
.alert-danger { background: var(--yw-danger-bg); border-color: var(--yw-danger-border); color: var(--yw-danger-text); }
|
.alert-danger { background: var(--yw-danger-bg); border-color: var(--yw-danger-border); color: var(--yw-danger-text); }
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
{{template "sidebar" .}}
|
{{template "sidebar" .}}
|
||||||
</nav>
|
</nav>
|
||||||
<main class="col-md-10 col-lg-10 ms-sm-auto px-md-4 py-3">
|
<main class="col-md-10 col-lg-10 ms-sm-auto px-md-4 py-3">
|
||||||
{{if .Flash}}<div class="alert alert-{{if eq .FlashKind "ok"}}success{{else}}danger{{end}}">{{.Flash}}</div>{{end}}
|
{{if .Flash}}<div class="alert alert-{{if eq .FlashKind "ok"}}success{{else if eq .FlashKind "info"}}info{{else}}danger{{end}}">{{.Flash}}</div>{{end}}
|
||||||
{{template "content" .}}
|
{{template "content" .}}
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
{{if .AppearancePath}}{{with .AppearanceMenu}}<details class="yw-appearance">
|
{{if .AppearancePath}}{{with .AppearanceMenu}}<details class="yw-appearance">
|
||||||
<summary class="btn btn-outline-secondary btn-sm" title="{{.ThemeHeading}}: {{.Current.Label}}"><span aria-hidden="true">{{.Current.Symbol}}</span> {{.Current.Label}}</summary>
|
<summary class="btn btn-outline-secondary btn-sm" title="{{.ThemeHeading}}: {{.Current.Label}}"><span aria-hidden="true">{{.Current.Symbol}}</span> {{.Current.Label}}</summary>
|
||||||
<form method="post" action="{{$.BasePath}}{{$.AppearancePath}}" class="yw-appearance-menu m-0">
|
<form method="post" action="{{$.BasePath}}{{$.AppearancePath}}" class="yw-appearance-menu m-0">
|
||||||
<input type="hidden" name="back" value="{{$.AppearanceBack}}">
|
<input type="hidden" name="back" value="{{$.AppearanceBack}}">{{$.AppearanceFormHTML}}
|
||||||
<h6>{{.ThemeHeading}}</h6>
|
<h6>{{.ThemeHeading}}</h6>
|
||||||
{{range .Themes}}<button type="submit" name="theme" value="{{.ID}}" aria-pressed="{{.Current}}"><span aria-hidden="true">{{.Symbol}}</span> {{.Label}}</button>
|
{{range .Themes}}<button type="submit" name="theme" value="{{.ID}}" aria-pressed="{{.Current}}"><span aria-hidden="true">{{.Symbol}}</span> {{.Label}}</button>
|
||||||
{{end}}<hr>
|
{{end}}<hr>
|
||||||
|
|||||||
Reference in new issue
Block a user