Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c4d1b464c | |||
| f1601020b1 | |||
| a048cb0d73 | |||
| 166b3fda5c |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -2,6 +2,9 @@
|
|||||||
# If you prefer the allow list template instead of the deny list, see community template:
|
# If you prefer the allow list template instead of the deny list, see community template:
|
||||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||||
#
|
#
|
||||||
|
|
||||||
|
.claude
|
||||||
|
|
||||||
# Binaries for programs and plugins
|
# Binaries for programs and plugins
|
||||||
*.exe
|
*.exe
|
||||||
*.exe~
|
*.exe~
|
||||||
@@ -24,4 +27,3 @@ go.work.sum
|
|||||||
|
|
||||||
# env file
|
# env file
|
||||||
.env
|
.env
|
||||||
|
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ func ParseEdPrivateKey(d []byte) (ed25519.PrivateKey, error) {
|
|||||||
case ed25519.PrivateKey:
|
case ed25519.PrivateKey:
|
||||||
return pub, nil
|
return pub, nil
|
||||||
default:
|
default:
|
||||||
return nil, errors.New("key type is not RSA")
|
return nil, errors.New("key type is not Ed25519")
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -99,6 +99,6 @@ func ParseEdPublicKey(d []byte) (ed25519.PublicKey, error) {
|
|||||||
case ed25519.PublicKey:
|
case ed25519.PublicKey:
|
||||||
return pub, nil
|
return pub, nil
|
||||||
default:
|
default:
|
||||||
return nil, errors.New("key type is not RSA")
|
return nil, errors.New("key type is not Ed25519")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ func StartOfDay(date time.Time) time.Time {
|
|||||||
|
|
||||||
func EndOfDay(date time.Time) time.Time {
|
func EndOfDay(date time.Time) time.Time {
|
||||||
year, month, day := date.Date()
|
year, month, day := date.Date()
|
||||||
return time.Date(year, month, day, 23, 59, 59, 0, date.Location())
|
return time.Date(year, month, day, 23, 59, 59, 999999999, date.Location())
|
||||||
}
|
}
|
||||||
|
|
||||||
func StartOfMonth(date time.Time) time.Time {
|
func StartOfMonth(date time.Time) time.Time {
|
||||||
|
|||||||
@@ -255,7 +255,7 @@ func isLineEnd(r rune) bool {
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
escapeRegex = regexp.MustCompile(`\\.`)
|
escapeRegex = regexp.MustCompile(`\\.`)
|
||||||
expandVarRegex = regexp.MustCompile(`(\\)?(\$)(\()?\{?([A-Z0-9_]+)?\}?`)
|
expandVarRegex = regexp.MustCompile(`(\\)?(\$)(\()?\{?([A-Za-z0-9_]+)?\}?`)
|
||||||
unescapeCharsRegex = regexp.MustCompile(`\\([^$])`)
|
unescapeCharsRegex = regexp.MustCompile(`\\([^$])`)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,7 +19,7 @@ func Write(envMap map[string]string, filename string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
file, err := os.Create(filename)
|
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -37,11 +36,7 @@ func Write(envMap map[string]string, filename string) error {
|
|||||||
func marshal(envMap map[string]string) (string, error) {
|
func marshal(envMap map[string]string) (string, error) {
|
||||||
lines := make([]string, 0, len(envMap))
|
lines := make([]string, 0, len(envMap))
|
||||||
for k, v := range envMap {
|
for k, v := range envMap {
|
||||||
if d, err := strconv.Atoi(v); err == nil {
|
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
|
||||||
lines = append(lines, fmt.Sprintf(`%s=%d`, k, d))
|
|
||||||
} else {
|
|
||||||
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
sort.Strings(lines)
|
sort.Strings(lines)
|
||||||
return strings.Join(lines, "\n"), nil
|
return strings.Join(lines, "\n"), nil
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/mail"
|
"net/mail"
|
||||||
|
"slices"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Sender is the interface that wraps the Send method.
|
// Sender is the interface that wraps the Send method.
|
||||||
@@ -98,10 +99,8 @@ func (m *Message) getRecipients() ([]string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func addAddress(list []string, addr string) []string {
|
func addAddress(list []string, addr string) []string {
|
||||||
for _, a := range list {
|
if slices.Contains(list, addr) {
|
||||||
if addr == a {
|
return list
|
||||||
return list
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return append(list, addr)
|
return append(list, addr)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package email
|
package email
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
@@ -19,7 +20,10 @@ func (DumpToTemp) Send(msg *Message) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dir := os.TempDir()
|
dir := os.TempDir()
|
||||||
id, _ := uuid.NewV7()
|
id, err := uuid.NewV7()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("email: failed to generate UUID: %w", err)
|
||||||
|
}
|
||||||
file := filepath.Join(dir, id.String()+".html")
|
file := filepath.Join(dir, id.String()+".html")
|
||||||
|
|
||||||
if err := os.WriteFile(file, []byte(msg.HtmlBody), 0440); err != nil {
|
if err := os.WriteFile(file, []byte(msg.HtmlBody), 0440); err != nil {
|
||||||
|
|||||||
@@ -87,6 +87,6 @@ func (t SMTP) Send(msg *Message) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
slog.Info("sent email %s" + msg.Subject)
|
slog.Info("sent email", slog.String("subject", msg.Subject))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
14
go.mod
14
go.mod
@@ -1,20 +1,20 @@
|
|||||||
module code.patial.tech/go/appcore
|
module code.patial.tech/go/appcore
|
||||||
|
|
||||||
go 1.25
|
go 1.26
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/go-playground/validator/v10 v10.28.0
|
github.com/go-playground/validator/v10 v10.30.1
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/sqids/sqids-go v0.4.1
|
github.com/sqids/sqids-go v0.4.1
|
||||||
golang.org/x/crypto v0.45.0
|
golang.org/x/crypto v0.48.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/gabriel-vasile/mimetype v1.4.11 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
golang.org/x/sys v0.38.0 // indirect
|
golang.org/x/sys v0.41.0 // indirect
|
||||||
golang.org/x/text v0.31.0 // indirect
|
golang.org/x/text v0.34.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
12
go.sum
12
go.sum
@@ -4,6 +4,8 @@ github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIp
|
|||||||
github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik=
|
github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
@@ -14,8 +16,12 @@ github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHO
|
|||||||
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||||
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=
|
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=
|
||||||
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=
|
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
@@ -30,13 +36,19 @@ golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
|||||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||||
|
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||||
|
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||||
|
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||||
|
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||||
|
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
12
gz/gz.go
12
gz/gz.go
@@ -8,8 +8,14 @@ package gz
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"compress/gzip"
|
"compress/gzip"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// MaxDecompressedSize is the maximum allowed size for decompressed data (256MB).
|
||||||
|
// This prevents decompression bomb attacks. Override if you need larger outputs.
|
||||||
|
var MaxDecompressedSize int64 = 256 << 20
|
||||||
|
|
||||||
func Zip(data []byte) ([]byte, error) {
|
func Zip(data []byte) ([]byte, error) {
|
||||||
var b bytes.Buffer
|
var b bytes.Buffer
|
||||||
gz := gzip.NewWriter(&b)
|
gz := gzip.NewWriter(&b)
|
||||||
@@ -37,9 +43,13 @@ func UnZip(data []byte) ([]byte, error) {
|
|||||||
defer r.Close() // Ensure reader is closed to prevent resource leak
|
defer r.Close() // Ensure reader is closed to prevent resource leak
|
||||||
|
|
||||||
var resB bytes.Buffer
|
var resB bytes.Buffer
|
||||||
if _, err := resB.ReadFrom(r); err != nil {
|
if _, err := io.Copy(&resB, io.LimitReader(r, MaxDecompressedSize+1)); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if int64(resB.Len()) > MaxDecompressedSize {
|
||||||
|
return nil, errors.New("gz: decompressed data exceeds maximum allowed size")
|
||||||
|
}
|
||||||
|
|
||||||
return resB.Bytes(), nil
|
return resB.Bytes(), nil
|
||||||
}
|
}
|
||||||
|
|||||||
89
jwt/jwt.go
89
jwt/jwt.go
@@ -6,6 +6,7 @@
|
|||||||
package jwt
|
package jwt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
"crypto/ed25519"
|
"crypto/ed25519"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -27,13 +28,14 @@ func Parse(key ed25519.PrivateKey, tokenString string, issuer string) (jwt.MapCl
|
|||||||
// SignEdDSA (Edwards-curve Digital Signature Algorithm, typically Ed25519) is an excellent,
|
// SignEdDSA (Edwards-curve Digital Signature Algorithm, typically Ed25519) is an excellent,
|
||||||
// modern choice for JWT signing—arguably safer and more efficient than both HS256 and traditional RSA/ECDSA.
|
// modern choice for JWT signing—arguably safer and more efficient than both HS256 and traditional RSA/ECDSA.
|
||||||
func SignEdDSA(key ed25519.PrivateKey, claims map[string]any, issuer string, d time.Duration) (string, error) {
|
func SignEdDSA(key ed25519.PrivateKey, claims map[string]any, issuer string, d time.Duration) (string, error) {
|
||||||
cl := jwt.MapClaims{
|
cl := jwt.MapClaims{}
|
||||||
"iss": issuer,
|
|
||||||
"iat": jwt.NewNumericDate(time.Now().UTC()),
|
|
||||||
"exp": jwt.NewNumericDate(time.Now().Add(d)),
|
|
||||||
}
|
|
||||||
maps.Copy(cl, claims)
|
maps.Copy(cl, claims)
|
||||||
|
|
||||||
|
// Set standard claims after user claims to prevent override
|
||||||
|
cl["iss"] = issuer
|
||||||
|
cl["iat"] = jwt.NewNumericDate(time.Now().UTC())
|
||||||
|
cl["exp"] = jwt.NewNumericDate(time.Now().Add(d))
|
||||||
|
|
||||||
t := jwt.NewWithClaims(jwt.SigningMethodEdDSA, cl)
|
t := jwt.NewWithClaims(jwt.SigningMethodEdDSA, cl)
|
||||||
return t.SignedString(key)
|
return t.SignedString(key)
|
||||||
}
|
}
|
||||||
@@ -60,13 +62,14 @@ func ParseEdDSA(key ed25519.PrivateKey, tokenString string, issuer string) (jwt.
|
|||||||
}
|
}
|
||||||
|
|
||||||
func SignHS256(secret []byte, claims map[string]any, issuer string, d time.Duration) (string, error) {
|
func SignHS256(secret []byte, claims map[string]any, issuer string, d time.Duration) (string, error) {
|
||||||
cl := jwt.MapClaims{
|
cl := jwt.MapClaims{}
|
||||||
"iss": issuer,
|
|
||||||
"iat": jwt.NewNumericDate(time.Now().UTC()),
|
|
||||||
"exp": jwt.NewNumericDate(time.Now().Add(d)),
|
|
||||||
}
|
|
||||||
maps.Copy(cl, claims)
|
maps.Copy(cl, claims)
|
||||||
|
|
||||||
|
// Set standard claims after user claims to prevent override
|
||||||
|
cl["iss"] = issuer
|
||||||
|
cl["iat"] = jwt.NewNumericDate(time.Now().UTC())
|
||||||
|
cl["exp"] = jwt.NewNumericDate(time.Now().Add(d))
|
||||||
|
|
||||||
t := jwt.NewWithClaims(jwt.SigningMethodHS256, cl)
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256, cl)
|
||||||
return t.SignedString(secret)
|
return t.SignedString(secret)
|
||||||
}
|
}
|
||||||
@@ -94,3 +97,69 @@ func ParseHS256(secret []byte, tokenString string, issuer string) (jwt.MapClaims
|
|||||||
}
|
}
|
||||||
return nil, errors.New("no claims found in token")
|
return nil, errors.New("no claims found in token")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SignES256 signs a JWT using ES256 (ECDSA P-256) algorithm.
|
||||||
|
// This is required for Apple Sign In which mandates ES256.
|
||||||
|
// Pass empty string for issuer, audience, or subject to omit them from the token.
|
||||||
|
func SignES256(
|
||||||
|
key *ecdsa.PrivateKey, issuer, audience, subject string, d time.Duration, claims map[string]any,
|
||||||
|
) (string, error) {
|
||||||
|
cl := jwt.MapClaims{}
|
||||||
|
maps.Copy(cl, claims)
|
||||||
|
|
||||||
|
// Set standard claims after user claims to prevent override
|
||||||
|
cl["iat"] = jwt.NewNumericDate(time.Now().UTC())
|
||||||
|
cl["exp"] = jwt.NewNumericDate(time.Now().Add(d))
|
||||||
|
|
||||||
|
if issuer != "" {
|
||||||
|
cl["iss"] = issuer
|
||||||
|
}
|
||||||
|
|
||||||
|
if audience != "" {
|
||||||
|
cl["aud"] = audience
|
||||||
|
}
|
||||||
|
|
||||||
|
if subject != "" {
|
||||||
|
cl["sub"] = subject
|
||||||
|
}
|
||||||
|
|
||||||
|
t := jwt.NewWithClaims(jwt.SigningMethodES256, cl)
|
||||||
|
return t.SignedString(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseES256 parses and validates a JWT signed with ES256 (ECDSA P-256) algorithm.
|
||||||
|
// This is required for Apple Sign In which mandates ES256.
|
||||||
|
// issuer and audience are typically validated, while subject is optional (pass empty string to skip).
|
||||||
|
func ParseES256(key *ecdsa.PublicKey, tokenString, issuer, audience string) (jwt.MapClaims, error) {
|
||||||
|
opts := []jwt.ParserOption{
|
||||||
|
jwt.WithValidMethods([]string{jwt.SigningMethodES256.Alg()}),
|
||||||
|
jwt.WithIssuedAt(),
|
||||||
|
jwt.WithExpirationRequired(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if issuer != "" {
|
||||||
|
opts = append(opts, jwt.WithIssuer(issuer))
|
||||||
|
}
|
||||||
|
if audience != "" {
|
||||||
|
opts = append(opts, jwt.WithAudience(audience))
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := jwt.Parse(
|
||||||
|
tokenString,
|
||||||
|
func(token *jwt.Token) (any, error) {
|
||||||
|
if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
|
||||||
|
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||||
|
}
|
||||||
|
return key, nil
|
||||||
|
},
|
||||||
|
opts...,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse JWT token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims, ok := token.Claims.(jwt.MapClaims); ok {
|
||||||
|
return claims, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("no claims found in token")
|
||||||
|
}
|
||||||
|
|||||||
133
jwt/jwt_test.go
133
jwt/jwt_test.go
@@ -6,6 +6,9 @@
|
|||||||
package jwt
|
package jwt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
"fmt"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -85,3 +88,133 @@ func TestHS256(t *testing.T) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestES256(t *testing.T) {
|
||||||
|
// Generate ECDSA P-256 key pair for testing
|
||||||
|
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
claims := map[string]any{
|
||||||
|
"email": "user@example.com",
|
||||||
|
}
|
||||||
|
issuer := "https://appleid.apple.com"
|
||||||
|
audience := "com.example.app"
|
||||||
|
subject := "001234.56789abcdef.1234"
|
||||||
|
|
||||||
|
// Sign with issuer, audience, and subject
|
||||||
|
token, err := SignES256(privKey, issuer, audience, subject, time.Hour, claims)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Log("ES256 token:", token)
|
||||||
|
|
||||||
|
// Parse with issuer and audience validation
|
||||||
|
parsedClaims, err := ParseES256(&privKey.PublicKey, token, issuer, audience)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify claims
|
||||||
|
if parsedClaims["sub"] != subject {
|
||||||
|
t.Errorf("expected sub to be '%s', got %v", subject, parsedClaims["sub"])
|
||||||
|
}
|
||||||
|
if parsedClaims["aud"] != audience {
|
||||||
|
t.Errorf("expected aud to be '%s', got %v", audience, parsedClaims["aud"])
|
||||||
|
}
|
||||||
|
if parsedClaims["email"] != "user@example.com" {
|
||||||
|
t.Errorf("expected email to be 'user@example.com', got %v", parsedClaims["email"])
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("Parsed claims: %v", parsedClaims)
|
||||||
|
|
||||||
|
// Test parsing without validation (empty strings)
|
||||||
|
parsedClaims2, err := ParseES256(&privKey.PublicKey, token, "", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if parsedClaims2["sub"] != subject {
|
||||||
|
t.Errorf("expected sub to be '%s', got %v", subject, parsedClaims2["sub"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestES256_ExpiredToken(t *testing.T) {
|
||||||
|
// Generate ECDSA P-256 key pair for testing
|
||||||
|
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
claims := map[string]any{}
|
||||||
|
issuer := "https://appleid.apple.com"
|
||||||
|
subject := "001234.56789abcdef.1234"
|
||||||
|
|
||||||
|
// Sign with very short duration
|
||||||
|
token, err := SignES256(privKey, issuer, "", subject, time.Nanosecond, claims)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for token to expire
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
|
||||||
|
// Parse should fail due to expiration
|
||||||
|
_, err = ParseES256(&privKey.PublicKey, token, issuer, "")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("expected error for expired token, got nil")
|
||||||
|
}
|
||||||
|
t.Logf("Expected error for expired token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestES256_InvalidIssuer(t *testing.T) {
|
||||||
|
// Generate ECDSA P-256 key pair for testing
|
||||||
|
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
claims := map[string]any{}
|
||||||
|
issuer := "https://appleid.apple.com"
|
||||||
|
subject := "001234.56789abcdef.1234"
|
||||||
|
|
||||||
|
// Sign with one issuer
|
||||||
|
token, err := SignES256(privKey, issuer, "", subject, time.Hour, claims)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse with different issuer should fail
|
||||||
|
_, err = ParseES256(&privKey.PublicKey, token, "https://wrong-issuer.com", "")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("expected error for invalid issuer, got nil")
|
||||||
|
}
|
||||||
|
t.Logf("Expected error for invalid issuer: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestES256_InvalidAudience(t *testing.T) {
|
||||||
|
// Generate ECDSA P-256 key pair for testing
|
||||||
|
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
claims := map[string]any{}
|
||||||
|
issuer := "https://appleid.apple.com"
|
||||||
|
audience := "com.example.app"
|
||||||
|
subject := "001234.56789abcdef.1234"
|
||||||
|
|
||||||
|
// Sign with one audience
|
||||||
|
token, err := SignES256(privKey, issuer, audience, subject, time.Hour, claims)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse with different audience should fail
|
||||||
|
_, err = ParseES256(&privKey.PublicKey, token, issuer, "com.wrong.app")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("expected error for invalid audience, got nil")
|
||||||
|
}
|
||||||
|
t.Logf("Expected error for invalid audience: %v", err)
|
||||||
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ func cleaninput(input string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func open(input string) *exec.Cmd {
|
func open(input string) *exec.Cmd {
|
||||||
cmd := exec.Command(runDll32, cmd, input)
|
cmd := exec.Command(runDll32, cmd, cleaninput(input))
|
||||||
// cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
// cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|||||||
12
ptr/ptr.go
12
ptr/ptr.go
@@ -7,8 +7,9 @@ package ptr
|
|||||||
|
|
||||||
import "strings"
|
import "strings"
|
||||||
|
|
||||||
|
//go:fix inline
|
||||||
func Ref[T string | bool | Num](v T) *T {
|
func Ref[T string | bool | Num](v T) *T {
|
||||||
return &v
|
return new(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Deref[T any](v *T) T {
|
func Deref[T any](v *T) T {
|
||||||
@@ -19,16 +20,18 @@ func Deref[T any](v *T) T {
|
|||||||
return *v
|
return *v
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//go:fix inline
|
||||||
func Bool(v bool) *bool {
|
func Bool(v bool) *bool {
|
||||||
return &v
|
return new(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetBool(v *bool) bool {
|
func GetBool(v *bool) bool {
|
||||||
return Deref(v)
|
return Deref(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//go:fix inline
|
||||||
func Str(v string) *string {
|
func Str(v string) *string {
|
||||||
return &v
|
return new(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetStr(v *string) string {
|
func GetStr(v *string) string {
|
||||||
@@ -48,8 +51,9 @@ type Num interface {
|
|||||||
uint8 | int8 | uint16 | int16 | uint32 | int32 | uint64 | int64 | uint | int | float32 | float64
|
uint8 | int8 | uint16 | int16 | uint32 | int32 | uint64 | int64 | uint | int | float32 | float64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//go:fix inline
|
||||||
func Number[T Num](v T) *T {
|
func Number[T Num](v T) *T {
|
||||||
return &v
|
return new(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetNumber[T Num](v *T) T {
|
func GetNumber[T Num](v *T) T {
|
||||||
|
|||||||
@@ -4,31 +4,31 @@ import "testing"
|
|||||||
|
|
||||||
func TestRefDeref(t *testing.T) {
|
func TestRefDeref(t *testing.T) {
|
||||||
a := 10
|
a := 10
|
||||||
if Deref(Ref(a)) != a {
|
if Deref(new(a)) != a {
|
||||||
t.Log("a) had a issue")
|
t.Log("a) had a issue")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
b := 10.1
|
b := 10.1
|
||||||
if Deref(Ref(b)) != b {
|
if Deref(new(b)) != b {
|
||||||
t.Log("b) had a issue")
|
t.Log("b) had a issue")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c := true
|
c := true
|
||||||
if Deref(Ref(c)) != c {
|
if Deref(new(c)) != c {
|
||||||
t.Log("c) had a issue")
|
t.Log("c) had a issue")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
d := "hello there"
|
d := "hello there"
|
||||||
if Deref(Ref(d)) != d {
|
if Deref(new(d)) != d {
|
||||||
t.Log("d) had a issue")
|
t.Log("d) had a issue")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var e string
|
var e string
|
||||||
if Deref(Ref(e)) != e {
|
if Deref(new(e)) != e {
|
||||||
t.Log("e) had a issue")
|
t.Log("e) had a issue")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ import (
|
|||||||
"code.patial.tech/go/appcore/ptr"
|
"code.patial.tech/go/appcore/ptr"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// MaxPageSize is the maximum allowed page size to prevent resource exhaustion.
|
||||||
|
var MaxPageSize = 1000
|
||||||
|
|
||||||
type Pager struct {
|
type Pager struct {
|
||||||
OrderBy *string `json:"orderBy"`
|
OrderBy *string `json:"orderBy"`
|
||||||
OrderAsc *bool `json:"orderAsc"`
|
OrderAsc *bool `json:"orderAsc"`
|
||||||
@@ -39,7 +42,9 @@ func (i *Pager) Offset() int {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
return (i.Page - 1) * i.Limit()
|
page := max(i.Page, 1)
|
||||||
|
|
||||||
|
return (page - 1) * i.Limit()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Pager) Limit() int {
|
func (i *Pager) Limit() int {
|
||||||
@@ -52,42 +57,47 @@ func (i *Pager) Limit() int {
|
|||||||
|
|
||||||
// GetPager info from request's query parameters
|
// GetPager info from request's query parameters
|
||||||
func GetPager(r *http.Request) Pager {
|
func GetPager(r *http.Request) Pager {
|
||||||
|
q := r.URL.Query()
|
||||||
|
|
||||||
p := Pager{
|
p := Pager{
|
||||||
Page: 1,
|
Page: 1,
|
||||||
Size: 20,
|
Size: 20,
|
||||||
OrderAsc: ptr.Bool(true),
|
OrderAsc: new(true),
|
||||||
}
|
}
|
||||||
|
|
||||||
if v := r.URL.Query().Get("q"); v != "" {
|
if v := q.Get("q"); v != "" {
|
||||||
p.Search = strings.TrimSpace(v)
|
p.Search = strings.TrimSpace(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
if v := r.URL.Query().Get("pg"); v != "" {
|
if v := q.Get("pg"); v != "" {
|
||||||
if vv, err := strconv.Atoi(v); err == nil {
|
if vv, err := strconv.Atoi(v); err == nil && vv > 0 {
|
||||||
p.Page = int(vv)
|
p.Page = vv
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v := r.URL.Query().Get("pg_s"); v != "" {
|
if v := q.Get("pg_s"); v != "" {
|
||||||
if vv, err := strconv.Atoi(v); err == nil {
|
if vv, err := strconv.Atoi(v); err == nil && vv > 0 {
|
||||||
p.Size = int(vv)
|
if vv > MaxPageSize {
|
||||||
|
vv = MaxPageSize
|
||||||
|
}
|
||||||
|
p.Size = vv
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v := r.URL.Query().Get("pg_ob"); v != "" {
|
if v := q.Get("pg_ob"); v != "" {
|
||||||
p.OrderBy = &v
|
p.OrderBy = &v
|
||||||
}
|
}
|
||||||
|
|
||||||
if v := r.URL.Query().Get("pg_o"); v != "" {
|
if v := q.Get("pg_o"); v != "" {
|
||||||
switch strings.ToLower(v) {
|
switch strings.ToLower(v) {
|
||||||
case "asc":
|
case "asc":
|
||||||
p.OrderAsc = ptr.Bool(true)
|
p.OrderAsc = new(true)
|
||||||
case "desc":
|
case "desc":
|
||||||
p.OrderAsc = ptr.Bool(false)
|
p.OrderAsc = new(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v := r.URL.Query().Get("pg_t"); v == "n" {
|
if v := q.Get("pg_t"); v == "n" {
|
||||||
p.TotalNeeded = true
|
p.TotalNeeded = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,10 +15,10 @@ import (
|
|||||||
"code.patial.tech/go/appcore/validate"
|
"code.patial.tech/go/appcore/validate"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MaxRequestBodySize is the maximum allowed size for request bodies (1MB default).
|
// MaxRequestBodySize is the maximum allowed size for request bodies (5MB default).
|
||||||
// This prevents resource exhaustion attacks from large payloads.
|
// This prevents resource exhaustion attacks from large payloads.
|
||||||
// Override this value if you need to accept larger requests.
|
// Override this value if you need to accept larger requests.
|
||||||
var MaxRequestBodySize int64 = 1 << 20 // 1MB
|
var MaxRequestBodySize int64 = 5 << 20 // 5MB
|
||||||
|
|
||||||
func FormField(r *http.Request, key string) (string, error) {
|
func FormField(r *http.Request, key string) (string, error) {
|
||||||
f, err := Payload[map[string]any](r)
|
f, err := Payload[map[string]any](r)
|
||||||
@@ -49,22 +49,24 @@ func PayloadWithValidate[T any](r *http.Request) (T, error) {
|
|||||||
func Payload[T any](r *http.Request) (T, error) {
|
func Payload[T any](r *http.Request) (T, error) {
|
||||||
var p T
|
var p T
|
||||||
|
|
||||||
|
if r.ContentLength > MaxRequestBodySize {
|
||||||
|
return p, errors.New("request body too large")
|
||||||
|
}
|
||||||
|
|
||||||
// Limit request body size to prevent resource exhaustion
|
// Limit request body size to prevent resource exhaustion
|
||||||
limited := io.LimitReader(r.Body, MaxRequestBodySize)
|
limited := io.LimitReader(r.Body, MaxRequestBodySize+1)
|
||||||
|
|
||||||
decoder := json.NewDecoder(limited)
|
decoder := json.NewDecoder(limited)
|
||||||
if err := decoder.Decode(&p); err != nil {
|
if err := decoder.Decode(&p); err != nil {
|
||||||
// Check if we hit the size limit
|
|
||||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
|
||||||
// Try to read one more byte to see if there's more data
|
|
||||||
var buf [1]byte
|
|
||||||
if n, _ := limited.Read(buf[:]); n == 0 {
|
|
||||||
// We hit the limit
|
|
||||||
return p, errors.New("request body too large")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return p, err
|
return p, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if there's more data beyond the limit
|
||||||
|
var buf [1]byte
|
||||||
|
if n, _ := limited.Read(buf[:]); n > 0 {
|
||||||
|
return p, errors.New("request body too large")
|
||||||
|
}
|
||||||
|
|
||||||
return p, nil
|
return p, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,21 +74,23 @@ func Payload[T any](r *http.Request) (T, error) {
|
|||||||
// This is useful when you want to decode into an existing variable.
|
// This is useful when you want to decode into an existing variable.
|
||||||
// The request body size is limited by MaxRequestBodySize to prevent DoS attacks.
|
// The request body size is limited by MaxRequestBodySize to prevent DoS attacks.
|
||||||
func DecodeJSON(r *http.Request, v any) error {
|
func DecodeJSON(r *http.Request, v any) error {
|
||||||
|
if r.ContentLength > MaxRequestBodySize {
|
||||||
|
return errors.New("request body too large")
|
||||||
|
}
|
||||||
|
|
||||||
// Limit request body size to prevent resource exhaustion
|
// Limit request body size to prevent resource exhaustion
|
||||||
limited := io.LimitReader(r.Body, MaxRequestBodySize)
|
limited := io.LimitReader(r.Body, MaxRequestBodySize+1)
|
||||||
|
|
||||||
decoder := json.NewDecoder(limited)
|
decoder := json.NewDecoder(limited)
|
||||||
if err := decoder.Decode(v); err != nil {
|
if err := decoder.Decode(v); err != nil {
|
||||||
// Check if we hit the size limit
|
|
||||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
|
||||||
// Try to read one more byte to see if there's more data
|
|
||||||
var buf [1]byte
|
|
||||||
if n, _ := limited.Read(buf[:]); n == 0 {
|
|
||||||
// We hit the limit
|
|
||||||
return errors.New("request body too large")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if there's more data beyond the limit
|
||||||
|
var buf [1]byte
|
||||||
|
if n, _ := limited.Read(buf[:]); n > 0 {
|
||||||
|
return errors.New("request body too large")
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,13 +19,13 @@ type Number interface {
|
|||||||
// NumberParam from request query string
|
// NumberParam from request query string
|
||||||
func NumberParam[T Number](r *http.Request, key string) (T, error) {
|
func NumberParam[T Number](r *http.Request, key string) (T, error) {
|
||||||
var noop T
|
var noop T
|
||||||
if !r.URL.Query().Has(key) {
|
q := r.URL.Query()
|
||||||
|
if !q.Has(key) {
|
||||||
return noop, fmt.Errorf("query param: %q is missing", key)
|
return noop, fmt.Errorf("query param: %q is missing", key)
|
||||||
}
|
}
|
||||||
|
|
||||||
p := r.URL.Query().Get(key)
|
p := q.Get(key)
|
||||||
t := reflect.TypeOf(noop)
|
k := reflect.TypeOf(noop).Kind()
|
||||||
k := t.Kind()
|
|
||||||
// float param
|
// float param
|
||||||
if k == reflect.Float32 || k == reflect.Float64 {
|
if k == reflect.Float32 || k == reflect.Float64 {
|
||||||
n, err := strconv.ParseFloat(p, 64)
|
n, err := strconv.ParseFloat(p, 64)
|
||||||
@@ -35,10 +35,21 @@ func NumberParam[T Number](r *http.Request, key string) (T, error) {
|
|||||||
return T(n), nil
|
return T(n), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// int param
|
// unsigned int param
|
||||||
|
if k >= reflect.Uint && k <= reflect.Uint64 {
|
||||||
|
n, err := strconv.ParseUint(p, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return noop, fmt.Errorf("query param: %q is not a valid unsigned integer", key)
|
||||||
|
}
|
||||||
|
|
||||||
|
return T(n), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// signed int param
|
||||||
n, err := strconv.ParseInt(p, 10, 64)
|
n, err := strconv.ParseInt(p, 10, 64)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return noop, fmt.Errorf("query param: %q is not a valid integer", key)
|
return noop, fmt.Errorf("query param: %q is not a valid integer", key)
|
||||||
}
|
}
|
||||||
|
|
||||||
return T(n), nil
|
return T(n), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,10 +59,12 @@ func reply(w http.ResponseWriter, data any, p *request.Pager) {
|
|||||||
|
|
||||||
// json data...
|
// json data...
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
json.NewEncoder(w).Encode(Detail{
|
if err := json.NewEncoder(w).Encode(Detail{
|
||||||
Data: data,
|
Data: data,
|
||||||
Pager: p,
|
Pager: p,
|
||||||
})
|
}); err != nil {
|
||||||
|
slog.Error(err.Error())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func BadRequest(w http.ResponseWriter, err error) {
|
func BadRequest(w http.ResponseWriter, err error) {
|
||||||
@@ -92,9 +94,14 @@ func SessionExpired(w http.ResponseWriter) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use NotAuthorized instead.
|
||||||
func NotAutorized(w http.ResponseWriter) {
|
func NotAutorized(w http.ResponseWriter) {
|
||||||
|
NotAuthorized(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NotAuthorized(w http.ResponseWriter) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusForbidden)
|
||||||
_, writeErr := fmt.Fprint(w, "{\"error\": \"You are not authorized to perform this action\"}")
|
_, writeErr := fmt.Fprint(w, "{\"error\": \"You are not authorized to perform this action\"}")
|
||||||
if writeErr != nil {
|
if writeErr != nil {
|
||||||
slog.Error(writeErr.Error())
|
slog.Error(writeErr.Error())
|
||||||
|
|||||||
@@ -20,13 +20,21 @@ func Map(obj any) map[string]any {
|
|||||||
|
|
||||||
for i := range val.NumField() {
|
for i := range val.NumField() {
|
||||||
fieldName := typ.Field(i).Name
|
fieldName := typ.Field(i).Name
|
||||||
fieldValueKind := val.Field(i).Kind()
|
field := val.Field(i)
|
||||||
|
fieldValueKind := field.Kind()
|
||||||
var fieldValue any
|
var fieldValue any
|
||||||
|
|
||||||
if fieldValueKind == reflect.Struct {
|
switch fieldValueKind {
|
||||||
fieldValue = Map(val.Field(i).Interface())
|
case reflect.Struct:
|
||||||
} else {
|
fieldValue = Map(field.Interface())
|
||||||
fieldValue = val.Field(i).Interface()
|
case reflect.Pointer:
|
||||||
|
if !field.IsNil() && field.Elem().Kind() == reflect.Struct {
|
||||||
|
fieldValue = Map(field.Elem().Interface())
|
||||||
|
} else {
|
||||||
|
fieldValue = field.Interface()
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
fieldValue = field.Interface()
|
||||||
}
|
}
|
||||||
|
|
||||||
result[fieldName] = fieldValue
|
result[fieldName] = fieldValue
|
||||||
|
|||||||
36
uid/sqid.go
36
uid/sqid.go
@@ -5,15 +5,45 @@
|
|||||||
|
|
||||||
package uid
|
package uid
|
||||||
|
|
||||||
import "github.com/sqids/sqids-go"
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/sqids/sqids-go"
|
||||||
|
)
|
||||||
|
|
||||||
type Service interface {
|
type Service interface {
|
||||||
SquiOptions() sqids.Options
|
SquiOptions() sqids.Options
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
mu sync.Mutex
|
||||||
|
sqidInst *sqids.Sqids
|
||||||
|
sqidOpts *sqids.Options
|
||||||
|
)
|
||||||
|
|
||||||
|
func getSqids(svc Service) (*sqids.Sqids, error) {
|
||||||
|
opts := svc.SquiOptions()
|
||||||
|
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
|
||||||
|
if sqidInst != nil && sqidOpts != nil && opts.Alphabet == sqidOpts.Alphabet && opts.MinLength == sqidOpts.MinLength {
|
||||||
|
return sqidInst, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
s, err := sqids.New(opts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
sqidInst = s
|
||||||
|
sqidOpts = &opts
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Encode a slice of IDs into one unique ID
|
// Encode a slice of IDs into one unique ID
|
||||||
func Encode(svc Service, ids ...uint64) (string, error) {
|
func Encode(svc Service, ids ...uint64) (string, error) {
|
||||||
s, err := sqids.New(svc.SquiOptions())
|
s, err := getSqids(svc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -23,7 +53,7 @@ func Encode(svc Service, ids ...uint64) (string, error) {
|
|||||||
|
|
||||||
// Decode an ID back to slice of IDs
|
// Decode an ID back to slice of IDs
|
||||||
func Decode(svc Service, id string) ([]uint64, error) {
|
func Decode(svc Service, id string) ([]uint64, error) {
|
||||||
s, err := sqids.New(svc.SquiOptions())
|
s, err := getSqids(svc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user