security review

This commit is contained in:
lucio committed 2026-06-02 01:24:19 -07:00
1 parent a9e2ba548b
commit 2f5c31499d
19 files changed
+317 -87

No files matched your search

+8 -7
View File
@@ -89,7 +89,7 @@ Templates and static files are embedded into the binary via `//go:embed` in `tem
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). Most JS is inline in templates; shared upload logic lives in `static/upload.js` and is exposed as `window.GlimmerUpload`. No build step, no npm, no bundler.
### CSS framework
[Pico CSS 2](https://picocss.com/) loaded from CDN. Custom overrides in `static/style.css`. Admin pages use `data-theme="dark"`.
[Pico CSS 2](https://picocss.com/) is **vendored locally** at `static/pico.min.css` (served from `/static/pico.min.css`) so the app works fully offline with no external requests. Custom overrides in `static/style.css`. Admin pages use `data-theme="dark"`. Do not reintroduce CDN `<link>`/`<script>`/image references — everything must be same-origin (enforced by the `Content-Security-Policy` header in `securityHeaders`).
---
@@ -149,15 +149,16 @@ Redirects uppercase paths to lowercase (for QR-code URL compatibility). **Exclud
```toml
[server]
port = 8888
base_url = "http://localhost:8888"
read_timeout = "5s"
write_timeout = "10s"
port = 8888
base_url = "http://localhost:8888"
read_timeout = "5s"
write_timeout = "10s"
trust_proxy = false # only honour X-Forwarded-For behind a trusted proxy
max_concurrent = 64 # in-flight request cap (503 beyond it); lower on RPi Zero
[admin]
username = "admin"
password_hash = "$2a$10$..." # bcrypt; generate with: ./glimmer --hash-password
session_hours = 24
password_hash = "$2a$10$..." # REQUIRED — server refuses to start if empty; generate with: ./glimmer --hash-password
[database]
path = "./data/urls.db"
+9 -3
View File
@@ -5,12 +5,18 @@ port = 8888
base_url = "http://luci.ooo"
read_timeout = "5s"
write_timeout = "10s"
# Only enable if behind a trusted reverse proxy that sets X-Forwarded-For.
# When false, the real connection IP is used for rate limiting (cannot be spoofed).
trust_proxy = false
# Maximum number of in-flight HTTP requests before returning 503. Tune down on
# very small hardware (e.g. RPi Zero) to bound memory/CPU use.
max_concurrent = 64
[admin]
username = "admin"
# Default password: "admin" — change this!
# Generate a new hash: ./glimmer --hash-password "your-password"
password_hash = "$2a$10$WXBoF7ZB7fIRl5smdGH9seqlNbXWiCS7ZbGNk0ONb9xjS8499gBpu"
# REQUIRED — the server refuses to start without this.
# Generate a hash: ./glimmer --hash-password "your-password"
password_hash = ""
session_hours = 24
[mcp]
+19 -5
View File
@@ -22,6 +22,14 @@ type ServerConfig struct {
BaseURL string `toml:"base_url"`
ReadTimeout string `toml:"read_timeout"`
WriteTimeout string `toml:"write_timeout"`
// TrustProxy controls whether X-Forwarded-For / X-Real-Ip headers are
// honoured for client IP detection. Only enable when the server sits
// behind a trusted reverse proxy that sets these headers; otherwise a
// client can spoof them to bypass rate limiting.
TrustProxy bool `toml:"trust_proxy"`
// MaxConcurrent caps the number of in-flight requests. Excess requests
// get 503 instead of piling up and exhausting RAM/CPU on small hardware.
MaxConcurrent int `toml:"max_concurrent"`
}
type AdminConfig struct {
@@ -67,10 +75,12 @@ func (c *ServerConfig) WriteTimeoutDuration() time.Duration {
func Load(path string) (*Config, error) {
cfg := &Config{
Server: ServerConfig{
Port: 8080,
BaseURL: "http://localhost:8080",
ReadTimeout: "5s",
WriteTimeout: "10s",
Port: 8080,
BaseURL: "http://localhost:8080",
ReadTimeout: "5s",
WriteTimeout: "10s",
TrustProxy: false,
MaxConcurrent: 64,
},
Admin: AdminConfig{
Username: "admin",
@@ -98,7 +108,11 @@ func Load(path string) (*Config, error) {
}
if cfg.Admin.PasswordHash == "" {
return nil, fmt.Errorf("admin.password_hash is required in config")
return nil, fmt.Errorf("admin.password_hash is required in config (generate one with: glimmer --hash-password \"your-password\")")
}
if cfg.Server.MaxConcurrent <= 0 {
cfg.Server.MaxConcurrent = 64
}
return cfg, nil
+21 -8
View File
@@ -31,7 +31,6 @@ import (
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/renderer/html"
"golang.org/x/crypto/bcrypt"
"rsc.io/qr"
)
@@ -135,7 +134,7 @@ func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleShorten(w http.ResponseWriter, r *http.Request) {
if !s.isLoggedIn(r) {
ip := clientIP(r)
ip := clientIP(r, s.cfg.Server.TrustProxy)
if !s.limiter.Allow(ip) {
s.renderIndex(w, r, "Too many requests. Please wait a moment.", "", "")
return
@@ -280,15 +279,29 @@ func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) {
}
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)})
// Throttle login attempts per IP to slow brute force.
if !s.authLimiter.Allow(clientIP(r, s.cfg.Server.TrustProxy)) {
w.WriteHeader(http.StatusTooManyRequests)
renderTemplate(w, "admin_login.html", pageData{Error: "Too many attempts. Please wait a moment.", CSRFToken: csrfToken(w, r)})
return
}
if err := bcrypt.CompareHashAndPassword([]byte(s.cfg.Admin.PasswordHash), []byte(password)); err != nil {
username := r.FormValue("username")
password := r.FormValue("password")
// Always run bcrypt (even when the username is wrong) so response timing
// does not reveal whether the username is valid. The username is compared
// in constant time. bcrypt runs through the concurrency gate.
userOK := subtle.ConstantTimeCompare([]byte(username), []byte(s.cfg.Admin.Username)) == 1
pwOK, available := s.checkPassword(s.cfg.Admin.PasswordHash, password)
if !available {
w.Header().Set("Retry-After", "1")
w.WriteHeader(http.StatusServiceUnavailable)
renderTemplate(w, "admin_login.html", pageData{Error: "Server busy. Please try again.", CSRFToken: csrfToken(w, r)})
return
}
if !userOK || !pwOK {
w.WriteHeader(http.StatusUnauthorized)
renderTemplate(w, "admin_login.html", pageData{Error: "Invalid credentials", CSRFToken: csrfToken(w, r)})
return
}
+50 -16
View File
@@ -15,8 +15,6 @@ import (
"glimmer/internal/db"
"glimmer/internal/slug"
"golang.org/x/crypto/bcrypt"
)
const mcpProtocolVersion = "2025-06-18"
@@ -50,7 +48,30 @@ func (s *Server) handleMCP(w http.ResponseWriter, r *http.Request) {
writeMCPHTTPError(w, nil, http.StatusForbidden, -32000, "Forbidden origin")
return
}
if !s.authorizeMCP(r) {
// Fast path: API key (constant-time, no bcrypt). Preferred for clients that
// make many requests. Falls back to Basic auth, which is CPU-expensive and
// therefore both per-IP rate-limited and routed through the bcrypt gate so
// it cannot exhaust the CPU on small hardware.
authorized := s.mcpAPIKeyAuth(r)
if !authorized {
if r.Header.Get("Authorization") != "" {
ip := clientIP(r, s.cfg.Server.TrustProxy)
if !s.authLimiter.Allow(ip) {
w.Header().Set("Retry-After", "1")
writeMCPHTTPError(w, nil, http.StatusTooManyRequests, -32000, "Too many attempts")
return
}
}
ok, available := s.mcpBasicAuth(r)
if !available {
w.Header().Set("Retry-After", "1")
writeMCPHTTPError(w, nil, http.StatusServiceUnavailable, -32000, "Server busy")
return
}
authorized = ok
}
if !authorized {
w.Header().Set("WWW-Authenticate", `Bearer realm="Glimmer MCP", Basic realm="Glimmer MCP"`)
writeMCPHTTPError(w, nil, http.StatusUnauthorized, -32000, "Unauthorized")
return
@@ -99,21 +120,34 @@ func (s *Server) handleMCP(w http.ResponseWriter, r *http.Request) {
}
}
func (s *Server) authorizeMCP(r *http.Request) bool {
if s.cfg.MCP.APIKey != "" {
if token := bearerToken(r.Header.Get("Authorization")); token != "" && constantTimeEqual(token, s.cfg.MCP.APIKey) {
return true
}
if token := r.Header.Get("X-API-Key"); token != "" && constantTimeEqual(token, s.cfg.MCP.APIKey) {
return true
}
}
username, password, ok := r.BasicAuth()
if !ok || username != s.cfg.Admin.Username || s.cfg.Admin.PasswordHash == "" {
// mcpAPIKeyAuth checks the configured API key via constant-time comparison.
// Returns false (rather than matching) when no API key is configured.
func (s *Server) mcpAPIKeyAuth(r *http.Request) bool {
if s.cfg.MCP.APIKey == "" {
return false
}
return bcrypt.CompareHashAndPassword([]byte(s.cfg.Admin.PasswordHash), []byte(password)) == nil
if token := bearerToken(r.Header.Get("Authorization")); token != "" && constantTimeEqual(token, s.cfg.MCP.APIKey) {
return true
}
if token := r.Header.Get("X-API-Key"); token != "" && constantTimeEqual(token, s.cfg.MCP.APIKey) {
return true
}
return false
}
// mcpBasicAuth verifies HTTP Basic credentials against the admin password.
// available is false when the bcrypt gate is saturated (caller should 503).
func (s *Server) mcpBasicAuth(r *http.Request) (ok bool, available bool) {
username, password, hasAuth := r.BasicAuth()
if !hasAuth || s.cfg.Admin.PasswordHash == "" {
return false, true
}
userOK := subtle.ConstantTimeCompare([]byte(username), []byte(s.cfg.Admin.Username)) == 1
pwOK, available := s.checkPassword(s.cfg.Admin.PasswordHash, password)
if !available {
return false, false
}
return userOK && pwOK, true
}
func (s *Server) validMCPOrigin(r *http.Request) bool {
+52 -8
View File
@@ -6,6 +6,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"glimmer/internal/config"
"glimmer/internal/db"
@@ -13,11 +14,21 @@ import (
"golang.org/x/crypto/bcrypt"
)
// newTestServer builds a Server with the auth-gating fields initialised the
// same way New() does, so handler-level tests don't hit nil channels/limiters.
func newTestServer(cfg *config.Config) *Server {
return &Server{
cfg: cfg,
authLimiter: newRateLimiter(time.Second),
bcryptSem: make(chan struct{}, 1),
}
}
func TestMCPRequiresAuthentication(t *testing.T) {
srv := &Server{cfg: &config.Config{
srv := newTestServer(&config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"},
}}
})
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
rec := httptest.NewRecorder()
@@ -30,10 +41,10 @@ func TestMCPRequiresAuthentication(t *testing.T) {
}
func TestMCPListsToolsWithAPIKey(t *testing.T) {
srv := &Server{cfg: &config.Config{
srv := newTestServer(&config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"},
}}
})
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
req.Header.Set("Authorization", "Bearer test-key")
@@ -50,10 +61,10 @@ func TestMCPListsToolsWithAPIKey(t *testing.T) {
}
func TestMCPRejectsUnexpectedOrigin(t *testing.T) {
srv := &Server{cfg: &config.Config{
srv := newTestServer(&config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"},
}}
})
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
req.Header.Set("Authorization", "Bearer test-key")
@@ -72,11 +83,11 @@ func TestMCPAcceptsBasicAuth(t *testing.T) {
if err != nil {
t.Fatalf("hash password: %v", err)
}
srv := &Server{cfg: &config.Config{
srv := newTestServer(&config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
Admin: config.AdminConfig{Username: "admin", PasswordHash: string(hash)},
MCP: config.MCPConfig{Enabled: true},
}}
})
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
req.SetBasicAuth("admin", "secret")
@@ -89,6 +100,39 @@ func TestMCPAcceptsBasicAuth(t *testing.T) {
}
}
func TestMCPRejectsWrongPasswordThenThrottles(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost)
if err != nil {
t.Fatalf("hash password: %v", err)
}
srv := newTestServer(&config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
Admin: config.AdminConfig{Username: "admin", PasswordHash: string(hash)},
MCP: config.MCPConfig{Enabled: true},
})
newReq := func() *http.Request {
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
req.SetBasicAuth("admin", "wrong")
req.RemoteAddr = "203.0.113.5:5555"
return req
}
rec := httptest.NewRecorder()
srv.handleMCP(rec, newReq())
if rec.Code != http.StatusUnauthorized {
t.Fatalf("first bad attempt: expected 401, got %d", rec.Code)
}
// Second bad attempt from the same IP within the window is throttled before
// another bcrypt runs.
rec = httptest.NewRecorder()
srv.handleMCP(rec, newReq())
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("second bad attempt: expected 429, got %d", rec.Code)
}
}
func TestMCPCreateAndListContent(t *testing.T) {
database, err := db.Open(filepath.Join(t.TempDir(), "urls.db"))
if err != nil {
+65 -9
View File
@@ -9,6 +9,8 @@ import (
"strings"
"sync"
"time"
"golang.org/x/crypto/bcrypt"
)
type sessionStore struct {
@@ -159,17 +161,71 @@ func (rl *rateLimiter) Allow(ip string) bool {
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])
// clientIP returns the client IP for rate-limiting purposes. Forwarded headers
// are only honoured when trustProxy is true, because any client can set them —
// trusting them unconditionally lets an attacker rotate X-Forwarded-For to
// bypass per-IP limits.
func clientIP(r *http.Request, trustProxy bool) string {
if trustProxy {
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)
}
return strings.TrimSpace(xff)
}
if xri := r.Header.Get("X-Real-Ip"); xri != "" {
return strings.TrimSpace(xri)
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
host, _, _ := net.SplitHostPort(r.RemoteAddr)
return host
}
// checkPassword runs a bcrypt comparison while bounding the number of
// concurrent bcrypt operations. bcrypt is deliberately CPU-heavy, so an
// unbounded flood of auth attempts can exhaust a single-core machine (e.g. an
// RPi Zero). The semaphore caps concurrency; if the gate cannot be acquired
// quickly the request is treated as temporarily unavailable (available=false)
// and the caller should return 503 rather than queueing more work.
func (srv *Server) checkPassword(hash, password string) (ok bool, available bool) {
select {
case srv.bcryptSem <- struct{}{}:
defer func() { <-srv.bcryptSem }()
case <-time.After(2 * time.Second):
return false, false
}
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil, true
}
// limitConcurrency bounds the number of in-flight requests. Beyond the limit it
// responds 503 instead of letting goroutines/buffers pile up and exhaust memory
// on small hardware.
func limitConcurrency(max int, next http.Handler) http.Handler {
sem := make(chan struct{}, max)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case sem <- struct{}{}:
defer func() { <-sem }()
next.ServeHTTP(w, r)
default:
w.Header().Set("Retry-After", "1")
http.Error(w, "Server busy", http.StatusServiceUnavailable)
}
})
}
// limitBody caps the request body size for ordinary routes so a large POST
// cannot exhaust memory. Upload handlers set their own (larger) MaxBytesReader
// and are excluded.
func limitBody(maxBytes int64, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost && !strings.HasPrefix(r.URL.Path, "/admin/upload") {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
}
next.ServeHTTP(w, r)
})
}
+52 -14
View File
@@ -6,6 +6,7 @@ import (
"log"
"net/http"
"os"
"runtime"
"strings"
"time"
@@ -14,19 +15,29 @@ import (
)
type Server struct {
cfg *config.Config
db *db.DB
sessions *sessionStore
limiter *rateLimiter
cfg *config.Config
db *db.DB
sessions *sessionStore
limiter *rateLimiter
authLimiter *rateLimiter
bcryptSem chan struct{}
}
func New(cfg *config.Config, database *db.DB) *Server {
ttl := time.Duration(cfg.Admin.SessionHours) * time.Hour
// Allow at most NumCPU concurrent bcrypt operations so password checks
// cannot peg the CPU on small hardware. Always at least 1.
bcryptWorkers := runtime.NumCPU()
if bcryptWorkers < 1 {
bcryptWorkers = 1
}
return &Server{
cfg: cfg,
db: database,
sessions: newSessionStore(ttl),
limiter: newRateLimiter(1 * time.Second),
cfg: cfg,
db: database,
sessions: newSessionStore(ttl),
limiter: newRateLimiter(1 * time.Second),
authLimiter: newRateLimiter(1 * time.Second),
bcryptSem: make(chan struct{}, bcryptWorkers),
}
}
@@ -35,6 +46,20 @@ func securityHeaders(next http.Handler) http.Handler {
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")
// All assets are served from the same origin (Pico CSS is vendored
// locally), so the app works fully offline and we can lock the origin
// down. img-src allows data: and https: so uploaded/remote images and
// favicons still render. 'unsafe-inline' is required by the inline
// scripts/styles in the templates; object-src/base-uri/frame-ancestors
// are pinned to blunt injection and clickjacking.
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"img-src 'self' data: https:; "+
"style-src 'self' 'unsafe-inline'; "+
"script-src 'self' 'unsafe-inline'; "+
"object-src 'none'; "+
"base-uri 'none'; "+
"frame-ancestors 'none'")
next.ServeHTTP(w, r)
})
}
@@ -78,7 +103,7 @@ func (s *Server) Start() error {
// Admin auth
mux.HandleFunc("GET /admin/login", s.handleLoginPage)
mux.HandleFunc("POST /admin/login", s.handleLogin)
mux.HandleFunc("POST /admin/login", s.requireCSRF(s.handleLogin))
mux.HandleFunc("POST /admin/logout", s.requireAuth(s.requireCSRF(s.handleLogout)))
// Admin routes (protected)
@@ -114,14 +139,27 @@ func (s *Server) Start() error {
mux.HandleFunc("GET /{slug}", s.handleRedirect)
addr := fmt.Sprintf(":%d", s.cfg.Server.Port)
// Middleware chain (outermost first):
// limitConcurrency — cap in-flight requests (memory/CPU guard)
// limitBody — cap body size for non-upload POSTs
// lowercasePath — normalise case for QR URLs
// securityHeaders — CSP + hardening headers
const maxBodyBytes = 1 << 20 // 1 MB for ordinary requests
handler := limitConcurrency(s.cfg.Server.MaxConcurrent,
limitBody(maxBodyBytes,
lowercasePath(securityHeaders(mux))))
srv := &http.Server{
Addr: addr,
Handler: mux,
ReadTimeout: s.cfg.Server.ReadTimeoutDuration(),
WriteTimeout: s.cfg.Server.WriteTimeoutDuration(),
Addr: addr,
Handler: handler,
ReadTimeout: s.cfg.Server.ReadTimeoutDuration(),
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: s.cfg.Server.WriteTimeoutDuration(),
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 16, // 64 KB
}
log.Printf("Starting server on %s (base URL: %s)", addr, s.cfg.Server.BaseURL)
srv.Handler = lowercasePath(securityHeaders(mux))
return srv.ListenAndServe()
}
+1 -1
View File
@@ -5,7 +5,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Not Found — Glimmer</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
+2 -3
View File
@@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin — Glimmer</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
@@ -49,8 +49,7 @@
</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'">
<a href="/{{.Slug}}" class="tile" target="_blank" rel="noopener noreferrer" title="{{.URL}}">
<span class="tile-slug">/{{.Slug}}</span>
<span class="tile-dest">{{.URL}}</span>
<span class="tile-clicks">{{.Clicks}} clicks</span>
+1 -1
View File
@@ -5,7 +5,7 @@
<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/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
@@ -5,7 +5,7 @@
<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/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
+1 -1
View File
@@ -5,7 +5,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Edit Link — Glimmer</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
+1 -1
View File
@@ -5,7 +5,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Login — Glimmer</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
+1 -1
View File
@@ -5,7 +5,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Uploads — Admin</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
+1 -1
View File
@@ -5,7 +5,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Access Token Required — Glimmer</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
+1 -1
View File
@@ -5,7 +5,7 @@
<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/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
+1 -1
View File
@@ -5,7 +5,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Glimmer</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
+30 -5
View File
@@ -1,8 +1,8 @@
package slug
import (
"crypto/rand"
"fmt"
"math/rand/v2"
"regexp"
"strings"
)
@@ -15,16 +15,41 @@ var reservedSlugs = map[string]bool{
"static": true,
"api": true,
"health": true,
"bin": true,
"uploads": true,
"mcp": true,
"login": true,
}
var validSlugRe = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
// Generate returns a random string of the given length drawn from the
// alphabet using a cryptographically secure source. It is safe to use for
// access tokens as well as public slugs. Uses rejection sampling so the
// 36-character alphabet maps onto bytes without modulo bias.
func Generate(length int) string {
b := make([]byte, length)
for i := range b {
b[i] = alphabet[rand.IntN(len(alphabet))]
const maxUnbiased = 256 - (256 % len(alphabet)) // 252
out := make([]byte, length)
buf := make([]byte, length)
filled := 0
for filled < length {
if _, err := rand.Read(buf); err != nil {
// crypto/rand should never fail; if it does, panic rather than
// silently emit a predictable token.
panic("slug: crypto/rand failed: " + err.Error())
}
for _, b := range buf {
if int(b) >= maxUnbiased {
continue
}
out[filled] = alphabet[int(b)%len(alphabet)]
filled++
if filled == length {
break
}
}
}
return string(b)
return string(out)
}
func Validate(slug string) error {