diff --git a/cmd/minibin/main.go b/cmd/minibin/main.go new file mode 100644 index 0000000..30ae5d2 --- /dev/null +++ b/cmd/minibin/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "context" + "log" + "net/http" + "os" + "time" + + "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/reports" + "git.whoswhip.dev/whoswhip/minibin/internal/server" + "git.whoswhip.dev/whoswhip/minibin/internal/uploads" +) + +func main() { + config, err := config.LoadConfig() + if err != nil { + log.Fatal(err) + } + + log.Println("config loaded") + + db, err := database.InitDatabase(config.DatabasePath) + + if err != nil { + log.Fatal(err) + } + + log.Println("database initialized") + + if err := os.MkdirAll(config.UploadDir, 0700); err != nil { + log.Fatal(err) + } + + pages, err := pages.LoadPages() + if err != nil { + log.Fatal(err) + } + + tracker := uploads.NewAccessTracker() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go tracker.Run(ctx, db) + + challengeStore := reports.NewChallengeStore(3 * time.Minute) + + log.Println("listening on", config.Addr) + router := server.NewRouter(db, config, pages, tracker, challengeStore) + err = http.ListenAndServe(config.Addr, router) + if err != nil { + log.Fatal(err) + } +} diff --git a/go.sum b/go.sum index ad3d1e0..dc53943 100644 --- a/go.sum +++ b/go.sum @@ -8,8 +8,6 @@ github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GM github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= diff --git a/config.go b/internal/config/config.go similarity index 97% rename from config.go rename to internal/config/config.go index 5bb13af..be317f5 100644 --- a/config.go +++ b/internal/config/config.go @@ -1,4 +1,4 @@ -package main +package config import ( "fmt" @@ -26,7 +26,7 @@ type Config struct { Addr string } -func loadConfig() (Config, error) { +func LoadConfig() (Config, error) { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") @@ -53,7 +53,7 @@ func loadConfig() (Config, error) { 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) + expiry, err := ParseExpiry(entry) if err != nil { return Config{}, fmt.Errorf("MINIBIN_EXPIRIES: %w", err) } diff --git a/expiry.go b/internal/config/expiry.go similarity index 92% rename from expiry.go rename to internal/config/expiry.go index 41f8329..5554795 100644 --- a/expiry.go +++ b/internal/config/expiry.go @@ -1,4 +1,4 @@ -package main +package config import ( "fmt" @@ -18,7 +18,7 @@ type Expiry struct { // 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) { +func ParseExpiry(expiry string) (Expiry, error) { expiry = strings.TrimSpace(expiry) if expiry == "0" { return Expiry{ @@ -45,7 +45,7 @@ func parseExpiry(expiry string) (Expiry, error) { }, nil } -func findExpiry(expiries []Expiry, label string) (Expiry, bool) { +func FindExpiry(expiries []Expiry, label string) (Expiry, bool) { index := slices.IndexFunc(expiries, func(expiry Expiry) bool { return expiry.Label == label }) diff --git a/database.go b/internal/database/database.go similarity index 90% rename from database.go rename to internal/database/database.go index 8d14446..1dc3e82 100644 --- a/database.go +++ b/internal/database/database.go @@ -1,4 +1,4 @@ -package main +package database import ( "errors" @@ -36,7 +36,7 @@ type Report struct { CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime"` } -func initDatabase(path string) (*gorm.DB, error) { +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) @@ -65,15 +65,15 @@ func initDatabase(path string) (*gorm.DB, error) { return db, nil } -func insertUpload(db *gorm.DB, upload *Upload) error { +func InsertUpload(db *gorm.DB, upload *Upload) error { return db.Create(upload).Error } -func insertReport(db *gorm.DB, report *Report) 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) { +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 diff --git a/pages.go b/internal/pages/pages.go similarity index 66% rename from pages.go rename to internal/pages/pages.go index 6f5628f..440e76f 100644 --- a/pages.go +++ b/internal/pages/pages.go @@ -1,7 +1,6 @@ -package main +package pages import ( - "encoding/hex" "errors" "html/template" "log" @@ -12,6 +11,7 @@ import ( "path/filepath" "strings" + "git.whoswhip.dev/whoswhip/minibin/internal/config" "github.com/dustin/go-humanize" ) @@ -22,27 +22,27 @@ type Pages struct { } type HomePageData struct { - Expiries []Expiry + Expiries []config.Expiry Qt string PastePlaceholder string FileMaxSize string PasteMaxSize string } -func (pages *Pages) render(w http.ResponseWriter, name string, data any) { +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 { +func StaticPage(pages *Pages, name string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - pages.render(w, name, getRandomQt(pages.Qts)) + pages.Render(w, name, GetRandomQt(pages.Qts)) } } -func resultPage(pages *Pages, title string, message string, statusCode ...int) 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 { @@ -50,25 +50,25 @@ func resultPage(pages *Pages, title string, message string, statusCode ...int) h } w.WriteHeader(code) - pages.render(w, "result.html", map[string]any{ - "Qt": getRandomQt(pages.Qts), + pages.Render(w, "result.html", map[string]any{ + "Qt": GetRandomQt(pages.Qts), "Title": title, "Message": message, }) } } -func getRandomQt(qts []string) string { +func GetRandomQt(qts []string) string { if len(qts) > 0 { return qts[rand.IntN(len(qts))] } return "" } -func loadPages() (*Pages, error) { +func LoadPages() (*Pages, error) { templates, err := template.New("").Funcs(template.FuncMap{ "hasPrefix": strings.HasPrefix, - }).ParseGlob("templates/*.html") + }).ParseGlob("web/templates/*.html") if err != nil { return nil, err } @@ -105,50 +105,30 @@ func loadPages() (*Pages, error) { return pages, nil } -func homeHandler(pages *Pages, cfg Config) http.HandlerFunc { +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), + Qt: GetRandomQt(pages.Qts), } if len(pages.Placeholders) > 0 { data.PastePlaceholder = pages.Placeholders[rand.IntN(len(pages.Placeholders))] } - pages.render(w, "home.html", data) + pages.Render(w, "home.html", data) } } -func faqHandler(pages *Pages, cfg Config) http.HandlerFunc { +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{ + pages.Render(w, "faq.html", map[string]any{ "Expiries": cfg.Expiries, "Host": cfg.Host, "NormalizeMIMETypes": cfg.NormalizeMIMETypes, - "Qt": getRandomQt(pages.Qts), - }) - } -} - -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 - } - pages.render(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, + "Qt": GetRandomQt(pages.Qts), }) } } diff --git a/internal/reports/handlers.go b/internal/reports/handlers.go new file mode 100644 index 0000000..4dc0598 --- /dev/null +++ b/internal/reports/handlers.go @@ -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, + }) + } +} diff --git a/pow.go b/internal/reports/pow.go similarity index 96% rename from pow.go rename to internal/reports/pow.go index d14fd14..370a868 100644 --- a/pow.go +++ b/internal/reports/pow.go @@ -1,4 +1,4 @@ -package main +package reports import ( "crypto/rand" @@ -9,6 +9,8 @@ import ( "log" "sync" "time" + + "git.whoswhip.dev/whoswhip/minibin/internal/storage" ) type Challenge struct { @@ -43,7 +45,7 @@ func (store *ChallengeStore) Issue(difficulty int) (id string, challenge Challen return "", Challenge{}, fmt.Errorf("challenge store is full") } - id = generateId(16) + id = storage.GenerateId(16) data := make([]byte, 32) if _, err := rand.Read(data); err != nil { log.Println("failed to generate PoW challenge:", err) diff --git a/internal/server/routes.go b/internal/server/routes.go new file mode 100644 index 0000000..bce3645 --- /dev/null +++ b/internal/server/routes.go @@ -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 +} diff --git a/storage.go b/internal/storage/storage.go similarity index 84% rename from storage.go rename to internal/storage/storage.go index ea0a2c4..20b626c 100644 --- a/storage.go +++ b/internal/storage/storage.go @@ -1,4 +1,4 @@ -package main +package storage import ( "crypto/rand" @@ -11,7 +11,7 @@ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 // generates a secure random id, // length must be either 10 or 16 -func generateId(length int) string { +func GenerateId(length int) string { if length != 10 && length != 16 { panic("length must be 10 or 16") } @@ -29,7 +29,7 @@ func generateId(length int) string { return string(bytes) } -func validPasteId(id string) bool { +func ValidPasteId(id string) bool { if len(id) != 10 && len(id) != 16 { return false } @@ -44,6 +44,6 @@ func validPasteId(id string) bool { return true } -func getStoragePath(uploadDir, id string) string { +func GetStoragePath(uploadDir, id string) string { return filepath.Join(uploadDir, id[:2], id[2:4], id) } diff --git a/access.go b/internal/uploads/access.go similarity index 86% rename from access.go rename to internal/uploads/access.go index 6fa6e75..e156578 100644 --- a/access.go +++ b/internal/uploads/access.go @@ -1,4 +1,4 @@ -package main +package uploads import ( "context" @@ -6,6 +6,7 @@ import ( "sync" "time" + "git.whoswhip.dev/whoswhip/minibin/internal/database" "gorm.io/gorm" ) @@ -14,6 +15,12 @@ type AccessTracker struct { 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() @@ -32,7 +39,7 @@ func (tracker *AccessTracker) Flush(ctx context.Context, db *gorm.DB) error { err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { for id, timestamp := range batch { - err := tx.Model(&Upload{}). + err := tx.Model(&database.Upload{}). Where("id = ? AND last_accessed_at < ?", id, timestamp). UpdateColumn("last_accessed_at", timestamp).Error if err != nil { diff --git a/handlers.go b/internal/uploads/handlers.go similarity index 64% rename from handlers.go rename to internal/uploads/handlers.go index 3c10dfd..5f89a62 100644 --- a/handlers.go +++ b/internal/uploads/handlers.go @@ -1,4 +1,4 @@ -package main +package uploads import ( "crypto/rand" @@ -15,44 +15,41 @@ import ( "os" "path/filepath" "slices" - "strconv" "strings" "time" "unicode/utf8" - "uuid" + "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" ) -func health(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain; charset=utf-8") - fmt.Fprintln(w, "OK") -} - type UploadInput struct { Reader io.Reader Filename string MIMEType string - Type ContentType + Type database.ContentType } type UploadResponse struct { - Upload + 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 { - Upload + database.Upload SHA256 string `json:"sha256"` Filename string `json:"-"` } -func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { +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") - pages.HTTPError(w, r, "invalid method", http.StatusMethodNotAllowed) + p.HTTPError(w, r, "invalid method", http.StatusMethodNotAllowed) return } @@ -64,7 +61,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { if r.Method == http.MethodPost || r.Header.Get("Content-Type") != "" { mediaType, _, err = mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil { - pages.HTTPError(w, r, "failed to find or parse Content-Type", http.StatusBadRequest) + p.HTTPError(w, r, "failed to find or parse Content-Type", http.StatusBadRequest) return } } @@ -84,11 +81,11 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { } if err != nil { if _, ok := errors.AsType[*http.MaxBytesError](err); ok { - pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) + p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) return } - pages.HTTPError(w, r, "invalid file", http.StatusBadRequest) + p.HTTPError(w, r, "invalid file", http.StatusBadRequest) return } defer file.Close() @@ -96,16 +93,16 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { input.MIMEType, err = detectMimeType(file) if err != nil { log.Println("detect file mime type:", err) - pages.HTTPError(w, r, "failed to detect mime type", http.StatusInternalServerError) + p.HTTPError(w, r, "failed to detect mime type", http.StatusInternalServerError) return } if slices.Contains(cfg.BannedMIMETypes, input.MIMEType) { - pages.HTTPError(w, r, "content type not allowed", http.StatusBadRequest) + p.HTTPError(w, r, "content type not allowed", http.StatusBadRequest) return } input.Reader = file input.Filename = header.Filename - input.Type = ContentFile + 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 @@ -124,16 +121,16 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { if err != nil { if _, ok := errors.AsType[*http.MaxBytesError](err); ok { - pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) + p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) return } - pages.HTTPError(w, r, "invalid paste upload", http.StatusBadRequest) + p.HTTPError(w, r, "invalid paste upload", http.StatusBadRequest) return } if strings.TrimSpace(content) == "" { - pages.HTTPError(w, r, "paste cannot be empty", http.StatusBadRequest) + p.HTTPError(w, r, "paste cannot be empty", http.StatusBadRequest) return } @@ -141,10 +138,10 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { Reader: strings.NewReader(content), Filename: "paste.txt", MIMEType: "text/plain; charset=utf-8", - Type: ContentPaste, + Type: database.ContentPaste, } default: - pages.HTTPError(w, r, "unsupported Content-Type", http.StatusUnsupportedMediaType) + p.HTTPError(w, r, "unsupported Content-Type", http.StatusUnsupportedMediaType) return } @@ -156,9 +153,9 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { expLabel = cfg.Expiries[0].Label } - selected, found := findExpiry(cfg.Expiries, expLabel) + selected, found := config.FindExpiry(cfg.Expiries, expLabel) if !found { - pages.HTTPError(w, r, "invalid expiry", http.StatusBadRequest) + p.HTTPError(w, r, "invalid expiry", http.StatusBadRequest) return } @@ -170,18 +167,18 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { idLength = 10 } - id := generateId(idLength) - path := getStoragePath(cfg.UploadDir, id) + 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) - pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError) + 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) - pages.HTTPError(w, r, "faield to save upload", http.StatusInternalServerError) + p.HTTPError(w, r, "faield to save upload", http.StatusInternalServerError) return } @@ -199,23 +196,23 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader) if err != nil { if _, ok := errors.AsType[*http.MaxBytesError](err); ok { - pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) + p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) return } log.Println("write file:", err) - pages.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError) + p.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError) return } if err := dest.Close(); err != nil { log.Println("close file:", err) - pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError) + 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 - pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) + p.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } @@ -235,7 +232,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { input.Filename = string(name[:255-len(ext)]) + string(ext) } - upload := Upload{ + upload := database.Upload{ ID: id, Type: input.Type, Filename: input.Filename, @@ -247,10 +244,10 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { LastAccessedAt: createdAt, DeleteToken: rand.Text(), } - err = insertUpload(db, &upload) + err = database.InsertUpload(db, &upload) if err != nil { log.Println("save upload:", err) - pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError) + p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError) return } saved = true @@ -260,13 +257,13 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { SHA256: hex.EncodeToString(upload.SHA256), DeleteToken: upload.DeleteToken, FileExtension: filepath.Ext(upload.Filename), - Qt: getRandomQt(pages.Qts), + Qt: pages.GetRandomQt(p.Qts), } switch returnType { // html & maybe xml? cant think of other return types case "html": - pages.render(w, "upload.html", response) + p.Render(w, "upload.html", response) case "redirect": http.Redirect(w, r, "/"+id, http.StatusSeeOther) default: @@ -280,41 +277,41 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { } } -func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker, pages *Pages) http.HandlerFunc { +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 !validPasteId(id) { - pages.HTTPError(w, r, "upload not found", 404) + if !storage.ValidPasteId(id) { + p.HTTPError(w, r, "upload not found", 404) return } - path := getStoragePath(cfg.UploadDir, id) - upload, err := getUploadById(db.WithContext(r.Context()), id) + 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) + p.HTTPError(w, r, "upload not found", 404) return } log.Println("get upload:", err) - pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) + p.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } now := time.Now().UTC().Unix() if upload.ExpiresAt != nil && now >= *upload.ExpiresAt { - pages.HTTPError(w, r, "upload not found", 404) + p.HTTPError(w, r, "upload not found", 404) return } file, err := os.Open(path) if err != nil { if errors.Is(err, os.ErrNotExist) { - pages.HTTPError(w, r, "upload not found", 404) + p.HTTPError(w, r, "upload not found", 404) return } log.Println("get upload file:", err) - pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) + p.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } @@ -346,16 +343,16 @@ func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker, pages *Page } } -func contentInfoHandler(db *gorm.DB, tracker *AccessTracker, pages *Pages) http.HandlerFunc { +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 !validPasteId(id) { + if !storage.ValidPasteId(id) { pages.HTTPError(w, r, "upload not found", 404) return } - upload, err := getUploadById(db, id) + upload, err := database.GetUploadById(db, id) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { pages.HTTPError(w, r, "upload not found", 404) @@ -378,10 +375,10 @@ func contentInfoHandler(db *gorm.DB, tracker *AccessTracker, pages *Pages) http. } } -func deleteHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { +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 !validPasteId(id) { + if !storage.ValidPasteId(id) { pages.HTTPError(w, r, "upload not found", 404) return } @@ -402,8 +399,8 @@ func deleteHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { token = r.PostFormValue("delete_token") } - path := getStoragePath(cfg.UploadDir, id) - upload, err := getUploadById(db.WithContext(r.Context()), id) + 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) @@ -444,69 +441,3 @@ func deleteHandler(db *gorm.DB, cfg Config, pages *Pages) 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 { - pages.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 == "" { - 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 { - pages.HTTPError(w, r, 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) - pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) - return - } - - resultPage(pages, "success!", "your report has been successfully submitted", 200)(w, r) - } -} diff --git a/mime.go b/internal/uploads/mime.go similarity index 98% rename from mime.go rename to internal/uploads/mime.go index a9a4b53..ed4060e 100644 --- a/mime.go +++ b/internal/uploads/mime.go @@ -1,4 +1,4 @@ -package main +package uploads import ( "fmt" diff --git a/main.go b/main.go deleted file mode 100644 index c11702d..0000000 --- a/main.go +++ /dev/null @@ -1,51 +0,0 @@ -package main - -import ( - "context" - "log" - "net/http" - "os" - "time" -) - -func main() { - config, err := loadConfig() - if err != nil { - log.Fatal(err) - } - - log.Println("config loaded") - - db, err := initDatabase(config.DatabasePath) - - if err != nil { - log.Fatal(err) - } - - log.Println("database initialized") - - if err := os.MkdirAll(config.UploadDir, 0700); err != nil { - log.Fatal(err) - } - - pages, err := loadPages() - if err != nil { - log.Fatal(err) - } - - tracker := &AccessTracker{ - pending: make(map[string]int64), - } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go tracker.Run(ctx, db) - - challengeStore := NewChallengeStore(3 * time.Minute) - - log.Println("listening on", config.Addr) - router := newRouter(db, config, pages, tracker, challengeStore) - err = http.ListenAndServe(config.Addr, router) - if err != nil { - log.Fatal(err) - } -} diff --git a/routes.go b/routes.go deleted file mode 100644 index 63fd410..0000000 --- a/routes.go +++ /dev/null @@ -1,35 +0,0 @@ -package main - -import ( - "net/http" - - "gorm.io/gorm" -) - -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) - 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 /{$}", homeHandler(pages, cfg)) - 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, pages)) - uploads.HandleFunc("GET /{id}/info", contentInfoHandler(db, tracker, pages)) - mux.Handle("/", uploads) - mux.HandleFunc("POST /upload", uploadHandler(db, cfg, pages)) - mux.HandleFunc("PUT /upload", uploadHandler(db, cfg, pages)) - mux.HandleFunc("DELETE /{id}", deleteHandler(db, cfg, pages)) - mux.HandleFunc("POST /{id}/delete", deleteHandler(db, cfg, pages)) - mux.HandleFunc("GET /health", health) - return mux -} diff --git a/static/css/main.css b/static/css/main.css deleted file mode 100644 index 93b77c9..0000000 --- a/static/css/main.css +++ /dev/null @@ -1,336 +0,0 @@ -:root { - --bg: #191919; - --surface: #2a2a2a; - --surface-between: #3a3a3a; - --surface-hover: #4a4a4a; - --text: #eee; - --text-muted: #aaa; - --border: #4e4e4e; - --border-strong: #7e7e7e; -} - -* { - box-sizing: border-box; -} - -body { - min-height: 100vh; - background-color: var(--bg); - color: var(--text); - margin: 0; - font-family: Consolas, monospace; - font-size: 14px; - background-image: var(--qt-url); - background-repeat: no-repeat; - background-position: bottom right; - background-size: auto 256px; - background-attachment: fixed; -} - -b { - font-weight: bold; -} - -h1, -h2 { - margin: 0; - font-weight: 400; -} - -h4 { - margin: 6px 0; -} - -h1 { - font-size: 18px; - font-weight: 700; -} - -a { - color: var(--text); -} - -main { - width: min(100% - 36px, 720px); - margin: 0 auto; - padding: 11px 0 64px; -} - -.site-header { - width: min(100% - 36px, 720px); - margin: 0 auto; - padding: 44px 0 0; - display: flex; - justify-content: space-between; -} - -textarea { - background: var(--bg); - display: block; - width: 100%; - min-height: 120px; - height: 120px; - resize: vertical; - border: 1px solid var(--border); - font: inherit; - padding: 12px; - outline: none; - color: var(--text); - 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; - gap: 0.75rem; -} - -.upload-tabs > label { - cursor: pointer; - border-bottom: 1px solid transparent; - color: var(--text-muted); -} - -.upload-tabs > input { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip-path: inset(50%); -} - -.upload-tabs > input:checked + label { - border-bottom-color: currentColor; - color: var(--text); -} - -.upload-tabs > input:focus-visible + label { - border: 1px solid currentColor; -} - -.file-panel, -.paste-panel { - display: none; - width: 100%; -} - -#type-file:checked ~ .file-panel, -#type-paste:checked ~ .paste-panel { - display: block; -} - -input[type="file"] { - display: block; - border: 1px solid var(--border); - color: var(--text); - width: 100%; - cursor: pointer; - margin-bottom: 12px; - font: inherit; -} - -input[type="file"]:hover { - background-color: var(--surface); -} -input[type="file"]:hover::file-selector-button { - background-color: var(--surface-hover); -} - -input[type="file"]::file-selector-button { - background-color: var(--surface); - border: none; - color: var(--text); - padding: 10px; - font: inherit; -} - -.muted { - color: var(--text-muted); -} -select { - padding: 0 0 2px; - background: var(--bg); - border: none; - color: var(--text); - border-bottom: 1px solid var(--border-strong); - border-radius: 0; - font: inherit; - margin-bottom: 12px; -} - -option { - background-color: var(--bg); - font: inherit; -} - -.btn { - border-radius: 0; - border: none; - background-color: var(--text); - padding: 11px; - color: var(--surface); - font: inherit; - cursor: pointer; -} - -.btn:hover { - background-color: var(--text-muted); -} - -.btn:disabled { - background-color: var(--surface); - color: var(--text-muted); - cursor: not-allowed; -} - -.link-btn { - border: none; - background: none; - padding: 0; - text-decoration: underline; - color: var(--text); - cursor: pointer; - font: inherit; -} - -img, -video, -audio { - max-width: 100%; - max-height: 80dvh; -} - -.upload-links { - margin-top: 12px; - display: flex; - flex-direction: row; - gap: 12px; - align-items: baseline; -} - -.upload-links form { - margin: 0; -} - -body.dragging::after { - content: "drop file to select"; - position: fixed; - inset: 0; - z-index: 100; - display: grid; - place-items: center; - background: rgb(0 0 0 / 30%); - color: var(--text); - font-size: 1.5rem; - pointer-events: none; -} - -.upload-metadata { - width: 100%; - table-layout: fixed; - border-collapse: collapse; -} - -.upload-metadata th, -.upload-metadata td { - padding: 8px 0; - border-bottom: 1px solid var(--border); - text-align: left; - vertical-align: top; - overflow-wrap: anywhere; -} - -.upload-metadata th:first-child { - width: 20%; - padding-right: 16px; -} - -.upload-metadata th[scope="row"] { - color: var(--text-muted); - font-weight: bold; -} - -code { - background-color: var(--surface-between); - padding-inline: 3px; - border: 1px solid var(--surface-hover); -} - -.submit-container { - width: 100%; - 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/copy.js b/static/js/copy.js deleted file mode 100644 index 1293964..0000000 --- a/static/js/copy.js +++ /dev/null @@ -1,18 +0,0 @@ -const link = document.getElementById("copy-link"); - -if (link && navigator.clipboard?.writeText) { - link.style.display = ""; - link.hidden = false; - link.onclick = async (e) => { - e.preventDefault(); - try { - await navigator.clipboard.writeText(`${location.origin}/${link.dataset.id}${link.dataset.extension}`); - link.textContent = "copied"; - setTimeout(() => { - link.textContent = "copy link"; - }, 2000); - } catch (error) { - console.error("failed to copy link:", error); - } - }; -} diff --git a/static/js/dnd.js b/static/js/dnd.js deleted file mode 100644 index 80a5fa1..0000000 --- a/static/js/dnd.js +++ /dev/null @@ -1,46 +0,0 @@ -const fileInput = document.getElementById("upload-file"); - -function isFile(event) { - return event.dataTransfer.types.includes("Files"); -} - -function resetDrag() { - document.body.classList.remove("dragging"); -} - -document.addEventListener("dragenter", (event) => { - if (!isFile(event)) return; - - event.preventDefault(); - document.body.classList.add("dragging"); -}); - -document.addEventListener("dragover", (event) => { - if (!isFile(event)) return; - - event.preventDefault(); - event.dataTransfer.dropEffect = "copy"; -}); - -document.addEventListener("dragleave", () => { - resetDrag(); -}); - -document.addEventListener("drop", (event) => { - resetDrag(); - if (!isFile(event)) return; - - event.preventDefault(); - - const file = event.dataTransfer.files[0]; - if (!file) return; - - const transfer = new DataTransfer(); - transfer.items.add(file); - fileInput.files = transfer.files; - - document.getElementById("type-file").checked = true; - fileInput.dispatchEvent(new Event("change", { bubbles: true })); -}); - -document.addEventListener("dragend", resetDrag); diff --git a/static/js/pow-worker.js b/static/js/pow-worker.js deleted file mode 100644 index d834a67..0000000 --- a/static/js/pow-worker.js +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index f85b76f..0000000 --- a/static/js/report.js +++ /dev/null @@ -1,17 +0,0 @@ -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/faq.html b/templates/faq.html deleted file mode 100644 index 670bb39..0000000 --- a/templates/faq.html +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - faq | minibin - - {{if .Qt}} - - {{end}} - - - {{template "site-header"}} -
-

frequently asked questions

-

how long are uploads/files kept for?

-

- minibin will store them for as long as their set expiry, unless they - violate the TOS or have not been accessed in a long time. -

-

are uploads modified in any way?

-

- no, all uploads are exactly the same as what you uploaded. uploads are - not compressed, transformed, or modified in any way, not even exif data. -

-

- be wary of any metadata included in the files you are uploading, - especially photos from a phone as they may contain GPS data. -

- {{if .NormalizeMIMETypes}} -

why are my html/svg/pdf uploads not being rendered?

-

they are being normalized for security.

- {{end}} -

api usage

-

how do i upload via the api?

-

- send a POST request to /upload. for files, use multipart - form data with a field named file. for pastes, send the - text with Content-Type: text/plain. -

-

- to add an expiry, append ?expiry={value}.
supported - values are: - {{range $i, $expiry := .Expiries}}{{if - $i}},{{end}}{{$expiry.Label}}{{end}}. omitting an expiry will use the first expiry listed. -

-

- you can also specify if you would prefer a long or short upload id, just - append
?idlength=short to get a shorter id (10 characters), - otherwise it defaults to long (16 character) -

-

uploading the output of a command

- cat super-cool-text.txt | curl -T - {{.Host}}/upload -

upload a file via curl

- curl -F "file=@very-cool-image.png" {{.Host}}/upload -

getting upload info

-

- you can retrieve an upload's metadata by simply appending /info to the end of an upload, like /{id}/info. - it returns all stored metadata except for the original filename. -

-
- - diff --git a/templates/header.html b/templates/header.html deleted file mode 100644 index 9e56c66..0000000 --- a/templates/header.html +++ /dev/null @@ -1,12 +0,0 @@ -{{define "site-header"}} - -{{end}} diff --git a/templates/home.html b/templates/home.html deleted file mode 100644 index 0d76ea6..0000000 --- a/templates/home.html +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - minibin - - - {{if .Qt}} - - {{end}} - - - - - - - {{template "site-header"}} -
-

simple file and paste hosting service

-
- - - - -
-
- - - - - -
- - max {{.FileMaxSize}} -
-
-
-
-
- - - - - -
- - max {{.PasteMaxSize}} -
-
-
-
-
- - diff --git a/templates/privacy.html b/templates/privacy.html deleted file mode 100644 index bb5ca9a..0000000 --- a/templates/privacy.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - privacy | minibin - - {{if .}} - - {{end}} - - - {{template "site-header"}} -
-

privacy policy

-

what we store

-

when you upload a file or paste, we store:

- -

- this information is used to serve uploads, check expiry, and allow - deletion of uploads. -

- -

who can access uploads

-

- anyone with the id of an upload can access and share it. minibin's - operator can also access stored uploads. avoid uploading anything - private. -

-

changes to this policy

-

- this policy may change as minibin changes. updates will be posted on - this page. -

-
- - diff --git a/templates/report.html b/templates/report.html deleted file mode 100644 index 2b8704b..0000000 --- a/templates/report.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - report | minibin - - - {{if .Qt}} - - {{end}} - - - {{template "site-header"}} - -
- -
- - - - - - - -
- - computing proof of work -
-
-
- - diff --git a/templates/result.html b/templates/result.html deleted file mode 100644 index 8be0b08..0000000 --- a/templates/result.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - {{.Title}} | minibin - - {{if .Qt}} - - {{end}} - - - {{template "site-header"}} -
-

{{.Title}}

-

{{.Message}}

-
- - diff --git a/templates/tos.html b/templates/tos.html deleted file mode 100644 index 9eff901..0000000 --- a/templates/tos.html +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - tos | minibin - - {{if .}} - - {{end}} - - - {{template "site-header"}} -
-

terms of service

-

by using minibin, you agree to these terms.

-

acceptable use

-

- you are responsible for what you upload and share. only upload content - that you own or are allowed to share. -

-

prohibited content

-

do not upload or share:

- -

storage and expiry

-

- uploads have an expiry based on the option selected when uploading. - indefinite means there is no scheduled expiry. -

-

- uploads may be removed earlier for breaking these terms, maintenance or - storage limits. ensure you keep a copy of anything important. -

- -

deleting uploads

-

- keep the delete token provided after uploading. anyone with that token - is able to delete the upload, so keep it private. -

-

changes to these terms

-

these terms may change, updates with be posted on this page.

-
- - diff --git a/templates/upload.html b/templates/upload.html deleted file mode 100644 index 15ef924..0000000 --- a/templates/upload.html +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - {{.ID}} | minibin - - {{if .Qt}} - - {{end}} - - - - {{template "site-header"}} -
-
- {{if hasPrefix .MIMEType "image/"}} - - {{else if hasPrefix .MIMEType "video/"}} - - {{else if hasPrefix .MIMEType "audio/"}} - - {{else}} -

{{.Filename}}

-

{{.ID}}{{.FileExtension}}

- {{end}} -
- -
- upload metadata - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - -
- -