feature/migrate models (#16)

* feat: add new supported attestation formats to genesis

* feat: refactor keyType to keytype enum

* refactor: remove unused imports and code

* refactor: update main.go to use src package

* refactor: move web-related structs from  to

* refactor: move client middleware package to root

* refactor: remove unused IndexedDB dependency

* feat: update worker implementation to use

* feat: add Caddyfile and Caddy configuration for vault service

* refactor(config): move keyshare and address to Motr config

* fix: validate service origin in AllocateVault

* chore: remove IndexedDB configuration

* feat: add support for IPNS-based vault access
This commit is contained in:
Prad Nukala
2024-09-19 02:04:22 -04:00
committed by GitHub
parent 6d8bd8fc85
commit 96e6486c43
151 changed files with 10997 additions and 21705 deletions
-17
View File
@@ -1,17 +0,0 @@
package dwn
import (
"github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/dwn/front"
"github.com/onsonr/sonr/internal/dwn/handlers"
"github.com/onsonr/sonr/internal/dwn/middleware"
)
// NewServer creates a new dwn server using echo
func NewServer() *echo.Echo {
e := echo.New()
e.Use(middleware.UseSession)
front.RegisterViews(e)
handlers.RegisterState(e)
return e
}
@@ -1,4 +1,4 @@
package state
package handlers
import (
"encoding/json"
@@ -8,16 +8,16 @@ import (
"github.com/labstack/echo/v4"
)
func CheckSubjectIsValid(e echo.Context) error {
func checkSubjectIsValid(e echo.Context) error {
credentialID := e.FormValue("credentialID")
return e.JSON(200, credentialID)
}
func HandleCredentialAssertion(e echo.Context) error {
func handleCredentialAssertion(e echo.Context) error {
return e.JSON(200, "HandleCredentialAssertion")
}
func HandleCredentialCreation(e echo.Context) error {
func handleCredentialCreation(e echo.Context) error {
// Get the serialized credential data from the form
credentialDataJSON := e.FormValue("credentialData")
+1
View File
@@ -0,0 +1 @@
package handlers
@@ -1,22 +1,22 @@
package state
package handlers
import (
"github.com/labstack/echo/v4"
)
func GrantAuthorization(e echo.Context) error {
func grantAuthorization(e echo.Context) error {
// Implement authorization endpoint using passkey authentication
// Store session data in cache
return nil
}
func GetJWKS(e echo.Context) error {
func getJWKS(e echo.Context) error {
// Implement token endpoint
// Use cached session data for validation
return nil
}
func GetToken(e echo.Context) error {
func getToken(e echo.Context) error {
// Implement token endpoint
// Use cached session data for validation
return nil
+6 -7
View File
@@ -2,19 +2,18 @@ package handlers
import (
"github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/dwn/handlers/state"
middleware "github.com/onsonr/sonr/internal/dwn/middleware"
)
func RegisterState(e *echo.Echo) {
g := e.Group("state")
g.POST("/login/:identifier", state.HandleCredentialAssertion)
g.POST("/login/:identifier", handleCredentialAssertion)
// g.GET("/discovery", state.GetDiscovery)
g.GET("/jwks", state.GetJWKS)
g.GET("/token", state.GetToken)
g.POST("/:origin/grant/:subject", state.GrantAuthorization)
g.POST("/register/:subject", state.HandleCredentialCreation)
g.POST("/register/:subject/check", state.CheckSubjectIsValid)
g.GET("/jwks", getJWKS)
g.GET("/token", getToken)
g.POST("/:origin/grant/:subject", grantAuthorization)
g.POST("/register/:subject", handleCredentialCreation)
g.POST("/register/:subject/check", checkSubjectIsValid)
}
func RegisterSync(e *echo.Echo) {
-1
View File
@@ -1 +0,0 @@
package sync
-1
View File
@@ -1 +0,0 @@
package sync
+1
View File
@@ -0,0 +1 @@
package handlers
@@ -6,10 +6,11 @@ package middleware
import (
"github.com/donseba/go-htmx"
"github.com/labstack/echo/v4"
"github.com/onsonr/sonr/config/dwn"
"github.com/onsonr/sonr/internal/dwn/middleware/jsexc"
)
type Browser struct {
type Client struct {
echo.Context
isMobile bool
userAgent string
@@ -23,13 +24,12 @@ type Browser struct {
// WebAPIs
indexedDB jsexc.IndexedDBAPI
localStorage jsexc.LocalStorageAPI
push jsexc.PushAPI
sessionStorage jsexc.SessionStorageAPI
}
func UseNavigator(next echo.HandlerFunc) echo.HandlerFunc {
func UseNavigator(next echo.HandlerFunc, cnfg *dwn.Config) echo.HandlerFunc {
return func(c echo.Context) error {
cc := jsexc.NewNavigator(c)
cc := jsexc.NewNavigator(c, cnfg)
return next(cc)
}
}
@@ -1,4 +1,4 @@
package client
package middleware
type RequestHeaders struct {
Authorization *string `header:"Authorization"`
+2 -1
View File
@@ -8,6 +8,7 @@ import (
"syscall/js"
"github.com/labstack/echo/v4"
"github.com/onsonr/sonr/config/dwn"
)
type Navigator struct {
@@ -16,7 +17,7 @@ type Navigator struct {
hasCredentials bool
}
func NewNavigator(c echo.Context) *Navigator {
func NewNavigator(c echo.Context, cnfg *dwn.Config) *Navigator {
navigator := js.Global().Get("navigator")
credentials := navigator.Get("credentials")
hasCredentials := !credentials.IsUndefined()
@@ -1,6 +0,0 @@
//go:build js && wasm
// +build js,wasm
package jsexc
type PushAPI interface{}
-37
View File
@@ -1,37 +0,0 @@
//go:build js && wasm
package jsexc
import (
"bytes"
"net/http"
"net/http/httptest"
"syscall/js"
promise "github.com/nlepage/go-js-promise"
)
// Request builds and returns the equivalent http.Request
func Request(r js.Value) *http.Request {
jsBody := js.Global().Get("Uint8Array").New(promise.Await(r.Call("arrayBuffer")))
body := make([]byte, jsBody.Get("length").Int())
js.CopyBytesToGo(body, jsBody)
req := httptest.NewRequest(
r.Get("method").String(),
r.Get("url").String(),
bytes.NewBuffer(body),
)
headersIt := r.Get("headers").Call("entries")
for {
e := headersIt.Call("next")
if e.Get("done").Bool() {
break
}
v := e.Get("value")
req.Header.Set(v.Index(0).String(), v.Index(1).String())
}
return req
}
-50
View File
@@ -1,50 +0,0 @@
//go:build js && wasm
package jsexc
import (
"io"
"net/http/httptest"
"syscall/js"
)
// ResponseRecorder uses httptest.ResponseRecorder to build a JS Response
type ResponseRecorder struct {
*httptest.ResponseRecorder
}
// NewResponseRecorder returns a new ResponseRecorder
func NewResponseRecorder() ResponseRecorder {
return ResponseRecorder{httptest.NewRecorder()}
}
// JSResponse builds and returns the equivalent JS Response
func (rr ResponseRecorder) JSResponse() js.Value {
res := rr.Result()
body := js.Undefined()
if res.ContentLength != 0 {
b, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
body = js.Global().Get("Uint8Array").New(len(b))
js.CopyBytesToJS(body, b)
}
init := make(map[string]interface{}, 2)
if res.StatusCode != 0 {
init["status"] = res.StatusCode
}
if len(res.Header) != 0 {
headers := make(map[string]interface{}, len(res.Header))
for k := range res.Header {
headers[k] = res.Header.Get(k)
}
init["headers"] = headers
}
return js.Global().Get("Response").New(body, init)
}
-59
View File
@@ -1,59 +0,0 @@
//go:build js && wasm
package jsexc
import (
"fmt"
"net/http"
"strings"
"syscall/js"
promise "github.com/nlepage/go-js-promise"
)
// Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil.
func Serve(handler http.Handler) func() {
h := handler
if h == nil {
h = http.DefaultServeMux
}
prefix := js.Global().Get("wasmhttp").Get("path").String()
for strings.HasSuffix(prefix, "/") {
prefix = strings.TrimSuffix(prefix, "/")
}
if prefix != "" {
mux := http.NewServeMux()
mux.Handle(prefix+"/", http.StripPrefix(prefix, h))
h = mux
}
cb := js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
resPromise, resolve, reject := promise.New()
go func() {
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
reject(fmt.Sprintf("wasmhttp: panic: %+v\n", err))
} else {
reject(fmt.Sprintf("wasmhttp: panic: %v\n", r))
}
}
}()
res := NewResponseRecorder()
h.ServeHTTP(res, Request(args[0]))
resolve(res.JSResponse())
}()
return resPromise
})
js.Global().Get("wasmhttp").Call("setHandler", cb)
return cb.Release
}
+128
View File
@@ -0,0 +1,128 @@
//go:build js && wasm
package jsexc
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"syscall/js"
promise "github.com/nlepage/go-js-promise"
)
// Serve serves HTTP requests using handler or http.DefaultServeMux if handler is nil.
func Serve(handler http.Handler) func() {
h := handler
if h == nil {
h = http.DefaultServeMux
}
prefix := js.Global().Get("wasmhttp").Get("path").String()
for strings.HasSuffix(prefix, "/") {
prefix = strings.TrimSuffix(prefix, "/")
}
if prefix != "" {
mux := http.NewServeMux()
mux.Handle(prefix+"/", http.StripPrefix(prefix, h))
h = mux
}
cb := js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
resPromise, resolve, reject := promise.New()
go func() {
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
reject(fmt.Sprintf("wasmhttp: panic: %+v\n", err))
} else {
reject(fmt.Sprintf("wasmhttp: panic: %v\n", r))
}
}
}()
res := NewResponseRecorder()
h.ServeHTTP(res, Request(args[0]))
resolve(res.JSResponse())
}()
return resPromise
})
js.Global().Get("wasmhttp").Call("setHandler", cb)
return cb.Release
}
// Request builds and returns the equivalent http.Request
func Request(r js.Value) *http.Request {
jsBody := js.Global().Get("Uint8Array").New(promise.Await(r.Call("arrayBuffer")))
body := make([]byte, jsBody.Get("length").Int())
js.CopyBytesToGo(body, jsBody)
req := httptest.NewRequest(
r.Get("method").String(),
r.Get("url").String(),
bytes.NewBuffer(body),
)
headersIt := r.Get("headers").Call("entries")
for {
e := headersIt.Call("next")
if e.Get("done").Bool() {
break
}
v := e.Get("value")
req.Header.Set(v.Index(0).String(), v.Index(1).String())
}
return req
}
// ResponseRecorder uses httptest.ResponseRecorder to build a JS Response
type ResponseRecorder struct {
*httptest.ResponseRecorder
}
// NewResponseRecorder returns a new ResponseRecorder
func NewResponseRecorder() ResponseRecorder {
return ResponseRecorder{httptest.NewRecorder()}
}
// JSResponse builds and returns the equivalent JS Response
func (rr ResponseRecorder) JSResponse() js.Value {
res := rr.Result()
body := js.Undefined()
if res.ContentLength != 0 {
b, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
body = js.Global().Get("Uint8Array").New(len(b))
js.CopyBytesToJS(body, b)
}
init := make(map[string]interface{}, 2)
if res.StatusCode != 0 {
init["status"] = res.StatusCode
}
if len(res.Header) != 0 {
headers := make(map[string]interface{}, len(res.Header))
for k := range res.Header {
headers[k] = res.Header.Get(k)
}
init["headers"] = headers
}
return js.Global().Get("Response").New(body, init)
}
@@ -4,20 +4,19 @@ import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/onsonr/sonr/internal/dwn/middleware/client"
"gopkg.in/macaroon.v2"
)
// GetSession returns the current Session
func GetSession(c echo.Context) *client.Session {
return c.(*client.Session)
func GetSession(c echo.Context) *Session {
return c.(*Session)
}
// UseSession establishes a Session Cookie.
func UseSession(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sc := client.NewSession(c)
headers := new(client.RequestHeaders)
sc := initSession(c)
headers := new(RequestHeaders)
sc.Bind(headers)
return next(sc)
}
@@ -46,7 +45,7 @@ func MacaroonMiddleware(secretKeyStr string, location string) echo.MiddlewareFun
// Verify the macaroon
err = token.Verify(secretKey, func(caveat string) error {
for _, c := range client.MacroonCaveats {
for _, c := range MacroonCaveats {
if c.String() == caveat {
return nil
}
@@ -1,4 +1,4 @@
package client
package middleware
import (
"net/http"
@@ -22,7 +22,7 @@ func (c *Session) ID() string {
return ReadCookie(c, "session")
}
func NewSession(c echo.Context) *Session {
func initSession(c echo.Context) *Session {
s := &Session{Context: c}
if val := ReadCookie(c, "session"); val == "" {
id := ksuid.New().String()
@@ -1,4 +1,4 @@
package client
package middleware
import (
"fmt"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
type Account struct {
Id string `pkl:"id" json:"id,omitempty" query:"id"`
@@ -1,5 +1,5 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
type Asset struct {
Id string `pkl:"id" json:"id,omitempty" query:"id"`
@@ -1,5 +1,5 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
type Chain struct {
Id string `pkl:"id" json:"id,omitempty" query:"id"`
@@ -1,5 +1,5 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
type Credential struct {
Id string `pkl:"id" json:"id,omitempty" query:"id"`
@@ -12,6 +12,10 @@ type Credential struct {
Origin string `pkl:"origin" json:"origin,omitempty"`
Label *string `pkl:"label" json:"label,omitempty"`
DeviceId *string `pkl:"deviceId" json:"deviceId,omitempty"`
CredentialId string `pkl:"credentialId" json:"credentialId,omitempty"`
PublicKey string `pkl:"publicKey" json:"publicKey,omitempty"`
@@ -1,5 +1,5 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
type Grant struct {
Id uint `pkl:"id" json:"id,omitempty" query:"id"`
+16
View File
@@ -0,0 +1,16 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
type JWK struct {
Kty string `pkl:"kty" json:"kty,omitempty"`
Crv string `pkl:"crv" json:"crv,omitempty"`
X string `pkl:"x" json:"x,omitempty"`
Y string `pkl:"y" json:"y,omitempty"`
N string `pkl:"n" json:"n,omitempty"`
E string `pkl:"e" json:"e,omitempty"`
}
@@ -1,5 +1,5 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
type Keyshare struct {
Id string `pkl:"id" json:"id,omitempty" query:"id"`
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
import (
"context"
@@ -7,11 +7,14 @@ import (
"github.com/apple/pkl-go/pkl"
)
type Txns struct {
type Orm struct {
DbName string `pkl:"db_name"`
DbVersion int `pkl:"db_version"`
}
// LoadFromPath loads the pkl module at the given path and evaluates it into a Txns
func LoadFromPath(ctx context.Context, path string) (ret *Txns, err error) {
// LoadFromPath loads the pkl module at the given path and evaluates it into a Orm
func LoadFromPath(ctx context.Context, path string) (ret *Orm, err error) {
evaluator, err := pkl.NewEvaluator(ctx, pkl.PreconfiguredOptions)
if err != nil {
return nil, err
@@ -26,9 +29,9 @@ func LoadFromPath(ctx context.Context, path string) (ret *Txns, err error) {
return ret, err
}
// Load loads the pkl module at the given source and evaluates it with the given evaluator into a Txns
func Load(ctx context.Context, evaluator pkl.Evaluator, source *pkl.ModuleSource) (*Txns, error) {
var ret Txns
// Load loads the pkl module at the given source and evaluates it with the given evaluator into a Orm
func Load(ctx context.Context, evaluator pkl.Evaluator, source *pkl.ModuleSource) (*Orm, error) {
var ret Orm
if err := evaluator.EvaluateModule(ctx, source, &ret); err != nil {
return nil, err
}
@@ -1,5 +1,5 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
type Profile struct {
Id string `pkl:"id" json:"id,omitempty" query:"id"`
+26
View File
@@ -0,0 +1,26 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
import (
"github.com/onsonr/sonr/internal/orm/keyalgorithm"
"github.com/onsonr/sonr/internal/orm/keycurve"
"github.com/onsonr/sonr/internal/orm/keyencoding"
"github.com/onsonr/sonr/internal/orm/keyrole"
"github.com/onsonr/sonr/internal/orm/keytype"
)
type PublicKey struct {
Role keyrole.KeyRole `pkl:"role" json:"role,omitempty" query:"role"`
Algorithm keyalgorithm.KeyAlgorithm `pkl:"algorithm"`
Encoding keyencoding.KeyEncoding `pkl:"encoding"`
Curve keycurve.KeyCurve `pkl:"curve"`
KeyType keytype.KeyType `pkl:"key_type"`
Raw string `pkl:"raw"`
Jwk *JWK `pkl:"jwk"`
}
+46
View File
@@ -0,0 +1,46 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package assettype
import (
"encoding"
"fmt"
)
type AssetType string
const (
Native AssetType = "native"
Wrapped AssetType = "wrapped"
Staking AssetType = "staking"
Pool AssetType = "pool"
Ibc AssetType = "ibc"
Cw20 AssetType = "cw20"
)
// String returns the string representation of AssetType
func (rcv AssetType) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(AssetType)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for AssetType.
func (rcv *AssetType) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "native":
*rcv = Native
case "wrapped":
*rcv = Wrapped
case "staking":
*rcv = Staking
case "pool":
*rcv = Pool
case "ibc":
*rcv = Ibc
case "cw20":
*rcv = Cw20
default:
return fmt.Errorf(`illegal: "%s" is not a valid AssetType`, str)
}
return nil
}
+116
View File
@@ -0,0 +1,116 @@
package orm
import (
"crypto/hmac"
"crypto/sha512"
"encoding/binary"
"encoding/hex"
"errors"
"math/big"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/onsonr/sonr/internal/orm/didmethod"
)
type ChainCode uint32
func GetChainCode(m didmethod.DIDMethod) ChainCode {
switch m {
case didmethod.Bitcoin:
return 0 // 0
case didmethod.Ethereum:
return 64 // 60
case didmethod.Ibc:
return 118 // 118
case didmethod.Sonr:
return 703 // 703
default:
return 0
}
}
func FormatAddress(pubKey *PublicKey, m didmethod.DIDMethod) (string, error) {
hexPubKey, err := hex.DecodeString(pubKey.Raw)
if err != nil {
return "", err
}
// switch m {
// case didmethod.Bitcoin:
// return bech32.Encode("bc", pubKey.Bytes())
//
// case didmethod.Ethereum:
// epk, err := pubKey.ECDSA()
// if err != nil {
// return "", err
// }
// return ComputeEthAddress(*epk), nil
//
// case didmethod.Sonr:
// return bech32.Encode("idx", hexPubKey)
//
// case didmethod.Ibc:
// return bech32.Encode("cosmos", hexPubKey)
//
// }
return string(hexPubKey), nil
}
// ComputeAccountPublicKey computes the public key of a child key given the extended public key, chain code, and index.
func ComputeBip32AccountPublicKey(extPubKey PublicKey, chainCode ChainCode, index int) (*PublicKey, error) {
// Check if the index is a hardened child key
if chainCode&0x80000000 != 0 && index < 0 {
return nil, errors.New("invalid index")
}
hexPubKey, err := hex.DecodeString(extPubKey.Raw)
if err != nil {
return nil, err
}
// Serialize the public key
pubKey, err := btcec.ParsePubKey(hexPubKey)
if err != nil {
return nil, err
}
pubKeyBytes := pubKey.SerializeCompressed()
// Serialize the index
indexBytes := make([]byte, 4)
binary.BigEndian.PutUint32(indexBytes, uint32(index))
// Compute the HMAC-SHA512
mac := hmac.New(sha512.New, []byte{byte(chainCode)})
mac.Write(pubKeyBytes)
mac.Write(indexBytes)
I := mac.Sum(nil)
// Split I into two 32-byte sequences
IL := I[:32]
// Convert IL to a big integer
ilNum := new(big.Int).SetBytes(IL)
// Check if parse256(IL) >= n
curve := btcec.S256()
if ilNum.Cmp(curve.N) >= 0 {
return nil, errors.New("invalid child key")
}
// Compute the child public key
ilx, ily := curve.ScalarBaseMult(IL)
childX, childY := curve.Add(ilx, ily, pubKey.X(), pubKey.Y())
lx := newBigIntFieldVal(childX)
ly := newBigIntFieldVal(childY)
// Create the child public key
_ = btcec.NewPublicKey(lx, ly)
return &PublicKey{}, nil
}
// newBigIntFieldVal creates a new field value from a big integer.
func newBigIntFieldVal(val *big.Int) *btcec.FieldVal {
lx := new(btcec.FieldVal)
lx.SetByteSlice(val.Bytes())
return lx
}
@@ -0,0 +1,10 @@
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
type AuthenticatorSelectionCriteria struct {
AuthenticatorAttachment string `pkl:"authenticatorAttachment"`
RequireResidentKey bool `pkl:"requireResidentKey"`
UserVerification string `pkl:"userVerification"`
}
@@ -1,5 +1,5 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
import (
"context"
@@ -7,11 +7,11 @@ import (
"github.com/apple/pkl-go/pkl"
)
type Models struct {
type Browser struct {
}
// LoadFromPath loads the pkl module at the given path and evaluates it into a Models
func LoadFromPath(ctx context.Context, path string) (ret *Models, err error) {
// LoadFromPath loads the pkl module at the given path and evaluates it into a Browser
func LoadFromPath(ctx context.Context, path string) (ret *Browser, err error) {
evaluator, err := pkl.NewEvaluator(ctx, pkl.PreconfiguredOptions)
if err != nil {
return nil, err
@@ -26,9 +26,9 @@ func LoadFromPath(ctx context.Context, path string) (ret *Models, err error) {
return ret, err
}
// Load loads the pkl module at the given source and evaluates it with the given evaluator into a Models
func Load(ctx context.Context, evaluator pkl.Evaluator, source *pkl.ModuleSource) (*Models, error) {
var ret Models
// Load loads the pkl module at the given source and evaluates it with the given evaluator into a Browser
func Load(ctx context.Context, evaluator pkl.Evaluator, source *pkl.ModuleSource) (*Browser, error) {
var ret Browser
if err := evaluator.EvaluateModule(ctx, source, &ret); err != nil {
return nil, err
}
@@ -0,0 +1,22 @@
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
type PublicKeyCredentialCreationOptions struct {
Rp *RpEntity `pkl:"rp"`
User *UserEntity `pkl:"user"`
Challenge string `pkl:"challenge"`
PubKeyCredParams []*PublicKeyCredentialParameters `pkl:"pubKeyCredParams"`
Timeout int `pkl:"timeout"`
ExcludeCredentials []*PublicKeyCredentialDescriptor `pkl:"excludeCredentials"`
AuthenticatorSelection *AuthenticatorSelectionCriteria `pkl:"authenticatorSelection"`
Attestation string `pkl:"attestation"`
Extensions []*PublicKeyCredentialParameters `pkl:"extensions"`
}
@@ -0,0 +1,10 @@
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
type PublicKeyCredentialDescriptor struct {
Id string `pkl:"id"`
Transports []string `pkl:"transports"`
Type string `pkl:"type"`
}
@@ -0,0 +1,8 @@
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
type PublicKeyCredentialParameters struct {
Type string `pkl:"type"`
Alg *int `pkl:"alg"`
}
@@ -0,0 +1,16 @@
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
type PublicKeyCredentialRequestOptions struct {
Challenge string `pkl:"challenge"`
Timeout int `pkl:"timeout"`
RpId string `pkl:"rpId"`
AllowCredentials []*PublicKeyCredentialDescriptor `pkl:"allowCredentials"`
UserVerification string `pkl:"userVerification"`
Extensions []*PublicKeyCredentialParameters `pkl:"extensions"`
}
+10
View File
@@ -0,0 +1,10 @@
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
type RpEntity struct {
Id string `pkl:"id"`
Name *string `pkl:"name"`
Icon *string `pkl:"icon"`
}
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
type SWT struct {
Origin string `pkl:"origin"`
+10
View File
@@ -0,0 +1,10 @@
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
type UserEntity struct {
Id string `pkl:"id"`
DisplayName *string `pkl:"displayName"`
Name *string `pkl:"name"`
}
+16
View File
@@ -0,0 +1,16 @@
// Code generated from Pkl module `browser`. DO NOT EDIT.
package browser
import "github.com/apple/pkl-go/pkl"
func init() {
pkl.RegisterMapping("browser", Browser{})
pkl.RegisterMapping("browser#PublicKeyCredentialRequestOptions", PublicKeyCredentialRequestOptions{})
pkl.RegisterMapping("browser#PublicKeyCredentialDescriptor", PublicKeyCredentialDescriptor{})
pkl.RegisterMapping("browser#PublicKeyCredentialParameters", PublicKeyCredentialParameters{})
pkl.RegisterMapping("browser#AuthenticatorSelectionCriteria", AuthenticatorSelectionCriteria{})
pkl.RegisterMapping("browser#PublicKeyCredentialCreationOptions", PublicKeyCredentialCreationOptions{})
pkl.RegisterMapping("browser#RpEntity", RpEntity{})
pkl.RegisterMapping("browser#UserEntity", UserEntity{})
pkl.RegisterMapping("browser#SWT", SWT{})
}
+334
View File
@@ -0,0 +1,334 @@
package orm
import (
"github.com/onsonr/sonr/x/did/types"
)
type (
AuthenticatorAttachment string
AuthenticatorTransport string
)
const (
// Platform represents a platform authenticator is attached using a client device-specific transport, called
// platform attachment, and is usually not removable from the client device. A public key credential bound to a
// platform authenticator is called a platform credential.
Platform AuthenticatorAttachment = "platform"
// CrossPlatform represents a roaming authenticator is attached using cross-platform transports, called
// cross-platform attachment. Authenticators of this class are removable from, and can "roam" among, client devices.
// A public key credential bound to a roaming authenticator is called a roaming credential.
CrossPlatform AuthenticatorAttachment = "cross-platform"
)
func ParseAuthenticatorAttachment(s string) AuthenticatorAttachment {
switch s {
case "platform":
return Platform
default:
return CrossPlatform
}
}
const (
// USB indicates the respective authenticator can be contacted over removable USB.
USB AuthenticatorTransport = "usb"
// NFC indicates the respective authenticator can be contacted over Near Field Communication (NFC).
NFC AuthenticatorTransport = "nfc"
// BLE indicates the respective authenticator can be contacted over Bluetooth Smart (Bluetooth Low Energy / BLE).
BLE AuthenticatorTransport = "ble"
// SmartCard indicates the respective authenticator can be contacted over ISO/IEC 7816 smart card with contacts.
//
// WebAuthn Level 3.
SmartCard AuthenticatorTransport = "smart-card"
// Hybrid indicates the respective authenticator can be contacted using a combination of (often separate)
// data-transport and proximity mechanisms. This supports, for example, authentication on a desktop computer using
// a smartphone.
//
// WebAuthn Level 3.
Hybrid AuthenticatorTransport = "hybrid"
// Internal indicates the respective authenticator is contacted using a client device-specific transport, i.e., it
// is a platform authenticator. These authenticators are not removable from the client device.
Internal AuthenticatorTransport = "internal"
)
func ParseAuthenticatorTransport(s string) AuthenticatorTransport {
switch s {
case "usb":
return USB
case "nfc":
return NFC
case "ble":
return BLE
case "smart-card":
return SmartCard
case "hybrid":
return Hybrid
default:
return Internal
}
}
type AuthenticatorFlags byte
const (
// FlagUserPresent Bit 00000001 in the byte sequence. Tells us if user is present. Also referred to as the UP flag.
FlagUserPresent AuthenticatorFlags = 1 << iota // Referred to as UP
// FlagRFU1 is a reserved for future use flag.
FlagRFU1
// FlagUserVerified Bit 00000100 in the byte sequence. Tells us if user is verified
// by the authenticator using a biometric or PIN. Also referred to as the UV flag.
FlagUserVerified
// FlagBackupEligible Bit 00001000 in the byte sequence. Tells us if a backup is eligible for device. Also referred
// to as the BE flag.
FlagBackupEligible // Referred to as BE
// FlagBackupState Bit 00010000 in the byte sequence. Tells us if a backup state for device. Also referred to as the
// BS flag.
FlagBackupState
// FlagRFU2 is a reserved for future use flag.
FlagRFU2
// FlagAttestedCredentialData Bit 01000000 in the byte sequence. Indicates whether
// the authenticator added attested credential data. Also referred to as the AT flag.
FlagAttestedCredentialData
// FlagHasExtensions Bit 10000000 in the byte sequence. Indicates if the authenticator data has extensions. Also
// referred to as the ED flag.
FlagHasExtensions
)
type AttestationFormat string
const (
// AttestationFormatPacked is the "packed" attestation statement format is a WebAuthn-optimized format for
// attestation. It uses a very compact but still extensible encoding method. This format is implementable by
// authenticators with limited resources (e.g., secure elements).
AttestationFormatPacked AttestationFormat = "packed"
// AttestationFormatTPM is the TPM attestation statement format returns an attestation statement in the same format
// as the packed attestation statement format, although the rawData and signature fields are computed differently.
AttestationFormatTPM AttestationFormat = "tpm"
// AttestationFormatAndroidKey is the attestation statement format for platform authenticators on versions "N", and
// later, which may provide this proprietary "hardware attestation" statement.
AttestationFormatAndroidKey AttestationFormat = "android-key"
// AttestationFormatAndroidSafetyNet is the attestation statement format that Android-based platform authenticators
// MAY produce an attestation statement based on the Android SafetyNet API.
AttestationFormatAndroidSafetyNet AttestationFormat = "android-safetynet"
// AttestationFormatFIDOUniversalSecondFactor is the attestation statement format that is used with FIDO U2F
// authenticators.
AttestationFormatFIDOUniversalSecondFactor AttestationFormat = "fido-u2f"
// AttestationFormatApple is the attestation statement format that is used with Apple devices' platform
// authenticators.
AttestationFormatApple AttestationFormat = "apple"
// AttestationFormatNone is the attestation statement format that is used to replace any authenticator-provided
// attestation statement when a WebAuthn Relying Party indicates it does not wish to receive attestation information.
AttestationFormatNone AttestationFormat = "none"
)
func ExtractAttestationFormats(p *types.Params) []AttestationFormat {
var formats []AttestationFormat
for _, v := range p.AttestationFormats {
formats = append(formats, parseAttestationFormat(v))
}
return formats
}
func parseAttestationFormat(s string) AttestationFormat {
switch s {
case "packed":
return AttestationFormatPacked
case "tpm":
return AttestationFormatTPM
case "android-key":
return AttestationFormatAndroidKey
case "android-safetynet":
return AttestationFormatAndroidSafetyNet
case "fido-u2f":
return AttestationFormatFIDOUniversalSecondFactor
case "apple":
return AttestationFormatApple
case "none":
return AttestationFormatNone
default:
return AttestationFormatPacked
}
}
type CredentialType string
const (
CredentialTypePublicKeyCredential CredentialType = "public-key"
)
type ConveyancePreference string
const (
// PreferNoAttestation is a ConveyancePreference value.
//
// This value indicates that the Relying Party is not interested in authenticator attestation. For example, in order
// to potentially avoid having to obtain user consent to relay identifying information to the Relying Party, or to
// save a round trip to an Attestation CA or Anonymization CA.
//
// This is the default value.
//
// Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#dom-attestationconveyancepreference-none)
PreferNoAttestation ConveyancePreference = "none"
// PreferIndirectAttestation is a ConveyancePreference value.
//
// This value indicates that the Relying Party prefers an attestation conveyance yielding verifiable attestation
// statements, but allows the client to decide how to obtain such attestation statements. The client MAY replace the
// authenticator-generated attestation statements with attestation statements generated by an Anonymization CA, in
// order to protect the users privacy, or to assist Relying Parties with attestation verification in a
// heterogeneous ecosystem.
//
// Note: There is no guarantee that the Relying Party will obtain a verifiable attestation statement in this case.
// For example, in the case that the authenticator employs self attestation.
//
// Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#dom-attestationconveyancepreference-indirect)
PreferIndirectAttestation ConveyancePreference = "indirect"
// PreferDirectAttestation is a ConveyancePreference value.
//
// This value indicates that the Relying Party wants to receive the attestation statement as generated by the
// authenticator.
//
// Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#dom-attestationconveyancepreference-direct)
PreferDirectAttestation ConveyancePreference = "direct"
// PreferEnterpriseAttestation is a ConveyancePreference value.
//
// This value indicates that the Relying Party wants to receive an attestation statement that may include uniquely
// identifying information. This is intended for controlled deployments within an enterprise where the organization
// wishes to tie registrations to specific authenticators. User agents MUST NOT provide such an attestation unless
// the user agent or authenticator configuration permits it for the requested RP ID.
//
// If permitted, the user agent SHOULD signal to the authenticator (at invocation time) that enterprise
// attestation is requested, and convey the resulting AAGUID and attestation statement, unaltered, to the Relying
// Party.
//
// Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#dom-attestationconveyancepreference-enterprise)
PreferEnterpriseAttestation ConveyancePreference = "enterprise"
)
func ExtractConveyancePreference(p *types.Params) ConveyancePreference {
switch p.ConveyancePreference {
case "none":
return PreferNoAttestation
case "indirect":
return PreferIndirectAttestation
case "direct":
return PreferDirectAttestation
case "enterprise":
return PreferEnterpriseAttestation
default:
return PreferNoAttestation
}
}
type PublicKeyCredentialHints string
const (
// PublicKeyCredentialHintSecurityKey is a PublicKeyCredentialHint that indicates that the Relying Party believes
// that users will satisfy this request with a physical security key. For example, an enterprise Relying Party may
// set this hint if they have issued security keys to their employees and will only accept those authenticators for
// registration and authentication.
//
// For compatibility with older user agents, when this hint is used in PublicKeyCredentialCreationOptions, the
// authenticatorAttachment SHOULD be set to cross-platform.
PublicKeyCredentialHintSecurityKey PublicKeyCredentialHints = "security-key"
// PublicKeyCredentialHintClientDevice is a PublicKeyCredentialHint that indicates that the Relying Party believes
// that users will satisfy this request with a platform authenticator attached to the client device.
//
// For compatibility with older user agents, when this hint is used in PublicKeyCredentialCreationOptions, the
// authenticatorAttachment SHOULD be set to platform.
PublicKeyCredentialHintClientDevice PublicKeyCredentialHints = "client-device"
// PublicKeyCredentialHintHybrid is a PublicKeyCredentialHint that indicates that the Relying Party believes that
// users will satisfy this request with general-purpose authenticators such as smartphones. For example, a consumer
// Relying Party may believe that only a small fraction of their customers possesses dedicated security keys. This
// option also implies that the local platform authenticator should not be promoted in the UI.
//
// For compatibility with older user agents, when this hint is used in PublicKeyCredentialCreationOptions, the
// authenticatorAttachment SHOULD be set to cross-platform.
PublicKeyCredentialHintHybrid PublicKeyCredentialHints = "hybrid"
)
func ParsePublicKeyCredentialHints(s string) PublicKeyCredentialHints {
switch s {
case "security-key":
return PublicKeyCredentialHintSecurityKey
case "client-device":
return PublicKeyCredentialHintClientDevice
case "hybrid":
return PublicKeyCredentialHintHybrid
default:
return ""
}
}
type AttestedCredentialData struct {
AAGUID []byte `json:"aaguid"`
CredentialID []byte `json:"credential_id"`
// The raw credential public key bytes received from the attestation data.
CredentialPublicKey []byte `json:"public_key"`
}
type ResidentKeyRequirement string
const (
// ResidentKeyRequirementDiscouraged indicates the Relying Party prefers creating a server-side credential, but will
// accept a client-side discoverable credential. This is the default.
ResidentKeyRequirementDiscouraged ResidentKeyRequirement = "discouraged"
// ResidentKeyRequirementPreferred indicates to the client we would prefer a discoverable credential.
ResidentKeyRequirementPreferred ResidentKeyRequirement = "preferred"
// ResidentKeyRequirementRequired indicates the Relying Party requires a client-side discoverable credential, and is
// prepared to receive an error if a client-side discoverable credential cannot be created.
ResidentKeyRequirementRequired ResidentKeyRequirement = "required"
)
func ParseResidentKeyRequirement(s string) ResidentKeyRequirement {
switch s {
case "discouraged":
return ResidentKeyRequirementDiscouraged
case "preferred":
return ResidentKeyRequirementPreferred
default:
return ResidentKeyRequirementRequired
}
}
type (
AuthenticationExtensions map[string]any
UserVerificationRequirement string
)
const (
// VerificationRequired User verification is required to create/release a credential
VerificationRequired UserVerificationRequirement = "required"
// VerificationPreferred User verification is preferred to create/release a credential
VerificationPreferred UserVerificationRequirement = "preferred" // This is the default
// VerificationDiscouraged The authenticator should not verify the user for the credential
VerificationDiscouraged UserVerificationRequirement = "discouraged"
)
+56
View File
@@ -0,0 +1,56 @@
package orm
import (
"encoding/base64"
"github.com/go-webauthn/webauthn/protocol"
)
// NewCredential will return a credential pointer on successful validation of a registration response.
func NewCredential(c *protocol.ParsedCredentialCreationData, origin, handle string) *Credential {
return &Credential{
Subject: handle,
Origin: origin,
AttestationType: c.Response.AttestationObject.Format,
CredentialId: BytesToBase64(c.Response.AttestationObject.AuthData.AttData.CredentialID),
PublicKey: BytesToBase64(c.Response.AttestationObject.AuthData.AttData.CredentialPublicKey),
Transport: NormalizeTransports(c.Response.Transports),
SignCount: uint(c.Response.AttestationObject.AuthData.Counter),
UserPresent: c.Response.AttestationObject.AuthData.Flags.HasUserPresent(),
UserVerified: c.Response.AttestationObject.AuthData.Flags.HasUserVerified(),
BackupEligible: c.Response.AttestationObject.AuthData.Flags.HasBackupEligible(),
BackupState: c.Response.AttestationObject.AuthData.Flags.HasAttestedCredentialData(),
}
}
func BytesToBase64(b []byte) string {
return base64.RawURLEncoding.EncodeToString(b)
}
func Base64ToBytes(b string) ([]byte, error) {
return base64.RawURLEncoding.DecodeString(b)
}
// Descriptor converts a Credential into a protocol.CredentialDescriptor.
func (c *Credential) Descriptor() protocol.CredentialDescriptor {
id, err := base64.RawURLEncoding.DecodeString(c.CredentialId)
if err != nil {
panic(err)
}
return protocol.CredentialDescriptor{
Type: protocol.PublicKeyCredentialType,
CredentialID: id,
Transport: ConvertTransports(c.Transport),
AttestationType: c.AttestationType,
}
}
// This is a signal that the authenticator may be cloned, see CloneWarning above for more information.
func (a *Credential) UpdateCounter(authDataCount uint) {
if authDataCount <= a.SignCount && (authDataCount != 0 || a.SignCount != 0) {
a.CloneWarning = true
return
}
a.SignCount = authDataCount
}
+52
View File
@@ -0,0 +1,52 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package didmethod
import (
"encoding"
"fmt"
)
type DIDMethod string
const (
Ipfs DIDMethod = "ipfs"
Sonr DIDMethod = "sonr"
Bitcoin DIDMethod = "bitcoin"
Ethereum DIDMethod = "ethereum"
Ibc DIDMethod = "ibc"
Webauthn DIDMethod = "webauthn"
Dwn DIDMethod = "dwn"
Service DIDMethod = "service"
)
// String returns the string representation of DIDMethod
func (rcv DIDMethod) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(DIDMethod)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for DIDMethod.
func (rcv *DIDMethod) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "ipfs":
*rcv = Ipfs
case "sonr":
*rcv = Sonr
case "bitcoin":
*rcv = Bitcoin
case "ethereum":
*rcv = Ethereum
case "ibc":
*rcv = Ibc
case "webauthn":
*rcv = Webauthn
case "dwn":
*rcv = Dwn
case "service":
*rcv = Service
default:
return fmt.Errorf(`illegal: "%s" is not a valid DIDMethod`, str)
}
return nil
}
+17
View File
@@ -0,0 +1,17 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package orm
import "github.com/apple/pkl-go/pkl"
func init() {
pkl.RegisterMapping("orm", Orm{})
pkl.RegisterMapping("orm#Account", Account{})
pkl.RegisterMapping("orm#Asset", Asset{})
pkl.RegisterMapping("orm#Chain", Chain{})
pkl.RegisterMapping("orm#Credential", Credential{})
pkl.RegisterMapping("orm#JWK", JWK{})
pkl.RegisterMapping("orm#Grant", Grant{})
pkl.RegisterMapping("orm#Keyshare", Keyshare{})
pkl.RegisterMapping("orm#PublicKey", PublicKey{})
pkl.RegisterMapping("orm#Profile", Profile{})
}
+111
View File
@@ -0,0 +1,111 @@
package orm
import (
"encoding/base64"
"fmt"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/protocol/webauthncose"
)
func FormatEC2PublicKey(key *webauthncose.EC2PublicKeyData) (*JWK, error) {
curve, err := GetCOSECurveName(key.Curve)
if err != nil {
return nil, err
}
jwkMap := map[string]interface{}{
"kty": "EC",
"crv": curve,
"x": base64.RawURLEncoding.EncodeToString(key.XCoord),
"y": base64.RawURLEncoding.EncodeToString(key.YCoord),
}
return MapToJWK(jwkMap)
}
func FormatRSAPublicKey(key *webauthncose.RSAPublicKeyData) (*JWK, error) {
jwkMap := map[string]interface{}{
"kty": "RSA",
"n": base64.RawURLEncoding.EncodeToString(key.Modulus),
"e": base64.RawURLEncoding.EncodeToString(key.Exponent),
}
return MapToJWK(jwkMap)
}
func FormatOKPPublicKey(key *webauthncose.OKPPublicKeyData) (*JWK, error) {
curve, err := GetOKPCurveName(key.Curve)
if err != nil {
return nil, err
}
jwkMap := map[string]interface{}{
"kty": "OKP",
"crv": curve,
"x": base64.RawURLEncoding.EncodeToString(key.XCoord),
}
return MapToJWK(jwkMap)
}
func MapToJWK(m map[string]interface{}) (*JWK, error) {
jwk := &JWK{}
for k, v := range m {
switch k {
case "kty":
jwk.Kty = v.(string)
case "crv":
jwk.Crv = v.(string)
case "x":
jwk.X = v.(string)
case "y":
jwk.Y = v.(string)
case "n":
jwk.N = v.(string)
case "e":
jwk.E = v.(string)
}
}
return jwk, nil
}
func GetCOSECurveName(curveID int64) (string, error) {
switch curveID {
case int64(webauthncose.P256):
return "P-256", nil
case int64(webauthncose.P384):
return "P-384", nil
case int64(webauthncose.P521):
return "P-521", nil
default:
return "", fmt.Errorf("unknown curve ID: %d", curveID)
}
}
func GetOKPCurveName(curveID int64) (string, error) {
switch curveID {
case int64(webauthncose.Ed25519):
return "Ed25519", nil
default:
return "", fmt.Errorf("unknown OKP curve ID: %d", curveID)
}
}
// ConvertTransports converts the transports from strings to protocol.AuthenticatorTransport
func ConvertTransports(transports []string) []protocol.AuthenticatorTransport {
tss := make([]protocol.AuthenticatorTransport, len(transports))
for i, t := range transports {
tss[i] = protocol.AuthenticatorTransport(t)
}
return tss
}
// NormalizeTransports returns the transports as strings
func NormalizeTransports(transports []protocol.AuthenticatorTransport) []string {
tss := make([]string, len(transports))
for i, t := range transports {
tss[i] = string(t)
}
return tss
}
+22
View File
@@ -0,0 +1,22 @@
package orm
import "github.com/onsonr/sonr/internal/orm/keyalgorithm"
type COSEAlgorithmIdentifier int
func GetCoseIdentifier(alg keyalgorithm.KeyAlgorithm) COSEAlgorithmIdentifier {
switch alg {
case keyalgorithm.Es256:
return COSEAlgorithmIdentifier(-7)
case keyalgorithm.Es384:
return COSEAlgorithmIdentifier(-35)
case keyalgorithm.Es512:
return COSEAlgorithmIdentifier(-36)
case keyalgorithm.Eddsa:
return COSEAlgorithmIdentifier(-8)
case keyalgorithm.Es256k:
return COSEAlgorithmIdentifier(-10)
default:
return COSEAlgorithmIdentifier(0)
}
}
@@ -0,0 +1,46 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package keyalgorithm
import (
"encoding"
"fmt"
)
type KeyAlgorithm string
const (
Es256 KeyAlgorithm = "es256"
Es384 KeyAlgorithm = "es384"
Es512 KeyAlgorithm = "es512"
Eddsa KeyAlgorithm = "eddsa"
Es256k KeyAlgorithm = "es256k"
Ecdsa KeyAlgorithm = "ecdsa"
)
// String returns the string representation of KeyAlgorithm
func (rcv KeyAlgorithm) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(KeyAlgorithm)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for KeyAlgorithm.
func (rcv *KeyAlgorithm) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "es256":
*rcv = Es256
case "es384":
*rcv = Es384
case "es512":
*rcv = Es512
case "eddsa":
*rcv = Eddsa
case "es256k":
*rcv = Es256k
case "ecdsa":
*rcv = Ecdsa
default:
return fmt.Errorf(`illegal: "%s" is not a valid KeyAlgorithm`, str)
}
return nil
}
+58
View File
@@ -0,0 +1,58 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package keycurve
import (
"encoding"
"fmt"
)
type KeyCurve string
const (
P256 KeyCurve = "p256"
P384 KeyCurve = "p384"
P521 KeyCurve = "p521"
X25519 KeyCurve = "x25519"
X448 KeyCurve = "x448"
Ed25519 KeyCurve = "ed25519"
Ed448 KeyCurve = "ed448"
Secp256k1 KeyCurve = "secp256k1"
Bls12381 KeyCurve = "bls12381"
Keccak256 KeyCurve = "keccak256"
)
// String returns the string representation of KeyCurve
func (rcv KeyCurve) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(KeyCurve)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for KeyCurve.
func (rcv *KeyCurve) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "p256":
*rcv = P256
case "p384":
*rcv = P384
case "p521":
*rcv = P521
case "x25519":
*rcv = X25519
case "x448":
*rcv = X448
case "ed25519":
*rcv = Ed25519
case "ed448":
*rcv = Ed448
case "secp256k1":
*rcv = Secp256k1
case "bls12381":
*rcv = Bls12381
case "keccak256":
*rcv = Keccak256
default:
return fmt.Errorf(`illegal: "%s" is not a valid KeyCurve`, str)
}
return nil
}
@@ -0,0 +1,37 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package keyencoding
import (
"encoding"
"fmt"
)
type KeyEncoding string
const (
Raw KeyEncoding = "raw"
Hex KeyEncoding = "hex"
Multibase KeyEncoding = "multibase"
)
// String returns the string representation of KeyEncoding
func (rcv KeyEncoding) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(KeyEncoding)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for KeyEncoding.
func (rcv *KeyEncoding) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "raw":
*rcv = Raw
case "hex":
*rcv = Hex
case "multibase":
*rcv = Multibase
default:
return fmt.Errorf(`illegal: "%s" is not a valid KeyEncoding`, str)
}
return nil
}
+40
View File
@@ -0,0 +1,40 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package keyrole
import (
"encoding"
"fmt"
)
type KeyRole string
const (
Authentication KeyRole = "authentication"
Assertion KeyRole = "assertion"
Delegation KeyRole = "delegation"
Invocation KeyRole = "invocation"
)
// String returns the string representation of KeyRole
func (rcv KeyRole) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(KeyRole)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for KeyRole.
func (rcv *KeyRole) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "authentication":
*rcv = Authentication
case "assertion":
*rcv = Assertion
case "delegation":
*rcv = Delegation
case "invocation":
*rcv = Invocation
default:
return fmt.Errorf(`illegal: "%s" is not a valid KeyRole`, str)
}
return nil
}
@@ -0,0 +1,34 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package keysharerole
import (
"encoding"
"fmt"
)
type KeyShareRole string
const (
User KeyShareRole = "user"
Validator KeyShareRole = "validator"
)
// String returns the string representation of KeyShareRole
func (rcv KeyShareRole) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(KeyShareRole)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for KeyShareRole.
func (rcv *KeyShareRole) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "user":
*rcv = User
case "validator":
*rcv = Validator
default:
return fmt.Errorf(`illegal: "%s" is not a valid KeyShareRole`, str)
}
return nil
}
+55
View File
@@ -0,0 +1,55 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package keytype
import (
"encoding"
"fmt"
)
type KeyType string
const (
Octet KeyType = "octet"
Elliptic KeyType = "elliptic"
Rsa KeyType = "rsa"
Symmetric KeyType = "symmetric"
Hmac KeyType = "hmac"
Mpc KeyType = "mpc"
Zk KeyType = "zk"
Webauthn KeyType = "webauthn"
Bip32 KeyType = "bip32"
)
// String returns the string representation of KeyType
func (rcv KeyType) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(KeyType)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for KeyType.
func (rcv *KeyType) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "octet":
*rcv = Octet
case "elliptic":
*rcv = Elliptic
case "rsa":
*rcv = Rsa
case "symmetric":
*rcv = Symmetric
case "hmac":
*rcv = Hmac
case "mpc":
*rcv = Mpc
case "zk":
*rcv = Zk
case "webauthn":
*rcv = Webauthn
case "bip32":
*rcv = Bip32
default:
return fmt.Errorf(`illegal: "%s" is not a valid KeyType`, str)
}
return nil
}
@@ -0,0 +1,46 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package permissiongrant
import (
"encoding"
"fmt"
)
type PermissionGrant string
const (
None PermissionGrant = "none"
Read PermissionGrant = "read"
Write PermissionGrant = "write"
Verify PermissionGrant = "verify"
Broadcast PermissionGrant = "broadcast"
Admin PermissionGrant = "admin"
)
// String returns the string representation of PermissionGrant
func (rcv PermissionGrant) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(PermissionGrant)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for PermissionGrant.
func (rcv *PermissionGrant) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "none":
*rcv = None
case "read":
*rcv = Read
case "write":
*rcv = Write
case "verify":
*rcv = Verify
case "broadcast":
*rcv = Broadcast
case "admin":
*rcv = Admin
default:
return fmt.Errorf(`illegal: "%s" is not a valid PermissionGrant`, str)
}
return nil
}
@@ -0,0 +1,49 @@
// Code generated from Pkl module `orm`. DO NOT EDIT.
package permissionscope
import (
"encoding"
"fmt"
)
type PermissionScope string
const (
Profile PermissionScope = "profile"
Metadata PermissionScope = "metadata"
Permissions PermissionScope = "permissions"
Wallets PermissionScope = "wallets"
Transactions PermissionScope = "transactions"
User PermissionScope = "user"
Validator PermissionScope = "validator"
)
// String returns the string representation of PermissionScope
func (rcv PermissionScope) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(PermissionScope)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for PermissionScope.
func (rcv *PermissionScope) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "profile":
*rcv = Profile
case "metadata":
*rcv = Metadata
case "permissions":
*rcv = Permissions
case "wallets":
*rcv = Wallets
case "transactions":
*rcv = Transactions
case "user":
*rcv = User
case "validator":
*rcv = Validator
default:
return fmt.Errorf(`illegal: "%s" is not a valid PermissionScope`, str)
}
return nil
}
+26
View File
@@ -0,0 +1,26 @@
package orm
import (
"fmt"
"github.com/go-webauthn/webauthn/protocol/webauthncose"
)
// ExtractWebAuthnPublicKey parses the raw public key bytes and returns a JWK representation
func ExtractWebAuthnPublicKey(keyBytes []byte) (*JWK, error) {
key, err := webauthncose.ParsePublicKey(keyBytes)
if err != nil {
return nil, fmt.Errorf("failed to parse public key: %w", err)
}
switch k := key.(type) {
case *webauthncose.EC2PublicKeyData:
return FormatEC2PublicKey(k)
case *webauthncose.RSAPublicKeyData:
return FormatRSAPublicKey(k)
case *webauthncose.OKPPublicKeyData:
return FormatOKPPublicKey(k)
default:
return nil, fmt.Errorf("unsupported key type")
}
}
+6
View File
@@ -0,0 +1,6 @@
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
type Msg interface {
GetTypeUrl() string
}
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
type MsgGovVote interface {
Msg
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
type MsgGroupVote interface {
Msg
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
// Base class for all proposals
type Proposal struct {
@@ -0,0 +1,36 @@
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import (
"context"
"github.com/apple/pkl-go/pkl"
)
type Transactions struct {
}
// LoadFromPath loads the pkl module at the given path and evaluates it into a Transactions
func LoadFromPath(ctx context.Context, path string) (ret *Transactions, err error) {
evaluator, err := pkl.NewEvaluator(ctx, pkl.PreconfiguredOptions)
if err != nil {
return nil, err
}
defer func() {
cerr := evaluator.Close()
if err == nil {
err = cerr
}
}()
ret, err = Load(ctx, evaluator, pkl.FileSource(path))
return ret, err
}
// Load loads the pkl module at the given source and evaluates it with the given evaluator into a Transactions
func Load(ctx context.Context, evaluator pkl.Evaluator, source *pkl.ModuleSource) (*Transactions, error) {
var ret Transactions
if err := evaluator.EvaluateModule(ctx, source, &ret); err != nil {
return nil, err
}
return &ret, nil
}
@@ -1,5 +1,5 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
+27
View File
@@ -0,0 +1,27 @@
// Code generated from Pkl module `transactions`. DO NOT EDIT.
package transactions
import "github.com/apple/pkl-go/pkl"
func init() {
pkl.RegisterMapping("transactions", Transactions{})
pkl.RegisterMapping("transactions#Proposal", Proposal{})
pkl.RegisterMapping("transactions#MsgGovSubmitProposal", MsgGovSubmitProposalImpl{})
pkl.RegisterMapping("transactions#MsgGovVote", MsgGovVoteImpl{})
pkl.RegisterMapping("transactions#MsgGovDeposit", MsgGovDepositImpl{})
pkl.RegisterMapping("transactions#MsgGroupCreateGroup", MsgGroupCreateGroupImpl{})
pkl.RegisterMapping("transactions#MsgGroupSubmitProposal", MsgGroupSubmitProposalImpl{})
pkl.RegisterMapping("transactions#MsgGroupVote", MsgGroupVoteImpl{})
pkl.RegisterMapping("transactions#MsgStakingCreateValidator", MsgStakingCreateValidatorImpl{})
pkl.RegisterMapping("transactions#MsgStakingDelegate", MsgStakingDelegateImpl{})
pkl.RegisterMapping("transactions#MsgStakingUndelegate", MsgStakingUndelegateImpl{})
pkl.RegisterMapping("transactions#MsgStakingBeginRedelegate", MsgStakingBeginRedelegateImpl{})
pkl.RegisterMapping("transactions#MsgDidUpdateParams", MsgDidUpdateParamsImpl{})
pkl.RegisterMapping("transactions#MsgDidAllocateVault", MsgDidAllocateVaultImpl{})
pkl.RegisterMapping("transactions#MsgDidProveWitness", MsgDidProveWitnessImpl{})
pkl.RegisterMapping("transactions#MsgDidSyncVault", MsgDidSyncVaultImpl{})
pkl.RegisterMapping("transactions#MsgDidRegisterController", MsgDidRegisterControllerImpl{})
pkl.RegisterMapping("transactions#MsgDidAuthorize", MsgDidAuthorizeImpl{})
pkl.RegisterMapping("transactions#MsgDidRegisterService", MsgDidRegisterServiceImpl{})
pkl.RegisterMapping("transactions#TxBody", TxBody{})
}
+14 -6
View File
@@ -18,12 +18,11 @@ var indexData []byte
var swJSData []byte
// NewDWNConfigFile uses the config template to generate the dwn config file
func NewDWNConfigFile(keyshareJSON string, adddress string) (files.Node, error) {
func NewDWNConfigFile(keyshareJSON string, adddress string, chainID string) (files.Node, error) {
dwnCfg := &dwn.Config{
Keyshare: &keyshareJSON,
Address: &adddress,
Ipfs: defaultIPFSConfig(),
Sonr: defaultSonrConfig(),
Motr: createMotrConfig(keyshareJSON, adddress, "sonr.id"),
Ipfs: defaultIPFSConfig(),
Sonr: defaultSonrConfig(chainID),
}
dwnConfigData, err := json.Marshal(dwnCfg)
if err != nil {
@@ -47,6 +46,14 @@ func SWJSFile() files.Node {
return files.NewBytesFile(swJSData)
}
func createMotrConfig(keyshareJSON string, adddress string, origin string) *dwn.Motr {
return &dwn.Motr{
Keyshare: keyshareJSON,
Address: adddress,
Origin: origin,
}
}
func defaultIPFSConfig() *dwn.IPFS {
return &dwn.IPFS{
ApiUrl: "https://api.sonr-ipfs.land",
@@ -54,11 +61,12 @@ func defaultIPFSConfig() *dwn.IPFS {
}
}
func defaultSonrConfig() *dwn.Sonr {
func defaultSonrConfig(chainID string) *dwn.Sonr {
return &dwn.Sonr{
ApiUrl: "https://api.sonr.land",
GrpcUrl: "https://grpc.sonr.land",
RpcUrl: "https://rpc.sonr.land",
WebSocketUrl: "wss://rpc.sonr.land/ws",
ChainId: chainID,
}
}
-6
View File
@@ -1,6 +0,0 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
type PublicKey struct {
Id string `pkl:"id" json:"id,omitempty" query:"id"`
}
-16
View File
@@ -1,16 +0,0 @@
// Code generated from Pkl module `models`. DO NOT EDIT.
package models
import "github.com/apple/pkl-go/pkl"
func init() {
pkl.RegisterMapping("models", Models{})
pkl.RegisterMapping("models#Account", Account{})
pkl.RegisterMapping("models#Asset", Asset{})
pkl.RegisterMapping("models#Chain", Chain{})
pkl.RegisterMapping("models#Credential", Credential{})
pkl.RegisterMapping("models#Grant", Grant{})
pkl.RegisterMapping("models#Keyshare", Keyshare{})
pkl.RegisterMapping("models#PublicKey", PublicKey{})
pkl.RegisterMapping("models#Profile", Profile{})
}
-6
View File
@@ -1,6 +0,0 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
type Msg interface {
GetTypeUrl() string
}
-28
View File
@@ -1,28 +0,0 @@
// Code generated from Pkl module `txns`. DO NOT EDIT.
package txns
import "github.com/apple/pkl-go/pkl"
func init() {
pkl.RegisterMapping("txns", Txns{})
pkl.RegisterMapping("txns#Proposal", Proposal{})
pkl.RegisterMapping("txns#SWT", SWT{})
pkl.RegisterMapping("txns#MsgGovSubmitProposal", MsgGovSubmitProposalImpl{})
pkl.RegisterMapping("txns#MsgGovVote", MsgGovVoteImpl{})
pkl.RegisterMapping("txns#MsgGovDeposit", MsgGovDepositImpl{})
pkl.RegisterMapping("txns#MsgGroupCreateGroup", MsgGroupCreateGroupImpl{})
pkl.RegisterMapping("txns#MsgGroupSubmitProposal", MsgGroupSubmitProposalImpl{})
pkl.RegisterMapping("txns#MsgGroupVote", MsgGroupVoteImpl{})
pkl.RegisterMapping("txns#MsgStakingCreateValidator", MsgStakingCreateValidatorImpl{})
pkl.RegisterMapping("txns#MsgStakingDelegate", MsgStakingDelegateImpl{})
pkl.RegisterMapping("txns#MsgStakingUndelegate", MsgStakingUndelegateImpl{})
pkl.RegisterMapping("txns#MsgStakingBeginRedelegate", MsgStakingBeginRedelegateImpl{})
pkl.RegisterMapping("txns#MsgDidUpdateParams", MsgDidUpdateParamsImpl{})
pkl.RegisterMapping("txns#MsgDidAllocateVault", MsgDidAllocateVaultImpl{})
pkl.RegisterMapping("txns#MsgDidProveWitness", MsgDidProveWitnessImpl{})
pkl.RegisterMapping("txns#MsgDidSyncVault", MsgDidSyncVaultImpl{})
pkl.RegisterMapping("txns#MsgDidRegisterController", MsgDidRegisterControllerImpl{})
pkl.RegisterMapping("txns#MsgDidAuthorize", MsgDidAuthorizeImpl{})
pkl.RegisterMapping("txns#MsgDidRegisterService", MsgDidRegisterServiceImpl{})
pkl.RegisterMapping("txns#TxBody", TxBody{})
}