refactor out into packages for easier unit test writing
This commit is contained in:
354
pkg/app/avatar/avatar.go
Normal file
354
pkg/app/avatar/avatar.go
Normal file
@@ -0,0 +1,354 @@
|
||||
package app_avatar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/nullrocks/identicon"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/sour-is/keyproofs/pkg/graceful"
|
||||
"github.com/sour-is/keyproofs/pkg/style"
|
||||
)
|
||||
|
||||
var pixl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
|
||||
|
||||
type avatar struct {
|
||||
path string
|
||||
}
|
||||
|
||||
func New(ctx context.Context, path string) (*avatar, error) {
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
path = filepath.Clean(path)
|
||||
app := &avatar{path: path}
|
||||
err := app.CheckFiles(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("check files: %w", err)
|
||||
}
|
||||
|
||||
watch, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, typ := range []string{"avatar", "bg", "cover"} {
|
||||
err = watch.Add(filepath.Join(path, typ))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("adding watch: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug().Msg("startup avatar watcher")
|
||||
wg := graceful.WaitGroup(ctx)
|
||||
wg.Go(func() error {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Debug().Msg("shutdown avatar watcher")
|
||||
return nil
|
||||
case op := <-watch.Events:
|
||||
log.Print(op)
|
||||
switch op.Op {
|
||||
case fsnotify.Create:
|
||||
path = filepath.Dir(op.Name)
|
||||
kind := filepath.Base(path)
|
||||
name := filepath.Base(op.Name)
|
||||
if err := app.createLinks(kind, name); err != nil {
|
||||
log.Err(err).Send()
|
||||
}
|
||||
case fsnotify.Remove, fsnotify.Rename:
|
||||
path = filepath.Dir(op.Name)
|
||||
kind := filepath.Base(path)
|
||||
name := filepath.Base(op.Name)
|
||||
if err := app.removeLinks(kind, name); err != nil {
|
||||
log.Error().Err(err).Send()
|
||||
}
|
||||
default:
|
||||
}
|
||||
case err := <-watch.Errors:
|
||||
log.Err(err).Send()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return app, nil
|
||||
}
|
||||
|
||||
func (app *avatar) CheckFiles(ctx context.Context) error {
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
for _, name := range []string{".links", "avatar", "bg", "cover"} {
|
||||
log.Debug().Msgf("mkdir: %s", filepath.Join(app.path, name))
|
||||
err := os.MkdirAll(filepath.Join(app.path, name), 0700)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return filepath.Walk(app.path, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("walk failed: %w", err)
|
||||
}
|
||||
if info.IsDir() {
|
||||
switch info.Name() {
|
||||
case "avatar", "bg", "cover":
|
||||
return nil
|
||||
default:
|
||||
return filepath.SkipDir
|
||||
}
|
||||
}
|
||||
|
||||
path = filepath.Dir(path)
|
||||
kind := filepath.Base(path)
|
||||
name := info.Name()
|
||||
|
||||
log.Debug().Msgf("link: %s %s %s", app.path, kind, name)
|
||||
|
||||
return app.createLinks(kind, name)
|
||||
})
|
||||
}
|
||||
|
||||
func (app *avatar) get(w http.ResponseWriter, r *http.Request) {
|
||||
log := log.Ctx(r.Context())
|
||||
|
||||
log.Print(r.Host)
|
||||
|
||||
kind := chi.URLParam(r, "kind")
|
||||
hash := chi.URLParam(r, "hash")
|
||||
|
||||
sizeW, sizeH, resize := 0, 0, false
|
||||
if s, err := strconv.Atoi(r.URL.Query().Get("s")); err == nil && s > 0 {
|
||||
sizeW, sizeH, resize = sizeByKind(kind, s)
|
||||
}
|
||||
log.Debug().Int("width", sizeW).Int("height", sizeH).Bool("resize", resize).Str("kind", kind).Msg("Get Image")
|
||||
|
||||
if strings.ContainsRune(hash, '@') {
|
||||
avatarHost, _, err := style.GetSRV(r.Context(), hash)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
hash = hashSHA256(strings.ToLower(hash))
|
||||
http.Redirect(w, r, fmt.Sprintf("https://%s/%s/%s?%s", avatarHost, kind, hash, r.URL.RawQuery), 301)
|
||||
return
|
||||
}
|
||||
|
||||
fname := filepath.Join(app.path, ".links", strings.Join([]string{kind, hash}, "-"))
|
||||
log.Debug().Msgf("path: %s", fname)
|
||||
|
||||
if !fileExists(fname) {
|
||||
switch kind {
|
||||
case "avatar":
|
||||
ig, err := identicon.New("sour.is", 5, 3)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ii, err := ig.Draw(hash)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.WriteHeader(200)
|
||||
err = ii.Png(clamp(128, 512, sizeW), w)
|
||||
log.Error().Err(err).Send()
|
||||
|
||||
return
|
||||
default:
|
||||
sp := strings.SplitN(pixl, ",", 2)
|
||||
b, _ := base64.RawStdEncoding.DecodeString(sp[1])
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.WriteHeader(200)
|
||||
if _, err := w.Write(b); err != nil {
|
||||
log.Error().Err(err).Send()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if !resize {
|
||||
f, err := os.Open(fname)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.WriteHeader(200)
|
||||
|
||||
_, err = io.Copy(w, f)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Send()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
img, err := imaging.Open(fname, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
img = imaging.Fill(img, sizeW, sizeH, imaging.Center, imaging.Lanczos)
|
||||
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.WriteHeader(200)
|
||||
log.Debug().Msg("writing image")
|
||||
err = imaging.Encode(w, img, imaging.PNG)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Send()
|
||||
}
|
||||
}
|
||||
|
||||
func (app *avatar) Routes(r *chi.Mux) {
|
||||
r.MethodFunc("GET", "/{kind:avatar|bg|cover}/{hash}", app.get)
|
||||
}
|
||||
|
||||
func hashString(value string, h hash.Hash) string {
|
||||
_, _ = h.Write([]byte(value))
|
||||
return fmt.Sprintf("%x", h.Sum(nil))
|
||||
}
|
||||
func hashMD5(name string) string {
|
||||
return hashString(name, md5.New())
|
||||
}
|
||||
func hashSHA256(name string) string {
|
||||
return hashString(name, sha256.New())
|
||||
}
|
||||
|
||||
func (app *avatar) createLinks(kind, name string) error {
|
||||
if !strings.ContainsRune(name, '@') {
|
||||
return nil
|
||||
}
|
||||
|
||||
src := filepath.Join("..", kind, name)
|
||||
name = strings.ToLower(name)
|
||||
|
||||
hash := hashMD5(name)
|
||||
link := filepath.Join(app.path, ".links", strings.Join([]string{kind, hash}, "-"))
|
||||
err := app.replaceLink(src, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hash = hashSHA256(name)
|
||||
link = filepath.Join(app.path, ".links", strings.Join([]string{kind, hash}, "-"))
|
||||
err = app.replaceLink(src, link)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (app *avatar) removeLinks(kind, name string) error {
|
||||
if !strings.ContainsRune(name, '@') {
|
||||
return nil
|
||||
}
|
||||
name = strings.ToLower(name)
|
||||
|
||||
hash := hashMD5(name)
|
||||
link := filepath.Join(app.path, ".links", strings.Join([]string{kind, hash}, "-"))
|
||||
err := os.Remove(link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hash = hashSHA256(name)
|
||||
link = filepath.Join(app.path, ".links", strings.Join([]string{kind, hash}, "-"))
|
||||
err = os.Remove(link)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (app *avatar) replaceLink(src, link string) error {
|
||||
if dst, err := os.Readlink(link); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
err = os.Symlink(src, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if dst != src {
|
||||
err = os.Remove(link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = os.Symlink(src, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fileExists(filename string) bool {
|
||||
info, err := os.Stat(filename)
|
||||
if os.IsNotExist(err) {
|
||||
return false
|
||||
}
|
||||
return !info.IsDir()
|
||||
}
|
||||
|
||||
func sizeByKind(kind string, size int) (sizeW int, sizeH int, resize bool) {
|
||||
switch kind {
|
||||
case "avatar":
|
||||
if size == 0 {
|
||||
size = 128
|
||||
}
|
||||
sizeW = clamp(128, 640, size)
|
||||
sizeH = sizeW
|
||||
resize = true
|
||||
|
||||
return
|
||||
case "cover":
|
||||
if size == 0 {
|
||||
size = 940
|
||||
}
|
||||
|
||||
sizeW = clamp(640, 1300, size)
|
||||
sizeH = ratio(sizeW, 2.7)
|
||||
resize = true
|
||||
|
||||
return
|
||||
default:
|
||||
return 0, 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func ratio(size int, ratio float64) int {
|
||||
return int(float64(size) / ratio)
|
||||
}
|
||||
func clamp(min, max, size int) int {
|
||||
if size > max {
|
||||
return max
|
||||
}
|
||||
|
||||
if size < min {
|
||||
return min
|
||||
}
|
||||
|
||||
return size
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
37
pkg/app/dns/dns.go
Normal file
37
pkg/app/dns/dns.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package app_dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
)
|
||||
|
||||
type app struct {
|
||||
resolver *net.Resolver
|
||||
}
|
||||
|
||||
func New(ctx context.Context) *app {
|
||||
return &app{resolver: net.DefaultResolver}
|
||||
}
|
||||
func (app *app) getDNS(w http.ResponseWriter, r *http.Request) {
|
||||
domain := chi.URLParam(r, "domain")
|
||||
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
|
||||
res, err := app.resolver.LookupTXT(r.Context(), domain)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
|
||||
fmt.Fprintln(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Fprintln(w, strings.Join(res, "\n"))
|
||||
}
|
||||
func (app *app) Routes(r *chi.Mux) {
|
||||
r.MethodFunc("GET", "/dns/{domain}", app.getDNS)
|
||||
}
|
||||
314
pkg/app/keyproofs/app.go
Normal file
314
pkg/app/keyproofs/app.go
Normal file
@@ -0,0 +1,314 @@
|
||||
package app_keyproofs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
zlog "github.com/rs/zerolog/log"
|
||||
"github.com/russross/blackfriday"
|
||||
"github.com/skip2/go-qrcode"
|
||||
|
||||
"github.com/sour-is/keyproofs/pkg/cache"
|
||||
"github.com/sour-is/keyproofs/pkg/config"
|
||||
"github.com/sour-is/keyproofs/pkg/opgp"
|
||||
"github.com/sour-is/keyproofs/pkg/opgp/entity"
|
||||
"github.com/sour-is/keyproofs/pkg/promise"
|
||||
"github.com/sour-is/keyproofs/pkg/style"
|
||||
)
|
||||
|
||||
var expireAfter = 20 * time.Minute
|
||||
var runnerTimeout = 30 * time.Second
|
||||
|
||||
// 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.Style{
|
||||
Avatar: pixl,
|
||||
Cover: pixl,
|
||||
Background: pixl,
|
||||
Palette: style.GetPalette("#93CCEA"),
|
||||
}
|
||||
|
||||
type keyproofApp struct {
|
||||
cache cache.Cacher
|
||||
tasker promise.Tasker
|
||||
}
|
||||
|
||||
func NewKeyProofApp(ctx context.Context, c cache.Cacher) *keyproofApp {
|
||||
return &keyproofApp{
|
||||
cache: c,
|
||||
tasker: promise.NewRunner(
|
||||
ctx,
|
||||
promise.Timeout(runnerTimeout),
|
||||
promise.WithCache(c, expireAfter),
|
||||
),
|
||||
}
|
||||
}
|
||||
func (app *keyproofApp) Routes(r *chi.Mux) {
|
||||
r.MethodFunc("GET", "/", app.getHome)
|
||||
r.MethodFunc("GET", "/id/{id}", app.getProofs)
|
||||
r.MethodFunc("GET", "/qr", app.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 (app *keyproofApp) getProofs(w http.ResponseWriter, r *http.Request) {
|
||||
log := zlog.Ctx(r.Context())
|
||||
cfg := config.FromContext(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 := app.tasker.Run(entity.Key(id), func(q promise.Q) {
|
||||
ctx := q.Context()
|
||||
log := zlog.Ctx(ctx).With().Interface(fmtKey(q), q.Key()).Logger()
|
||||
|
||||
key := q.Key().(entity.Key)
|
||||
|
||||
e, err := opgp.GetKey(ctx, string(key))
|
||||
if err != nil {
|
||||
q.Reject(err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().Msg("Resolving Entity")
|
||||
q.Resolve(e)
|
||||
})
|
||||
|
||||
task.After(func(q promise.ResultQ) {
|
||||
entity := q.Result().(*entity.Entity)
|
||||
|
||||
zlog.Ctx(q.Context()).
|
||||
Info().
|
||||
Str("email", entity.Primary.Address).
|
||||
Interface(fmtKey(q), q.Key()).
|
||||
Msg("Do Style ")
|
||||
|
||||
q.Run(style.Key(entity.Primary.Address), func(q promise.Q) {
|
||||
ctx := q.Context()
|
||||
log := zlog.Ctx(ctx).With().Interface(fmtKey(q), q.Key()).Logger()
|
||||
|
||||
key := q.Key().(style.Key)
|
||||
|
||||
log.Debug().Msg("start task")
|
||||
style, err := style.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.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}
|
||||
page.AppName = fmt.Sprintf("%s v%s", cfg.GetString("app-name"), cfg.GetString("app-version"))
|
||||
page.AppBuild = fmt.Sprintf("%s %s", cfg.GetString("build-date"), cfg.GetString("build-hash"))
|
||||
|
||||
// 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.Entity)
|
||||
|
||||
case <-ctx.Done():
|
||||
log.Print("Deadline Timeout")
|
||||
if e, ok := app.cache.Get(entity.Key(id)); ok {
|
||||
page.Entity = e.Value().(*entity.Entity)
|
||||
}
|
||||
}
|
||||
|
||||
// Build page based on available information.
|
||||
if page.Entity != nil {
|
||||
var gotStyle, gotProofs bool
|
||||
|
||||
if s, ok := app.cache.Get(style.Key(page.Entity.Primary.Address)); ok {
|
||||
page.Style = s.Value().(*style.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 := app.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.
|
||||
var err error
|
||||
t := template.New("page")
|
||||
t, err = t.Parse(pageTPL)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
t, err = t.Parse(proofTPL)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = t.Execute(w, page)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
func (app *keyproofApp) getHome(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
cfg := config.FromContext(ctx)
|
||||
|
||||
baseURL := cfg.GetString("base-url")
|
||||
if id := r.URL.Query().Get("id"); id != "" {
|
||||
http.Redirect(w, r, fmt.Sprintf("%s/id/%s", baseURL, id), http.StatusFound)
|
||||
return
|
||||
}
|
||||
|
||||
page := page{Style: defaultStyle, IsComplete: true, Markdown: homeMKDN}
|
||||
page.AppName = fmt.Sprintf("%s v%s", cfg.GetString("app-name"), cfg.GetString("app-version"))
|
||||
|
||||
// Template and display.
|
||||
var err error
|
||||
t := template.New("page")
|
||||
t = t.Funcs(template.FuncMap{"markDown": markDowner})
|
||||
t, err = t.Parse(pageTPL)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
t, err = t.Parse(homeTPL)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = t.Execute(w, page)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
func (app *keyproofApp) 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 markDowner(args ...interface{}) template.HTML {
|
||||
s := blackfriday.MarkdownCommon([]byte(fmt.Sprintf("%s", args...)))
|
||||
return template.HTML(s)
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
|
||||
func fmtKey(key promise.Key) string {
|
||||
return fmt.Sprintf("%T", key.Key())
|
||||
}
|
||||
456
pkg/app/keyproofs/proofs.go
Normal file
456
pkg/app/keyproofs/proofs.go
Normal file
@@ -0,0 +1,456 @@
|
||||
package app_keyproofs
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"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}
|
||||
}
|
||||
|
||||
case strings.Contains(p.URI.Path, "/conv/"), strings.Contains(p.URI.Path, "/twt/"):
|
||||
if sp := strings.SplitN(p.URI.Path, "/", 3); len(sp) == 3 {
|
||||
p.Icon = "fas fa-comment-alt"
|
||||
p.Service = "Twtxt"
|
||||
p.Name = fmt.Sprintf("...@%s", p.URI.Host)
|
||||
p.Link = fmt.Sprintf("https://%s", p.URI.Host)
|
||||
|
||||
url := fmt.Sprintf("https://%s/api/v1/conv", p.URI.Host)
|
||||
return &twtxtResolve{p, url, sp[2], 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 (r *gitlabResolve) Proof() *Proof {
|
||||
return &r.proof
|
||||
}
|
||||
|
||||
func (p *Proof) Resolve(ctx context.Context) error {
|
||||
return fmt.Errorf("Not Implemented")
|
||||
}
|
||||
func (p *Proof) Proof() *Proof {
|
||||
return p
|
||||
}
|
||||
|
||||
type twtxtResolve struct {
|
||||
proof Proof `json:"-"`
|
||||
url string `json:"-"`
|
||||
Hash string `json:"hash"`
|
||||
headers map[string]string `json:"-"`
|
||||
}
|
||||
|
||||
func (t *twtxtResolve) Resolve(ctx context.Context) error {
|
||||
t.proof.Status = ProofInvalid
|
||||
|
||||
twt := struct {
|
||||
Twts []struct {
|
||||
Text string `json:"text"`
|
||||
Twter struct{ Nick string }
|
||||
} `json:"twts"`
|
||||
}{}
|
||||
|
||||
if err := postJSON(ctx, t.url, nil, t, &twt); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(twt.Twts) > 0 {
|
||||
nick := twt.Twts[0].Twter.Nick
|
||||
t.proof.Name = fmt.Sprintf("%s@%s", nick, t.proof.URI.Host)
|
||||
t.proof.Link += "/user/" + nick
|
||||
|
||||
ck := fmt.Sprintf("[Verifying my OpenPGP key: openpgp4fpr:%s]", t.proof.Fingerprint)
|
||||
if strings.Contains(twt.Twts[0].Text, ck) {
|
||||
t.proof.Status = ProofVerified
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return ErrNoFingerprint
|
||||
}
|
||||
func (t *twtxtResolve) Proof() *Proof {
|
||||
return &t.proof
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func postJSON(ctx context.Context, uri string, hdr map[string]string, payload, dst interface{}) error {
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
log.Info().Str("URI", uri).Msg("postJSON")
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
return err
|
||||
}
|
||||
buf := bytes.NewBuffer(body)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", uri, buf)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
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)
|
||||
}
|
||||
280
pkg/app/keyproofs/template.go
Normal file
280
pkg/app/keyproofs/template.go
Normal file
@@ -0,0 +1,280 @@
|
||||
package app_keyproofs
|
||||
|
||||
import (
|
||||
"github.com/sour-is/keyproofs/pkg/opgp/entity"
|
||||
"github.com/sour-is/keyproofs/pkg/style"
|
||||
)
|
||||
|
||||
type page struct {
|
||||
AppName string
|
||||
AppBuild string
|
||||
Entity *entity.Entity
|
||||
Style *style.Style
|
||||
Proofs *Proofs
|
||||
|
||||
Markdown string
|
||||
HasProofs bool
|
||||
IsComplete bool
|
||||
Err error
|
||||
}
|
||||
|
||||
var pageTPL = `
|
||||
<html>
|
||||
<head>
|
||||
{{if not .IsComplete}}<meta http-equiv="refresh" content="1">{{end}}
|
||||
|
||||
<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>
|
||||
@font-face { font-family: "Font Awesome 5 Free"; font-weight: 900; src: url(https://pagecdn.io/lib/font-awesome/5.14.0/webfonts/fa-solid-900.woff2); }
|
||||
@font-face { font-family: "Font Awesome 5 Free"; font-weight: 400; src: url(https://pagecdn.io/lib/font-awesome/5.14.0/webfonts/fa-regular-400.woff2); }
|
||||
@font-face { font-family: "Font Awesome 5 Brands"; src: url(https://pagecdn.io/lib/font-awesome/5.14.0/webfonts/fa-brands-400.woff2); }
|
||||
|
||||
{{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; }
|
||||
.scroll { height: 20em; overflow: scroll; }
|
||||
|
||||
@media only screen and (max-width: 991px) {
|
||||
.jumbotron h1 { font-size: 2rem; }
|
||||
.jumbotron .lead { font-size: 1.0rem; }
|
||||
}
|
||||
|
||||
@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% }
|
||||
.jumbotron h1 { font-size: 2rem; }
|
||||
.jumbotron .lead { font-size: 1.0rem; }
|
||||
}
|
||||
|
||||
@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% }
|
||||
.jumbotron .lead { font-size: 0.8rem; }
|
||||
body { font-size: 0.8rem; }
|
||||
}
|
||||
</style>
|
||||
{{end}}
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
{{template "content" .}}
|
||||
|
||||
<div class="card-footer text-muted text-center">
|
||||
<a href="/" alt="{{.AppBuild}}">{{.AppName}}</a>
|
||||
| © 2020 Sour.is
|
||||
| <a href="/id/me@sour.is">About me</a>
|
||||
| <a href="https://github.com/sour-is/keyproofs">GitHub</a>
|
||||
| Inspired by <a href="https://keyoxide.org/">keyoxide</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
var homeTPL = `
|
||||
{{define "content"}}
|
||||
<div class="jumbotron heading">
|
||||
<div class="container">
|
||||
<div class="row shade">
|
||||
<div class="col-md">
|
||||
<h1 class="display-8 fg-color-8">Key Proofs</h1>
|
||||
<p class="lead fg-color-11">Verify social identitys using OpenPGP</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<br/>
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<form method="GET" action="/">
|
||||
<div class="input-group mb-3">
|
||||
<input type="text"
|
||||
name="id"
|
||||
class="form-control"
|
||||
placeholder="Email or Fingerprint..."
|
||||
aria-label="Email or Fingerprint"
|
||||
aria-describedby="button-addon" />
|
||||
<div class="input-group-append">
|
||||
<button class="btn btn-outline-secondary" type="submit" id="button-addon">GO</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container"> {{.Markdown | markDown}} </div>
|
||||
{{end}}
|
||||
`
|
||||
|
||||
var proofTPL = `
|
||||
{{define "content"}}
|
||||
<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">
|
||||
<div class="row">
|
||||
<div class="col-lg-4 col-md-12 col-sm-12 col-xs-12">
|
||||
{{ 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>
|
||||
<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"}}
|
||||
<br/>
|
||||
<img src="/qr?s=-2&c={{.Link}}" alt="qrcode" style="width:88px; height:88px">
|
||||
{{end}}
|
||||
</div>
|
||||
</li>
|
||||
{{end}}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="card">
|
||||
<div class="card-header">Proofs</div>
|
||||
<div class="card-body">Loading...</div>
|
||||
</div>
|
||||
<br/>
|
||||
{{end}}
|
||||
{{end}}
|
||||
<div class="col-lg-8 col-md-12 col-sm-12 col-xs-12">
|
||||
<div class="card">
|
||||
<div class="card-header">Public Key</div>
|
||||
<div class="card-body scroll">
|
||||
<pre><code>
|
||||
Last Updated {{.Entity.SelfSignature.CreationTime}}
|
||||
|
||||
{{.Entity.ArmorText}}
|
||||
</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
`
|
||||
|
||||
var homeMKDN = `
|
||||
## About Keyproofs
|
||||
|
||||
KeyProofs is a server side version of Keyoxide. There is no JavaScript executed on this page and resourcesKeys are looked up via [Web key directory](https://datatracker.ietf.org/doc/draft-koch-openpgp-webkey-service/)
|
||||
or from <https://keys.openpgp.org/>.
|
||||
|
||||
|
||||
### Decentralized online identity proofs
|
||||
|
||||
- You decide which accounts are linked together
|
||||
- You decide where this data is stored
|
||||
- KeyProofs does not store your identity data on its servers
|
||||
- KeyProofs merely verifies the identity proofs and displays them
|
||||
|
||||
### Empowering the internet citizen
|
||||
|
||||
- A verified identity proof proves ownership of an account and builds trust
|
||||
- No bad actor can impersonate you as long as your accounts aren't compromised
|
||||
- Your online identity data is safe from greedy internet corporations
|
||||
|
||||
### User-centric platform
|
||||
|
||||
- KeyProofs generates QR codes that integrate with OpenKeychain and Conversations
|
||||
- KeyProofs fetches the key wherever the user decides to store it
|
||||
- KeyProofs is self-hostable, meaning you could put it on any server you trust
|
||||
|
||||
### Secure and privacy-friendly
|
||||
|
||||
- KeyProofs doesn't want your personal data, track you or show you ads
|
||||
- KeyProofs relies on OpenPGP, a widely used public-key cryptography standard (RFC-4880)
|
||||
- Cryptographic operations are performed on server.
|
||||
`
|
||||
48
pkg/app/vcard/app.go
Normal file
48
pkg/app/vcard/app.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package app_vcard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"gosrc.io/xmpp"
|
||||
)
|
||||
|
||||
type app struct {
|
||||
conn *connection
|
||||
}
|
||||
|
||||
func New(ctx context.Context, xmppConfig *xmpp.Config) (*app, error) {
|
||||
conn, err := NewXMPP(ctx, xmppConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &app{conn: conn}, nil
|
||||
}
|
||||
func (app *app) Routes(r *chi.Mux) {
|
||||
r.MethodFunc("GET", "/vcard/{jid}", app.getVCard)
|
||||
}
|
||||
func (app *app) getVCard(w http.ResponseWriter, r *http.Request) {
|
||||
jid := chi.URLParam(r, "jid")
|
||||
if _, err := mail.ParseAddress(jid); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprint(w, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
vcard, err := app.conn.GetXMPPVCard(r.Context(), jid)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprint(w, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/xml")
|
||||
w.WriteHeader(200)
|
||||
fmt.Fprint(w, vcard)
|
||||
}
|
||||
36
pkg/app/vcard/vcard.go
Normal file
36
pkg/app/vcard/vcard.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package app_vcard
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
|
||||
"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{})
|
||||
}
|
||||
76
pkg/app/vcard/xmpp.go
Normal file
76
pkg/app/vcard/xmpp.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package app_vcard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/sour-is/keyproofs/pkg/graceful"
|
||||
"gosrc.io/xmpp"
|
||||
"gosrc.io/xmpp/stanza"
|
||||
)
|
||||
|
||||
type connection struct {
|
||||
client xmpp.StreamClient
|
||||
}
|
||||
|
||||
func NewXMPP(ctx context.Context, config *xmpp.Config) (*connection, error) {
|
||||
log := log.Ctx(ctx)
|
||||
wg := graceful.WaitGroup(ctx)
|
||||
|
||||
router := xmpp.NewRouter()
|
||||
conn := &connection{}
|
||||
|
||||
cl, err := xmpp.NewClient(config, router, func(err error) { log.Error().Err(err).Send() })
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn.client = cl
|
||||
|
||||
sc := xmpp.NewStreamManager(cl, func(c xmpp.Sender) { log.Info().Msg("XMPP Client connected.") })
|
||||
|
||||
wg.Go(func() error {
|
||||
log.Debug().Msg("starting XMPP")
|
||||
return sc.Run()
|
||||
})
|
||||
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
sc.Stop()
|
||||
log.Info().Msg("XMPP Client shutdown.")
|
||||
}()
|
||||
|
||||
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)
|
||||
}
|
||||
390
pkg/app/wkd/app.go
Normal file
390
pkg/app/wkd/app.go
Normal file
@@ -0,0 +1,390 @@
|
||||
package app_wkd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/sour-is/crypto/openpgp"
|
||||
"github.com/tv42/zbase32"
|
||||
|
||||
"github.com/sour-is/keyproofs/pkg/graceful"
|
||||
"github.com/sour-is/keyproofs/pkg/opgp/entity"
|
||||
)
|
||||
|
||||
type wkdApp struct {
|
||||
path string
|
||||
domain string
|
||||
}
|
||||
|
||||
func New(ctx context.Context, path, domain string) (*wkdApp, error) {
|
||||
log := log.Ctx(ctx)
|
||||
log.Debug().Str("domain", domain).Str("path", path).Msg("NewWKDApp")
|
||||
|
||||
path = filepath.Clean(path)
|
||||
app := &wkdApp{path: path, domain: domain}
|
||||
err := app.CheckFiles(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
watch, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, typ := range []string{"keys"} {
|
||||
err = watch.Add(filepath.Join(path, typ))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug().Msg("startup wkd watcher")
|
||||
wg := graceful.WaitGroup(ctx)
|
||||
wg.Go(func() error {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Debug().Msg("shutdown wkd watcher")
|
||||
return nil
|
||||
case op := <-watch.Events:
|
||||
log.Print(op)
|
||||
switch op.Op {
|
||||
case fsnotify.Create:
|
||||
path = filepath.Dir(op.Name)
|
||||
kind := filepath.Base(path)
|
||||
name := filepath.Base(op.Name)
|
||||
if err := app.createLinks(kind, name); err != nil {
|
||||
log.Err(err).Send()
|
||||
}
|
||||
case fsnotify.Remove, fsnotify.Rename:
|
||||
path = filepath.Dir(op.Name)
|
||||
kind := filepath.Base(path)
|
||||
name := filepath.Base(op.Name)
|
||||
if err := app.removeLinks(kind, name); err != nil {
|
||||
log.Error().Err(err).Send()
|
||||
}
|
||||
default:
|
||||
}
|
||||
case err := <-watch.Errors:
|
||||
log.Err(err).Send()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return app, nil
|
||||
}
|
||||
|
||||
func (app *wkdApp) CheckFiles(ctx context.Context) error {
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
for _, name := range []string{".links", "keys"} {
|
||||
log.Debug().Msgf("mkdir: %s", filepath.Join(app.path, name))
|
||||
err := os.MkdirAll(filepath.Join(app.path, name), 0700)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return filepath.Walk(app.path, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Debug().Msg(info.Name())
|
||||
if path == app.path {
|
||||
return nil
|
||||
}
|
||||
if info.IsDir() {
|
||||
switch info.Name() {
|
||||
case "keys":
|
||||
return nil
|
||||
}
|
||||
return filepath.SkipDir
|
||||
|
||||
}
|
||||
|
||||
path = filepath.Dir(path)
|
||||
kind := filepath.Base(path)
|
||||
name := info.Name()
|
||||
|
||||
log.Debug().Msgf("link: %s %s %s", app.path, kind, name)
|
||||
|
||||
return app.createLinks(kind, name)
|
||||
})
|
||||
}
|
||||
|
||||
func (app *wkdApp) getRedirect(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
log.Print(r.Host)
|
||||
|
||||
hash := chi.URLParam(r, "hash")
|
||||
|
||||
if strings.ContainsRune(hash, '@') {
|
||||
hash, domain := hashHuman(hash)
|
||||
log.Debug().Str("hash", hash).Str("domain", domain).Msg("redirect")
|
||||
if host, adv := getWKDDomain(ctx, domain); adv {
|
||||
log.Debug().Str("host", host).Str("domain", domain).Bool("adv", adv).Msg("redirect")
|
||||
http.Redirect(w, r, fmt.Sprintf("https://%s/.well-known/openpgpkey/hu/%s/%s", host, domain, hash), http.StatusTemporaryRedirect)
|
||||
} else {
|
||||
log.Debug().Str("host", host).Str("domain", domain).Bool("adv", adv).Msg("redirect")
|
||||
http.Redirect(w, r, fmt.Sprintf("https://%s/.well-known/openpgpkey/hu/%s", domain, hash), http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
writeText(w, http.StatusBadRequest, "Bad Request")
|
||||
}
|
||||
|
||||
func (app *wkdApp) get(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
log.Print(r.Host)
|
||||
|
||||
hash := chi.URLParam(r, "hash")
|
||||
domain := chi.URLParam(r, "domain")
|
||||
if domain == "" {
|
||||
domain = app.domain
|
||||
}
|
||||
|
||||
if strings.ContainsRune(hash, '@') {
|
||||
hash, domain = hashHuman(hash)
|
||||
}
|
||||
|
||||
fname := filepath.Join(app.path, ".links", strings.Join([]string{"keys", domain, hash}, "-"))
|
||||
log.Debug().Msgf("path: %s", fname)
|
||||
|
||||
f, err := os.Open(fname)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
_, err = io.Copy(w, f)
|
||||
if err != nil {
|
||||
writeText(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (app *wkdApp) Routes(r *chi.Mux) {
|
||||
r.MethodFunc("GET", "/wkd/{hash}", app.getRedirect)
|
||||
r.MethodFunc("GET", "/key/{hash}", app.get)
|
||||
r.MethodFunc("POST", "/pks/add", app.postKey)
|
||||
r.MethodFunc("GET", "/.well-known/openpgpkey/hu/{hash}", app.get)
|
||||
r.MethodFunc("GET", "/.well-known/openpgpkey/hu/{domain}/{hash}", app.get)
|
||||
}
|
||||
|
||||
func (app *wkdApp) createLinks(kind, name string) error {
|
||||
if !strings.ContainsRune(name, '@') {
|
||||
return nil
|
||||
}
|
||||
|
||||
src := filepath.Join("..", kind, name)
|
||||
name = strings.ToLower(name)
|
||||
|
||||
hash, domain := hashHuman(name)
|
||||
link := filepath.Join(app.path, ".links", strings.Join([]string{kind, domain, hash}, "-"))
|
||||
err := app.replaceLink(src, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
func hashHuman(name string) (string, string) {
|
||||
name = strings.ToLower(name)
|
||||
parts := strings.SplitN(name, "@", 2)
|
||||
hash := sha1.Sum([]byte(parts[0]))
|
||||
lp := zbase32.EncodeToString(hash[:])
|
||||
|
||||
return lp, parts[1]
|
||||
}
|
||||
|
||||
func (app *wkdApp) removeLinks(kind, name string) error {
|
||||
if !strings.ContainsRune(name, '@') {
|
||||
return nil
|
||||
}
|
||||
name = strings.ToLower(name)
|
||||
|
||||
hash, domain := hashHuman(name)
|
||||
link := filepath.Join(app.path, ".links", strings.Join([]string{kind, domain, hash}, "-"))
|
||||
err := os.Remove(link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (app *wkdApp) replaceLink(src, link string) error {
|
||||
if dst, err := os.Readlink(link); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
err = os.Symlink(src, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if dst != src {
|
||||
err = os.Remove(link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = os.Symlink(src, link)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getWKDDomain(ctx context.Context, domain string) (string, bool) {
|
||||
adv := "openpgpkey." + domain
|
||||
_, err := net.DefaultResolver.LookupCNAME(ctx, adv)
|
||||
if err == nil {
|
||||
return adv, true
|
||||
}
|
||||
return domain, false
|
||||
}
|
||||
|
||||
func (app *wkdApp) postKey(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
log := log.Ctx(ctx)
|
||||
|
||||
body, err := ioutil.ReadAll(r.Body)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusBadRequest, "ERR BODY")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
q, err := url.ParseQuery(string(body))
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusBadRequest, "ERR PARSE")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
lis, err := openpgp.ReadArmoredKeyRing(strings.NewReader(q.Get("keytext")))
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusBadRequest, "ERR READ KEY")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
e, err := entity.GetOne(lis)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusBadRequest, "ERR ENTITY")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fname := filepath.Join(app.path, "keys", e.Primary.Address)
|
||||
|
||||
f, err := os.Open(fname)
|
||||
if os.IsNotExist(err) {
|
||||
out, err := os.Create(fname)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusInternalServerError, "ERR CREATE")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = e.Serialize(out)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusInternalServerError, "ERR WRITE")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("X-HKP-Status", "Created key")
|
||||
writeText(w, http.StatusOK, "OK CREATED")
|
||||
return
|
||||
}
|
||||
|
||||
current, err := openpgp.ReadKeyRing(f)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusInternalServerError, "ERR READ")
|
||||
|
||||
return
|
||||
}
|
||||
f.Close()
|
||||
|
||||
compare, err := entity.GetOne(current)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusInternalServerError, "ERR PARSE")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if e.Fingerprint != compare.Fingerprint {
|
||||
w.Header().Set("X-HKP-Status", "Mismatch fingerprint")
|
||||
writeText(w, http.StatusBadRequest, "ERR FINGERPRINT")
|
||||
return
|
||||
}
|
||||
if e.SelfSignature == nil || compare.SelfSignature == nil {
|
||||
w.Header().Set("X-HKP-Status", "Missing signature")
|
||||
writeText(w, http.StatusBadRequest, "ERR SIGNATURE")
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug().Msgf("%v < %v", e.SelfSignature.CreationTime, compare.SelfSignature.CreationTime)
|
||||
|
||||
if !compare.SelfSignature.CreationTime.Before(e.SelfSignature.CreationTime) {
|
||||
w.Header().Set("X-HKP-Status", "out of date")
|
||||
writeText(w, http.StatusBadRequest, "ERR OUT OF DATE")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
out, err := os.Create(fname)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusInternalServerError, "ERR CREATE")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = e.Serialize(out)
|
||||
if err != nil {
|
||||
log.Err(err).Send()
|
||||
writeText(w, http.StatusInternalServerError, "ERR WRITE")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("X-HKP-Status", "Updated key")
|
||||
writeText(w, http.StatusOK, "OK UPDATED")
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
Reference in New Issue
Block a user