Add sessions using LNURL-auth

This commit is contained in:
ekzyis 2023-09-09 22:52:50 +02:00
parent 54574d2e7e
commit 9440f58efe
14 changed files with 383 additions and 16 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
# go executable
delphi.market
.env

67
auth.go Normal file
View File

@ -0,0 +1,67 @@
package main
import (
"crypto/ecdsa"
"crypto/rand"
"encoding/hex"
"fmt"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcutil/bech32"
)
type LnAuth struct {
k1 string
lnurl string
}
type LnAuthResponse struct {
K1 string `query:"k1"`
Sig string `query:"sig"`
Key string `query:"key"`
}
type Session struct {
pubkey string
}
func lnAuth() (*LnAuth, error) {
k1 := make([]byte, 32)
_, err := rand.Read(k1)
if err != nil {
return nil, fmt.Errorf("rand.Read error: %w", err)
}
k1hex := hex.EncodeToString(k1)
url := []byte(fmt.Sprintf("https://delphi.market/api/login?tag=login&k1=%s&action=login", k1hex))
conv, err := bech32.ConvertBits(url, 8, 5, true)
if err != nil {
return nil, fmt.Errorf("bech32.ConvertBits error: %w", err)
}
lnurl, err := bech32.Encode("lnurl", conv)
if err != nil {
return nil, fmt.Errorf("bech32.Encode error: %w", err)
}
return &LnAuth{k1hex, lnurl}, nil
}
func lnAuthVerify(r *LnAuthResponse) (bool, error) {
var k1Bytes, sigBytes, keyBytes []byte
k1Bytes, err := hex.DecodeString(r.K1)
if err != nil {
return false, fmt.Errorf("k1 decode error: %w", err)
}
sigBytes, err = hex.DecodeString(r.Sig)
if err != nil {
return false, fmt.Errorf("sig decode error: %w", err)
}
keyBytes, err = hex.DecodeString(r.Key)
if err != nil {
return false, fmt.Errorf("key decode error: %w", err)
}
key, err := btcec.ParsePubKey(keyBytes)
if err != nil {
return false, fmt.Errorf("key parse error: %w", err)
}
ecdsaKey := ecdsa.PublicKey{Curve: btcec.S256(), X: key.X(), Y: key.Y()}
return ecdsa.VerifyASN1(&ecdsaKey, k1Bytes, sigBytes), nil
}

40
db.go Normal file
View File

@ -0,0 +1,40 @@
package main
import (
"database/sql"
"log"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"github.com/namsral/flag"
)
var (
DbUrl string
db *sql.DB
)
func init() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
flag.StringVar(&DbUrl, "DATABASE_URL", "", "Database URL")
flag.Parse()
validateFlags()
db = initDb()
}
func initDb() *sql.DB {
db, err := sql.Open("postgres", DbUrl)
if err != nil {
log.Fatal(err)
}
return db
}
func validateFlags() {
if DbUrl == "" {
log.Fatal("DATABASE_URL not set")
}
}

18
docker-compose.yml Normal file
View File

@ -0,0 +1,18 @@
services:
db:
image: postgres:15.3
container_name: delphi-db
environment:
POSTGRES_PASSWORD: delphi
POSTGRES_USER: delphi
POSTGRES_DB: delphi
PORT: 5432
# POSTGRES_HOST_AUTH_METHOD: trust
ports:
- 127.0.0.1:5432:5432
volumes:
- delphi:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
volumes:
delphi:

11
go.mod
View File

@ -2,13 +2,22 @@ module delphi.market
go 1.20 go 1.20
require github.com/labstack/echo/v4 v4.11.1 require (
github.com/btcsuite/btcd/btcec/v2 v2.3.2
github.com/btcsuite/btcutil v1.0.2
github.com/labstack/echo/v4 v4.11.1
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
)
require ( require (
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/labstack/gommon v0.4.0 // indirect github.com/labstack/gommon v0.4.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect github.com/mattn/go-isatty v0.0.19 // indirect
github.com/namsral/flag v1.7.4-pre // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect
golang.org/x/crypto v0.11.0 // indirect golang.org/x/crypto v0.11.0 // indirect

46
go.sum
View File

@ -1,12 +1,38 @@
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U=
github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
github.com/btcsuite/btcutil v1.0.2 h1:9iZ1Terx9fMIOtq1VrwdqfsATL9MC2l8ZrUY6YZ2uts=
github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
github.com/labstack/echo/v4 v4.11.1 h1:dEpLU2FLg4UVmvCGPuk/APjlH6GDpbEPti61srUUUs4= github.com/labstack/echo/v4 v4.11.1 h1:dEpLU2FLg4UVmvCGPuk/APjlH6GDpbEPti61srUUUs4=
github.com/labstack/echo/v4 v4.11.1/go.mod h1:YuYRTSM3CHs2ybfrL8Px48bO6BAnYIN4l8wSTMP6BDQ= github.com/labstack/echo/v4 v4.11.1/go.mod h1:YuYRTSM3CHs2ybfrL8Px48bO6BAnYIN4l8wSTMP6BDQ=
github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8=
github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
@ -14,8 +40,15 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/namsral/flag v1.7.4-pre h1:b2ScHhoCUkbsq0d2C15Mv+VU8bl8hAXV8arnWiOHNZs=
github.com/namsral/flag v1.7.4-pre/go.mod h1:OXldTctbM6SWH1K899kPZcf65KxJiD7MsceFUpB5yDo=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
@ -24,10 +57,19 @@ github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyC
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50=
golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@ -35,11 +77,15 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4=
golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

10
init.sql Normal file
View File

@ -0,0 +1,10 @@
CREATE TABLE lnauth(
k1 VARCHAR(64) NOT NULL PRIMARY KEY,
lnurl TEXT NOT NULL,
created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
session_id VARCHAR(48) NOT NULL DEFAULT encode(gen_random_uuid()::text::bytea, 'base64')
);
CREATE TABLE sessions(
pubkey TEXT NOT NULL,
session_id VARCHAR(48)
);

View File

@ -15,7 +15,6 @@
<header class="flex flex-row text-center justify-center pt-1"> <header class="flex flex-row text-center justify-center pt-1">
<nav> <nav>
<a href="/">home</a> <a href="/">home</a>
<a href="/login">login</a>
</nav> </nav>
</header> </header>
<div class="container flex flex-column text-center"> <div class="container flex flex-column text-center">

View File

@ -15,7 +15,6 @@
<header class="flex flex-row text-center justify-center pt-1"> <header class="flex flex-row text-center justify-center pt-1">
<nav> <nav>
<a href="/">home</a> <a href="/">home</a>
<a href="/login">login</a>
</nav> </nav>
</header> </header>
<div class="container flex flex-column text-center"> <div class="container flex flex-column text-center">

View File

@ -9,6 +9,9 @@ body {
justify-content: center; justify-content: center;
} }
nav {
display: flex;
}
a { a {
color: #8787a4; color: #8787a4;
text-decoration: underline; text-decoration: underline;
@ -20,6 +23,23 @@ a:hover {
nav > a { nav > a {
margin: 0 3px; margin: 0 3px;
} }
nav > form > button {
color: #8787a4;
text-decoration: underline;
border: none;
outline: none;
background: none;
cursor: pointer;
padding: 0;
text-decoration: underline;
font-family: inherit;
font-size: inherit;
margin: 0 3px;
}
nav > form > button:hover {
background: #8787A4;
color: #ffffff;
}
hr { hr {
border: none; border: none;
@ -84,3 +104,7 @@ ul {
.pt-1 { .pt-1 {
padding-top: 1em; padding-top: 1em;
} }
.word-wrap {
word-wrap: break-word;
}

116
router.go
View File

@ -1,13 +1,17 @@
package main package main
import ( import (
"database/sql"
"encoding/base64"
"fmt" "fmt"
"html/template" "html/template"
"io" "io"
"net/http" "net/http"
"os" "os"
"time"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/skip2/go-qrcode"
) )
type Template struct { type Template struct {
@ -19,11 +23,119 @@ func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Con
} }
func index(c echo.Context) error { func index(c echo.Context) error {
return c.Render(http.StatusOK, "index.html", map[string]string{"VERSION": VERSION, "COMMIT_LONG_SHA": COMMIT_LONG_SHA}) return c.Render(http.StatusOK, "index.html", map[string]any{"session": c.Get("session"), "VERSION": VERSION, "COMMIT_LONG_SHA": COMMIT_LONG_SHA})
} }
func login(c echo.Context) error { func login(c echo.Context) error {
return c.Render(http.StatusOK, "login.html", map[string]string{"user": ""}) lnauth, err := lnAuth()
if err != nil {
return err
}
var sessionId string
err = db.QueryRow("INSERT INTO lnauth(k1, lnurl) VALUES($1, $2) RETURNING session_id", lnauth.k1, lnauth.lnurl).Scan(&sessionId)
if err != nil {
return err
}
expires := time.Now().Add(60 * 60 * 24 * 365 * time.Second)
c.SetCookie(&http.Cookie{Name: "session", HttpOnly: true, Path: "/", Value: sessionId, Secure: true, Expires: expires})
png, err := qrcode.Encode(lnauth.lnurl, qrcode.Medium, 256)
if err != nil {
return err
}
qr := base64.StdEncoding.EncodeToString([]byte(png))
return c.Render(http.StatusOK, "login.html", map[string]any{"session": c.Get("session"), "lnurl": lnauth.lnurl, "qr": qr})
}
func verifyLogin(c echo.Context) error {
var query LnAuthResponse
if err := c.Bind(&query); err != nil {
c.Logger().Error(err)
return c.JSON(http.StatusBadRequest, map[string]string{"status": "ERROR", "reason": "bad request"})
}
var sessionId string
err := db.QueryRow("SELECT session_id FROM lnauth WHERE k1 = $1", query.K1).Scan(&sessionId)
if err == sql.ErrNoRows {
return c.JSON(http.StatusBadRequest, map[string]string{"status": "ERROR", "reason": "unknown k1"})
} else if err != nil {
c.Logger().Error(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"status": "ERROR", "reason": "internal server error"})
}
ok, err := lnAuthVerify(&query)
if err != nil {
c.Logger().Error(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"status": "ERROR", "reason": "internal server error"})
}
if !ok {
c.Logger().Error("bad signature")
return c.JSON(http.StatusUnauthorized, map[string]string{"status": "ERROR", "reason": "bad signature"})
}
_, err = db.Exec("INSERT INTO sessions(pubkey, session_id) VALUES($1, $2)", query.Key, sessionId)
if err != nil {
c.Logger().Error(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"status": "ERROR", "reason": "internal server error"})
}
_, err = db.Exec("DELETE FROM lnauth WHERE k1 = $1", query.K1)
if err != nil {
c.Logger().Error(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"status": "ERROR", "reason": "internal server error"})
}
return c.JSON(http.StatusOK, map[string]string{"status": "OK"})
}
func checkSession(c echo.Context) error {
cookie, err := c.Cookie("session")
if err != nil {
c.Logger().Error(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"status": "ERROR", "reason": "internal server error"})
}
sessionId := cookie.Value
var pubkey string
err = db.QueryRow("SELECT pubkey FROM sessions WHERE session_id = $1", sessionId).Scan(&pubkey)
if err == sql.ErrNoRows {
return c.JSON(http.StatusNotFound, map[string]string{"status": "Not Found", "message": "session not found"})
} else if err != nil {
c.Logger().Error(err)
return c.JSON(http.StatusInternalServerError, map[string]string{"status": "ERROR", "reason": "internal server error"})
}
return c.JSON(http.StatusOK, map[string]string{"pubkey": pubkey})
}
func sessionHandler(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cookie, err := c.Cookie("session")
if err != nil {
// cookie not found
return next(c)
}
sessionId := cookie.Value
var pubkey string
err = db.QueryRow("SELECT pubkey FROM sessions WHERE session_id = $1", sessionId).Scan(&pubkey)
if err == nil {
// session found
c.Set("session", Session{pubkey})
} else if err != sql.ErrNoRows {
c.Logger().Error(err)
}
// session not found
return next(c)
}
}
func logout(c echo.Context) error {
cookie, err := c.Cookie("session")
if err != nil {
// cookie not found
return c.Redirect(http.StatusSeeOther, "/")
}
sessionId := cookie.Value
_, err = db.Exec("DELETE FROM sessions where session_id = $1", sessionId)
if err != nil {
c.Logger().Error(err)
return err
}
// tell browser that cookie is expired and thus can be deleted
c.SetCookie(&http.Cookie{Name: "session", HttpOnly: true, Path: "/", Value: sessionId, Secure: true, Expires: time.Now()})
return c.Redirect(http.StatusSeeOther, "/")
} }
func serve500(c echo.Context) { func serve500(c echo.Context) {

View File

@ -45,10 +45,14 @@ func main() {
e.Renderer = t e.Renderer = t
e.GET("/", index) e.GET("/", index)
e.GET("/login", login) e.GET("/login", login)
e.GET("/api/login", verifyLogin)
e.GET("/api/session", checkSession)
e.POST("/logout", logout)
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "${time_custom} ${method} ${uri} ${status}\n", Format: "${time_custom} ${method} ${uri} ${status}\n",
CustomTimeFormat: "2006-01-02 15:04:05.00000-0700", CustomTimeFormat: "2006-01-02 15:04:05.00000-0700",
})) }))
e.Use(sessionHandler)
e.HTTPErrorHandler = httpErrorHandler e.HTTPErrorHandler = httpErrorHandler
err := e.Start(":8080") err := e.Start(":8080")
if err != http.ErrServerClosed { if err != http.ErrServerClosed {

View File

@ -15,7 +15,11 @@
<header class="flex flex-row text-center justify-center pt-1"> <header class="flex flex-row text-center justify-center pt-1">
<nav> <nav>
<a href="/">home</a> <a href="/">home</a>
<a href="/login">login</a> {{ if .session }}
<form action='/logout' method='post'>
<button type='submit'>logout</button>
</form>
{{ else }} <a href="/login">login</a> {{ end }}
</nav> </nav>
</header> </header>
<div class="container flex flex-column text-center"> <div class="container flex flex-column text-center">

View File

@ -15,24 +15,55 @@
<header class="flex flex-row text-center justify-center pt-1"> <header class="flex flex-row text-center justify-center pt-1">
<nav> <nav>
<a href="/">home</a> <a href="/">home</a>
<a href="/login">login</a> {{ if .session }} <a href="/login">login</a> {{ else }} <a href="/logout">logout</a> {{ end }}
</nav> </nav>
</header> </header>
<div class="container flex flex-column text-center"> <div class="container flex flex-column text-center justify-center">
<code> <code>
<strong> <strong>
<pre> <pre>
__ _____ ____ _ _
\ \ / /_ _| _ \ | | ___ __ _(_)_ __
\ \ /\ / / | || |_) | | |/ _ \ / _` | | '_ \
\ V V / | || __/ | | (_) | (_| | | | | |
\_/\_/ |___|_| </pre> |_|\___/ \__, |_|_| |_|
|___/ </pre>
</strong> </strong>
</code> </code>
<div class="font-mono mb-1">Work In Progress</div> <div id="lnauth-qr">
<div> <div class="mb-1">Login with Lightning</div>
{{if .user}} You are logged in as {{.user}} {{end}} <img class="m-auto mb-1" src="data:image/png;base64,{{.qr}}" width="33%"/>
<div class="font-mono word-wrap">{{.lnurl}}</div>
</div>
<div id="lnauth-success" hidden>
<div>Login successful</div>
<div>You are <span id="lnauth-pubkey" class="font-mono"></span></div>
<div id="lnauth-countdown">Redirecting in 3 ...</div>
</div> </div>
</div> </div>
</body> </body>
<script>
const qr = document.querySelector("#lnauth-qr")
const success = document.querySelector("#lnauth-success")
const pubkey = document.querySelector("#lnauth-pubkey")
const countdown = document.querySelector("#lnauth-countdown")
const interval = setInterval(async () => {
const body = await fetch(`/api/session`)
.then((r) => r.json())
.catch(console.error)
if (body.pubkey) {
qr.setAttribute("hidden", true)
pubkey.textContent = body.pubkey.slice(0, 10)
success.removeAttribute("hidden")
clearInterval(interval)
let timer = 2
const redirect = setInterval(() => {
countdown.textContent = `Redirecting in ${timer--} ...`
if (timer === -1) {
window.location.href = "https://delphi.market/";
}
}, 1000)
}
}, 1000)
</script>
</html> </html>