Compare commits

...

10 commits

Author SHA1 Message Date
arzumify
88e55fd76b Try to fix the cursed subdomain architecture 2024-10-20 19:51:48 +01:00
arzumify
3d05173883 Update packages 2024-10-20 18:30:34 +01:00
Arzumify
b8eeb98804 Update to latest fulgens version 2024-10-15 20:34:22 +01:00
Arzumify
59c05d8248 Updated libraries 2024-10-15 19:08:33 +01:00
Arzumify
74ef3b9030 Updated fulgens library 2024-10-15 19:06:36 +01:00
Arzumify
a9ede05d37 Updated fulgens library, fixed SQL data types 2024-10-15 14:32:13 +01:00
Arzumify
d3b0aec1b9 Got rid of unneeded deferration of the body 2024-10-05 10:19:23 +01:00
Arzumify
677a89445a Updated /x/net 2024-10-04 19:49:11 +01:00
Arzumify
d35922b296 Added oauth, fixed pretty much everything that exists 2024-10-04 19:47:49 +01:00
Arzumify
d4b99ccbc8 Added some temporary static files 2024-10-03 19:14:41 +01:00
11 changed files with 1048 additions and 107 deletions

View file

@ -6,5 +6,7 @@ rm -rf "$resourceDir" || exit 1
rm -rf "$path/../../services/eternity-web.fgs" || exit 1
cd "$path" || exit 1
go build -o "$path/../../services/eternity-web.fgs" --buildmode=plugin -ldflags "-s -w" || exit 1
cd "$path/resources/wasm/oauth" || exit 1
GOOS=js GOARCH=wasm go build -o "$resourceDir/static/wasm/oauth.wasm" -ldflags "-s -w" || exit 1
cp -r "$path/resources/static" "$resourceDir/" || exit 1
cp -r "$path/resources/templates" "$resourceDir/" || exit 1

21
go.mod
View file

@ -1,10 +1,12 @@
module git.oreonproject.org/oreon/eternity-web
module git.oreonproject.org/oreonproject/eternity-web
go 1.23.1
require (
git.ailur.dev/ailur/fg-library v0.0.0-20241003180318-4ddf4f56f935
git.oreonproject.org/oreonproject/eternity v0.0.0-20241002170712-a05c59b04471
git.ailur.dev/ailur/fg-library/v2 v2.1.0
git.ailur.dev/ailur/fg-nucleus-library v1.0.2
git.oreonproject.org/oreonproject/eternity v1.0.0
github.com/go-chi/chi/v5 v5.1.0
github.com/go-git/go-git/v5 v5.12.0
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
@ -16,25 +18,24 @@ require (
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/go-crypto v1.0.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudflare/circl v1.4.0 // indirect
github.com/cyphar/filepath-securejoin v0.3.3 // indirect
github.com/cloudflare/circl v1.5.0 // indirect
github.com/cyphar/filepath-securejoin v0.3.4 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/fatih/color v1.17.0 // indirect
github.com/go-chi/chi/v5 v5.1.0 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
github.com/go-git/go-billy/v5 v5.5.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/klauspost/compress v1.17.10 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pjbgf/sha1cd v0.3.0 // indirect
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
github.com/skeema/knownhosts v1.3.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
golang.org/x/crypto v0.27.0 // indirect
golang.org/x/net v0.29.0 // indirect
golang.org/x/sys v0.25.0 // indirect
golang.org/x/crypto v0.28.0 // indirect
golang.org/x/net v0.30.0 // indirect
golang.org/x/sys v0.26.0 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
)

42
go.sum
View file

@ -1,9 +1,17 @@
dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
git.ailur.dev/ailur/fg-library v0.0.0-20241003180318-4ddf4f56f935 h1:CmKzDupKFyOi7g1eATrYz5sLU4o1HhG/LCyIH1sLdUE=
git.ailur.dev/ailur/fg-library v0.0.0-20241003180318-4ddf4f56f935/go.mod h1:hOUkxs2rRouSwNnNZlo7CsFVH12kmjqheyzPQ4to1N8=
git.oreonproject.org/oreonproject/eternity v0.0.0-20241002170712-a05c59b04471 h1:F7FEvmbI1hOm0r3orbaTXmio6NrjVDOgdPMQsedSlRY=
git.oreonproject.org/oreonproject/eternity v0.0.0-20241002170712-a05c59b04471/go.mod h1:bV3LgSwVeBAAHuB8hYCw+BQy5OabVtJ/lwVp9BNz3Jk=
git.ailur.dev/ailur/fg-library/v2 v2.0.0 h1:NanDV52W+NBu96v/HPDPGqH8NOxLp6MRrRdXLPEsgYw=
git.ailur.dev/ailur/fg-library/v2 v2.0.0/go.mod h1:1jYbWhabGcIwp7CkhHqvRwC8eP+nHv5BrXPe9NX2HE8=
git.ailur.dev/ailur/fg-library/v2 v2.0.1 h1:ltPYXf/Om0hnMD8gr1K5bkYrfHqKPSbb0hxa0wtTnZ0=
git.ailur.dev/ailur/fg-library/v2 v2.0.1/go.mod h1:1jYbWhabGcIwp7CkhHqvRwC8eP+nHv5BrXPe9NX2HE8=
git.ailur.dev/ailur/fg-library/v2 v2.1.0 h1:SsLZ56poM6GZPfV/ywU/8WDTelu2dtlPp6jzbEZ4hrA=
git.ailur.dev/ailur/fg-library/v2 v2.1.0/go.mod h1:1jYbWhabGcIwp7CkhHqvRwC8eP+nHv5BrXPe9NX2HE8=
git.ailur.dev/ailur/fg-nucleus-library v1.0.0 h1:TT1V4cfka+uUpvV1zU7bc4KXFkgnsI/sIvaZDDxXk+k=
git.ailur.dev/ailur/fg-nucleus-library v1.0.0/go.mod h1:m4gNSEypfgrUV8bXaR8NLB8zchUM59y0ellV1wp/C+I=
git.ailur.dev/ailur/fg-nucleus-library v1.0.2 h1:EWfeab+wJKaxx/Qg5TKpvZHicA0V/NilUv2g6W97rtg=
git.ailur.dev/ailur/fg-nucleus-library v1.0.2/go.mod h1:T2mdUiXlZqb917CkNB2vwujkD/QhJDpCHLRvKuskBpY=
git.oreonproject.org/oreonproject/eternity v1.0.0 h1:EHKJsLI84+L/yFz8yECys0AZCUn0bnGNSoD7KpXzgYY=
git.oreonproject.org/oreonproject/eternity v1.0.0/go.mod h1:bV3LgSwVeBAAHuB8hYCw+BQy5OabVtJ/lwVp9BNz3Jk=
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
@ -21,8 +29,12 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL
github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA=
github.com/cloudflare/circl v1.4.0 h1:BV7h5MgrktNzytKmWjpOtdYrf0lkkbF8YMlBGPhJQrY=
github.com/cloudflare/circl v1.4.0/go.mod h1:PDRU+oXvdD7KCtgKxW95M5Z8BpSCJXQORiZFnBQS5QU=
github.com/cloudflare/circl v1.5.0 h1:hxIWksrX6XN5a1L2TI/h53AGPhNHoUBo+TD1ms9+pys=
github.com/cloudflare/circl v1.5.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
github.com/cyphar/filepath-securejoin v0.3.3 h1:lofZkCEVFIBe0KcdQOzFs8Soy9oaHOWl4gGtPI+gCFc=
github.com/cyphar/filepath-securejoin v0.3.3/go.mod h1:8s/MCNJREmFK0H02MF6Ihv1nakJe4L/w3WZLHNkvlYM=
github.com/cyphar/filepath-securejoin v0.3.4 h1:VBWugsJh2ZxJmLFSM06/0qzQyiQX2Qs0ViKrUAcqdZ8=
github.com/cyphar/filepath-securejoin v0.3.4/go.mod h1:8s/MCNJREmFK0H02MF6Ihv1nakJe4L/w3WZLHNkvlYM=
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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -58,6 +70,8 @@ github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/klauspost/compress v1.17.10 h1:oXAz+Vh0PMUvJczoi+flxpnBEPxoER1IaAnU/NMPtT0=
github.com/klauspost/compress v1.17.10/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
@ -98,8 +112,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@ -109,8 +123,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -128,15 +142,15 @@ golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM=
golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8=
golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24=
golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@ -144,8 +158,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=

278
main.go
View file

@ -3,7 +3,8 @@ package main
import (
"bytes"
"errors"
"io"
"github.com/go-chi/chi/v5"
"net/url"
"os"
"time"
@ -16,7 +17,8 @@ import (
"net/http"
"path/filepath"
library "git.ailur.dev/ailur/fg-library"
library "git.ailur.dev/ailur/fg-library/v2"
authLibrary "git.ailur.dev/ailur/fg-nucleus-library"
"git.oreonproject.org/oreonproject/eternity/common"
"git.oreonproject.org/oreonproject/eternity/lib"
"github.com/go-git/go-git/v5"
@ -47,13 +49,6 @@ func logFunc(message string, messageType uint64, information library.ServiceInit
}
}
func deferBody(Body io.ReadCloser, information library.ServiceInitializationInformation) {
err := Body.Close()
if err != nil {
logFunc(err.Error(), 1, information)
}
}
func renderTemplate(statusCode int, w http.ResponseWriter, data map[string]interface{}, templatePath string, information library.ServiceInitializationInformation) {
var err error
var requestedTemplate *template.Template
@ -88,7 +83,18 @@ func renderJSON(statusCode int, w http.ResponseWriter, data map[string]interface
}
}
func verifyJwt(token string, publicKey ed25519.PublicKey) (jwt.MapClaims, bool) {
func verifySecret(secret string, conn library.Database) bool {
// Check if the secret is in the secrets table
var secretCheck string
err := conn.DB.QueryRow("SELECT secret FROM secrets WHERE secret = $1", secret).Scan(&secretCheck)
if err != nil || secretCheck != secret {
return false
}
return true
}
func verifyJwt(token string, publicKey ed25519.PublicKey, conn library.Database) (jwt.MapClaims, bool) {
parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return publicKey, nil
})
@ -107,11 +113,14 @@ func verifyJwt(token string, publicKey ed25519.PublicKey) (jwt.MapClaims, bool)
// Check if the token expired
date, err := claims.GetExpirationTime()
if err != nil {
if err != nil || date.Before(time.Now()) || claims["sub"] != nil || claims["isOpenID"] != nil || claims["isOAuth"].(bool) {
return claims, false
}
if date.Before(time.Now()) {
// Check if the token is in users
var idCheck []byte
err = conn.DB.QueryRow("SELECT id FROM users WHERE id = $1", claims["sub"]).Scan(&idCheck)
if err != nil || claims["sub"] != uuid.Must(uuid.FromBytes(idCheck)).String() {
return claims, false
}
@ -119,9 +128,10 @@ func verifyJwt(token string, publicKey ed25519.PublicKey) (jwt.MapClaims, bool)
}
func Main(information library.ServiceInitializationInformation) {
var conn *sql.DB
var conn library.Database
gitDir := information.Configuration["gitDir"].(string)
outputDir := information.Configuration["outputDir"].(string)
hostName := information.Configuration["hostName"].(string)
// Initiate a connection to the database
// Call service ID 1 to get the database connection information
@ -138,11 +148,39 @@ func Main(information library.ServiceInitializationInformation) {
if response.MessageType == 2 {
// This is the connection information
// Set up the database connection
conn = response.Message.(*sql.DB)
// Create the packages table
_, err := conn.Exec("CREATE TABLE IF NOT EXISTS packages (creator BLOB NOT NULL, name BLOB NOT NULL, path STRING NOT NULL)")
if err != nil {
logFunc(err.Error(), 3, information)
conn = response.Message.(library.Database)
if conn.DBType == library.Sqlite {
// Create the packages table
_, err := conn.DB.Exec("CREATE TABLE IF NOT EXISTS packages (creator BLOB NOT NULL, name TEXT NOT NULL, path TEXT NOT NULL)")
if err != nil {
logFunc(err.Error(), 3, information)
}
// Create the secrets table
_, err = conn.DB.Exec("CREATE TABLE IF NOT EXISTS secrets (secret BLOB NOT NULL)")
if err != nil {
logFunc(err.Error(), 3, information)
}
// Create the users table
_, err = conn.DB.Exec("CREATE TABLE IF NOT EXISTS users (id BLOB NOT NULL)")
if err != nil {
logFunc(err.Error(), 3, information)
}
} else {
// Create the packages table
_, err := conn.DB.Exec("CREATE TABLE IF NOT EXISTS packages (creator BYTEA NOT NULL, name TEXT NOT NULL, path TEXT NOT NULL)")
if err != nil {
logFunc(err.Error(), 3, information)
}
// Create the secrets table
_, err = conn.DB.Exec("CREATE TABLE IF NOT EXISTS secrets (secret BYTEA NOT NULL)")
if err != nil {
logFunc(err.Error(), 3, information)
}
// Create the users table
_, err = conn.DB.Exec("CREATE TABLE IF NOT EXISTS users (id BYTEA NOT NULL)")
if err != nil {
logFunc(err.Error(), 3, information)
}
}
} else {
// This is an error message
@ -161,9 +199,9 @@ func Main(information library.ServiceInitializationInformation) {
var publicKey ed25519.PublicKey = nil
// 10 second timeout
// 3 second timeout
go func() {
time.Sleep(10 * time.Second)
time.Sleep(3 * time.Second)
if publicKey == nil {
logFunc("Timeout while waiting for the public key from the authentication service", 3, information)
}
@ -180,22 +218,68 @@ func Main(information library.ServiceInitializationInformation) {
logFunc(response.Message.(error).Error(), 3, information)
}
// Ask the authentication service to create a new OAuth2 client
urlPath, err := url.JoinPath(hostName, "/oauth")
if err != nil {
logFunc(err.Error(), 3, information)
}
information.Outbox <- library.InterServiceMessage{
ServiceID: ServiceInformation.ServiceID,
ForServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000004"), // Authentication service
MessageType: 1, // Create OAuth2 client
SentAt: time.Now(),
Message: authLibrary.OAuthInformation{
Name: "Eternity Web",
RedirectUri: urlPath,
KeyShareUri: "",
Scopes: []string{"openid"},
},
}
oauthResponse := authLibrary.OAuthResponse{}
// 3 second timeout
go func() {
time.Sleep(3 * time.Second)
if oauthResponse == (authLibrary.OAuthResponse{}) {
logFunc("Timeout while waiting for the OAuth response from the authentication service", 3, information)
}
}()
// Wait for the response
response = <-information.Inbox
switch response.MessageType {
case 0:
// Success, set the OAuth response
oauthResponse = response.Message.(authLibrary.OAuthResponse)
logFunc("Initialized with App ID: "+oauthResponse.AppID, 0, information)
case 1:
// An error which is their fault
logFunc(response.Message.(error).Error(), 3, information)
case 2:
// An error which is our fault
logFunc(response.Message.(error).Error(), 3, information)
default:
// An unknown error
logFunc("Unknown error", 3, information)
}
// Set up the router
router := information.Router
router := chi.NewRouter()
// Set up the static routes
staticDir, err := fs.Sub(information.ResourceDir, "static")
if err != nil {
logFunc(err.Error(), 3, information)
} else {
router.Handle("/static/eternity/*", http.StripPrefix("/static/", http.FileServerFS(staticDir)))
router.Handle("/static-eternity/*", http.StripPrefix("/static-eternity/", http.FileServerFS(staticDir)))
}
// Set up the API routes
router.Post("/api/packages/list", func(w http.ResponseWriter, r *http.Request) {
defer deferBody(r.Body, information)
// Get the list of packages
rows, err := conn.Query("SELECT name FROM packages")
rows, err := conn.DB.Query("SELECT name FROM packages")
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "01"}, information)
return
@ -218,11 +302,11 @@ func Main(information library.ServiceInitializationInformation) {
})
router.Post("/api/packages/add", func(w http.ResponseWriter, r *http.Request) {
defer deferBody(r.Body, information)
type packageData struct {
Name string `json:"name"`
RepositoryPath string `json:"repositoryPath"`
JwtToken string `json:"token"`
Secret string `json:"secret"`
}
var data packageData
err := json.NewDecoder(r.Body).Decode(&data)
@ -231,11 +315,21 @@ func Main(information library.ServiceInitializationInformation) {
return
}
// Verify the JWT token
claims, ok := verifyJwt(data.JwtToken, publicKey)
if !ok {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JWT token"}, information)
return
var claims jwt.MapClaims
if data.Secret != "" {
// Verify the secret
if !verifySecret(data.Secret, conn) {
renderJSON(400, w, map[string]interface{}{"error": "Invalid secret"}, information)
return
}
} else {
// Verify the JWT token
var ok bool
claims, ok = verifyJwt(data.JwtToken, publicKey, conn)
if !ok {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JWT token"}, information)
return
}
}
// Fetch the Git repository
@ -249,12 +343,20 @@ func Main(information library.ServiceInitializationInformation) {
}
// Add the package to the database
userid, err := uuid.MustParse(claims["sub"].(string)).MarshalBinary()
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "03"}, information)
var userid []byte
if data.Secret != "" {
userid, err = uuid.MustParse("00000000-0000-0000-0000-000000000000").MarshalBinary()
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "03"}, information)
}
} else {
userid, err = uuid.MustParse(claims["sub"].(string)).MarshalBinary()
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "03"}, information)
}
}
_, err = conn.Exec("INSERT INTO packages (creator, name, path) VALUES (?, ?, ?)", userid, data.Name, data.RepositoryPath)
_, err = conn.DB.Exec("INSERT INTO packages (creator, name, path) VALUES ($1, $2, $3)", userid, data.Name, data.RepositoryPath)
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "04"}, information)
return
@ -264,10 +366,10 @@ func Main(information library.ServiceInitializationInformation) {
})
router.Post("/api/packages/remove", func(w http.ResponseWriter, r *http.Request) {
defer deferBody(r.Body, information)
type packageData struct {
Name string `json:"name"`
JwtToken string `json:"token"`
Secret string `json:"secret"`
}
var data packageData
err := json.NewDecoder(r.Body).Decode(&data)
@ -277,19 +379,38 @@ func Main(information library.ServiceInitializationInformation) {
}
// Verify the JWT token
claims, ok := verifyJwt(data.JwtToken, publicKey)
if !ok {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JWT token"}, information)
return
var claims jwt.MapClaims
if data.Secret != "" {
// Verify the secret
if !verifySecret(data.Secret, conn) {
renderJSON(400, w, map[string]interface{}{"error": "Invalid secret"}, information)
return
}
} else {
// Verify the JWT token
var ok bool
claims, ok = verifyJwt(data.JwtToken, publicKey, conn)
if !ok {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JWT token"}, information)
return
}
}
// Remove the package from the database
userid, err := uuid.MustParse(claims["sub"].(string)).MarshalBinary()
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "03"}, information)
var userid []byte
if data.Secret != "" {
userid, err = uuid.MustParse("00000000-0000-0000-0000-000000000000").MarshalBinary()
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "03"}, information)
}
} else {
userid, err = uuid.MustParse(claims["sub"].(string)).MarshalBinary()
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "03"}, information)
}
}
_, err = conn.Exec("DELETE FROM packages WHERE creator = ? AND name = ?", userid, data.Name)
_, err = conn.DB.Exec("DELETE FROM packages WHERE creator = $1 AND name = $2", userid, data.Name)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
renderJSON(404, w, map[string]interface{}{"error": "Package not found"}, information)
@ -311,10 +432,10 @@ func Main(information library.ServiceInitializationInformation) {
})
router.Post("/api/packages/get", func(w http.ResponseWriter, r *http.Request) {
defer deferBody(r.Body, information)
type packageData struct {
Name string `json:"name"`
JwtToken string `json:"token"`
Secret string `json:"secret"`
}
var data packageData
err := json.NewDecoder(r.Body).Decode(&data)
@ -324,20 +445,24 @@ func Main(information library.ServiceInitializationInformation) {
}
// Verify the JWT token
claims, ok := verifyJwt(data.JwtToken, publicKey)
if !ok {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JWT token"}, information)
return
}
// Fetch the package from the database
userid, err := uuid.MustParse(claims["sub"].(string)).MarshalBinary()
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "03"}, information)
if data.Secret != "" {
// Verify the secret
if !verifySecret(data.Secret, conn) {
renderJSON(400, w, map[string]interface{}{"error": "Invalid secret"}, information)
return
}
} else {
// Verify the JWT token
var ok bool
_, ok = verifyJwt(data.JwtToken, publicKey, conn)
if !ok {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JWT token"}, information)
return
}
}
var nameCheck string
err = conn.QueryRow("SELECT name FROM packages WHERE creator = ? AND name = ?", userid, data.Name).Scan(&nameCheck)
err = conn.DB.QueryRow("SELECT name FROM packages WHERE name = $1", data.Name).Scan(&nameCheck)
if err != nil || nameCheck != data.Name {
if err != nil && errors.Is(err, sql.ErrNoRows) {
renderJSON(404, w, map[string]interface{}{"error": "Package not found"}, information)
@ -365,10 +490,10 @@ func Main(information library.ServiceInitializationInformation) {
})
router.Post("/api/packages/compile", func(w http.ResponseWriter, r *http.Request) {
defer deferBody(r.Body, information)
type packageData struct {
Name string `json:"name"`
JwtToken string `json:"token"`
Secret string `json:"secret"`
PrivateKey string `json:"privateKey"`
}
var data packageData
@ -379,20 +504,25 @@ func Main(information library.ServiceInitializationInformation) {
}
// Verify the JWT token
claims, ok := verifyJwt(data.JwtToken, publicKey)
if !ok {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JWT token"}, information)
return
if data.Secret != "" {
// Verify the secret
if !verifySecret(data.Secret, conn) {
renderJSON(400, w, map[string]interface{}{"error": "Invalid secret"}, information)
return
}
} else {
// Verify the JWT token
var ok bool
_, ok = verifyJwt(data.JwtToken, publicKey, conn)
if !ok {
renderJSON(400, w, map[string]interface{}{"error": "Invalid JWT token"}, information)
return
}
}
// Fetch the package from the database
userid, err := uuid.MustParse(claims["sub"].(string)).MarshalBinary()
if err != nil {
renderJSON(500, w, map[string]interface{}{"error": "Internal server error", "code": "03"}, information)
}
var nameCheck, path string
err = conn.QueryRow("SELECT name, path FROM packages WHERE creator = ? AND name = ?", userid, data.Name).Scan(&nameCheck, &path)
err = conn.DB.QueryRow("SELECT name, path FROM packages WHERE name = $1", data.Name).Scan(&nameCheck, &path)
if err != nil || nameCheck != data.Name {
if err != nil && errors.Is(err, sql.ErrNoRows) {
renderJSON(404, w, map[string]interface{}{"error": "Package not found"}, information)
@ -456,26 +586,16 @@ func Main(information library.ServiceInitializationInformation) {
// Set up the template routes
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
defer deferBody(r.Body, information)
renderTemplate(200, w, map[string]interface{}{}, "index.html", information)
})
router.Get("/packages", func(w http.ResponseWriter, r *http.Request) {
defer deferBody(r.Body, information)
renderTemplate(200, w, map[string]interface{}{}, "packages.html", information)
})
router.Get("/oauth", func(w http.ResponseWriter, r *http.Request) {
defer deferBody(r.Body, information)
renderTemplate(200, w, map[string]interface{}{}, "oauth.html", information)
renderTemplate(200, w, map[string]interface{}{
"ClientId": oauthResponse.AppID,
}, "oauth.html", information)
})
// Report a successful activation
information.Outbox <- library.InterServiceMessage{
ServiceID: ServiceInformation.ServiceID,
ForServiceID: uuid.MustParse("00000000-0000-0000-0000-000000000001"), // Activation service
MessageType: 0,
SentAt: time.Now(),
Message: true,
}
}

3
resources/go.mod Normal file
View file

@ -0,0 +1,3 @@
module git.oreonproject.org/oreonproject/eternity-web/resources
go 1.23.1

0
resources/go.sum Normal file
View file

View file

View file

@ -0,0 +1 @@
console.log("Not implemented")

View file

@ -0,0 +1,583 @@
// @license magnet:?xt=urn:btih:0ef1b8170b3b615170ff270def6427c317705f85&dn=lgpl-3.0.txt LGPL-3.0
/*
* wasm_helper
* (c) Arzumify
* @license LGPL-3.0
*/
async function loadWasm(url) {
const go = new Go();
WebAssembly.instantiateStreaming(fetch(url), go.importObject).then((result) => {
go.run(result.instance);
})
}
// @license-end
// @license magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt BSD-3-Clause
/*
* wasm_exec (https://github.com/golang/go)
* (c) The Go Authors
* @license BSD-3-Clause
*/
"use strict";
(() => {
const enosys = () => {
const err = new Error("not implemented");
err.code = "ENOSYS";
return err;
};
if (!globalThis.fs) {
let outputBuf = "";
globalThis.fs = {
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
writeSync(fd, buf) {
outputBuf += decoder.decode(buf);
const nl = outputBuf.lastIndexOf("\n");
if (nl != -1) {
console.log(outputBuf.substring(0, nl));
outputBuf = outputBuf.substring(nl + 1);
}
return buf.length;
},
write(fd, buf, offset, length, position, callback) {
if (offset !== 0 || length !== buf.length || position !== null) {
callback(enosys());
return;
}
const n = this.writeSync(fd, buf);
callback(null, n);
},
chmod(path, mode, callback) { callback(enosys()); },
chown(path, uid, gid, callback) { callback(enosys()); },
close(fd, callback) { callback(enosys()); },
fchmod(fd, mode, callback) { callback(enosys()); },
fchown(fd, uid, gid, callback) { callback(enosys()); },
fstat(fd, callback) { callback(enosys()); },
fsync(fd, callback) { callback(null); },
ftruncate(fd, length, callback) { callback(enosys()); },
lchown(path, uid, gid, callback) { callback(enosys()); },
link(path, link, callback) { callback(enosys()); },
lstat(path, callback) { callback(enosys()); },
mkdir(path, perm, callback) { callback(enosys()); },
open(path, flags, mode, callback) { callback(enosys()); },
read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
readdir(path, callback) { callback(enosys()); },
readlink(path, callback) { callback(enosys()); },
rename(from, to, callback) { callback(enosys()); },
rmdir(path, callback) { callback(enosys()); },
stat(path, callback) { callback(enosys()); },
symlink(path, link, callback) { callback(enosys()); },
truncate(path, length, callback) { callback(enosys()); },
unlink(path, callback) { callback(enosys()); },
utimes(path, atime, mtime, callback) { callback(enosys()); },
};
}
if (!globalThis.process) {
globalThis.process = {
getuid() { return -1; },
getgid() { return -1; },
geteuid() { return -1; },
getegid() { return -1; },
getgroups() { throw enosys(); },
pid: -1,
ppid: -1,
umask() { throw enosys(); },
cwd() { throw enosys(); },
chdir() { throw enosys(); },
}
}
if (!globalThis.crypto) {
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
}
if (!globalThis.performance) {
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
}
if (!globalThis.TextEncoder) {
throw new Error("globalThis.TextEncoder is not available, polyfill required");
}
if (!globalThis.TextDecoder) {
throw new Error("globalThis.TextDecoder is not available, polyfill required");
}
const encoder = new TextEncoder("utf-8");
const decoder = new TextDecoder("utf-8");
globalThis.Go = class {
constructor() {
this.argv = ["js"];
this.env = {};
this.exit = (code) => {
if (code !== 0) {
console.warn("exit code:", code);
}
};
this._exitPromise = new Promise((resolve) => {
this._resolveExitPromise = resolve;
});
this._pendingEvent = null;
this._scheduledTimeouts = new Map();
this._nextCallbackTimeoutID = 1;
const setInt64 = (addr, v) => {
this.mem.setUint32(addr + 0, v, true);
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
}
const setInt32 = (addr, v) => {
this.mem.setUint32(addr + 0, v, true);
}
const getInt64 = (addr) => {
const low = this.mem.getUint32(addr + 0, true);
const high = this.mem.getInt32(addr + 4, true);
return low + high * 4294967296;
}
const loadValue = (addr) => {
const f = this.mem.getFloat64(addr, true);
if (f === 0) {
return undefined;
}
if (!isNaN(f)) {
return f;
}
const id = this.mem.getUint32(addr, true);
return this._values[id];
}
const storeValue = (addr, v) => {
const nanHead = 0x7FF80000;
if (typeof v === "number" && v !== 0) {
if (isNaN(v)) {
this.mem.setUint32(addr + 4, nanHead, true);
this.mem.setUint32(addr, 0, true);
return;
}
this.mem.setFloat64(addr, v, true);
return;
}
if (v === undefined) {
this.mem.setFloat64(addr, 0, true);
return;
}
let id = this._ids.get(v);
if (id === undefined) {
id = this._idPool.pop();
if (id === undefined) {
id = this._values.length;
}
this._values[id] = v;
this._goRefCounts[id] = 0;
this._ids.set(v, id);
}
this._goRefCounts[id]++;
let typeFlag = 0;
switch (typeof v) {
case "object":
if (v !== null) {
typeFlag = 1;
}
break;
case "string":
typeFlag = 2;
break;
case "symbol":
typeFlag = 3;
break;
case "function":
typeFlag = 4;
break;
}
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
this.mem.setUint32(addr, id, true);
}
const loadSlice = (addr) => {
const array = getInt64(addr + 0);
const len = getInt64(addr + 8);
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
}
const loadSliceOfValues = (addr) => {
const array = getInt64(addr + 0);
const len = getInt64(addr + 8);
const a = new Array(len);
for (let i = 0; i < len; i++) {
a[i] = loadValue(array + i * 8);
}
return a;
}
const loadString = (addr) => {
const saddr = getInt64(addr + 0);
const len = getInt64(addr + 8);
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
}
const timeOrigin = Date.now() - performance.now();
this.importObject = {
_gotest: {
add: (a, b) => a + b,
},
gojs: {
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
// This changes the SP, thus we have to update the SP used by the imported function.
// func wasmExit(code int32)
"runtime.wasmExit": (sp) => {
sp >>>= 0;
const code = this.mem.getInt32(sp + 8, true);
this.exited = true;
delete this._inst;
delete this._values;
delete this._goRefCounts;
delete this._ids;
delete this._idPool;
this.exit(code);
},
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
"runtime.wasmWrite": (sp) => {
sp >>>= 0;
const fd = getInt64(sp + 8);
const p = getInt64(sp + 16);
const n = this.mem.getInt32(sp + 24, true);
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
},
// func resetMemoryDataView()
"runtime.resetMemoryDataView": (sp) => {
sp >>>= 0;
this.mem = new DataView(this._inst.exports.mem.buffer);
},
// func nanotime1() int64
"runtime.nanotime1": (sp) => {
sp >>>= 0;
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
},
// func walltime() (sec int64, nsec int32)
"runtime.walltime": (sp) => {
sp >>>= 0;
const msec = (new Date).getTime();
setInt64(sp + 8, msec / 1000);
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
},
// func scheduleTimeoutEvent(delay int64) int32
"runtime.scheduleTimeoutEvent": (sp) => {
sp >>>= 0;
const id = this._nextCallbackTimeoutID;
this._nextCallbackTimeoutID++;
this._scheduledTimeouts.set(id, setTimeout(
() => {
this._resume();
while (this._scheduledTimeouts.has(id)) {
// for some reason Go failed to register the timeout event, log and try again
// (temporary workaround for https://github.com/golang/go/issues/28975)
console.warn("scheduleTimeoutEvent: missed timeout event");
this._resume();
}
},
getInt64(sp + 8),
));
this.mem.setInt32(sp + 16, id, true);
},
// func clearTimeoutEvent(id int32)
"runtime.clearTimeoutEvent": (sp) => {
sp >>>= 0;
const id = this.mem.getInt32(sp + 8, true);
clearTimeout(this._scheduledTimeouts.get(id));
this._scheduledTimeouts.delete(id);
},
// func getRandomData(r []byte)
"runtime.getRandomData": (sp) => {
sp >>>= 0;
crypto.getRandomValues(loadSlice(sp + 8));
},
// func finalizeRef(v ref)
"syscall/js.finalizeRef": (sp) => {
sp >>>= 0;
const id = this.mem.getUint32(sp + 8, true);
this._goRefCounts[id]--;
if (this._goRefCounts[id] === 0) {
const v = this._values[id];
this._values[id] = null;
this._ids.delete(v);
this._idPool.push(id);
}
},
// func stringVal(value string) ref
"syscall/js.stringVal": (sp) => {
sp >>>= 0;
storeValue(sp + 24, loadString(sp + 8));
},
// func valueGet(v ref, p string) ref
"syscall/js.valueGet": (sp) => {
sp >>>= 0;
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 32, result);
},
// func valueSet(v ref, p string, x ref)
"syscall/js.valueSet": (sp) => {
sp >>>= 0;
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
},
// func valueDelete(v ref, p string)
"syscall/js.valueDelete": (sp) => {
sp >>>= 0;
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
},
// func valueIndex(v ref, i int) ref
"syscall/js.valueIndex": (sp) => {
sp >>>= 0;
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
},
// valueSetIndex(v ref, i int, x ref)
"syscall/js.valueSetIndex": (sp) => {
sp >>>= 0;
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
},
// func valueCall(v ref, m string, args []ref) (ref, bool)
"syscall/js.valueCall": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const m = Reflect.get(v, loadString(sp + 16));
const args = loadSliceOfValues(sp + 32);
const result = Reflect.apply(m, v, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 56, result);
this.mem.setUint8(sp + 64, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 56, err);
this.mem.setUint8(sp + 64, 0);
}
},
// func valueInvoke(v ref, args []ref) (ref, bool)
"syscall/js.valueInvoke": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const args = loadSliceOfValues(sp + 16);
const result = Reflect.apply(v, undefined, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, result);
this.mem.setUint8(sp + 48, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, err);
this.mem.setUint8(sp + 48, 0);
}
},
// func valueNew(v ref, args []ref) (ref, bool)
"syscall/js.valueNew": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const args = loadSliceOfValues(sp + 16);
const result = Reflect.construct(v, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, result);
this.mem.setUint8(sp + 48, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, err);
this.mem.setUint8(sp + 48, 0);
}
},
// func valueLength(v ref) int
"syscall/js.valueLength": (sp) => {
sp >>>= 0;
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
},
// valuePrepareString(v ref) (ref, int)
"syscall/js.valuePrepareString": (sp) => {
sp >>>= 0;
const str = encoder.encode(String(loadValue(sp + 8)));
storeValue(sp + 16, str);
setInt64(sp + 24, str.length);
},
// valueLoadString(v ref, b []byte)
"syscall/js.valueLoadString": (sp) => {
sp >>>= 0;
const str = loadValue(sp + 8);
loadSlice(sp + 16).set(str);
},
// func valueInstanceOf(v ref, t ref) bool
"syscall/js.valueInstanceOf": (sp) => {
sp >>>= 0;
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
},
// func copyBytesToGo(dst []byte, src ref) (int, bool)
"syscall/js.copyBytesToGo": (sp) => {
sp >>>= 0;
const dst = loadSlice(sp + 8);
const src = loadValue(sp + 32);
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
this.mem.setUint8(sp + 48, 0);
return;
}
const toCopy = src.subarray(0, dst.length);
dst.set(toCopy);
setInt64(sp + 40, toCopy.length);
this.mem.setUint8(sp + 48, 1);
},
// func copyBytesToJS(dst ref, src []byte) (int, bool)
"syscall/js.copyBytesToJS": (sp) => {
sp >>>= 0;
const dst = loadValue(sp + 8);
const src = loadSlice(sp + 16);
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
this.mem.setUint8(sp + 48, 0);
return;
}
const toCopy = src.subarray(0, dst.length);
dst.set(toCopy);
setInt64(sp + 40, toCopy.length);
this.mem.setUint8(sp + 48, 1);
},
"debug": (value) => {
console.log(value);
},
}
};
}
async run(instance) {
if (!(instance instanceof WebAssembly.Instance)) {
throw new Error("Go.run: WebAssembly.Instance expected");
}
this._inst = instance;
this.mem = new DataView(this._inst.exports.mem.buffer);
this._values = [ // JS values that Go currently has references to, indexed by reference id
NaN,
0,
null,
true,
false,
globalThis,
this,
];
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
this._ids = new Map([ // mapping from JS values to reference ids
[0, 1],
[null, 2],
[true, 3],
[false, 4],
[globalThis, 5],
[this, 6],
]);
this._idPool = []; // unused ids that have been garbage collected
this.exited = false; // whether the Go program has exited
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
let offset = 4096;
const strPtr = (str) => {
const ptr = offset;
const bytes = encoder.encode(str + "\0");
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
offset += bytes.length;
if (offset % 8 !== 0) {
offset += 8 - (offset % 8);
}
return ptr;
};
const argc = this.argv.length;
const argvPtrs = [];
this.argv.forEach((arg) => {
argvPtrs.push(strPtr(arg));
});
argvPtrs.push(0);
const keys = Object.keys(this.env).sort();
keys.forEach((key) => {
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
});
argvPtrs.push(0);
const argv = offset;
argvPtrs.forEach((ptr) => {
this.mem.setUint32(offset, ptr, true);
this.mem.setUint32(offset + 4, 0, true);
offset += 8;
});
// The linker guarantees global data starts from at least wasmMinDataAddr.
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
const wasmMinDataAddr = 4096 + 8192;
if (offset >= wasmMinDataAddr) {
throw new Error("total length of command line and environment variables exceeds limit");
}
this._inst.exports.run(argc, argv);
if (this.exited) {
this._resolveExitPromise();
}
await this._exitPromise;
}
_resume() {
if (this.exited) {
throw new Error("Go program has already exited");
}
this._inst.exports.resume();
if (this.exited) {
this._resolveExitPromise();
}
}
_makeFuncWrapper(id) {
const go = this;
return function () {
const event = { id: id, this: this, args: arguments };
go._pendingEvent = event;
go._resume();
return event.result;
};
}
}
})();
// @license-end

View file

@ -1,10 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OA</title>
<title>Logging in...</title>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="/static/js/wasm_exec.js"></script>
</head>
<body>
<text id="clientId" style="display: none">{{ .ClientId }}</text>
<h2>Logging in...</h2>
<p id="statusBox"></p>
<button id="tryAgain" style="display: none">Try again</button>
<script>
loadWasm("/static-eternity/wasm/oauth.wasm")
</script>
</body>
</html>
</html>

View file

@ -0,0 +1,208 @@
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"syscall/js"
"time"
)
func sha256Base64(s string) string {
hashed := sha256.Sum256([]byte(s))
encoded := base64.URLEncoding.EncodeToString(hashed[:])
encoded = strings.TrimRight(encoded, "=")
return encoded
}
func randomChars(length int) (string, error) {
var saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
if length <= 0 {
return "", errors.New("salt length must be greater than 0")
}
salt := make([]byte, length)
randomBytes := make([]byte, length)
_, err := rand.Read(randomBytes)
if err != nil {
return "", err
}
for i := range salt {
salt[i] = saltChars[int(randomBytes[i])%len(saltChars)]
}
return string(salt), nil
}
func main() {
// Redirect to packages if already logged in
localStorage := js.Global().Get("localStorage")
if !localStorage.Call("getItem", "SECRET-token").IsNull() {
js.Global().Get("window").Get("location").Call("replace", "/packages")
}
statusBox := js.Global().Get("document").Call("getElementById", "statusBox")
tryAgain := js.Global().Get("document").Call("getElementById", "tryAgain")
go func() {
// Check if the URL has a code
urlParams, err := url.ParseQuery(strings.TrimPrefix(js.Global().Get("window").Get("location").Get("search").String(), "?"))
if err != nil {
statusBox.Set("innerText", "Error parsing URL: "+err.Error())
tryAgain.Set("style", "")
return
}
if urlParams.Has("code") {
// Set the status box
statusBox.Set("innerText", "Authenticating...")
// Create the form data
var formData = url.Values{}
formData.Set("grant_type", "authorization_code")
formData.Set("code", urlParams.Get("code"))
formData.Set("client_id", js.Global().Get("document").Call("getElementById", "clientId").Get("innerText").String())
formData.Set("redirect_uri", js.Global().Get("window").Get("location").Get("origin").String()+"/oauth")
formData.Set("code_verifier", localStorage.Call("getItem", "OAUTH-verifier").String())
// Create the request
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/token")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
tryAgain.Set("style", "")
return
}
response, err := http.Post(requestUri, "application/x-www-form-urlencoded", strings.NewReader(formData.Encode()))
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
tryAgain.Set("style", "")
return
}
// Read the response
var responseMap map[string]interface{}
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
tryAgain.Set("style", "")
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
if response.StatusCode == 200 {
// Fetch userinfo
requestUri, err := url.JoinPath(js.Global().Get("window").Get("location").Get("origin").String(), "/api/oauth/userinfo")
if err != nil {
statusBox.Set("innerText", "Error joining URL: "+err.Error())
tryAgain.Set("style", "")
return
}
// Create the request
request, err := http.NewRequest("GET", requestUri, nil)
if err != nil {
statusBox.Set("innerText", "Error creating request: "+err.Error())
tryAgain.Set("style", "")
return
}
// Set the authorization header
request.Header.Set("Authorization", "Bearer "+responseMap["id_token"].(string))
// Send the request
response, err := http.DefaultClient.Do(request)
if err != nil {
statusBox.Set("innerText", "Error contacting server: "+err.Error())
tryAgain.Set("style", "")
return
}
// Read the response
decoder = json.NewDecoder(response.Body)
err = decoder.Decode(&responseMap)
if err != nil {
statusBox.Set("innerText", "Error decoding server response: "+err.Error())
tryAgain.Set("style", "")
return
}
// Close the response body
err = response.Body.Close()
if err != nil {
fmt.Println("Could not close response body: " + err.Error() + ", memory leaks may occur")
}
// Save the username and token
localStorage.Call("setItem", "CONFIG-username", responseMap["username"].(string))
localStorage.Call("setItem", "SECRET-token", responseMap["access_token"].(string))
// Remove the verifier
localStorage.Call("removeItem", "OAUTH-verifier")
// Set the status box
statusBox.Set("innerText", "Successfully authenticated!")
// Wait for 1 second
time.Sleep(1 * time.Second)
// Redirect to packages
js.Global().Get("window").Get("location").Call("replace", "/packages")
return
} else if response.StatusCode != 500 {
statusBox.Set("innerText", responseMap["error"].(string))
tryAgain.Set("style", "")
} else {
statusBox.Set("innerText", "Something went wrong! (error code: "+responseMap["code"].(string)+")")
tryAgain.Set("style", "")
}
} else if urlParams.Has("error") {
if urlParams.Get("error") == "access_denied" {
statusBox.Set("innerText", "Access denied")
tryAgain.Set("style", "")
} else {
statusBox.Set("innerText", "Authentication failed (error code: "+urlParams.Get("error")+")")
tryAgain.Set("style", "")
}
} else {
// Start the authorization process
verifier, err := randomChars(128)
if err != nil {
statusBox.Set("innerText", "Error generating verifier: "+err.Error())
tryAgain.Set("style", "")
return
}
// Generate the challenge
verifierChallenge := sha256Base64(verifier)
// Save the verifier
localStorage.Call("setItem", "OAUTH-verifier", verifier)
// Redirect to the authorization page
js.Global().Get("window").Get("location").Call("replace", "/authorize?response_type=code&client_id="+js.Global().Get("document").Call("getElementById", "clientId").Get("innerText").String()+"&redirect_uri="+url.QueryEscape(js.Global().Get("window").Get("location").Get("origin").String()+"/oauth")+"&code_challenge="+verifierChallenge+"&code_challenge_method=S256")
}
}()
// Add event listener to try again button
tryAgain.Call("addEventListener", "click", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
// Redirect to the same URL without the query
js.Global().Get("window").Get("location").Call("replace", js.Global().Get("window").Get("location").Get("origin").String()+js.Global().Get("window").Get("location").Get("pathname").String())
return nil
}))
// Wait for events
select {}
}