Initial commit: URL shortener + pastebin with dark admin UI and deploy scripts

Features:
- URL shortener with QR codes, click tracking, deduplication, rate limiting
- Pastebin with Markdown rendering, access tokens, raw view
- Admin dashboard: dark theme, stats bar, Quick Links tiles with favicons,
  card-based layout, format/token badges, empty states
- CSRF protection, bcrypt auth, in-memory sessions, security headers
- Pure-Go SQLite (no CGo), single self-contained binary

Deploy:
- deploy/install.sh: auto-detects systemd vs SysV init
- deploy/urlshort.service: hardened systemd unit
- deploy/urlshort.init: SysV init script for older Ubuntu

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This commit is contained in:
lucioandClaude Sonnet 4.6 committed 2026-04-02 03:00:08 -07:00
1 parent 013ff09132
commit 60a09fa878
30 files changed
+3541

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
urlshort
urlshort.exe
urlshort.exe~
urlshort-arm
data/
node_modules/
+19
View File
@@ -0,0 +1,19 @@
.PHONY: build build-arm run clean hash
build:
go build -ldflags="-s -w" -o urlshort.exe ./
build-linux:
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o urlshort ./
build-arm:
GOOS=linux GOARCH=arm GOARM=5 go build -ldflags="-s -w" -o urlshort-arm ./
run: build
./urlshort.exe
clean:
rm -f urlshort urlshort.exe urlshort-arm
hash:
@read -p "Password: " pw && go run . --hash-password "$$pw"
+511
View File
@@ -0,0 +1,511 @@
# urlshort
A lightweight, single-binary URL shortener and pastebin built in Go. Designed to run on a Raspberry Pi Zero (512MB RAM, single-core ARM) with minimal dependencies and no external runtime requirements.
---
## Features
### URL Shortener
- **Public:** Anyone can shorten a URL — no account required
- **Auto-scheme:** Submitting `google.com` automatically becomes `https://google.com`
- **Deduplication:** Submitting the same URL a second time returns the existing short link
- **QR codes:** Server-side SVG QR codes generated for every short link (crisp, no CDN)
- **Click tracking:** Every redirect increments the click counter
- **IP rate limiting:** Anonymous users limited to 1 short link per second; admin is never limited
- **Short slugs:** 3-character base-36 auto-generated (`a-z`, `0-9`); up to 64 characters for custom (admin only)
### Admin Dashboard
- Login protected with bcrypt-hashed password; centered dark-theme login card
- **Dark UI** throughout all admin pages (login, dashboard, edit forms, pastes)
- **Stats bar:** live counts of My Links, Anonymous Links, and Quick Links at a glance
- **My Links** card: links the admin created, with edit/delete and click counts
- **Anonymous Links** card: links created by unauthenticated users, also manageable
- **Quick Links tile grid:** Top 20 most-clicked admin links displayed as tiles with favicon, destination hostname, and click count; one click to open
- **Pastes list:** format and token-status badges; empty states with guidance
- Create links with custom slugs (blocked for anonymous users)
- Edit slug and destination URL
### Pastebin
- **Admin:** Create, edit, delete pastes
- **Public:** Read-only access; optionally protected by a 12-character access token
- **Formats:** Markdown (GitHub-Flavored, rendered server-side) and plain text
- **Raw view:** Append `?raw=1` to any paste URL for `text/plain` output
- **Copy button:** One-click clipboard copy in the paste viewer
### Security
- CSRF protection on every state-changing POST (double-submit cookie pattern)
- `crypto/subtle.ConstantTimeCompare` for CSRF and paste token comparisons
- Session cookie: `HttpOnly`, `SameSite=Lax`, conditionally `Secure` when behind HTTPS proxy
- Security headers on all responses: `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy`
- Input length limits: URLs 2048 chars, paste content 512 KB
- URL scheme re-validated before every redirect (defense in depth)
- In-memory sessions with hourly cleanup goroutine
---
## Project Layout
```
urlshort/
├── main.go # Entry point; flag parsing; --hash-password helper
├── config.toml # Runtime configuration (port, admin creds, db path)
├── go.mod / go.sum
├── Makefile
├── deploy/
│ ├── install.sh # Install script (auto-detects systemd vs SysV)
│ ├── urlshort.service # systemd unit file (Ubuntu 15.04+)
│ └── urlshort.init # SysV init script (Ubuntu 14.04 and older)
├── data/
│ └── urls.db # SQLite database (auto-created on first run)
└── internal/
├── config/
│ └── config.go # TOML config loader; Config struct
├── db/
│ └── db.go # SQLite open/migrate; Link & Paste CRUD
├── slug/
│ └── slug.go # Base-36 slug generation and validation
└── server/
├── server.go # HTTP mux registration; security headers middleware
├── handlers.go # All request handlers; template rendering helpers
├── middleware.go # requireAuth, requireCSRF, rateLimiter, sessionStore, clientIP
├── static/
│ └── style.css # Custom styles on top of Pico CSS
└── templates/
├── index.html # Public home: shorten form + QR result
├── admin_login.html # Login form (dark, centered card)
├── admin.html # Admin dashboard: stats bar, tiles, links tables
├── admin_edit.html # Edit a single link
├── admin_bin.html # Pastes list with format/token badges
├── admin_bin_edit.html # Create / edit a paste
├── bin_view.html # Public paste viewer (GitHub Gist style)
└── 404.html # Not found page
```
---
## Dependencies
| Package | Purpose |
|---|---|
| `github.com/BurntSushi/toml` | TOML config parsing |
| `golang.org/x/crypto/bcrypt` | Admin password hashing |
| `modernc.org/sqlite` | Pure-Go SQLite driver (no CGo required) |
| `github.com/yuin/goldmark` | Markdown rendering (GFM + tables) |
| `rsc.io/qr` | Server-side QR code generation (SVG) |
All other entries in `go.sum` are transitive dependencies of the above.
---
## Getting Started
### Prerequisites
- Go 1.22 or later
- No CGo, no external C libraries, no system SQLite needed
> **Windows note:** If Go is not in your bash `PATH`, prefix every command:
> ```bash
> export PATH="/c/Program Files/Go/bin:$PATH"
> ```
### 1. Clone and install dependencies
```bash
git clone <repo-url>
cd url
go mod download
```
### 2. Configure
Edit `config.toml`:
```toml
[server]
port = 8888
base_url = "http://localhost:8888" # Override by Host header at runtime
read_timeout = "5s"
write_timeout = "10s"
[admin]
username = "admin"
password_hash = "$2a$10$..." # See step 3 below
session_hours = 24
[database]
path = "./data/urls.db"
[slugs]
length = 3 # Auto-generated slug length (characters)
```
### 3. Set your admin password
```bash
./urlshort --hash-password "your-secure-password"
# or via make:
make hash
```
Copy the printed bcrypt hash into `config.toml` under `admin.password_hash`.
### 4. Build and run
```bash
# Windows
make build
./urlshort.exe
# Linux / macOS
make build-linux
./urlshort
# Raspberry Pi Zero (ARMv5)
make build-arm
# Copy urlshort-arm to the Pi, then run it there
```
The server starts on `http://localhost:8888` (or whatever port you set).
---
## Makefile Targets
| Target | Description |
|---|---|
| `make build` | Build `urlshort.exe` for Windows (stripped binary) |
| `make build-linux` | Build `urlshort` for Linux x86-64 |
| `make build-arm` | Cross-compile `urlshort-arm` for Raspberry Pi Zero (ARMv5) |
| `make run` | Build then immediately run on Windows |
| `make clean` | Remove all compiled binaries |
| `make hash` | Interactively hash a password for `config.toml` |
---
## Deploying to Raspberry Pi Zero
```bash
# On your dev machine — cross-compile for ARMv5 (Pi Zero)
make build-arm
# Copy binary, config, and deploy scripts to the Pi
scp urlshort-arm [email protected]:~/urlshort
scp config.toml [email protected]:~/config.toml
scp -r deploy/ [email protected]:~/deploy/
```
The binary is fully self-contained — no Go runtime, no system SQLite, no shared libraries required.
### Install as a system service
The `deploy/` directory contains an install script and service files compatible with Ubuntu/Debian (both modern systemd and older SysV init systems):
```bash
# On the Pi (or any Ubuntu/Debian host):
chmod +x urlshort
sudo ./deploy/install.sh
```
The script will:
- Create a dedicated `urlshort` system user
- Install the binary to `/opt/urlshort/`
- Install the config to `/etc/urlshort/config.toml`
- Create `/var/lib/urlshort/` for the database
- Register and enable the service (systemd or SysV, auto-detected)
**After install**, set your admin password hash in the config:
```bash
/opt/urlshort/urlshort -hash-password "your-secure-password"
# Paste the output into /etc/urlshort/config.toml → admin.password_hash
sudo systemctl start urlshort
```
**Service management:**
```bash
sudo systemctl status urlshort
sudo systemctl restart urlshort
sudo journalctl -u urlshort -f # live logs
```
---
## Behind a Reverse Proxy — nginx
The app reads `Host` and `X-Forwarded-Proto` headers automatically to build correct short URLs and set `Secure` cookies. No `base_url` change is needed in `config.toml` when running behind a proxy.
### 1. Install nginx
```bash
sudo apt update
sudo apt install -y nginx
```
### 2. Create a site config
```bash
sudo nano /etc/nginx/sites-available/urlshort
```
Paste the following, replacing `short.example.com` with your domain:
```nginx
server {
listen 80;
server_name short.example.com;
location / {
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
}
}
```
```bash
sudo ln -s /etc/nginx/sites-available/urlshort /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
```
At this point the site is reachable over HTTP. Proceed to step 3 to add HTTPS.
### 3. Add HTTPS with Let's Encrypt (certbot)
```bash
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d short.example.com
```
Certbot will automatically update the nginx config to add SSL and redirect HTTP → HTTPS. Certificates auto-renew via a systemd timer or cron job that certbot installs.
> **No public domain?** If running on a local network (e.g. Raspberry Pi at home), skip certbot and use a self-signed certificate instead:
> ```bash
> sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
> -keyout /etc/ssl/private/urlshort.key \
> -out /etc/ssl/certs/urlshort.crt \
> -subj "/CN=urlshort"
> ```
> Then reference them manually in the nginx config (`ssl_certificate`, `ssl_certificate_key`).
### 4. Recommended production nginx config
After certbot runs, your config will look roughly like this. The additions below tighten security headers and enable compression:
```nginx
server {
listen 80;
server_name short.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name short.example.com;
# TLS — managed by certbot
ssl_certificate /etc/letsencrypt/live/short.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/short.example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# Compression
gzip on;
gzip_types text/css text/html application/javascript;
gzip_min_length 1024;
# Security headers
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin" always;
location / {
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_buffering off;
}
}
```
```bash
sudo nginx -t && sudo systemctl reload nginx
```
### 5. Update config.toml base_url (optional)
`base_url` is only used as a fallback when no `Host` header is present (e.g. direct `curl` on localhost). When nginx is in front, the `Host` header is always forwarded, so the generated short links will automatically use your domain. If you want the fallback to also be correct:
```toml
[server]
base_url = "https://short.example.com"
```
Then restart the service: `sudo systemctl restart urlshort`
### Verify everything works
```bash
# Confirm redirect (should return 301 to https)
curl -I http://short.example.com/
# Confirm HTTPS proxy is working
curl -I https://short.example.com/
# Check urlshort is running and nginx can reach it
sudo systemctl status urlshort
sudo systemctl status nginx
```
### Cloudflare note
If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limiting since Cloudflare controls the header. For direct-to-internet deployments without a trusted proxy, clients could spoof `X-Forwarded-For` to bypass IP rate limits — see "Possible Future Improvements".
---
## URL Routes
| Method | Path | Auth | Description |
|---|---|---|---|
| `GET` | `/` | Public | Home / shorten form |
| `POST` | `/shorten` | Public | Create short link |
| `GET` | `/{slug}` | Public | Redirect to destination |
| `GET` | `/bin/{name}` | Public | View paste |
| `GET` | `/bin/{name}/{token}` | Public | View token-protected paste |
| `GET` | `/admin/login` | Public | Login form |
| `POST` | `/admin/login` | Public | Submit login |
| `POST` | `/admin/logout` | Admin | Logout (CSRF protected) |
| `GET` | `/admin` | Admin | Dashboard: links + tiles |
| `GET` | `/admin/edit/{id}` | Admin | Edit link form |
| `POST` | `/admin/edit/{id}` | Admin | Save link edit (CSRF) |
| `POST` | `/admin/delete/{id}` | Admin | Delete link (CSRF) |
| `GET` | `/admin/bin` | Admin | Pastes list |
| `GET` | `/admin/bin/new` | Admin | New paste form |
| `POST` | `/admin/bin/new` | Admin | Create paste (CSRF) |
| `GET` | `/admin/bin/edit/{id}` | Admin | Edit paste form |
| `POST` | `/admin/bin/edit/{id}` | Admin | Save paste edit (CSRF) |
| `POST` | `/admin/bin/delete/{id}` | Admin | Delete paste (CSRF) |
| `GET` | `/static/*` | Public | CSS / static assets |
---
## Database Schema
SQLite, WAL mode, single writer, auto-migrated on startup.
```sql
CREATE TABLE links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
url TEXT NOT NULL,
created_by TEXT NOT NULL DEFAULT 'anonymous', -- 'admin' or 'anonymous'
clicks INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE pastes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE, -- URL slug, e.g. "my-script"
title TEXT NOT NULL DEFAULT '',
content TEXT NOT NULL DEFAULT '',
format TEXT NOT NULL DEFAULT 'markdown', -- 'markdown' | 'text'
token TEXT, -- NULL = public; non-null = token required
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
```
To reset the database (e.g. during development):
```bash
rm -f data/urls.db
# Restart the server — it will recreate the DB automatically
```
---
## Configuration Reference
```toml
[server]
port = 8888 # TCP port to listen on
base_url = "http://localhost:8888" # Fallback base URL (overridden by Host header)
read_timeout = "5s" # HTTP read timeout
write_timeout = "10s" # HTTP write timeout
[admin]
username = "admin" # Admin login username
password_hash = "$2a$10$..." # bcrypt hash — generate with: ./urlshort --hash-password
session_hours = 24 # How long admin sessions last
[database]
path = "./data/urls.db" # Path to SQLite file (directory auto-created)
[slugs]
length = 3 # Length of auto-generated slugs (recommended: 3–6)
```
---
## Security Notes
- **Change the default password.** The default hash in `config.toml` is for the password `admin`. Run `./urlshort --hash-password` immediately.
- **CSRF protection** uses the double-submit cookie pattern. Every admin POST requires a `csrf_token` form field matching the `csrf` cookie value, compared with constant-time equality.
- **Sessions** are stored in memory. They are lost when the server restarts (acceptable for single-user use). Session IDs are 32 bytes of `crypto/rand`.
- **Paste tokens** are 12-character random strings. Token comparison uses `crypto/subtle.ConstantTimeCompare` to prevent timing attacks.
- **Rate limiting** is 1 short link per second per IP for anonymous users. The rate limiter table is lazily cleaned up at 10,000 entries.
---
## Development Tips
### Rebuild and restart quickly (Windows)
```bash
export PATH="/c/Program Files/Go/bin:$PATH"
pkill -f urlshort.exe; sleep 1
go build -o urlshort.exe ./ && ./urlshort.exe &
```
### Check logs
```bash
# If started with output redirected:
tail -f /tmp/urlshort.log
```
### Useful one-liners
```bash
# Hash a new password
go run . --hash-password "mynewpassword"
# Check what's listening on 8888 (Windows PowerShell)
Get-NetTCPConnection -LocalPort 8888 | Select-Object OwningProcess
# Kill whatever is on port 8888 (Windows PowerShell)
Get-NetTCPConnection -LocalPort 8888 | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force }
```
---
## Possible Future Improvements
- [ ] Configurable trusted-proxy IP list (for safer `X-Forwarded-For` handling)
- [ ] Persistent sessions (write to SQLite) so restarts don't log out admin
- [ ] Optional expiry date per link
- [ ] Bulk delete / bulk import via CSV
- [ ] Syntax highlighting for code pastes
+20
View File
@@ -0,0 +1,20 @@
# URL Shortener Configuration
[server]
port = 8888
base_url = "http://localhost:8888"
read_timeout = "5s"
write_timeout = "10s"
[admin]
username = "admin"
# Default password: "admin" — change this!
# Generate a new hash: ./urlshort --hash-password "your-password"
password_hash = "$2a$10$WXBoF7ZB7fIRl5smdGH9seqlNbXWiCS7ZbGNk0ONb9xjS8499gBpu"
session_hours = 24
[database]
path = "./data/urls.db"
[slugs]
length = 3
+98
View File
@@ -0,0 +1,98 @@
#!/bin/sh
# install.sh — Install urlshort as a system service on Ubuntu/Debian
# Works with systemd (Ubuntu 15.04+) and SysV init (older systems)
# Run as root: sudo ./install.sh
set -e
BINARY_SRC="./urlshort"
INSTALL_DIR="/opt/urlshort"
CONFIG_DIR="/etc/urlshort"
DATA_DIR="/var/lib/urlshort"
SERVICE_USER="urlshort"
SERVICE_NAME="urlshort"
# ── Helpers ───────────────────────────────────────────────────────────────────
die() { echo "ERROR: $1" >&2; exit 1; }
info() { echo " --> $1"; }
require_root() {
[ "$(id -u)" -eq 0 ] || die "This script must be run as root (use sudo)."
}
has_systemd() {
command -v systemctl >/dev/null 2>&1 && systemctl --version >/dev/null 2>&1
}
# ── Preflight ─────────────────────────────────────────────────────────────────
require_root
[ -f "$BINARY_SRC" ] || die "Binary '$BINARY_SRC' not found. Build first: GOOS=linux GOARCH=arm go build -o urlshort ."
[ -f "./deploy/urlshort.service" ] || die "deploy/urlshort.service not found."
[ -f "./deploy/urlshort.init" ] || die "deploy/urlshort.init not found."
echo "Installing urlshort..."
# ── Create service user ───────────────────────────────────────────────────────
if ! id "$SERVICE_USER" >/dev/null 2>&1; then
info "Creating system user '$SERVICE_USER'"
useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER"
else
info "User '$SERVICE_USER' already exists"
fi
# ── Create directories ────────────────────────────────────────────────────────
info "Creating directories"
mkdir -p "$INSTALL_DIR" "$CONFIG_DIR" "$DATA_DIR"
chown "$SERVICE_USER:$SERVICE_USER" "$DATA_DIR"
chmod 750 "$DATA_DIR"
# ── Install binary ────────────────────────────────────────────────────────────
info "Installing binary to $INSTALL_DIR/urlshort"
cp "$BINARY_SRC" "$INSTALL_DIR/urlshort"
chown root:root "$INSTALL_DIR/urlshort"
chmod 755 "$INSTALL_DIR/urlshort"
# ── Install config (only if not already present) ──────────────────────────────
if [ ! -f "$CONFIG_DIR/config.toml" ]; then
info "Installing default config to $CONFIG_DIR/config.toml"
cp ./config.toml "$CONFIG_DIR/config.toml"
# Point the database path at the data directory
sed -i 's|path = .*|path = "/var/lib/urlshort/urls.db"|' "$CONFIG_DIR/config.toml"
chown root:"$SERVICE_USER" "$CONFIG_DIR/config.toml"
chmod 640 "$CONFIG_DIR/config.toml"
echo ""
echo " ** IMPORTANT: Edit $CONFIG_DIR/config.toml and set admin.password_hash."
echo " Generate a hash with: $INSTALL_DIR/urlshort -hash-password 'yourpassword'"
echo ""
else
info "Config already exists at $CONFIG_DIR/config.toml — skipping"
fi
# ── Install and enable service ────────────────────────────────────────────────
if has_systemd; then
info "Installing systemd service"
cp ./deploy/urlshort.service /etc/systemd/system/urlshort.service
chmod 644 /etc/systemd/system/urlshort.service
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
info "Service enabled. Start with: systemctl start $SERVICE_NAME"
info "View logs with: journalctl -u $SERVICE_NAME -f"
else
info "systemd not found — installing SysV init script"
cp ./deploy/urlshort.init /etc/init.d/urlshort
chmod 755 /etc/init.d/urlshort
update-rc.d urlshort defaults
info "Service enabled. Start with: service $SERVICE_NAME start"
info "View logs with: tail -f /var/log/$SERVICE_NAME.log"
fi
echo ""
echo "Installation complete."
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: urlshort
# Required-Start: $network $local_fs $remote_fs
# Required-Stop: $network $local_fs $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: URL Shortener
# Description: URL Shortener and Pastebin server
### END INIT INFO
NAME=urlshort
DAEMON=/opt/urlshort/urlshort
DAEMON_ARGS="-config /etc/urlshort/config.toml"
PIDFILE=/var/run/$NAME.pid
LOGFILE=/var/log/$NAME.log
RUN_AS=urlshort
. /lib/lsb/init-functions
do_start() {
if [ ! -x "$DAEMON" ]; then
log_failure_msg "$DAEMON not found or not executable"
return 1
fi
start-stop-daemon --start --quiet \
--pidfile "$PIDFILE" --make-pidfile \
--background --no-close \
--chuid "$RUN_AS" \
--exec "$DAEMON" -- $DAEMON_ARGS \
>> "$LOGFILE" 2>&1
return $?
}
do_stop() {
start-stop-daemon --stop --quiet \
--pidfile "$PIDFILE" \
--retry=TERM/10/KILL/5
RETVAL=$?
rm -f "$PIDFILE"
return $RETVAL
}
case "$1" in
start)
log_daemon_msg "Starting $NAME"
do_start
log_end_msg $?
;;
stop)
log_daemon_msg "Stopping $NAME"
do_stop
log_end_msg $?
;;
restart|force-reload)
log_daemon_msg "Restarting $NAME"
do_stop
sleep 1
do_start
log_end_msg $?
;;
status)
status_of_proc -p "$PIDFILE" "$DAEMON" "$NAME"
;;
*)
echo "Usage: $0 {start|stop|restart|force-reload|status}"
exit 1
;;
esac
exit 0
+29
View File
@@ -0,0 +1,29 @@
[Unit]
Description=URL Shortener
Documentation=https://github.com/
After=network.target
Wants=network.target
[Service]
Type=simple
User=urlshort
Group=urlshort
WorkingDirectory=/opt/urlshort
ExecStart=/opt/urlshort/urlshort -config /etc/urlshort/config.toml
Restart=on-failure
RestartSec=5
TimeoutStopSec=10
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=urlshort
# Hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/var/lib/urlshort
[Install]
WantedBy=multi-user.target
+23
View File
@@ -0,0 +1,23 @@
module urlshort
go 1.26.1
require (
github.com/BurntSushi/toml v1.6.0
golang.org/x/crypto v0.49.0
modernc.org/sqlite v1.48.0
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/yuin/goldmark v1.8.2 // indirect
golang.org/x/sys v0.42.0 // indirect
modernc.org/libc v1.70.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
rsc.io/qr v0.2.0 // indirect
)
+59
View File
@@ -0,0 +1,59 @@
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE=
github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.32.0 h1:hjG66bI/kqIPX1b2yT6fr/jt+QedtP2fqojG2VrFuVw=
modernc.org/ccgo/v4 v4.32.0/go.mod h1:6F08EBCx5uQc38kMGl+0Nm0oWczoo1c7cgpzEry7Uc0=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.70.0 h1:U58NawXqXbgpZ/dcdS9kMshu08aiA6b7gusEusqzNkw=
modernc.org/libc v1.70.0/go.mod h1:OVmxFGP1CI/Z4L3E0Q3Mf1PDE0BucwMkcXjjLntvHJo=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.48.0 h1:ElZyLop3Q2mHYk5IFPPXADejZrlHu7APbpB0sF78bq4=
modernc.org/sqlite v1.48.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
+89
View File
@@ -0,0 +1,89 @@
package config
import (
"fmt"
"os"
"time"
"github.com/BurntSushi/toml"
)
type Config struct {
Server ServerConfig `toml:"server"`
Admin AdminConfig `toml:"admin"`
Database DatabaseConfig `toml:"database"`
Slugs SlugConfig `toml:"slugs"`
}
type ServerConfig struct {
Port int `toml:"port"`
BaseURL string `toml:"base_url"`
ReadTimeout string `toml:"read_timeout"`
WriteTimeout string `toml:"write_timeout"`
}
type AdminConfig struct {
Username string `toml:"username"`
PasswordHash string `toml:"password_hash"`
SessionHours int `toml:"session_hours"`
}
type DatabaseConfig struct {
Path string `toml:"path"`
}
type SlugConfig struct {
Length int `toml:"length"`
}
func (c *ServerConfig) ReadTimeoutDuration() time.Duration {
d, err := time.ParseDuration(c.ReadTimeout)
if err != nil {
return 5 * time.Second
}
return d
}
func (c *ServerConfig) WriteTimeoutDuration() time.Duration {
d, err := time.ParseDuration(c.WriteTimeout)
if err != nil {
return 10 * time.Second
}
return d
}
func Load(path string) (*Config, error) {
cfg := &Config{
Server: ServerConfig{
Port: 8080,
BaseURL: "http://localhost:8080",
ReadTimeout: "5s",
WriteTimeout: "10s",
},
Admin: AdminConfig{
Username: "admin",
SessionHours: 24,
},
Database: DatabaseConfig{
Path: "./data/urls.db",
},
Slugs: SlugConfig{
Length: 3,
},
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading config: %w", err)
}
if err := toml.Unmarshal(data, cfg); err != nil {
return nil, fmt.Errorf("parsing config: %w", err)
}
if cfg.Admin.PasswordHash == "" {
return nil, fmt.Errorf("admin.password_hash is required in config")
}
return cfg, nil
}
+274
View File
@@ -0,0 +1,274 @@
package db
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"time"
_ "modernc.org/sqlite"
)
type Paste struct {
ID int64
Name string
Title string
Content string
Format string
Token string // empty = disabled
CreatedAt time.Time
UpdatedAt time.Time
}
type Link struct {
ID int64
Slug string
URL string
CreatedBy string
Clicks int64
CreatedAt time.Time
}
type DB struct {
conn *sql.DB
}
func Open(path string) (*DB, error) {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return nil, fmt.Errorf("creating db directory: %w", err)
}
conn, err := sql.Open("sqlite", path+"?_journal_mode=WAL&_busy_timeout=5000")
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
conn.SetMaxOpenConns(1)
if err := migrate(conn); err != nil {
conn.Close()
return nil, err
}
return &DB{conn: conn}, nil
}
func migrate(conn *sql.DB) error {
_, err := conn.Exec(`
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
url TEXT NOT NULL,
created_by TEXT NOT NULL DEFAULT 'anonymous',
clicks INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_links_slug ON links(slug);
CREATE TABLE IF NOT EXISTS pastes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
title TEXT NOT NULL DEFAULT '',
content TEXT NOT NULL DEFAULT '',
format TEXT NOT NULL DEFAULT 'markdown',
token TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
`)
if err != nil {
return fmt.Errorf("running migrations: %w", err)
}
// Add columns if upgrading from older schema
conn.Exec(`ALTER TABLE links ADD COLUMN created_by TEXT NOT NULL DEFAULT 'anonymous'`)
conn.Exec(`ALTER TABLE links ADD COLUMN clicks INTEGER NOT NULL DEFAULT 0`)
return nil
}
func (d *DB) Close() error {
return d.conn.Close()
}
func (d *DB) Create(slug, url, createdBy string) (*Link, error) {
res, err := d.conn.Exec("INSERT INTO links (slug, url, created_by) VALUES (?, ?, ?)", slug, url, createdBy)
if err != nil {
return nil, err
}
id, _ := res.LastInsertId()
return &Link{ID: id, Slug: slug, URL: url, CreatedBy: createdBy, CreatedAt: time.Now()}, nil
}
func (d *DB) GetBySlug(slug string) (*Link, error) {
row := d.conn.QueryRow("SELECT id, slug, url, created_by, clicks, created_at FROM links WHERE slug = ?", slug)
return scanLink(row)
}
func (d *DB) GetByID(id int64) (*Link, error) {
row := d.conn.QueryRow("SELECT id, slug, url, created_by, clicks, created_at FROM links WHERE id = ?", id)
return scanLink(row)
}
func (d *DB) IncrementClicks(slug string) error {
_, err := d.conn.Exec("UPDATE links SET clicks = clicks + 1 WHERE slug = ?", slug)
return err
}
func (d *DB) TopLinks(createdBy string, limit int) ([]Link, error) {
rows, err := d.conn.Query(
"SELECT id, slug, url, created_by, clicks, created_at FROM links WHERE created_by = ? ORDER BY clicks DESC LIMIT ?",
createdBy, limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
return scanLinks(rows)
}
func (d *DB) List() ([]Link, error) {
rows, err := d.conn.Query("SELECT id, slug, url, created_by, clicks, created_at FROM links ORDER BY id DESC")
if err != nil {
return nil, err
}
defer rows.Close()
return scanLinks(rows)
}
func (d *DB) ListByCreator(createdBy string) ([]Link, error) {
rows, err := d.conn.Query("SELECT id, slug, url, created_by, clicks, created_at FROM links WHERE created_by = ? ORDER BY id DESC", createdBy)
if err != nil {
return nil, err
}
defer rows.Close()
return scanLinks(rows)
}
func (d *DB) Update(id int64, slug, url string) error {
_, err := d.conn.Exec("UPDATE links SET slug = ?, url = ? WHERE id = ?", slug, url, id)
return err
}
func (d *DB) Delete(id int64) error {
_, err := d.conn.Exec("DELETE FROM links WHERE id = ?", id)
return err
}
func (d *DB) GetByURL(url string) (*Link, error) {
row := d.conn.QueryRow("SELECT id, slug, url, created_by, clicks, created_at FROM links WHERE url = ? LIMIT 1", url)
return scanLink(row)
}
func (d *DB) SlugExists(slug string) (bool, error) {
var count int
err := d.conn.QueryRow("SELECT COUNT(*) FROM links WHERE slug = ?", slug).Scan(&count)
return count > 0, err
}
func scanLinks(rows *sql.Rows) ([]Link, error) {
var links []Link
for rows.Next() {
var l Link
var ts string
if err := rows.Scan(&l.ID, &l.Slug, &l.URL, &l.CreatedBy, &l.Clicks, &ts); err != nil {
return nil, err
}
l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", ts)
links = append(links, l)
}
return links, rows.Err()
}
// ---- Paste CRUD ----
func (d *DB) CreatePaste(name, title, content, format, token string) (*Paste, error) {
var tokenVal interface{}
if token != "" {
tokenVal = token
}
res, err := d.conn.Exec(
"INSERT INTO pastes (name, title, content, format, token) VALUES (?, ?, ?, ?, ?)",
name, title, content, format, tokenVal,
)
if err != nil {
return nil, err
}
id, _ := res.LastInsertId()
now := time.Now()
return &Paste{ID: id, Name: name, Title: title, Content: content, Format: format, Token: token, CreatedAt: now, UpdatedAt: now}, nil
}
func (d *DB) GetPasteByName(name string) (*Paste, error) {
row := d.conn.QueryRow("SELECT id, name, title, content, format, COALESCE(token,''), created_at, updated_at FROM pastes WHERE name = ?", name)
return scanPaste(row)
}
func (d *DB) GetPasteByID(id int64) (*Paste, error) {
row := d.conn.QueryRow("SELECT id, name, title, content, format, COALESCE(token,''), created_at, updated_at FROM pastes WHERE id = ?", id)
return scanPaste(row)
}
func (d *DB) ListPastes() ([]Paste, error) {
rows, err := d.conn.Query("SELECT id, name, title, content, format, COALESCE(token,''), created_at, updated_at FROM pastes ORDER BY updated_at DESC")
if err != nil {
return nil, err
}
defer rows.Close()
var pastes []Paste
for rows.Next() {
var p Paste
var created, updated string
if err := rows.Scan(&p.ID, &p.Name, &p.Title, &p.Content, &p.Format, &p.Token, &created, &updated); err != nil {
return nil, err
}
p.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created)
p.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated)
pastes = append(pastes, p)
}
return pastes, rows.Err()
}
func (d *DB) UpdatePaste(id int64, name, title, content, format, token string) error {
var tokenVal interface{}
if token != "" {
tokenVal = token
}
_, err := d.conn.Exec(
"UPDATE pastes SET name=?, title=?, content=?, format=?, token=?, updated_at=datetime('now') WHERE id=?",
name, title, content, format, tokenVal, id,
)
return err
}
func (d *DB) DeletePaste(id int64) error {
_, err := d.conn.Exec("DELETE FROM pastes WHERE id = ?", id)
return err
}
func (d *DB) PasteNameExists(name string) (bool, error) {
var count int
err := d.conn.QueryRow("SELECT COUNT(*) FROM pastes WHERE name = ?", name).Scan(&count)
return count > 0, err
}
func scanPaste(row *sql.Row) (*Paste, error) {
var p Paste
var created, updated string
if err := row.Scan(&p.ID, &p.Name, &p.Title, &p.Content, &p.Format, &p.Token, &created, &updated); err != nil {
return nil, err
}
p.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created)
p.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated)
return &p, nil
}
func scanLink(row *sql.Row) (*Link, error) {
var l Link
var ts string
if err := row.Scan(&l.ID, &l.Slug, &l.URL, &l.CreatedBy, &l.Clicks, &ts); err != nil {
return nil, err
}
l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", ts)
return &l, nil
}
+605
View File
@@ -0,0 +1,605 @@
package server
import (
"bytes"
"crypto/subtle"
"database/sql"
"fmt"
"html/template"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"urlshort/internal/slug"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/renderer/html"
"golang.org/x/crypto/bcrypt"
"rsc.io/qr"
)
type pageData struct {
BaseURL string
Error string
Success string
ShortURL string
OriginalURL string
QRSVG template.HTML
Links any
AdminLinks any
AnonLinks any
Link any
TopLinks any
Paste any
Pastes any
PasteBody template.HTML
LoggedIn bool
CSRFToken string
}
var mdRenderer = goldmark.New(
goldmark.WithExtensions(extension.GFM, extension.Table),
goldmark.WithRendererOptions(html.WithUnsafe()),
)
func renderMarkdown(src string) template.HTML {
var buf bytes.Buffer
if err := mdRenderer.Convert([]byte(src), &buf); err != nil {
return template.HTML(template.HTMLEscapeString(src))
}
return template.HTML(buf.String())
}
func makeQRSVG(text string, size int) template.HTML {
code, err := qr.Encode(strings.ToUpper(text), qr.L)
if err != nil {
return ""
}
n := code.Size
pad := 2
total := n + pad*2
var paths strings.Builder
for r := 0; r < n; r++ {
for c := 0; c < n; c++ {
if code.Black(c, r) {
fmt.Fprintf(&paths, "M%d,%dh1v1h-1z", c+pad, r+pad)
}
}
}
svg := fmt.Sprintf(
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" width="%d" height="%d" shape-rendering="crispEdges"><rect width="100%%" height="100%%" fill="#fff"/><path d="%s" fill="#000"/></svg>`,
total, total, size, size, paths.String(),
)
return template.HTML(svg)
}
func (s *Server) baseURL(r *http.Request) string {
host := r.Host
if host == "" {
return s.cfg.Server.BaseURL
}
proto := r.Header.Get("X-Forwarded-Proto")
if proto == "" {
proto = "http"
}
return proto + "://" + host
}
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "index.html", pageData{BaseURL: s.baseURL(r), LoggedIn: s.isLoggedIn(r), CSRFToken: csrfToken(w, r)})
}
func (s *Server) handleShorten(w http.ResponseWriter, r *http.Request) {
if !s.isLoggedIn(r) {
ip := clientIP(r)
if !s.limiter.Allow(ip) {
s.renderIndex(w, r, "Too many requests. Please wait a moment.", "", "")
return
}
}
rawURL := strings.TrimSpace(r.FormValue("url"))
customSlug := strings.TrimSpace(r.FormValue("slug"))
if rawURL == "" {
s.renderIndex(w, r, "URL is required", "", "")
return
}
if len(rawURL) > 2048 {
s.renderIndex(w, r, "URL is too long (max 2048 characters)", "", "")
return
}
if !strings.Contains(rawURL, "://") {
rawURL = "https://" + rawURL
}
parsed, err := url.ParseRequestURI(rawURL)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
s.renderIndex(w, r, "Invalid URL", "", "")
return
}
isAdmin := s.isLoggedIn(r)
// Only admin can use custom slugs
if customSlug != "" && !isAdmin {
customSlug = ""
}
var finalSlug string
if customSlug != "" {
customSlug = strings.ToLower(customSlug)
if err := slug.Validate(customSlug); err != nil {
s.renderIndex(w, r, err.Error(), "", "")
return
}
exists, err := s.db.SlugExists(customSlug)
if err != nil {
s.renderIndex(w, r, "Database error", "", "")
return
}
if exists {
s.renderIndex(w, r, fmt.Sprintf("Slug %q is already taken", customSlug), "", "")
return
}
finalSlug = customSlug
} else {
// Return existing link if this URL was shortened before
if existing, err := s.db.GetByURL(rawURL); err == nil {
shortURL := s.baseURL(r) + "/" + existing.Slug
s.renderIndex(w, r, "", shortURL, rawURL)
return
}
for range 10 {
candidate := slug.Generate(s.cfg.Slugs.Length)
exists, err := s.db.SlugExists(candidate)
if err != nil {
s.renderIndex(w, r, "Database error", "", "")
return
}
if !exists {
finalSlug = candidate
break
}
}
if finalSlug == "" {
s.renderIndex(w, r, "Could not generate a unique slug. Try again.", "", "")
return
}
}
createdBy := "anonymous"
if isAdmin {
createdBy = "admin"
}
if _, err := s.db.Create(finalSlug, rawURL, createdBy); err != nil {
s.renderIndex(w, r, "Failed to create link", "", "")
return
}
shortURL := s.baseURL(r) + "/" + finalSlug
s.renderIndex(w, r, "", shortURL, rawURL)
}
func (s *Server) renderIndex(w http.ResponseWriter, r *http.Request, errMsg, shortURL, originalURL string) {
var qrsvg template.HTML
if shortURL != "" {
qrsvg = makeQRSVG(shortURL, 180)
}
renderTemplate(w, "index.html", pageData{
BaseURL: s.baseURL(r),
Error: errMsg,
ShortURL: shortURL,
OriginalURL: originalURL,
QRSVG: qrsvg,
LoggedIn: s.isLoggedIn(r),
CSRFToken: csrfToken(w, r),
})
}
func (s *Server) handleRedirect(w http.ResponseWriter, r *http.Request) {
sl := strings.ToLower(r.PathValue("slug"))
if sl == "" {
http.NotFound(w, r)
return
}
link, err := s.db.GetBySlug(sl)
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound)
renderTemplate(w, "404.html", pageData{BaseURL: s.baseURL(r)})
return
}
if err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Re-validate scheme before redirecting (defense in depth)
if parsed, err := url.Parse(link.URL); err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
http.Error(w, "Invalid redirect target", http.StatusBadGateway)
return
}
s.db.IncrementClicks(sl)
http.Redirect(w, r, link.URL, http.StatusMovedPermanently)
}
// Admin handlers
func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "admin_login.html", pageData{BaseURL: s.baseURL(r), CSRFToken: csrfToken(w, r)})
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
if username != s.cfg.Admin.Username {
renderTemplate(w, "admin_login.html", pageData{Error: "Invalid credentials", CSRFToken: csrfToken(w, r)})
return
}
if err := bcrypt.CompareHashAndPassword([]byte(s.cfg.Admin.PasswordHash), []byte(password)); err != nil {
renderTemplate(w, "admin_login.html", pageData{Error: "Invalid credentials", CSRFToken: csrfToken(w, r)})
return
}
token, err := s.sessions.Create()
if err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
secure := r.Header.Get("X-Forwarded-Proto") == "https"
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: token,
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteLaxMode,
MaxAge: s.cfg.Admin.SessionHours * 3600,
})
http.Redirect(w, r, "/admin", http.StatusSeeOther)
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie("session"); err == nil {
s.sessions.Delete(cookie.Value)
}
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: "",
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
MaxAge: -1,
})
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func (s *Server) adminPage(w http.ResponseWriter, r *http.Request) pageData {
return pageData{
BaseURL: s.baseURL(r),
LoggedIn: true,
CSRFToken: csrfToken(w, r),
}
}
func (s *Server) handleAdmin(w http.ResponseWriter, r *http.Request) {
adminLinks, err := s.db.ListByCreator("admin")
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
anonLinks, err := s.db.ListByCreator("anonymous")
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
topLinks, _ := s.db.TopLinks("admin", 20)
d := s.adminPage(w, r)
d.AdminLinks = adminLinks
d.AnonLinks = anonLinks
d.TopLinks = topLinks
renderTemplate(w, "admin.html", d)
}
func (s *Server) handleAdminEdit(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
link, err := s.db.GetByID(id)
if err == sql.ErrNoRows {
http.NotFound(w, r)
return
}
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
d := s.adminPage(w, r)
d.Link = link
renderTemplate(w, "admin_edit.html", d)
}
func (s *Server) handleAdminEditSave(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
newSlug := strings.TrimSpace(r.FormValue("slug"))
newURL := strings.TrimSpace(r.FormValue("url"))
renderEditErr := func(msg string) {
link, _ := s.db.GetByID(id)
d := s.adminPage(w, r)
d.Link = link
d.Error = msg
renderTemplate(w, "admin_edit.html", d)
}
if newSlug == "" || newURL == "" {
renderEditErr("Slug and URL are required")
return
}
if err := slug.Validate(newSlug); err != nil {
renderEditErr(err.Error())
return
}
parsed, err := url.ParseRequestURI(newURL)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
renderEditErr("Invalid URL")
return
}
if err := s.db.Update(id, newSlug, newURL); err != nil {
renderEditErr("Failed to update: slug may already be taken")
return
}
http.Redirect(w, r, "/admin", http.StatusSeeOther)
}
func (s *Server) handleAdminDelete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
s.db.Delete(id)
http.Redirect(w, r, "/admin", http.StatusSeeOther)
}
func (s *Server) isLoggedIn(r *http.Request) bool {
cookie, err := r.Cookie("session")
if err != nil {
return false
}
return s.sessions.Valid(cookie.Value)
}
func formatTime(t time.Time) string {
return t.Format("2006-01-02 15:04")
}
// ---- Paste handlers ----
func (s *Server) handleBinView(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("name")
providedToken := r.PathValue("token")
paste, err := s.db.GetPasteByName(name)
if err == sql.ErrNoRows {
http.NotFound(w, r)
return
}
if err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Token check (constant-time to prevent timing attacks)
if paste.Token != "" && subtle.ConstantTimeCompare([]byte(paste.Token), []byte(providedToken)) != 1 {
http.Error(w, "Access denied: invalid or missing token.", http.StatusForbidden)
return
}
// Raw view
if r.URL.Query().Get("raw") == "1" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte(paste.Content))
return
}
var body template.HTML
if paste.Format == "markdown" {
body = renderMarkdown(paste.Content)
} else {
body = template.HTML("<pre><code>" + template.HTMLEscapeString(paste.Content) + "</code></pre>")
}
renderTemplate(w, "bin_view.html", pageData{
BaseURL: s.baseURL(r),
Paste: paste,
PasteBody: body,
LoggedIn: s.isLoggedIn(r),
})
}
func (s *Server) handleAdminBin(w http.ResponseWriter, r *http.Request) {
pastes, err := s.db.ListPastes()
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
d := s.adminPage(w, r)
d.Pastes = pastes
renderTemplate(w, "admin_bin.html", d)
}
func (s *Server) handleAdminBinNew(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "admin_bin_edit.html", s.adminPage(w, r))
}
func (s *Server) handleAdminBinCreate(w http.ResponseWriter, r *http.Request) {
name := strings.TrimSpace(r.FormValue("name"))
title := strings.TrimSpace(r.FormValue("title"))
content := r.FormValue("content")
format := r.FormValue("format")
if format != "text" {
format = "markdown"
}
enableToken := r.FormValue("enable_token") == "1"
newErrPage := func(msg string) {
d := s.adminPage(w, r)
d.Error = msg
renderTemplate(w, "admin_bin_edit.html", d)
}
if len(content) > 512*1024 {
newErrPage("Paste content too large (max 512 KB)")
return
}
if name == "" {
newErrPage("Name is required")
return
}
if !validPasteName(name) {
newErrPage("Name must be alphanumeric with hyphens/underscores only")
return
}
exists, _ := s.db.PasteNameExists(name)
if exists {
newErrPage(fmt.Sprintf("Name %q is already taken", name))
return
}
token := ""
if enableToken {
token = slug.Generate(12)
}
if _, err := s.db.CreatePaste(name, title, content, format, token); err != nil {
newErrPage("Failed to create paste")
return
}
http.Redirect(w, r, "/admin/bin", http.StatusSeeOther)
}
func (s *Server) handleAdminBinEdit(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
paste, err := s.db.GetPasteByID(id)
if err == sql.ErrNoRows {
http.NotFound(w, r)
return
}
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
d := s.adminPage(w, r)
d.Paste = paste
renderTemplate(w, "admin_bin_edit.html", d)
}
func (s *Server) handleAdminBinSave(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
paste, err := s.db.GetPasteByID(id)
if err == sql.ErrNoRows {
http.NotFound(w, r)
return
}
name := strings.TrimSpace(r.FormValue("name"))
title := strings.TrimSpace(r.FormValue("title"))
content := r.FormValue("content")
format := r.FormValue("format")
if format != "text" {
format = "markdown"
}
tokenAction := r.FormValue("token_action") // "keep", "disable", "regenerate"
editErrPage := func(msg string) {
d := s.adminPage(w, r)
d.Paste = paste
d.Error = msg
renderTemplate(w, "admin_bin_edit.html", d)
}
if len(content) > 512*1024 {
editErrPage("Paste content too large (max 512 KB)")
return
}
if name == "" || !validPasteName(name) {
editErrPage("Invalid name")
return
}
token := paste.Token
switch tokenAction {
case "disable":
token = ""
case "regenerate":
token = slug.Generate(12)
}
if err := s.db.UpdatePaste(id, name, title, content, format, token); err != nil {
editErrPage("Failed to save: name may already be taken")
return
}
http.Redirect(w, r, "/admin/bin", http.StatusSeeOther)
}
func (s *Server) handleAdminBinDelete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
s.db.DeletePaste(id)
http.Redirect(w, r, "/admin/bin", http.StatusSeeOther)
}
var validPasteNameRe = strings.NewReplacer() // placeholder — use inline check below
func validPasteName(name string) bool {
if len(name) == 0 || len(name) > 64 {
return false
}
for _, c := range name {
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') {
return false
}
}
return true
}
+175
View File
@@ -0,0 +1,175 @@
package server
import (
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"net"
"net/http"
"strings"
"sync"
"time"
)
type sessionStore struct {
mu sync.RWMutex
sessions map[string]time.Time
ttl time.Duration
}
func newSessionStore(ttl time.Duration) *sessionStore {
s := &sessionStore{
sessions: make(map[string]time.Time),
ttl: ttl,
}
go s.cleanup()
return s
}
func (s *sessionStore) cleanup() {
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for range ticker.C {
s.mu.Lock()
now := time.Now()
for token, expiry := range s.sessions {
if now.After(expiry) {
delete(s.sessions, token)
}
}
s.mu.Unlock()
}
}
func (s *sessionStore) Create() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
token := hex.EncodeToString(b)
s.mu.Lock()
s.sessions[token] = time.Now().Add(s.ttl)
s.mu.Unlock()
return token, nil
}
func (s *sessionStore) Valid(token string) bool {
s.mu.RLock()
expiry, ok := s.sessions[token]
s.mu.RUnlock()
if !ok {
return false
}
if time.Now().After(expiry) {
s.mu.Lock()
delete(s.sessions, token)
s.mu.Unlock()
return false
}
return true
}
func (s *sessionStore) Delete(token string) {
s.mu.Lock()
delete(s.sessions, token)
s.mu.Unlock()
}
func (srv *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session")
if err != nil || !srv.sessions.Valid(cookie.Value) {
http.Redirect(w, r, "/admin/login", http.StatusSeeOther)
return
}
next(w, r)
}
}
// csrfToken returns the CSRF token for this session, creating one if needed.
// Uses a separate cookie (not HttpOnly so JS can read it, but SameSite=Lax
// already blocks cross-site POSTs for most cases). The token is also embedded
// in each form and verified server-side on every state-changing POST.
func csrfToken(w http.ResponseWriter, r *http.Request) string {
if c, err := r.Cookie("csrf"); err == nil && len(c.Value) == 64 {
return c.Value
}
b := make([]byte, 32)
rand.Read(b)
token := hex.EncodeToString(b)
http.SetCookie(w, &http.Cookie{
Name: "csrf",
Value: token,
Path: "/",
SameSite: http.SameSiteLaxMode,
MaxAge: 86400,
})
return token
}
func verifyCSRF(r *http.Request) bool {
cookie, err := r.Cookie("csrf")
if err != nil {
return false
}
formToken := r.FormValue("csrf_token")
return subtle.ConstantTimeCompare([]byte(cookie.Value), []byte(formToken)) == 1
}
func (srv *Server) requireCSRF(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !verifyCSRF(r) {
http.Error(w, "Invalid CSRF token", http.StatusForbidden)
return
}
next(w, r)
}
}
// rateLimiter tracks the last request time per IP.
type rateLimiter struct {
mu sync.Mutex
clients map[string]time.Time
window time.Duration
}
func newRateLimiter(window time.Duration) *rateLimiter {
return &rateLimiter{
clients: make(map[string]time.Time),
window: window,
}
}
func (rl *rateLimiter) Allow(ip string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
if last, ok := rl.clients[ip]; ok && now.Sub(last) < rl.window {
return false
}
rl.clients[ip] = now
// Lazy cleanup: purge stale entries when map grows large
if len(rl.clients) > 10000 {
for k, v := range rl.clients {
if now.Sub(v) > rl.window*10 {
delete(rl.clients, k)
}
}
}
return true
}
func clientIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
// First IP in the chain is the original client
if i := strings.Index(xff, ","); i > 0 {
return strings.TrimSpace(xff[:i])
}
return strings.TrimSpace(xff)
}
if xri := r.Header.Get("X-Real-Ip"); xri != "" {
return strings.TrimSpace(xri)
}
host, _, _ := net.SplitHostPort(r.RemoteAddr)
return host
}
+90
View File
@@ -0,0 +1,90 @@
package server
import (
"fmt"
"io/fs"
"log"
"net/http"
"time"
"urlshort/internal/config"
"urlshort/internal/db"
)
type Server struct {
cfg *config.Config
db *db.DB
sessions *sessionStore
limiter *rateLimiter
}
func New(cfg *config.Config, database *db.DB) *Server {
ttl := time.Duration(cfg.Admin.SessionHours) * time.Hour
return &Server{
cfg: cfg,
db: database,
sessions: newSessionStore(ttl),
limiter: newRateLimiter(1 * time.Second),
}
}
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
next.ServeHTTP(w, r)
})
}
func (s *Server) Start() error {
initTemplates()
mux := http.NewServeMux()
// Static files
staticSub, _ := fs.Sub(staticFS, "static")
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub))))
// Public routes
mux.HandleFunc("GET /{$}", s.handleIndex)
mux.HandleFunc("POST /shorten", s.handleShorten)
// Admin auth
mux.HandleFunc("GET /admin/login", s.handleLoginPage)
mux.HandleFunc("POST /admin/login", s.handleLogin)
mux.HandleFunc("POST /admin/logout", s.requireAuth(s.requireCSRF(s.handleLogout)))
// Admin routes (protected)
mux.HandleFunc("GET /admin", s.requireAuth(s.handleAdmin))
mux.HandleFunc("GET /admin/edit/{id}", s.requireAuth(s.handleAdminEdit))
mux.HandleFunc("POST /admin/edit/{id}", s.requireAuth(s.requireCSRF(s.handleAdminEditSave)))
mux.HandleFunc("POST /admin/delete/{id}", s.requireAuth(s.requireCSRF(s.handleAdminDelete)))
// Pastebin admin routes (protected)
mux.HandleFunc("GET /admin/bin", s.requireAuth(s.handleAdminBin))
mux.HandleFunc("GET /admin/bin/new", s.requireAuth(s.handleAdminBinNew))
mux.HandleFunc("POST /admin/bin/new", s.requireAuth(s.requireCSRF(s.handleAdminBinCreate)))
mux.HandleFunc("GET /admin/bin/edit/{id}", s.requireAuth(s.handleAdminBinEdit))
mux.HandleFunc("POST /admin/bin/edit/{id}", s.requireAuth(s.requireCSRF(s.handleAdminBinSave)))
mux.HandleFunc("POST /admin/bin/delete/{id}", s.requireAuth(s.requireCSRF(s.handleAdminBinDelete)))
// Pastebin public routes (before catch-all)
mux.HandleFunc("GET /bin/{name}", s.handleBinView)
mux.HandleFunc("GET /bin/{name}/{token}", s.handleBinView)
// Redirect catch-all (must be last)
mux.HandleFunc("GET /{slug}", s.handleRedirect)
addr := fmt.Sprintf(":%d", s.cfg.Server.Port)
srv := &http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: s.cfg.Server.ReadTimeoutDuration(),
WriteTimeout: s.cfg.Server.WriteTimeoutDuration(),
}
log.Printf("Starting server on %s (base URL: %s)", addr, s.cfg.Server.BaseURL)
srv.Handler = securityHeaders(mux)
return srv.ListenAndServe()
}
+287
View File
@@ -0,0 +1,287 @@
/**
* Minimal QR Code SVG generator — alphanumeric + byte mode, EC level L.
* No dependencies. Auto-selects alphanumeric mode when possible (smaller QR).
* Usage: QR.toSVG(text, {size, padding, fg, bg}) => SVG string
*/
var QR = (function () {
"use strict";
// Alphanumeric charset (QR spec order)
var ALNUM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
function isAlnum(str) {
for (var i = 0; i < str.length; i++)
if (ALNUM_CHARS.indexOf(str[i]) < 0) return false;
return true;
}
// Capacity tables [version] = max chars, EC level L
var CAP_ALNUM = [0,25,47,77,114,154,195,224,279,335,395];
var CAP_BYTE = [0,17,32,53, 78,106,134,154,192,230,271];
function minVersion(str, alnum) {
var cap = alnum ? CAP_ALNUM : CAP_BYTE;
for (var v = 1; v <= 10; v++) if (str.length <= cap[v]) return v;
return 10;
}
// EC codewords per version (level L), total codewords, blocks
var EC_CW = [0,7,10,15,20,26,18,20,24,30,18];
var TOT_CW = [0,26,44,70,100,134,172,196,242,292,346];
var NBLOCKS= [0,1,1,1,1,1,2,2,2,2,4];
// Reed-Solomon
var GF_EXP = new Array(256), GF_LOG = new Array(256);
(function(){var x=1;for(var i=0;i<256;i++){GF_EXP[i]=x;GF_LOG[x]=i;x*=2;if(x>=256)x^=285;}})();
function gfMul(a,b){return(!a||!b)?0:GF_EXP[(GF_LOG[a]+GF_LOG[b])%255];}
// Generator polynomials for EC lengths 7,10,13,15,16,17,18,20,22,24,26,28,30
var GEN_POLY = {
7:[0,87,229,146,149,238,102,21],
10:[0,251,67,46,61,118,70,64,94,32,45],
13:[0,74,152,176,100,86,100,106,104,130,218,206,140,78],
15:[0,8,183,61,91,202,37,51,58,58,237,140,124,5,99,105],
16:[0,120,104,107,109,102,161,76,3,91,191,147,169,182,194,225,120],
17:[0,43,139,206,78,43,239,123,206,214,147,24,99,150,39,243,163,136],
18:[0,215,234,158,94,184,97,118,170,79,187,152,148,252,179,5,98,96,153],
20:[0,17,60,79,50,61,163,26,187,202,180,221,225,83,239,156,164,212,212,188,190],
22:[0,210,171,247,242,93,230,14,109,221,53,200,74,8,172,98,80,219,134,160,105,165,231],
24:[0,229,121,135,48,211,117,251,126,159,180,169,152,192,226,228,218,111,0,117,232,87,96,227,21],
26:[0,173,125,158,2,103,182,118,17,145,201,111,28,165,53,161,21,245,142,13,102,48,227,153,145,218,70],
28:[0,168,223,200,104,224,234,108,180,110,190,195,147,205,27,232,201,21,43,245,87,42,195,212,119,242,37,9,123],
30:[0,41,173,145,152,216,31,179,182,50,48,110,86,239,96,222,125,42,173,226,193,224,130,156,37,251,216,238,40,192,180]
};
function rsEncode(data, ecLen) {
var gp = GEN_POLY[ecLen];
var msg = data.slice();
for (var i = 0; i < ecLen; i++) msg.push(0);
for (var i = 0; i < data.length; i++) {
var c = msg[i];
if (c !== 0) for (var j = 0; j < gp.length; j++) msg[i+j] ^= gfMul(c, GF_EXP[(GF_LOG[GF_EXP[gp[j]]] )%255]||gp[j]);
}
return msg.slice(data.length);
}
// Simpler RS encode using generator polynomial directly
function rsEncode2(data, ecLen) {
var gp = GEN_POLY[ecLen];
if (!gp) throw new Error("No generator for ecLen="+ecLen);
var msg = data.concat(new Array(ecLen).fill(0));
for (var i = 0; i < data.length; i++) {
var coef = msg[i];
if (coef !== 0) {
for (var j = 1; j < gp.length; j++) {
msg[i+j] ^= GF_EXP[(GF_LOG[coef] + gp[j]) % 255];
}
}
}
return msg.slice(data.length);
}
function encodeAlnum(text, ver) {
var dataCW = TOT_CW[ver] - EC_CW[ver];
var bits = [];
function push(val, len) { for (var i = len-1; i >= 0; i--) bits.push((val>>i)&1); }
push(2, 4); // alphanumeric mode indicator
push(text.length, 9); // char count (9 bits for ver 1-9)
for (var i = 0; i < text.length - 1; i += 2) {
var v = ALNUM_CHARS.indexOf(text[i]) * 45 + ALNUM_CHARS.indexOf(text[i+1]);
push(v, 11);
}
if (text.length % 2 === 1) push(ALNUM_CHARS.indexOf(text[text.length-1]), 6);
// terminator + padding
push(0, Math.min(4, dataCW*8 - bits.length));
while (bits.length % 8) bits.push(0);
var pads = [0xEC, 0x11];
for (var pi = 0; bits.length < dataCW*8; pi++) { push(pads[pi%2], 8); }
bits.length = dataCW * 8;
var bytes = [];
for (var i = 0; i < bits.length; i += 8)
bytes.push((bits[i]<<7)|(bits[i+1]<<6)|(bits[i+2]<<5)|(bits[i+3]<<4)|(bits[i+4]<<3)|(bits[i+5]<<2)|(bits[i+6]<<1)|bits[i+7]);
return bytes;
}
function encodeByte(text, ver) {
var dataCW = TOT_CW[ver] - EC_CW[ver];
var bits = [];
function push(val, len) { for (var i = len-1; i >= 0; i--) bits.push((val>>i)&1); }
push(4, 4); // byte mode indicator
push(text.length, ver <= 9 ? 8 : 16);
for (var i = 0; i < text.length; i++) push(text.charCodeAt(i), 8);
push(0, Math.min(4, dataCW*8 - bits.length));
while (bits.length % 8) bits.push(0);
var pads = [0xEC, 0x11];
for (var pi = 0; bits.length < dataCW*8; pi++) { push(pads[pi%2], 8); }
bits.length = dataCW * 8;
var bytes = [];
for (var i = 0; i < bits.length; i += 8)
bytes.push((bits[i]<<7)|(bits[i+1]<<6)|(bits[i+2]<<5)|(bits[i+3]<<4)|(bits[i+4]<<3)|(bits[i+5]<<2)|(bits[i+6]<<1)|bits[i+7]);
return bytes;
}
function interleave(data, ver) {
var ecCW = EC_CW[ver], nb = NBLOCKS[ver];
var bsize = Math.floor(data.length / nb);
var blocks = [], ecBlocks = [];
for (var i = 0; i < nb; i++) {
var extra = i < data.length % nb ? 1 : 0;
var b = data.slice(i * bsize, i * bsize + bsize + extra);
blocks.push(b);
ecBlocks.push(rsEncode2(b, ecCW));
}
var out = [];
var maxLen = blocks[blocks.length-1].length;
for (var i = 0; i < maxLen; i++) for (var j = 0; j < nb; j++) if (i < blocks[j].length) out.push(blocks[j][i]);
for (var i = 0; i < ecCW; i++) for (var j = 0; j < nb; j++) out.push(ecBlocks[j][i]);
return out;
}
// Matrix building
var ALIGN_POS = [null,null,[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50]];
var FMT_BITS = [0x77c4,0x72f3,0x7daa,0x789d,0x662f,0x6318,0x6c41,0x6976]; // EC-L, masks 0-7
function makeMatrix(n) {
var m = [];
for (var i = 0; i < n; i++) { m[i] = []; for (var j = 0; j < n; j++) m[i][j] = null; }
return m;
}
function putFinder(m, r, c) {
var n = m.length;
for (var dr = -1; dr <= 7; dr++) for (var dc = -1; dc <= 7; dc++) {
var rr = r+dr, cc = c+dc;
if (rr < 0 || rr >= n || cc < 0 || cc >= n) continue;
m[rr][cc] = (dr>=0&&dr<=6&&(dc===0||dc===6))||(dc>=0&&dc<=6&&(dr===0||dr===6))||(dr>=2&&dr<=4&&dc>=2&&dc<=4) ? 1 : 0;
}
}
function putAlign(m, r, c) {
for (var dr = -2; dr <= 2; dr++) for (var dc = -2; dc <= 2; dc++)
m[r+dr][c+dc] = (Math.abs(dr)===2||Math.abs(dc)===2||(!dr&&!dc)) ? 1 : 0;
}
function placeFixed(m, ver) {
var n = m.length;
putFinder(m,0,0); putFinder(m,0,n-7); putFinder(m,n-7,0);
var ap = ALIGN_POS[ver];
if (ap) for (var i = 0; i < ap.length; i++) for (var j = 0; j < ap.length; j++) {
if ((i===0&&j===0)||(i===0&&j===ap.length-1)||(i===ap.length-1&&j===0)) continue;
putAlign(m, ap[i], ap[j]);
}
for (var i = 8; i < n-8; i++) { m[6][i] = i%2===0?1:0; m[i][6] = i%2===0?1:0; }
// format area placeholders
for (var i = 0; i < 9; i++) { if(m[8][i]===null) m[8][i]=0; if(m[i][8]===null) m[i][8]=0; }
for (var i = 0; i < 8; i++) { if(m[8][n-1-i]===null) m[8][n-1-i]=0; if(m[n-1-i][8]===null) m[n-1-i][8]=0; }
m[n-8][8] = 1; // dark module
}
function putFormat(m, mask) {
var n = m.length, bits = FMT_BITS[mask];
for (var i = 0; i < 15; i++) {
var b = (bits >> i) & 1;
if (i < 6) m[8][i] = b; else if (i < 8) m[8][i+1] = b; else m[14-i][8] = b;
if (i < 7) m[n-1-i][8] = b; else if (i < 8) m[8][n-15+i] = b; else m[8][n-15+i] = b;
}
// second copy bottom-left / top-right
for (var i = 0; i < 8; i++) m[n-1-i][8] = (bits >> i) & 1;
for (var i = 8; i < 15; i++) m[8][n-15+i] = (bits >> i) & 1;
}
function isData(m, r, c) {
var n = m.length;
if (r <= 8 && c <= 8) return false;
if (r <= 8 && c >= n-8) return false;
if (r >= n-8 && c <= 8) return false;
if (r === 6 || c === 6) return false;
if (r === n-8 && c === 8) return false;
return true;
}
function placeData(m, codewords) {
var n = m.length, bitIdx = 0, total = codewords.length * 8;
var x = n - 1, up = true;
while (x >= 0) {
if (x === 6) x--;
var cols = [x, x-1];
var rows = [];
if (up) { for (var i = n-1; i >= 0; i--) rows.push(i); }
else { for (var i = 0; i < n; i++) rows.push(i); }
for (var ri = 0; ri < rows.length; ri++) for (var ci = 0; ci < 2; ci++) {
var r = rows[ri], c = cols[ci];
if (c < 0 || m[r][c] !== null) continue;
m[r][c] = bitIdx < total ? (codewords[bitIdx>>3] >> (7-(bitIdx&7))) & 1 : 0;
bitIdx++;
}
x -= 2; up = !up;
}
}
var MASK_FNS = [
function(r,c){return(r+c)%2===0;},
function(r,c){return r%2===0;},
function(r,c){return c%3===0;},
function(r,c){return(r+c)%3===0;},
function(r,c){return(Math.floor(r/2)+Math.floor(c/3))%2===0;},
function(r,c){return(r*c)%2+(r*c)%3===0;},
function(r,c){return((r*c)%2+(r*c)%3)%2===0;},
function(r,c){return((r+c)%2+(r*c)%3)%2===0;}
];
function applyMask(m, mask) {
var n = m.length, fn = MASK_FNS[mask];
for (var r = 0; r < n; r++) for (var c = 0; c < n; c++)
if (isData(m,r,c)) m[r][c] ^= fn(r,c) ? 1 : 0;
}
function penalty(m) {
var n = m.length, s = 0;
for (var r = 0; r < n; r++) {
var run = 1;
for (var c = 1; c < n; c++) { if (m[r][c]===m[r][c-1]) run++; else { if(run>=5) s+=run-2; run=1; } }
if (run >= 5) s += run-2;
}
for (var c = 0; c < n; c++) {
var run = 1;
for (var r = 1; r < n; r++) { if (m[r][c]===m[r-1][c]) run++; else { if(run>=5) s+=run-2; run=1; } }
if (run >= 5) s += run-2;
}
return s;
}
function generate(text) {
var alnum = isAlnum(text);
var ver = minVersion(text, alnum);
var rawData = alnum ? encodeAlnum(text, ver) : encodeByte(text, ver);
var codewords = interleave(rawData, ver);
var best = null, bestScore = Infinity;
for (var mask = 0; mask < 8; mask++) {
var m = makeMatrix(17 + ver*4);
placeFixed(m, ver);
placeData(m, codewords);
applyMask(m, mask);
putFormat(m, mask);
var s = penalty(m);
if (s < bestScore) { bestScore = s; best = m; }
}
return best;
}
function toSVG(text, opts) {
opts = opts || {};
var size = opts.size || 200, pad = opts.padding != null ? opts.padding : 2;
var fg = opts.fg || "#000", bg = opts.bg || "#fff";
var m = generate(text);
var n = m.length, total = n + pad*2;
var paths = [];
for (var r = 0; r < n; r++) for (var c = 0; c < n; c++)
if (m[r][c]) paths.push("M"+(c+pad)+","+(r+pad)+"h1v1h-1z");
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 '+total+' '+total+'" width="'+size+'" height="'+size+'" shape-rendering="crispEdges">'
+ '<rect width="100%" height="100%" fill="'+bg+'"/>'
+ '<path d="'+paths.join("")+'" fill="'+fg+'"/>'
+ '</svg>';
}
return { toSVG: toSVG };
})();
+370
View File
@@ -0,0 +1,370 @@
:root {
--pico-font-size: 16px;
}
body > nav {
padding: 0.5rem 1rem;
}
.container {
max-width: 640px;
margin: 0 auto;
padding: 2rem 1rem;
}
.result-box {
background: var(--pico-card-background-color);
border: 2px solid var(--pico-primary);
border-radius: var(--pico-border-radius);
padding: 1rem;
display: flex;
align-items: center;
gap: 0.5rem;
margin-top: 1rem;
}
.result-box code {
flex: 1;
word-break: break-all;
font-size: 1.1rem;
}
.result-box button {
width: auto;
margin: 0;
padding: 0.4rem 0.8rem;
}
table td {
max-width: 300px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.actions {
display: flex;
gap: 0.25rem;
}
.actions form {
margin: 0;
}
.actions a, .actions button {
padding: 0.25rem 0.5rem;
font-size: 0.85rem;
margin: 0;
}
[role="group"] form {
margin: 0;
display: flex;
}
[role="group"] form button {
height: 100%;
}
h1 a {
text-decoration: none;
color: inherit;
}
.tile-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 0.5rem;
margin-bottom: 1rem;
}
.tile {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.2rem;
padding: 0.75rem 0.5rem;
border-radius: var(--pico-border-radius);
background: var(--pico-card-background-color);
border: 1px solid var(--pico-muted-border-color);
text-decoration: none;
text-align: center;
transition: border-color 0.15s, box-shadow 0.15s;
}
.tile:hover {
border-color: var(--pico-primary);
box-shadow: 0 4px 16px rgba(0,0,0,0.25), inset 0 0 0 1px var(--pico-primary);
}
.tile-slug {
font-weight: 600;
font-size: 1rem;
color: var(--pico-primary);
}
.tile-favicon {
width: 20px;
height: 20px;
border-radius: 3px;
margin-bottom: 0.1rem;
}
.tile-dest {
font-size: 0.72rem;
color: var(--pico-muted-color);
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tile-clicks {
font-size: 0.72rem;
color: var(--pico-muted-color);
font-variant-numeric: tabular-nums;
}
/* Admin tab navigation */
.admin-tabs {
display: flex;
gap: 0;
padding: 0 1rem;
border-bottom: 2px solid var(--pico-muted-border-color);
background: var(--pico-background-color);
}
.tab-link {
display: inline-block;
padding: 0.6rem 1.25rem;
text-decoration: none;
color: var(--pico-muted-color);
font-weight: 500;
border-bottom: 2px solid transparent;
margin-bottom: -2px;
transition: color 0.15s, border-color 0.15s;
}
.tab-link:hover {
color: var(--pico-primary);
}
.tab-link.active {
color: var(--pico-primary);
border-bottom-color: var(--pico-primary);
}
/* Paste view */
.paste-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 1rem;
flex-wrap: wrap;
margin-bottom: 0.5rem;
}
.paste-toolbar {
display: flex;
gap: 0.5rem;
align-items: center;
flex-shrink: 0;
}
.paste-toolbar button,
.paste-toolbar a {
margin: 0;
}
.format-badge {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: var(--pico-border-radius);
background: var(--pico-card-background-color);
border: 1px solid var(--pico-muted-border-color);
font-size: 0.75rem;
font-family: monospace;
}
/* Paste rendered markdown body */
.paste-body {
line-height: 1.7;
}
.paste-body pre {
background: var(--pico-card-background-color);
border: 1px solid var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
padding: 1rem;
overflow-x: auto;
}
.paste-body code {
font-size: 0.9em;
}
.paste-body pre code {
background: none;
padding: 0;
}
.paste-body blockquote {
border-left: 4px solid var(--pico-muted-border-color);
margin: 0;
padding-left: 1rem;
color: var(--pico-muted-color);
}
.paste-body table {
width: 100%;
border-collapse: collapse;
}
.paste-body th, .paste-body td {
border: 1px solid var(--pico-muted-border-color);
padding: 0.4rem 0.75rem;
text-align: left;
max-width: none;
white-space: normal;
overflow: visible;
text-overflow: clip;
}
/* ── Admin redesign components ───────────────────────────────────────── */
/* Stats bar */
.stats-bar {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
gap: 1rem;
margin-bottom: 1.5rem;
}
.stats-card {
background: var(--pico-card-background-color);
border: 1px solid var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
padding: 1rem 1.25rem;
text-align: center;
}
.stats-card .stats-value {
font-size: 2rem;
font-weight: 700;
color: var(--pico-primary);
line-height: 1.1;
display: block;
}
.stats-card .stats-label {
font-size: 0.8rem;
color: var(--pico-muted-color);
text-transform: uppercase;
letter-spacing: 0.04em;
display: block;
margin-top: 0.25rem;
}
/* Section header (title left, action button right) */
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 1rem 1.25rem 0;
}
.section-header hgroup {
margin: 0;
}
/* Card-wrapped table: no padding so table runs edge-to-edge */
.card-table {
padding: 0;
overflow: hidden;
}
.card-table figure {
margin: 0.75rem 0 0;
}
/* Empty state */
.empty-state {
padding: 3rem 1rem;
text-align: center;
color: var(--pico-muted-color);
}
.empty-state .empty-icon {
font-size: 2.5rem;
display: block;
margin-bottom: 0.75rem;
}
.empty-state p {
margin: 0 0 1rem;
}
/* Badges */
mark.badge-format {
background: var(--pico-card-background-color);
color: var(--pico-primary);
border: 1px solid var(--pico-primary);
padding: 0.1rem 0.45rem;
font-size: 0.72rem;
font-family: monospace;
border-radius: var(--pico-border-radius);
}
mark.badge-token {
background: color-mix(in srgb, var(--pico-ins-color) 15%, transparent);
color: var(--pico-ins-color);
border: 1px solid var(--pico-ins-color);
padding: 0.1rem 0.45rem;
font-size: 0.72rem;
border-radius: var(--pico-border-radius);
}
mark.badge-public {
background: transparent;
color: var(--pico-muted-color);
border: 1px solid var(--pico-muted-border-color);
padding: 0.1rem 0.45rem;
font-size: 0.72rem;
border-radius: var(--pico-border-radius);
}
/* Centered login card */
.login-wrap {
min-height: calc(100vh - 80px);
display: flex;
align-items: center;
justify-content: center;
padding: 2rem 1rem;
}
.login-card {
width: 100%;
max-width: 420px;
}
/* Alert helpers (replace repeated inline styles) */
.alert-success {
border-left: 4px solid var(--pico-ins-color);
padding: 0.75rem 1rem;
background: color-mix(in srgb, var(--pico-ins-color) 10%, transparent);
}
.alert-error {
border-left: 4px solid var(--pico-del-color);
padding: 0.75rem 1rem;
background: color-mix(in srgb, var(--pico-del-color) 10%, transparent);
}
/* Small button utility */
.btn-sm {
margin: 0;
padding: 0.25rem 0.75rem;
font-size: 0.85rem;
}
+23
View File
@@ -0,0 +1,23 @@
package server
import (
"embed"
"html/template"
"io"
)
//go:embed all:templates
var templateFS embed.FS
//go:embed all:static
var staticFS embed.FS
var templates *template.Template
func initTemplates() {
templates = template.Must(template.ParseFS(templateFS, "templates/*.html"))
}
func renderTemplate(w io.Writer, name string, data any) error {
return templates.ExecuteTemplate(w, name, data)
}
+21
View File
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Not Found — URL Shortener</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Shortener</a></strong></li></ul>
<ul><li><a href="/">Home</a></li></ul>
</nav>
<main class="container" style="text-align:center;padding-top:4rem">
<h1>404</h1>
<p>This short link doesn't exist.</p>
<a href="/" role="button">Create a new one</a>
</main>
</body>
</html>
+175
View File
@@ -0,0 +1,175 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin — URL Shortener</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Shortener</a></strong></li></ul>
<ul>
<li><a href="/">Home</a></li>
<li>
<form method="post" action="/admin/logout" style="margin:0">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary btn-sm">Logout</button>
</form>
</li>
</ul>
</nav>
<div class="admin-tabs">
<a href="/admin" class="tab-link active">Links</a>
<a href="/admin/bin" class="tab-link">Pastes</a>
</div>
<main class="container" style="max-width:960px">
<div class="stats-bar">
<div class="stats-card">
<span class="stats-value">{{len .AdminLinks}}</span>
<span class="stats-label">My Links</span>
</div>
<div class="stats-card">
<span class="stats-value">{{len .AnonLinks}}</span>
<span class="stats-label">Anonymous</span>
</div>
<div class="stats-card">
<span class="stats-value">{{len .TopLinks}}</span>
<span class="stats-label">Quick Links</span>
</div>
</div>
{{if .TopLinks}}
<article>
<header>
<h3>Quick Links</h3>
</header>
<div class="tile-grid">
{{range .TopLinks}}
<a href="/{{.Slug}}" class="tile" target="_blank" title="{{.URL}}">
<img class="tile-favicon" src="https://www.google.com/s2/favicons?sz=32&domain_url={{.URL}}" loading="lazy" alt="" onerror="this.style.display='none'">
<span class="tile-slug">/{{.Slug}}</span>
<span class="tile-dest">{{.URL}}</span>
<span class="tile-clicks">{{.Clicks}} clicks</span>
</a>
{{end}}
</div>
</article>
{{end}}
{{if .Success}}
<article aria-label="success" class="alert-success">{{.Success}}</article>
{{end}}
<article class="card-table">
<div class="section-header">
<hgroup>
<h2>My Links</h2>
<p>{{len .AdminLinks}} links</p>
</hgroup>
<a href="/" role="button" class="outline btn-sm">+ New Link</a>
</div>
<figure>
<table role="grid">
<thead>
<tr>
<th>Slug</th>
<th>Destination</th>
<th>Clicks</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{range .AdminLinks}}
<tr>
<td><a href="/{{.Slug}}" target="_blank">/{{.Slug}}</a></td>
<td title="{{.URL}}">{{.URL}}</td>
<td>{{.Clicks}}</td>
<td>{{.CreatedAt.Format "2006-01-02 15:04"}}</td>
<td>
<div role="group">
<a href="/admin/edit/{{.ID}}" role="button" class="outline">Edit</a>
<form method="post" action="/admin/delete/{{.ID}}" onsubmit="return confirm('Delete /{{.Slug}}?')">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary">Del</button>
</form>
</div>
</td>
</tr>
{{else}}
<tr>
<td colspan="5">
<div class="empty-state">
<span class="empty-icon">&#128279;</span>
<p>No links yet.</p>
<a href="/">Create your first link</a>
</div>
</td>
</tr>
{{end}}
</tbody>
</table>
</figure>
</article>
<article class="card-table">
<div class="section-header">
<hgroup>
<h2>Anonymous Links</h2>
<p>{{len .AnonLinks}} links</p>
</hgroup>
</div>
<figure>
<table role="grid">
<thead>
<tr>
<th>Slug</th>
<th>Destination</th>
<th>Clicks</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{range .AnonLinks}}
<tr>
<td><a href="/{{.Slug}}" target="_blank">/{{.Slug}}</a></td>
<td title="{{.URL}}">{{.URL}}</td>
<td>{{.Clicks}}</td>
<td>{{.CreatedAt.Format "2006-01-02 15:04"}}</td>
<td>
<div role="group">
<a href="/admin/edit/{{.ID}}" role="button" class="outline">Edit</a>
<form method="post" action="/admin/delete/{{.ID}}" onsubmit="return confirm('Delete /{{.Slug}}?')">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary">Del</button>
</form>
</div>
</td>
</tr>
{{else}}
<tr>
<td colspan="5">
<div class="empty-state">
<span class="empty-icon">&#128101;</span>
<p>No anonymous links.</p>
</div>
</td>
</tr>
{{end}}
</tbody>
</table>
</figure>
</article>
</main>
<script>
document.querySelectorAll('.tile-dest').forEach(el => {
try { el.textContent = new URL(el.textContent.trim()).hostname; } catch(e) {}
});
</script>
</body>
</html>
+87
View File
@@ -0,0 +1,87 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pastes — Admin</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Shortener</a></strong></li></ul>
<ul>
<li><a href="/">Home</a></li>
<li>
<form method="post" action="/admin/logout" style="margin:0">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary btn-sm">Logout</button>
</form>
</li>
</ul>
</nav>
<div class="admin-tabs">
<a href="/admin" class="tab-link">Links</a>
<a href="/admin/bin" class="tab-link active">Pastes</a>
</div>
<main class="container" style="max-width:960px">
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
<article class="card-table">
<div class="section-header">
<hgroup>
<h2>Pastes</h2>
<p>{{len .Pastes}} pastes</p>
</hgroup>
<a href="/admin/bin/new" role="button" class="btn-sm">+ New Paste</a>
</div>
<figure>
<table role="grid">
<thead>
<tr>
<th>Name</th>
<th>Title</th>
<th>Format</th>
<th>Token</th>
<th>Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{range .Pastes}}
<tr>
<td><a href="/bin/{{.Name}}{{if .Token}}/{{.Token}}{{end}}" target="_blank">{{.Name}}</a></td>
<td>{{.Title}}</td>
<td><mark class="badge-format">{{.Format}}</mark></td>
<td>{{if .Token}}<mark class="badge-token">&#128274; token</mark>{{else}}<mark class="badge-public">public</mark>{{end}}</td>
<td>{{.UpdatedAt.Format "2006-01-02 15:04"}}</td>
<td>
<div role="group">
<a href="/admin/bin/edit/{{.ID}}" role="button" class="outline">Edit</a>
<form method="post" action="/admin/bin/delete/{{.ID}}" onsubmit="return confirm('Delete paste {{.Name}}?')">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary">Del</button>
</form>
</div>
</td>
</tr>
{{else}}
<tr>
<td colspan="6">
<div class="empty-state">
<span class="empty-icon">&#128196;</span>
<p>No pastes yet.</p>
<a href="/admin/bin/new">Create your first paste</a>
</div>
</td>
</tr>
{{end}}
</tbody>
</table>
</figure>
</article>
</main>
</body>
</html>
@@ -0,0 +1,118 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{if .Paste}}Edit Paste{{else}}New Paste{{end}} — Admin</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Shortener</a></strong></li></ul>
<ul>
<li><a href="/">Home</a></li>
<li>
<form method="post" action="/admin/logout" style="margin:0">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary btn-sm">Logout</button>
</form>
</li>
</ul>
</nav>
<div class="admin-tabs">
<a href="/admin" class="tab-link">Links</a>
<a href="/admin/bin" class="tab-link active">Pastes</a>
</div>
<main class="container" style="max-width:860px">
<article>
<header>
<h2>{{if .Paste}}Edit Paste{{else}}New Paste{{end}}</h2>
</header>
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
{{if .Paste}}
{{with .Paste}}
<form method="post" action="/admin/bin/edit/{{.ID}}">
{{else}}{{end}}
{{else}}
<form method="post" action="/admin/bin/new">
{{end}}
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<div style="display:grid;grid-template-columns:1fr 2fr;gap:1rem;">
<label>
Name <small>(URL slug)</small>
{{if .Paste}}
{{with .Paste}}<input type="text" name="name" value="{{.Name}}" required pattern="[a-zA-Z0-9_-]+" title="Letters, numbers, hyphens, underscores">{{end}}
{{else}}
<input type="text" name="name" required pattern="[a-zA-Z0-9_-]+" placeholder="my-script" title="Letters, numbers, hyphens, underscores">
{{end}}
</label>
<label>
Title <small>(optional)</small>
{{if .Paste}}
{{with .Paste}}<input type="text" name="title" value="{{.Title}}" placeholder="A short description">{{end}}
{{else}}
<input type="text" name="title" placeholder="A short description">
{{end}}
</label>
</div>
<label>Format
<select name="format">
{{if .Paste}}
{{with .Paste}}
<option value="markdown"{{if eq .Format "markdown"}} selected{{end}}>Markdown</option>
<option value="text"{{if eq .Format "text"}} selected{{end}}>Plain text</option>
{{end}}
{{else}}
<option value="markdown" selected>Markdown</option>
<option value="text">Plain text</option>
{{end}}
</select>
</label>
<label>Content
{{if .Paste}}
{{with .Paste}}<textarea name="content" rows="20" style="font-family:monospace;font-size:0.9rem">{{.Content}}</textarea>{{end}}
{{else}}
<textarea name="content" rows="20" style="font-family:monospace;font-size:0.9rem" placeholder="# Hello&#10;&#10;Write your markdown here..."></textarea>
{{end}}
</label>
<fieldset>
<legend>Access Token</legend>
{{if .Paste}}
{{with .Paste}}
{{if .Token}}
<p>Current token: <code>{{.Token}}</code> &mdash; URL: <code>/bin/{{.Name}}/{{.Token}}</code></p>
<label><input type="radio" name="token_action" value="keep" checked> Keep current token</label>
<label><input type="radio" name="token_action" value="regenerate"> Regenerate token</label>
<label><input type="radio" name="token_action" value="disable"> Disable token (public access)</label>
{{else}}
<p>Token is currently <strong>disabled</strong> — paste is publicly accessible.</p>
<label><input type="radio" name="token_action" value="keep" checked> Keep disabled</label>
<label><input type="radio" name="token_action" value="regenerate"> Enable with new token</label>
{{end}}
{{end}}
{{else}}
<label><input type="radio" name="enable_token" value="0" checked> No token (public access)</label>
<label><input type="radio" name="enable_token" value="1"> Generate access token</label>
{{end}}
</fieldset>
<div role="group" style="margin-top:1rem">
<button type="submit">Save</button>
<a href="/admin/bin" role="button" class="outline secondary">Cancel</a>
</div>
</form>
{{if .Paste}}{{with .Paste}}{{end}}{{end}}
</article>
</main>
</body>
</html>
+51
View File
@@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Edit Link — URL Shortener</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Shortener</a></strong></li></ul>
<ul>
<li><a href="/admin">Back to list</a></li>
<li>
<form method="post" action="/admin/logout" style="margin:0">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary btn-sm">Logout</button>
</form>
</li>
</ul>
</nav>
<main class="container">
<article>
<header>
<h2>Edit Link</h2>
</header>
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
{{with .Link}}
<form method="post" action="/admin/edit/{{.ID}}">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<label for="slug">Slug</label>
<input type="text" id="slug" name="slug" value="{{.Slug}}" required pattern="[a-zA-Z0-9_-]+" title="Letters, numbers, hyphens, underscores only">
<label for="url">Destination URL</label>
<input type="url" id="url" name="url" value="{{.URL}}" required>
<div role="group">
<button type="submit">Save</button>
<a href="/admin" role="button" class="outline secondary">Cancel</a>
</div>
</form>
{{end}}
</article>
</main>
</body>
</html>
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Login — URL Shortener</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Shortener</a></strong></li></ul>
<ul><li><a href="/">Home</a></li></ul>
</nav>
<main>
<div class="login-wrap">
<article class="login-card">
<header>
<hgroup>
<h2>Admin Login</h2>
<p>Sign in to manage your links</p>
</hgroup>
</header>
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
<form method="post" action="/admin/login">
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<label for="username">Username</label>
<input type="text" id="username" name="username" required autofocus>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<button type="submit">Log in</button>
</form>
</article>
</div>
</main>
</body>
</html>
+48
View File
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{with .Paste}}{{with .Title}}<title>{{.}}</title>{{else}}<title>{{with $.Paste}}{{.Name}}{{end}}</title>{{end}}{{end}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Shortener</a></strong></li></ul>
<ul><li>{{if .LoggedIn}}<a href="/admin/bin">Admin</a>{{else}}<a href="/admin/login">Admin</a>{{end}}</li></ul>
</nav>
<main class="container" style="max-width:860px">
{{with .Paste}}
<div class="paste-header">
<div>
<h2 style="margin-bottom:0.25rem">{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}</h2>
<small style="color:var(--pico-muted-color)">
<code>/bin/{{.Name}}</code>
&nbsp;&middot;&nbsp;
<span class="format-badge">{{.Format}}</span>
&nbsp;&middot;&nbsp;
{{if .Token}}<span style="color:var(--pico-ins-color)">&#128274; token protected</span>{{else}}<span>public</span>{{end}}
&nbsp;&middot;&nbsp;
updated {{.UpdatedAt.Format "2006-01-02 15:04"}}
</small>
</div>
<div class="paste-toolbar">
<a href="?raw=1" role="button" class="outline" style="padding:0.3rem 0.75rem;font-size:0.85rem">Raw</a>
<button class="outline" style="padding:0.3rem 0.75rem;font-size:0.85rem"
onclick="navigator.clipboard.writeText(document.getElementById('paste-raw').innerText).then(()=>{this.textContent='Copied!';setTimeout(()=>this.textContent='Copy',1500)})">Copy</button>
</div>
</div>
<hr>
{{end}}
<div class="paste-body">
{{.PasteBody}}
</div>
{{with .Paste}}
<pre id="paste-raw" style="display:none">{{.Content}}</pre>
{{end}}
</main>
</body>
</html>
+63
View File
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>URL Shortener</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Shortener</a></strong></li></ul>
<ul><li>{{if .LoggedIn}}<a href="/admin">Admin</a>{{else}}<a href="/admin/login">Admin</a>{{end}}</li></ul>
</nav>
<main class="container">
<hgroup>
<h2>Shorten a URL</h2>
<p>Paste a long URL and get a short link</p>
</hgroup>
{{if .Error}}
<article aria-label="error" style="border-left: 4px solid var(--pico-del-color); padding: 0.75rem 1rem;">
{{.Error}}
</article>
{{end}}
{{if .ShortURL}}
<article aria-label="success">
<p>Your short link is ready:</p>
<p><small>{{.OriginalURL}}</small></p>
<div class="result-box">
<code id="short-url">{{.ShortURL}}</code>
<button onclick="navigator.clipboard.writeText(document.getElementById('short-url').textContent).then(()=>{this.textContent='Copied!'})">Copy</button>
</div>
{{if .QRSVG}}
<div style="text-align:center; margin-top:1rem;">{{.QRSVG}}</div>
{{end}}
</article>
{{end}}
<form method="post" action="/shorten" id="shorten-form">
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<label for="url">URL to shorten</label>
<input type="text" inputmode="url" id="url" name="url" placeholder="https://example.com/very/long/url" required>
{{if .LoggedIn}}
<label for="slug">Custom slug <small>(optional)</small></label>
<input type="text" id="slug" name="slug" placeholder="my-link" pattern="[a-zA-Z0-9_-]+" title="Letters, numbers, hyphens, underscores only">
{{end}}
<button type="submit">Shorten</button>
</form>
<script>
document.getElementById('shorten-form').addEventListener('submit', function() {
const input = document.getElementById('url');
if (input.value && !input.value.includes('://')) {
input.value = 'https://' + input.value;
}
});
</script>
</main>
</body>
</html>
+44
View File
@@ -0,0 +1,44 @@
package slug
import (
"fmt"
"math/rand/v2"
"regexp"
"strings"
)
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
var reservedSlugs = map[string]bool{
"admin": true,
"shorten": true,
"static": true,
"api": true,
"health": true,
}
var validSlugRe = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
func Generate(length int) string {
b := make([]byte, length)
for i := range b {
b[i] = alphabet[rand.IntN(len(alphabet))]
}
return string(b)
}
func Validate(slug string) error {
if len(slug) == 0 {
return fmt.Errorf("slug cannot be empty")
}
if len(slug) > 64 {
return fmt.Errorf("slug too long (max 64 characters)")
}
if !validSlugRe.MatchString(slug) {
return fmt.Errorf("slug can only contain letters, numbers, hyphens, and underscores")
}
if reservedSlugs[strings.ToLower(slug)] {
return fmt.Errorf("slug %q is reserved", slug)
}
return nil
}
+65
View File
@@ -0,0 +1,65 @@
package slug
import (
"testing"
)
func TestGenerate_Length(t *testing.T) {
for _, length := range []int{2, 3, 4, 5} {
s := Generate(length)
if len(s) != length {
t.Errorf("Generate(%d) = %q (len %d), want len %d", length, s, len(s), length)
}
}
}
func TestGenerate_Unique(t *testing.T) {
seen := make(map[string]bool)
for range 1000 {
s := Generate(3)
if seen[s] {
// Collisions can happen but should be very rare in 1000 samples
// with 238k possibilities. Just skip.
continue
}
seen[s] = true
}
if len(seen) < 950 {
t.Errorf("too many collisions: only %d unique slugs out of 1000", len(seen))
}
}
func TestGenerate_ValidChars(t *testing.T) {
for range 100 {
s := Generate(3)
for _, c := range s {
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
t.Errorf("Generate(3) = %q, contains invalid char %c", s, c)
}
}
}
}
func TestValidate(t *testing.T) {
tests := []struct {
slug string
wantErr bool
}{
{"abc", false},
{"my-link", false},
{"test_123", false},
{"ABC", false},
{"", true},
{"admin", true},
{"shorten", true},
{"a b", true},
{"a/b", true},
}
for _, tt := range tests {
err := Validate(tt.slug)
if (err != nil) != tt.wantErr {
t.Errorf("Validate(%q) error = %v, wantErr %v", tt.slug, err, tt.wantErr)
}
}
}
+46
View File
@@ -0,0 +1,46 @@
package main
import (
"flag"
"fmt"
"log"
"os"
"golang.org/x/crypto/bcrypt"
"urlshort/internal/config"
"urlshort/internal/db"
"urlshort/internal/server"
)
func main() {
configPath := flag.String("config", "config.toml", "path to config file")
hashPassword := flag.String("hash-password", "", "hash a password and print the bcrypt hash, then exit")
flag.Parse()
if *hashPassword != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(*hashPassword), bcrypt.DefaultCost)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
fmt.Println(string(hash))
return
}
cfg, err := config.Load(*configPath)
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
database, err := db.Open(cfg.Database.Path)
if err != nil {
log.Fatalf("Failed to open database: %v", err)
}
defer database.Close()
srv := server.New(cfg, database)
if err := srv.Start(); err != nil {
log.Fatalf("Server error: %v", err)
}
}
+26
View File
@@ -0,0 +1,26 @@
{
"name": "url",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"devDependencies": {
"typescript": "^6.0.2"
}
},
"node_modules/typescript": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz",
"integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"devDependencies": {
"typescript": "^6.0.2"
}
}