@@ -19,6 +19,8 @@ import (
1919 ipath "github.com/ipfs/boxo/coreiface/path"
2020 cid "github.com/ipfs/go-cid"
2121 logging "github.com/ipfs/go-log"
22+ "github.com/libp2p/go-libp2p/core/peer"
23+ "github.com/multiformats/go-multibase"
2224 prometheus "github.com/prometheus/client_golang/prometheus"
2325 "go.opentelemetry.io/otel/attribute"
2426 "go.opentelemetry.io/otel/trace"
@@ -204,6 +206,10 @@ func (i *handler) getOrHeadHandler(w http.ResponseWriter, r *http.Request) {
204206 return
205207 }
206208
209+ if handleIpnsB58mhToCidRedirection (w , r ) {
210+ return
211+ }
212+
207213 contentPath := ipath .New (r .URL .Path )
208214 ctx := context .WithValue (r .Context (), ContentPathKey , contentPath )
209215 r = r .WithContext (ctx )
@@ -728,6 +734,52 @@ func handleServiceWorkerRegistration(r *http.Request) (err *ErrorResponse) {
728734 return nil
729735}
730736
737+ // handleIpnsB58mhToCidRedirection redirects from /ipns/b58mh to /ipns/cid in
738+ // the most cost-effective way.
739+ func handleIpnsB58mhToCidRedirection (w http.ResponseWriter , r * http.Request ) bool {
740+ fmt .Println (w .Header ().Get ("Location" ))
741+ if w .Header ().Get ("Location" ) != "" {
742+ // Ignore this if there is already a redirection in place. This happens
743+ // if there is a subdomain redirection. In that case, the path is already
744+ // converted to CIDv1.
745+ return false
746+ }
747+
748+ pathParts := strings .Split (r .URL .Path , "/" )
749+ fmt .Println (pathParts )
750+ if len (pathParts ) < 3 {
751+ return false
752+ }
753+
754+ if pathParts [1 ] != "ipns" {
755+ return false
756+ }
757+
758+ id , err := peer .Decode (pathParts [2 ])
759+ if err != nil {
760+ return false
761+ }
762+
763+ // Convert the peer ID to a CIDv1.
764+ cid := peer .ToCid (id )
765+
766+ // Encode CID in base36 to match the subdomain URLs.
767+ encodedCID , err := cid .StringOfBase (multibase .Base36 )
768+ if err != nil {
769+ return false
770+ }
771+
772+ // If the CID was already encoded, do not redirect.
773+ if encodedCID == pathParts [2 ] {
774+ return false
775+ }
776+
777+ pathParts [2 ] = encodedCID
778+ r .URL .Path = strings .Join (pathParts , "/" )
779+ http .Redirect (w , r , r .URL .String (), http .StatusFound )
780+ return true
781+ }
782+
731783// Attempt to fix redundant /ipfs/ namespace as long as resulting
732784// 'intended' path is valid. This is in case gremlins were tickled
733785// wrong way and user ended up at /ipfs/ipfs/{cid} or /ipfs/ipns/{id}
0 commit comments