// Package httpapi builds the binary's HTTP API on Huma, so every operation a // module registers is described in the OpenAPI document served beside it. package httpapi import ( "net/http" "path" "reflect" "strings" "unicode" "github.com/danielgtaylor/huma/v2" "github.com/danielgtaylor/huma/v2/adapters/humago" "github.com/samcharles93/archie-core/internal/platform/httpjson" ) // DocumentPath is where the API serves its OpenAPI document, as .json and // .yaml. const DocumentPath = "/api/openapi" // Reply is an operation's output whose response body is T. type Reply[T any] struct { Body T } // OK wraps v as an operation's response body. func OK[T any](v T) *Reply[T] { return &Reply[T]{Body: v} } // New returns an API on mux whose every operation requires the bootstrap admin // token, held only as its hash. func New(mux *http.ServeMux, version, adminHash string) huma.API { api := humago.New(mux, config(version)) api.UseMiddleware(admin(api, adminHash)) return api } func config(version string) huma.Config { cfg := huma.DefaultConfig("Archie", version) cfg.OpenAPIPath = DocumentPath cfg.DocsPath = "/api/docs" // Schema links would put a $schema member in every response body. cfg.SchemasPath = "" cfg.CreateHooks = nil cfg.Components.Schemas = huma.NewMapRegistry("#/components/schemas/", schemaName) cfg.Components.SecuritySchemes = map[string]*huma.SecurityScheme{ "admin": {Type: "http", Scheme: "bearer", Description: "The bootstrap admin token"}, } cfg.Security = []map[string][]string{{"admin": {}}} return cfg } func admin(api huma.API, hash string) func(huma.Context, func(huma.Context)) { return func(ctx huma.Context, next func(huma.Context)) { token, ok := strings.CutPrefix(ctx.Header("Authorization"), "Bearer ") if !ok || !httpjson.TokenMatches(strings.TrimSpace(token), hash) { _ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "admin token required") return } next(ctx) } } // schemaName prefixes a type of Archie's own with its package, since modules // reuse short names like Source and Request. func schemaName(t reflect.Type, hint string) string { name := huma.DefaultSchemaNamer(t, hint) for t.Kind() == reflect.Pointer { t = t.Elem() } if t.Name() == "" || !strings.HasPrefix(t.PkgPath(), "github.com/samcharles93/archie-core/") { return name } pkg := []rune(path.Base(t.PkgPath())) pkg[0] = unicode.ToUpper(pkg[0]) return string(pkg) + name }