mirror of
https://github.com/skidoodle/safebin.git
synced 2026-04-28 03:07:41 +02:00
feat: initial release
This commit is contained in:
@@ -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"))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
const (
|
||||
GCMChunkSize = 64 * 1024
|
||||
NonceSize = 12
|
||||
)
|
||||
|
||||
func DeriveKey(r io.Reader) ([]byte, error) {
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h.Sum(nil)[:16], nil
|
||||
}
|
||||
|
||||
func GetID(key []byte, ext string) string {
|
||||
h := sha256.New()
|
||||
h.Write(key)
|
||||
h.Write([]byte(ext))
|
||||
return base64.RawURLEncoding.EncodeToString(h.Sum(nil)[:9])
|
||||
}
|
||||
|
||||
type GCMStreamer struct {
|
||||
AEAD cipher.AEAD
|
||||
}
|
||||
|
||||
func NewGCMStreamer(key []byte) (*GCMStreamer, error) {
|
||||
b, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g, err := cipher.NewGCM(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &GCMStreamer{AEAD: g}, nil
|
||||
}
|
||||
|
||||
func (g *GCMStreamer) EncryptStream(dst io.Writer, src io.Reader) error {
|
||||
buf := make([]byte, GCMChunkSize)
|
||||
var chunkIdx uint64 = 0
|
||||
for {
|
||||
n, err := io.ReadFull(src, buf)
|
||||
if n > 0 {
|
||||
nonce := make([]byte, NonceSize)
|
||||
binary.BigEndian.PutUint64(nonce[4:], chunkIdx)
|
||||
ciphertext := g.AEAD.Seal(nil, nonce, buf[:n], nil)
|
||||
if _, werr := dst.Write(ciphertext); werr != nil {
|
||||
return werr
|
||||
}
|
||||
chunkIdx++
|
||||
}
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
type Decryptor struct {
|
||||
rs io.ReadSeeker
|
||||
aead cipher.AEAD
|
||||
size int64
|
||||
offset int64
|
||||
}
|
||||
|
||||
func NewDecryptor(rs io.ReadSeeker, aead cipher.AEAD, encryptedSize int64) *Decryptor {
|
||||
overhead := int64(aead.Overhead())
|
||||
fullBlocks := encryptedSize / (GCMChunkSize + overhead)
|
||||
remainder := encryptedSize % (GCMChunkSize + overhead)
|
||||
|
||||
plainSize := (fullBlocks * GCMChunkSize)
|
||||
if remainder > overhead {
|
||||
plainSize += (remainder - overhead)
|
||||
}
|
||||
|
||||
return &Decryptor{
|
||||
rs: rs,
|
||||
aead: aead,
|
||||
size: plainSize,
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Decryptor) Read(p []byte) (int, error) {
|
||||
if d.offset >= d.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
chunkIdx := d.offset / GCMChunkSize
|
||||
overhang := d.offset % GCMChunkSize
|
||||
|
||||
overhead := int64(d.aead.Overhead())
|
||||
actualChunkSize := int64(GCMChunkSize + overhead)
|
||||
|
||||
_, err := d.rs.Seek(chunkIdx*actualChunkSize, io.SeekStart)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
encrypted := make([]byte, actualChunkSize)
|
||||
n, err := io.ReadFull(d.rs, encrypted)
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
nonce := make([]byte, NonceSize)
|
||||
binary.BigEndian.PutUint64(nonce[4:], uint64(chunkIdx))
|
||||
|
||||
plaintext, err := d.aead.Open(nil, nonce, encrypted[:n], nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if overhang >= int64(len(plaintext)) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
available := plaintext[overhang:]
|
||||
nCopied := copy(p, available)
|
||||
d.offset += int64(nCopied)
|
||||
|
||||
return nCopied, nil
|
||||
}
|
||||
|
||||
func (d *Decryptor) Seek(offset int64, whence int) (int64, error) {
|
||||
var abs int64
|
||||
switch whence {
|
||||
case io.SeekStart:
|
||||
abs = offset
|
||||
case io.SeekCurrent:
|
||||
abs = d.offset + offset
|
||||
case io.SeekEnd:
|
||||
abs = d.size + offset
|
||||
default:
|
||||
return 0, errors.New("invalid whence")
|
||||
}
|
||||
if abs < 0 {
|
||||
return 0, errors.New("negative bias")
|
||||
}
|
||||
d.offset = abs
|
||||
return abs, nil
|
||||
}
|
||||
Reference in New Issue
Block a user