2021-03-12 13:11:10 +00:00
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
2021-03-11 17:40:33 +00:00
|
|
|
package alias
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-03-12 11:16:00 +00:00
|
|
|
"encoding/base64"
|
2021-03-11 17:40:33 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2021-03-12 11:16:00 +00:00
|
|
|
"strings"
|
2021-03-11 17:40:33 +00:00
|
|
|
|
2021-03-12 12:43:52 +00:00
|
|
|
kitlog "github.com/go-kit/kit/log"
|
|
|
|
"go.cryptoscope.co/muxrpc/v2"
|
|
|
|
|
2021-03-11 17:40:33 +00:00
|
|
|
"github.com/ssb-ngi-pointer/go-ssb-room/aliases"
|
|
|
|
"github.com/ssb-ngi-pointer/go-ssb-room/internal/network"
|
|
|
|
"github.com/ssb-ngi-pointer/go-ssb-room/roomdb"
|
|
|
|
refs "go.mindeco.de/ssb-refs"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Handler struct {
|
|
|
|
logger kitlog.Logger
|
|
|
|
self refs.FeedRef
|
|
|
|
|
|
|
|
db roomdb.AliasService
|
|
|
|
}
|
|
|
|
|
2021-03-12 11:16:00 +00:00
|
|
|
const sigSuffix = ".sig.ed25519"
|
|
|
|
|
2021-03-11 17:40:33 +00:00
|
|
|
func (h Handler) Register(ctx context.Context, req *muxrpc.Request) (interface{}, error) {
|
|
|
|
|
2021-03-12 11:16:00 +00:00
|
|
|
var args []string
|
2021-03-11 17:40:33 +00:00
|
|
|
|
|
|
|
err := json.Unmarshal(req.RawArgs, &args)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("registerAlias: bad request: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if n := len(args); n != 2 {
|
|
|
|
return nil, fmt.Errorf("registerAlias: expected two arguments got %d", n)
|
|
|
|
}
|
|
|
|
|
2021-03-12 11:16:00 +00:00
|
|
|
if !strings.HasSuffix(args[1], sigSuffix) {
|
|
|
|
return nil, fmt.Errorf("registerAlias: signature does not have the expected suffix")
|
|
|
|
}
|
|
|
|
|
|
|
|
// remove the suffix of the base64 string
|
|
|
|
sig := strings.TrimSuffix(args[1], sigSuffix)
|
|
|
|
|
2021-03-11 17:40:33 +00:00
|
|
|
var confirmation aliases.Confirmation
|
|
|
|
confirmation.RoomID = h.self
|
2021-03-12 11:16:00 +00:00
|
|
|
confirmation.Alias = args[0]
|
|
|
|
confirmation.Signature, err = base64.StdEncoding.DecodeString(sig)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("registerAlias: bad signature encoding: %w", err)
|
|
|
|
}
|
|
|
|
|
2021-03-11 17:40:33 +00:00
|
|
|
// check alias is valid
|
|
|
|
// if !aliases.IsValid(confirmation.Alias) { ... }
|
|
|
|
|
|
|
|
// get the user from the muxrpc connection
|
|
|
|
userID, err := network.GetFeedRefFromAddr(req.RemoteAddr())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
confirmation.UserID = *userID
|
|
|
|
|
|
|
|
// check the signature
|
|
|
|
if !confirmation.Verify() {
|
|
|
|
return nil, fmt.Errorf("registerAlias: invalid signature")
|
|
|
|
}
|
|
|
|
|
2021-03-12 09:53:43 +00:00
|
|
|
err = h.db.Register(ctx, confirmation.Alias, confirmation.UserID, confirmation.Signature)
|
2021-03-11 17:40:33 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("registerAlias: could not register alias: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return true, nil
|
|
|
|
}
|