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:
2026-11-21 16:18:30 -05:00
parent 741b91b637
commit e5a2f47f47
28 changed files with 304 additions and 1148 deletions
+98
View File
@@ -0,0 +1,98 @@
package config
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/joho/godotenv"
)
type Config struct {
UploadDir string
MaxPasteBytes int64
MaxFileBytes int64
Expiries []Expiry
NormalizeMIMETypes bool
BannedMIMETypes []string
PoWDifficulty int
ReportOptions []string
DatabasePath string
// public host like "https://bin.zip", NOT the address minbin listens on
Host string
Addr string
}
func LoadConfig() (Config, error) {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
pasteSizeSetting := envOrDefault("MINIBIN_MAX_PASTE_KIB", "1024")
maxPasteKiB, err := strconv.ParseInt(pasteSizeSetting, 10, 64)
if err != nil {
return Config{}, fmt.Errorf("failed to parse MINIBIN_MAX_PASTE_KIB: %w", err)
}
if maxPasteKiB <= 0 {
return Config{}, fmt.Errorf("MINIBIN_MAX_PASTE_KIB must be greater than 0")
}
fileSizeSetting := envOrDefault("MINIBIN_MAX_FILE_KIB", "1024")
maxFileKiB, err := strconv.ParseInt(fileSizeSetting, 10, 64)
if err != nil {
return Config{}, fmt.Errorf("failed to parse MINIBIN_MAX_FILE_KIB: %w", err)
}
if maxFileKiB <= 0 {
return Config{}, fmt.Errorf("MINIBIN_MAX_FILE_KIB must be greater than 0")
}
expiriesSetting := envOrDefault("MINIBIN_EXPIRIES", "1h,12h,1d,7d,2w,1mo,6mo,1y,5y,0")
var expiries []Expiry
for entry := range strings.SplitSeq(expiriesSetting, ",") {
expiry, err := ParseExpiry(entry)
if err != nil {
return Config{}, fmt.Errorf("MINIBIN_EXPIRIES: %w", err)
}
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,
MaxFileBytes: maxFileKiB * 1024,
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"),
Addr: envOrDefault("MINIBIN_ADDR", "localhost:8080"),
}, nil
}
func envOrDefault(key, fallback string) string {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
return fallback
}
return value
}
+78
View File
@@ -0,0 +1,78 @@
package config
import (
"fmt"
"regexp"
"slices"
"strconv"
"strings"
"time"
)
type Expiry struct {
Label string
Amount int
Unit string
}
// this will parse something like "1d" into 2 groups: the amount, and the unit
var expiryPattern = regexp.MustCompile(`^([1-9][0-9]*)(h|d|w|mo|y)$`)
func ParseExpiry(expiry string) (Expiry, error) {
expiry = strings.TrimSpace(expiry)
if expiry == "0" {
return Expiry{
Label: "indefinite",
Unit: "indefinite",
}, nil
}
matches := expiryPattern.FindStringSubmatch(expiry)
if matches == nil {
return Expiry{}, fmt.Errorf("invalid expiry %q", expiry)
}
// parses the string amount to an int
// the amount is 2nd (1) in the index because the first (0) is the entire string
amount, err := strconv.Atoi(matches[1])
if err != nil {
return Expiry{}, fmt.Errorf("invalid expiry %q: %w", expiry, err)
}
return Expiry{
Label: expiry,
Amount: amount,
Unit: matches[2],
}, nil
}
func FindExpiry(expiries []Expiry, label string) (Expiry, bool) {
index := slices.IndexFunc(expiries, func(expiry Expiry) bool {
return expiry.Label == label
})
if index == -1 {
return Expiry{}, false
}
return expiries[index], true
}
func (expiry Expiry) ExpiresFrom(now time.Time) (*time.Time, error) {
var expires time.Time
switch expiry.Unit {
case "h":
expires = now.Add(time.Duration(expiry.Amount) * time.Hour)
case "d":
expires = now.AddDate(0, 0, expiry.Amount)
case "w":
expires = now.AddDate(0, 0, expiry.Amount*7)
case "mo":
expires = now.AddDate(0, expiry.Amount, 0)
case "y":
expires = now.AddDate(expiry.Amount, 0, 0)
case "indefinite":
return nil, nil
default:
return nil, fmt.Errorf("unsupported expiry unit %q", expiry.Unit)
}
return &expires, nil
}
+82
View File
@@ -0,0 +1,82 @@
package database
import (
"errors"
"fmt"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
type ContentType uint8
const (
ContentFile ContentType = iota
ContentPaste
)
type Upload struct {
ID string `gorm:"column:id;primaryKey" json:"id"`
Type ContentType `gorm:"column:type;not null;default:0;type:integer" json:"type"`
Filename string `gorm:"column:filename;not null" json:"-"`
MIMEType string `gorm:"column:mime_type;not null" json:"mime_type"`
Size int64 `gorm:"column:size;not null" json:"size"`
SHA256 []byte `gorm:"column:sha256;type:blob;notnull;index" json:"-"`
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime" json:"created_at"`
ExpiresAt *int64 `gorm:"column:expires_at;index" json:"expires_at"` // null means no expiration
LastAccessedAt int64 `gorm:"column:last_accessed_at;not null;autoCreateTime;index" json:"last_accessed_at"`
DeleteToken string `gorm:"column:delete_token;not null" json:"-"`
}
type Report struct {
ID string `gorm:"column:id;primaryKey"`
UploadID string `gorm:"column:upload_id;not null;index"`
Reason string `gorm:"column:reason;not null"`
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{TranslateError: true})
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
sqlDB, err := db.DB()
if err != nil {
return nil, fmt.Errorf("get database handle: %w", err)
}
sqlDB.SetMaxOpenConns(1)
sqlDB.SetMaxIdleConns(1)
if err := db.Exec("PRAGMA journal_mode = WAL").Error; err != nil {
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)
return nil, errors.Join(migrationErr, sqlDB.Close())
}
return db, nil
}
func InsertUpload(db *gorm.DB, upload *Upload) error {
return db.Create(upload).Error
}
func InsertReport(db *gorm.DB, report *Report) error {
return db.Omit("Upload").Create(report).Error
}
func GetUploadById(db *gorm.DB, id string) (*Upload, error) {
var upload Upload
if err := db.First(&upload, "id = ?", id).Error; err != nil {
return nil, err
}
return &upload, nil
}
+147
View File
@@ -0,0 +1,147 @@
package pages
import (
"errors"
"html/template"
"log"
"math/rand/v2"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"git.whoswhip.dev/whoswhip/minibin/internal/config"
"github.com/dustin/go-humanize"
)
type Pages struct {
Templates *template.Template
Qts []string
Placeholders []string
}
type HomePageData struct {
Expiries []config.Expiry
Qt string
PastePlaceholder string
FileMaxSize string
PasteMaxSize string
}
func (pages *Pages) Render(w http.ResponseWriter, name string, data any) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := pages.Templates.ExecuteTemplate(w, name, data); err != nil {
log.Printf("render %s: %v", name, err)
}
}
func StaticPage(pages *Pages, name string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pages.Render(w, name, GetRandomQt(pages.Qts))
}
}
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)
pages.Render(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))]
}
return ""
}
func LoadPages() (*Pages, error) {
templates, err := template.New("").Funcs(template.FuncMap{
"hasPrefix": strings.HasPrefix,
}).ParseGlob("web/templates/*.html")
if err != nil {
return nil, err
}
pages := &Pages{
Templates: templates,
Placeholders: []string{"cmon, paste something already!"},
}
qtFiles, err := os.ReadDir("qts")
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
for _, qt := range qtFiles {
if qt.IsDir() {
continue
}
switch strings.ToLower(filepath.Ext(qt.Name())) {
case ".jpeg", ".jpg", ".jxl", ".png", ".webp", ".avif", ".gif":
pages.Qts = append(pages.Qts, "/qts/"+url.PathEscape(qt.Name()))
}
}
pastePlaceholders, err := os.ReadFile("paste-placeholders.txt")
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
placeholders := strings.TrimSpace(strings.ReplaceAll(string(pastePlaceholders), "\r\n", "\n"))
if placeholders != "" {
pages.Placeholders = strings.Split(placeholders, "\n")
}
return pages, nil
}
func HomeHandler(pages *Pages, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := HomePageData{
Expiries: cfg.Expiries,
FileMaxSize: humanize.Bytes(uint64(cfg.MaxFileBytes)),
PasteMaxSize: humanize.Bytes(uint64(cfg.MaxPasteBytes)),
Qt: GetRandomQt(pages.Qts),
}
if len(pages.Placeholders) > 0 {
data.PastePlaceholder = pages.Placeholders[rand.IntN(len(pages.Placeholders))]
}
pages.Render(w, "home.html", data)
}
}
func FaqHandler(pages *Pages, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pages.Render(w, "faq.html", map[string]any{
"Expiries": cfg.Expiries,
"Host": cfg.Host,
"NormalizeMIMETypes": cfg.NormalizeMIMETypes,
"Qt": GetRandomQt(pages.Qts),
})
}
}
func (pages *Pages) HTTPError(w http.ResponseWriter, r *http.Request, message string, status int) {
if strings.Contains(r.Header.Get("Accept"), "text/html") {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
_ = pages.Templates.ExecuteTemplate(w, "result.html", map[string]any{
"Title": status,
"Message": message,
})
return
}
http.Error(w, message, status)
}
+103
View File
@@ -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,
})
}
}
+126
View File
@@ -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
}
+45
View File
@@ -0,0 +1,45 @@
package server
import (
"fmt"
"net/http"
"git.whoswhip.dev/whoswhip/minibin/internal/config"
"git.whoswhip.dev/whoswhip/minibin/internal/pages"
"git.whoswhip.dev/whoswhip/minibin/internal/reports"
"git.whoswhip.dev/whoswhip/minibin/internal/uploads"
"gorm.io/gorm"
)
func health(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "OK")
}
func NewRouter(db *gorm.DB, cfg config.Config, p *pages.Pages, tracker *uploads.AccessTracker, cStore *reports.ChallengeStore) http.Handler {
mux := http.NewServeMux()
fs := http.FileServer(http.Dir("web/static"))
mux.Handle("GET /css/", fs)
mux.Handle("GET /js/", fs)
mux.Handle("GET /static/", http.StripPrefix("/static/", fs))
mux.Handle("GET /qts/", http.StripPrefix(
"/qts/",
http.FileServer((http.Dir("qts"))),
))
mux.HandleFunc("GET /{$}", pages.HomeHandler(p, cfg))
mux.HandleFunc("GET /tos", pages.StaticPage(p, "tos.html"))
mux.HandleFunc("GET /privacy", pages.StaticPage(p, "privacy.html"))
mux.HandleFunc("GET /faq", pages.FaqHandler(p, cfg))
mux.HandleFunc("GET /report", reports.ReportPageHandler(p, cStore, cfg))
mux.HandleFunc("POST /report", reports.ReportUploadHandler(db, cfg, p, cStore))
u := http.NewServeMux()
u.HandleFunc("GET /{id}", uploads.ContentHandler(db, cfg, tracker, p))
u.HandleFunc("GET /{id}/info", uploads.ContentInfoHandler(db, tracker, p))
mux.Handle("/", u)
mux.HandleFunc("POST /upload", uploads.UploadHandler(db, cfg, p))
mux.HandleFunc("PUT /upload", uploads.UploadHandler(db, cfg, p))
mux.HandleFunc("DELETE /{id}", uploads.DeleteHandler(db, cfg, p))
mux.HandleFunc("POST /{id}/delete", uploads.DeleteHandler(db, cfg, p))
mux.HandleFunc("GET /health", health)
return mux
}
+49
View File
@@ -0,0 +1,49 @@
package storage
import (
"crypto/rand"
"math/big"
"path/filepath"
"strings"
)
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
// generates a secure random id,
// length must be either 10 or 16
func GenerateId(length int) string {
if length != 10 && length != 16 {
panic("length must be 10 or 16")
}
bytes := make([]byte, length)
max := big.NewInt(int64(len(alphabet)))
for i := range bytes {
rr, err := rand.Int(rand.Reader, max)
if err != nil {
panic(err)
}
bytes[i] = alphabet[rr.Int64()]
}
return string(bytes)
}
func ValidPasteId(id string) bool {
if len(id) != 10 && len(id) != 16 {
return false
}
// check if it uses our alphabet
for _, r := range id {
if !strings.ContainsRune(alphabet, r) {
return false
}
}
return true
}
func GetStoragePath(uploadDir, id string) string {
return filepath.Join(uploadDir, id[:2], id[2:4], id)
}
+83
View File
@@ -0,0 +1,83 @@
package uploads
import (
"context"
"log"
"sync"
"time"
"git.whoswhip.dev/whoswhip/minibin/internal/database"
"gorm.io/gorm"
)
type AccessTracker struct {
mu sync.Mutex
pending map[string]int64
}
func NewAccessTracker() *AccessTracker {
return &AccessTracker{
pending: make(map[string]int64),
}
}
func (tracker *AccessTracker) Record(id string) {
tracker.mu.Lock()
defer tracker.mu.Unlock()
tracker.pending[id] = time.Now().UTC().Unix()
}
func (tracker *AccessTracker) Flush(ctx context.Context, db *gorm.DB) error {
tracker.mu.Lock()
batch := tracker.pending
tracker.pending = make(map[string]int64)
tracker.mu.Unlock()
if len(batch) == 0 {
return nil
}
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for id, timestamp := range batch {
err := tx.Model(&database.Upload{}).
Where("id = ? AND last_accessed_at < ?", id, timestamp).
UpdateColumn("last_accessed_at", timestamp).Error
if err != nil {
return err
}
}
return nil
})
if err != nil {
tracker.mu.Lock()
for id, timestamp := range batch {
if timestamp > tracker.pending[id] {
tracker.pending[id] = timestamp
}
}
tracker.mu.Unlock()
return err
}
log.Printf("updated access timestamps for %d uploads", len(batch))
return nil
}
func (tracker *AccessTracker) Run(ctx context.Context, db *gorm.DB) {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
err := tracker.Flush(ctx, db)
if err != nil {
log.Println("flush pending access:", err)
}
case <-ctx.Done():
return
}
}
}
+443
View File
@@ -0,0 +1,443 @@
package uploads
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"mime"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"time"
"unicode/utf8"
"git.whoswhip.dev/whoswhip/minibin/internal/config"
"git.whoswhip.dev/whoswhip/minibin/internal/database"
"git.whoswhip.dev/whoswhip/minibin/internal/pages"
"git.whoswhip.dev/whoswhip/minibin/internal/storage"
"gorm.io/gorm"
)
type UploadInput struct {
Reader io.Reader
Filename string
MIMEType string
Type database.ContentType
}
type UploadResponse struct {
database.Upload
SHA256 string `json:"sha256"`
DeleteToken string `json:"deleteToken"`
FileExtension string `json:"extension"` // useful for things like sharex to append the extension
Qt string `json:"-"`
}
type ContentInfoResponse struct {
database.Upload
SHA256 string `json:"sha256"`
Filename string `json:"-"`
}
func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost && r.Method != http.MethodPut {
w.Header().Set("Allow", "POST,PUT")
p.HTTPError(w, r, "invalid method", http.StatusMethodNotAllowed)
return
}
// use the largest of the sizes, and then do another size check per type down the line
r.Body = http.MaxBytesReader(w, r.Body, max(cfg.MaxFileBytes, cfg.MaxPasteBytes))
var err error
mediaType := "text/plain"
if r.Method == http.MethodPost || r.Header.Get("Content-Type") != "" {
mediaType, _, err = mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
p.HTTPError(w, r, "failed to find or parse Content-Type", http.StatusBadRequest)
return
}
}
returnType := strings.TrimSpace(r.URL.Query().Get("return"))
if returnType == "" {
returnType = "json"
}
var input UploadInput
switch mediaType {
case "multipart/form-data": // file uploads
r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxFileBytes)
file, header, err := r.FormFile("file")
if r.MultipartForm != nil {
defer r.MultipartForm.RemoveAll()
}
if err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
return
}
p.HTTPError(w, r, "invalid file", http.StatusBadRequest)
return
}
defer file.Close()
input.MIMEType, err = detectMimeType(file)
if err != nil {
log.Println("detect file mime type:", err)
p.HTTPError(w, r, "failed to detect mime type", http.StatusInternalServerError)
return
}
if slices.Contains(cfg.BannedMIMETypes, input.MIMEType) {
p.HTTPError(w, r, "content type not allowed", http.StatusBadRequest)
return
}
input.Reader = file
input.Filename = header.Filename
input.Type = database.ContentFile
case "text/plain", "application/x-www-form-urlencoded": // paste uploads
r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxPasteBytes)
var content string
if mediaType == "application/x-www-form-urlencoded" {
err = r.ParseForm()
if err == nil {
content = r.PostForm.Get("content")
}
} else {
var body []byte
body, err := io.ReadAll(r.Body)
if err == nil {
content = string(body)
}
}
if err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
return
}
p.HTTPError(w, r, "invalid paste upload", http.StatusBadRequest)
return
}
if strings.TrimSpace(content) == "" {
p.HTTPError(w, r, "paste cannot be empty", http.StatusBadRequest)
return
}
input = UploadInput{
Reader: strings.NewReader(content),
Filename: "paste.txt",
MIMEType: "text/plain; charset=utf-8",
Type: database.ContentPaste,
}
default:
p.HTTPError(w, r, "unsupported Content-Type", http.StatusUnsupportedMediaType)
return
}
expLabel := r.URL.Query().Get("expiry")
if expLabel == "" {
expLabel = r.PostForm.Get("expiry") // html form request
}
if expLabel == "" {
expLabel = cfg.Expiries[0].Label
}
selected, found := config.FindExpiry(cfg.Expiries, expLabel)
if !found {
p.HTTPError(w, r, "invalid expiry", http.StatusBadRequest)
return
}
idLength := 16
if r.URL.Query().Get("idlength") == "short" {
idLength = 10
}
if r.PostForm.Get("idlength") == "short" {
idLength = 10
}
id := storage.GenerateId(idLength)
path := storage.GetStoragePath(cfg.UploadDir, id)
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
log.Println("create directories:", err)
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return
}
dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
log.Println("create file:", err)
p.HTTPError(w, r, "faield to save upload", http.StatusInternalServerError)
return
}
saved := false
defer func() {
dest.Close()
if !saved {
if err := os.Remove(path); err != nil {
log.Printf("remove incomplete upload %s: %v", id, err)
}
}
}()
hasher := sha256.New()
size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader)
if err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
return
}
log.Println("write file:", err)
p.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError)
return
}
if err := dest.Close(); err != nil {
log.Println("close file:", err)
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return
}
createdAt := time.Now().UTC().Unix()
expires, err := selected.ExpiresFrom(time.Now().UTC())
if err != nil {
log.Println("calc expiry:", err) // im just using slang
p.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return
}
// the following code prevents a panic, trying to convert a null pointer to unix perhaps doesnt work
var expiresAt *int64
if expires != nil {
timestamp := expires.Unix()
expiresAt = &timestamp
}
if utf8.RuneCountInString(input.Filename) > 255 {
name := []rune(input.Filename)
ext := []rune(filepath.Ext(input.Filename))
if len(ext) >= 255 {
ext = nil
}
input.Filename = string(name[:255-len(ext)]) + string(ext)
}
upload := database.Upload{
ID: id,
Type: input.Type,
Filename: input.Filename,
MIMEType: input.MIMEType,
Size: size,
SHA256: hasher.Sum(nil),
CreatedAt: createdAt,
ExpiresAt: expiresAt,
LastAccessedAt: createdAt,
DeleteToken: rand.Text(),
}
err = database.InsertUpload(db, &upload)
if err != nil {
log.Println("save upload:", err)
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return
}
saved = true
response := UploadResponse{
Upload: upload,
SHA256: hex.EncodeToString(upload.SHA256),
DeleteToken: upload.DeleteToken,
FileExtension: filepath.Ext(upload.Filename),
Qt: pages.GetRandomQt(p.Qts),
}
switch returnType {
// html & maybe xml? cant think of other return types
case "html":
p.Render(w, "upload.html", response)
case "redirect":
http.Redirect(w, r, "/"+id, http.StatusSeeOther)
default:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Println("failed to encode response:", err)
}
}
}
}
func ContentHandler(db *gorm.DB, cfg config.Config, tracker *AccessTracker, p *pages.Pages) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut
if !storage.ValidPasteId(id) {
p.HTTPError(w, r, "upload not found", 404)
return
}
path := storage.GetStoragePath(cfg.UploadDir, id)
upload, err := database.GetUploadById(db.WithContext(r.Context()), id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
p.HTTPError(w, r, "upload not found", 404)
return
}
log.Println("get upload:", err)
p.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return
}
now := time.Now().UTC().Unix()
if upload.ExpiresAt != nil && now >= *upload.ExpiresAt {
p.HTTPError(w, r, "upload not found", 404)
return
}
file, err := os.Open(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
p.HTTPError(w, r, "upload not found", 404)
return
}
log.Println("get upload file:", err)
p.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return
}
defer file.Close()
tracker.Record(id)
ttl := 600 // 10 minutes
if upload.ExpiresAt != nil {
ttl = int(*upload.ExpiresAt - now)
}
mimetype := upload.MIMEType
if cfg.NormalizeMIMETypes {
mimetype = normalizeMIMEType(mimetype)
}
if mimetype == "application/octet-stream" {
w.Header().Set(
"Content-Disposition",
fmt.Sprintf("attachment; filename=\"%s%s\"", upload.ID, filepath.Ext(upload.Filename)),
)
}
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d, must-revalidate", ttl))
w.Header().Set("ETag", "\""+hex.EncodeToString(upload.SHA256)+"\"")
w.Header().Set("Content-Security-Policy", "sandbox")
w.Header().Set("Content-Type", mimetype)
w.Header().Set("X-Content-Type-Options", "nosniff")
http.ServeContent(w, r, upload.Filename, time.Unix(upload.CreatedAt, 0), file)
}
}
func ContentInfoHandler(db *gorm.DB, tracker *AccessTracker, pages *pages.Pages) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut
if !storage.ValidPasteId(id) {
pages.HTTPError(w, r, "upload not found", 404)
return
}
upload, err := database.GetUploadById(db, id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
pages.HTTPError(w, r, "upload not found", 404)
return
}
log.Println("get upload:", err)
pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return
}
tracker.Record(id)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(ContentInfoResponse{
Upload: *upload,
SHA256: hex.EncodeToString(upload.SHA256),
}); err != nil {
log.Println("failed to encode response:", err)
}
}
}
func DeleteHandler(db *gorm.DB, cfg config.Config, pages *pages.Pages) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if !storage.ValidPasteId(id) {
pages.HTTPError(w, r, "upload not found", 404)
return
}
redirect := r.URL.Query().Get("redirect") == "true"
var token string
switch r.Method {
case http.MethodDelete:
bearer := r.Header.Get("Authorization")
var scheme string
var found bool
scheme, token, found = strings.Cut(bearer, " ")
if !found || scheme != "Bearer" {
pages.HTTPError(w, r, "invalid token", http.StatusBadRequest)
return
}
case http.MethodPost:
token = r.PostFormValue("delete_token")
}
path := storage.GetStoragePath(cfg.UploadDir, id)
upload, err := database.GetUploadById(db.WithContext(r.Context()), id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
pages.HTTPError(w, r, "upload not found", 404)
return
}
log.Println("get upload:", err)
pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return
}
if token == "" || subtle.ConstantTimeCompare([]byte(upload.DeleteToken), []byte(token)) != 1 {
pages.HTTPError(w, r, "invalid token", http.StatusBadRequest)
return
}
// 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)
pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return
}
if err := db.WithContext(r.Context()).Delete(upload).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
pages.HTTPError(w, r, "upload not found", 404)
return
}
log.Println("remove upload file:", err)
pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return
}
if redirect {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
w.WriteHeader(http.StatusNoContent)
}
}
+50
View File
@@ -0,0 +1,50 @@
package uploads
import (
"fmt"
"io"
"mime"
"strings"
"github.com/gabriel-vasile/mimetype"
)
func detectMimeType(file io.ReadSeeker) (string, error) {
if _, err := file.Seek(0, io.SeekStart); err != nil {
return "", fmt.Errorf("rewind file: %w", err)
}
mtype, dtcErr := mimetype.DetectReader(file)
if _, err := file.Seek(0, io.SeekStart); err != nil {
return "", fmt.Errorf("rewind file: %w", err)
}
if dtcErr != nil {
return "", fmt.Errorf("detect MIME type: %w", dtcErr)
}
return mtype.String(), nil
}
func normalizeMIMEType(contentType string) string {
const plaintext = "text/plain; charset=utf-8"
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return plaintext
}
if strings.HasSuffix(mediaType, "+xml") {
return plaintext
}
switch mediaType {
case "text/html", "text/javascript", "application/javascript",
"application/ecmascript", "text/ecmascript", "application/xml",
"text/xml", "text/xsl",
"text/css", "application/wasm":
return plaintext
case "application/pdf":
return "application/octet-stream"
default:
return contentType
}
}