initial commit
This commit is contained in:
78
pkg/cache/cache.go
vendored
Normal file
78
pkg/cache/cache.go
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type Key interface {
|
||||
Key() interface{}
|
||||
}
|
||||
type Value interface {
|
||||
Stale() bool
|
||||
Value() interface{}
|
||||
}
|
||||
type item struct {
|
||||
key interface{}
|
||||
value interface{}
|
||||
expireOn time.Time
|
||||
}
|
||||
|
||||
func NewItem(key, value interface{}, expires time.Duration) *item {
|
||||
return &item{
|
||||
key: key,
|
||||
value: value,
|
||||
expireOn: time.Now().Add(expires),
|
||||
}
|
||||
}
|
||||
func (e *item) Stale() bool {
|
||||
if e == nil || e.value == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
return time.Now().After(e.expireOn)
|
||||
}
|
||||
func (s *item) Value() interface{} {
|
||||
return s.value
|
||||
}
|
||||
|
||||
type Cacher interface {
|
||||
Add(Key, Value)
|
||||
Contains(Key) bool
|
||||
Get(Key) (Value, bool)
|
||||
Remove(Key)
|
||||
}
|
||||
|
||||
// InterfaceCacher external cache interface.
|
||||
type InterfaceCacher interface {
|
||||
Add(interface{}, interface{})
|
||||
Get(interface{}) (interface{}, bool)
|
||||
Contains(interface{}) bool
|
||||
Remove(interface{})
|
||||
}
|
||||
|
||||
type cache struct {
|
||||
cache InterfaceCacher
|
||||
}
|
||||
|
||||
func New(c InterfaceCacher) Cacher {
|
||||
return &cache{cache: c}
|
||||
}
|
||||
func (c *cache) Add(key Key, value Value) {
|
||||
c.cache.Add(key.Key(), value)
|
||||
}
|
||||
func (c *cache) Get(key Key) (Value, bool) {
|
||||
if v, ok := c.cache.Get(key.Key()); ok {
|
||||
if value, ok := v.(Value); ok && !value.Stale() {
|
||||
return value, true
|
||||
}
|
||||
c.cache.Remove(key.Key())
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
func (c *cache) Contains(key Key) bool {
|
||||
_, ok := c.Get(key)
|
||||
return ok
|
||||
}
|
||||
func (c *cache) Remove(key Key) {
|
||||
c.cache.Remove(key.Key())
|
||||
}
|
||||
103
pkg/config/config.go
Normal file
103
pkg/config/config.go
Normal file
@@ -0,0 +1,103 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type cfg struct {
|
||||
sync.RWMutex
|
||||
m map[string]interface{}
|
||||
}
|
||||
|
||||
var key struct{}
|
||||
|
||||
func New() *cfg {
|
||||
return &cfg{m: make(map[string]interface{})}
|
||||
}
|
||||
|
||||
func FromContext(ctx context.Context) *cfg {
|
||||
if v, ok := ctx.Value(key).(*cfg); ok {
|
||||
return v
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *cfg) Apply(ctx context.Context) context.Context {
|
||||
if inctx := FromContext(ctx); inctx != nil {
|
||||
inctx.setAll(c.m)
|
||||
}
|
||||
|
||||
return context.WithValue(ctx, key, c)
|
||||
}
|
||||
|
||||
func (c *cfg) setAll(m map[string]interface{}) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
c.m = m
|
||||
}
|
||||
|
||||
func (c *cfg) GetString(name string) string {
|
||||
if v := c.Get(name); v != nil {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
} else {
|
||||
return fmt.Sprint(s)
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c *cfg) Set(name string, value interface{}) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
c.m[name] = value
|
||||
}
|
||||
|
||||
func (c *cfg) Get(name string) interface{} {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
|
||||
return c.m[name]
|
||||
}
|
||||
|
||||
func (c *cfg) String() string {
|
||||
if c == nil {
|
||||
return "<nil>"
|
||||
}
|
||||
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
|
||||
var b bytes.Buffer
|
||||
for k, v := range c.m {
|
||||
fmt.Fprintf(&b, "%s = %v\n", k, v)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (c *cfg) ApplyHTTP(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r = r.WithContext(c.Apply(r.Context()))
|
||||
h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
204
pkg/keyproofs/opengpg.go
Normal file
204
pkg/keyproofs/opengpg.go
Normal file
@@ -0,0 +1,204 @@
|
||||
package keyproofs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/sour-is/crypto/openpgp"
|
||||
"github.com/tv42/zbase32"
|
||||
"golang.org/x/crypto/openpgp/armor"
|
||||
)
|
||||
|
||||
func getOpenPGPkey(ctx context.Context, id string) (entity *Entity, err error) {
|
||||
if isFingerprint(id) {
|
||||
addr := "https://keys.openpgp.org/vks/v1/by-fingerprint/" + strings.ToUpper(id)
|
||||
return getEntityHTTP(ctx, addr, true)
|
||||
} else if email, err := mail.ParseAddress(id); err == nil {
|
||||
addr := getWKDPubKeyAddr(email)
|
||||
req, err := getEntityHTTP(ctx, addr, false)
|
||||
if err == nil {
|
||||
return req, err
|
||||
}
|
||||
|
||||
addr = "https://keys.openpgp.org/vks/v1/by-email/" + url.QueryEscape(id)
|
||||
return getEntityHTTP(ctx, addr, true)
|
||||
} else {
|
||||
return entity, fmt.Errorf("Parse address: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
func getEntityHTTP(ctx context.Context, url string, useArmored bool) (entity *Entity, err error) {
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return entity, err
|
||||
}
|
||||
cl := http.Client{}
|
||||
resp, err := cl.Do(req)
|
||||
log.Debug().
|
||||
Bool("useArmored", useArmored).
|
||||
Str("status", resp.Status).
|
||||
Str("url", url).
|
||||
Msg("getEntityHTTP")
|
||||
|
||||
if err != nil {
|
||||
return entity, fmt.Errorf("Requesting key: %w\nRemote URL: %v", err, url)
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return entity, fmt.Errorf("bad response from remote: %s\nRemote URL: %v", resp.Status, url)
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.Header.Get("Content-Type") == "application/pgp-keys" {
|
||||
useArmored = true
|
||||
}
|
||||
|
||||
return ReadKey(resp.Body, useArmored)
|
||||
}
|
||||
|
||||
type EntityKey string
|
||||
|
||||
func (k EntityKey) Key() interface{} {
|
||||
return k
|
||||
}
|
||||
|
||||
type Entity struct {
|
||||
Primary *mail.Address
|
||||
Emails []*mail.Address
|
||||
Fingerprint string
|
||||
Proofs []string
|
||||
ArmorText string
|
||||
}
|
||||
|
||||
func getEntity(lis openpgp.EntityList) (*Entity, error) {
|
||||
entity := &Entity{}
|
||||
var err error
|
||||
|
||||
for _, e := range lis {
|
||||
if e == nil {
|
||||
continue
|
||||
}
|
||||
if e.PrimaryKey == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
entity.Fingerprint = fmt.Sprintf("%X", e.PrimaryKey.Fingerprint)
|
||||
|
||||
for name, ident := range e.Identities {
|
||||
// Pick first identity
|
||||
if entity.Primary == nil {
|
||||
entity.Primary, err = mail.ParseAddress(name)
|
||||
if err != nil {
|
||||
return entity, err
|
||||
}
|
||||
}
|
||||
// If one is marked primary use that
|
||||
if ident.SelfSignature != nil && ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
|
||||
entity.Primary, err = mail.ParseAddress(name)
|
||||
if err != nil {
|
||||
return entity, err
|
||||
}
|
||||
|
||||
} else {
|
||||
var email *mail.Address
|
||||
if email, err = mail.ParseAddress(name); err != nil {
|
||||
return entity, err
|
||||
}
|
||||
if email.Address != entity.Primary.Address {
|
||||
entity.Emails = append(entity.Emails, email)
|
||||
}
|
||||
}
|
||||
|
||||
// If identity is self signed read notation data.
|
||||
if ident.SelfSignature != nil && ident.SelfSignature.NotationData != nil {
|
||||
// Get proofs and append to list.
|
||||
if proofs, ok := ident.SelfSignature.NotationData["proof@metacode.biz"]; ok {
|
||||
entity.Proofs = append(entity.Proofs, proofs...)
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
if entity.Primary == nil {
|
||||
entity.Primary, _ = mail.ParseAddress("nobody@nodomain.xyz")
|
||||
}
|
||||
|
||||
return entity, err
|
||||
}
|
||||
|
||||
func ReadKey(r io.Reader, useArmored bool) (e *Entity, err error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
var w io.Writer = &buf
|
||||
|
||||
e = &Entity{}
|
||||
|
||||
if !useArmored {
|
||||
var aw io.WriteCloser
|
||||
aw, err = armor.Encode(&buf, "PGP PUBLIC KEY BLOCK", nil)
|
||||
if err != nil {
|
||||
return e, fmt.Errorf("Read key: %w", err)
|
||||
}
|
||||
defer aw.Close()
|
||||
|
||||
w = aw
|
||||
}
|
||||
defer func() {
|
||||
if e != nil {
|
||||
e.ArmorText = buf.String()
|
||||
}
|
||||
}()
|
||||
|
||||
r = io.TeeReader(r, w)
|
||||
|
||||
var lis openpgp.EntityList
|
||||
|
||||
if useArmored {
|
||||
lis, err = openpgp.ReadArmoredKeyRing(r)
|
||||
} else {
|
||||
lis, err = openpgp.ReadKeyRing(r)
|
||||
}
|
||||
if err != nil {
|
||||
return e, fmt.Errorf("Read key: %w", err)
|
||||
}
|
||||
|
||||
e, err = getEntity(lis)
|
||||
if err != nil {
|
||||
return e, fmt.Errorf("Parse key: %w", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func isFingerprint(s string) bool {
|
||||
for _, r := range s {
|
||||
switch r {
|
||||
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func getWKDPubKeyAddr(email *mail.Address) string {
|
||||
parts := strings.SplitN(email.Address, "@", 2)
|
||||
|
||||
hash := sha1.Sum([]byte(parts[0]))
|
||||
lp := zbase32.EncodeToString(hash[:])
|
||||
|
||||
return fmt.Sprintf("https://%s/.well-known/openpgpkey/hu/%s", parts[1], lp)
|
||||
}
|
||||
372
pkg/keyproofs/proofs.go
Normal file
372
pkg/keyproofs/proofs.go
Normal file
@@ -0,0 +1,372 @@
|
||||
package keyproofs
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/sour-is/keyproofs/pkg/config"
|
||||
)
|
||||
|
||||
type Proof struct {
|
||||
Fingerprint string
|
||||
Icon string
|
||||
Service string
|
||||
Name string
|
||||
Verify string
|
||||
Link string
|
||||
Status ProofStatus
|
||||
|
||||
URI *url.URL
|
||||
}
|
||||
type Proofs map[string]*Proof
|
||||
|
||||
type ProofKey string
|
||||
|
||||
func (k ProofKey) Key() interface{} {
|
||||
return k
|
||||
}
|
||||
|
||||
type ProofStatus int
|
||||
|
||||
const (
|
||||
ProofChecking ProofStatus = iota
|
||||
ProofError
|
||||
ProofInvalid
|
||||
ProofVerified
|
||||
)
|
||||
|
||||
func (p ProofStatus) String() string {
|
||||
switch p {
|
||||
case ProofChecking:
|
||||
return "Checking"
|
||||
case ProofError:
|
||||
return "Error"
|
||||
case ProofInvalid:
|
||||
return "Invalid"
|
||||
case ProofVerified:
|
||||
return "Verified"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func NewProof(ctx context.Context, uri, fingerprint string) ProofResolver {
|
||||
log := log.Ctx(ctx)
|
||||
baseURL := config.FromContext(ctx).GetString("base-url")
|
||||
|
||||
p := Proof{Verify: uri, Link: uri, Fingerprint: fingerprint}
|
||||
defer log.Info().
|
||||
Interface("path", p.URI).
|
||||
Str("name", p.Name).
|
||||
Str("service", p.Service).
|
||||
Str("link", p.Link).
|
||||
Msg("Proof")
|
||||
|
||||
var err error
|
||||
|
||||
p.URI, err = url.Parse(uri)
|
||||
if err != nil {
|
||||
p.Icon = "exclamation-triangle"
|
||||
p.Service = "error"
|
||||
p.Name = err.Error()
|
||||
|
||||
return &p
|
||||
}
|
||||
|
||||
p.Service = p.URI.Scheme
|
||||
|
||||
switch p.URI.Scheme {
|
||||
case "dns":
|
||||
p.Icon = "fas fa-globe"
|
||||
p.Name = p.URI.Opaque
|
||||
p.Link = fmt.Sprintf("https://%s", p.URI.Opaque)
|
||||
p.Verify = fmt.Sprintf("%s/dns/%s", baseURL, p.URI.Opaque)
|
||||
return &httpResolve{p, p.Verify, nil}
|
||||
|
||||
case "xmpp":
|
||||
p.Icon = "fas fa-comments"
|
||||
p.Name = p.URI.Opaque
|
||||
p.Verify = fmt.Sprintf("%s/vcard/%s", baseURL, p.URI.Opaque)
|
||||
return &httpResolve{p, p.Verify, nil}
|
||||
|
||||
case "https":
|
||||
p.Icon = "fas fa-atlas"
|
||||
p.Name = p.URI.Hostname()
|
||||
p.Link = fmt.Sprintf("https://%s", p.URI.Hostname())
|
||||
|
||||
switch {
|
||||
case strings.HasPrefix(p.URI.Host, "twitter.com"):
|
||||
// TODO: Add api authenticated code path.
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 3); len(sp) > 1 {
|
||||
p.Icon = "fab fa-twitter"
|
||||
p.Service = "Twitter"
|
||||
p.Name = sp[1]
|
||||
p.Link = fmt.Sprintf("https://twitter.com/%s", p.Name)
|
||||
p.Verify = fmt.Sprintf("https://twitter.com%s", p.URI.Path)
|
||||
url := fmt.Sprintf("https://mobile.twitter.com%s", p.URI.Path)
|
||||
return &httpResolve{p, url, nil}
|
||||
}
|
||||
|
||||
case strings.HasPrefix(p.URI.Host, "news.ycombinator.com"):
|
||||
p.Icon = "fab fa-hacker-news"
|
||||
p.Service = "HackerNews"
|
||||
p.Name = p.URI.Query().Get("id")
|
||||
p.Link = uri
|
||||
return &httpResolve{p, p.Verify, nil}
|
||||
|
||||
case strings.HasPrefix(p.URI.Host, "dev.to"):
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 3); len(sp) > 1 {
|
||||
p.Icon = "fab fa-dev"
|
||||
p.Service = "dev.to"
|
||||
p.Name = sp[1]
|
||||
p.Link = fmt.Sprintf("https://dev.to/%s", p.Name)
|
||||
url := fmt.Sprintf("https://dev.to/api/articles/%s/%s", sp[1], sp[2])
|
||||
return &httpResolve{p, url, nil}
|
||||
}
|
||||
|
||||
case strings.HasPrefix(p.URI.Host, "reddit.com"), strings.HasPrefix(p.URI.Host, "www.reddit.com"):
|
||||
var headers map[string]string
|
||||
|
||||
cfg := config.FromContext(ctx)
|
||||
if apikey := cfg.GetString("reddit.api-key"); apikey != "" {
|
||||
secret := cfg.GetString("reddit.secret")
|
||||
|
||||
headers = map[string]string{
|
||||
"Authorization": fmt.Sprintf("basic %s",
|
||||
base64.StdEncoding.EncodeToString([]byte(apikey+":"+secret))),
|
||||
"User-Agent": "ipseity/0.1.0",
|
||||
}
|
||||
}
|
||||
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 6); len(sp) > 5 {
|
||||
p.Icon = "fab fa-reddit"
|
||||
p.Service = "Reddit"
|
||||
p.Name = sp[2]
|
||||
p.Link = fmt.Sprintf("https://www.reddit.com/user/%s", p.Name)
|
||||
url := fmt.Sprintf("https://api.reddit.com/user/%s/comments/%s/%s", sp[2], sp[4], sp[5])
|
||||
return &httpResolve{p, url, headers}
|
||||
}
|
||||
|
||||
case strings.HasPrefix(p.URI.Host, "gist.github.com"):
|
||||
p.Icon = "fab fa-github"
|
||||
p.Service = "GitHub"
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 3); len(sp) > 2 {
|
||||
var headers map[string]string
|
||||
if secret := config.FromContext(ctx).GetString("github.secret"); secret != "" {
|
||||
headers = map[string]string{
|
||||
"Authorization": fmt.Sprintf("bearer %s", secret),
|
||||
"User-Agent": "keyproofs/0.1.0",
|
||||
}
|
||||
}
|
||||
|
||||
p.Name = sp[1]
|
||||
p.Link = fmt.Sprintf("https://github.com/%s", p.Name)
|
||||
url := fmt.Sprintf("https://api.github.com/gists/%s", sp[2])
|
||||
return &httpResolve{p, url, headers}
|
||||
}
|
||||
|
||||
case strings.HasPrefix(p.URI.Host, "lobste.rs"):
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 3); len(sp) > 2 {
|
||||
p.Icon = "fas fa-list-ul"
|
||||
p.Service = "Lobsters"
|
||||
p.Name = sp[2]
|
||||
p.Link = uri
|
||||
p.Verify += ".json"
|
||||
return &httpResolve{p, p.Verify, nil}
|
||||
}
|
||||
|
||||
case strings.HasSuffix(p.URI.Path, "/gitlab_proof"):
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 3); len(sp) > 1 {
|
||||
p.Icon = "fab fa-gitlab"
|
||||
p.Service = "GetLab"
|
||||
p.Name = sp[1]
|
||||
p.Link = fmt.Sprintf("https://%s/%s", p.URI.Host, p.Name)
|
||||
p.Name = fmt.Sprintf("%s@%s", p.Name, p.URI.Host)
|
||||
return &gitlabResolve{p}
|
||||
}
|
||||
|
||||
case strings.HasSuffix(p.URI.Path, "/gitea_proof"):
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 3); len(sp) > 2 {
|
||||
p.Icon = "fas fa-mug-hot"
|
||||
p.Service = "Gitea"
|
||||
p.Name = sp[1]
|
||||
p.Link = fmt.Sprintf("https://%s/%s", p.URI.Host, p.Name)
|
||||
p.Name = fmt.Sprintf("%s@%s", p.Name, p.URI.Host)
|
||||
url := fmt.Sprintf("https://%s/api/v1/repos/%s/gitea_proof", p.URI.Host, sp[1])
|
||||
return &httpResolve{p, url, nil}
|
||||
}
|
||||
|
||||
default:
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 3); len(sp) > 1 {
|
||||
p.Icon = "fas fa-project-diagram"
|
||||
p.Service = "Fediverse"
|
||||
if len(sp) > 2 && (sp[1] == "u" || sp[1] == "user" || sp[1] == "users") {
|
||||
p.Name = sp[2]
|
||||
} else {
|
||||
p.Name = sp[1]
|
||||
}
|
||||
p.Name = fmt.Sprintf("%s@%s", p.Name, p.URI.Host)
|
||||
p.Link = uri
|
||||
return &httpResolve{p, p.Verify, nil}
|
||||
}
|
||||
}
|
||||
default:
|
||||
p.Icon = "exclamation-triangle"
|
||||
p.Service = "unknown"
|
||||
p.Name = "nobody"
|
||||
}
|
||||
|
||||
return &p
|
||||
}
|
||||
|
||||
type ProofResolver interface {
|
||||
Resolve(context.Context) error
|
||||
Proof() *Proof
|
||||
}
|
||||
|
||||
type httpResolve struct {
|
||||
proof Proof
|
||||
url string
|
||||
headers map[string]string
|
||||
}
|
||||
|
||||
func (p *httpResolve) Resolve(ctx context.Context) error {
|
||||
err := checkHTTP(ctx, p.url, p.proof.Fingerprint, p.headers)
|
||||
if err == ErrNoFingerprint {
|
||||
p.proof.Status = ProofInvalid
|
||||
} else if err != nil {
|
||||
p.proof.Status = ProofError
|
||||
} else {
|
||||
p.proof.Status = ProofVerified
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (p *httpResolve) Proof() *Proof {
|
||||
return &p.proof
|
||||
}
|
||||
|
||||
type gitlabResolve struct {
|
||||
proof Proof
|
||||
}
|
||||
|
||||
func (r *gitlabResolve) Resolve(ctx context.Context) error {
|
||||
uri := r.proof.URI
|
||||
r.proof.Status = ProofInvalid
|
||||
|
||||
if sp := strings.SplitN(uri.Path, "/", 3); len(sp) > 1 {
|
||||
user := []struct {
|
||||
Id int `json:"id"`
|
||||
}{}
|
||||
if err := httpJSON(ctx, fmt.Sprintf("https://%s/api/v4/users?username=%s", uri.Host, sp[1]), nil, &user); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(user) == 0 {
|
||||
return ErrNoFingerprint
|
||||
}
|
||||
u := user[0]
|
||||
url := fmt.Sprintf("https://%s/api/v4/users/%d/projects", uri.Host, u.Id)
|
||||
proofs := []struct {
|
||||
Description string
|
||||
}{}
|
||||
if err := httpJSON(ctx, url, nil, &proofs); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(proofs) == 0 {
|
||||
return ErrNoFingerprint
|
||||
}
|
||||
ck := fmt.Sprintf("[Verifying my OpenPGP key: openpgp4fpr:%s]", strings.ToLower(r.proof.Fingerprint))
|
||||
for _, p := range proofs {
|
||||
if strings.Contains(p.Description, ck) {
|
||||
r.proof.Status = ProofVerified
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ErrNoFingerprint
|
||||
}
|
||||
func (p *gitlabResolve) Proof() *Proof {
|
||||
return &p.proof
|
||||
}
|
||||
|
||||
func (p *Proof) Resolve(ctx context.Context) error {
|
||||
return fmt.Errorf("Not Implemented")
|
||||
}
|
||||
func (p *Proof) Proof() *Proof {
|
||||
return p
|
||||
}
|
||||
|
||||
func checkHTTP(ctx context.Context, uri, fingerprint string, hdr map[string]string) error {
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
log.Info().
|
||||
Str("URI", uri).
|
||||
Str("fp", fingerprint).
|
||||
Msg("Proof")
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", uri, nil)
|
||||
if err != nil {
|
||||
log.Err(err)
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
for k, v := range hdr {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
log.Err(err)
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
ts := rand.Int63()
|
||||
log.Info().Str("uri", uri).Int64("ts", ts).Msg("Reading data")
|
||||
defer log.Info().Str("uri", uri).Int64("ts", ts).Msg("Read data")
|
||||
|
||||
scan := bufio.NewScanner(res.Body)
|
||||
for scan.Scan() {
|
||||
if strings.Contains(strings.ToUpper(scan.Text()), fingerprint) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return ErrNoFingerprint
|
||||
}
|
||||
|
||||
var ErrNoFingerprint = errors.New("fingerprint not found")
|
||||
|
||||
func httpJSON(ctx context.Context, uri string, hdr map[string]string, dst interface{}) error {
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
log.Info().Str("URI", uri).Msg("httpJSON")
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", uri, nil)
|
||||
if err != nil {
|
||||
log.Err(err)
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
for k, v := range hdr {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
log.Err(err)
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
return json.NewDecoder(res.Body).Decode(dst)
|
||||
}
|
||||
324
pkg/keyproofs/routes.go
Normal file
324
pkg/keyproofs/routes.go
Normal file
@@ -0,0 +1,324 @@
|
||||
package keyproofs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
zlog "github.com/rs/zerolog/log"
|
||||
"github.com/skip2/go-qrcode"
|
||||
"gosrc.io/xmpp"
|
||||
|
||||
"github.com/sour-is/keyproofs/pkg/cache"
|
||||
"github.com/sour-is/keyproofs/pkg/config"
|
||||
"github.com/sour-is/keyproofs/pkg/promise"
|
||||
)
|
||||
|
||||
var expireAfter = 20 * time.Minute
|
||||
|
||||
func New(ctx context.Context, c cache.Cacher) (*identity, error) {
|
||||
log := zlog.Ctx(ctx)
|
||||
|
||||
var ok bool
|
||||
var xmppConfig *xmpp.Config
|
||||
if xmppConfig, ok = config.FromContext(ctx).Get("xmpp-config").(*xmpp.Config); !ok {
|
||||
log.Error().Msg("no xmpp-config")
|
||||
|
||||
return nil, fmt.Errorf("no xmpp config")
|
||||
}
|
||||
|
||||
conn, err := NewXMPP(ctx, xmppConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tasker := promise.NewRunner(ctx, promise.Timeout(30*time.Second), promise.WithCache(c, expireAfter))
|
||||
i := &identity{
|
||||
cache: c,
|
||||
tasker: tasker,
|
||||
conn: conn,
|
||||
}
|
||||
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// 1x1 gif pixel
|
||||
var pixl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
|
||||
var keypng, _ = base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABKUlEQVQ4jZ2SvUoDURCFUy/Y2Fv4BoKIiFgLSWbmCWw0e3cmNgGfwacQsbCxUEFEEIVkxsQulaK1kheIiFVW1mJXiZv904FbXb5zzvzUaiWlPqyYwIkyvRjjqwmeaauxUcbFMKOvTKEJRVPv05hCY9wrhHt+fckEJ79gxg9rweJN8qdSkESZjlLOkQm+Xe9szlubFkxwYoznuQIm9DgrQJEyjZXpPU5Eo6L+H7IEUmJFAnBQJmAMp5nw0IFnjFoiEGrQXJuBLx14JtgtiR5qAO2c4aFLAffGeGiMT8b0rAEe96WxnBlbGbbia/vZ+2CwjXO5g0pN/TZ1NNXgoQPPHO2aJLsViu4E+xdVnXsOOtPOMbxeDY6jw/6/nL+r6+qryjQyhqs/OSf1Bf+pJC1wKqO/AAAAAElFTkSuQmCC")
|
||||
|
||||
var defaultStyle = &Style{
|
||||
Avatar: pixl,
|
||||
Cover: pixl,
|
||||
Background: pixl,
|
||||
Palette: getPalette("#93CCEA"),
|
||||
}
|
||||
|
||||
type identity struct {
|
||||
cache cache.Cacher
|
||||
tasker promise.Tasker
|
||||
conn *connection
|
||||
}
|
||||
|
||||
func (s *identity) Routes(r *chi.Mux) {
|
||||
r.Use(secHeaders)
|
||||
r.MethodFunc("GET", "/id/{id}", s.get)
|
||||
r.MethodFunc("GET", "/dns/{domain}", s.getDNS)
|
||||
r.MethodFunc("GET", "/vcard/{jid}", s.getVCard)
|
||||
r.MethodFunc("GET", "/qr", s.getQR)
|
||||
r.MethodFunc("GET", "/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.WriteHeader(200)
|
||||
_, _ = w.Write(keypng)
|
||||
})
|
||||
}
|
||||
|
||||
func fmtKey(key promise.Key) string {
|
||||
return fmt.Sprintf("%T", key.Key())
|
||||
}
|
||||
|
||||
func (s *identity) get(w http.ResponseWriter, r *http.Request) {
|
||||
log := zlog.Ctx(r.Context())
|
||||
|
||||
id := chi.URLParam(r, "id")
|
||||
log.Debug().Str("get ", id).Send()
|
||||
|
||||
// Setup timeout for page refresh
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Run tasks to resolve entity, style, and proofs.
|
||||
task := s.tasker.Run(EntityKey(id), func(q promise.Q) {
|
||||
ctx := q.Context()
|
||||
log := zlog.Ctx(ctx).With().Interface(fmtKey(q), q.Key()).Logger()
|
||||
|
||||
key := q.Key().(EntityKey)
|
||||
|
||||
entity, err := getOpenPGPkey(ctx, string(key))
|
||||
if err != nil {
|
||||
q.Reject(err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().Msg("Resolving Entity")
|
||||
q.Resolve(entity)
|
||||
})
|
||||
|
||||
task.After(func(q promise.ResultQ) {
|
||||
entity := q.Result().(*Entity)
|
||||
|
||||
zlog.Ctx(q.Context()).
|
||||
Info().
|
||||
Str("email", entity.Primary.Address).
|
||||
Interface(fmtKey(q), q.Key()).
|
||||
Msg("Do Style ")
|
||||
|
||||
q.Run(StyleKey(entity.Primary.Address), func(q promise.Q) {
|
||||
ctx := q.Context()
|
||||
log := zlog.Ctx(ctx).With().Interface(fmtKey(q), q.Key()).Logger()
|
||||
|
||||
key := q.Key().(StyleKey)
|
||||
|
||||
log.Debug().Msg("start task")
|
||||
style, err := s.getStyle(ctx, string(key))
|
||||
if err != nil {
|
||||
q.Reject(err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().Msg("Resolving Style")
|
||||
q.Resolve(style)
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
task.After(func(q promise.ResultQ) {
|
||||
entity := q.Result().(*Entity)
|
||||
log := zlog.Ctx(ctx).
|
||||
With().
|
||||
Interface(fmtKey(q), q.Key()).
|
||||
Logger()
|
||||
|
||||
log.Info().
|
||||
Int("num", len(entity.Proofs)).
|
||||
Msg("Scheduling Proofs")
|
||||
|
||||
for i := range entity.Proofs {
|
||||
q.Run(ProofKey(entity.Proofs[i]), func(q promise.Q) {
|
||||
ctx := q.Context()
|
||||
log := zlog.Ctx(ctx).
|
||||
With().
|
||||
Interface(fmtKey(q), q.Key()).
|
||||
Logger()
|
||||
|
||||
key := q.Key().(ProofKey)
|
||||
proof := NewProof(ctx, string(key), entity.Fingerprint)
|
||||
defer log.Debug().Interface("status", proof.Proof().Status).Msg("Resolving Proof")
|
||||
|
||||
if err := proof.Resolve(ctx); err != nil && err != ErrNoFingerprint {
|
||||
log.Err(err).Send()
|
||||
}
|
||||
|
||||
q.Resolve(proof.Proof())
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
page := page{Style: defaultStyle}
|
||||
|
||||
// Wait for either entity to resolve or timeout
|
||||
select {
|
||||
case <-task.Await():
|
||||
log.Print("Tasks Competed")
|
||||
if err := task.Err(); err != nil {
|
||||
page.Err = err
|
||||
page.IsComplete = true
|
||||
break
|
||||
}
|
||||
page.Entity = task.Result().(*Entity)
|
||||
|
||||
case <-ctx.Done():
|
||||
log.Print("Deadline Timeout")
|
||||
if e, ok := s.cache.Get(EntityKey(id)); ok {
|
||||
page.Entity = e.Value().(*Entity)
|
||||
}
|
||||
}
|
||||
|
||||
// Build page based on available information.
|
||||
if page.Entity != nil {
|
||||
var gotStyle, gotProofs bool
|
||||
|
||||
if s, ok := s.cache.Get(StyleKey(page.Entity.Primary.Address)); ok {
|
||||
page.Style = s.Value().(*Style)
|
||||
gotStyle = true
|
||||
}
|
||||
|
||||
gotProofs = true
|
||||
if len(page.Entity.Proofs) > 0 {
|
||||
page.HasProofs = true
|
||||
proofs := make(Proofs, len(page.Entity.Proofs))
|
||||
for i := range page.Entity.Proofs {
|
||||
p := page.Entity.Proofs[i]
|
||||
|
||||
if s, ok := s.cache.Get(ProofKey(p)); ok {
|
||||
log.Debug().Str("uri", p).Msg("Proof from cache")
|
||||
proofs[p] = s.Value().(*Proof)
|
||||
} else {
|
||||
log.Debug().Str("uri", p).Msg("Missing proof")
|
||||
proofs[p] = NewProof(ctx, p, page.Entity.Fingerprint).Proof()
|
||||
gotProofs = false
|
||||
}
|
||||
}
|
||||
page.Proofs = &proofs
|
||||
}
|
||||
|
||||
page.IsComplete = gotStyle && gotProofs
|
||||
}
|
||||
|
||||
// Template and display.
|
||||
t, err := template.New("identity").Parse(pageTPL)
|
||||
if err != nil {
|
||||
WriteText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
err = t.Execute(w, page)
|
||||
if err != nil {
|
||||
WriteText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (s *identity) getDNS(w http.ResponseWriter, r *http.Request) {
|
||||
domain := chi.URLParam(r, "domain")
|
||||
|
||||
res, err := net.DefaultResolver.LookupTXT(r.Context(), domain)
|
||||
if err != nil {
|
||||
WriteText(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
WriteText(w, 200, strings.Join(res, "\n"))
|
||||
}
|
||||
|
||||
func (s *identity) getQR(w http.ResponseWriter, r *http.Request) {
|
||||
log := zlog.Ctx(r.Context())
|
||||
|
||||
content := r.URL.Query().Get("c")
|
||||
size := 64
|
||||
|
||||
sz, _ := strconv.Atoi(r.URL.Query().Get("s"))
|
||||
|
||||
if sz > -10 && sz < 0 {
|
||||
size = sz
|
||||
} else if sz > 64 && sz < 4096 {
|
||||
size = sz
|
||||
} else if sz > 4096 {
|
||||
size = 4096
|
||||
}
|
||||
|
||||
quality := qrcode.Medium
|
||||
switch r.URL.Query().Get("r") {
|
||||
case "L":
|
||||
quality = qrcode.Low
|
||||
case "Q":
|
||||
quality = qrcode.High
|
||||
case "H":
|
||||
quality = qrcode.Highest
|
||||
}
|
||||
|
||||
log.Debug().Str("content", content).Int("size", size).Interface("quality", quality).Int("s", sz).Msg("QRCode")
|
||||
|
||||
png, err := qrcode.Encode(content, quality, size)
|
||||
if err != nil {
|
||||
WriteText(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Add("Content-Type", "image/png")
|
||||
w.WriteHeader(200)
|
||||
|
||||
_, _ = w.Write(png)
|
||||
}
|
||||
|
||||
func (s *identity) getVCard(w http.ResponseWriter, r *http.Request) {
|
||||
jid := chi.URLParam(r, "jid")
|
||||
if _, err := mail.ParseAddress(jid); err != nil {
|
||||
fmt.Fprint(w, err)
|
||||
w.WriteHeader(400)
|
||||
}
|
||||
|
||||
vcard, err := s.conn.GetXMPPVCard(r.Context(), jid)
|
||||
if err != nil {
|
||||
fmt.Fprint(w, err)
|
||||
w.WriteHeader(500)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/xml")
|
||||
w.WriteHeader(200)
|
||||
fmt.Fprint(w, vcard)
|
||||
}
|
||||
|
||||
func secHeaders(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-XSS-Protection", "1; mode=block")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
|
||||
h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// WriteText writes plain text
|
||||
func WriteText(w http.ResponseWriter, code int, o string) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.WriteHeader(code)
|
||||
_, _ = w.Write([]byte(o))
|
||||
}
|
||||
127
pkg/keyproofs/style.go
Normal file
127
pkg/keyproofs/style.go
Normal file
@@ -0,0 +1,127 @@
|
||||
package keyproofs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/lucasb-eyer/go-colorful"
|
||||
"sour.is/x/toolbox/log"
|
||||
)
|
||||
|
||||
type StyleKey string
|
||||
|
||||
func (s StyleKey) Key() interface{} {
|
||||
return s
|
||||
}
|
||||
|
||||
type Style struct {
|
||||
Avatar,
|
||||
Cover,
|
||||
Background string
|
||||
|
||||
Palette []string
|
||||
}
|
||||
|
||||
func (s *identity) getStyle(ctx context.Context, email string) (*Style, error) {
|
||||
avatarHost, styleHost, err := styleSRV(ctx, email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Infos("getStyle", "avatar", avatarHost, "style", styleHost)
|
||||
|
||||
hash := md5.New()
|
||||
email = strings.TrimSpace(strings.ToLower(email))
|
||||
_, _ = hash.Write([]byte(email))
|
||||
|
||||
id := hash.Sum(nil)
|
||||
|
||||
style := &Style{}
|
||||
|
||||
style.Palette = getPalette(fmt.Sprintf("#%x", id[:3]))
|
||||
style.Avatar = fmt.Sprintf("https://%s/avatar/%x", avatarHost, id)
|
||||
style.Cover = pixl
|
||||
style.Background = "https://lavana.sour.is/bg/52548b3dcb032882675afe1e4bcba0e9"
|
||||
|
||||
if styleHost != "" {
|
||||
style.Cover = fmt.Sprintf("https://%s/cover/%x", styleHost, id)
|
||||
style.Background = fmt.Sprintf("https://%s/bg/%x", styleHost, id)
|
||||
}
|
||||
|
||||
return style, err
|
||||
}
|
||||
|
||||
func styleSRV(ctx context.Context, email string) (avatar string, style string, err error) {
|
||||
|
||||
// Defaults
|
||||
style = ""
|
||||
avatar = "www.gravatar.com"
|
||||
|
||||
parts := strings.SplitN(email, "@", 2)
|
||||
if _, srv, err := net.DefaultResolver.LookupSRV(ctx, "style-sec", "tcp", parts[1]); err == nil {
|
||||
if len(srv) > 0 {
|
||||
style = strings.TrimSuffix(srv[0].Target, ".")
|
||||
avatar = strings.TrimSuffix(srv[0].Target, ".")
|
||||
|
||||
return avatar, style, err
|
||||
}
|
||||
}
|
||||
|
||||
if _, srv, err := net.DefaultResolver.LookupSRV(ctx, "avatars-sec", "tcp", parts[1]); err == nil {
|
||||
if len(srv) > 0 {
|
||||
avatar = strings.TrimSuffix(srv[0].Target, ".")
|
||||
|
||||
return avatar, style, err
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// getPalette maes a complementary color palette. https://play.golang.org/p/nBXLUocGsU5
|
||||
func getPalette(hex string) []string {
|
||||
reference, _ := colorful.Hex(hex)
|
||||
reference = sat(lum(reference, 0, .5), 0, .5)
|
||||
|
||||
white := colorful.Color{R: 1, G: 1, B: 1}
|
||||
black := colorful.Color{R: 0, G: 0, B: 0}
|
||||
accentA := hue(reference, 60)
|
||||
accentB := hue(reference, -60)
|
||||
accentC := hue(reference, -180)
|
||||
|
||||
return append(
|
||||
[]string{},
|
||||
|
||||
white.Hex(),
|
||||
lum(reference, .4, .6).Hex(),
|
||||
reference.Hex(),
|
||||
lum(reference, .4, 0).Hex(),
|
||||
black.Hex(),
|
||||
|
||||
lum(accentA, .4, .6).Hex(),
|
||||
accentA.Hex(),
|
||||
lum(accentA, .4, 0).Hex(),
|
||||
|
||||
lum(accentB, .4, .6).Hex(),
|
||||
accentB.Hex(),
|
||||
lum(accentB, .4, 0).Hex(),
|
||||
|
||||
lum(accentC, .4, .6).Hex(),
|
||||
accentC.Hex(),
|
||||
lum(accentC, .4, 0).Hex(),
|
||||
)
|
||||
}
|
||||
func hue(in colorful.Color, H float64) colorful.Color {
|
||||
h, s, l := in.Hsl()
|
||||
return colorful.Hsl(h+H, s, l)
|
||||
}
|
||||
func sat(in colorful.Color, S, V float64) colorful.Color {
|
||||
h, s, l := in.Hsl()
|
||||
return colorful.Hsl(h, V+s*S, l)
|
||||
}
|
||||
func lum(in colorful.Color, L, V float64) colorful.Color {
|
||||
h, s, l := in.Hsl()
|
||||
return colorful.Hsl(h, s, V+l*L)
|
||||
}
|
||||
182
pkg/keyproofs/template.go
Normal file
182
pkg/keyproofs/template.go
Normal file
@@ -0,0 +1,182 @@
|
||||
package keyproofs
|
||||
|
||||
type page struct {
|
||||
Entity *Entity
|
||||
Style *Style
|
||||
Proofs *Proofs
|
||||
|
||||
HasProofs bool
|
||||
IsComplete bool
|
||||
Err error
|
||||
}
|
||||
|
||||
var pageTPL = `
|
||||
<html>
|
||||
<head>
|
||||
{{if not .IsComplete}}<meta http-equiv="refresh" content="1">{{end}}
|
||||
<script src="https://pagecdn.io/lib/font-awesome/5.14.0/js/fontawesome.min.js" crossorigin="anonymous" integrity="sha256-dNZKI9qQEpJG03MLdR2Rg9Dva1o+50fN3zmlDP+3I+Y="></script>
|
||||
|
||||
<link href="https://pagecdn.io/lib/bootstrap/4.5.1/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous" integrity="sha256-VoFZSlmyTXsegReQCNmbXrS4hBBUl/cexZvPmPWoJsY=" >
|
||||
<link href="https://pagecdn.io/lib/font-awesome/5.14.0/css/fontawesome.min.css" rel="stylesheet" crossorigin="anonymous" integrity="sha256-7YMlwkILTJEm0TSengNDszUuNSeZu4KTN3z7XrhUQvc=" >
|
||||
<link href="https://pagecdn.io/lib/font-awesome/5.14.0/css/solid.min.css" rel="stylesheet" crossorigin="anonymous" integrity="sha256-s0DhrAmIsT5gZ3X4f+9wIXUbH52CMiqFAwgqCmdPoec=" >
|
||||
<link href="https://pagecdn.io/lib/font-awesome/5.14.0/css/regular.min.css" rel="stylesheet" crossorigin="anonymous" integrity="sha256-FAKIbnpfWhK6v5Re+NAi9n+5+dXanJvXVFohtH6WAuw=" >
|
||||
<link href="https://pagecdn.io/lib/font-awesome/5.14.0/css/brands.min.css" rel="stylesheet" crossorigin="anonymous" integrity="sha256-xN44ju35FR+kTO/TP/UkqrVbM3LpqUI1VJCWDGbG1ew=" >
|
||||
|
||||
{{ with .Style }}
|
||||
<style>
|
||||
{{range $i, $val := .Palette}}.fg-color-{{$i}} { color: {{$val}}; }
|
||||
{{end}}
|
||||
|
||||
{{range $i, $val := .Palette}}.bg-color-{{$i}} { background-color: {{$val}}; }
|
||||
{{end}}
|
||||
|
||||
body {
|
||||
background-image: url('{{.Background}}');
|
||||
background-repeat: repeat;
|
||||
background-color: {{index .Palette 7}};
|
||||
padding-top: 1em;
|
||||
}
|
||||
.heading {
|
||||
background-image: url('{{.Cover}}');
|
||||
background-size: cover;
|
||||
background-repeat: no-repeat;
|
||||
background-color: {{index .Palette 3}};
|
||||
}
|
||||
.shade { background-color: {{index .Palette 3}}80; border-radius: .25rem;}
|
||||
.lead { padding:0; margin:0; }
|
||||
|
||||
@media only screen and (max-width: 768px) {
|
||||
.center-xs { text-align: center; width: 100% }
|
||||
.center-sm { text-align: center; width: 100% }
|
||||
.center-md { text-align: center; width: 100% }
|
||||
h1, h2, h3, h4, h5, h6, .lead { font-size: 75% }
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 576px) {
|
||||
.center-xs { text-align: center; width: 100% }
|
||||
.center-sm { text-align: center; width: 100% }
|
||||
.center-md { text-align: center; width: 100% }
|
||||
h1, h2, h3, h4, h5, h6, .lead { font-size: 75% }
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 0) {
|
||||
.center-xs { text-align: center; width: 100% }
|
||||
.center-sm { text-align: center; width: 100% }
|
||||
.center-md { text-align: center; width: 100% }
|
||||
h1, h2, h3, h4, h5, h6, .lead { font-size: 60% }
|
||||
}
|
||||
|
||||
</style>
|
||||
{{end}}
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="jumbotron heading">
|
||||
<div class="container">
|
||||
<div class="row shade">
|
||||
|
||||
{{ with .Err }}
|
||||
<div class="col-xs center-md">
|
||||
<i class="fas fa-exclamation-triangle fa-4x fg-color-11"></i>
|
||||
</div>
|
||||
|
||||
<div class="col-md">
|
||||
<h1 class="display-8 fg-color-8">Something went wrong...</h1>
|
||||
<pre class="fg-color-11">{{.}}</pre>
|
||||
</div>
|
||||
{{else}}
|
||||
{{ with .Style }}
|
||||
<div class="col-xs center-md">
|
||||
<img src="{{.Avatar}}" class="img-thumbnail" alt="avatar" style="width:88px; height:88px">
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
|
||||
{{with .Entity}}
|
||||
<div class="col-md center-md">
|
||||
<h1 class="display-8 fg-color-8">{{.Primary.Name}}</h1>
|
||||
<p class="lead fg-color-11"><i class="fas fa-fingerprint"></i> {{.Fingerprint}}</p>
|
||||
</div>
|
||||
<div class="col-xs center-md">
|
||||
<img src="/qr?s=-2&c=OPENPGP4FPR%3A{{.Fingerprint}}" class="img-thumbnail" alt="qrcode" style="width:88px; height:88px">
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="col-md">
|
||||
<h1 class="display-8 fg-color-8">Loading...</h1>
|
||||
<p class="lead fg-color-11">Reading key from remote service.</p>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
{{ with .Entity }}
|
||||
<div class="card">
|
||||
<div class="card-header">Contact</div>
|
||||
<div class="list-group list-group-flush">
|
||||
{{with .Primary}}<a href="mailto:{{.Address}}" class="list-group-item list-group-item-action"><i class="fas fa-envelope"></i> <b>{{.Name}} <{{.Address}}></b> <span class="badge badge-secondary">Primary</span></a>{{end}}
|
||||
{{range .Emails}}<a href="mailto:{{.Address}}" class="list-group-item list-group-item-action"><i class="far fa-envelope"></i> {{.Name}} <{{.Address}}></a>{{end}}
|
||||
</div>
|
||||
</div>
|
||||
<br />
|
||||
{{end}}
|
||||
|
||||
{{if .HasProofs}}
|
||||
{{with .Proofs}}
|
||||
<div class="card">
|
||||
<div class="card-header">Proofs</div>
|
||||
<ul class="list-group list-group-flush">
|
||||
{{range .}}
|
||||
<li class="list-group-item">
|
||||
<div class="d-flex w-100 justify-content-between">
|
||||
<div>
|
||||
<a title="{{.Link}}" class="font-weight-bold" href="{{.Link}}">
|
||||
<i title="{{.Service}}" class="{{.Icon}}"></i>
|
||||
{{.Name}}
|
||||
</a>
|
||||
|
||||
{{if eq .Status 0}}
|
||||
<a class="text-muted" href="{{.Verify}}"> <i class="fas fa-ellipsis-h"> Checking</i></a>
|
||||
{{else if eq .Status 1}}
|
||||
<a class="text-warning" href="{{.Verify}}"> <i class="fas fa-exclamation-triangle"></i> Error</a>
|
||||
{{else if eq .Status 2}}
|
||||
<a class="text-danger" href="{{.Verify}}"> <i class="far fa-times-circle"></i> Invalid</a>
|
||||
{{else if eq .Status 3}}
|
||||
<a class="text-success" href="{{.Verify}}"> <i class="far fa-check-square"></i> Verified</a>
|
||||
{{end}}
|
||||
</div>
|
||||
<div>
|
||||
{{if eq .Service "xmpp"}}
|
||||
<img src="/qr?s=-2&c={{.Link}}" alt="qrcode" style="width:88px; height:88px">
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
</div>
|
||||
<br/>
|
||||
{{else}}
|
||||
<div class="card">
|
||||
<div class="card-header">Proofs</div>
|
||||
<div class="card-body">Loading...</div>
|
||||
</div>
|
||||
<br/>
|
||||
{{end}}
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<div class="card-footer text-muted text-center">
|
||||
© 2020 Sour.is
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
97
pkg/keyproofs/vcard.go
Normal file
97
pkg/keyproofs/vcard.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package keyproofs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"gosrc.io/xmpp"
|
||||
"gosrc.io/xmpp/stanza"
|
||||
)
|
||||
|
||||
type VCard struct {
|
||||
XMLName xml.Name `xml:"vcard-temp vCard"`
|
||||
FullName string `xml:"FN"`
|
||||
NickName string `xml:"NICKNAME"`
|
||||
Description string `xml:"DESC"`
|
||||
URL string `xml:"URL"`
|
||||
}
|
||||
|
||||
func NewVCard() *VCard {
|
||||
return &VCard{}
|
||||
}
|
||||
|
||||
func (c *VCard) Namespace() string {
|
||||
return c.XMLName.Space
|
||||
}
|
||||
|
||||
func (c *VCard) GetSet() *stanza.ResultSet {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *VCard) String() string {
|
||||
b, _ := xml.MarshalIndent(c, "", " ")
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func init() {
|
||||
stanza.TypeRegistry.MapExtension(stanza.PKTIQ, xml.Name{Space: "vcard-temp", Local: "vCard"}, VCard{})
|
||||
}
|
||||
|
||||
type connection struct {
|
||||
client *xmpp.Client
|
||||
}
|
||||
|
||||
func NewXMPP(ctx context.Context, config *xmpp.Config) (*connection, error) {
|
||||
log := log.Ctx(ctx)
|
||||
router := xmpp.NewRouter()
|
||||
conn := &connection{}
|
||||
|
||||
var err error
|
||||
conn.client, err = xmpp.NewClient(config, router, func(err error) { log.Error().Err(err).Send() })
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
err := conn.client.Disconnect()
|
||||
log.Error().Err(err).Send()
|
||||
}()
|
||||
|
||||
err = conn.client.Connect()
|
||||
|
||||
return conn, err
|
||||
}
|
||||
|
||||
func (conn *connection) GetXMPPVCard(ctx context.Context, jid string) (vc *VCard, err error) {
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
var iq *stanza.IQ
|
||||
iq, err = stanza.NewIQ(stanza.Attrs{To: jid, Type: "get"})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
iq.Payload = NewVCard()
|
||||
|
||||
var ch chan stanza.IQ
|
||||
ch, err = conn.client.SendIQ(ctx, iq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
select {
|
||||
case result := <-ch:
|
||||
b, _ := xml.MarshalIndent(result, "", " ")
|
||||
log.Debug().Msgf("%s", b)
|
||||
if vcard, ok := result.Payload.(*VCard); ok {
|
||||
return vcard, nil
|
||||
}
|
||||
return nil, fmt.Errorf("bad response: %s", result.Payload)
|
||||
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("timeout requesting vcard for %s", jid)
|
||||
}
|
||||
219
pkg/promise/promise.go
Normal file
219
pkg/promise/promise.go
Normal file
@@ -0,0 +1,219 @@
|
||||
package promise
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"go.uber.org/ratelimit"
|
||||
)
|
||||
|
||||
type Q interface {
|
||||
Key() interface{}
|
||||
Context() context.Context
|
||||
Resolve(interface{})
|
||||
Reject(error)
|
||||
|
||||
Tasker
|
||||
}
|
||||
type ResultQ interface {
|
||||
Key() interface{}
|
||||
Context() context.Context
|
||||
Result() interface{}
|
||||
|
||||
Tasker
|
||||
}
|
||||
type Fn func(Q)
|
||||
type AfterFn func(ResultQ)
|
||||
type Key interface {
|
||||
Key() interface{}
|
||||
}
|
||||
|
||||
func typ(v interface{}) string {
|
||||
return fmt.Sprintf("%T", v)
|
||||
}
|
||||
|
||||
type qTask struct {
|
||||
key Key
|
||||
|
||||
fn Fn
|
||||
ctx context.Context
|
||||
|
||||
cancel func()
|
||||
done chan struct{}
|
||||
|
||||
result interface{}
|
||||
err error
|
||||
|
||||
Tasker
|
||||
}
|
||||
|
||||
func (t *qTask) Key() interface{} { return t.key }
|
||||
func (t *qTask) Context() context.Context { return t.ctx }
|
||||
func (t *qTask) Resolve(r interface{}) { t.result = r; t.finish() }
|
||||
func (t *qTask) Reject(err error) { t.err = err; t.finish() }
|
||||
|
||||
// After runs on successful completion of the task.
|
||||
func (t *qTask) After(fn AfterFn) {
|
||||
log := log.Ctx(t.Context())
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Panic().Msgf("%v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
<-t.Await()
|
||||
if err := t.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
fn(t)
|
||||
}()
|
||||
}
|
||||
func (t *qTask) Await() <-chan struct{} { return t.done }
|
||||
func (t *qTask) Cancel() { t.err = fmt.Errorf("task cancelled"); t.finish() }
|
||||
|
||||
func (t *qTask) Result() interface{} { return t.result }
|
||||
func (t *qTask) Err() error { return t.err }
|
||||
|
||||
func (t *qTask) finish() {
|
||||
if t.done == nil {
|
||||
return
|
||||
}
|
||||
|
||||
t.cancel()
|
||||
close(t.done)
|
||||
t.done = nil
|
||||
}
|
||||
|
||||
type Option interface {
|
||||
Apply(*qTask)
|
||||
}
|
||||
type OptionFn func(*qTask)
|
||||
|
||||
func (fn OptionFn) Apply(t *qTask) { fn(t) }
|
||||
|
||||
type Tasker interface {
|
||||
Run(Key, Fn, ...Option) *qTask
|
||||
}
|
||||
|
||||
type Runner struct {
|
||||
defaultOpts []Option
|
||||
queue map[interface{}]*qTask
|
||||
mu sync.RWMutex
|
||||
ctx context.Context
|
||||
cancel func()
|
||||
pause chan struct{}
|
||||
limiter ratelimit.Limiter
|
||||
}
|
||||
|
||||
type Timeout time.Duration
|
||||
|
||||
func (d Timeout) Apply(task *qTask) {
|
||||
task.ctx, task.cancel = context.WithTimeout(task.ctx, time.Duration(d))
|
||||
}
|
||||
|
||||
func (tr *Runner) Run(key Key, fn Fn, opts ...Option) *qTask {
|
||||
log := log.Ctx(tr.ctx)
|
||||
|
||||
tr.mu.RLock()
|
||||
log.Trace().Interface(typ(key), key.Key()).Msg("task to run")
|
||||
|
||||
if task, ok := tr.queue[key.Key()]; ok {
|
||||
tr.mu.RUnlock()
|
||||
log.Trace().Interface(typ(key), key.Key()).Msg("task found running")
|
||||
|
||||
return task
|
||||
}
|
||||
tr.mu.RUnlock()
|
||||
|
||||
task := &qTask{
|
||||
key: key,
|
||||
fn: fn,
|
||||
cancel: func() {},
|
||||
ctx: tr.ctx,
|
||||
done: make(chan struct{}),
|
||||
Tasker: tr,
|
||||
}
|
||||
|
||||
for _, opt := range tr.defaultOpts {
|
||||
opt.Apply(task)
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt.Apply(task)
|
||||
}
|
||||
|
||||
tr.mu.Lock()
|
||||
tr.queue[key.Key()] = task
|
||||
tr.mu.Unlock()
|
||||
|
||||
tr.limiter.Take()
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Panic().Msgf("%v", r)
|
||||
}
|
||||
|
||||
if err := task.Err(); err == nil {
|
||||
log.Trace().Interface(typ(key), key.Key()).Msg("task complete")
|
||||
} else {
|
||||
log.Debug().Interface(typ(key), key.Key()).Err(err).Msg("task Failed")
|
||||
}
|
||||
|
||||
tr.mu.Lock()
|
||||
delete(tr.queue, task.Key())
|
||||
tr.mu.Unlock()
|
||||
}()
|
||||
|
||||
log.Trace().Interface(typ(key), key.Key()).Msg("task Running")
|
||||
|
||||
task.fn(task)
|
||||
}()
|
||||
|
||||
return task
|
||||
}
|
||||
|
||||
func NewRunner(ctx context.Context, defaultOpts ...Option) *Runner {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
tr := &Runner{
|
||||
defaultOpts: defaultOpts,
|
||||
queue: make(map[interface{}]*qTask),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
pause: make(chan struct{}),
|
||||
limiter: ratelimit.New(10),
|
||||
}
|
||||
|
||||
return tr
|
||||
}
|
||||
|
||||
func (tr *Runner) List() []*qTask {
|
||||
tr.mu.RLock()
|
||||
defer tr.mu.RUnlock()
|
||||
|
||||
lis := make([]*qTask, 0, len(tr.queue))
|
||||
|
||||
for _, task := range tr.queue {
|
||||
lis = append(lis, task)
|
||||
}
|
||||
|
||||
return lis
|
||||
}
|
||||
|
||||
func (tr *Runner) Stop() {
|
||||
tr.cancel()
|
||||
}
|
||||
|
||||
func (tr *Runner) Len() int {
|
||||
tr.mu.RLock()
|
||||
defer tr.mu.RUnlock()
|
||||
|
||||
return len(tr.queue)
|
||||
}
|
||||
47
pkg/promise/with-cache.go
Normal file
47
pkg/promise/with-cache.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package promise
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/sour-is/keyproofs/pkg/cache"
|
||||
)
|
||||
|
||||
func WithCache(c cache.Cacher, expireAfter time.Duration) OptionFn {
|
||||
return func(task *qTask) {
|
||||
innerFn := task.fn
|
||||
task.fn = func(q Q) {
|
||||
log := log.Ctx(q.Context())
|
||||
|
||||
cacheKey, ok := q.Key().(cache.Key)
|
||||
if !ok {
|
||||
log.Trace().Interface(typ(q), q.Key()).Msg("not a cache key")
|
||||
innerFn(q)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if v, ok := c.Get(cacheKey); ok {
|
||||
log.Trace().Interface(typ(cacheKey), cacheKey.Key()).Msg("task result in cache")
|
||||
q.Resolve(v.Value())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Trace().Interface(typ(cacheKey), cacheKey.Key()).Msg("task not in cache")
|
||||
innerFn(q)
|
||||
|
||||
if err := task.Err(); err != nil {
|
||||
log.Err(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// expireAfter = time.Duration(rand.Int63() % int64(5*time.Second))
|
||||
result := cache.NewItem(cacheKey, task.Result(), expireAfter)
|
||||
|
||||
log.Trace().Interface(typ(cacheKey), cacheKey.Key()).Msgf("task result to cache")
|
||||
c.Add(cacheKey, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user