Compare commits

..

No commits in common. "main" and "v1.1.0" have entirely different histories.
main ... v1.1.0

16 changed files with 243 additions and 860 deletions

View File

@ -1,28 +0,0 @@
name: Build and Push Docker Image Tag
on:
push:
tags:
- "*"
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Log in to Docker registry
run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login git.jabuxas.xyz -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
- name: Build and push Docker image
run: |
docker build -t git.jabuxas.xyz/jabuxas/abyss:${{ github.ref_name }} .
docker push git.jabuxas.xyz/jabuxas/abyss:${{ github.ref_name }}
- name: Log out of Docker registry
run: docker logout git.jabuxas.xyz

89
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,89 @@
# .github/workflows/release.yaml
on: release
name: Build Release
jobs:
release-linux-386:
name: release linux/386
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: compile and release
uses: ngs/go-release.action@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GOARCH: "386"
GOOS: linux
EXTRA_FILES: "README.md LICENSE"
release-linux-amd64:
name: release linux/amd64
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: compile and release
uses: ngs/go-release.action@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GOARCH: amd64
GOOS: linux
EXTRA_FILES: "README.md LICENSE"
release-linux-arm:
name: release linux/386
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: compile and release
uses: ngs/go-release.action@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GOARCH: "arm"
GOOS: linux
EXTRA_FILES: "README.md LICENSE"
release-linux-arm64:
name: release linux/amd64
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: compile and release
uses: ngs/go-release.action@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GOARCH: arm64
GOOS: linux
EXTRA_FILES: "README.md LICENSE"
release-darwin-amd64:
name: release darwin/amd64
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: compile and release
uses: ngs/go-release.action@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GOARCH: amd64
GOOS: darwin
EXTRA_FILES: "README.md LICENSE"
release-windows-386:
name: release windows/386
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: compile and release
uses: ngs/go-release.action@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GOARCH: "386"
GOOS: windows
EXTRA_FILES: "README.md LICENSE"
release-windows-amd64:
name: release windows/amd64
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: compile and release
uses: ngs/go-release.action@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GOARCH: amd64
GOOS: windows
EXTRA_FILES: "README.md LICENSE"

View File

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

165
README.md
View File

@ -1,196 +1,71 @@
# abyss
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
abyss is a basic single user http server made for uploading files (logs, images) and then sharing them to the internet
<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>
note: this is a project made for learning purposes, you should use other more mature projects if running in production. probably.
## table of contents
- [features](#features)
- [running abyss](#running)
- [installing with docker](#docker)
- [installing manually](#directly)
- [installing manually](#manual)
- [uploading files](#uploading)
- [theming](#theming)
- [docs](#docs)
- [todo list](#todo)
- [more pictures](#pictures)
## features
## running:
- **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
- run `./generate_config.sh` to setup the necessary environment variables
### docker
- to run with docker, you can use the `docker-compose.yml` file available in this repo. to do so, run:
```bash
docker compose up -d # might be docker-compose depending on distro
```
```bash
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
### directly
### manual
- to run it manually, build it with `go build -o abyss` or grab a binary from github actions and run:
- to run it manually, build it with `go build -o abyss` and run:
```bash
./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`
```bash
./abyss
```
## uploading
#### with curl
- then, simply 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
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.
<details>
<summary>click for an example for bash/zsh:</summary>
```bash
pst() {
local file
if [[ -p /dev/stdin ]]; then
file=$(mktemp)
cat > "$file"
elif [[ -n $1 ]]; then
file="$1"
else
echo "Usage: pst [file]"
return 1
fi
curl -F "file=@$file" -H "X-Auth: $(cat ~/.key)" http://localhost:3235/
if [[ -p /dev/stdin ]]; then
rm "$file"
fi
}
```
</details>
<details>
<summary>click for an example for fish shell:</summary>
```bash
function pst
set -l file
if command test -p /dev/stdin
set file "/tmp/tmp.txt"
cat > $file
else if test -n "$argv[1]"
set file "$argv[1]"
end
curl -F "file=@$file" -H "X-Auth: $(cat ~/.key)" http://localhost:3235/
if command test -p /dev/stdin
rm "$file"
end
end
```
</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
- you can only upload text through the browser, to do so, simply write text in the form in the default webpage and click upload.
- this upload can be restricted to need authentication or not, controlled by an environment variable.
```bash
curl -F "file=@/path/to/file" -H "X-Auth: "$(cat /path/to/.key) http://localhost:3235/
```
## theming
- there is an example homepage in `static/` you can edit directly, which the server will serve automatically
- if running with docker, it's also possible to override `/static` inside the container with your own page.
- otherwise you will need to clone this repository and edit `static/` and `templates/` manually, or recreate the structure.
- same thing with templates in `templates/`
- it is preferred to use `dev/` for that reason, since it is git-ignored and that way makes it easier if wanting to update regularly without making changes to the tree
## docs
- `ABYSS_URL`: this is used for the correct formatting of the response of `curl`.
- `AUTH_USERNAME | AUTH_PASSWORD`: this is used to access `/tree`, which shows all uploaded files
- `AUTH_USERNAME | AUTH_PASSWORD`: this is used to access `/tree/`, which shows all uploaded files
- `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_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 you will need authentication (same auth as `/tree`), any value other than that and upload is authless
## todo:
- [x] add upload of logs funcionality (like 0x0.st)
- [x] add docker easy setup
- ~~add db for tracking of file names~~ (dont need that)
- [x] add file browser (like file://)
- [x] add file extension in its name
- [x] login prompt when accessing /tree
- [x] home page
- [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>
- [ ] add rate limits

View File

@ -11,48 +11,20 @@ import (
)
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"),
}
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")
parseEnv(app)
mux := http.NewServeMux()
setupHandlers(mux, app)
srv := &http.Server{
Addr: app.port,
Handler: mux,
IdleTimeout: 10 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 60 * time.Second,
}
log.Printf("starting server on %s", srv.Addr)
if err := srv.ListenAndServe(); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
func parseEnv(app *Application) {
if app.auth.username == "" {
log.Fatal("basic auth username must be provided")
}
@ -82,22 +54,29 @@ func parseEnv(app *Application) {
slog.Warn("no root url detected, defaulting to localhost.")
app.url = "localhost" + app.port
}
}
func setupHandlers(mux *http.ServeMux, app *Application) {
mux := http.NewServeMux()
mux.HandleFunc("/", app.indexHandler)
mux.Handle(
"/tree/",
http.StripPrefix(
"/tree",
BasicAuth(app.fileListingHandler, app),
app.basicAuth(app.fileListingHandler),
),
)
mux.HandleFunc("/last", app.lastHandler)
mux.HandleFunc("/last", app.lastUploadedHandler)
srv := &http.Server{
Addr: app.port,
Handler: mux,
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 60 * time.Second,
}
mux.HandleFunc("/token", BasicAuth(app.createTokenHandler, app))
log.Printf("starting server on %s", srv.Addr)
mux.HandleFunc("/files/", app.fileHandler)
if err := srv.ListenAndServe(); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}

View File

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

View File

@ -1,75 +0,0 @@
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

@ -22,11 +22,6 @@ if [ -z $AUTH_PASSWORD ]; then
AUTH_PASSWORD="admin"
fi
read -p "Auth for upload form - should password be needed to upload text through the browser? [yes]: " -e SHOULD_AUTH
if [ -z $SHOULD_AUTH ]; then
SHOULD_AUTH="yes"
fi
cat << EOF > .env
# This is the full name of the final domain for the server. Example: paste.abyss.dev
ABYSS_URL=$ABYSS_URL
@ -43,9 +38,6 @@ AUTH_USERNAME=$AUTH_USERNAME
# This is the password of the user for accessing /tree
AUTH_PASSWORD=$AUTH_PASSWORD
# This is whether you need a password to upload text (through browser or curl)
SHOULD_AUTH=$SHOULD_AUTH
# This is the key needed to make uploads. Include it as X-Auth in curl.
# Tip: Save it somewhere and use it in curl with \$(cat /path/to/key)
UPLOAD_KEY=$UPLOAD_KEY

2
go.mod
View File

@ -3,5 +3,3 @@ module github.com/jabuxas/abyss
go 1.22.6
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,4 +1,2 @@
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/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=

View File

@ -1,19 +1,17 @@
package main
import (
"embed"
"crypto/md5"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"html/template"
"io"
"io/fs"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"text/template"
)
type Application struct {
@ -25,15 +23,20 @@ type Application struct {
key string
filesDir string
port string
authUpload string
lastUploadedFile string
}
//go:embed static/**
var static embed.FS
type FileInfo struct {
Name string
Path string
Size int64
FormattedSize string
}
//go:embed templates/dirlist.html
var treeTemplate embed.FS
type TemplateData struct {
Files []FileInfo
URL string
}
func (app *Application) fileListingHandler(w http.ResponseWriter, r *http.Request) {
dir := app.filesDir + r.URL.Path
@ -57,50 +60,32 @@ func (app *Application) fileListingHandler(w http.ResponseWriter, r *http.Reques
Name: file.Name(),
Path: filepath.Join(r.URL.Path, file.Name()),
Size: info.Size(),
FormattedSize: FormatFileSize(info.Size()),
TimeUploaded: info.ModTime().
UTC().
Format("2006-01-02 15:04:05 UTC"),
FormattedSize: formatFileSize(info.Size()),
})
}
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"))
}
tmpl := template.Must(template.ParseFiles("templates/dirlist.html"))
templateData := TemplateData{
Files: fileInfos,
URL: app.url,
}
if err := tmpl.Execute(w, templateData); err != nil {
slog.Warn(err.Error())
slog.Warn(error.Error(err))
}
}
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 formatFileSize(size int64) string {
if size < 1024 {
return fmt.Sprintf("%d B", size)
} else if size < 1024*1024 {
return fmt.Sprintf("%.2f KB", float64(size)/1024)
} else if size < 1024*1024*1024 {
return fmt.Sprintf("%.2f MB", float64(size)/(1024*1024))
}
return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024))
}
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 {
app.uploadHandler(w, r)
return
@ -115,81 +100,51 @@ func (app *Application) indexHandler(w http.ResponseWriter, r *http.Request) {
}
if fileInfo, err := os.Stat(path); err == nil && !fileInfo.IsDir() {
DisplayFile(app, "/"+path, w)
ext := filepath.Ext(path)
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,
}
if textExtensions[ext] {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
}
http.ServeFile(w, r, path)
return
}
if _, err := os.Stat("./static"); err == nil {
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) lastHandler(w http.ResponseWriter, r *http.Request) {
if app.lastUploadedFile == "" {
http.Error(w, "No new files uploaded yet", http.StatusNotFound)
return
}
DisplayFile(app, "/"+app.lastUploadedFile, w)
http.ServeFile(w, r, app.lastUploadedFile)
}
func (app *Application) uploadHandler(w http.ResponseWriter, r *http.Request) {
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)
}
} else if strings.Split(contentType, ";")[0] == "multipart/form-data" {
app.curlHandler(w, r)
} else {
http.Error(w, "Method not allowed", http.StatusUnauthorized)
}
}
func (app *Application) formHandler(w http.ResponseWriter, r *http.Request) {
content := r.FormValue("content")
if err := os.WriteFile("/tmp/file.txt", []byte(content), 0666); err != nil {
http.Error(w, "Couldn't parse content body", http.StatusNoContent)
}
file, err := os.Open("/tmp/file.txt")
if err != nil {
http.Error(w, "Couldn't find file", http.StatusNotFound)
}
defer file.Close()
full := true
if len(r.Form["secret"]) == 0 {
full = false
}
filename := app.publicURL(file, ".txt", full)
// reopening file because hash consumes it
file, err = os.Open("/tmp/file.txt")
if err != nil {
http.Error(w, "Couldn't find file", http.StatusNotFound)
}
defer file.Close()
err = SaveFile(app.lastUploadedFile, file)
if err != nil {
fmt.Fprintf(w, "Error parsing file: %s", err.Error())
}
ResponseURLHandler(w, app.url, filename)
}
func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Method not allowed", http.StatusUnauthorized)
return
}
if !CheckAuth(r, app.key) {
if !app.checkAuth(r) {
http.Error(w, "You're not authorized.", http.StatusBadRequest)
return
}
@ -197,16 +152,27 @@ func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) {
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, "Error retrieving the file", http.StatusBadRequest)
slog.Warn(err.Error())
return
}
defer file.Close()
full := true
if len(r.Form["secret"]) == 0 {
full = false
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)
}
filename := app.publicURL(file, filepath.Ext(handler.Filename), full)
}
hasher := md5.New()
if _, err := io.Copy(hasher, file); err != nil {
http.Error(w, "Error hashing file content", http.StatusInternalServerError)
return
}
sha1Hash := hex.EncodeToString(hasher.Sum(nil))[:8]
filename := fmt.Sprintf("%s%s", sha1Hash, filepath.Ext(handler.Filename))
filepath := filepath.Join(app.filesDir, filename)
// reopen the file for copying, as the hash process consumed the file reader
file, _, err = r.FormFile("file")
@ -216,33 +182,48 @@ func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) {
}
defer file.Close()
if err = SaveFile(app.lastUploadedFile, file); err != nil {
fmt.Fprintf(w, "Error parsing file: %s", err.Error())
dst, err := os.Create(filepath)
if err != nil {
http.Error(w, "Error creating file\n", http.StatusInternalServerError)
}
defer dst.Close()
ResponseURLHandler(w, app.url, filename)
}
func (app *Application) publicURL(file io.Reader, extension string, full bool) string {
filename, _ := HashFile(file, extension, full)
filepath := filepath.Join(app.filesDir, filename)
if _, err := io.Copy(dst, file); err != nil {
http.Error(w, "Error copying the file", http.StatusInternalServerError)
}
app.lastUploadedFile = filepath
return filename
fmt.Fprintf(w, "http://%s/%s\n", app.url, 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(),
})
func (app *Application) checkAuth(r *http.Request) bool {
return r.Header.Get("X-Auth") == string(app.key)
}
tokenString, err := token.SignedString([]byte(app.key))
if err != nil {
http.Error(w, "Error generating token", http.StatusInternalServerError)
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
}
}
fmt.Fprintf(w, "%s", tokenString)
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
}

View File

@ -1,134 +0,0 @@
package main
import (
"crypto/md5"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"io"
"net/http"
"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 {
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 {
if size < 1024 {
return fmt.Sprintf("%d B", size)
} else if size < 1024*1024 {
return fmt.Sprintf("%.2f KB", float64(size)/1024)
} else if size < 1024*1024*1024 {
return fmt.Sprintf("%.2f MB", float64(size)/(1024*1024))
}
return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024))
}
func HashFile(file io.Reader, extension string, full bool) (string, error) {
hasher := md5.New()
if _, err := io.Copy(hasher, file); err != nil {
return "", err
}
sha1Hash := strings.ToUpper(hex.EncodeToString(hasher.Sum(nil)))
filename := fmt.Sprintf("%s%s", sha1Hash, extension)
if full {
return filename, nil
} else {
return fmt.Sprintf("%s%s", sha1Hash[:5], extension), nil
}
}
func SaveFile(name string, file io.Reader) error {
dst, err := os.Create(name)
if err != nil {
return err
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
return err
}
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

@ -11,25 +11,9 @@
<body>
<h1>abyss paste</h1>
<div>
<a href="/tree">
<button>all uploaded files</button>
</a>
<a href="/last">
<button>last uploaded file</button>
</a>
</div>
<form action="/" method="POST">
<textarea name="content" placeholder="Enter your content here..."></textarea>
<br />
<button type="submit">upload</button>
</form>
<footer>
abyss paste - powered by
<a href="https://github.com/jabuxas/abyss" target="_blank">abyss</a>
</footer>
</body>
</html>

View File

@ -29,44 +29,3 @@ button {
button:hover {
background-color: #45a29e;
}
footer {
position: absolute;
bottom: 1rem;
font-size: 0.8rem;
color: #777;
}
footer a {
color: #66fcf1;
text-decoration: none;
font-weight: bold;
}
div {
display: flex;
gap: 10px;
align-items: center;
}
form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 30px;
gap: 10px;
}
textarea {
background-color: #333;
color: #fff;
border: 1px solid #555;
padding: 10px;
width: 400px;
height: 150px;
border-radius: 5px;
}
textarea::placeholder {
color: #bbb;
}

View File

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

View File

@ -1,228 +0,0 @@
<!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>