organize project
took me a bit to figure out how to do this properly, but i believe it's improved my understanding of how go works
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
package reports
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"uuid"
|
||||
|
||||
"git.whoswhip.dev/whoswhip/minibin/internal/config"
|
||||
"git.whoswhip.dev/whoswhip/minibin/internal/database"
|
||||
"git.whoswhip.dev/whoswhip/minibin/internal/pages"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func ReportUploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages, cStore *ChallengeStore) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
p.HTTPError(w, r, "Invalid form data", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
powResult := strings.TrimSpace(r.PostForm.Get("pow_result"))
|
||||
powNonceForm := strings.TrimSpace(r.PostForm.Get("pow_nonce"))
|
||||
powChallengeId := strings.TrimSpace(r.PostForm.Get("pow_challenge_id"))
|
||||
uploadId := strings.TrimSpace(r.PostForm.Get("upload_id"))
|
||||
reportReason := strings.TrimSpace(r.PostForm.Get("report_reason"))
|
||||
|
||||
if powResult == "" || powNonceForm == "" || powChallengeId == "" {
|
||||
pages.ResultPage(p, "400, bad request", "proof of work is required", 400)(w, r)
|
||||
return
|
||||
}
|
||||
if uploadId == "" || (len(uploadId) != 10 && len(uploadId) != 16) {
|
||||
pages.ResultPage(p, "400, bad request", "invalid upload id provided", 400)(w, r)
|
||||
return
|
||||
}
|
||||
if reportReason == "" || !slices.Contains(cfg.ReportOptions, reportReason) {
|
||||
pages.ResultPage(p, "400, bad request", "invalid reason provided", 400)(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
powNonce, err := strconv.Atoi(powNonceForm)
|
||||
if err != nil {
|
||||
log.Println("failed to parse pow nonce:", err)
|
||||
pages.ResultPage(p, "400, bad request", "the nonce provided is not a valid integer", 400)(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
clientError, err := cStore.Verify(powChallengeId, powResult, powNonce)
|
||||
if err != nil && !clientError {
|
||||
log.Println("failed to verify pow:", err)
|
||||
pages.ResultPage(p, "500, internal server error", "server went kaput", 500)(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil && clientError {
|
||||
p.HTTPError(w, r, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
report := &database.Report{
|
||||
ID: uuid.NewV7().String(),
|
||||
UploadID: uploadId,
|
||||
Reason: reportReason,
|
||||
}
|
||||
|
||||
err = database.InsertReport(db.WithContext(r.Context()), report)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrForeignKeyViolated) {
|
||||
pages.ResultPage(p, "404, upload not found", "the upload you are reporting was not found", 404)(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("failed to insert report:", err)
|
||||
p.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
pages.ResultPage(p, "success!", "your report has been successfully submitted", 200)(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func ReportPageHandler(p *pages.Pages, store *ChallengeStore, cfg config.Config) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id, challenge, err := store.Issue(cfg.PoWDifficulty)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to generate PoW challenge", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
p.Render(w, "report.html", map[string]any{
|
||||
"Qt": pages.GetRandomQt(p.Qts),
|
||||
"Challenge": map[string]any{
|
||||
"Data": hex.EncodeToString(challenge.Data),
|
||||
"Difficulty": challenge.Difficulty,
|
||||
"ExpiresAt": challenge.ExpiresAt,
|
||||
"Id": id,
|
||||
},
|
||||
"ReportOptions": cfg.ReportOptions,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package reports
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.whoswhip.dev/whoswhip/minibin/internal/storage"
|
||||
)
|
||||
|
||||
type Challenge struct {
|
||||
Data []byte
|
||||
Difficulty int
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type ChallengeStore struct {
|
||||
mu sync.Mutex
|
||||
challenges map[string]Challenge
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
const MaxChallenges = 10000
|
||||
|
||||
func NewChallengeStore(ttl time.Duration) *ChallengeStore {
|
||||
if ttl <= 0 || ttl > 10*time.Minute {
|
||||
panic("invalid challenge ttl")
|
||||
}
|
||||
return &ChallengeStore{
|
||||
challenges: make(map[string]Challenge),
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
func (store *ChallengeStore) Issue(difficulty int) (id string, challenge Challenge, err error) {
|
||||
if difficulty < 0 || difficulty > 256 {
|
||||
return "", Challenge{}, fmt.Errorf("invalid difficulty")
|
||||
}
|
||||
if len(store.challenges) >= MaxChallenges {
|
||||
return "", Challenge{}, fmt.Errorf("challenge store is full")
|
||||
}
|
||||
|
||||
id = storage.GenerateId(16)
|
||||
data := make([]byte, 32)
|
||||
if _, err := rand.Read(data); err != nil {
|
||||
log.Println("failed to generate PoW challenge:", err)
|
||||
return "", Challenge{}, err
|
||||
}
|
||||
challenge = Challenge{
|
||||
Data: data,
|
||||
Difficulty: difficulty,
|
||||
ExpiresAt: time.Now().UTC().Add(store.ttl),
|
||||
}
|
||||
store.mu.Lock()
|
||||
store.deleteExpired(time.Now().UTC())
|
||||
store.challenges[id] = challenge
|
||||
store.mu.Unlock()
|
||||
return id, challenge, nil
|
||||
}
|
||||
|
||||
func (store *ChallengeStore) Verify(id string, result string, nonce int) (clientError bool, err error) {
|
||||
if len(id) != 16 {
|
||||
return true, fmt.Errorf("invalid id")
|
||||
}
|
||||
if nonce < 0 {
|
||||
return true, fmt.Errorf("invalid nonce")
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
challenge, exists := store.challenges[id]
|
||||
if !exists {
|
||||
return true, fmt.Errorf("challenge not found")
|
||||
}
|
||||
if challenge.Difficulty < 0 || challenge.Difficulty > 256 {
|
||||
return true, fmt.Errorf("invalid difficulty")
|
||||
}
|
||||
if !time.Now().Before(challenge.ExpiresAt) {
|
||||
delete(store.challenges, id)
|
||||
return true, fmt.Errorf("challenge expired")
|
||||
}
|
||||
if len(result) != 64 {
|
||||
return true, fmt.Errorf("invalid length")
|
||||
}
|
||||
hashBytes, err := hex.DecodeString(result)
|
||||
if err != nil {
|
||||
log.Println("failed to decode result:", err)
|
||||
return false, err
|
||||
}
|
||||
if !hasLeadingZeroBits(hashBytes, challenge.Difficulty) {
|
||||
return true, fmt.Errorf("proof-of-work is not complete")
|
||||
}
|
||||
input := fmt.Appendf(nil, "%s%d", hex.EncodeToString(challenge.Data), nonce)
|
||||
localResult := sha256.Sum256(input)
|
||||
if subtle.ConstantTimeCompare(localResult[:], hashBytes) != 1 {
|
||||
return true, fmt.Errorf("results do not match")
|
||||
}
|
||||
delete(store.challenges, id)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *ChallengeStore) deleteExpired(now time.Time) {
|
||||
for id, challenge := range store.challenges {
|
||||
if !now.Before(challenge.ExpiresAt) {
|
||||
delete(store.challenges, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func hasLeadingZeroBits(hash []byte, requiredBits int) bool {
|
||||
if requiredBits < 0 || requiredBits > len(hash)*8 {
|
||||
return false
|
||||
}
|
||||
whole, remaining := requiredBits/8, requiredBits%8
|
||||
for _, b := range hash[:whole] {
|
||||
if b != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return remaining == 0 || hash[whole]>>(8-remaining) == 0
|
||||
}
|
||||
Reference in New Issue
Block a user