feat: initial release

This commit is contained in:
2026-01-16 02:39:40 +01:00
parent 15af32d382
commit 2af23db0ad
21 changed files with 1163 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
package app
import (
"flag"
"fmt"
"html/template"
"log/slog"
"os"
"strconv"
)
type Config struct {
Addr string
StorageDir string
MaxMB int64
}
type App struct {
Conf Config
Tmpl *template.Template
Logger *slog.Logger
}
func LoadConfig() Config {
h := getEnv("SAFEBIN_HOST", "0.0.0.0")
p := getEnvInt("SAFEBIN_PORT", 8080)
s := getEnv("SAFEBIN_STORAGE", "./storage")
mDefault := int64(getEnvInt("SAFEBIN_MAX_MB", 512))
var m int64
flag.StringVar(&h, "h", h, "Bind address")
flag.IntVar(&p, "p", p, "Port")
flag.StringVar(&s, "s", s, "Storage directory")
flag.Int64Var(&m, "m", mDefault, "Max file size in MB")
flag.Parse()
return Config{Addr: fmt.Sprintf("%s:%d", h, p), StorageDir: s, MaxMB: m}
}
func getEnv(k, f string) string {
if v, ok := os.LookupEnv(k); ok {
return v
}
return f
}
func getEnvInt(k string, f int) int {
if v, ok := os.LookupEnv(k); ok {
if i, err := strconv.Atoi(v); err == nil {
return i
}
}
return f
}
func ParseTemplates() *template.Template {
return template.Must(template.ParseGlob("./web/templates/*.html"))
}
+174
View File
@@ -0,0 +1,174 @@
package app
import (
"encoding/base64"
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"github.com/skidoodle/safebin/internal/crypto"
)
var reUploadID = regexp.MustCompile(`^[a-zA-Z0-9]{10,50}$`)
func (app *App) HandleHome(w http.ResponseWriter, r *http.Request) {
err := app.Tmpl.ExecuteTemplate(w, "base", map[string]any{
"MaxMB": app.Conf.MaxMB,
"Host": r.Host,
})
if err != nil {
app.Logger.Error("Template error", "err", err)
}
}
func (app *App) HandleUpload(w http.ResponseWriter, r *http.Request) {
limit := (app.Conf.MaxMB << 20) + (1 << 20)
r.Body = http.MaxBytesReader(w, r.Body, limit)
file, header, err := r.FormFile("file")
if err != nil {
app.SendError(w, r, http.StatusBadRequest)
return
}
defer file.Close()
tmpPath := filepath.Join(app.Conf.StorageDir, "tmp", fmt.Sprintf("up_%d", os.Getpid()))
tmp, _ := os.Create(tmpPath)
defer os.Remove(tmpPath)
defer tmp.Close()
if _, err := io.Copy(tmp, file); err != nil {
app.SendError(w, r, http.StatusRequestEntityTooLarge)
return
}
app.FinalizeFile(w, r, tmp, header.Filename)
}
func (app *App) HandleChunk(w http.ResponseWriter, r *http.Request) {
uid := r.FormValue("upload_id")
idx, _ := strconv.Atoi(r.FormValue("index"))
if !reUploadID.MatchString(uid) || idx > 1000 {
app.SendError(w, r, http.StatusBadRequest)
return
}
file, _, err := r.FormFile("chunk")
if err != nil {
return
}
defer file.Close()
dir := filepath.Join(app.Conf.StorageDir, "tmp", uid)
os.MkdirAll(dir, 0700)
dest, _ := os.Create(filepath.Join(dir, strconv.Itoa(idx)))
defer dest.Close()
io.Copy(dest, file)
}
func (app *App) HandleFinish(w http.ResponseWriter, r *http.Request) {
uid := r.FormValue("upload_id")
total, _ := strconv.Atoi(r.FormValue("total"))
if !reUploadID.MatchString(uid) || total > 1000 {
app.SendError(w, r, http.StatusBadRequest)
return
}
tmpPath := filepath.Join(app.Conf.StorageDir, "tmp", "m_"+uid)
merged, _ := os.Create(tmpPath)
defer os.Remove(tmpPath)
defer merged.Close()
for i := range total {
partPath := filepath.Join(app.Conf.StorageDir, "tmp", uid, strconv.Itoa(i))
part, err := os.Open(partPath)
if err != nil {
continue
}
io.Copy(merged, part)
part.Close()
}
app.FinalizeFile(w, r, merged, r.FormValue("filename"))
os.RemoveAll(filepath.Join(app.Conf.StorageDir, "tmp", uid))
}
func (app *App) HandleGetFile(w http.ResponseWriter, r *http.Request) {
slug := r.PathValue("slug")
if len(slug) < 22 {
app.SendError(w, r, http.StatusBadRequest)
return
}
keyBase64 := slug[:22]
ext := slug[22:]
key, err := base64.RawURLEncoding.DecodeString(keyBase64)
if err != nil || len(key) != 16 {
app.SendError(w, r, http.StatusUnauthorized)
return
}
id := crypto.GetID(key, ext)
path := filepath.Join(app.Conf.StorageDir, id)
info, err := os.Stat(path)
if err != nil {
app.SendError(w, r, http.StatusNotFound)
return
}
f, _ := os.Open(path)
defer f.Close()
streamer, _ := crypto.NewGCMStreamer(key)
decryptor := crypto.NewDecryptor(f, streamer.AEAD, info.Size())
contentType := mime.TypeByExtension(ext)
if contentType == "" {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self' data:; style-src 'unsafe-inline'; sandbox allow-forms allow-scripts allow-downloads allow-same-origin")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=%q", slug))
http.ServeContent(w, r, slug, info.ModTime(), decryptor)
}
func (app *App) FinalizeFile(w http.ResponseWriter, r *http.Request, src *os.File, filename string) {
src.Seek(0, 0)
key, _ := crypto.DeriveKey(src)
ext := filepath.Ext(filename)
id := crypto.GetID(key, ext)
src.Seek(0, 0)
finalPath := filepath.Join(app.Conf.StorageDir, id)
if _, err := os.Stat(finalPath); err == nil {
app.RespondWithLink(w, r, key, filename)
return
}
out, _ := os.Create(finalPath + ".tmp")
streamer, _ := crypto.NewGCMStreamer(key)
if err := streamer.EncryptStream(out, src); err != nil {
out.Close()
os.Remove(finalPath + ".tmp")
app.SendError(w, r, http.StatusInternalServerError)
return
}
out.Close()
os.Rename(finalPath+".tmp", finalPath)
app.RespondWithLink(w, r, key, filename)
}
+58
View File
@@ -0,0 +1,58 @@
package app
import (
"encoding/base64"
"fmt"
"net/http"
"path/filepath"
)
func (app *App) Routes() *http.ServeMux {
mux := http.NewServeMux()
fs := http.FileServer(http.Dir("./web/static"))
mux.Handle("GET /static/", http.StripPrefix("/static/", fs))
mux.HandleFunc("GET /{$}", app.HandleHome)
mux.HandleFunc("POST /{$}", app.HandleUpload)
mux.HandleFunc("POST /upload/chunk", app.HandleChunk)
mux.HandleFunc("POST /upload/finish", app.HandleFinish)
mux.HandleFunc("GET /{slug}", app.HandleGetFile)
return mux
}
func (app *App) RespondWithLink(w http.ResponseWriter, r *http.Request, key []byte, originalName string) {
keySlug := base64.RawURLEncoding.EncodeToString(key)
ext := filepath.Ext(originalName)
link := fmt.Sprintf("%s/%s%s", r.Host, keySlug, ext)
if r.Header.Get("X-Requested-With") == "XMLHttpRequest" {
fmt.Fprintf(w, `
<div style="text-align: left;">
<div class="dim" style="margin-bottom: 8px;">Upload Complete:</div>
<div class="copy-box">
<input type="text" value="%s" id="share-url" readonly onclick="this.select()">
<button onclick="copyToClipboard(this)">Copy</button>
</div>
<button class="reset-btn" onclick="resetUI()">Upload another</button>
</div>`, link)
return
}
scheme := "https"
if r.TLS == nil {
scheme = "http"
}
fmt.Fprintf(w, "%s://%s\n", scheme, link)
}
func (app *App) SendError(w http.ResponseWriter, r *http.Request, code int) {
if r.Header.Get("X-Requested-With") == "XMLHttpRequest" {
w.WriteHeader(code)
fmt.Fprintf(w, `<div class="error-text">Error %d</div><button class="reset-btn" onclick="resetUI()">Try again</button>`, code)
return
}
http.Error(w, http.StatusText(code), code)
}
+50
View File
@@ -0,0 +1,50 @@
package app
import (
"context"
"math"
"os"
"path/filepath"
"time"
)
func (app *App) StartCleanupTask(ctx context.Context) {
ticker := time.NewTicker(1 * time.Hour)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
app.CleanDir(app.Conf.StorageDir, false)
app.CleanDir(filepath.Join(app.Conf.StorageDir, "tmp"), true)
}
}
}
func (app *App) CleanDir(path string, isTmp bool) {
entries, _ := os.ReadDir(path)
for _, entry := range entries {
info, _ := entry.Info()
expiry := 4 * time.Hour
if !isTmp {
expiry = CalculateRetention(info.Size(), app.Conf.MaxMB)
}
if time.Since(info.ModTime()) > expiry {
os.RemoveAll(filepath.Join(path, entry.Name()))
}
}
}
func CalculateRetention(fileSize int64, maxMB int64) time.Duration {
const (
minAge = 24 * time.Hour
maxAge = 365 * 24 * time.Hour
)
ratio := math.Max(0, math.Min(1, float64(fileSize)/float64(maxMB<<20)))
retention := float64(maxAge) * math.Pow(1.0-ratio, 3)
if retention < float64(minAge) {
return minAge
}
return time.Duration(retention)
}