knotserver: redirect handle-path to did-path #705

open
opened by boltless.me targeting master from push-xpolynpvotzt

fixing issue reported on discord: https://discord.com/channels/1361963801993285692/1361966362653757450/1430609124114301060

knotserver: redirect handle-path to did-path

this will allow handle based url when cloning from knot over https
usually appview will resolve this before redirecting to the knot

this implementation just redirects to resolved path instead of passing
the entire identity for performance. As we won't want to resolve same
identity twice when proxied by appview.

Signed-off-by: Seongmin Lee <git@boltless.me>
Changed files
+24
knotserver
+24
knotserver/router.go
···
"fmt"
"log/slog"
"net/http"
+
"strings"
"github.com/go-chi/chi/v5"
"tangled.org/core/idresolver"
···
})
r.Route("/{did}", func(r chi.Router) {
+
r.Use(h.resolveDidRedirect)
r.Route("/{name}", func(r chi.Router) {
// routes for git operations
r.Get("/info/refs", h.InfoRefs)
···
return xrpc.Router()
}
+
func (h *Knot) resolveDidRedirect(next http.Handler) http.Handler {
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+
didOrHandle := chi.URLParam(r, "did")
+
if strings.HasPrefix(didOrHandle, "did:") {
+
next.ServeHTTP(w, r)
+
return
+
}
+
+
trimmed := strings.TrimPrefix(didOrHandle, "@")
+
id, err := h.resolver.ResolveIdent(r.Context(), trimmed)
+
if err != nil {
+
// invalid did or handle
+
h.l.Error("failed to resolve did/handle", "handle", trimmed, "err", err)
+
http.Error(w, fmt.Sprintf("failed to resolve did/handle: %s", trimmed), http.StatusInternalServerError)
+
return
+
}
+
+
newPath := strings.Replace(r.URL.Path, "/"+didOrHandle, "/"+id.DID.String(), 1)
+
http.Redirect(w, r, newPath, http.StatusTemporaryRedirect)
+
})
+
}
+
func (h *Knot) configureOwner() error {
cfgOwner := h.c.Server.Owner