Compare commits

...

10 Commits

7 changed files with 346 additions and 77 deletions

View File

@ -64,7 +64,7 @@ pst() {
return 1 return 1
fi fi
curl -F "file=@$file" -H "X-Auth: $(cat ~/.key)" https://paste.jabuxas.xyz curl -F "file=@$file" -H "X-Auth: $(cat ~/.key)" http://localhost:3235
if [[ -p /dev/stdin ]]; then if [[ -p /dev/stdin ]]; then
rm "$file" rm "$file"
@ -88,7 +88,7 @@ function pst
set file "$argv[1]" set file "$argv[1]"
end end
curl -F "file=@$file" -H "X-Auth: $(cat ~/.key)" https://paste.jabuxas.xyz curl -F "file=@$file" -H "X-Auth: $(cat ~/.key)" http://localhost:3235
if command test -p /dev/stdin if command test -p /dev/stdin
rm "$file" rm "$file"
@ -129,4 +129,5 @@ end
- [x] add file extension in its name - [x] add file extension in its name
- [x] login prompt when accessing /tree - [x] login prompt when accessing /tree
- [x] home page - [x] home page
- [x] custom file displaying!!
- [ ] add rate limits - [ ] add rate limits

View File

@ -87,14 +87,16 @@ func setupHandlers(mux *http.ServeMux, app *Application) {
"/tree/", "/tree/",
http.StripPrefix( http.StripPrefix(
"/tree", "/tree",
app.basicAuth(app.fileListingHandler), BasicAuth(app.fileListingHandler, app),
), ),
) )
mux.HandleFunc("/last", app.lastUploadedHandler) mux.HandleFunc("/last", app.lastUploadedHandler)
mux.HandleFunc("/files/", app.fileHandler)
if app.authText == "yes" { if app.authText == "yes" {
mux.HandleFunc("/upload", app.basicAuth(app.uploadHandler)) mux.HandleFunc("/upload", BasicAuth(app.uploadHandler, app))
slog.Warn("text uploading through the browser will be restricted") slog.Warn("text uploading through the browser will be restricted")
} else { } else {
mux.HandleFunc("/upload", app.uploadHandler) mux.HandleFunc("/upload", app.uploadHandler)

63
file_display.go Normal file
View File

@ -0,0 +1,63 @@
package main
import (
"html/template"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
)
var extensions = map[string]string{
".mp4": "video", ".mkv": "video", ".webm": "video",
".pdf": "pdf",
".png": "image", ".jpg": "image", ".jpeg": "image", ".webp": "image",
".sh": "text", ".bash": "text", ".zsh": "text",
".bat": "text", ".cmd": "text", ".ps1": "text",
".ini": "text", ".cfg": "text", ".conf": "text",
".toml": "text", ".yml": "text", ".yaml": "text",
".c": "text", ".cpp": "text", ".h": "text",
".go": "text", ".py": "text", ".js": "text",
".ts": "text", ".html": "text", ".htm": "text",
".xml": "text", ".css": "text", ".java": "text",
".rs": "text", ".rb": "text", ".php": "text",
".pl": "text", ".sql": "text", ".md": "text",
".log": "text", ".txt": "text", ".csv": "text",
".json": "text", ".env": "text", ".sum": "text",
".gitignore": "text", ".dockerfile": "text", ".Makefile": "text",
".rst": "text",
}
func DisplayFile(app *Application, file string, w http.ResponseWriter) {
tmpl := template.Must(template.ParseFiles("templates/files.html"))
fileStat, _ := os.Stat("." + file)
fileContent, _ := os.ReadFile("." + file)
fileInfo := FileInfo{
Name: file,
Path: filepath.Join(app.url, file),
Type: getType(file),
Content: string(fileContent),
TimeUploaded: fileStat.ModTime().
UTC().
Format("2006-01-02 15:04:05 UTC"),
}
if err := tmpl.Execute(w, fileInfo); err != nil {
slog.Warn(err.Error())
}
}
func getType(file string) string {
extension := strings.ToLower(filepath.Ext(file))
if fileType, exists := extensions[extension]; exists {
return fileType
}
return "text"
}

View File

@ -1,8 +1,6 @@
package main package main
import ( import (
"crypto/sha256"
"crypto/subtle"
"fmt" "fmt"
"html/template" "html/template"
"io" "io"
@ -26,18 +24,6 @@ type Application struct {
lastUploadedFile string lastUploadedFile string
} }
type FileInfo struct {
Name string
Path string
Size int64
FormattedSize string
}
type TemplateData struct {
Files []FileInfo
URL string
}
func (app *Application) fileListingHandler(w http.ResponseWriter, r *http.Request) { func (app *Application) fileListingHandler(w http.ResponseWriter, r *http.Request) {
dir := app.filesDir + r.URL.Path dir := app.filesDir + r.URL.Path
@ -61,6 +47,9 @@ func (app *Application) fileListingHandler(w http.ResponseWriter, r *http.Reques
Path: filepath.Join(r.URL.Path, file.Name()), Path: filepath.Join(r.URL.Path, file.Name()),
Size: info.Size(), Size: info.Size(),
FormattedSize: FormatFileSize(info.Size()), FormattedSize: FormatFileSize(info.Size()),
TimeUploaded: info.ModTime().
UTC().
Format("2006-01-02 15:04:05 UTC"),
}) })
} }
@ -74,6 +63,20 @@ func (app *Application) fileListingHandler(w http.ResponseWriter, r *http.Reques
} }
} }
func (app *Application) fileHandler(w http.ResponseWriter, r *http.Request) {
path := fmt.Sprintf(".%s", filepath.Clean(r.URL.Path))
if !filepath.IsLocal(path) {
http.Error(w, "Wrong url", http.StatusBadRequest)
return
}
if fileInfo, err := os.Stat(path); err == nil && !fileInfo.IsDir() {
http.ServeFile(w, r, path)
return
}
}
func (app *Application) indexHandler(w http.ResponseWriter, r *http.Request) { func (app *Application) indexHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost { if r.Method == http.MethodPost {
app.uploadHandler(w, r) app.uploadHandler(w, r)
@ -89,38 +92,7 @@ func (app *Application) indexHandler(w http.ResponseWriter, r *http.Request) {
} }
if fileInfo, err := os.Stat(path); err == nil && !fileInfo.IsDir() { if fileInfo, err := os.Stat(path); err == nil && !fileInfo.IsDir() {
ext := filepath.Ext(path) DisplayFile(app, "/"+path, w)
textExtensions := map[string]bool{
".sh": true, ".bash": true, ".zsh": true,
".bat": true, ".cmd": true, ".ps1": true,
".ini": true, ".cfg": true, ".conf": true,
".toml": true, ".yml": true, ".yaml": true,
".c": true, ".cpp": true, ".h": true,
".go": true, ".py": true, ".js": true,
".ts": true, ".html": true, ".htm": true,
".xml": true, ".css": true, ".java": true,
".rs": true, ".rb": true, ".php": true,
".pl": true, ".sql": true, ".md": true,
".log": true, ".txt": true, ".csv": true,
".json": true, ".env": true, ".sum": true,
".gitignore": true, ".dockerfile": true, ".Makefile": true,
".rst": true,
}
videoExtensions := map[string]bool{
".mkv": true,
}
if textExtensions[ext] {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
}
if videoExtensions[ext] {
w.Header().Set("Content-Type", "video/mp4")
}
http.ServeFile(w, r, path)
return return
} }
@ -150,33 +122,6 @@ func (app *Application) uploadHandler(w http.ResponseWriter, r *http.Request) {
} }
} }
func (app *Application) basicAuth(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
// hash password received
usernameHash := sha256.Sum256([]byte(username))
passwordHash := sha256.Sum256([]byte(password))
// hash our password
expectedUsernameHash := sha256.Sum256([]byte(app.auth.username))
expectedPasswordHash := sha256.Sum256([]byte(app.auth.password))
// compare hashes
usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1)
passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1)
if usernameMatch && passwordMatch {
next.ServeHTTP(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
}
func (app *Application) formHandler(w http.ResponseWriter, r *http.Request) { func (app *Application) formHandler(w http.ResponseWriter, r *http.Request) {
content := r.FormValue("content") content := r.FormValue("content")

View File

@ -2,6 +2,8 @@ package main
import ( import (
"crypto/md5" "crypto/md5"
"crypto/sha256"
"crypto/subtle"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io" "io"
@ -9,6 +11,21 @@ import (
"os" "os"
) )
type FileInfo struct {
Name string
Path string
Size int64
FormattedSize string
Type string
Content string
TimeUploaded string
}
type TemplateData struct {
Files []FileInfo
URL string
}
func CheckAuth(r *http.Request, key string) bool { func CheckAuth(r *http.Request, key string) bool {
return r.Header.Get("X-Auth") == key return r.Header.Get("X-Auth") == key
} }
@ -49,3 +66,30 @@ func SaveFile(name string, file io.Reader) error {
} }
return nil return nil
} }
func BasicAuth(next http.HandlerFunc, app *Application) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
// hash password received
usernameHash := sha256.Sum256([]byte(username))
passwordHash := sha256.Sum256([]byte(password))
// hash our password
expectedUsernameHash := sha256.Sum256([]byte(app.auth.username))
expectedPasswordHash := sha256.Sum256([]byte(app.auth.password))
// compare hashes
usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1)
passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1)
if usernameMatch && passwordMatch {
next.ServeHTTP(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
}

View File

@ -68,6 +68,7 @@
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th>Time Uploaded</th>
<th>Size</th> <th>Size</th>
</tr> </tr>
</thead> </thead>
@ -77,6 +78,7 @@
<td> <td>
<a href="{{.Path}}">{{.Name}}</a> <a href="{{.Path}}">{{.Name}}</a>
</td> </td>
<td>{{.TimeUploaded}}</td>
<td>{{.FormattedSize}}</td> <td>{{.FormattedSize}}</td>
</tr> </tr>
{{end}} {{end}}

212
templates/files.html Normal file
View File

@ -0,0 +1,212 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>abyss paste</title>
{{if eq .Type "text"}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>
window.onload = function () {
var allPre, i, j;
allPre = document.getElementsByTagName("pre");
for (i = 0, j = allPre.length; i < j; i++) {
hljs.highlightBlock(allPre[i]);
}
};
</script>
<style>
pre.hljs {
display: block;
overflow-x: auto;
padding: 1em;
}
.hljs {
color: #ffffff;
}
.hljs-comment {
color: #7d7d7d;
}
.hljs-punctuation,
.hljs-tag {
color: #dcdcdc;
}
.hljs-tag .hljs-attr,
.hljs-tag .hljs-name {
color: #f1f1f1;
}
.hljs-attribute,
.hljs-doctag,
.hljs-keyword,
.hljs-meta .hljs-keyword,
.hljs-name,
.hljs-selector-tag {
font-weight: bold;
color: #ff9d00;
}
.hljs-deletion,
.hljs-number,
.hljs-quote,
.hljs-selector-class,
.hljs-selector-id,
.hljs-string,
.hljs-template-tag,
.hljs-type {
color: #d19a66;
}
.hljs-section,
.hljs-title {
color: #61afef;
font-weight: bold;
}
.hljs-link,
.hljs-operator,
.hljs-regexp,
.hljs-selector-attr,
.hljs-selector-pseudo,
.hljs-symbol,
.hljs-template-variable,
.hljs-variable {
color: #c678dd;
}
.hljs-literal {
color: #dcaeea;
}
.hljs-addition,
.hljs-built_in,
.hljs-bullet,
.hljs-code {
color: #98c379;
}
.hljs-meta {
color: #56b6c2;
}
.hljs-meta .hljs-string {
color: #e5c07b;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}
</style>
{{end}}
<style>
body {
margin: 0;
padding: 0;
background-color: #1d1f21;
color: #c5c6c7;
font-family: "Arial", sans-serif;
display: flex;
flex-direction: column;
height: 100vh;
}
header,
footer {
background-color: #2e2e2e;
text-align: center;
font-size: 1rem;
font-weight: bold;
position: sticky;
top: 0;
z-index: 10;
padding: 10px;
}
.content {
flex-grow: 1;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
img,
video,
embed,
iframe {
max-width: 100%;
max-height: 100%;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
video {
background-color: #000;
}
.pdf-embed {
width: 100%;
height: 100%;
border: none;
}
pre {
white-space: pre;
font-family: monospace;
font-size: 1rem;
background-color: #2e2e2e;
padding: 20px;
border-radius: 8px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #686868 #2e2e2e;
}
pre::-webkit-scrollbar {
width: 12px;
}
pre::-webkit-scrollbar-track {
background: #2e2e2e;
border-radius: 10px;
}
pre::-webkit-scrollbar-thumb {
background-color: #686868;
border-radius: 10px;
border: 3px solid #2e2e2e;
}
</style>
</head>
<body>
<header>{{.Path}}</header>
<div class="content">
{{if eq .Type "text"}}
<pre>{{.Content}}</pre>
{{else if eq .Type "image"}}
<img src="{{.Name}}" alt="Image" />
{{else if eq .Type "pdf"}}
<embed src="{{.Name}}" type="application/pdf" class="pdf-embed" />
{{else if eq .Type "video"}}
<video controls>
<source src="{{.Name}}" type="video/mp4" />
Your browser does not support the video tag.
</video>
{{end}}
</div>
<footer>file uploaded in {{.TimeUploaded}}</footer>
</body>
</html>