pluginsdk/route/route.go
Alex Dunmow 754a713b0e Add the route package: plugin routes declare their access
Routes under /api/plugins/<name> take Public, Visitor or Admin. Visitor and
Admin routes check the host-verified identity; a public POST goes through
Form, which requires the host-verified captcha and a per-instance submission
limit. CaptchaWidget returns the CMS widget markup for Go-rendered forms.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 05:52:55 +08:00

188 lines
5.7 KiB
Go

// Package route serves a plugin's HTTP routes under /api/plugins/<name> with
// an access level declared for every route. Admin and Visitor routes answer
// only callers the host verified; a public POST goes through Form, which
// requires the host-verified captcha and caps how many submissions a plugin
// instance accepts per minute.
package route
import (
"fmt"
"net/http"
"strings"
"sync"
"time"
"git.dev.alexdunmow.com/block/pluginsdk/auth"
)
// Access is who may call a route.
type Access int
const (
// Public routes answer anyone. Use them for data a visitor may read.
Public Access = iota + 1
// Visitor routes answer a signed-in site visitor (public user session).
Visitor
// Admin routes answer a signed-in CMS admin or superadmin.
Admin
)
func (a Access) String() string {
switch a {
case Public:
return "public"
case Visitor:
return "visitor"
case Admin:
return "admin"
}
return fmt.Sprintf("Access(%d)", int(a))
}
// Form limits: each plugin instance accepts FormBurst submissions at once and
// FormsPerMinute after that, across all of its Form routes.
const (
FormBurst = 10
FormsPerMinute = 30
MaxFormBytes = 64 << 10
)
// Router is an http.Handler for one plugin's routes.
type Router struct {
prefix string
mux *http.ServeMux
forms *limiter
routes []Route
}
// CaptchaWidget is the host's proof-of-work captcha widget. Put it inside a
// form that posts to a Form route: the visitor's browser solves it and the
// form submits a cap-token field, which the host verifies before the plugin
// sees the request. The markup matches the CMS captcha widget, served from the
// site's own origin.
func CaptchaWidget() string { return captchaWidgetHTML }
const captchaWidgetHTML = `<script>
window.CAP_CUSTOM_WASM_URL = "/assets/captcha/cap_wasm_bg.wasm";
window.CAP_PAKO_URL = "/assets/captcha/pako_inflate.min.js";
</script><cap-widget data-cap-api-endpoint="/api/captcha/" data-cap-worker-count="2"></cap-widget><script src="/assets/captcha/cap.min.js" defer></script>`
// Route is one registered route, for tests and host checks.
type Route struct {
Method string
Path string
Access Access
}
// New returns a Router for the plugin named pluginName.
func New(pluginName string) *Router {
return &Router{
prefix: "/api/plugins/" + pluginName,
mux: http.NewServeMux(),
forms: newLimiter(FormBurst, FormsPerMinute, time.Now),
}
}
// Handle serves method on path (below the plugin's address, starting with a
// slash) for callers that access allows. A Public route may only read: GET or
// HEAD. A public POST must use Form. Invalid registrations panic, like
// http.ServeMux does for conflicting patterns.
func (r *Router) Handle(method, path string, access Access, h http.HandlerFunc) {
method = strings.ToUpper(method)
if access == Public && method != http.MethodGet && method != http.MethodHead {
panic(fmt.Sprintf("route: public %s %s must use Form", method, path))
}
r.handle(method, path, access, guard(access, h))
}
// Form serves a public POST on path. The host must have verified the
// request's captcha (render the widget with the ninjatpl captcha tag so the
// form posts a cap-token); a request without it gets 403, and a request past
// the submission limit gets 429. The body is capped at MaxFormBytes.
func (r *Router) Form(path string, h http.HandlerFunc) {
r.handle(http.MethodPost, path, Public, func(w http.ResponseWriter, req *http.Request) {
if !auth.CaptchaVerified(req.Header) {
http.Error(w, "please complete the captcha", http.StatusForbidden)
return
}
if !r.forms.allow() {
http.Error(w, "too many submissions, please try again in a minute", http.StatusTooManyRequests)
return
}
req.Body = http.MaxBytesReader(w, req.Body, MaxFormBytes)
h(w, req)
})
}
// Routes lists the registered routes in registration order.
func (r *Router) Routes() []Route { return append([]Route(nil), r.routes...) }
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.mux.ServeHTTP(w, req)
}
func (r *Router) handle(method, path string, access Access, h http.HandlerFunc) {
if access < Public || access > Admin {
panic(fmt.Sprintf("route: %s %s has no access level", method, path))
}
if !strings.HasPrefix(path, "/") {
panic(fmt.Sprintf("route: path %q must start with a slash", path))
}
pattern := r.prefix + path
if path == "/" {
pattern += "{$}"
}
r.mux.HandleFunc(method+" "+pattern, h)
r.routes = append(r.routes, Route{Method: method, Path: path, Access: access})
}
func guard(access Access, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
ctx := auth.ContextFromTrustedHeaders(req.Context(), req.Header)
switch access {
case Admin:
user, ok := auth.GetUserFromContext(ctx)
if !ok {
http.Error(w, "sign in required", http.StatusUnauthorized)
return
}
if user.Role != "admin" && user.Role != "superadmin" {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
case Visitor:
if _, ok := auth.GetPublicUserFromContext(ctx); !ok {
http.Error(w, "sign in required", http.StatusUnauthorized)
return
}
}
h(w, req.WithContext(ctx))
}
}
type limiter struct {
mu sync.Mutex
tokens float64
burst float64
perSec float64
last time.Time
clockNow func() time.Time
}
func newLimiter(burst, perMinute int, now func() time.Time) *limiter {
return &limiter{tokens: float64(burst), burst: float64(burst), perSec: float64(perMinute) / 60, last: now(), clockNow: now}
}
func (l *limiter) allow() bool {
l.mu.Lock()
defer l.mu.Unlock()
now := l.clockNow()
l.tokens = min(l.burst, l.tokens+now.Sub(l.last).Seconds()*l.perSec)
l.last = now
if l.tokens < 1 {
return false
}
l.tokens--
return true
}