Add generic file upload support to pastebin (5 MB max)
Adds a new POST /admin/upload-file endpoint for uploading any file type alongside the existing image upload. Files are served with Content-Disposition: attachment to prevent same-origin XSS via uploaded HTML/SVG/JS. The display filename embedded in markdown link responses is sanitized to block markdown injection. Co-Authored-By: Claude Opus 4.6 <[email protected]>
This commit is contained in:
1 parent
d788210aa9
commit
b069027d56
4 files changed
+227
-52
No files matched your search
+130
-6
@@ -63,6 +63,7 @@ type UploadInfo struct {
|
||||
Width int
|
||||
Height int
|
||||
CanResize bool
|
||||
IsImage bool
|
||||
ModTime time.Time
|
||||
}
|
||||
|
||||
@@ -687,12 +688,20 @@ func (s *Server) handleAdminBinDelete(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// ---- Upload helpers ----
|
||||
|
||||
var validUploadRe = regexp.MustCompile(`^[0-9a-f]{32}\.(png|jpg|gif|webp)$`)
|
||||
var validUploadRe = regexp.MustCompile(`^[0-9a-f]{32}\.[a-z0-9]{1,10}$`)
|
||||
|
||||
func validUploadFilename(name string) bool {
|
||||
return validUploadRe.MatchString(name)
|
||||
}
|
||||
|
||||
var imageExts = map[string]bool{
|
||||
".png": true, ".jpg": true, ".gif": true, ".webp": true,
|
||||
}
|
||||
|
||||
func isImageFile(name string) bool {
|
||||
return imageExts[strings.ToLower(filepath.Ext(name))]
|
||||
}
|
||||
|
||||
func formatBytes(n int64) string {
|
||||
switch {
|
||||
case n >= 1024*1024:
|
||||
@@ -749,6 +758,24 @@ func scaleImage(src image.Image, maxDim int) image.Image {
|
||||
return dst
|
||||
}
|
||||
|
||||
// handleUploadsServe serves files from the upload directory. For non-image
|
||||
// files it forces Content-Disposition: attachment with an octet-stream type so
|
||||
// that arbitrary uploads (e.g. HTML, SVG, JS) cannot be rendered in-browser
|
||||
// from the same origin as the admin panel.
|
||||
func (s *Server) handleUploadsServe(w http.ResponseWriter, r *http.Request) {
|
||||
name := strings.TrimPrefix(r.URL.Path, "/uploads/")
|
||||
if !validUploadFilename(name) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
path := filepath.Join(s.cfg.Upload.Dir, name)
|
||||
if !isImageFile(name) {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
|
||||
}
|
||||
http.ServeFile(w, r, path)
|
||||
}
|
||||
|
||||
// ---- Upload management handlers ----
|
||||
|
||||
func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -776,15 +803,18 @@ func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) {
|
||||
Size: info.Size(),
|
||||
SizeHuman: formatBytes(info.Size()),
|
||||
URL: "/uploads/" + name,
|
||||
IsImage: isImageFile(name),
|
||||
ModTime: info.ModTime(),
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(name))
|
||||
if f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, name)); err == nil {
|
||||
if cfg, _, err := image.DecodeConfig(f); err == nil {
|
||||
ui.Width = cfg.Width
|
||||
ui.Height = cfg.Height
|
||||
if ui.IsImage {
|
||||
if f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, name)); err == nil {
|
||||
if cfg, _, err := image.DecodeConfig(f); err == nil {
|
||||
ui.Width = cfg.Width
|
||||
ui.Height = cfg.Height
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
if ext == ".png" || ext == ".jpg" {
|
||||
ui.CanResize = true
|
||||
@@ -981,6 +1011,100 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// ---- File upload handler (any file, 5 MB max) ----
|
||||
|
||||
var validExtRe = regexp.MustCompile(`^[a-z0-9]{1,10}$`)
|
||||
|
||||
func (s *Server) handleFileUpload(w http.ResponseWriter, r *http.Request) {
|
||||
const maxFileBytes = 5 * 1024 * 1024
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxFileBytes+4096)
|
||||
|
||||
rc := http.NewResponseController(w)
|
||||
rc.SetReadDeadline(time.Now().Add(120 * time.Second))
|
||||
rc.SetWriteDeadline(time.Now().Add(120 * time.Second))
|
||||
|
||||
if !verifyCSRF(r) {
|
||||
jsonError(w, "Invalid CSRF token", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
if err.Error() == "http: request body too large" {
|
||||
jsonError(w, "File too large (max 5 MB)", http.StatusRequestEntityTooLarge)
|
||||
} else {
|
||||
jsonError(w, "No file provided", http.StatusBadRequest)
|
||||
}
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(header.Filename), "."))
|
||||
if ext == "" || !validExtRe.MatchString(ext) {
|
||||
jsonError(w, "Invalid file extension", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
randBytes := make([]byte, 16)
|
||||
rand.Read(randBytes)
|
||||
filename := hex.EncodeToString(randBytes) + "." + ext
|
||||
|
||||
destPath := filepath.Join(s.cfg.Upload.Dir, filename)
|
||||
out, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
jsonError(w, "Failed to save file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
written, err := io.Copy(out, file)
|
||||
if err != nil {
|
||||
os.Remove(destPath)
|
||||
jsonError(w, "Failed to save file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if written > maxFileBytes {
|
||||
os.Remove(destPath)
|
||||
jsonError(w, "File too large (max 5 MB)", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
|
||||
fileURL := "/uploads/" + filename
|
||||
displayName := sanitizeDisplayFilename(header.Filename)
|
||||
if displayName == "" {
|
||||
displayName = filename
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"url": fileURL,
|
||||
"filename": displayName,
|
||||
"markdown": "[" + displayName + "](" + fileURL + ")",
|
||||
})
|
||||
}
|
||||
|
||||
// sanitizeDisplayFilename strips path components, control chars, and
|
||||
// markdown-significant characters from a user-supplied filename so that it
|
||||
// can be safely embedded in a markdown link.
|
||||
func sanitizeDisplayFilename(name string) string {
|
||||
name = filepath.Base(name)
|
||||
var b strings.Builder
|
||||
for _, r := range name {
|
||||
if r < 32 || r == 127 {
|
||||
continue
|
||||
}
|
||||
switch r {
|
||||
case '[', ']', '(', ')', '\\', '`', '*', '<', '>', '"', '\'':
|
||||
continue
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
s := strings.TrimSpace(b.String())
|
||||
if len(s) > 100 {
|
||||
s = s[:100]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
var validPasteNameRe = strings.NewReplacer() // placeholder — use inline check below
|
||||
func validPasteName(name string) bool {
|
||||
if len(name) == 0 || len(name) > 64 {
|
||||
|
||||
@@ -68,8 +68,9 @@ func (s *Server) Start() error {
|
||||
staticSub, _ := fs.Sub(staticFS, "static")
|
||||
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub))))
|
||||
|
||||
// Uploaded images (public — images appear in public pastes)
|
||||
mux.Handle("GET /uploads/", http.StripPrefix("/uploads/", http.FileServer(http.Dir(s.cfg.Upload.Dir))))
|
||||
// Uploaded files (public — appear in public pastes). Non-image files are
|
||||
// served as attachments to prevent same-origin XSS via HTML/SVG/JS uploads.
|
||||
mux.HandleFunc("GET /uploads/", s.handleUploadsServe)
|
||||
|
||||
// Public routes
|
||||
mux.HandleFunc("GET /{$}", s.handleIndex)
|
||||
@@ -96,6 +97,7 @@ func (s *Server) Start() error {
|
||||
mux.HandleFunc("POST /admin/bin/delete/{id}", s.requireAuth(s.requireCSRF(s.handleAdminBinDelete)))
|
||||
mux.HandleFunc("GET /admin/bin/qr/{name}", s.requireAuth(s.handleBinQR))
|
||||
mux.HandleFunc("POST /admin/upload", s.requireAuth(s.handleUpload))
|
||||
mux.HandleFunc("POST /admin/upload-file", s.requireAuth(s.handleFileUpload))
|
||||
mux.HandleFunc("GET /admin/uploads", s.requireAuth(s.handleAdminUploads))
|
||||
mux.HandleFunc("POST /admin/uploads/delete/{filename}", s.requireAuth(s.requireCSRF(s.handleAdminUploadDelete)))
|
||||
mux.HandleFunc("POST /admin/uploads/resize/{filename}", s.requireAuth(s.handleAdminUploadResize))
|
||||
|
||||
@@ -80,8 +80,10 @@
|
||||
|
||||
<label>Content</label>
|
||||
<div class="upload-controls">
|
||||
<button type="button" id="upload-btn" class="outline secondary">Upload Image</button>
|
||||
<input type="file" id="file-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
|
||||
<button type="button" id="upload-img-btn" class="outline secondary">Upload Image</button>
|
||||
<button type="button" id="upload-file-btn" class="outline secondary">Upload File</button>
|
||||
<input type="file" id="img-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
|
||||
<input type="file" id="file-input" style="display:none">
|
||||
<small id="upload-status"></small>
|
||||
</div>
|
||||
{{if .Paste}}
|
||||
@@ -148,7 +150,9 @@
|
||||
|
||||
(function() {
|
||||
var textarea = document.querySelector('textarea[name="content"]');
|
||||
var uploadBtn = document.getElementById('upload-btn');
|
||||
var uploadImgBtn = document.getElementById('upload-img-btn');
|
||||
var uploadFileBtn = document.getElementById('upload-file-btn');
|
||||
var imgInput = document.getElementById('img-input');
|
||||
var fileInput = document.getElementById('file-input');
|
||||
var status = document.getElementById('upload-status');
|
||||
|
||||
@@ -157,26 +161,39 @@
|
||||
return match ? match[1] : '';
|
||||
}
|
||||
|
||||
function uploadFile(file) {
|
||||
if (!file || !file.type.startsWith('image/')) {
|
||||
status.textContent = 'Not an image file';
|
||||
return;
|
||||
}
|
||||
if (file.size > 50 * 1024 * 1024) {
|
||||
status.textContent = 'File too large (max 50 MB)';
|
||||
return;
|
||||
function setButtonsDisabled(v) {
|
||||
uploadImgBtn.disabled = v;
|
||||
uploadFileBtn.disabled = v;
|
||||
}
|
||||
|
||||
function doUpload(file, isImage) {
|
||||
if (isImage) {
|
||||
if (!file || !file.type.startsWith('image/')) {
|
||||
status.textContent = 'Not an image file';
|
||||
return;
|
||||
}
|
||||
if (file.size > 50 * 1024 * 1024) {
|
||||
status.textContent = 'File too large (max 50 MB)';
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
status.textContent = 'File too large (max 5 MB)';
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
status.textContent = 'Uploading\u2026';
|
||||
uploadBtn.disabled = true;
|
||||
setButtonsDisabled(true);
|
||||
var fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
var endpoint = isImage ? '/admin/upload' : '/admin/upload-file';
|
||||
|
||||
fetch('/admin/upload', { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
.then(function(res) { return res.json(); })
|
||||
.then(function(data) {
|
||||
uploadBtn.disabled = false;
|
||||
setButtonsDisabled(false);
|
||||
if (data.error) {
|
||||
status.textContent = 'Error: ' + data.error;
|
||||
return;
|
||||
@@ -186,7 +203,7 @@
|
||||
setTimeout(function() { status.textContent = ''; }, 3000);
|
||||
})
|
||||
.catch(function() {
|
||||
uploadBtn.disabled = false;
|
||||
setButtonsDisabled(false);
|
||||
status.textContent = 'Upload failed';
|
||||
});
|
||||
}
|
||||
@@ -201,9 +218,15 @@
|
||||
textarea.focus();
|
||||
}
|
||||
|
||||
uploadBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
uploadImgBtn.addEventListener('click', function() { imgInput.click(); });
|
||||
uploadFileBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
|
||||
imgInput.addEventListener('change', function() {
|
||||
if (imgInput.files.length > 0) doUpload(imgInput.files[0], true);
|
||||
imgInput.value = '';
|
||||
});
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (fileInput.files.length > 0) uploadFile(fileInput.files[0]);
|
||||
if (fileInput.files.length > 0) doUpload(fileInput.files[0], false);
|
||||
fileInput.value = '';
|
||||
});
|
||||
|
||||
@@ -212,7 +235,7 @@
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
if (items[i].type.indexOf('image') !== -1) {
|
||||
e.preventDefault();
|
||||
uploadFile(items[i].getAsFile());
|
||||
doUpload(items[i].getAsFile(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,11 +35,13 @@
|
||||
<div class="section-header">
|
||||
<hgroup>
|
||||
<h2>Uploads</h2>
|
||||
<p>{{len .Uploads}} images</p>
|
||||
<p>{{len .Uploads}} files</p>
|
||||
</hgroup>
|
||||
<div class="upload-controls">
|
||||
<button type="button" id="upload-btn" class="btn-sm">Upload Image</button>
|
||||
<input type="file" id="file-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
|
||||
<button type="button" id="upload-img-btn" class="btn-sm">Upload Image</button>
|
||||
<button type="button" id="upload-file-btn" class="btn-sm outline">Upload File</button>
|
||||
<input type="file" id="img-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
|
||||
<input type="file" id="file-input" style="display:none">
|
||||
<small id="upload-status"></small>
|
||||
</div>
|
||||
</div>
|
||||
@@ -58,16 +60,20 @@
|
||||
<tbody>
|
||||
{{range .Uploads}}
|
||||
<tr>
|
||||
<td><a href="{{.URL}}" target="_blank"><img src="{{.URL}}" style="max-width:72px;max-height:52px;object-fit:contain;border-radius:4px"></a></td>
|
||||
<td>
|
||||
{{if .IsImage}}<a href="{{.URL}}" target="_blank"><img src="{{.URL}}" style="max-width:72px;max-height:52px;object-fit:contain;border-radius:4px"></a>
|
||||
{{else}}<a href="{{.URL}}" target="_blank" style="font-size:1.5rem" title="Download file">📄</a>
|
||||
{{end}}
|
||||
</td>
|
||||
<td><code style="font-size:0.75rem">{{.Filename}}</code></td>
|
||||
<td id="size-{{.Filename}}">{{.SizeHuman}}</td>
|
||||
<td id="dim-{{.Filename}}">{{if .Width}}{{.Width}}×{{.Height}}{{else}}—{{end}}</td>
|
||||
<td>{{.ModTime.Format "2006-01-02 15:04"}}</td>
|
||||
<td>
|
||||
<div role="group">
|
||||
<button type="button" class="outline btn-sm" onclick="copyMarkdown('{{.Filename}}', this)">Copy</button>
|
||||
<button type="button" class="outline btn-sm" onclick="copyMarkdown('{{.Filename}}', {{.IsImage}}, this)">Copy</button>
|
||||
{{if .CanResize}}<button type="button" class="outline btn-sm" onclick="openResize('{{.Filename}}', {{.Width}}, {{.Height}})">Resize</button>{{end}}
|
||||
<form method="post" action="/admin/uploads/delete/{{.Filename}}" onsubmit="return confirm('Delete this image?')" style="margin:0">
|
||||
<form method="post" action="/admin/uploads/delete/{{.Filename}}" onsubmit="return confirm('Delete this file?')" style="margin:0">
|
||||
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
|
||||
<button type="submit" class="outline secondary btn-sm">Del</button>
|
||||
</form>
|
||||
@@ -78,8 +84,8 @@
|
||||
<tr>
|
||||
<td colspan="6">
|
||||
<div class="empty-state">
|
||||
<span class="empty-icon">🖼</span>
|
||||
<p>No uploads yet. Use the button above to upload an image.</p>
|
||||
<span class="empty-icon">📄</span>
|
||||
<p>No uploads yet. Use the buttons above to upload an image or file.</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -117,8 +123,9 @@
|
||||
return match ? match[1] : '';
|
||||
}
|
||||
|
||||
function copyMarkdown(filename, btn) {
|
||||
var md = '';
|
||||
function copyMarkdown(filename, isImage, btn) {
|
||||
var url = '/uploads/' + filename;
|
||||
var md = isImage ? '' : '[' + filename + '](' + url + ')';
|
||||
navigator.clipboard.writeText(md).then(function() {
|
||||
var orig = btn.textContent;
|
||||
btn.textContent = 'Copied!';
|
||||
@@ -168,35 +175,53 @@
|
||||
});
|
||||
});
|
||||
|
||||
// Upload button
|
||||
var uploadBtn = document.getElementById('upload-btn');
|
||||
// Upload buttons
|
||||
var uploadImgBtn = document.getElementById('upload-img-btn');
|
||||
var uploadFileBtn = document.getElementById('upload-file-btn');
|
||||
var imgInput = document.getElementById('img-input');
|
||||
var fileInput = document.getElementById('file-input');
|
||||
var uploadStatus = document.getElementById('upload-status');
|
||||
|
||||
uploadBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
uploadImgBtn.addEventListener('click', function() { imgInput.click(); });
|
||||
uploadFileBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
|
||||
imgInput.addEventListener('change', function() {
|
||||
if (imgInput.files.length > 0) doUpload(imgInput.files[0], true);
|
||||
imgInput.value = '';
|
||||
});
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (fileInput.files.length > 0) doUpload(fileInput.files[0]);
|
||||
if (fileInput.files.length > 0) doUpload(fileInput.files[0], false);
|
||||
fileInput.value = '';
|
||||
});
|
||||
|
||||
function doUpload(file) {
|
||||
if (!file || !file.type.startsWith('image/')) {
|
||||
uploadStatus.textContent = 'Not an image file';
|
||||
return;
|
||||
}
|
||||
if (file.size > 50 * 1024 * 1024) {
|
||||
uploadStatus.textContent = 'File too large (max 50 MB)';
|
||||
return;
|
||||
function doUpload(file, isImage) {
|
||||
if (isImage) {
|
||||
if (!file || !file.type.startsWith('image/')) {
|
||||
uploadStatus.textContent = 'Not an image file';
|
||||
return;
|
||||
}
|
||||
if (file.size > 50 * 1024 * 1024) {
|
||||
uploadStatus.textContent = 'File too large (max 50 MB)';
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
uploadStatus.textContent = 'File too large (max 5 MB)';
|
||||
return;
|
||||
}
|
||||
}
|
||||
uploadStatus.textContent = 'Uploading\u2026';
|
||||
uploadBtn.disabled = true;
|
||||
uploadImgBtn.disabled = true;
|
||||
uploadFileBtn.disabled = true;
|
||||
var fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
fetch('/admin/upload', { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
var endpoint = isImage ? '/admin/upload' : '/admin/upload-file';
|
||||
fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
uploadBtn.disabled = false;
|
||||
uploadImgBtn.disabled = false;
|
||||
uploadFileBtn.disabled = false;
|
||||
if (data.error) {
|
||||
uploadStatus.textContent = 'Error: ' + data.error;
|
||||
} else {
|
||||
@@ -204,7 +229,8 @@
|
||||
}
|
||||
})
|
||||
.catch(function() {
|
||||
uploadBtn.disabled = false;
|
||||
uploadImgBtn.disabled = false;
|
||||
uploadFileBtn.disabled = false;
|
||||
uploadStatus.textContent = 'Upload failed';
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user