diff --git a/config.go b/config.go index f04bf71..5bb13af 100644 --- a/config.go +++ b/config.go @@ -17,6 +17,8 @@ type Config struct { Expiries []Expiry NormalizeMIMETypes bool BannedMIMETypes []string + PoWDifficulty int + ReportOptions []string DatabasePath string // public host like "https://bin.zip", NOT the address minbin listens on @@ -58,6 +60,19 @@ func loadConfig() (Config, error) { expiries = append(expiries, expiry) } + powDifficultySetting := envOrDefault("MINIBIN_POW_DIFFICULTY", "18") + powDifficulty, err := strconv.Atoi(powDifficultySetting) + if err != nil { + return Config{}, fmt.Errorf("failed to parse MINIBIN_POW_DIFFICULTY") + } + reportOptionsSetting := envOrDefault("MINIBIN_REPORT_OPTIONS", "Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud") + reportOptions := strings.Split(reportOptionsSetting, ",") + if len(reportOptions) == 0 { + return Config{}, fmt.Errorf("no valid report options set") + } + + log.Println(len(reportOptions)) + return Config{ UploadDir: envOrDefault("MINIBIN_UPLOAD_DIR", "uploads"), MaxPasteBytes: maxPasteKiB * 1024, @@ -65,6 +80,8 @@ func loadConfig() (Config, error) { Expiries: expiries, NormalizeMIMETypes: envOrDefault("MINIBIN_NORMALIZE_MIME_TYPES", "true") == "true", BannedMIMETypes: strings.Split(envOrDefault("MINIBIN_BANNED_MIME_TYPES", ""), ","), + PoWDifficulty: powDifficulty, + ReportOptions: reportOptions, DatabasePath: envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite"), Host: envOrDefault("MINIBIN_HOST", "http://localhost:8080"), diff --git a/database.go b/database.go index 2a8f5ad..8d14446 100644 --- a/database.go +++ b/database.go @@ -30,14 +30,14 @@ type Upload struct { type Report struct { ID string `gorm:"column:id;primaryKey"` - UploadID string + UploadID string `gorm:"column:upload_id;not null;index"` Reason string `gorm:"column:reason;not null"` - Upload Upload `gorm:"foreignKey:UploadID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` + Upload Upload `gorm:"foreignKey:UploadID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime"` } func initDatabase(path string) (*gorm.DB, error) { - db, err := gorm.Open(sqlite.Open(path), &gorm.Config{}) + db, err := gorm.Open(sqlite.Open(path), &gorm.Config{TranslateError: true}) if err != nil { return nil, fmt.Errorf("open database: %w", err) } @@ -53,6 +53,9 @@ func initDatabase(path string) (*gorm.DB, error) { walModeErr := fmt.Errorf("enable database WAL: %w", err) return nil, errors.Join(walModeErr, sqlDB.Close()) } + if err := db.Exec("PRAGMA foreign_keys = ON").Error; err != nil { + return nil, fmt.Errorf("enable foreign keys: %w", err) + } if err := db.AutoMigrate(&Upload{}, &Report{}); err != nil { migrationErr := fmt.Errorf("migrate database: %w", err) @@ -63,11 +66,11 @@ func initDatabase(path string) (*gorm.DB, error) { } func insertUpload(db *gorm.DB, upload *Upload) error { - return db.Omit("Upload").Create(upload).Error + return db.Create(upload).Error } func insertReport(db *gorm.DB, report *Report) error { - return db.Create(report).Error + return db.Omit("Upload").Create(report).Error } func getUploadById(db *gorm.DB, id string) (*Upload, error) { diff --git a/handlers.go b/handlers.go index bd64b3e..7e5890b 100644 --- a/handlers.go +++ b/handlers.go @@ -15,9 +15,11 @@ import ( "os" "path/filepath" "slices" + "strconv" "strings" "time" "unicode/utf8" + "uuid" "gorm.io/gorm" ) @@ -418,7 +420,6 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc { // continue to delete from database IF the file doesnt exist on disk if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { - log.Println("remove upload file:", err) http.Error(w, "internal server error", http.StatusInternalServerError) return @@ -443,3 +444,69 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc { w.WriteHeader(http.StatusNoContent) } } + +func reportUploadHandler(db *gorm.DB, cfg Config, pages *Pages, cStore *ChallengeStore) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "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 == "" { + resultPage(pages, "400, bad request", "proof of work is required", 400)(w, r) + return + } + if uploadId == "" || (len(uploadId) != 10 && len(uploadId) != 16) { + resultPage(pages, "400, bad request", "invalid upload id provided", 400)(w, r) + return + } + if reportReason == "" || !slices.Contains(cfg.ReportOptions, reportReason) { + resultPage(pages, "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) + resultPage(pages, "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) + resultPage(pages, "500, internal server error", "server went kaput", 500)(w, r) + return + } + if err != nil && clientError { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + report := &Report{ + ID: uuid.NewV7().String(), + UploadID: uploadId, + Reason: reportReason, + } + + err = insertReport(db.WithContext(r.Context()), report) + if err != nil { + if errors.Is(err, gorm.ErrForeignKeyViolated) { + resultPage(pages, "404, upload not found", "the upload you are reporting was not found", 404)(w, r) + return + } + + log.Println("failed to insert report:", err) + http.Error(w, "internal server error", http.StatusInternalServerError) + return + } + + resultPage(pages, "success!", "your report has been successfully submitted", 200)(w, r) + } +} diff --git a/main.go b/main.go index 1b94018..c11702d 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "log" "net/http" "os" + "time" ) func main() { @@ -39,8 +40,10 @@ func main() { defer cancel() go tracker.Run(ctx, db) + challengeStore := NewChallengeStore(3 * time.Minute) + log.Println("listening on", config.Addr) - router := newRouter(db, config, pages, tracker) + router := newRouter(db, config, pages, tracker, challengeStore) err = http.ListenAndServe(config.Addr, router) if err != nil { log.Fatal(err) diff --git a/pages.go b/pages.go index 6832236..00a99a6 100644 --- a/pages.go +++ b/pages.go @@ -1,6 +1,7 @@ package main import ( + "encoding/hex" "errors" "html/template" "log" @@ -41,6 +42,22 @@ func staticPage(pages *Pages, name string) http.HandlerFunc { } } +func resultPage(pages *Pages, title string, message string, statusCode ...int) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + code := 200 + if len(statusCode) > 0 { + code = statusCode[0] + } + w.WriteHeader(code) + + render(pages, w, "result.html", map[string]any{ + "Qt": getRandomQt(pages.Qts), + "Title": title, + "Message": message, + }) + } +} + func getRandomQt(qts []string) string { if len(qts) > 0 { return qts[rand.IntN(len(qts))] @@ -115,3 +132,23 @@ func faqHandler(pages *Pages, cfg Config) http.HandlerFunc { }) } } + +func reportPageHandler(pages *Pages, store *ChallengeStore, cfg 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 + } + render(pages, w, "report.html", map[string]any{ + "Qt": getRandomQt(pages.Qts), + "Challenge": map[string]any{ + "Data": hex.EncodeToString(challenge.Data), + "Difficulty": challenge.Difficulty, + "ExpiresAt": challenge.ExpiresAt, + "Id": id, + }, + "ReportOptions": cfg.ReportOptions, + }) + } +} diff --git a/pow.go b/pow.go new file mode 100644 index 0000000..d14fd14 --- /dev/null +++ b/pow.go @@ -0,0 +1,124 @@ +package main + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "fmt" + "log" + "sync" + "time" +) + +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 = 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 +} diff --git a/readme.md b/readme.md index 4bcca0c..bc4ee28 100644 --- a/readme.md +++ b/readme.md @@ -38,9 +38,9 @@ goals: - [x] [switch mime type detection library](https://git.whoswhip.dev/whoswhip/minibin/src/commit/47518993577f94d7cf9c0743042d2ac133055924/handlers.go#L273-L276) - [ ] ratelimits - [ ] simplify rendering & serving pages (too much duplicate code rn) -- [ ] reports +- [x] reports - POW captchas? - - what library? self rolled? + - [ ] switch to argon2id instead of sha256 - javascript required ## misc goals diff --git a/routes.go b/routes.go index e34e5f9..e1a51f1 100644 --- a/routes.go +++ b/routes.go @@ -6,7 +6,7 @@ import ( "gorm.io/gorm" ) -func newRouter(db *gorm.DB, cfg Config, pages *Pages, tracker *AccessTracker) http.Handler { +func newRouter(db *gorm.DB, cfg Config, pages *Pages, tracker *AccessTracker, cStore *ChallengeStore) http.Handler { mux := http.NewServeMux() fs := http.FileServer(http.Dir("static")) mux.Handle("GET /css/", fs) @@ -20,6 +20,8 @@ func newRouter(db *gorm.DB, cfg Config, pages *Pages, tracker *AccessTracker) ht mux.HandleFunc("GET /tos", staticPage(pages, "tos.html")) mux.HandleFunc("GET /privacy", staticPage(pages, "privacy.html")) mux.HandleFunc("GET /faq", faqHandler(pages, cfg)) + mux.HandleFunc("GET /report", reportPageHandler(pages, cStore, cfg)) + mux.HandleFunc("POST /report", reportUploadHandler(db, cfg, pages, cStore)) uploads := http.NewServeMux() uploads.HandleFunc("GET /{id}", contentHandler(db, cfg, tracker)) uploads.HandleFunc("GET /{id}/info", contentInfoHandler(db, tracker)) diff --git a/static/css/main.css b/static/css/main.css index e6fddab..649b340 100644 --- a/static/css/main.css +++ b/static/css/main.css @@ -20,7 +20,7 @@ body { margin: 0; font-family: Consolas, monospace; font-size: 14px; - background-image:var(--qt-url); + background-image: var(--qt-url); background-repeat: no-repeat; background-position: bottom right; background-size: auto 256px; @@ -28,7 +28,7 @@ body { } b { - font-weight: bold; + font-weight: bold; } h1, @@ -38,7 +38,7 @@ h2 { } h4 { - margin: 6px 0; + margin: 6px 0; } h1 { @@ -79,6 +79,27 @@ textarea { margin-bottom: 12px; } +textarea:focus { + border-color: var(--border-strong); +} + +input[type="text"] { + background: var(--bg); + display: block; + width: 100%; + border: 1px solid var(--border); + font: inherit; + padding: 12px; + outline: none; + color: var(--text); + margin-top: 6px; + margin-bottom: 12px; +} + +input[type="text"]:focus { + border-color: var(--border-strong); +} + .upload-tabs { display: flex; flex-wrap: wrap; @@ -177,6 +198,12 @@ option { background-color: var(--text-muted); } +.btn:disabled { + background-color: var(--surface); + color: var(--text-muted); + cursor: not-allowed; +} + .link-btn { border: none; background: none; @@ -244,8 +271,9 @@ body.dragging::after { } code { - background-color: var(--surface-between); - padding-inline: 4px; + background-color: var(--surface-between); + padding-inline: 3px; + border: 1px solid var(--surface-hover); } .submit-container { @@ -253,4 +281,55 @@ code { display: flex; justify-content: space-between; align-items: center; +} + +.noscript { + border: var(--border-strong); + background-color: var(--surface-between); + width: 100%; + display: block; + font-size: larger; + padding: 0.5rem; + margin-bottom: 5px; +} + +.full-dropdown { + background: var(--bg); + display: block; + width: 100%; + border: 1px solid var(--border); + font: inherit; + padding: 12px; + outline: none; + color: var(--text); + margin-top: 6px; + margin-bottom: 12px; +} + +.loading { + position: relative; + overflow: hidden; + background: var(--surface); + isolation: isolate; +} + +.loading::before { + content: ""; + position: absolute; + inset: 0; + width: 200%; + background: repeating-linear-gradient( + 45deg, + var(--surface-hover) 0 25%, + transparent 25% 50% + ); + background-size: 1em 1em; + animation: barStripe 1s linear infinite; + z-index: -1; +} + +@keyframes barStripe { + to { + transform: translateX(-1em); + } } \ No newline at end of file diff --git a/static/js/pow-worker.js b/static/js/pow-worker.js new file mode 100644 index 0000000..d834a67 --- /dev/null +++ b/static/js/pow-worker.js @@ -0,0 +1,32 @@ +function hasLeadingZeroBits(bytes, requiredBits) { + const whole = Math.floor(requiredBits / 8); + const remaining = requiredBits % 8; + for (let i = 0; i < whole; i++) { + if (bytes[i] !== 0) return false; + } + return remaining === 0 || bytes[whole] >>> (8 - remaining) === 0; +} + +self.onmessage = async ({ data }) => { + const { challenge, difficulty, startNonce = 0 } = data; + if (difficulty < 0 || difficulty > 256 || !Number.isInteger(difficulty)) { + throw new Error("Invalid difficulty"); + } + console.log(`[PoW] Difficulty: ${difficulty}, Starting Nonce: ${startNonce}, Challenge: ${challenge}`) + const startTime = performance.now(); + const encoder = new TextEncoder(); + for (let nonce = startNonce; ; nonce++) { + const input = encoder.encode(`${challenge}${nonce}`); + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", input)); + if (hasLeadingZeroBits(digest, difficulty)) { + const hashHex = Array.from(digest).map((b) => b.toString(16).padStart(2, "0")).join(""); + const elapsed = performance.now() - startTime; + const attempts = nonce - startNonce + 1; + console.log(`[PoW] took ${elapsed} ms to solve challenge`) + console.log(`[PoW] ${(attempts / (elapsed / 1000)).toFixed(0)} hashes/s`) + console.log(`[PoW] Result: ${hashHex}, Nonce: ${nonce}`) + self.postMessage({ nonce: nonce, hash: hashHex, }); + return; + } + } +}; \ No newline at end of file diff --git a/static/js/report.js b/static/js/report.js new file mode 100644 index 0000000..f85b76f --- /dev/null +++ b/static/js/report.js @@ -0,0 +1,17 @@ +const worker = new Worker("/js/pow-worker.js"); +const reportForm = document.getElementById("report-form"); +const submitBtn = document.getElementById("submit-btn"); +const powLabel = document.getElementById("pow-label"); +const challenge = reportForm.dataset; +submitBtn.disabled = true; +worker.onmessage = ({ data }) => { + submitBtn.disabled = false; + powLabel.style.display = "none"; + submitBtn.classList.remove("loading"); + document.getElementById("pow-result").value = data.hash; + document.getElementById("pow-nonce").value = data.nonce; +} +worker.postMessage({ + challenge: reportForm.dataset.challengeData, + difficulty: Number.parseInt(reportForm.dataset.challengeDifficulty, 10), +}) \ No newline at end of file diff --git a/templates/header.html b/templates/header.html index 0b58961..9e56c66 100644 --- a/templates/header.html +++ b/templates/header.html @@ -5,6 +5,7 @@ tos privacy faq + report src diff --git a/templates/report.html b/templates/report.html new file mode 100644 index 0000000..026b2d8 --- /dev/null +++ b/templates/report.html @@ -0,0 +1,50 @@ + + + + + + report | minibin + + + {{if .Qt}} + + {{end}} + + + {{template "site-header"}} + +
+ +
+ + + + + + + +
+ + computing proof of work +
+
+
+ + diff --git a/templates/result.html b/templates/result.html new file mode 100644 index 0000000..8be0b08 --- /dev/null +++ b/templates/result.html @@ -0,0 +1,23 @@ + + + + + + {{.Title}} | minibin + + {{if .Qt}} + + {{end}} + + + {{template "site-header"}} +
+

{{.Title}}

+

{{.Message}}

+
+ +