1package helpers
2
3import (
4 crand "crypto/rand"
5 "encoding/hex"
6 "errors"
7 "math/rand"
8 "net/url"
9
10 "github.com/Azure/go-autorest/autorest/to"
11 "github.com/labstack/echo/v4"
12 "github.com/lestrrat-go/jwx/v2/jwk"
13)
14
15// This will confirm to the regex in the application if 5 chars are used for each side of the -
16// /^[A-Z2-7]{5}-[A-Z2-7]{5}$/
17var letters = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")
18
19func InputError(e echo.Context, custom *string) error {
20 msg := "InvalidRequest"
21 if custom != nil {
22 msg = *custom
23 }
24 return genericError(e, 400, msg)
25}
26
27func ServerError(e echo.Context, suffix *string) error {
28 msg := "Internal server error"
29 if suffix != nil {
30 msg += ". " + *suffix
31 }
32 return genericError(e, 400, msg)
33}
34
35func InvalidTokenError(e echo.Context) error {
36 return InputError(e, to.StringPtr("InvalidToken"))
37}
38
39func ExpiredTokenError(e echo.Context) error {
40 // WARN: See https://github.com/bluesky-social/atproto/discussions/3319
41 return e.JSON(400, map[string]string{
42 "error": "ExpiredToken",
43 "message": "*",
44 })
45}
46
47func genericError(e echo.Context, code int, msg string) error {
48 return e.JSON(code, map[string]string{
49 "error": msg,
50 })
51}
52
53func RandomVarchar(length int) string {
54 b := make([]rune, length)
55 for i := range b {
56 b[i] = letters[rand.Intn(len(letters))]
57 }
58 return string(b)
59}
60
61func RandomHex(n int) (string, error) {
62 bytes := make([]byte, n)
63 if _, err := crand.Read(bytes); err != nil {
64 return "", err
65 }
66 return hex.EncodeToString(bytes), nil
67}
68
69func RandomBytes(n int) []byte {
70 bs := make([]byte, n)
71 crand.Read(bs)
72 return bs
73}
74
75func ParseJWKFromBytes(b []byte) (jwk.Key, error) {
76 return jwk.ParseKey(b)
77}
78
79func OauthParseHtu(htu string) (string, error) {
80 u, err := url.Parse(htu)
81 if err != nil {
82 return "", errors.New("`htu` is not a valid URL")
83 }
84
85 if u.User != nil {
86 _, containsPass := u.User.Password()
87 if u.User.Username() != "" || containsPass {
88 return "", errors.New("`htu` must not contain credentials")
89 }
90 }
91
92 if u.Scheme != "http" && u.Scheme != "https" {
93 return "", errors.New("`htu` must be http or https")
94 }
95
96 return OauthNormalizeHtu(u), nil
97}
98
99func OauthNormalizeHtu(u *url.URL) string {
100 return u.Scheme + "://" + u.Host + u.RawPath
101}