Files
yetano-webui-template/busweb/busweb.go
T
terminarandClaude Opus 5.5 7afb6a022a busweb: web UIs over the YAPL bus; httpsec.BearerTokens
busweb.Serve runs a <name>.web@N request (verse/web, D-200) against a
UI's http.Handler; Prefix/User/FromBus tell the handler where it is
mounted and who yasta says is logged in; WithPrefix serves the same
handler on a TCP port. httpsec.BearerTokens is the access control of a
UI without user management (a reverse proxy or yasta sends the token).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:27:48 +01:00

148 lines
4.4 KiB
Go

// 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() {}