mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-24 09:18:31 +02:00
feat: hCaptcha middleware
This commit is contained in:
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)
|
||||
}
|
||||
Reference in New Issue
Block a user