Files
skillshare/internal/server/handler_hub_refs.go
T
Willie 36a314442b refactor(server): decode JSON request bodies through one size-limited helper
About 57 handlers decoded request bodies with no size limit, and the few
that had one each picked their own. They now go through decodeJSON with a
1 MiB default; handlers that need more keep their larger limit. An
oversized body gets 413 instead of whatever the handler returned for bad
JSON (MCP and plugin requests used to answer 400). Every other decode
error keeps the handler's existing status and message.
2026-09-30 02:25:42 +08:00

76 lines
1.9 KiB
Go

package server
import (
"errors"
"net/http"
"skillshare/internal/install"
)
type hubRefsResponse struct {
Pinnable bool `json:"pinnable"`
Current string `json:"current"`
DefaultBranch string `json:"defaultBranch"`
Branches []string `json:"branches"`
Tags []string `json:"tags"`
Source *string `json:"source,omitempty"`
}
// handleHubRefs lists the branches and tags a hub entry's source can pin, and
// with "ref" in the body also returns the source rewritten to pin that ref.
func (s *Server) handleHubRefs(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
parseOpts := s.parseOpts()
s.mu.RUnlock()
var body struct {
Source string `json:"source"`
Ref *string `json:"ref"`
}
if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil {
if !errors.Is(err, errBodyTooLarge) {
writeError(w, http.StatusBadRequest, "invalid JSON body")
}
return
}
if body.Source == "" {
writeError(w, http.StatusBadRequest, "source is required")
return
}
source, err := install.ParseSourceWithOptions(body.Source, parseOpts)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid source: "+err.Error())
return
}
resp := hubRefsResponse{Branches: []string{}, Tags: []string{}}
if _, ok := source.PinnedRef(); !ok {
writeJSON(w, resp)
return
}
var refs install.RemoteRefs
list, err := refs.List(source)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
if err := refs.Settle(source); err != nil {
writeError(w, http.StatusBadRequest, "invalid source: "+err.Error())
return
}
resp.Pinnable = true
resp.Current, _ = source.PinnedRef()
resp.DefaultBranch = list.DefaultBranch
resp.Branches = list.Branches
resp.Tags = list.Tags
if body.Ref != nil {
pinned, err := source.AtRef(*body.Ref)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
resp.Source = &pinned
}
writeJSON(w, resp)
}