Compare commits

..

36 Commits
v1.2.0 ... main

Author SHA1 Message Date
6c301cff0c fix!: bug where it was possible to send text unauthenticated 2024-11-02 01:34:52 -03:00
b73c06f1ab docs: update on what SHOULD_AUTH actually does 2024-10-31 10:17:23 -03:00
0668e42ea8 style: br on a newline 2024-10-31 10:13:58 -03:00
f2e38fda23 feat: change uploaded filename to uppercase 2024-10-31 10:08:56 -03:00
ae81ead712 feat: add audio displaying 2024-10-29 19:28:30 -03:00
9262f436b6 fix: logic on naming url with secret 2024-10-29 19:21:23 -03:00
343af57742 docs: document -Fsecret 2024-10-29 17:52:38 -03:00
e216e2a1b5 feat: add longer url if "secret" field is present 2024-10-29 17:51:27 -03:00
6a2bf1ea4a feat: add Location header to response 2024-10-21 12:01:32 -03:00
fae72778d9 docs: fix indentation on code blocks 2024-10-21 11:27:27 -03:00
4190f15a50 docs: add fast setup instructions 2024-10-18 11:38:33 -03:00
5c951b3a6d build: remove unecessary files in final image
These aren't needed anymore because we started embedding `static` and
`templates` directly into the binary, so that makes it easier to:

1. Distribute
2. Setup
3. Run
2024-10-18 11:26:43 -03:00
ecb147533a feat: embed UI assets into binary for easier distributing 2024-10-18 11:18:35 -03:00
0b3f167fce build!: fix error that would make an initial setup not work properly 2024-10-17 19:18:28 -03:00
766efc53c3 ops: comment out replacing templates
this can cause issues since if the template isnt found then it blows up
2024-10-17 19:00:33 -03:00
ddfc788ac5 docs: add setup instructions 2024-10-17 18:56:09 -03:00
e753301e33 chore: remove duplicated features
some mistake on my end while rebasing
2024-10-17 18:48:08 -03:00
37f12ad067 fix: make files cover all space available 2024-10-17 18:22:16 -03:00
c3424c1bb3 refactor: set values on Application creation 2024-10-17 15:26:13 -03:00
a36cec5cb1 feat: add support for fish scripts 2024-10-17 13:08:29 -03:00
35b1b183b2 docs: add features to readme 2024-10-17 13:07:49 -03:00
d6b7dcc74e docs: add tutorial for jwt tokens 2024-10-17 13:06:12 -03:00
ed2c0e7ef9 feat: add tokens for authentication 2024-10-17 10:52:33 -03:00
7ed16a5397 feat: redirect to another link if file is not supported 2024-10-16 23:34:08 -03:00
18bc590525 docs: add syntax highlighting goal completed 2024-10-16 23:27:02 -03:00
eda09669f8 feat: make /last also use new template 2024-10-16 23:20:14 -03:00
c32a459147 docs: add another goal completed 2024-10-16 22:42:46 -03:00
6c87fe724c feat: add syntax highlighting to files using highlightjs 2024-10-16 22:41:59 -03:00
8b0300c738 feat: add timeUploaded to /tree 2024-10-16 22:41:59 -03:00
8ec85fdc1b feat: add uploadedTime to index page 2024-10-16 22:41:59 -03:00
4384cfaa35 feat: add text support for custom page 2024-10-16 22:41:59 -03:00
6d9dd1aa65 feat: add custom page handling for most media format
I haven't gotten text to work yet
2024-10-16 22:41:59 -03:00
ff566a2ff5 wip: add handling for extensions 2024-10-16 22:41:59 -03:00
c64c63d333 feat: remove download button and make header more useful 2024-10-16 22:41:59 -03:00
ebe2c461f5 wip: add custom template for displaying files 2024-10-16 22:41:59 -03:00
52fa208aab docs: change from my domain to standard localhost 2024-10-16 11:14:51 -03:00
13 changed files with 636 additions and 183 deletions

View File

@ -3,7 +3,10 @@ FROM golang:1.23 AS builder
WORKDIR /app WORKDIR /app
COPY go.mod go.sum ./ COPY go.mod go.sum ./
COPY go.mod ./
# this is needed because we embed these files into the binary
COPY static/ ./static/
COPY templates/ ./templates
RUN go mod download RUN go mod download

View File

@ -1,22 +1,45 @@
# abyss # abyss
abyss is a basic (mostly) single user http server made for uploading files (logs, images) and then sharing them to the internet abyss is a basic and mostly single user http server written in go made for uploading files (logs, images) and then sharing them to the internet
note: this is a project made for learning purposes, you should use other more mature projects if running in production. probably. <figure>
<img src="https://github.com/user-attachments/assets/eae42368-d8b5-4c42-ac8a-0e1486fcd0d4" alt="homepage"/>
<figcaption>this is abyss' default home page<figcaption/>
</figure>
## table of contents ## table of contents
- [features](#features)
- [running abyss](#running) - [running abyss](#running)
- [installing with docker](#docker) - [installing with docker](#docker)
- [installing manually](#manual) - [installing manually](#directly)
- [uploading files](#uploading) - [uploading files](#uploading)
- [theming](#theming) - [theming](#theming)
- [docs](#docs) - [docs](#docs)
- [todo list](#todo) - [todo list](#todo)
- [more pictures](#pictures)
## running: ## features
- run `./generate_config.sh` to setup the necessary environment variables - **file uploads**: supports uploading various file types, including images, videos, and documents.
- **flexible media display**: automatically renders uploaded files on a webpage based on their type (images, pdfs, videos, or plain text).
- **easily customizable interface**: allows for easy modification of color schemes and layout to suit specific design needs.
- **syntax highlighting for code**: syntax highlighting available by default for code files, with support for multiple programming languages. (can be tweaked/changed and even removed)
- **security considerations**: as it is single user, it's mostly secure but there are still some edges to sharpen
- **easy and fast setup**: assets files are baked into the binary, so setting it up is as easy as compiling/grabbing a binary from gh actions and running it!
## running
#### (recommended) setting it up
- clone the repository and cd into it:
```bash
git clone https://github.com/jabuxas/abyss.git --depth 1 && cd abyss
```
- then run `./generate_config.sh` to setup the necessary environment variables
- after that, you can use either docker or run it directly
### docker ### docker
@ -28,24 +51,35 @@ docker compose up -d # might be docker-compose depending on distro
- you can optionally use the [docker image](https://git.jabuxas.xyz/jabuxas/-/packages/container/abyss/latest) directly and set it up how you want - you can optionally use the [docker image](https://git.jabuxas.xyz/jabuxas/-/packages/container/abyss/latest) directly and set it up how you want
### manual ### directly
- to run it manually, build it with `go build -o abyss` and run: - to run it manually, build it with `go build -o abyss` or grab a binary from github actions and run:
```bash ```bash
./abyss ./abyss
``` ```
- you will need to either:
- create a `.env` file in `$(pwd)` and set up the necessary variables as in [docs](#docs)
- run it with the variables prepended: `AUTH_USERNAME=admin AUTH_PASSWORD=admin ./abyss` (example)
- and then (hopefully) create a service that does that automatically and runs `abyss`
## uploading ## uploading
#### with curl #### with curl
- to upload your files with curl: - you can upload both with the main key and with jwt tokens
##### main key
- to upload your files with main key:
```bash ```bash
curl -F "file=@/path/to/file" -H "X-Auth: "$(cat /path/to/.key) http://localhost:3235/ curl -F "file=@/path/to/file" -H "X-Auth: "$(cat /path/to/.key) http://localhost:3235/
``` ```
- it is also possible to add a `-Fsecret=` to your POST to make filenames bigger and harder to guess.
- you should probably create an `alias` or a `function` to do this automatically for you. - you should probably create an `alias` or a `function` to do this automatically for you.
<details> <details>
<summary>click for an example for bash/zsh:</summary> <summary>click for an example for bash/zsh:</summary>
@ -64,7 +98,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 +122,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"
@ -98,6 +132,22 @@ end
</details> </details>
##### with jwt tokens
- you first need to generate them:
```bash
curl -u admin http://localhost:3235/token # you can also access the url in the browser directly
```
- the user will be the value of `$AUTH_USERNAME` and password the value of `$AUTH_PASSWORD`
- then you use the token in place of the main key:
```bash
curl -F"file=@/path/to/file.jpg" -H "X-Auth: your-token" http://localhost:3235/
```
#### through the browser #### through the browser
- you can only upload text through the browser, to do so, simply write text in the form in the default webpage and click upload. - you can only upload text through the browser, to do so, simply write text in the form in the default webpage and click upload.
@ -118,15 +168,29 @@ end
- `UPLOAD_KEY`: this is key checked when uploading files. if the key doesn't match with server's one, then it refuses uploading. - `UPLOAD_KEY`: this is key checked when uploading files. if the key doesn't match with server's one, then it refuses uploading.
- `ABYSS_FILEDIR`: this points to the directory where abyss will save the uploads to. defaults to `./files` - `ABYSS_FILEDIR`: this points to the directory where abyss will save the uploads to. defaults to `./files`
- `ABYSS_PORT`: this is the port the server will run on. safe to leave empty. defaults to 3235 - `ABYSS_PORT`: this is the port the server will run on. safe to leave empty. defaults to 3235
- `SHOULD_AUTH`: if it is `yes`, then to upload text through the browser you will need authentication (same auth as `/tree`), any value other than that and upload is auth-less - `SHOULD_AUTH`: if it is `yes`, then to upload text you will need authentication (same auth as `/tree`), any value other than that and upload is authless
## todo: ## todo:
- [x] add upload of logs funcionality (like 0x0.st) - [x] add upload of logs funcionality (like 0x0.st)
- [x] add docker easy setup - [x] add docker easy setup
- ~~add db for tracking of file names~~ (dont need that)
- [x] add file browser (like file://) - [x] add file browser (like file://)
- [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
- [ ] add rate limits - [x] custom file displaying!!
- [x] syntax highlighting
- [ ] create example services (openrc/systemd)
- [ ] distribute it in some distros
## pictures
<figure>
<img src="https://github.com/user-attachments/assets/32ce9b3a-8c0f-4bb5-bdcf-3a602e0c81e6"/>
<figcaption>this is abyss' default directory list<figcaption/>
</figure>
<figure>
<img src="https://github.com/user-attachments/assets/e842e481-13ee-464b-be43-5ba0f4bb43ec"/>
<figcaption>this is abyss' default file presentation<figcaption/>
</figure>

View File

@ -11,7 +11,25 @@ import (
) )
func main() { func main() {
app := new(Application) err := godotenv.Load()
if err != nil {
slog.Warn("no .env file detected, getting env from running process")
}
app := &Application{
auth: struct {
username string
password string
}{
username: os.Getenv("AUTH_USERNAME"),
password: os.Getenv("AUTH_PASSWORD"),
},
url: os.Getenv("ABYSS_URL"),
key: os.Getenv("UPLOAD_KEY"),
filesDir: os.Getenv("ABYSS_FILEDIR"),
port: os.Getenv("ABYSS_PORT"),
authUpload: os.Getenv("SHOULD_AUTH"),
}
parseEnv(app) parseEnv(app)
@ -35,20 +53,6 @@ func main() {
} }
func parseEnv(app *Application) { func parseEnv(app *Application) {
err := godotenv.Load()
if err != nil {
slog.Warn("no .env file detected, getting env from running process")
}
app.auth.username = os.Getenv("AUTH_USERNAME")
app.auth.password = os.Getenv("AUTH_PASSWORD")
app.url = os.Getenv("ABYSS_URL")
app.key = os.Getenv("UPLOAD_KEY")
app.filesDir = os.Getenv("ABYSS_FILEDIR")
app.port = os.Getenv("ABYSS_PORT")
app.authText = os.Getenv("SHOULD_AUTH")
if app.auth.username == "" { if app.auth.username == "" {
log.Fatal("basic auth username must be provided") log.Fatal("basic auth username must be provided")
} }
@ -87,17 +91,13 @@ 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)
if app.authText == "yes" { mux.HandleFunc("/token", BasicAuth(app.createTokenHandler, app))
mux.HandleFunc("/upload", app.basicAuth(app.uploadHandler))
slog.Warn("text uploading through the browser will be restricted") mux.HandleFunc("/files/", app.fileHandler)
} else {
mux.HandleFunc("/upload", app.uploadHandler)
slog.Warn("text uploading through the browser will NOT be restricted")
}
} }

View File

@ -5,8 +5,8 @@ services:
- "3235:3235" - "3235:3235"
volumes: volumes:
- ./files:/files - ./files:/files
- ./dev/home:/static:ro # - ./dev/home:/static:ro
- ./dev/templates:/templates:ro # - ./dev/templates:/templates:ro
env_file: env_file:
- .env - .env
tmpfs: tmpfs:

75
file_display.go Normal file
View File

@ -0,0 +1,75 @@
package main
import (
"embed"
"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",
".mp3": "audio", ".aac": "audio", ".wav": "audio", ".flac": "audio", ".ogg": "audio",
".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", ".el": "text", ".fish": "text",
}
//go:embed templates/files.html
var filesTemplate embed.FS
func DisplayFile(app *Application, file string, w http.ResponseWriter) {
var tmpl *template.Template
if _, err := os.Stat("./templates/dirlist.html"); err == nil {
tmpl = template.Must(template.ParseFiles("templates/files.html"))
} else {
tmpl = template.Must(template.ParseFS(filesTemplate, "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 "unknown"
}

View File

@ -43,7 +43,7 @@ AUTH_USERNAME=$AUTH_USERNAME
# This is the password of the user for accessing /tree # This is the password of the user for accessing /tree
AUTH_PASSWORD=$AUTH_PASSWORD AUTH_PASSWORD=$AUTH_PASSWORD
# This is whether you need a password to upload text through the browser # This is whether you need a password to upload text (through browser or curl)
SHOULD_AUTH=$SHOULD_AUTH SHOULD_AUTH=$SHOULD_AUTH
# This is the key needed to make uploads. Include it as X-Auth in curl. # This is the key needed to make uploads. Include it as X-Auth in curl.

2
go.mod
View File

@ -3,3 +3,5 @@ module github.com/jabuxas/abyss
go 1.22.6 go 1.22.6
require github.com/joho/godotenv v1.5.1 require github.com/joho/godotenv v1.5.1
require github.com/golang-jwt/jwt/v5 v5.2.1 // indirect

2
go.sum
View File

@ -1,2 +1,4 @@
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=

View File

@ -1,16 +1,19 @@
package main package main
import ( import (
"crypto/sha256" "embed"
"crypto/subtle"
"fmt" "fmt"
"html/template" "html/template"
"io" "io"
"io/fs"
"log/slog" "log/slog"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time"
"github.com/golang-jwt/jwt/v5"
) )
type Application struct { type Application struct {
@ -22,21 +25,15 @@ type Application struct {
key string key string
filesDir string filesDir string
port string port string
authText string authUpload string
lastUploadedFile string lastUploadedFile string
} }
type FileInfo struct { //go:embed static/**
Name string var static embed.FS
Path string
Size int64
FormattedSize string
}
type TemplateData struct { //go:embed templates/dirlist.html
Files []FileInfo var treeTemplate embed.FS
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,10 +58,19 @@ 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"),
}) })
} }
tmpl := template.Must(template.ParseFiles("templates/dirlist.html")) var tmpl *template.Template
if _, err := os.Stat("./templates/dirlist.html"); err == nil {
tmpl = template.Must(template.ParseFiles("templates/dirlist.html"))
} else {
tmpl = template.Must(template.ParseFS(treeTemplate, "templates/dirlist.html"))
}
templateData := TemplateData{ templateData := TemplateData{
Files: fileInfos, Files: fileInfos,
URL: app.url, URL: app.url,
@ -74,7 +80,27 @@ 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 _, err := os.Stat(app.filesDir); err != nil {
if err := os.Mkdir(app.filesDir, 0750); err != nil {
http.Error(w, "Error creating storage directory", http.StatusInternalServerError)
}
}
if r.Method == http.MethodPost { if r.Method == http.MethodPost {
app.uploadHandler(w, r) app.uploadHandler(w, r)
return return
@ -89,42 +115,16 @@ 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
} }
if _, err := os.Stat("./static"); err == nil {
http.StripPrefix("/", http.FileServer(http.Dir("./static"))).ServeHTTP(w, r) http.StripPrefix("/", http.FileServer(http.Dir("./static"))).ServeHTTP(w, r)
} else {
fs, _ := fs.Sub(static, "static")
http.StripPrefix("/", http.FileServer(http.FS(fs))).ServeHTTP(w, r)
}
} }
func (app *Application) lastUploadedHandler(w http.ResponseWriter, r *http.Request) { func (app *Application) lastUploadedHandler(w http.ResponseWriter, r *http.Request) {
@ -132,17 +132,16 @@ func (app *Application) lastUploadedHandler(w http.ResponseWriter, r *http.Reque
http.Error(w, "No new files uploaded yet", http.StatusNotFound) http.Error(w, "No new files uploaded yet", http.StatusNotFound)
return return
} }
http.ServeFile(w, r, app.lastUploadedFile) DisplayFile(app, "/"+app.lastUploadedFile, w)
} }
func (app *Application) uploadHandler(w http.ResponseWriter, r *http.Request) { func (app *Application) uploadHandler(w http.ResponseWriter, r *http.Request) {
if _, err := os.Stat(app.filesDir); err != nil {
if err := os.Mkdir(app.filesDir, 0750); err != nil {
http.Error(w, "Error creating storage directory", http.StatusInternalServerError)
}
}
if contentType := r.Header.Get("Content-Type"); contentType == "application/x-www-form-urlencoded" { if contentType := r.Header.Get("Content-Type"); contentType == "application/x-www-form-urlencoded" {
if app.authUpload == "yes" {
BasicAuth(app.formHandler, app)(w, r)
} else {
app.formHandler(w, r) app.formHandler(w, r)
}
} else if strings.Split(contentType, ";")[0] == "multipart/form-data" { } else if strings.Split(contentType, ";")[0] == "multipart/form-data" {
app.curlHandler(w, r) app.curlHandler(w, r)
} else { } else {
@ -150,33 +149,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")
@ -190,7 +162,11 @@ func (app *Application) formHandler(w http.ResponseWriter, r *http.Request) {
} }
defer file.Close() defer file.Close()
filename := app.publicURL(file, ".txt") full := true
if len(r.Form["secret"]) == 0 {
full = false
}
filename := app.publicURL(file, ".txt", full)
// reopening file because hash consumes it // reopening file because hash consumes it
file, err = os.Open("/tmp/file.txt") file, err = os.Open("/tmp/file.txt")
@ -204,7 +180,7 @@ func (app *Application) formHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Error parsing file: %s", err.Error()) fmt.Fprintf(w, "Error parsing file: %s", err.Error())
} }
fmt.Fprintf(w, "%s", fmt.Sprintf("http://%s/%s\n", app.url, filename)) ResponseURLHandler(w, app.url, filename)
} }
func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) { func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) {
@ -226,7 +202,11 @@ func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) {
} }
defer file.Close() defer file.Close()
filename := app.publicURL(file, filepath.Ext(handler.Filename)) full := true
if len(r.Form["secret"]) == 0 {
full = false
}
filename := app.publicURL(file, filepath.Ext(handler.Filename), full)
// reopen the file for copying, as the hash process consumed the file reader // reopen the file for copying, as the hash process consumed the file reader
file, _, err = r.FormFile("file") file, _, err = r.FormFile("file")
@ -236,16 +216,15 @@ func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) {
} }
defer file.Close() defer file.Close()
err = SaveFile(app.lastUploadedFile, file) if err = SaveFile(app.lastUploadedFile, file); err != nil {
if err != nil {
fmt.Fprintf(w, "Error parsing file: %s", err.Error()) fmt.Fprintf(w, "Error parsing file: %s", err.Error())
} }
fmt.Fprintf(w, "%s", fmt.Sprintf("http://%s/%s\n", app.url, filename)) ResponseURLHandler(w, app.url, filename)
} }
func (app *Application) publicURL(file io.Reader, extension string) string { func (app *Application) publicURL(file io.Reader, extension string, full bool) string {
filename, _ := HashFile(file, extension) filename, _ := HashFile(file, extension, full)
filepath := filepath.Join(app.filesDir, filename) filepath := filepath.Join(app.filesDir, filename)
@ -253,3 +232,17 @@ func (app *Application) publicURL(file io.Reader, extension string) string {
return filename return filename
} }
func (app *Application) createTokenHandler(w http.ResponseWriter, r *http.Request) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().Add(time.Hour * 2).Unix(),
})
tokenString, err := token.SignedString([]byte(app.key))
if err != nil {
http.Error(w, "Error generating token", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s", tokenString)
}

View File

@ -2,15 +2,59 @@ package main
import ( import (
"crypto/md5" "crypto/md5"
"crypto/sha256"
"crypto/subtle"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"os" "os"
"strings"
"github.com/golang-jwt/jwt/v5"
) )
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 receivedKey := r.Header.Get("X-Auth")
if receivedKey == key {
return true
} else if err := validateToken(receivedKey, key); err == nil {
return true
}
return false
}
func validateToken(tokenString, key string) error {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(key), nil
})
if err != nil {
return err
}
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return nil
} else {
return fmt.Errorf("invalid token")
}
} }
func FormatFileSize(size int64) string { func FormatFileSize(size int64) string {
@ -24,17 +68,19 @@ func FormatFileSize(size int64) string {
return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024)) return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024))
} }
func HashFile(file io.Reader, extension string) (string, error) { func HashFile(file io.Reader, extension string, full bool) (string, error) {
hasher := md5.New() hasher := md5.New()
if _, err := io.Copy(hasher, file); err != nil { if _, err := io.Copy(hasher, file); err != nil {
return "", err return "", err
} }
sha1Hash := hex.EncodeToString(hasher.Sum(nil))[:8] sha1Hash := strings.ToUpper(hex.EncodeToString(hasher.Sum(nil)))
filename := fmt.Sprintf("%s%s", sha1Hash, extension) filename := fmt.Sprintf("%s%s", sha1Hash, extension)
if full {
return filename, nil return filename, nil
} else {
return fmt.Sprintf("%s%s", sha1Hash[:5], extension), nil
}
} }
func SaveFile(name string, file io.Reader) error { func SaveFile(name string, file io.Reader) error {
@ -49,3 +95,40 @@ 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)
})
}
func ResponseURLHandler(w http.ResponseWriter, url, filename string) {
pasteURL := fmt.Sprintf("http://%s/%s\n", url, filename)
w.Header().Set("Location", pasteURL)
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "%s", pasteURL)
}

View File

@ -20,8 +20,9 @@
</a> </a>
</div> </div>
<form action="/upload" method="POST"> <form action="/" method="POST">
<textarea name="content" placeholder="Enter your content here..."></textarea><br /> <textarea name="content" placeholder="Enter your content here..."></textarea>
<br />
<button type="submit">upload</button> <button type="submit">upload</button>
</form> </form>

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}}

228
templates/files.html Normal file
View File

@ -0,0 +1,228 @@
<!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: 10px;
}
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 {
flex: 1;
width: 100%;
height: 100%;
white-space: pre;
font-family: monospace;
font-size: 1rem;
background-color: #2e2e2e;
padding: 10px;
border-radius: 8px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #686868 #2e2e2e;
box-sizing: border-box;
}
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;
}
a {
color: #0288d1;
text-decoration: none;
}
</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>
{{else if eq .Type "audio"}}
<audio controls src="{{.Name}}"><audio />
{{else}}
<p>
Couldn't detect file from extension, visit
<a href="http://{{.Path}}">this link</a> to see/download your file.
</p>
{{end}}
</div>
<footer>file uploaded in {{.TimeUploaded}}</footer>
</body>
</html>