mirror of
https://github.com/yusing/godoxy.git
synced 2026-02-16 05:47:45 +01:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4df31263b5 | ||
|
|
9eae809690 | ||
|
|
f1ba554a24 | ||
|
|
f9a8aede20 | ||
|
|
e275ee634c | ||
|
|
797d88772f | ||
|
|
8ef8015a7f | ||
|
|
5fce4b445b | ||
|
|
7552a706a7 | ||
|
|
e1bc6d1f44 |
@@ -9,7 +9,7 @@ require (
|
||||
github.com/docker/docker v28.1.1+incompatible
|
||||
github.com/rs/zerolog v1.34.0
|
||||
github.com/stretchr/testify v1.10.0
|
||||
github.com/yusing/go-proxy v0.11.9
|
||||
github.com/yusing/go-proxy v0.12.0
|
||||
)
|
||||
|
||||
replace github.com/docker/docker => github.com/godoxy-app/docker v0.0.0-20250425105916-b2ad800de7a1
|
||||
|
||||
10
go.mod
10
go.mod
@@ -41,8 +41,8 @@ require (
|
||||
github.com/samber/slog-zerolog/v2 v2.7.3
|
||||
github.com/spf13/afero v1.14.0
|
||||
github.com/stretchr/testify v1.10.0
|
||||
github.com/yusing/go-proxy/agent v0.0.0-20250501215534-7fa7b55b1889
|
||||
github.com/yusing/go-proxy/internal/dnsproviders v0.0.0-20250501215534-7fa7b55b1889
|
||||
github.com/yusing/go-proxy/agent v0.0.0-20250503173201-5f780f490224
|
||||
github.com/yusing/go-proxy/internal/dnsproviders v0.0.0-20250503173201-5f780f490224
|
||||
go.uber.org/atomic v1.11.0
|
||||
)
|
||||
|
||||
@@ -205,7 +205,7 @@ require (
|
||||
github.com/softlayer/xmlrpc v0.0.0-20200409220501-5f089df7cb7e // indirect
|
||||
github.com/sony/gobreaker v1.0.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/cast v1.7.1 // indirect
|
||||
github.com/spf13/cast v1.8.0 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
github.com/spf13/viper v1.20.1 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
@@ -243,12 +243,12 @@ require (
|
||||
google.golang.org/protobuf v1.36.6 // indirect
|
||||
gopkg.in/inf.v0 v0.9.1 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/ns1/ns1-go.v2 v2.14.2 // indirect
|
||||
gopkg.in/ns1/ns1-go.v2 v2.14.3 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
k8s.io/api v0.33.0 // indirect
|
||||
k8s.io/apimachinery v0.33.0 // indirect
|
||||
k8s.io/klog/v2 v2.130.1 // indirect
|
||||
k8s.io/utils v0.0.0-20250321185631-1f6e0b77f77e // indirect
|
||||
k8s.io/utils v0.0.0-20250502105355-0f33e8f1c979 // indirect
|
||||
sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect
|
||||
sigs.k8s.io/randfill v1.0.0 // indirect
|
||||
sigs.k8s.io/structured-merge-diff/v4 v4.7.0 // indirect
|
||||
|
||||
12
go.sum
12
go.sum
@@ -1572,8 +1572,8 @@ github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZ
|
||||
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48=
|
||||
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
|
||||
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk=
|
||||
github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
|
||||
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
|
||||
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
||||
@@ -2523,8 +2523,8 @@ gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
|
||||
gopkg.in/ns1/ns1-go.v2 v2.14.2 h1:wz/toj9U20wBrmYxW4vTz7sZWED+JJVRjUBBJ7CKrzI=
|
||||
gopkg.in/ns1/ns1-go.v2 v2.14.2/go.mod h1:pfaU0vECVP7DIOr453z03HXS6dFJpXdNRwOyRzwmPSc=
|
||||
gopkg.in/ns1/ns1-go.v2 v2.14.3 h1:Yn72GgB6AA9I4602AsLMtbC1ZKT5EUrKiG+IPS+Ovr0=
|
||||
gopkg.in/ns1/ns1-go.v2 v2.14.3/go.mod h1:pfaU0vECVP7DIOr453z03HXS6dFJpXdNRwOyRzwmPSc=
|
||||
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
@@ -2560,8 +2560,8 @@ k8s.io/apimachinery v0.33.0 h1:1a6kHrJxb2hs4t8EE5wuR/WxKDwGN1FKH3JvDtA0CIQ=
|
||||
k8s.io/apimachinery v0.33.0/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM=
|
||||
k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
|
||||
k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=
|
||||
k8s.io/utils v0.0.0-20250321185631-1f6e0b77f77e h1:KqK5c/ghOm8xkHYhlodbp6i6+r+ChV2vuAuVRdFbLro=
|
||||
k8s.io/utils v0.0.0-20250321185631-1f6e0b77f77e/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
|
||||
k8s.io/utils v0.0.0-20250502105355-0f33e8f1c979 h1:jgJW5IePPXLGB8e/1wvd0Ich9QE97RvvF3a8J3fP/Lg=
|
||||
k8s.io/utils v0.0.0-20250502105355-0f33e8f1c979/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
|
||||
lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
|
||||
lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
|
||||
modernc.org/cc/v3 v3.36.0/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=
|
||||
|
||||
@@ -131,7 +131,7 @@ func (auth *OIDCProvider) setSessionTokenCookie(w http.ResponseWriter, r *http.R
|
||||
logging.Err(err).Msg("failed to sign session token")
|
||||
return
|
||||
}
|
||||
setTokenCookie(w, r, CookieOauthSessionToken, signed, common.APIJWTTokenTTL)
|
||||
SetTokenCookie(w, r, CookieOauthSessionToken, signed, common.APIJWTTokenTTL)
|
||||
}
|
||||
|
||||
func (auth *OIDCProvider) parseSessionJWT(sessionJWT string) (claims *sessionClaims, valid bool, err error) {
|
||||
|
||||
@@ -176,7 +176,7 @@ func (auth *OIDCProvider) LoginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
state := generateState()
|
||||
setTokenCookie(w, r, CookieOauthState, state, 300*time.Second)
|
||||
SetTokenCookie(w, r, CookieOauthState, state, 300*time.Second)
|
||||
// redirect user to Idp
|
||||
http.Redirect(w, r, auth.oauthConfig.AuthCodeURL(state, optRedirectPostAuth(r)), http.StatusFound)
|
||||
}
|
||||
@@ -301,12 +301,12 @@ func (auth *OIDCProvider) LogoutHandler(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
func (auth *OIDCProvider) setIDTokenCookie(w http.ResponseWriter, r *http.Request, jwt string, ttl time.Duration) {
|
||||
setTokenCookie(w, r, CookieOauthToken, jwt, ttl)
|
||||
SetTokenCookie(w, r, CookieOauthToken, jwt, ttl)
|
||||
}
|
||||
|
||||
func (auth *OIDCProvider) clearCookie(w http.ResponseWriter, r *http.Request) {
|
||||
clearTokenCookie(w, r, CookieOauthToken)
|
||||
clearTokenCookie(w, r, CookieOauthSessionToken)
|
||||
ClearTokenCookie(w, r, CookieOauthToken)
|
||||
ClearTokenCookie(w, r, CookieOauthSessionToken)
|
||||
}
|
||||
|
||||
// handleTestCallback handles OIDC callback in test environment.
|
||||
@@ -323,7 +323,7 @@ func (auth *OIDCProvider) handleTestCallback(w http.ResponseWriter, r *http.Requ
|
||||
}
|
||||
|
||||
// Create test JWT token
|
||||
setTokenCookie(w, r, CookieOauthToken, "test", time.Hour)
|
||||
SetTokenCookie(w, r, CookieOauthToken, "test", time.Hour)
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ func (auth *UserPassAuth) PostAuthCallbackHandler(w http.ResponseWriter, r *http
|
||||
gphttp.ServerError(w, r, err)
|
||||
return
|
||||
}
|
||||
setTokenCookie(w, r, auth.TokenCookieName(), token, auth.tokenTTL)
|
||||
SetTokenCookie(w, r, auth.TokenCookieName(), token, auth.tokenTTL)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
@@ -128,7 +128,7 @@ func (auth *UserPassAuth) LoginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (auth *UserPassAuth) LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
||||
clearTokenCookie(w, r, auth.TokenCookieName())
|
||||
ClearTokenCookie(w, r, auth.TokenCookieName())
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ func cookieDomain(r *http.Request) string {
|
||||
return strutils.JoinRune(parts, '.')
|
||||
}
|
||||
|
||||
func setTokenCookie(w http.ResponseWriter, r *http.Request, name, value string, ttl time.Duration) {
|
||||
func SetTokenCookie(w http.ResponseWriter, r *http.Request, name, value string, ttl time.Duration) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
@@ -57,7 +57,7 @@ func setTokenCookie(w http.ResponseWriter, r *http.Request, name, value string,
|
||||
})
|
||||
}
|
||||
|
||||
func clearTokenCookie(w http.ResponseWriter, r *http.Request, name string) {
|
||||
func ClearTokenCookie(w http.ResponseWriter, r *http.Request, name string) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: name,
|
||||
Value: "",
|
||||
|
||||
@@ -14,6 +14,9 @@ func Multiline() *MultilineError {
|
||||
}
|
||||
|
||||
func (m *MultilineError) add(err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
m.Extras = append(m.Extras, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -68,75 +68,58 @@ func (err *nestedError) Is(other error) bool {
|
||||
var nilError = newError("<nil>")
|
||||
var bulletPrefix = []byte("• ")
|
||||
var markdownBulletPrefix = []byte("- ")
|
||||
var spaces = []byte(" ")
|
||||
var spaces = []byte(" ")
|
||||
|
||||
type appendLineFunc func(buf []byte, err error, level int) []byte
|
||||
|
||||
func (err *nestedError) Error() string {
|
||||
func (err *nestedError) fmtError(appendLine appendLineFunc) []byte {
|
||||
if err == nil {
|
||||
return nilError.Error()
|
||||
return appendLine(nil, nilError, 0)
|
||||
}
|
||||
buf := appendLineNormal(nil, err.Err, 0)
|
||||
if len(err.Extras) > 0 {
|
||||
if err.Err != nil {
|
||||
buf := appendLine(nil, err.Err, 0)
|
||||
buf = append(buf, '\n')
|
||||
buf = appendLines(buf, err.Extras, 1, appendLineNormal)
|
||||
buf = appendLines(buf, err.Extras, 1, appendLine)
|
||||
return buf
|
||||
}
|
||||
return string(buf)
|
||||
return appendLines(nil, err.Extras, 0, appendLine)
|
||||
}
|
||||
|
||||
func (err *nestedError) Error() string {
|
||||
return string(err.fmtError(appendLineNormal))
|
||||
}
|
||||
|
||||
func (err *nestedError) Plain() []byte {
|
||||
if err == nil {
|
||||
return appendLinePlain(nil, nilError, 0)
|
||||
}
|
||||
buf := appendLinePlain(nil, err.Err, 0)
|
||||
if len(err.Extras) > 0 {
|
||||
buf = append(buf, '\n')
|
||||
buf = appendLines(buf, err.Extras, 1, appendLinePlain)
|
||||
}
|
||||
return buf
|
||||
return err.fmtError(appendLinePlain)
|
||||
}
|
||||
|
||||
func (err *nestedError) Markdown() []byte {
|
||||
if err == nil {
|
||||
return appendLineMd(nil, nilError, 0)
|
||||
}
|
||||
return err.fmtError(appendLineMd)
|
||||
}
|
||||
|
||||
buf := appendLineMd(nil, err.Err, 0)
|
||||
if len(err.Extras) > 0 {
|
||||
buf = append(buf, '\n')
|
||||
buf = appendLines(buf, err.Extras, 1, appendLineMd)
|
||||
func appendLine(buf []byte, err error, level int, prefix []byte, format func(err error) []byte) []byte {
|
||||
if err == nil {
|
||||
return appendLine(buf, nilError, level, prefix, format)
|
||||
}
|
||||
if level == 0 {
|
||||
return append(buf, format(err)...)
|
||||
}
|
||||
buf = append(buf, spaces[:2*level]...)
|
||||
buf = append(buf, prefix...)
|
||||
buf = append(buf, format(err)...)
|
||||
return buf
|
||||
}
|
||||
|
||||
func appendLineNormal(buf []byte, err error, level int) []byte {
|
||||
if level == 0 {
|
||||
return append(buf, err.Error()...)
|
||||
}
|
||||
buf = append(buf, spaces[:2*level]...)
|
||||
buf = append(buf, bulletPrefix...)
|
||||
buf = append(buf, err.Error()...)
|
||||
return buf
|
||||
return appendLine(buf, err, level, bulletPrefix, Normal)
|
||||
}
|
||||
|
||||
func appendLinePlain(buf []byte, err error, level int) []byte {
|
||||
if level == 0 {
|
||||
return append(buf, Plain(err)...)
|
||||
}
|
||||
buf = append(buf, spaces[:2*level]...)
|
||||
buf = append(buf, bulletPrefix...)
|
||||
buf = append(buf, Plain(err)...)
|
||||
return buf
|
||||
return appendLine(buf, err, level, bulletPrefix, Plain)
|
||||
}
|
||||
|
||||
func appendLineMd(buf []byte, err error, level int) []byte {
|
||||
if level == 0 {
|
||||
return append(buf, Markdown(err)...)
|
||||
}
|
||||
buf = append(buf, spaces[:2*level]...)
|
||||
buf = append(buf, markdownBulletPrefix...)
|
||||
buf = append(buf, Markdown(err)...)
|
||||
return buf
|
||||
return appendLine(buf, err, level, markdownBulletPrefix, Markdown)
|
||||
}
|
||||
|
||||
func appendLines(buf []byte, errs []error, level int, appendLine appendLineFunc) []byte {
|
||||
@@ -154,6 +137,9 @@ func appendLines(buf []byte, errs []error, level int, appendLine appendLineFunc)
|
||||
buf = appendLines(buf, err.Extras, level, appendLine)
|
||||
}
|
||||
default:
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
buf = appendLine(buf, err, level)
|
||||
buf = append(buf, '\n')
|
||||
}
|
||||
|
||||
@@ -85,12 +85,27 @@ func Join(errors ...error) Error {
|
||||
return &nestedError{Extras: errs}
|
||||
}
|
||||
|
||||
func JoinLines(main error, errors ...string) Error {
|
||||
errs := make([]error, len(errors))
|
||||
for i, err := range errors {
|
||||
errs[i] = newError(err)
|
||||
}
|
||||
return &nestedError{Err: main, Extras: errs}
|
||||
}
|
||||
|
||||
func Collect[T any, Err error, Arg any, Func func(Arg) (T, Err)](eb *Builder, fn Func, arg Arg) T {
|
||||
result, err := fn(arg)
|
||||
eb.Add(err)
|
||||
return result
|
||||
}
|
||||
|
||||
func Normal(err error) []byte {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return []byte(err.Error())
|
||||
}
|
||||
|
||||
func Plain(err error) []byte {
|
||||
if err == nil {
|
||||
return nil
|
||||
|
||||
@@ -114,12 +114,18 @@ func fetchKnownIcon(ctx context.Context, url *IconURL) *FetchResult {
|
||||
return fetchIconAbsolute(ctx, url.URL())
|
||||
}
|
||||
|
||||
func fetchIcon(ctx context.Context, filetype, filename string) *FetchResult {
|
||||
result := fetchKnownIcon(ctx, NewSelfhStIconURL(filename, filetype))
|
||||
if result.OK() {
|
||||
return result
|
||||
func fetchIcon(ctx context.Context, filename string) *FetchResult {
|
||||
for _, fileType := range []string{"svg", "webp", "png"} {
|
||||
result := fetchKnownIcon(ctx, NewSelfhStIconURL(filename, fileType))
|
||||
if result.OK() {
|
||||
return result
|
||||
}
|
||||
result = fetchKnownIcon(ctx, NewWalkXCodeIconURL(filename, fileType))
|
||||
if result.OK() {
|
||||
return result
|
||||
}
|
||||
}
|
||||
return fetchKnownIcon(ctx, NewWalkXCodeIconURL(filename, filetype))
|
||||
return &FetchResult{StatusCode: http.StatusNotFound, ErrMsg: "no icon found"}
|
||||
}
|
||||
|
||||
func FindIcon(ctx context.Context, r route, uri string) *FetchResult {
|
||||
@@ -127,17 +133,18 @@ func FindIcon(ctx context.Context, r route, uri string) *FetchResult {
|
||||
return result
|
||||
}
|
||||
|
||||
result := fetchIcon(ctx, "png", sanitizeName(r.Reference()))
|
||||
if !result.OK() {
|
||||
if r, ok := r.(httpRoute); ok {
|
||||
// fallback to parse html
|
||||
result = findIconSlow(ctx, r, uri, nil)
|
||||
for _, ref := range r.References() {
|
||||
result := fetchIcon(ctx, sanitizeName(ref))
|
||||
if result.OK() {
|
||||
storeIconCache(r.Key(), result)
|
||||
return result
|
||||
}
|
||||
}
|
||||
if result.OK() {
|
||||
storeIconCache(r.Key(), result)
|
||||
if r, ok := r.(httpRoute); ok {
|
||||
// fallback to parse html
|
||||
return findIconSlow(ctx, r, uri, nil)
|
||||
}
|
||||
return result
|
||||
return &FetchResult{StatusCode: http.StatusNotFound, ErrMsg: "no icon found"}
|
||||
}
|
||||
|
||||
func findIconSlow(ctx context.Context, r httpRoute, uri string, stack []string) *FetchResult {
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
type route interface {
|
||||
pool.Object
|
||||
ProviderName() string
|
||||
Reference() string
|
||||
References() []string
|
||||
TargetURL() *gpnet.URL
|
||||
}
|
||||
|
||||
|
||||
@@ -12,9 +12,6 @@ func SetInstance(parent task.Parent, cfg *Config) gperr.Error {
|
||||
if err := newInstance.LoadMaxMindDB(parent); err != nil {
|
||||
return err
|
||||
}
|
||||
if instance != nil {
|
||||
instance.task.Finish("updated")
|
||||
}
|
||||
instance = newInstance
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
type MaxMind struct {
|
||||
*Config
|
||||
lastUpdate time.Time
|
||||
task *task.Task
|
||||
db struct {
|
||||
*maxminddb.Reader
|
||||
sync.RWMutex
|
||||
@@ -70,7 +69,9 @@ func (cfg *MaxMind) LoadMaxMindDB(parent task.Parent) gperr.Error {
|
||||
return nil
|
||||
}
|
||||
|
||||
cfg.task = parent.Subtask("maxmind_db", true)
|
||||
init := parent.Subtask("maxmind_db", true)
|
||||
defer init.Finish(nil)
|
||||
|
||||
path := dbPath(cfg)
|
||||
reader, err := maxmindDBOpen(path)
|
||||
valid := true
|
||||
@@ -95,7 +96,7 @@ func (cfg *MaxMind) LoadMaxMindDB(parent task.Parent) gperr.Error {
|
||||
} else {
|
||||
cfg.Logger().Info().Msg("MaxMind DB loaded")
|
||||
cfg.db.Reader = reader
|
||||
go cfg.scheduleUpdate(cfg.task)
|
||||
go cfg.scheduleUpdate(parent)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -114,7 +115,7 @@ func (cfg *MaxMind) setLastUpdate(t time.Time) {
|
||||
}
|
||||
|
||||
func (cfg *MaxMind) scheduleUpdate(parent task.Parent) {
|
||||
task := parent.Subtask("schedule_update", true)
|
||||
task := parent.Subtask("maxmind_schedule_update", true)
|
||||
ticker := time.NewTicker(updateInterval)
|
||||
|
||||
cfg.loadLastUpdate()
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/shirou/gopsutil/v4/cpu"
|
||||
@@ -71,6 +72,10 @@ func _() { // check if this behavior is not changed
|
||||
var _ sensors.Warnings = disk.Warnings{}
|
||||
}
|
||||
|
||||
func isNoDataAvailable(err error) bool {
|
||||
return errors.Is(err, syscall.ENODATA)
|
||||
}
|
||||
|
||||
func getSystemInfo(ctx context.Context, lastResult *SystemInfo) (*SystemInfo, error) {
|
||||
errs := gperr.NewBuilder("failed to get system info")
|
||||
var s SystemInfo
|
||||
@@ -99,6 +104,9 @@ func getSystemInfo(ctx context.Context, lastResult *SystemInfo) (*SystemInfo, er
|
||||
warnings := new(warning.Warning)
|
||||
if errors.As(err, &warnings) {
|
||||
for _, warning := range warnings.List {
|
||||
if isNoDataAvailable(warning) {
|
||||
continue
|
||||
}
|
||||
allWarnings.Add(warning)
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -3,6 +3,7 @@ package gphttp
|
||||
import (
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type (
|
||||
@@ -33,13 +34,20 @@ func GetContentType(h http.Header) ContentType {
|
||||
|
||||
func GetAccept(h http.Header) AcceptContentType {
|
||||
var accepts []ContentType
|
||||
for _, v := range h["Accept"] {
|
||||
acceptHeader := h["Accept"]
|
||||
if len(acceptHeader) == 1 {
|
||||
acceptHeader = strings.Split(acceptHeader[0], ",")
|
||||
}
|
||||
for _, v := range acceptHeader {
|
||||
ct, _, err := mime.ParseMediaType(v)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
accepts = append(accepts, ContentType(ct))
|
||||
}
|
||||
if len(accepts) == 0 {
|
||||
return []ContentType{"*/*"}
|
||||
}
|
||||
return accepts
|
||||
}
|
||||
|
||||
|
||||
69
internal/net/gphttp/httpheaders/csp.go
Normal file
69
internal/net/gphttp/httpheaders/csp.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package httpheaders
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AppendCSP appends a CSP header to specific directives in the response writer.
|
||||
//
|
||||
// Directives other than the ones in cspDirectives will be kept as is.
|
||||
//
|
||||
// It will replace 'none' with the sources.
|
||||
//
|
||||
// It will append 'self' to the sources if it's not already present.
|
||||
func AppendCSP(w http.ResponseWriter, r *http.Request, cspDirectives []string, sources []string) {
|
||||
csp := make(map[string]string)
|
||||
cspValues := r.Header.Values("Content-Security-Policy")
|
||||
if len(cspValues) == 1 {
|
||||
cspValues = strings.Split(cspValues[0], ";")
|
||||
for i, cspString := range cspValues {
|
||||
cspValues[i] = strings.TrimSpace(cspString)
|
||||
}
|
||||
}
|
||||
|
||||
for _, cspString := range cspValues {
|
||||
parts := strings.SplitN(cspString, " ", 2)
|
||||
if len(parts) == 2 {
|
||||
csp[parts[0]] = parts[1]
|
||||
}
|
||||
}
|
||||
|
||||
for _, directive := range cspDirectives {
|
||||
value, ok := csp[directive]
|
||||
if !ok {
|
||||
value = "'self'"
|
||||
}
|
||||
switch value {
|
||||
case "'self'":
|
||||
csp[directive] = value + " " + strings.Join(sources, " ")
|
||||
case "'none'":
|
||||
csp[directive] = strings.Join(sources, " ")
|
||||
default:
|
||||
for _, source := range sources {
|
||||
if !strings.Contains(value, source) {
|
||||
value += " " + source
|
||||
}
|
||||
}
|
||||
if !strings.Contains(value, "'self'") {
|
||||
value = "'self' " + value
|
||||
}
|
||||
csp[directive] = value
|
||||
}
|
||||
}
|
||||
|
||||
values := make([]string, 0, len(csp))
|
||||
for directive, value := range csp {
|
||||
values = append(values, directive+" "+value)
|
||||
}
|
||||
|
||||
// Remove existing CSP header, case insensitive
|
||||
for k := range w.Header() {
|
||||
if strings.EqualFold(k, "Content-Security-Policy") {
|
||||
delete(w.Header(), k)
|
||||
}
|
||||
}
|
||||
|
||||
// Set new CSP header
|
||||
w.Header()["Content-Security-Policy"] = values
|
||||
}
|
||||
168
internal/net/gphttp/httpheaders/csp_test.go
Normal file
168
internal/net/gphttp/httpheaders/csp_test.go
Normal file
@@ -0,0 +1,168 @@
|
||||
package httpheaders
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAppendCSP(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
initialHeaders map[string][]string
|
||||
sources []string
|
||||
directives []string
|
||||
expectedCSP map[string]string
|
||||
}{
|
||||
{
|
||||
name: "No CSP header",
|
||||
initialHeaders: map[string][]string{},
|
||||
sources: []string{},
|
||||
directives: []string{"default-src", "script-src", "frame-src", "style-src", "connect-src"},
|
||||
expectedCSP: map[string]string{"default-src": "'self'", "script-src": "'self'", "frame-src": "'self'", "style-src": "'self'", "connect-src": "'self'"},
|
||||
},
|
||||
{
|
||||
name: "No CSP header with sources",
|
||||
initialHeaders: map[string][]string{},
|
||||
sources: []string{"https://example.com"},
|
||||
directives: []string{"default-src", "script-src", "frame-src", "style-src", "connect-src"},
|
||||
expectedCSP: map[string]string{"default-src": "'self' https://example.com", "script-src": "'self' https://example.com", "frame-src": "'self' https://example.com", "style-src": "'self' https://example.com", "connect-src": "'self' https://example.com"},
|
||||
},
|
||||
{
|
||||
name: "replace 'none' with sources",
|
||||
initialHeaders: map[string][]string{
|
||||
"Content-Security-Policy": {"default-src 'none'"},
|
||||
},
|
||||
sources: []string{"https://example.com"},
|
||||
directives: []string{"default-src"},
|
||||
expectedCSP: map[string]string{"default-src": "https://example.com"},
|
||||
},
|
||||
{
|
||||
name: "CSP header with some directives",
|
||||
initialHeaders: map[string][]string{
|
||||
"Content-Security-Policy": {"default-src 'none'", "script-src 'unsafe-inline'"},
|
||||
},
|
||||
sources: []string{"https://example.com"},
|
||||
directives: []string{"script-src"},
|
||||
expectedCSP: map[string]string{
|
||||
"default-src": "'none",
|
||||
"script-src": "'unsafe-inline' https://example.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "CSP header with some directives with self",
|
||||
initialHeaders: map[string][]string{
|
||||
"Content-Security-Policy": {"default-src 'self'", "connect-src 'self'"},
|
||||
},
|
||||
sources: []string{"https://api.example.com"},
|
||||
directives: []string{"default-src", "connect-src"},
|
||||
expectedCSP: map[string]string{
|
||||
"default-src": "'self' https://api.example.com",
|
||||
"connect-src": "'self' https://api.example.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "AppendCSP sources conflict with existing CSP header",
|
||||
initialHeaders: map[string][]string{
|
||||
"Content-Security-Policy": {"default-src 'self' https://cdn.example.com", "script-src 'unsafe-inline'"},
|
||||
},
|
||||
sources: []string{"https://cdn.example.com", "https://api.example.com"},
|
||||
directives: []string{"default-src", "script-src"},
|
||||
expectedCSP: map[string]string{
|
||||
"default-src": "'self' https://cdn.example.com https://api.example.com",
|
||||
"script-src": "'unsafe-inline' https://cdn.example.com https://api.example.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Non-standard CSP directive",
|
||||
initialHeaders: map[string][]string{
|
||||
"Content-Security-Policy": {
|
||||
"default-src 'self'",
|
||||
"script-src 'unsafe-inline'",
|
||||
"img-src 'self'", // img-src is not in cspDirectives list
|
||||
},
|
||||
},
|
||||
sources: []string{"https://example.com"},
|
||||
directives: []string{"default-src", "script-src"},
|
||||
expectedCSP: map[string]string{
|
||||
"default-src": "'self' https://example.com",
|
||||
"script-src": "'unsafe-inline' https://example.com",
|
||||
// img-src should not be present in response as it's not in cspDirectives
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Create a test request with initial headers
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
for header, values := range tc.initialHeaders {
|
||||
req.Header[header] = values
|
||||
}
|
||||
|
||||
// Create a test response recorder
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// Call the function under test
|
||||
AppendCSP(w, req, tc.directives, tc.sources)
|
||||
|
||||
// Check the resulting CSP headers
|
||||
respHeaders := w.Header()
|
||||
cspValues, exists := respHeaders["Content-Security-Policy"]
|
||||
|
||||
// If we expect no CSP headers, verify none exist
|
||||
if len(tc.expectedCSP) == 0 {
|
||||
if exists && len(cspValues) > 0 {
|
||||
t.Errorf("Expected no CSP header, but got %v", cspValues)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Verify CSP headers exist when expected
|
||||
if !exists || len(cspValues) == 0 {
|
||||
t.Errorf("Expected CSP header to be set, but it was not")
|
||||
return
|
||||
}
|
||||
|
||||
// Parse the CSP response and verify each directive
|
||||
foundDirectives := make(map[string]string)
|
||||
for _, cspValue := range cspValues {
|
||||
parts := strings.Split(cspValue, ";")
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
directiveParts := strings.SplitN(part, " ", 2)
|
||||
if len(directiveParts) != 2 {
|
||||
t.Errorf("Invalid CSP directive format: %s", part)
|
||||
continue
|
||||
}
|
||||
|
||||
directive := directiveParts[0]
|
||||
value := directiveParts[1]
|
||||
foundDirectives[directive] = value
|
||||
}
|
||||
}
|
||||
|
||||
// Verify expected directives
|
||||
for directive, expectedValue := range tc.expectedCSP {
|
||||
actualValue, ok := foundDirectives[directive]
|
||||
if !ok {
|
||||
t.Errorf("Expected directive %s not found in response", directive)
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if all expected sources are in the actual value
|
||||
expectedSources := strings.SplitSeq(expectedValue, " ")
|
||||
for source := range expectedSources {
|
||||
if !strings.Contains(actualValue, source) {
|
||||
t.Errorf("Directive %s missing expected source %s. Got: %s", directive, source, actualValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
17
internal/net/gphttp/middleware/captcha.go
Normal file
17
internal/net/gphttp/middleware/captcha.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/yusing/go-proxy/internal/net/gphttp/middleware/captcha"
|
||||
)
|
||||
|
||||
type hCaptcha struct {
|
||||
captcha.HcaptchaProvider
|
||||
}
|
||||
|
||||
func (h *hCaptcha) before(w http.ResponseWriter, r *http.Request) (proceed bool) {
|
||||
return captcha.PreRequest(h, w, r)
|
||||
}
|
||||
|
||||
var HCaptcha = NewMiddleware[hCaptcha]()
|
||||
293
internal/net/gphttp/middleware/captcha/captcha.html
Normal file
293
internal/net/gphttp/middleware/captcha/captcha.html
Normal file
@@ -0,0 +1,293 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Verification Required</title>
|
||||
{{.ScriptHTML}}
|
||||
<script>
|
||||
function updateTheme() {
|
||||
const theme = window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light";
|
||||
document
|
||||
.querySelector("#verification-form > :first-child")
|
||||
.setAttribute("data-theme", theme);
|
||||
}
|
||||
window.addEventListener("load", updateTheme);
|
||||
</script>
|
||||
<style>
|
||||
:root {
|
||||
/* Light mode colors */
|
||||
--background-light: #f8f9fa;
|
||||
--text-light: #2d3748;
|
||||
--container-bg-light: #ffffff;
|
||||
--shadow-light: rgba(0, 0, 0, 0.08);
|
||||
--heading-light: #3d4852;
|
||||
--button-bg-light: #4f46e5;
|
||||
--button-hover-light: #4338ca;
|
||||
--button-disabled-bg-light: #e9ecef;
|
||||
--button-disabled-text-light: #a0aec0;
|
||||
--accent-light: #6366f1;
|
||||
|
||||
/* Dark mode colors */
|
||||
--background-dark: #111827;
|
||||
--text-dark: #e5e7eb;
|
||||
--container-bg-dark: #1f2937;
|
||||
--shadow-dark: rgba(0, 0, 0, 0.3);
|
||||
--heading-dark: #f3f4f6;
|
||||
--button-bg-dark: #6366f1;
|
||||
--button-hover-dark: #4f46e5;
|
||||
--button-disabled-bg-dark: #374151;
|
||||
--button-disabled-text-dark: #9ca3af;
|
||||
--accent-dark: #818cf8;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
body {
|
||||
background: linear-gradient(135deg, var(--background-light), #f0f4f8);
|
||||
color: var(--text-light);
|
||||
}
|
||||
.container {
|
||||
background-color: var(--container-bg-light);
|
||||
box-shadow: 0 10px 25px var(--shadow-light);
|
||||
border: 1px solid rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
h1 {
|
||||
color: var(--heading-light);
|
||||
}
|
||||
button {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
var(--button-bg-light),
|
||||
var(--accent-light)
|
||||
);
|
||||
}
|
||||
button:hover:not(:disabled) {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
var(--button-hover-light),
|
||||
var(--button-bg-light)
|
||||
);
|
||||
}
|
||||
button:disabled {
|
||||
background: var(--button-disabled-bg-light);
|
||||
color: var(--button-disabled-text-light);
|
||||
}
|
||||
.container::before {
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
rgba(99, 102, 241, 0.1),
|
||||
rgba(79, 70, 229, 0.05)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
background: linear-gradient(135deg, var(--background-dark), #0f172a);
|
||||
color: var(--text-dark);
|
||||
}
|
||||
.container {
|
||||
background-color: var(--container-bg-dark);
|
||||
box-shadow: 0 10px 25px var(--shadow-dark);
|
||||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
h1 {
|
||||
color: var(--heading-dark);
|
||||
}
|
||||
button {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
var(--button-bg-dark),
|
||||
var(--accent-dark)
|
||||
);
|
||||
}
|
||||
button:hover:not(:disabled) {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
var(--button-hover-dark),
|
||||
var(--button-bg-dark)
|
||||
);
|
||||
}
|
||||
button:disabled {
|
||||
background: var(--button-disabled-bg-dark);
|
||||
color: var(--button-disabled-text-dark);
|
||||
}
|
||||
.container::before {
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
rgba(99, 102, 241, 0.1),
|
||||
rgba(129, 140, 248, 0.05)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
font-family:
|
||||
"Inter",
|
||||
system-ui,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
"Segoe UI",
|
||||
Roboto,
|
||||
Oxygen,
|
||||
Ubuntu,
|
||||
Cantarell,
|
||||
"Open Sans",
|
||||
"Helvetica Neue",
|
||||
sans-serif;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
transition:
|
||||
background-color 0.5s ease,
|
||||
color 0.3s ease;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.container {
|
||||
position: relative;
|
||||
padding: 48px 42px;
|
||||
border-radius: 16px;
|
||||
text-align: center;
|
||||
max-width: 420px;
|
||||
width: 90%;
|
||||
transition:
|
||||
background-color 0.3s ease,
|
||||
box-shadow 0.3s ease,
|
||||
transform 0.3s ease;
|
||||
overflow: hidden;
|
||||
animation: fadeIn 0.5s ease-out;
|
||||
}
|
||||
|
||||
.container::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: -10%;
|
||||
left: -10%;
|
||||
width: 120%;
|
||||
height: 120%;
|
||||
border-radius: 30%;
|
||||
opacity: 0.5;
|
||||
z-index: 0;
|
||||
transform: rotate(-8deg);
|
||||
}
|
||||
|
||||
.content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.75em;
|
||||
font-weight: 700;
|
||||
margin-bottom: 28px;
|
||||
transition: color 0.3s ease;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
button {
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 13px 30px;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
transition:
|
||||
all 0.25s ease,
|
||||
transform 0.15s ease;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
button:active:not(:disabled) {
|
||||
transform: translateY(0);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
button:focus {
|
||||
outline: none;
|
||||
box-shadow:
|
||||
0 0 0 2px rgba(99, 102, 241, 0.5),
|
||||
0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: not-allowed;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
#verification-form {
|
||||
margin-top: 30px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 22px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
#verification-form > :first-child {
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.description {
|
||||
color: var(--text-light);
|
||||
opacity: 0.85;
|
||||
font-size: 0.95rem;
|
||||
margin-bottom: 20px;
|
||||
max-width: 90%;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.description {
|
||||
color: var(--text-dark);
|
||||
opacity: 0.75;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
function onDataCallback() {
|
||||
document.getElementById("verification-form").submit();
|
||||
}
|
||||
</script>
|
||||
<div class="container">
|
||||
<div class="content">
|
||||
<h1>Human Verification</h1>
|
||||
<p class="description">
|
||||
Please complete the verification below to continue.
|
||||
</p>
|
||||
<form id="verification-form" method="POST" action="">
|
||||
{{.FormHTML}}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
96
internal/net/gphttp/middleware/captcha/hcaptcha.go
Normal file
96
internal/net/gphttp/middleware/captcha/hcaptcha.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
_ "embed"
|
||||
|
||||
"github.com/yusing/go-proxy/internal/gperr"
|
||||
)
|
||||
|
||||
type HcaptchaProvider struct {
|
||||
ProviderBase
|
||||
|
||||
SiteKey string `json:"site_key" validate:"required"`
|
||||
Secret string `json:"secret" validate:"required"`
|
||||
}
|
||||
|
||||
// https://docs.hcaptcha.com/#content-security-policy-settings
|
||||
func (p *HcaptchaProvider) CSPDirectives() []string {
|
||||
return []string{"script-src", "frame-src", "style-src", "connect-src"}
|
||||
}
|
||||
|
||||
// https://docs.hcaptcha.com/#content-security-policy-settings
|
||||
func (p *HcaptchaProvider) CSPSources() []string {
|
||||
return []string{
|
||||
"https://hcaptcha.com",
|
||||
"https://*.hcaptcha.com",
|
||||
}
|
||||
}
|
||||
|
||||
func (p *HcaptchaProvider) Verify(r *http.Request) error {
|
||||
response := r.PostFormValue("h-captcha-response")
|
||||
if response == "" {
|
||||
return errors.New("h-captcha-response is missing")
|
||||
}
|
||||
|
||||
remoteIP := r.RemoteAddr
|
||||
if ip, _, err := net.SplitHostPort(remoteIP); err == nil {
|
||||
remoteIP = ip
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
formData := url.Values{}
|
||||
formData.Set("secret", p.Secret)
|
||||
formData.Set("response", response)
|
||||
formData.Set("remoteip", remoteIP)
|
||||
formData.Set("sitekey", p.SiteKey)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.hcaptcha.com/siteverify", bytes.NewBufferString(formData.Encode()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respData struct {
|
||||
Success bool `json:"success"`
|
||||
Error []string `json:"error-codes"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&respData); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !respData.Success {
|
||||
return gperr.JoinLines(ErrCaptchaVerificationFailed, respData.Error...)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *HcaptchaProvider) ScriptHTML() string {
|
||||
return `
|
||||
<script src="https://js.hcaptcha.com/1/api.js" async defer></script>`
|
||||
}
|
||||
|
||||
func (p *HcaptchaProvider) FormHTML() string {
|
||||
return `
|
||||
<div
|
||||
class="h-captcha"
|
||||
data-sitekey="` + p.SiteKey + `"
|
||||
data-callback="onDataCallback"
|
||||
/>`
|
||||
}
|
||||
61
internal/net/gphttp/middleware/captcha/middleware.go
Normal file
61
internal/net/gphttp/middleware/captcha/middleware.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"text/template"
|
||||
|
||||
"github.com/yusing/go-proxy/internal/auth"
|
||||
"github.com/yusing/go-proxy/internal/logging"
|
||||
"github.com/yusing/go-proxy/internal/net/gphttp"
|
||||
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
const cookieName = "godoxy_captcha_session"
|
||||
|
||||
//go:embed captcha.html
|
||||
var captchaPageHTML string
|
||||
var captchaPage = template.Must(template.New("captcha").Parse(captchaPageHTML))
|
||||
|
||||
func PreRequest(p Provider, w http.ResponseWriter, r *http.Request) (proceed bool) {
|
||||
// check session
|
||||
sessionID, err := r.Cookie(cookieName)
|
||||
if err == nil {
|
||||
session, ok := CaptchaSessions.Load(sessionID.Value)
|
||||
if ok {
|
||||
if session.expired() {
|
||||
CaptchaSessions.Delete(sessionID.Value)
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !gphttp.GetAccept(r.Header).AcceptHTML() {
|
||||
gphttp.Forbidden(w, "Captcha is required")
|
||||
return false
|
||||
}
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
err := p.Verify(r)
|
||||
if err == nil {
|
||||
session := newCaptchaSession(p)
|
||||
CaptchaSessions.Store(session.ID, session)
|
||||
auth.SetTokenCookie(w, r, cookieName, session.ID, p.SessionExpiry())
|
||||
http.Redirect(w, r, r.URL.Path, http.StatusFound)
|
||||
return false
|
||||
}
|
||||
gphttp.Unauthorized(w, err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
// captcha challenge
|
||||
err = captchaPage.Execute(w, map[string]any{
|
||||
"ScriptHTML": p.ScriptHTML(),
|
||||
"FormHTML": p.FormHTML(),
|
||||
})
|
||||
if err != nil {
|
||||
logging.Error().Err(err).Msg("failed to execute captcha page")
|
||||
}
|
||||
return false
|
||||
}
|
||||
21
internal/net/gphttp/middleware/captcha/provider.go
Normal file
21
internal/net/gphttp/middleware/captcha/provider.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/yusing/go-proxy/internal/gperr"
|
||||
)
|
||||
|
||||
type Provider interface {
|
||||
CSPDirectives() []string
|
||||
CSPSources() []string
|
||||
Verify(r *http.Request) error
|
||||
SessionExpiry() time.Duration
|
||||
ScriptHTML() string
|
||||
FormHTML() string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrCaptchaVerificationFailed = gperr.New("captcha verification failed")
|
||||
)
|
||||
14
internal/net/gphttp/middleware/captcha/provider_base.go
Normal file
14
internal/net/gphttp/middleware/captcha/provider_base.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package captcha
|
||||
|
||||
import "time"
|
||||
|
||||
type ProviderBase struct {
|
||||
Expiry time.Duration `json:"session_expiry"`
|
||||
}
|
||||
|
||||
func (p *ProviderBase) SessionExpiry() time.Duration {
|
||||
if p.Expiry == 0 {
|
||||
p.Expiry = 24 * time.Hour
|
||||
}
|
||||
return p.Expiry
|
||||
}
|
||||
34
internal/net/gphttp/middleware/captcha/session.go
Normal file
34
internal/net/gphttp/middleware/captcha/session.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
|
||||
_ "embed"
|
||||
|
||||
"github.com/yusing/go-proxy/internal/jsonstore"
|
||||
"github.com/yusing/go-proxy/internal/utils"
|
||||
)
|
||||
|
||||
type CaptchaSession struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
Expiry time.Time `json:"expiry"`
|
||||
}
|
||||
|
||||
var CaptchaSessions = jsonstore.Store[*CaptchaSession]("captcha_sessions")
|
||||
|
||||
func newCaptchaSession(p Provider) *CaptchaSession {
|
||||
buf := make([]byte, 32)
|
||||
_, _ = rand.Read(buf)
|
||||
now := utils.TimeNow()
|
||||
return &CaptchaSession{
|
||||
ID: hex.EncodeToString(buf),
|
||||
Expiry: now.Add(p.SessionExpiry()),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CaptchaSession) expired() bool {
|
||||
return utils.TimeNow().After(s.Expiry)
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func NewMiddlewareChain(name string, chain []*Middleware) *Middleware {
|
||||
comp.setParent(m)
|
||||
}
|
||||
|
||||
if common.IsDebug {
|
||||
if common.IsTrace {
|
||||
for _, child := range chain {
|
||||
child.enableTrace()
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ var allMiddlewares = map[string]*Middleware{
|
||||
|
||||
"cidrwhitelist": CIDRWhiteList,
|
||||
"ratelimit": RateLimiter,
|
||||
|
||||
"hcaptcha": HCaptcha,
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -71,7 +71,7 @@ func (msg *LogMessage) notify(ctx context.Context, provider Provider) error {
|
||||
defer resp.Body.Close()
|
||||
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK, http.StatusCreated, http.StatusAccepted:
|
||||
case http.StatusOK, http.StatusCreated, http.StatusAccepted, http.StatusNoContent:
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
logging.Debug().
|
||||
Str("provider", provider.GetName()).
|
||||
|
||||
@@ -243,11 +243,14 @@ func (r *Route) TargetURL() *net.URL {
|
||||
return r.ProxyURL
|
||||
}
|
||||
|
||||
func (r *Route) Reference() string {
|
||||
func (r *Route) References() []string {
|
||||
if r.Container != nil {
|
||||
return r.Container.Image.Name
|
||||
if r.Container.ContainerName != r.Alias {
|
||||
return []string{r.Container.Image.Name, r.Container.ContainerName, r.Alias, r.Container.Image.Author}
|
||||
}
|
||||
return []string{r.Container.Image.Name, r.Alias, r.Container.Image.Author}
|
||||
}
|
||||
return r.Alias
|
||||
return []string{r.Alias}
|
||||
}
|
||||
|
||||
// Name implements pool.Object.
|
||||
@@ -476,21 +479,24 @@ func (r *Route) FinalizeHomepageConfig() {
|
||||
r.Homepage = r.Homepage.GetOverride(r.Alias)
|
||||
|
||||
hp := r.Homepage
|
||||
ref := r.Reference()
|
||||
meta, ok := homepage.GetHomepageMeta(ref)
|
||||
if ok {
|
||||
if hp.Name == "" {
|
||||
hp.Name = meta.DisplayName
|
||||
}
|
||||
if hp.Category == "" {
|
||||
hp.Category = meta.Tag
|
||||
refs := r.References()
|
||||
for _, ref := range refs {
|
||||
meta, ok := homepage.GetHomepageMeta(ref)
|
||||
if ok {
|
||||
if hp.Name == "" {
|
||||
hp.Name = meta.DisplayName
|
||||
}
|
||||
if hp.Category == "" {
|
||||
hp.Category = meta.Tag
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if hp.Name == "" {
|
||||
hp.Name = strutils.Title(
|
||||
strings.ReplaceAll(
|
||||
strings.ReplaceAll(ref, "-", " "),
|
||||
strings.ReplaceAll(refs[0], "-", " "),
|
||||
"_", " ",
|
||||
),
|
||||
)
|
||||
@@ -498,8 +504,11 @@ func (r *Route) FinalizeHomepageConfig() {
|
||||
|
||||
if hp.Category == "" {
|
||||
if config.GetInstance().Value().Homepage.UseDefaultCategories {
|
||||
if category, ok := homepage.PredefinedCategories[ref]; ok {
|
||||
hp.Category = category
|
||||
for _, ref := range refs {
|
||||
if category, ok := homepage.PredefinedCategories[ref]; ok {
|
||||
hp.Category = category
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ type (
|
||||
ProviderName() string
|
||||
TargetURL() *net.URL
|
||||
HealthMonitor() health.HealthMonitor
|
||||
Reference() string
|
||||
References() []string
|
||||
|
||||
Started() bool
|
||||
|
||||
|
||||
Reference in New Issue
Block a user